text stringlengths 54 60.6k |
|---|
<commit_before>#include "stdafx.h"
#include "CommandHack.h"
CommandHack::CommandHack()
{
}
CommandHack::~CommandHack()
{
}
bool CommandHack::ShouldRunThisCommand(ParsedCommand* Parsed)
{
return (Parsed->Words->at(0) == "hack");
}
void CommandHack::Run(ParsedCommand* Parsed)
{
if (Parsed->Words->size() > 1)
{
string valid = Parsed->Words->at(1);
register unsigned __int8 length = valid.size();
this->Chars = new char[length];
this->CharsLength = length;
register unsigned __int8 i = 0;
while (i != length)
{
this->Chars[i] = valid[i];
i++;
}
}
else
{
this->Chars = new char[96];
this->CharsLength = 96;
register unsigned __int8 i = 32;
while (i != 128)
{
this->Chars[i - 32] = i;
++i;
}
}
Sleep(10000);
this->Crack();
}
string* CommandHack::GetName()
{
return new string("Hack");
}
string* CommandHack::GetHelp()
{
return new string("In 10 seconds, it tries to hack into whatever input box the user is hovering over.");
}
void CommandHack::Attempt(string* attempt)
{
Console->WriteLine(attempt);
register char next;
register unsigned int size = attempt->size();
register unsigned int i = 0;
while (i != size)
{
next = attempt->at(i);
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
ip.ki.wScan = next; // Which key press to simulate
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
SendInput(1, &ip, sizeof(INPUT));
++i;
}
////Enter
//ip.type = INPUT_KEYBOARD;
//ip.ki.time = 0;
//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
//ip.ki.wScan = VK_RETURN; // Which key press to simulate
//ip.ki.wVk = 0;
//ip.ki.dwExtraInfo = 0;
//SendInput(1, &ip, sizeof(INPUT));
//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
//SendInput(1, &ip, sizeof(INPUT));
keybd_event(VK_RETURN, '5A', 0, 0);
keybd_event(VK_RETURN, '5A', KEYEVENTF_KEYUP, 0);
register unsigned __int8 ab = -20;
while (ab != this->Length)
{
keybd_event(VK_BACK, '66', 0, 0);
keybd_event(VK_BACK, '66', KEYEVENTF_KEYUP, 0);
//ip.type = INPUT_KEYBOARD;
//ip.ki.time = 0;
//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
//ip.ki.wScan = VK_BACK; // Which key press to simulate
//ip.ki.wVk = 0;
//ip.ki.dwExtraInfo = 0;
//SendInput(1, &ip, sizeof(INPUT));
//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
//SendInput(1, &ip, sizeof(INPUT));
++ab;
}
}
void CommandHack::Crack()
{
//32-137
//Acquire common characters.
register unsigned __int8 i = 32;
i = 1;
string* Attemptter = new string("");
while (i != 128)
{
this->Length = i;
// Keep growing till I get it right
this->makeCombinations(Attemptter, i);
++i;
}
ToDelete->push_back(Attemptter);
}
void CommandHack::makeCombinations(string* s, unsigned __int8 length)
{
if (length == 0) // when length has been reached
{
this->Attempt(s); // print it out
Sleep(10);
return;
}
register string appended;
for (register unsigned __int8 i = 0; i < this->CharsLength; i++) // iterate through alphabet
{
// Create new string with next character
// Call generate again until string has reached it's length
appended = *s + this->Chars[i];
this->makeCombinations(&appended, length - 1);
}
}
<commit_msg>Updated help.<commit_after>#include "stdafx.h"
#include "CommandHack.h"
CommandHack::CommandHack()
{
}
CommandHack::~CommandHack()
{
}
bool CommandHack::ShouldRunThisCommand(ParsedCommand* Parsed)
{
return (Parsed->Words->at(0) == "hack");
}
//hack aAnNrRsStTuUyY1_mMeE
void CommandHack::Run(ParsedCommand* Parsed)
{
if (Parsed->Words->size() > 1)
{
string valid = Parsed->Words->at(1);
register unsigned __int8 length = valid.size();
this->Chars = new char[length];
this->CharsLength = length;
register unsigned __int8 i = 0;
while (i != length)
{
this->Chars[i] = valid[i];
i++;
}
}
else
{
this->Chars = new char[96];
this->CharsLength = 96;
register unsigned __int8 i = 32;
while (i != 128)
{
this->Chars[i - 32] = i;
++i;
}
}
Sleep(10000);
this->Crack();
}
string* CommandHack::GetName()
{
return new string("Hack");
}
string* CommandHack::GetHelp()
{
return new string("In 10 seconds, it tries to hack into whatever input box the user is hovering over. Optional: hack (Characters here) will use only those characters in an attack. Doesn't handle spaces.");
}
void CommandHack::Attempt(string* attempt)
{
Console->WriteLine(attempt);
register char next;
register unsigned int size = attempt->size();
register unsigned int i = 0;
while (i != size)
{
next = attempt->at(i);
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
ip.ki.wScan = next; // Which key press to simulate
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
SendInput(1, &ip, sizeof(INPUT));
++i;
}
////Enter
//ip.type = INPUT_KEYBOARD;
//ip.ki.time = 0;
//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
//ip.ki.wScan = VK_RETURN; // Which key press to simulate
//ip.ki.wVk = 0;
//ip.ki.dwExtraInfo = 0;
//SendInput(1, &ip, sizeof(INPUT));
//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
//SendInput(1, &ip, sizeof(INPUT));
keybd_event(VK_RETURN, '5A', 0, 0);
keybd_event(VK_RETURN, '5A', KEYEVENTF_KEYUP, 0);
register unsigned __int8 ab = -20;
while (ab != this->Length)
{
keybd_event(VK_BACK, '66', 0, 0);
keybd_event(VK_BACK, '66', KEYEVENTF_KEYUP, 0);
//ip.type = INPUT_KEYBOARD;
//ip.ki.time = 0;
//ip.ki.dwFlags = KEYEVENTF_UNICODE; // Specify the key as a Unicode character
//ip.ki.wScan = VK_BACK; // Which key press to simulate
//ip.ki.wVk = 0;
//ip.ki.dwExtraInfo = 0;
//SendInput(1, &ip, sizeof(INPUT));
//ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release1*
//SendInput(1, &ip, sizeof(INPUT));
++ab;
}
}
void CommandHack::Crack()
{
//32-137
//Acquire common characters.
register unsigned __int8 i = 32;
i = 1;
string* Attemptter = new string("");
while (i != 128)
{
this->Length = i;
// Keep growing till I get it right
this->makeCombinations(Attemptter, i);
++i;
}
ToDelete->push_back(Attemptter);
}
void CommandHack::makeCombinations(string* s, unsigned __int8 length)
{
if (length == 0) // when length has been reached
{
this->Attempt(s); // print it out
Sleep(10);
return;
}
register string appended;
for (register unsigned __int8 i = 0; i < this->CharsLength; i++) // iterate through alphabet
{
// Create new string with next character
// Call generate again until string has reached it's length
appended = *s + this->Chars[i];
this->makeCombinations(&appended, length - 1);
}
}
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: ResidueRotamerSet_test.C,v 1.1.2.2 2007/04/03 13:29:29 bertsch Exp $
//
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/STRUCTURE/residueRotamerSet.h>
#include <BALL/STRUCTURE/fragmentDB.h>
///////////////////////////
START_TEST(RotamerLibrary, "$Id: ResidueRotamerSet_test.C,v 1.1.2.2 2007/04/03 13:29:29 bertsch Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
FragmentDB frag_db("fragments/Fragments.db");
Rotamer* rot_ptr = 0;
CHECK(Rotamer::Rotamer())
rot_ptr = new Rotamer;
TEST_NOT_EQUAL(rot_ptr, 0)
ABORT_IF(rot_ptr == 0)
TEST_EQUAL(rot_ptr->P, 0.0)
TEST_EQUAL(rot_ptr->chi1, 0.0)
TEST_EQUAL(rot_ptr->chi2, 0.0)
TEST_EQUAL(rot_ptr->chi3, 0.0)
TEST_EQUAL(rot_ptr->chi4, 0.0)
RESULT
CHECK(Rotamer::~Rotamer())
delete rot_ptr;
RESULT
CHECK(Rotamer::Rotamer(const Rotamer& rotamer))
Rotamer r;
r.P = 1.0;
r.chi1 = Angle(2.1).toDegree();
r.chi2 = Angle(3.2).toDegree();
r.chi3 = Angle(4.3).toDegree();
r.chi4 = Angle(5.4).toDegree();
Rotamer r2(r);
TEST_EQUAL(r2.chi1, r.chi1)
TEST_EQUAL(r2.chi2, r.chi2)
TEST_EQUAL(r2.chi3, r.chi3)
TEST_EQUAL(r2.chi4, r.chi4)
TEST_EQUAL(r2.P, r.P)
RESULT
CHECK(Rotamer::Rotamer(float P, float, chi1, float, chi2, float chi3, float chi4))
Rotamer r(1.0, 2.0, 3.0, 4.0, 5.0);
TEST_REAL_EQUAL(r.chi1, 2.0)
TEST_REAL_EQUAL(r.chi2, 3.0)
TEST_REAL_EQUAL(r.chi3, 4.0)
TEST_REAL_EQUAL(r.chi4, 5.0)
TEST_REAL_EQUAL(r.P, 1.0)
RESULT
ResidueRotamerSet* rrs_ptr = 0;
CHECK(ResidueRotamerSet::ResidueRotamerSet())
rrs_ptr = new ResidueRotamerSet;
TEST_NOT_EQUAL(rrs_ptr, 0)
RESULT
CHECK(ResidueRotamerSet::~ResidueRotamerSet())
delete rrs_ptr;
RESULT
CHECK(ResidueRotamerSet::ResidueRotamerSet(const Residue& residue, Size number_of_torsions))
ResidueRotamerSet r;
ResidueRotamerSet r2(r);
RESULT
CHECK(bool ResidueRotamerSet::isValid())
ResidueRotamerSet r;
TEST_EQUAL(r.isValid(), false)
RESULT
CHECK(const String& ResidueRotamerSet::getName() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getName(), "")
RESULT
CHECK(void ResidueRotamerSet::setName(const String& name))
ResidueRotamerSet r;
TEST_EQUAL(r.getName(), "")
r.setName("asdf");
TEST_EQUAL(r.getName(), "asdf")
r.setName("");
TEST_EQUAL(r.getName(), "")
RESULT
CHECK(Size ResidueRotamerSet::getNumberOfRotamers() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfRotamers(), 0)
RESULT
CHECK(Size ResidueRotamerSet::getNumberOfTorsions() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfTorsions(), 0)
RESULT
CHECK(void ResidueRotamerSet::setNumberOfTorsions(Size number_of_torsions) throw(Exception::IndexOverflow))
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfTorsions(), 0)
r.setNumberOfTorsions(1);
TEST_EQUAL(r.getNumberOfTorsions(), 1)
r.setNumberOfTorsions(2);
TEST_EQUAL(r.getNumberOfTorsions(), 2)
r.setNumberOfTorsions(3);
TEST_EQUAL(r.getNumberOfTorsions(), 3)
r.setNumberOfTorsions(4);
TEST_EQUAL(r.getNumberOfTorsions(), 4)
r.setNumberOfTorsions(0);
TEST_EQUAL(r.getNumberOfTorsions(), 0)
TEST_EXCEPTION(Exception::IndexOverflow, r.setNumberOfTorsions(5))
TEST_EXCEPTION(Exception::IndexOverflow, r.setNumberOfTorsions(6))
RESULT
/*
CHECK(const Residue& ResidueRotamerSet::getResidue() const)
ResidueRotamerSet r;
const ResidueRotamerSet& c_r(r);
TEST_NOT_EQUAL(&(c_r.getResidue()), 0)
TEST_EQUAL(c_r.getResidue().countAtoms(), 0)
RESULT
CHECK(Residue& ResidueRotamerSet::getResidue())
ResidueRotamerSet r;
TEST_EQUAL(r.getResidue().countAtoms(), 0)
r.getResidue().insert(*new PDBAtom);
TEST_EQUAL(r.getResidue().countAtoms(), 1)
RESULT
*/
CHECK(const ResidueRotamerSet::operator = (const ResidueRotamerSet& rhs))
// ????
RESULT
CHECK(Rotamer& ResidueRotamerSet::operator [] (Position index) throw(Exception::IndexOverflow))
// ????
RESULT
CHECK(bool setRotamer(Residue& residue, const Rotamer& rotamer))
// ????
RESULT
CHECK(Rotamer getRotamer(const Residue& residue))
// ????
RESULT
CHECK(const Rotamer& getRotamer(Position index))
// ????
RESULT
CHECK(void addRotamer(const Rotamer& rotamer))
// ????
RESULT
CHECK(ResidueRotamerSet::begin())
// ???
RESULT
CHECK(ResidueRotamerSet::end())
// ???
RESULT
CHECK(ResidueRotamerSet::begin() const)
// ???
RESULT
CHECK(ResidueRotamerSet::end() const)
// ???
RESULT
CHECK(ResidueRotamerSet::ResidueRotamerSet(const ResidueRotamerSet& rotamer_set))
ResidueRotamerSet r;
ResidueRotamerSet r2(r);
RESULT
CHECK(Residue* ResidueRotamerSet::buildRotamer(const Rotamer& rotamer))
// ???
RESULT
CHECK(void ResidueRotamerSet::resetResidue())
// ????
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>completed tests<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: ResidueRotamerSet_test.C,v 1.1.2.3 2007/08/07 12:32:18 toussaint Exp $
//
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/STRUCTURE/residueRotamerSet.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/KERNEL/system.h>
///////////////////////////
START_TEST(RotamerLibrary, "$Id: ResidueRotamerSet_test.C,v 1.1.2.3 2007/08/07 12:32:18 toussaint Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
FragmentDB frag_db("fragments/Fragments.db");
Rotamer* rot_ptr = 0;
CHECK(Rotamer::Rotamer())
rot_ptr = new Rotamer;
TEST_NOT_EQUAL(rot_ptr, 0)
ABORT_IF(rot_ptr == 0)
TEST_EQUAL(rot_ptr->P, 0.0)
TEST_EQUAL(rot_ptr->chi1, 0.0)
TEST_EQUAL(rot_ptr->chi2, 0.0)
TEST_EQUAL(rot_ptr->chi3, 0.0)
TEST_EQUAL(rot_ptr->chi4, 0.0)
RESULT
CHECK(Rotamer::~Rotamer())
delete rot_ptr;
RESULT
CHECK(Rotamer::Rotamer(const Rotamer& rotamer))
Rotamer r;
r.P = 1.0;
r.chi1 = Angle(2.1).toDegree();
r.chi2 = Angle(3.2).toDegree();
r.chi3 = Angle(4.3).toDegree();
r.chi4 = Angle(5.4).toDegree();
Rotamer r2(r);
TEST_EQUAL(r2.chi1, r.chi1)
TEST_EQUAL(r2.chi2, r.chi2)
TEST_EQUAL(r2.chi3, r.chi3)
TEST_EQUAL(r2.chi4, r.chi4)
TEST_EQUAL(r2.P, r.P)
RESULT
CHECK(Rotamer::Rotamer(float P, float, chi1, float, chi2, float chi3, float chi4))
Rotamer r(1.0, 2.0, 3.0, 4.0, 5.0);
TEST_REAL_EQUAL(r.chi1, 2.0)
TEST_REAL_EQUAL(r.chi2, 3.0)
TEST_REAL_EQUAL(r.chi3, 4.0)
TEST_REAL_EQUAL(r.chi4, 5.0)
TEST_REAL_EQUAL(r.P, 1.0)
RESULT
ResidueRotamerSet* rrs_ptr = 0;
CHECK(ResidueRotamerSet::ResidueRotamerSet())
rrs_ptr = new ResidueRotamerSet;
TEST_NOT_EQUAL(rrs_ptr, 0)
RESULT
CHECK(ResidueRotamerSet::~ResidueRotamerSet())
delete rrs_ptr;
RESULT
CHECK(ResidueRotamerSet::ResidueRotamerSet(const ResidueRotamerSet& rotamer_set))
ResidueRotamerSet r;
ResidueRotamerSet r2(r);
RESULT
CHECK(ResidueRotamerSet::ResidueRotamerSet(const Residue& residue, Size number_of_torsions))
Residue ser(*frag_db.getResidue("SER"));
ResidueRotamerSet r(ser, 1);
RESULT
CHECK(bool ResidueRotamerSet::isValid())
ResidueRotamerSet r;
TEST_EQUAL(r.isValid(), false)
RESULT
CHECK(const String& ResidueRotamerSet::getName() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getName(), "")
RESULT
CHECK(void ResidueRotamerSet::setName(const String& name))
ResidueRotamerSet r;
TEST_EQUAL(r.getName(), "")
r.setName("asdf");
TEST_EQUAL(r.getName(), "asdf")
r.setName("");
TEST_EQUAL(r.getName(), "")
RESULT
CHECK(Size ResidueRotamerSet::getNumberOfRotamers() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfRotamers(), 0)
RESULT
CHECK(Size ResidueRotamerSet::getNumberOfTorsions() const)
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfTorsions(), 0)
RESULT
CHECK(void ResidueRotamerSet::setNumberOfTorsions(Size number_of_torsions) throw(Exception::IndexOverflow))
ResidueRotamerSet r;
TEST_EQUAL(r.getNumberOfTorsions(), 0)
r.setNumberOfTorsions(1);
TEST_EQUAL(r.getNumberOfTorsions(), 1)
r.setNumberOfTorsions(2);
TEST_EQUAL(r.getNumberOfTorsions(), 2)
r.setNumberOfTorsions(3);
TEST_EQUAL(r.getNumberOfTorsions(), 3)
r.setNumberOfTorsions(4);
TEST_EQUAL(r.getNumberOfTorsions(), 4)
r.setNumberOfTorsions(0);
TEST_EQUAL(r.getNumberOfTorsions(), 0)
TEST_EXCEPTION(Exception::IndexOverflow, r.setNumberOfTorsions(5))
TEST_EXCEPTION(Exception::IndexOverflow, r.setNumberOfTorsions(6))
RESULT
Residue ser(*frag_db.getResidue("SER"));
ResidueRotamerSet rrs(ser, 1);
CHECK(void ResidueRotamerSet::addRotamer(const Rotamer& rotamer))
TEST_EQUAL(rrs.getNumberOfRotamers(), 0)
Rotamer rotamer(0.2, -80, 0, 0, 0);
rrs.addRotamer(rotamer);
Rotamer rotamer2(0.4, 50.2, 0, 0, 0);
rrs.addRotamer(rotamer2);
TEST_EQUAL(rrs.getNumberOfRotamers(), 2)
RESULT
CHECK(const ResidueRotamerSet::operator = (const ResidueRotamerSet& rhs))
ResidueRotamerSet copy_of_rrs;
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 0)
copy_of_rrs = rrs;
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 2)
RESULT
CHECK(Rotamer& ResidueRotamerSet::operator [] (Position index) throw(Exception::IndexOverflow))
TEST_REAL_EQUAL(rrs[0].chi1, -80)
TEST_REAL_EQUAL(rrs[1].P, 0.4)
RESULT
CHECK(const Rotamer& ResidueRotamerSet::getRotamer(Position index))
TEST_REAL_EQUAL(rrs.getRotamer(0).chi1, -80)
TEST_REAL_EQUAL(rrs.getRotamer(1).P, 0.4)
RESULT
CHECK(Rotamer ResidueRotamerSet::getRotamer(const Residue& residue))
System S;
HINFile ags_file("data/AlaGlySer.hin");
ags_file >> S;
ABORT_IF(S.countResidues() != 3)
Residue& serine(*++(++S.beginResidue()));
Rotamer rotamer = rrs.getRotamer(serine);
TEST_NOT_EQUAL(rotamer.chi1, 0)
RESULT
CHECK(bool ResidueRotamerSet::setRotamer(Residue& residue, const Rotamer& rotamer))
Rotamer original(1.0, 75.0, -40.0, 0, 0);
rrs.setRotamer(ser, original);
Rotamer set_rotamer = rrs.getRotamer(ser);
PRECISION(0.001)
TEST_REAL_EQUAL(set_rotamer.chi1, original.chi1)
// Serine only has chi1
TEST_EQUAL(set_rotamer.chi2, 0)
RESULT
CHECK(bool ResidueRotamerSet::hasTorsionPhi())
TEST_EQUAL(rrs.hasTorsionPhi(), false);
RESULT
CHECK(Angle ResidueRotamerSet::getTorsionPhi() const)
TEST_EQUAL(rrs.getTorsionPhi().toDegree(), 0)
RESULT
CHECK(void ResidueRotamerSet::setTorsionPhi(const Angle& phi))
rrs.setTorsionPhi(Angle(60, false));
TEST_EQUAL(rrs.getTorsionPhi().toDegree(), 60)
RESULT
CHECK(bool ResidueRotamerSet::hasTorsionPsi())
TEST_EQUAL(rrs.hasTorsionPsi(), false);
RESULT
CHECK(Angle ResidueRotamerSet::getTorsionPsi() const)
TEST_EQUAL(rrs.getTorsionPsi().toDegree(), 0)
RESULT
CHECK(void ResidueRotamerSet::setTorsionPsi(const Angle& psi))
rrs.setTorsionPsi(Angle(-60, false));
TEST_EQUAL(rrs.getTorsionPsi().toDegree(), -60)
RESULT
CHECK(bool ResidueRotamerSet::setTemplateResidue(const Residue& residue, Size number_of_torsions))
System S;
HINFile ags_file("data/AlaGlySer.hin");
ags_file >> S;
ABORT_IF(S.countResidues() != 3)
Residue& gly(*++S.beginResidue());
ResidueRotamerSet copy_of_rrs(rrs);
TEST_EQUAL(copy_of_rrs.getName(), "SER")
copy_of_rrs.setTemplateResidue(gly, 0);
TEST_EQUAL(copy_of_rrs.getName(), "GLY")
RESULT
CHECK(void ResidueRotamerSet::deleteRotamer(Iterator loc))
ResidueRotamerSet copy_of_rrs(rrs);
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 2)
copy_of_rrs.deleteRotamer(copy_of_rrs.begin());
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 1)
RESULT
CHECK(void ResidueRotamerSet::deleteRotamers(Iterator begin, Iterator end))
ResidueRotamerSet copy_of_rrs(rrs);
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 2)
copy_of_rrs.deleteRotamers(copy_of_rrs.begin(), copy_of_rrs.end());
TEST_EQUAL(copy_of_rrs.getNumberOfRotamers(), 0)
RESULT
CHECK(void ResidueRotamerSet::sort())
ResidueRotamerSet copy_of_rrs(rrs);
TEST_REAL_EQUAL(copy_of_rrs[0].P, 0.2)
copy_of_rrs.sort();
TEST_REAL_EQUAL(copy_of_rrs[0].P, 0.4)
RESULT
CHECK(ResidueRotamerSet::begin())
Rotamer rotamer = rrs[0];
ResidueRotamerSet::Iterator iter = rrs.begin();
TEST_REAL_EQUAL((*iter).P, rotamer.P)
RESULT
CHECK(ResidueRotamerSet::end())
ResidueRotamerSet::Iterator begin = rrs.begin();
ResidueRotamerSet::Iterator end = rrs.end();
TEST_EQUAL(end-begin, 2)
RESULT
CHECK(ResidueRotamerSet::begin() const)
Rotamer rotamer = rrs[0];
ResidueRotamerSet::Iterator iter = rrs.begin();
TEST_REAL_EQUAL((*iter).P, rotamer.P)
RESULT
CHECK(ResidueRotamerSet::end() const)
ResidueRotamerSet::ConstIterator begin = rrs.begin();
ResidueRotamerSet::ConstIterator end = rrs.end();
TEST_EQUAL(end-begin, 2)
RESULT
CHECK(ResidueRotamerSet::ResidueRotamerSet(const ResidueRotamerSet& rotamer_set))
ResidueRotamerSet r;
ResidueRotamerSet r2(r);
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>#include "NetworkListenerSystem.h"
NetworkListenerSystem::NetworkListenerSystem( TcpServer* p_server )
: EntitySystem( SystemType::NetworkListenerSystem, 1, ComponentType::NetworkSynced)
{
m_server = p_server;
}
NetworkListenerSystem::~NetworkListenerSystem()
{
m_server->stopListening();
}
void NetworkListenerSystem::processEntities( const vector<Entity*>& p_entities )
{
while (m_server->hasNewDisconnections())
{
int id = m_server->popNewDisconnection();
for (unsigned int index = 0; index < p_entities.size(); index++)
{
NetworkSynced* netSync = static_cast<NetworkSynced*>(
m_world->getComponentManager()->getComponent( p_entities[index],
ComponentType::getTypeFor( ComponentType::NetworkSynced ) ) );
// When a client is disconnecting, then all other clients must know this.
// HACK: This deletion is what caused the magical crashes all the time.
// This should be solved as soon as possible.
// if (netSync->getNetworkIdentity() == id)
// m_world->deleteEntity(p_entities[index]);
}
}
if ( m_server->isListening() )
{
while( m_server->hasNewConnections() )
{
int id = m_server->popNewConnection();
Entity* e = m_world->createEntity();
e->addComponent( ComponentType::getTypeFor( ComponentType::Transform ),
new Transform( (float)(id) * 10.0f, 0, 0 ) );
e->addComponent( ComponentType::getTypeFor( ComponentType::NetworkSynced ),
new NetworkSynced( id, id ) );
m_world->addEntity( e );
// When a client is connecting, the server must broadcast to all other
// clients that a new client exists.
// Packet needed: ON_CLIENT_CONNECT
// data: clientId
// And entity creation.
vector<int> currentConnections = m_server->getActiveConnections();
for( unsigned int i=0; i<currentConnections.size(); i++ )
{
if( currentConnections[i] == id )
{
currentConnections.erase( currentConnections.begin() + i );
DEBUGPRINT(( toString(i).c_str() ));
}
}
// HACK: Just some testing packet here.
Packet newClientConnected;
newClientConnected << (char)PacketType::EntityCreation <<
(char)NetworkType::Ship << id << e->getIndex() <<
(float)(id) * 10.0f << (float)0 << (float)0;
m_server->multicastPacket( currentConnections, newClientConnected );
// The server must then initialize data for the new client.
// Packets needed: CREATE_ENTITY
// int: id
// string: name (debug)
// Packets needed: ADD_COMPONENT
// int: entityId
// int: componentTypeId
// *: specificComponentData
// Send the new ship created:
NetworkSynced* netSync = NULL;
netSync = (NetworkSynced*)m_world->getComponentManager()->
getComponent(
e->getIndex(), ComponentType::NetworkSynced );
// Send the old networkSynced stuff:
for( unsigned int i=0; i<p_entities.size(); i++ )
{
netSync = (NetworkSynced*)m_world->getComponentManager()->
getComponent(
p_entities[i]->getIndex(), ComponentType::NetworkSynced );
// Create entity
if( netSync->getNetworkType() == NetworkType::Ship )
{
Packet packet;
packet << (char)PacketType::EntityCreation <<
(char)NetworkType::Ship << id << p_entities[i]->getIndex() <<
(float)(id) * 10.0f << (float)0 << (float)0;
m_server->unicastPacket( packet, id );
}
}
}
}
}
void NetworkListenerSystem::initialize()
{
m_server->startListening(1337);
}<commit_msg>Changed so that ComponentType::getTypeFor() method isn't used any more. I might have missed some old ones.<commit_after>#include "NetworkListenerSystem.h"
NetworkListenerSystem::NetworkListenerSystem( TcpServer* p_server )
: EntitySystem( SystemType::NetworkListenerSystem, 1, ComponentType::NetworkSynced)
{
m_server = p_server;
}
NetworkListenerSystem::~NetworkListenerSystem()
{
m_server->stopListening();
}
void NetworkListenerSystem::processEntities( const vector<Entity*>& p_entities )
{
while (m_server->hasNewDisconnections())
{
int id = m_server->popNewDisconnection();
for (unsigned int index = 0; index < p_entities.size(); index++)
{
NetworkSynced* netSync = static_cast<NetworkSynced*>(
m_world->getComponentManager()->getComponent( p_entities[index],
ComponentType::NetworkSynced ) );
// When a client is disconnecting, then all other clients must know this.
// HACK: This deletion is what caused the magical crashes all the time.
// This should be solved as soon as possible.
// if (netSync->getNetworkIdentity() == id)
// m_world->deleteEntity(p_entities[index]);
}
}
if ( m_server->isListening() )
{
while( m_server->hasNewConnections() )
{
int id = m_server->popNewConnection();
Entity* e = m_world->createEntity();
e->addComponent( ComponentType::Transform,
new Transform( (float)(id) * 10.0f, 0, 0 ) );
e->addComponent( ComponentType::NetworkSynced,
new NetworkSynced( e->getIndex(), id, NetworkType::Ship ) );
m_world->addEntity( e );
// When a client is connecting, the server must broadcast to all other
// clients that a new client exists.
// Packet needed: ON_CLIENT_CONNECT
// data: clientId
// And entity creation.
vector<int> currentConnections = m_server->getActiveConnections();
for( unsigned int i=0; i<currentConnections.size(); i++ )
{
if( currentConnections[i] == id )
{
currentConnections.erase( currentConnections.begin() + i );
DEBUGPRINT(( toString(i).c_str() ));
}
}
// HACK: Just some testing packet here.
Packet newClientConnected;
newClientConnected << (char)PacketType::EntityCreation <<
(char)NetworkType::Ship << id << e->getIndex() <<
(float)(id) * 10.0f << (float)0 << (float)0;
m_server->multicastPacket( currentConnections, newClientConnected );
// The server must then initialize data for the new client.
// Packets needed: CREATE_ENTITY
// int: id
// string: name (debug)
// Packets needed: ADD_COMPONENT
// int: entityId
// int: componentTypeId
// *: specificComponentData
// Send the new ship created:
NetworkSynced* netSync = NULL;
netSync = (NetworkSynced*)m_world->getComponentManager()->
getComponent(
e->getIndex(), ComponentType::NetworkSynced );
// Send the old networkSynced stuff:
for( unsigned int i=0; i<p_entities.size(); i++ )
{
netSync = (NetworkSynced*)m_world->getComponentManager()->
getComponent(
p_entities[i]->getIndex(), ComponentType::NetworkSynced );
// Create entity
if( netSync->getNetworkType() == NetworkType::Ship )
{
Packet packet;
packet << (char)PacketType::EntityCreation <<
(char)NetworkType::Ship << id << p_entities[i]->getIndex() <<
(float)(id) * 10.0f << (float)0 << (float)0;
m_server->unicastPacket( packet, id );
}
}
}
}
}
void NetworkListenerSystem::initialize()
{
m_server->startListening(1337);
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/umain.hh
#ifndef URBI_UMAIN_HH
# define URBI_UMAIN_HH
# include <libport/cli.hh>
# include <urbi/exit.hh>
# include <urbi/uobject.hh>
# include <urbi/urbi-root.hh>
# define UMAIN() \
\
int \
main(int argc, const char** argv) \
{ \
UrbiRoot urbi_root(argv[0]); \
return urbi::main(argc, argv, urbi_root, true, true); \
} \
\
int \
main_args(const libport::cli_args_type& args) \
{ \
size_t argc = args.size(); \
const char** argv = new const char*[argc]; \
for (unsigned i = 0; i < argc; ++i) \
argv[i] = args[i].c_str(); \
int res = main(argc, argv); \
delete [] argv; \
return res; \
} \
extern "C"
{
/** Bouncer to urbi::main() for easier access through dlsym(). */
URBI_SDK_API int urbi_main(int argc, const char* argv[], UrbiRoot& root,
bool block, bool errors);
/** Bouncer to urbi::main() for easier access through dlsym(). */
URBI_SDK_API int urbi_main_args(const libport::cli_args_type& args, UrbiRoot& root,
bool block, bool errors);
}
namespace urbi
{
/** Initialisation method.
* Both plugin and remote libraries include a main function whose only
* effect is to call urbi::main. If you need to write your own main, call
* urbi::main(argc, argv) after your work is done.
* This function returns if block is set to false.
*/
URBI_SDK_API int main(const libport::cli_args_type& args, UrbiRoot& root,
bool block = true, bool errors = false);
/** Initialisation method using C style arguments.
*/
URBI_SDK_API int main(int argc, const char *argv[], UrbiRoot& root,
bool block = true, bool errors = false);
/** Initialisation method, for remote mode only, that returns.
* \param host the host to connect to.
* \param port the port number to connect to (you can use the constant
* UAbstractClient::URBI_PORT).
* \param buflen receive and send buffer size (you can use the constant
* UAbstractClient::URBI_BUFLEN).
* \param exitOnDisconnect call exit() if we get disconnected from server.
* \return 0 if no error occured.
*/
int URBI_SDK_API initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server = false);
}
#endif /* !URBI_UMAIN_HH */
<commit_msg>umain: Use UrbiRoot.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/umain.hh
#ifndef URBI_UMAIN_HH
# define URBI_UMAIN_HH
# include <libport/cli.hh>
# include <urbi/exit.hh>
# include <urbi/uobject.hh>
# include <urbi/urbi-root.hh>
# define UMAIN() \
\
int \
main(int argc, const char** argv) \
{ \
UrbiRoot urbi_root(argv[0]); \
std::vector<std::string> args(argv, argv + argc); \
return urbi_root.urbi_main(args, true, true); \
} \
\
int \
main_args(const libport::cli_args_type& args) \
{ \
size_t argc = args.size(); \
const char** argv = new const char*[argc]; \
for (unsigned i = 0; i < argc; ++i) \
argv[i] = args[i].c_str(); \
int res = main(argc, argv); \
delete [] argv; \
return res; \
} \
extern "C"
{
/** Bouncer to urbi::main() for easier access through dlsym(). */
URBI_SDK_API int urbi_main(int argc, const char* argv[], UrbiRoot& root,
bool block, bool errors);
/** Bouncer to urbi::main() for easier access through dlsym(). */
URBI_SDK_API int urbi_main_args(const libport::cli_args_type& args, UrbiRoot& root,
bool block, bool errors);
}
namespace urbi
{
/** Initialisation method.
* Both plugin and remote libraries include a main function whose only
* effect is to call urbi::main. If you need to write your own main, call
* urbi::main(argc, argv) after your work is done.
* This function returns if block is set to false.
*/
URBI_SDK_API int main(const libport::cli_args_type& args, UrbiRoot& root,
bool block = true, bool errors = false);
/** Initialisation method using C style arguments.
*/
URBI_SDK_API int main(int argc, const char *argv[], UrbiRoot& root,
bool block = true, bool errors = false);
/** Initialisation method, for remote mode only, that returns.
* \param host the host to connect to.
* \param port the port number to connect to (you can use the constant
* UAbstractClient::URBI_PORT).
* \param buflen receive and send buffer size (you can use the constant
* UAbstractClient::URBI_BUFLEN).
* \param exitOnDisconnect call exit() if we get disconnected from server.
* \return 0 if no error occured.
*/
int URBI_SDK_API initialize(const std::string& host, int port, size_t buflen,
bool exitOnDisconnect, bool server = false);
}
#endif /* !URBI_UMAIN_HH */
<|endoftext|> |
<commit_before>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0
AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
delete this->m_AIComponents.at(i);
}
return SUCCESS;
}
int AIHandler::Initialize(int nrOfAIComponents)
{
this->m_nrOfAIComponents = 0;
if (nrOfAIComponents < 0)
return FAIL;
this->m_nrOfAIComponents = nrOfAIComponents;
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
m_AIComponents.push_back(CreateAIComponent(i));
}
return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
using namespace DirectX;
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
{
// AIComponent logic/behavior, movement of e.g. platforms
int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
int pattern = this->m_AIComponents.at(i)->m_pattern;
int time = this->m_AIComponents.at(i)->m_time;
int direction = this->m_AIComponents.at(i)->m_direction;
if (pattern == 1)
{
if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
{
if (direction == 0)
this->m_AIComponents.at(i)->m_direction = 1;
else
this->m_AIComponents.at(i)->m_direction = 0;
}
}
else if (pattern == 3)
{
//TODO Round-trip pattern
}
else
{
//Identical to pattern 2 (Circular)
if (direction == 0)
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint++;
if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = 0;
}
}
else
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint--;
if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
}
}
}
//TODO Update position
}
}
return SUCCESS;
}
void AIHandler::SetComponentActive(int compID)
{
this->m_AIComponents.at(compID)->m_active = true;
}
void AIHandler::SetComponentFalse(int compID)
{
this->m_AIComponents.at(compID)->m_active = false;
}
void AIHandler::SetEntityID(int compID, int entityID)
{
this->m_AIComponents.at(compID)->m_entityID = entityID;
}
void AIHandler::SetTriggered(int compID, bool triggered)
{
this->m_AIComponents.at(compID)->m_triggered = triggered;
}
void AIHandler::SetTime(int compID, int time)
{
this->m_AIComponents.at(compID)->m_time = time;
}
void AIHandler::SetSpeed(int compID, int speed)
{
this->m_AIComponents.at(compID)->m_speed = speed;
}
void AIHandler::SetDirection(int compID, int direction)
{
this->m_AIComponents.at(compID)->m_direction = direction;
}
void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}
AIDLL_API void AIHandler::SetPattern(int compID, int pattern)
{
this->m_AIComponents.at(compID)->m_pattern = pattern;
}
void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
for (int i = 0; i < 8; i++)
{
this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
}
}
int AIHandler::GetNrOfAIComponents() const
{
return this->m_nrOfAIComponents;
}
AIDLL_API DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
return this->m_AIComponents.at(compID)->m_position;
}
AIComponent* AIHandler::CreateAIComponent(int entityID)
{
AIComponent* newComponent = nullptr;
newComponent = new AIComponent;
newComponent->m_active = 0;
newComponent->m_entityID = entityID;
newComponent->m_position = DirectX::XMVECTOR();
newComponent->m_triggered = false;
newComponent->m_time = 0;
newComponent->m_speed = 0;
newComponent->m_direction = 0;
newComponent->m_currentWaypoint = 0;
newComponent->m_nrOfWaypoint = 0;
for (int i = 0; i < 8; i++) {
newComponent->m_waypoints[i] = DirectX::XMVECTOR();
newComponent->m_nrOfWaypoint++;
}
return newComponent;
}
bool AIHandler::WaypointApprox(int compID)
{
using namespace DirectX;
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
,this->m_AIComponents.at(compID)->m_waypoints[current]);
float length = VectorLength(v);
if (length > 0.1)
{
return true;
}
return false;
}
int AIHandler::GetNextWaypoint(int compID, int pattern)
{
/*const int ARR_LEN = 10;
int arr[ARR_LEN] = { 0,1,2,3,4,5,6,7,8,9 };
for (int i = 0; i < ARR_LEN * 2; ++i)
cout << arr[i % ARR_LEN] << " ";*/
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
if (pattern == 1)
{
//TODO Linear pattern next waypoint logic
}
else
{
//if (this->m_AIComponents.at(compID)->m_nrOfWaypoint)
}
if (next == current)
{
}
this->m_AIComponents.at(compID)->m_currentWaypoint;
this->m_AIComponents.at(compID)->m_direction;
//this->m_AIComponents.at(compID)->m_waypoints[i];
return 0;
}
float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
return length;
}
<commit_msg>REMOVE dllexport macro since it's suppose to be in header only<commit_after>#include "AIHandler.h"
#define SUCCESS 1
#define FAIL 0
AIHandler::AIHandler(){}
AIHandler::~AIHandler(){}
int AIHandler::Shutdown()
{
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
delete this->m_AIComponents.at(i);
}
return SUCCESS;
}
int AIHandler::Initialize(int nrOfAIComponents)
{
this->m_nrOfAIComponents = 0;
if (nrOfAIComponents < 0)
return FAIL;
this->m_nrOfAIComponents = nrOfAIComponents;
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
m_AIComponents.push_back(CreateAIComponent(i));
}
return SUCCESS;
}
int AIHandler::Update(float deltaTime)
{
using namespace DirectX;
for (int i = 0; i < this->m_nrOfAIComponents; i++)
{
if (this->m_AIComponents.at(i)->m_active && this->m_AIComponents.at(i)->m_triggered)
{
// AIComponent logic/behavior, movement of e.g. platforms
int currentWaypoint = this->m_AIComponents.at(i)->m_currentWaypoint;
int nrOfWaypoint = this->m_AIComponents.at(i)->m_nrOfWaypoint;
int pattern = this->m_AIComponents.at(i)->m_pattern;
int time = this->m_AIComponents.at(i)->m_time;
int direction = this->m_AIComponents.at(i)->m_direction;
if (pattern == 1)
{
if (currentWaypoint == 0 || currentWaypoint == nrOfWaypoint)
{
if (direction == 0)
this->m_AIComponents.at(i)->m_direction = 1;
else
this->m_AIComponents.at(i)->m_direction = 0;
}
}
else if (pattern == 3)
{
//TODO Round-trip pattern
}
else
{
//Identical to pattern 2 (Circular)
if (direction == 0)
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint++;
if (this->m_AIComponents.at(i)->m_nextWaypoint >= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = 0;
}
}
else
{
if (WaypointApprox(i))
{
currentWaypoint = this->m_AIComponents.at(i)->m_nextWaypoint;
this->m_AIComponents.at(i)->m_nextWaypoint--;
if (this->m_AIComponents.at(i)->m_nextWaypoint <= this->m_AIComponents.at(i)->m_nrOfWaypoint)
this->m_AIComponents.at(i)->m_nextWaypoint = nrOfWaypoint;
}
}
}
//TODO Update position
}
}
return SUCCESS;
}
void AIHandler::SetComponentActive(int compID)
{
this->m_AIComponents.at(compID)->m_active = true;
}
void AIHandler::SetComponentFalse(int compID)
{
this->m_AIComponents.at(compID)->m_active = false;
}
void AIHandler::SetEntityID(int compID, int entityID)
{
this->m_AIComponents.at(compID)->m_entityID = entityID;
}
void AIHandler::SetTriggered(int compID, bool triggered)
{
this->m_AIComponents.at(compID)->m_triggered = triggered;
}
void AIHandler::SetTime(int compID, int time)
{
this->m_AIComponents.at(compID)->m_time = time;
}
void AIHandler::SetSpeed(int compID, int speed)
{
this->m_AIComponents.at(compID)->m_speed = speed;
}
void AIHandler::SetDirection(int compID, int direction)
{
this->m_AIComponents.at(compID)->m_direction = direction;
}
void AIHandler::SetCurrentWaypoint(int compID, int currentWaypoint)
{
this->m_AIComponents.at(compID)->m_currentWaypoint = currentWaypoint;
}
void AIHandler::SetPattern(int compID, int pattern)
{
this->m_AIComponents.at(compID)->m_pattern = pattern;
}
void AIHandler::SetWaypoints(int compID, DirectX::XMVECTOR waypoints[])
{
for (int i = 0; i < 8; i++)
{
this->m_AIComponents.at(compID)->m_waypoints[i] = waypoints[i];
this->m_AIComponents.at(compID)->m_nrOfWaypoint++;
}
}
int AIHandler::GetNrOfAIComponents() const
{
return this->m_nrOfAIComponents;
}
DirectX::XMVECTOR AIHandler::GetPosition(int compID) const
{
return this->m_AIComponents.at(compID)->m_position;
}
AIComponent* AIHandler::CreateAIComponent(int entityID)
{
AIComponent* newComponent = nullptr;
newComponent = new AIComponent;
newComponent->m_active = 0;
newComponent->m_entityID = entityID;
newComponent->m_position = DirectX::XMVECTOR();
newComponent->m_triggered = false;
newComponent->m_time = 0;
newComponent->m_speed = 0;
newComponent->m_direction = 0;
newComponent->m_currentWaypoint = 0;
newComponent->m_nrOfWaypoint = 0;
for (int i = 0; i < 8; i++) {
newComponent->m_waypoints[i] = DirectX::XMVECTOR();
newComponent->m_nrOfWaypoint++;
}
return newComponent;
}
bool AIHandler::WaypointApprox(int compID)
{
using namespace DirectX;
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
DirectX::XMVECTOR v = DirectX::XMVectorSubtract(this->m_AIComponents.at(compID)->m_waypoints[next]
,this->m_AIComponents.at(compID)->m_waypoints[current]);
float length = VectorLength(v);
if (length > 0.1)
{
return true;
}
return false;
}
int AIHandler::GetNextWaypoint(int compID, int pattern)
{
/*const int ARR_LEN = 10;
int arr[ARR_LEN] = { 0,1,2,3,4,5,6,7,8,9 };
for (int i = 0; i < ARR_LEN * 2; ++i)
cout << arr[i % ARR_LEN] << " ";*/
int next = this->m_AIComponents.at(compID)->m_currentWaypoint;
int current = this->m_AIComponents.at(compID)->m_nextWaypoint;
if (pattern == 1)
{
//TODO Linear pattern next waypoint logic
}
else
{
//if (this->m_AIComponents.at(compID)->m_nrOfWaypoint)
}
if (next == current)
{
}
this->m_AIComponents.at(compID)->m_currentWaypoint;
this->m_AIComponents.at(compID)->m_direction;
//this->m_AIComponents.at(compID)->m_waypoints[i];
return 0;
}
float AIHandler::VectorLength(DirectX::XMVECTOR v)
{
float length = DirectX::XMVectorGetX(DirectX::XMVector3Length(v));
return length;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the AliESDfriendTrack class
// This class keeps complementary to the AliESDtrack information
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include "AliTrackPointArray.h"
#include "AliESDfriendTrack.h"
#include "TObjArray.h"
#include "TClonesArray.h"
#include "AliKalmanTrack.h"
#include "AliVTPCseed.h"
#include "AliLog.h"
ClassImp(AliESDfriendTrack)
AliESDfriendTrack::AliESDfriendTrack():
AliVfriendTrack(),
f1P(0),
fnMaxITScluster(0),
fnMaxTPCcluster(0),
fnMaxTRDcluster(0),
fITSindex(0x0),
fTPCindex(0x0),
fTRDindex(0x0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0),
fTPCOut(0),
fITSOut(0),
fTRDIn(0)
{
//
// Default constructor
//
// Int_t i;
// fITSindex = new Int_t[fnMaxITScluster];
//fTPCindex = new Int_t[fnMaxTPCcluster];
//fTRDindex = new Int_t[fnMaxTRDcluster];
//for (i=0; i<kMaxITScluster; i++) fITSindex[i]=-2;
//for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=-2;
//for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=-2;
//fHmpPhotClus->SetOwner(kTRUE);
}
AliESDfriendTrack::AliESDfriendTrack(const AliESDfriendTrack &t):
AliVfriendTrack(t),
f1P(t.f1P),
fnMaxITScluster(t.fnMaxITScluster),
fnMaxTPCcluster(t.fnMaxTPCcluster),
fnMaxTRDcluster(t.fnMaxTRDcluster),
fITSindex(0x0),
fTPCindex(0x0),
fTRDindex(0x0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0),
fTPCOut(0),
fITSOut(0),
fTRDIn(0)
{
//
// Copy constructor
//
AliDebug(2,"Calling copy constructor");
Int_t i;
if (fnMaxITScluster != 0){
fITSindex = new Int_t[fnMaxITScluster];
for (i=0; i<fnMaxITScluster; i++) fITSindex[i]=t.fITSindex[i];
}
if (fnMaxTPCcluster != 0){
fTPCindex = new Int_t[fnMaxTPCcluster];
for (i=0; i<fnMaxTPCcluster; i++) fTPCindex[i]=t.fTPCindex[i];
}
if (fnMaxTRDcluster != 0){
fTRDindex = new Int_t[fnMaxTRDcluster];
for (i=0; i<fnMaxTRDcluster; i++) fTRDindex[i]=t.fTRDindex[i];
}
AliDebug(2,Form("fnMaxITScluster = %d",fnMaxITScluster));
AliDebug(2,Form("fnMaxTPCcluster = %d",fnMaxTPCcluster));
AliDebug(2,Form("fnMaxTRDcluster = %d",fnMaxTRDcluster));
if (t.fPoints) fPoints=new AliTrackPointArray(*t.fPoints);
if (t.fCalibContainer) {
fCalibContainer = new TObjArray(5);
fCalibContainer->SetOwner();
Int_t no=t.fCalibContainer->GetEntriesFast();
for (i=0; i<no; i++) {
TObject *o=t.fCalibContainer->At(i);
if (o) fCalibContainer->AddLast(o->Clone());
}
}
if (t.fTPCOut) fTPCOut = new AliExternalTrackParam(*(t.fTPCOut));
if (t.fITSOut) fITSOut = new AliExternalTrackParam(*(t.fITSOut));
if (t.fTRDIn) fTRDIn = new AliExternalTrackParam(*(t.fTRDIn));
}
AliESDfriendTrack::~AliESDfriendTrack() {
//
// Simple destructor
//
if(fPoints)
delete fPoints;
fPoints=0;
if (fCalibContainer){
fCalibContainer->Delete();
delete fCalibContainer;
fCalibContainer=0;
}
if(fITStrack)
delete fITStrack;
fITStrack=0;
if(fTRDtrack)
delete fTRDtrack;
fTRDtrack=0;
if(fTPCOut)
delete fTPCOut;
fTPCOut=0;
if(fITSOut)
delete fITSOut;
fITSOut=0;
if(fTRDIn)
delete fTRDIn;
fTRDIn=0;
if(fITSindex)
delete[] fITSindex;
fITSindex=0;
if(fTPCindex)
delete[] fTPCindex;
fTPCindex=0;
if(fTRDindex)
delete[] fTRDindex;
fTRDindex=0;
}
void AliESDfriendTrack::AddCalibObject(TObject * calibObject){
//
// add calibration object to array -
// track is owner of the objects in the container
//
if (!fCalibContainer) {
fCalibContainer = new TObjArray(5);
fCalibContainer->SetOwner();
}
fCalibContainer->AddLast(calibObject);
}
void AliESDfriendTrack::RemoveCalibObject(TObject * calibObject){
//
// remove calibration object from the array -
//
if (fCalibContainer) fCalibContainer->Remove(calibObject);
}
TObject * AliESDfriendTrack::GetCalibObject(Int_t index) const {
//
//
//
if (!fCalibContainer) return 0;
if (index>=fCalibContainer->GetEntriesFast()) return 0;
return fCalibContainer->At(index);
}
Int_t AliESDfriendTrack::GetTPCseed( AliTPCseed &seed) const {
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) {
seedP->CopyToTPCseed( seed );
return 0;
}
}
return -1;
}
const TObject* AliESDfriendTrack::GetTPCseed() const
{
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) return calibObject;
}
return 0;
}
void AliESDfriendTrack::ResetTPCseed( const AliTPCseed* seed )
{
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) break;
}
if (seedP) seedP->SetFromTPCseed(seed);
}
void AliESDfriendTrack::SetTPCOut(const AliExternalTrackParam ¶m) {
//
// backup TPC out track
//
if(fTPCOut)
delete fTPCOut;
fTPCOut=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetITSOut(const AliExternalTrackParam ¶m) {
//
// backup ITS out track
//
if(fITSOut)
delete fITSOut;
fITSOut=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetTRDIn(const AliExternalTrackParam ¶m) {
//
// backup TRD in track
//
if(fTRDIn)
delete fTRDIn;
fTRDIn=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetITSIndices(Int_t* indices, Int_t n){
//
// setting fITSindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxITScluster && fnMaxITScluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxITScluster,n));
}
fnMaxITScluster = n;
AliDebug(2,Form("fnMaxITScluster = %d",fnMaxITScluster));
if (fITSindex == 0x0){
fITSindex = new Int_t[fnMaxITScluster];
}
for (Int_t i = 0; i < fnMaxITScluster; i++){
fITSindex[i] = indices[i];
}
}
void AliESDfriendTrack::SetTPCIndices(Int_t* indices, Int_t n){
//
// setting fTPCindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxTPCcluster && fnMaxTPCcluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxTPCcluster,n));
}
fnMaxTPCcluster = n;
AliDebug(2,Form("fnMaxTPCcluster = %d",fnMaxTPCcluster));
if (fTPCindex == 0x0){
fTPCindex = new Int_t[fnMaxTPCcluster];
}
for (Int_t i = 0; i < fnMaxTPCcluster; i++){
fTPCindex[i] = indices[i];
}
}
void AliESDfriendTrack::SetTRDIndices(Int_t* indices, Int_t n){
//
// setting fTRDindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxTRDcluster && fnMaxTRDcluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxTRDcluster,n));
}
fnMaxTRDcluster = n;
AliDebug(2,Form("fnMaxTRDcluster = %d",fnMaxTRDcluster));
if (fTRDindex == 0x0){
fTRDindex = new Int_t[fnMaxTRDcluster];
}
for (Int_t i = 0; i < fnMaxTRDcluster; i++){
fTRDindex[i] = indices[i];
}
}
<commit_msg>use memcpy instead of assignment in loop for large arrays<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the AliESDfriendTrack class
// This class keeps complementary to the AliESDtrack information
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include "AliTrackPointArray.h"
#include "AliESDfriendTrack.h"
#include "TObjArray.h"
#include "TClonesArray.h"
#include "AliKalmanTrack.h"
#include "AliVTPCseed.h"
#include "AliLog.h"
ClassImp(AliESDfriendTrack)
AliESDfriendTrack::AliESDfriendTrack():
AliVfriendTrack(),
f1P(0),
fnMaxITScluster(0),
fnMaxTPCcluster(0),
fnMaxTRDcluster(0),
fITSindex(0x0),
fTPCindex(0x0),
fTRDindex(0x0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0),
fTPCOut(0),
fITSOut(0),
fTRDIn(0)
{
//
// Default constructor
//
// Int_t i;
// fITSindex = new Int_t[fnMaxITScluster];
//fTPCindex = new Int_t[fnMaxTPCcluster];
//fTRDindex = new Int_t[fnMaxTRDcluster];
//for (i=0; i<kMaxITScluster; i++) fITSindex[i]=-2;
//for (i=0; i<kMaxTPCcluster; i++) fTPCindex[i]=-2;
//for (i=0; i<kMaxTRDcluster; i++) fTRDindex[i]=-2;
//fHmpPhotClus->SetOwner(kTRUE);
}
AliESDfriendTrack::AliESDfriendTrack(const AliESDfriendTrack &t):
AliVfriendTrack(t),
f1P(t.f1P),
fnMaxITScluster(t.fnMaxITScluster),
fnMaxTPCcluster(t.fnMaxTPCcluster),
fnMaxTRDcluster(t.fnMaxTRDcluster),
fITSindex(0x0),
fTPCindex(0x0),
fTRDindex(0x0),
fPoints(0),
fCalibContainer(0),
fITStrack(0),
fTRDtrack(0),
fTPCOut(0),
fITSOut(0),
fTRDIn(0)
{
//
// Copy constructor
//
AliDebug(2,"Calling copy constructor");
Int_t i;
if (fnMaxITScluster != 0){
fITSindex = new Int_t[fnMaxITScluster];
for (i=0; i<fnMaxITScluster; i++) fITSindex[i]=t.fITSindex[i];
}
if (fnMaxTPCcluster != 0){
fTPCindex = new Int_t[fnMaxTPCcluster];
for (i=0; i<fnMaxTPCcluster; i++) fTPCindex[i]=t.fTPCindex[i];
}
if (fnMaxTRDcluster != 0){
fTRDindex = new Int_t[fnMaxTRDcluster];
for (i=0; i<fnMaxTRDcluster; i++) fTRDindex[i]=t.fTRDindex[i];
}
AliDebug(2,Form("fnMaxITScluster = %d",fnMaxITScluster));
AliDebug(2,Form("fnMaxTPCcluster = %d",fnMaxTPCcluster));
AliDebug(2,Form("fnMaxTRDcluster = %d",fnMaxTRDcluster));
if (t.fPoints) fPoints=new AliTrackPointArray(*t.fPoints);
if (t.fCalibContainer) {
fCalibContainer = new TObjArray(5);
fCalibContainer->SetOwner();
Int_t no=t.fCalibContainer->GetEntriesFast();
for (i=0; i<no; i++) {
TObject *o=t.fCalibContainer->At(i);
if (o) fCalibContainer->AddLast(o->Clone());
}
}
if (t.fTPCOut) fTPCOut = new AliExternalTrackParam(*(t.fTPCOut));
if (t.fITSOut) fITSOut = new AliExternalTrackParam(*(t.fITSOut));
if (t.fTRDIn) fTRDIn = new AliExternalTrackParam(*(t.fTRDIn));
}
AliESDfriendTrack::~AliESDfriendTrack() {
//
// Simple destructor
//
if(fPoints)
delete fPoints;
fPoints=0;
if (fCalibContainer){
fCalibContainer->Delete();
delete fCalibContainer;
fCalibContainer=0;
}
if(fITStrack)
delete fITStrack;
fITStrack=0;
if(fTRDtrack)
delete fTRDtrack;
fTRDtrack=0;
if(fTPCOut)
delete fTPCOut;
fTPCOut=0;
if(fITSOut)
delete fITSOut;
fITSOut=0;
if(fTRDIn)
delete fTRDIn;
fTRDIn=0;
if(fITSindex)
delete[] fITSindex;
fITSindex=0;
if(fTPCindex)
delete[] fTPCindex;
fTPCindex=0;
if(fTRDindex)
delete[] fTRDindex;
fTRDindex=0;
}
void AliESDfriendTrack::AddCalibObject(TObject * calibObject){
//
// add calibration object to array -
// track is owner of the objects in the container
//
if (!fCalibContainer) {
fCalibContainer = new TObjArray(5);
fCalibContainer->SetOwner();
}
fCalibContainer->AddLast(calibObject);
}
void AliESDfriendTrack::RemoveCalibObject(TObject * calibObject){
//
// remove calibration object from the array -
//
if (fCalibContainer) fCalibContainer->Remove(calibObject);
}
TObject * AliESDfriendTrack::GetCalibObject(Int_t index) const {
//
//
//
if (!fCalibContainer) return 0;
if (index>=fCalibContainer->GetEntriesFast()) return 0;
return fCalibContainer->At(index);
}
Int_t AliESDfriendTrack::GetTPCseed( AliTPCseed &seed) const {
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) {
seedP->CopyToTPCseed( seed );
return 0;
}
}
return -1;
}
const TObject* AliESDfriendTrack::GetTPCseed() const
{
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) return calibObject;
}
return 0;
}
void AliESDfriendTrack::ResetTPCseed( const AliTPCseed* seed )
{
TObject* calibObject = NULL;
AliVTPCseed* seedP = NULL;
for (Int_t idx = 0; (calibObject = GetCalibObject(idx)); ++idx) {
if ((seedP = dynamic_cast<AliVTPCseed*>(calibObject))) break;
}
if (seedP) seedP->SetFromTPCseed(seed);
}
void AliESDfriendTrack::SetTPCOut(const AliExternalTrackParam ¶m) {
//
// backup TPC out track
//
if(fTPCOut)
delete fTPCOut;
fTPCOut=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetITSOut(const AliExternalTrackParam ¶m) {
//
// backup ITS out track
//
if(fITSOut)
delete fITSOut;
fITSOut=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetTRDIn(const AliExternalTrackParam ¶m) {
//
// backup TRD in track
//
if(fTRDIn)
delete fTRDIn;
fTRDIn=new AliExternalTrackParam(param);
}
void AliESDfriendTrack::SetITSIndices(Int_t* indices, Int_t n){
//
// setting fITSindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxITScluster && fnMaxITScluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxITScluster,n));
}
fnMaxITScluster = n;
AliDebug(2,Form("fnMaxITScluster = %d",fnMaxITScluster));
if (fITSindex == 0x0){
fITSindex = new Int_t[fnMaxITScluster];
}
for (Int_t i = 0; i < fnMaxITScluster; i++){
fITSindex[i] = indices[i];
}
}
void AliESDfriendTrack::SetTPCIndices(Int_t* indices, Int_t n){
//
// setting fTPCindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxTPCcluster && fnMaxTPCcluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxTPCcluster,n));
}
fnMaxTPCcluster = n;
AliDebug(2,Form("fnMaxTPCcluster = %d",fnMaxTPCcluster));
if (fTPCindex == 0x0){
fTPCindex = new Int_t[fnMaxTPCcluster];
}
memcpy(fTPCindex,indices,sizeof(Int_t)*fnMaxTPCcluster); //RS
//for (Int_t i = 0; i < fnMaxTPCcluster; i++){fTPCindex[i] = indices[i];}
}
void AliESDfriendTrack::SetTRDIndices(Int_t* indices, Int_t n){
//
// setting fTRDindex
// instantiating the pointer if still NULL
//
// TODO: what if the array was already set but
// the old fnMaxITScluster and n differ!?
if(fnMaxTRDcluster && fnMaxTRDcluster!=n){
AliError(Form("Array size does not fit %d/%d\n"
,fnMaxTRDcluster,n));
}
fnMaxTRDcluster = n;
AliDebug(2,Form("fnMaxTRDcluster = %d",fnMaxTRDcluster));
if (fTRDindex == 0x0){
fTRDindex = new Int_t[fnMaxTRDcluster];
}
memcpy(fTRDindex,indices,sizeof(Int_t)*fnMaxTRDcluster); //RS
//for (Int_t i = 0; i < fnMaxTRDcluster; i++){fTRDindex[i] = indices[i];}
}
<|endoftext|> |
<commit_before>#include <testlib/testlib_test.h>
// And explicitly does *not* #include <cmath>,
// since the standard std::pow() functions are wittingly not used.
// A recursive implementation for a^b with a and b both integer;
// this is a more accurate alternative for std::pow(double a,double b),
// certainly in those cases where b is relatively small.
// Negative exponents make of course no sense since the result must be int.
// Beware of overflow!
#if !(defined(__GNUC__) && defined(__OPTIMIZE__))
inline // breaks test "Power of 2 with overflow" with gcc -O3
#endif
static int int_pow(int a, unsigned int b)
{
if (b==0) return 1;
else if (b==1) return a;
else return int_pow(a*a,b/2) * int_pow(a, b%2);
}
// A recursive implementation for a^b with a double and b integer;
// this is a more accurate alternative for std::pow(double a,double b),
// certainly in those cases where b is relatively small.
inline static double int_pow(double a, int b)
{
if (b==0) return 1;
else if (b==1) return a;
else if (b<0) return int_pow(1.0/a, -b);
else return int_pow(a*a,b/2) * int_pow(a, b%2);
}
// An implementation for floor(log(a)/log(8)) with integer argument a;
// this is a more straightforward (and not too inefficient) alternative for
// std::floor(std::log(double a)/std::log(8.0)).
// Negative arguments make of course no sense; strictly speaking, also a=0
// makes no sense, but in that case a "very negative" value is returned.
inline static int log8(unsigned int a)
{
if (a==0) return -0x7fffffffL-1L; // stands for minus infinity
int r = 0;
while (a >= 8) ++r, a>>=3; // divide by 8
return r;
}
static void test_int_pow()
{
TEST("Exponent 0", int_pow(-33, 0U), 1);
TEST("Exponent 1", int_pow(-33, 1U), -33);
TEST("Exponent of 1", int_pow(1, 12345U), 1);
TEST("Even exponent of -1", int_pow(-1, 12346U), 1);
TEST("Odd exponent of -1", int_pow(-1, 12345U), -1);
TEST("Large power of 2", int_pow(2, 30U), 0x40000000);
TEST("Power of 2 with overflow", int_pow(2, 31U), (int)(-0x80000000L));
TEST("Power of 2 with even more overflow", int_pow(2, 32U), 0);
TEST("Just a \"random\" case...", int_pow(-19, 7U), -893871739);
}
static void test_dbl_pow()
{
TEST("Exponent 0", int_pow(-33.3, 0), 1.0);
TEST("Exponent 1", int_pow(-33.3, 1), -33.3);
TEST("Exponent -1", int_pow(0.4, -1), 2.5);
TEST("Even exponent of -1", int_pow(-1.0, 12346), 1.0);
TEST("Odd exponent of -1", int_pow(-1.0, 12345), -1.0);
TEST("Just a small \"random\" case...", int_pow(-23.0, 7), -3404825447.0);
// for small x: (1+x)^a = 1 + ax + a(a-1)/2 x^2 + ...
TEST_NEAR("And a larger example...", int_pow(1.00000001, 900), 1.000009000040455, 1e-13);
TEST_NEAR("And a large example...", int_pow(-10.0, 300), 1e300, 1e285);
TEST_NEAR("Negative exponent", int_pow(-10.0, -300), 1e-300, 1e-313);
}
static void test_log()
{
TEST("log(1)", log8(1), 0);
TEST("log(2)", log8(2), 0);
TEST("log(7)", log8(7), 0);
TEST("log(8)", log8(8), 1);
TEST("log(9)", log8(9), 1);
TEST("log(60)", log8(60), 1);
TEST("log(64)", log8(64), 2);
TEST("log(69)", log8(69), 2);
TEST("log(500)", log8(500), 2);
TEST("log(511)", log8(511), 2);
TEST("log(512)", log8(512), 3);
TEST("log(0x7fffffff)", log8(0x7fffffff), 10);
TEST("log(0)", log8(0) < -0x7fffffffL, true);
}
static void test_pow_log()
{
test_int_pow();
test_dbl_pow();
test_log();
}
TESTMAIN( test_pow_log );
<commit_msg>BUG: Increase tolerance for large double int_pow<commit_after>#include <testlib/testlib_test.h>
// And explicitly does *not* #include <cmath>,
// since the standard std::pow() functions are wittingly not used.
// A recursive implementation for a^b with a and b both integer;
// this is a more accurate alternative for std::pow(double a,double b),
// certainly in those cases where b is relatively small.
// Negative exponents make of course no sense since the result must be int.
// Beware of overflow!
#if !(defined(__GNUC__) && defined(__OPTIMIZE__))
inline // breaks test "Power of 2 with overflow" with gcc -O3
#endif
static int int_pow(int a, unsigned int b)
{
if (b==0) return 1;
else if (b==1) return a;
else return int_pow(a*a,b/2) * int_pow(a, b%2);
}
// A recursive implementation for a^b with a double and b integer;
// this is a more accurate alternative for std::pow(double a,double b),
// certainly in those cases where b is relatively small.
inline static double int_pow(double a, int b)
{
if (b==0) return 1;
else if (b==1) return a;
else if (b<0) return int_pow(1.0/a, -b);
else return int_pow(a*a,b/2) * int_pow(a, b%2);
}
// An implementation for floor(log(a)/log(8)) with integer argument a;
// this is a more straightforward (and not too inefficient) alternative for
// std::floor(std::log(double a)/std::log(8.0)).
// Negative arguments make of course no sense; strictly speaking, also a=0
// makes no sense, but in that case a "very negative" value is returned.
inline static int log8(unsigned int a)
{
if (a==0) return -0x7fffffffL-1L; // stands for minus infinity
int r = 0;
while (a >= 8) ++r, a>>=3; // divide by 8
return r;
}
static void test_int_pow()
{
TEST("Exponent 0", int_pow(-33, 0U), 1);
TEST("Exponent 1", int_pow(-33, 1U), -33);
TEST("Exponent of 1", int_pow(1, 12345U), 1);
TEST("Even exponent of -1", int_pow(-1, 12346U), 1);
TEST("Odd exponent of -1", int_pow(-1, 12345U), -1);
TEST("Large power of 2", int_pow(2, 30U), 0x40000000);
TEST("Power of 2 with overflow", int_pow(2, 31U), (int)(-0x80000000L));
TEST("Power of 2 with even more overflow", int_pow(2, 32U), 0);
TEST("Just a \"random\" case...", int_pow(-19, 7U), -893871739);
}
static void test_dbl_pow()
{
TEST("Exponent 0", int_pow(-33.3, 0), 1.0);
TEST("Exponent 1", int_pow(-33.3, 1), -33.3);
TEST("Exponent -1", int_pow(0.4, -1), 2.5);
TEST("Even exponent of -1", int_pow(-1.0, 12346), 1.0);
TEST("Odd exponent of -1", int_pow(-1.0, 12345), -1.0);
TEST("Just a small \"random\" case...", int_pow(-23.0, 7), -3404825447.0);
// for small x: (1+x)^a = 1 + ax + a(a-1)/2 x^2 + ...
// Note tolerance increased from 1e-13 to 1.075e-13 to meet olerance of the Fedora12-gcc4.4.4 optimized compilation.
// where the failing case was due to a difference of 1.05249e-13
TEST_NEAR("And a larger example...", int_pow(1.00000001, 900), 1.000009000040455, 1.075e-13);
TEST_NEAR("And a large example...", int_pow(-10.0, 300), 1e300, 1e285);
TEST_NEAR("Negative exponent", int_pow(-10.0, -300), 1e-300, 1e-313);
}
static void test_log()
{
TEST("log(1)", log8(1), 0);
TEST("log(2)", log8(2), 0);
TEST("log(7)", log8(7), 0);
TEST("log(8)", log8(8), 1);
TEST("log(9)", log8(9), 1);
TEST("log(60)", log8(60), 1);
TEST("log(64)", log8(64), 2);
TEST("log(69)", log8(69), 2);
TEST("log(500)", log8(500), 2);
TEST("log(511)", log8(511), 2);
TEST("log(512)", log8(512), 3);
TEST("log(0x7fffffff)", log8(0x7fffffff), 10);
TEST("log(0)", log8(0) < -0x7fffffffL, true);
}
static void test_pow_log()
{
test_int_pow();
test_dbl_pow();
test_log();
}
TESTMAIN( test_pow_log );
<|endoftext|> |
<commit_before>#include <Systems/FreeFlyCamera.hh>
#include <Components/CameraComponent.hpp>
#include <Core/Inputs/Input.hh>
#include <Context/IRenderContext.hh>
#include <Threads/ThreadManager.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#include <Components/FreeFlyComponent.hh>
namespace AGE
{
FreeFlyCamera::FreeFlyCamera(AScene *scene) :
System(std::move(scene)),
_cameras(std::move(scene))
{
_name = "Free fly camera";
}
bool FreeFlyCamera::initialize()
{
_cameras.requireComponent<CameraComponent>();
_cameras.requireComponent<FreeFlyComponent>();
return (true);
}
void FreeFlyCamera::updateBegin(float time)
{
}
void FreeFlyCamera::mainUpdate(float time)
{
const float verticalAngleLimit = glm::pi<float>();
size_t camIndex = 0;
if (_cameras.getCollection().size() < _cameraAngles.size())
_cameraAngles.resize(_cameras.getCollection().size());
for (auto cam : _cameras.getCollection())
{
auto &camLink = cam.getLink();
if (camIndex == _cameraAngles.size())
{
glm::quat camRotation = camLink.getOrientation();
_cameraAngles.emplace_back(glm::vec2(glm::eulerAngles(camRotation)));
}
_handleKeyboard(time, camLink, camIndex);
_handleMouse(time, camLink, camIndex);
_handleController(time, camLink, camIndex);
_cameraAngles[camIndex].x = glm::clamp(_cameraAngles[camIndex].x, -verticalAngleLimit, verticalAngleLimit);
glm::quat finalOrientation = glm::quat(glm::vec3(_cameraAngles[camIndex], 0));
camLink.setOrientation(finalOrientation);
++camIndex;
}
}
void FreeFlyCamera::updateEnd(float time)
{
}
void FreeFlyCamera::_handleKeyboard(float time, Link &camLink, size_t camIdx)
{
float camTranslationSpeed = 5.0f;
float maxAcceleration = 10.0f;
float camRotationSpeed = 2.0f;
Input *inputs = _scene->getInstance<Input>();
// If shift is pressed, we accelerate
if (inputs->getPhysicalKeyPressed(AGE_LSHIFT))
camTranslationSpeed += maxAcceleration;
// translations
if (inputs->getPhysicalKeyPressed(AGE_w))
camLink.setForward(glm::vec3(0, 0, -camTranslationSpeed * time));
if (inputs->getPhysicalKeyPressed(AGE_s))
camLink.setForward(glm::vec3(0, 0, camTranslationSpeed * time));
if (inputs->getPhysicalKeyPressed(AGE_a))
camLink.setForward(glm::vec3(-camTranslationSpeed * time, 0, 0));
if (inputs->getPhysicalKeyPressed(AGE_d))
camLink.setForward(glm::vec3(camTranslationSpeed * time, 0, 0));
// rotations
if (inputs->getPhysicalKeyPressed(AGE_UP))
_cameraAngles[camIdx].x += camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_DOWN))
_cameraAngles[camIdx].x -= camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_RIGHT))
_cameraAngles[camIdx].y -= camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_LEFT))
_cameraAngles[camIdx].y += camRotationSpeed * time;
}
void FreeFlyCamera::_handleMouse(float time, Link &camLink, size_t camIdx)
{
float camMouseRotationSpeed = 0.0005f;
Input *inputs = _scene->getInstance<Input>();
// On click, the context grab the mouse
if (inputs->getMouseButtonJustPressed(AGE_MOUSE_LEFT))
{
GetRenderThread()->getQueue()->emplaceTask<Tasks::Render::ContextGrabMouse>(true);
}
else if (inputs->getMouseButtonJustReleased(AGE_MOUSE_LEFT))
{
GetRenderThread()->getQueue()->emplaceTask<Tasks::Render::ContextGrabMouse>(false);
}
// If clicked, handle the rotation with the mouse
if (inputs->getMouseButtonPressed(AGE_MOUSE_LEFT))
{
_cameraAngles[camIdx].y -= (float)inputs->getMouseDelta().x * camMouseRotationSpeed;
_cameraAngles[camIdx].x -= (float)inputs->getMouseDelta().y * camMouseRotationSpeed;
}
}
void FreeFlyCamera::_handleController(float time, Link &camLink, size_t camIdx)
{
float camTranslationSpeed = 5.0f;
float maxAcceleration = 10.0f;
float camRotationSpeed = 2.0f;
Input *inputs = _scene->getInstance<Input>();
Joystick controller;
// Handle the Xbox controller
if (inputs->getJoystick(0, controller))
{
float rightTrigger = controller.getAxis(AGE_JOYSTICK_AXIS_TRIGGERRIGHT) * 0.5f + 0.5f;
// If right trigger pressed, accelerate
camTranslationSpeed += rightTrigger * maxAcceleration;
// Handle translations
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTY)) > 0.3)
camLink.setForward(glm::vec3(0.f, 0.f, controller.getAxis(AGE_JOYSTICK_AXIS_LEFTY) * camTranslationSpeed * time));
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTX)) > 0.3)
camLink.setForward(glm::vec3(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTX) * camTranslationSpeed * time, 0.f, 0.f));
// Handle rotations
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTX)) > 0.3)
_cameraAngles[camIdx].y -= controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTX) * camRotationSpeed * time;
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTY)) > 0.3)
_cameraAngles[camIdx].x -= controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTY) * camRotationSpeed * time;
}
}
}<commit_msg>flee fly mouse key modified<commit_after>#include <Systems/FreeFlyCamera.hh>
#include <Components/CameraComponent.hpp>
#include <Core/Inputs/Input.hh>
#include <Context/IRenderContext.hh>
#include <Threads/ThreadManager.hpp>
#include <Threads/Tasks/ToRenderTasks.hpp>
#include <Components/FreeFlyComponent.hh>
namespace AGE
{
FreeFlyCamera::FreeFlyCamera(AScene *scene) :
System(std::move(scene)),
_cameras(std::move(scene))
{
_name = "Free fly camera";
}
bool FreeFlyCamera::initialize()
{
_cameras.requireComponent<CameraComponent>();
_cameras.requireComponent<FreeFlyComponent>();
return (true);
}
void FreeFlyCamera::updateBegin(float time)
{
}
void FreeFlyCamera::mainUpdate(float time)
{
const float verticalAngleLimit = glm::pi<float>();
size_t camIndex = 0;
if (_cameras.getCollection().size() < _cameraAngles.size())
_cameraAngles.resize(_cameras.getCollection().size());
for (auto cam : _cameras.getCollection())
{
auto &camLink = cam.getLink();
if (camIndex == _cameraAngles.size())
{
glm::quat camRotation = camLink.getOrientation();
_cameraAngles.emplace_back(glm::vec2(glm::eulerAngles(camRotation)));
}
_handleKeyboard(time, camLink, camIndex);
_handleMouse(time, camLink, camIndex);
_handleController(time, camLink, camIndex);
_cameraAngles[camIndex].x = glm::clamp(_cameraAngles[camIndex].x, -verticalAngleLimit, verticalAngleLimit);
glm::quat finalOrientation = glm::quat(glm::vec3(_cameraAngles[camIndex], 0));
camLink.setOrientation(finalOrientation);
++camIndex;
}
}
void FreeFlyCamera::updateEnd(float time)
{
}
void FreeFlyCamera::_handleKeyboard(float time, Link &camLink, size_t camIdx)
{
float camTranslationSpeed = 5.0f;
float maxAcceleration = 10.0f;
float camRotationSpeed = 2.0f;
Input *inputs = _scene->getInstance<Input>();
// If shift is pressed, we accelerate
if (inputs->getPhysicalKeyPressed(AGE_LSHIFT))
camTranslationSpeed += maxAcceleration;
// translations
if (inputs->getPhysicalKeyPressed(AGE_w))
camLink.setForward(glm::vec3(0, 0, -camTranslationSpeed * time));
if (inputs->getPhysicalKeyPressed(AGE_s))
camLink.setForward(glm::vec3(0, 0, camTranslationSpeed * time));
if (inputs->getPhysicalKeyPressed(AGE_a))
camLink.setForward(glm::vec3(-camTranslationSpeed * time, 0, 0));
if (inputs->getPhysicalKeyPressed(AGE_d))
camLink.setForward(glm::vec3(camTranslationSpeed * time, 0, 0));
// rotations
if (inputs->getPhysicalKeyPressed(AGE_UP))
_cameraAngles[camIdx].x += camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_DOWN))
_cameraAngles[camIdx].x -= camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_RIGHT))
_cameraAngles[camIdx].y -= camRotationSpeed * time;
if (inputs->getPhysicalKeyPressed(AGE_LEFT))
_cameraAngles[camIdx].y += camRotationSpeed * time;
}
void FreeFlyCamera::_handleMouse(float time, Link &camLink, size_t camIdx)
{
float camMouseRotationSpeed = 0.0005f;
Input *inputs = _scene->getInstance<Input>();
// On click, the context grab the mouse
if (inputs->getMouseButtonJustPressed(AGE_MOUSE_RIGHT))
{
GetRenderThread()->getQueue()->emplaceTask<Tasks::Render::ContextGrabMouse>(true);
}
else if (inputs->getMouseButtonJustReleased(AGE_MOUSE_RIGHT))
{
GetRenderThread()->getQueue()->emplaceTask<Tasks::Render::ContextGrabMouse>(false);
}
// If clicked, handle the rotation with the mouse
if (inputs->getMouseButtonPressed(AGE_MOUSE_RIGHT))
{
_cameraAngles[camIdx].y -= (float)inputs->getMouseDelta().x * camMouseRotationSpeed;
_cameraAngles[camIdx].x -= (float)inputs->getMouseDelta().y * camMouseRotationSpeed;
}
}
void FreeFlyCamera::_handleController(float time, Link &camLink, size_t camIdx)
{
float camTranslationSpeed = 5.0f;
float maxAcceleration = 10.0f;
float camRotationSpeed = 2.0f;
Input *inputs = _scene->getInstance<Input>();
Joystick controller;
// Handle the Xbox controller
if (inputs->getJoystick(0, controller))
{
float rightTrigger = controller.getAxis(AGE_JOYSTICK_AXIS_TRIGGERRIGHT) * 0.5f + 0.5f;
// If right trigger pressed, accelerate
camTranslationSpeed += rightTrigger * maxAcceleration;
// Handle translations
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTY)) > 0.3)
camLink.setForward(glm::vec3(0.f, 0.f, controller.getAxis(AGE_JOYSTICK_AXIS_LEFTY) * camTranslationSpeed * time));
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTX)) > 0.3)
camLink.setForward(glm::vec3(controller.getAxis(AGE_JOYSTICK_AXIS_LEFTX) * camTranslationSpeed * time, 0.f, 0.f));
// Handle rotations
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTX)) > 0.3)
_cameraAngles[camIdx].y -= controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTX) * camRotationSpeed * time;
if (glm::abs(controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTY)) > 0.3)
_cameraAngles[camIdx].x -= controller.getAxis(AGE_JOYSTICK_AXIS_RIGHTY) * camRotationSpeed * time;
}
}
}<|endoftext|> |
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "parse_tree/show_query.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace NLP {
namespace UnitTests {
TEST_CLASS(ShowQueryTests) {
TEST_METHOD(convertsToStream) {
std::wostringstream stream;
stream << DUMMY;
Assert::AreEqual(
std::wstring(L"Show tasks (criteria none, sort by "
L"Description ascending)"),
stream.str());
}
TEST_METHOD(convertsToString) {
Assert::AreEqual(
std::wstring(L"Show tasks (criteria none, sort by "
L"Description ascending)"),
boost::lexical_cast<std::wstring>(DUMMY));
}
TEST_METHOD(comparesEquality) {
SHOW_QUERY local = DUMMY;
Assert::AreEqual(DUMMY, local);
}
TEST_METHOD(comparesInequality) {
SHOW_QUERY local {
{},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING }
}
};
Assert::AreEqual(DUMMY, local);
local.order[0].field = TaskField::DEADLINE;
Assert::AreNotEqual(DUMMY, local);
local = DUMMY;
local.order.push_back(SHOW_QUERY::FIELD_ORDER {
TaskField::DESCRIPTION
});
Assert::AreNotEqual(DUMMY, local);
local = DUMMY;
local.predicates.emplace_back(SHOW_QUERY::FIELD_FILTER {
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::EQUAL,
Utils::make_option<std::wstring>(L"")
});
Assert::AreNotEqual(DUMMY, local);
}
private:
/// A dummy object.
static const SHOW_QUERY DUMMY;
};
const SHOW_QUERY ShowQueryTests::DUMMY {
{},
{ { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } }
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<commit_msg>Add tests to check for predicate equality.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "parse_tree/show_query.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace NLP {
namespace UnitTests {
TEST_CLASS(ShowQueryTests) {
TEST_METHOD(convertsToStream) {
std::wostringstream stream;
stream << DUMMY;
Assert::AreEqual(
std::wstring(L"Show tasks (criteria none, sort by "
L"Description ascending)"),
stream.str());
}
TEST_METHOD(convertsToString) {
Assert::AreEqual(
std::wstring(L"Show tasks (criteria none, sort by "
L"Description ascending)"),
boost::lexical_cast<std::wstring>(DUMMY));
}
TEST_METHOD(comparesEquality) {
SHOW_QUERY local = DUMMY;
Assert::AreEqual(DUMMY, local);
}
TEST_METHOD(comparesInequality) {
SHOW_QUERY local {
{},
{
{ TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING }
}
};
Assert::AreEqual(DUMMY, local);
local.order[0].field = TaskField::DEADLINE;
Assert::AreNotEqual(DUMMY, local);
local = DUMMY;
local.order.push_back(SHOW_QUERY::FIELD_ORDER {
TaskField::DESCRIPTION
});
Assert::AreNotEqual(DUMMY, local);
local = DUMMY;
local.predicates.emplace_back(SHOW_QUERY::FIELD_FILTER {
TaskField::DESCRIPTION,
SHOW_QUERY::Predicate::EQUAL,
Utils::make_option<std::wstring>(L"")
});
Assert::AreNotEqual(DUMMY, local);
SHOW_QUERY local2 = local;
local2.predicates.push_back(local2.predicates[0]);
Assert::AreNotEqual(local, local2);
local2 = local;
local2.predicates[0].field = TaskField::PRIORITY;
Assert::AreNotEqual(local, local2);
local2 = local;
local2.predicates[0].predicate = SHOW_QUERY::Predicate::GREATER_THAN;
Assert::AreNotEqual(local, local2);
local2 = local;
local2.predicates[0].value = std::wstring(L"not empty");
Assert::AreNotEqual(local, local2);
}
private:
/// A dummy object.
static const SHOW_QUERY DUMMY;
};
const SHOW_QUERY ShowQueryTests::DUMMY {
{},
{ { TaskField::DESCRIPTION, SHOW_QUERY::Order::ASCENDING } }
};
} // namespace UnitTests
} // namespace NLP
} // namespace You
<|endoftext|> |
<commit_before>#ifndef ITER_FILTER_FALSE_HPP_
#define ITER_FILTER_FALSE_HPP_
#include "iterbase.hpp"
#include "filter.hpp"
#include <utility>
namespace iter {
namespace detail {
// Callable object that reverses the boolean result of another
// callable, taking the object in a Container's iterator
template <typename FilterFunc, typename Container>
class PredicateFlipper {
private:
FilterFunc filter_func;
public:
PredicateFlipper(FilterFunc filter_func) :
filter_func(filter_func)
{ }
PredicateFlipper() = delete;
PredicateFlipper(const PredicateFlipper&) = default;
// Calls the filter_func
bool operator() (const iterator_deref<Container> item) const {
return !bool(filter_func(item));
}
// with non-const incase FilterFunc::operator() is non-const
bool operator() (const iterator_deref<Container> item) {
return !bool(filter_func(item));
}
};
// Reverses the bool() conversion result of anything that supports a
// bool conversion
template <typename Container>
class BoolFlipper {
public:
bool operator() (const iterator_deref<Container> item) const {
return !bool(item);
}
};
}
// Creates a PredicateFlipper for the predicate function, which reverses
// the bool result of the function. The PredicateFlipper is then passed
// to the normal filter() function
template <typename FilterFunc, typename Container>
auto filterfalse(FilterFunc filter_func, Container&& container) ->
decltype(filter(
detail::PredicateFlipper<FilterFunc, Container>(
filter_func),
std::forward<Container>(container))) {
return filter(
detail::PredicateFlipper<FilterFunc, Container>(filter_func),
std::forward<Container>(container));
}
// Single argument version, uses a BoolFlipper to reverse the truthiness
// of an object
template <typename Container>
auto filterfalse(Container&& container) ->
decltype(filter(
detail::BoolFlipper<Container>(),
std::forward<Container>(container))) {
return filter(
detail::BoolFlipper<Container>(),
std::forward<Container>(container));
}
//specializations for initializer_lists
template <typename FilterFunc, typename T>
auto filterfalse(FilterFunc filter_func, std::initializer_list<T> container) ->
decltype(filter(
detail::PredicateFlipper<FilterFunc, std::initializer_list<T>>(
filter_func),
std::move(container))) {
return filter(
detail::PredicateFlipper<FilterFunc, std::initializer_list<T>>(filter_func),
std::move(container));
}
// Single argument version, uses a BoolFlipper to reverse the truthiness
// of an object
template <typename T>
auto filterfalse(std::initializer_list<T> container) ->
decltype(filter(
detail::BoolFlipper<std::initializer_list<T>>(),
std::move(container))) {
return filter(
detail::BoolFlipper<std::initializer_list<T>>(),
std::move(container));
}
}
#endif
<commit_msg>eliminates shadow warnings from filterfalse<commit_after>#ifndef ITER_FILTER_FALSE_HPP_
#define ITER_FILTER_FALSE_HPP_
#include "iterbase.hpp"
#include "filter.hpp"
#include <utility>
namespace iter {
namespace detail {
// Callable object that reverses the boolean result of another
// callable, taking the object in a Container's iterator
template <typename FilterFunc, typename Container>
class PredicateFlipper {
private:
FilterFunc filter_func;
public:
PredicateFlipper(FilterFunc in_filter_func) :
filter_func(in_filter_func)
{ }
PredicateFlipper() = delete;
PredicateFlipper(const PredicateFlipper&) = default;
// Calls the filter_func
bool operator() (const iterator_deref<Container> item) const {
return !bool(filter_func(item));
}
// with non-const incase FilterFunc::operator() is non-const
bool operator() (const iterator_deref<Container> item) {
return !bool(filter_func(item));
}
};
// Reverses the bool() conversion result of anything that supports a
// bool conversion
template <typename Container>
class BoolFlipper {
public:
bool operator() (const iterator_deref<Container> item) const {
return !bool(item);
}
};
}
// Creates a PredicateFlipper for the predicate function, which reverses
// the bool result of the function. The PredicateFlipper is then passed
// to the normal filter() function
template <typename FilterFunc, typename Container>
auto filterfalse(FilterFunc filter_func, Container&& container) ->
decltype(filter(
detail::PredicateFlipper<FilterFunc, Container>(
filter_func),
std::forward<Container>(container))) {
return filter(
detail::PredicateFlipper<FilterFunc, Container>(filter_func),
std::forward<Container>(container));
}
// Single argument version, uses a BoolFlipper to reverse the truthiness
// of an object
template <typename Container>
auto filterfalse(Container&& container) ->
decltype(filter(
detail::BoolFlipper<Container>(),
std::forward<Container>(container))) {
return filter(
detail::BoolFlipper<Container>(),
std::forward<Container>(container));
}
//specializations for initializer_lists
template <typename FilterFunc, typename T>
auto filterfalse(FilterFunc filter_func, std::initializer_list<T> container) ->
decltype(filter(
detail::PredicateFlipper<FilterFunc, std::initializer_list<T>>(
filter_func),
std::move(container))) {
return filter(
detail::PredicateFlipper<FilterFunc, std::initializer_list<T>>(filter_func),
std::move(container));
}
// Single argument version, uses a BoolFlipper to reverse the truthiness
// of an object
template <typename T>
auto filterfalse(std::initializer_list<T> container) ->
decltype(filter(
detail::BoolFlipper<std::initializer_list<T>>(),
std::move(container))) {
return filter(
detail::BoolFlipper<std::initializer_list<T>>(),
std::move(container));
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_unicode.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-10-17 15:42:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_
#include <breakiteratorImpl.hxx>
#include <unicode/brkiter.h>
namespace com { namespace sun { namespace star { namespace i18n {
#define LOAD_CHARACTER_BREAKITERATOR 0
#define LOAD_WORD_BREAKITERATOR 1
#define LOAD_SENTENCE_BREAKITERATOR 2
#define LOAD_LINE_BREAKITERATOR 3
// ----------------------------------------------------
// class BreakIterator_Unicode
// ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
BreakIterator_Unicode();
~BreakIterator_Unicode();
virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException );
protected:
const sal_Char *cBreakIterator, *wordRule;
Boundary result; // for word break iterator
rtl::OUString aText;
com::sun::star::lang::Locale aLocale;
icu::BreakIterator *aBreakIterator;
sal_Int16 aBreakType, aWordType;
void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};
} } } }
#endif
<commit_msg>INTEGRATION: CWS thaiissues (1.10.6); FILE MERGED 2005/10/26 20:41:53 khong 1.10.6.1: use icu thai linke break algorithm for thai breakiterator<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: breakiterator_unicode.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2005-11-16 10:17:20 $
*
* 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 _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_
#include <breakiteratorImpl.hxx>
#include <unicode/brkiter.h>
namespace com { namespace sun { namespace star { namespace i18n {
#define LOAD_CHARACTER_BREAKITERATOR 0
#define LOAD_WORD_BREAKITERATOR 1
#define LOAD_SENTENCE_BREAKITERATOR 2
#define LOAD_LINE_BREAKITERATOR 3
// ----------------------------------------------------
// class BreakIterator_Unicode
// ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
BreakIterator_Unicode();
~BreakIterator_Unicode();
virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
throw(com::sun::star::uno::RuntimeException);
//XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
throw( com::sun::star::uno::RuntimeException );
protected:
const sal_Char *cBreakIterator, *wordRule, *lineRule;
Boundary result; // for word break iterator
rtl::OUString aText;
com::sun::star::lang::Locale aLocale;
icu::BreakIterator *aBreakIterator;
sal_Int16 aBreakType, aWordType;
void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};
} } } }
#endif
<|endoftext|> |
<commit_before>/*
test_main.cpp
For graphicc, primarily testing drawing rectangles.
For animwin32, testing sizing a window, and drawing into
it over time.
The step() function basically draws a set of bars which are
proportional to the modulus of their time interval. So, a bar
that is supposed to take one second to go from zero to the top,
will grow from size zero, the height of window, within that second.
*/
#include "animwin32.h"
#include "linearalgebra.h"
#include <math.h>
static uint32_t colors[] = {
pBlack,
pRed,
pDarkGray,
pGreen,
pLightGray,
pBlue,
aliceblue,
pYellow,
pTurquoise,
pWhite,
};
static double intervals[] = {
// 1.0 / 0.125,
// 1.0 / 0.25,
// 1.0 / 0.333,
// 1.0 / 0.5,
1.0 / 0.75,
1.0 / 1.0,
1.0 / 1.25,
1.0 / 2.0,
1.0 / 3.0
};
static int numintervals = 0;
static int numcolors = 0;
static int bargap = 4;
static int numbars = 10;
static int barwidth = 0;
typedef struct {
uint32_t color;
double interval;
}bar;
bar *bars;
void drawPoints()
{
stroke(pBlack);
point(130, 20);
point(185, 20);
point(185, 75);
point(130, 75);
}
void drawLines()
{
line(30, 20, 85, 75);
line(30, 20, 85, 20);
stroke((uint8_t)126);
line(85, 20, 85, 75);
stroke((uint8_t)255);
line(85, 75, 30, 75);
}
void drawRects()
{
stroke(pBlack);
rectMode(CORNER);
fill((uint8_t)255);
rect(25, 25, 60, 60);
rectMode(CORNERS);
fill((uint8_t)100);
rect(25, 25, 50, 50);
rectMode(RADIUS);
fill((uint8_t)255);
rect(250, 50, 30, 30);
rectMode(CENTER);
fill((uint8_t)100);
rect(250, 50, 30, 30);
}
void drawRandomRectangles()
{
int lwidth = 32;
int lheight = 32;
rectMode(CORNER);
//noStroke();
stroke(pBlack);
for (int cnt = 1001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 202);
int x1 = rand() % (width - 1);
int y1 = rand() % (height - 1);
//noFill();
fill(c);
rect(x1, y1, lwidth, lheight);
}
}
void drawQuads()
{
stroke(pBlack);
fill(pWhite);
quad(38, 31, 86, 20, 69, 63, 30, 76);
}
void drawRandomLines()
{
for (int cnt = 1001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 255);
int x1 = rand() % width - 1;
int y1 = rand() % height - 1;
int x2 = rand() % width - 1;
int y2 = rand() % height - 1;
stroke(c);
line(x1, y1, x2, y2);
}
}
void drawEllipses()
{
stroke(pBlack);
ellipse(10, 10, 160, 120);
}
void drawTriangles()
{
stroke(pBlack);
fill((uint8_t)255);
//triangle(30, 75, 58, 20, 86, 75);
stroke(pBlack);
fill(pWhite);
triangle(38, 31, 86, 20, 30, 76);
}
void drawRandomTriangles()
{
//noStroke();
stroke(pBlack);
for (int cnt = 5001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 202);
int x1 = rand() % (width - 64)+20;
int y1 = rand() % (height - 64)+20;
int maxsize = 20;
int minx = x1 - maxsize;
int miny = y1 - maxsize;
int xrange = (x1 + maxsize) - (x1 - maxsize);
int yrange = (y1 + maxsize) - (y1 - maxsize);
int x2 = (rand() % xrange) + minx;
int y2 = (rand() % yrange) + miny;
int x3 = (rand() % xrange) + minx;
int y3 = (rand() % yrange) + miny;
//noFill();
fill(c);
triangle(x1, y1, x2, y2, x3, y3);
}
}
void drawBars()
{
rectMode(CORNER);
//nostroke();
stroke(pBlack);
for (int offset = 0; offset < numbars; offset++)
{
double secfrag = fmod(seconds(), bars[offset].interval);
int barheight = MAP(secfrag, 0, bars[offset].interval, 4, height - 1);
fill(bars[offset].color);
rect(offset*(bargap + barwidth) + bargap, height - barheight, barwidth, barheight);
}
}
void drawMouse()
{
int mWidth = 64;
int mHeight = 64;
rectMode(CENTER);
stroke(pBlack);
fill(RGBA(0, 127, 255, 200));
rect(mouseX, mouseY, mWidth, mHeight);
}
LRESULT CALLBACK myKbHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CHAR:
// Processing regular characters, after translation of various keycodes
//key = wParam;
switch (wParam){
case 0x1B: // ESC
quit();
break;
}
break;
}
return 0;
}
extern "C"
void setup()
{
size(1024, 768);
background(pLightGray);
// setup the array of color bars
numintervals = sizeof(intervals) / sizeof(intervals[0]);
numcolors = sizeof(colors) / sizeof(colors[0]);
int availwidth = width - (2 + numbars - 1)*bargap;
barwidth = availwidth / numbars;
// assign colors to bars
bars = new bar[numbars];
for (int idx = 0; idx < numbars; idx++)
{
bars[idx].color = colors[rand() % 10];
bars[idx].interval = intervals[rand() % numintervals];
}
setKeyboardHandler(myKbHandler);
}
extern "C"
void step(pb_rgba *pb)
{
//drawEllipses();
//drawLines();
//drawPoints();
//drawRects();
//drawTriangles();
//drawQuads();
//drawRandomRectangles();
//drawRandomLines();
drawRandomTriangles();
drawBars();
drawMouse();
}
<commit_msg>Changed red color bar to be semi-transparent<commit_after>/*
test_main.cpp
For graphicc, primarily testing drawing rectangles.
For animwin32, testing sizing a window, and drawing into
it over time.
The step() function basically draws a set of bars which are
proportional to the modulus of their time interval. So, a bar
that is supposed to take one second to go from zero to the top,
will grow from size zero, the height of window, within that second.
*/
#include "animwin32.h"
#include "linearalgebra.h"
#include <math.h>
static uint32_t colors[] = {
pBlack,
RGBA(255, 0, 0, 202), // Red
pDarkGray,
pGreen,
pLightGray,
pBlue,
aliceblue,
pYellow,
pTurquoise,
pWhite,
};
static double intervals[] = {
// 1.0 / 0.125,
// 1.0 / 0.25,
// 1.0 / 0.333,
// 1.0 / 0.5,
1.0 / 0.75,
1.0 / 1.0,
1.0 / 1.25,
1.0 / 2.0,
1.0 / 3.0
};
static int numintervals = 0;
static int numcolors = 0;
static int bargap = 4;
static int numbars = 20;
static int barwidth = 0;
typedef struct {
uint32_t color;
double interval;
}bar;
bar *bars;
void drawPoints()
{
stroke(pBlack);
point(130, 20);
point(185, 20);
point(185, 75);
point(130, 75);
}
void drawLines()
{
line(30, 20, 85, 75);
line(30, 20, 85, 20);
stroke((uint8_t)126);
line(85, 20, 85, 75);
stroke((uint8_t)255);
line(85, 75, 30, 75);
}
void drawRects()
{
stroke(pBlack);
rectMode(CORNER);
fill((uint8_t)255);
rect(25, 25, 60, 60);
rectMode(CORNERS);
fill((uint8_t)100);
rect(25, 25, 50, 50);
rectMode(RADIUS);
fill((uint8_t)255);
rect(250, 50, 30, 30);
rectMode(CENTER);
fill((uint8_t)100);
rect(250, 50, 30, 30);
}
void drawRandomRectangles()
{
int lwidth = 32;
int lheight = 32;
rectMode(CORNER);
//noStroke();
stroke(pBlack);
for (int cnt = 1001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 202);
int x1 = rand() % (width - 1);
int y1 = rand() % (height - 1);
//noFill();
fill(c);
rect(x1, y1, lwidth, lheight);
}
}
void drawQuads()
{
stroke(pBlack);
fill(pWhite);
quad(38, 31, 86, 20, 69, 63, 30, 76);
}
void drawRandomLines()
{
for (int cnt = 1001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 255);
int x1 = rand() % width - 1;
int y1 = rand() % height - 1;
int x2 = rand() % width - 1;
int y2 = rand() % height - 1;
stroke(c);
line(x1, y1, x2, y2);
}
}
void drawEllipses()
{
stroke(pBlack);
ellipse(10, 10, 160, 120);
}
void drawTriangles()
{
stroke(pBlack);
fill((uint8_t)255);
//triangle(30, 75, 58, 20, 86, 75);
stroke(pBlack);
fill(pWhite);
triangle(38, 31, 86, 20, 30, 76);
}
void drawRandomTriangles()
{
//noStroke();
stroke(pBlack);
for (int cnt = 10001; cnt; cnt--)
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t c = RGBA(r, g, b, 202);
int x1 = rand() % (width - 64)+20;
int y1 = rand() % (height - 64)+20;
int maxsize = 20;
int minx = x1 - maxsize;
int miny = y1 - maxsize;
int xrange = (x1 + maxsize) - (x1 - maxsize);
int yrange = (y1 + maxsize) - (y1 - maxsize);
int x2 = (rand() % xrange) + minx;
int y2 = (rand() % yrange) + miny;
int x3 = (rand() % xrange) + minx;
int y3 = (rand() % yrange) + miny;
//noFill();
fill(c);
triangle(x1, y1, x2, y2, x3, y3);
}
}
void drawBars()
{
rectMode(CORNER);
//nostroke();
stroke(pBlack);
for (int offset = 0; offset < numbars; offset++)
{
double secfrag = fmod(seconds(), bars[offset].interval);
int barheight = MAP(secfrag, 0, bars[offset].interval, 4, height - 1);
fill(bars[offset].color);
rect(offset*(bargap + barwidth) + bargap, height - barheight, barwidth, barheight);
}
}
void drawMouse()
{
int mWidth = 64;
int mHeight = 64;
rectMode(CENTER);
stroke(pBlack);
fill(RGBA(0, 127, 255, 200));
rect(mouseX, mouseY, mWidth, mHeight);
}
LRESULT CALLBACK myKbHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CHAR:
// Processing regular characters, after translation of various keycodes
//key = wParam;
switch (wParam){
case 0x1B: // ESC
quit();
break;
}
break;
}
return 0;
}
extern "C"
void setup()
{
size(1920, 1200);
background(pLightGray);
// setup the array of color bars
numintervals = sizeof(intervals) / sizeof(intervals[0]);
numcolors = sizeof(colors) / sizeof(colors[0]);
int availwidth = width - (2 + numbars - 1)*bargap;
barwidth = availwidth / numbars;
// assign colors to bars
bars = new bar[numbars];
for (int idx = 0; idx < numbars; idx++)
{
bars[idx].color = colors[rand() % 10];
bars[idx].interval = intervals[rand() % numintervals];
}
setKeyboardHandler(myKbHandler);
}
extern "C"
void step(pb_rgba *pb)
{
//drawEllipses();
//drawLines();
//drawPoints();
//drawRects();
//drawTriangles();
//drawQuads();
//drawRandomRectangles();
//drawRandomLines();
drawRandomTriangles();
drawBars();
drawMouse();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <list>
#include <cppunit/TestCase.h>
#include <cppunit/TestFixture.h>
#include <cppunit/ui/text/TextTestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <netinet/in.h>
#include "Calculator.hpp"
using namespace CppUnit;
using namespace std;
//-----------------------------------------------------------------------------
class TestCalculator : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestCalculator);
CPPUNIT_TEST(testSummation);
CPPUNIT_TEST(testDifference);
CPPUNIT_TEST(testMultiplication);
CPPUNIT_TEST(testDivision);
CPPUNIT_TEST_SUITE_END();
public:
void setUp(void);
void tearDown(void);
protected:
void testSummation(void);
void testDifference(void);
void testMultiplication(void);
void testDivision(void);
private:
Calculator *mTestObj;
};
//-----------------------------------------------------------------------------
void
TestCalculator::testSummation(void)
{
CPPUNIT_ASSERT(9 == mTestObj->Summation(6,3));
}
void
TestCalculator::testDifference(void)
{
CPPUNIT_ASSERT(3 == mTestObj->Difference(6,3));
}
void
TestCalculator::testMultiplication(void)
{
CPPUNIT_ASSERT(18 == mTestObj->Multiplication(6,3));
}
void
TestCalculator::testDivision(void)
{
CPPUNIT_ASSERT(2 == mTestObj->Division(6,3));
}
void
TestCalculator::setUp(void)
{
mTestObj = new Calculator();
}
void TestCalculator::tearDown(void)
{
delete mTestObj;
}
//-----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( TestCalculator );
int main(int argc, char* argv[])
{
// informs test-listener about testresults
CPPUNIT_NS::TestResult testresult;
// register listener for collecting the test-results
CPPUNIT_NS::TestResultCollector collectedresults;
testresult.addListener (&collectedresults);
// register listener for per-test progress output
CPPUNIT_NS::BriefTestProgressListener progress;
testresult.addListener (&progress);
// insert test-suite at test-runner by registry
CPPUNIT_NS::TestRunner testrunner;
testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());
testrunner.run(testresult);
// output results in compiler-format
CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);
compileroutputter.write ();
// Output XML for Jenkins CPPunit plugin
ofstream xmlFileOut("cppTestBasicMathResults.xml");
XmlOutputter xmlOut(&collectedresults, xmlFileOut);
xmlOut.write();
// return 0 if tests were successful
return collectedresults.wasSuccessful() ? 0 : 1;
}
<commit_msg>Create TestCalculator.cpp<commit_after>#include <iostream>
#include <string>
#include <list>
#include <cppunit/TestCase>
#include <cppunit/TestFixture.h>
#include <cppunit/ui/text/TextTestRunner.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <netinet/in.h>
#include "Calculator.hpp"
using namespace CppUnit;
using namespace std;
//-----------------------------------------------------------------------------
class TestCalculator : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestCalculator);
CPPUNIT_TEST(testSummation);
CPPUNIT_TEST(testDifference);
CPPUNIT_TEST(testMultiplication);
CPPUNIT_TEST(testDivision);
CPPUNIT_TEST_SUITE_END();
public:
void setUp(void);
void tearDown(void);
protected:
void testSummation(void);
void testDifference(void);
void testMultiplication(void);
void testDivision(void);
private:
Calculator *mTestObj;
};
//-----------------------------------------------------------------------------
void
TestCalculator::testSummation(void)
{
CPPUNIT_ASSERT(9 == mTestObj->Summation(6,3));
}
void
TestCalculator::testDifference(void)
{
CPPUNIT_ASSERT(3 == mTestObj->Difference(6,3));
}
void
TestCalculator::testMultiplication(void)
{
CPPUNIT_ASSERT(18 == mTestObj->Multiplication(6,3));
}
void
TestCalculator::testDivision(void)
{
CPPUNIT_ASSERT(2 == mTestObj->Division(6,3));
}
void
TestCalculator::setUp(void)
{
mTestObj = new Calculator();
}
void TestCalculator::tearDown(void)
{
delete mTestObj;
}
//-----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( TestCalculator );
int main(int argc, char* argv[])
{
// informs test-listener about testresults
CPPUNIT_NS::TestResult testresult;
// register listener for collecting the test-results
CPPUNIT_NS::TestResultCollector collectedresults;
testresult.addListener (&collectedresults);
// register listener for per-test progress output
CPPUNIT_NS::BriefTestProgressListener progress;
testresult.addListener (&progress);
// insert test-suite at test-runner by registry
CPPUNIT_NS::TestRunner testrunner;
testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());
testrunner.run(testresult);
// output results in compiler-format
CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);
compileroutputter.write ();
// Output XML for Jenkins CPPunit plugin
ofstream xmlFileOut("cppTestBasicMathResults.xml");
XmlOutputter xmlOut(&collectedresults, xmlFileOut);
xmlOut.write();
// return 0 if tests were successful
return collectedresults.wasSuccessful() ? 0 : 1;
}
<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/codec/webm_file_muxer.h"
#include "base/logging.h"
#include <cstdio>
#include <cstring>
#include <libwebm/webmids.hpp>
namespace base {
WebmFileMuxer::WebmFileMuxer() = default;
WebmFileMuxer::~WebmFileMuxer() = default;
bool WebmFileMuxer::init(FILE* file)
{
// Construct and Init |WebMChunkWriter|. It handles writes coming from libwebm.
writer_ = std::make_unique<mkvmuxer::MkvWriter>(file);
// Construct and init |ptr_segment_|, then enable live mode.
segment_ = std::make_unique<mkvmuxer::Segment>();
if (!segment_->Init(writer_.get()))
{
LOG(LS_ERROR) << "Cannot Init Segment";
return false;
}
segment_->set_mode(mkvmuxer::Segment::kFile);
// Set segment info fields.
mkvmuxer::SegmentInfo* const segment_info = segment_->GetSegmentInfo();
if (!segment_info)
{
LOG(LS_ERROR) << "Segment has no SegmentInfo";
return false;
}
// Set writing application name.
segment_info->set_writing_app("WebmFileMuxer");
initialized_ = true;
return true;
}
bool WebmFileMuxer::addAudioTrack(int sample_rate, int channels, std::string_view codec_id)
{
if (audio_track_num_ != 0)
{
LOG(LS_ERROR) << "Cannot add audio track: it already exists";
return false;
}
if (codec_id.empty())
{
LOG(LS_ERROR) << "Cannot AddAudioTrack with empty codec_id";
return false;
}
audio_track_num_ = segment_->AddAudioTrack(sample_rate, channels, 0);
if (!audio_track_num_)
{
LOG(LS_ERROR) << "Cannot AddAudioTrack on segment";
return false;
}
mkvmuxer::AudioTrack* const audio_track = static_cast<mkvmuxer::AudioTrack*>(
segment_->GetTrackByNumber(audio_track_num_));
if (!audio_track)
{
LOG(LS_ERROR) << "Unable to set audio codec_id: Track look up failed";
return false;
}
audio_track->set_codec_id(codec_id.data());
return true;
}
bool WebmFileMuxer::addVideoTrack(int width, int height, std::string_view codec_id)
{
if (video_track_num_ != 0)
{
LOG(LS_ERROR) << "Cannot add video track: it already exists";
return false;
}
if (codec_id.empty())
{
LOG(LS_ERROR) << "Cannot AddVideoTrack with empty codec_id";
return false;
}
video_track_num_ = segment_->AddVideoTrack(width, height, 0);
if (!video_track_num_)
{
LOG(LS_ERROR) << "Cannot AddVideoTrack on segment";
return false;
}
mkvmuxer::VideoTrack* const video_track = static_cast<mkvmuxer::VideoTrack*>(
segment_->GetTrackByNumber(video_track_num_));
if (!video_track)
{
LOG(LS_ERROR) << "Unable to set video codec_id: Track look up failed";
return false;
}
video_track->set_codec_id(codec_id.data());
return true;
}
bool WebmFileMuxer::finalize()
{
if (!segment_->Finalize())
{
LOG(LS_ERROR) << "libwebm mkvmuxer Finalize failed";
return false;
}
return true;
}
bool WebmFileMuxer::writeAudioFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp)
{
if (audio_track_num_ == 0)
{
LOG(LS_ERROR) << "Cannot WriteAudioFrame without an audio track";
return false;
}
return writeFrame(frame, timestamp, audio_track_num_, false);
}
bool WebmFileMuxer::writeVideoFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp,
bool is_key)
{
if (video_track_num_ == 0)
{
LOG(LS_ERROR) << "Cannot WriteVideoFrame without a video track";
return false;
}
return writeFrame(frame, timestamp, video_track_num_, is_key);
}
bool WebmFileMuxer::writeFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp,
uint64_t track_num, bool is_key)
{
if (!segment_->AddFrame(reinterpret_cast<const uint8_t*>(frame.data()), frame.size(),
track_num, static_cast<uint64_t>(timestamp.count()), is_key))
{
LOG(LS_ERROR) << "AddFrame failed";
return false;
}
return true;
}
} // namespace base
<commit_msg>Added variable check.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/codec/webm_file_muxer.h"
#include "base/logging.h"
#include <cstdio>
#include <cstring>
#include <libwebm/webmids.hpp>
namespace base {
WebmFileMuxer::WebmFileMuxer() = default;
WebmFileMuxer::~WebmFileMuxer() = default;
bool WebmFileMuxer::init(FILE* file)
{
DCHECK(file);
// Construct and Init |WebMChunkWriter|. It handles writes coming from libwebm.
writer_ = std::make_unique<mkvmuxer::MkvWriter>(file);
// Construct and init |ptr_segment_|, then enable live mode.
segment_ = std::make_unique<mkvmuxer::Segment>();
if (!segment_->Init(writer_.get()))
{
LOG(LS_ERROR) << "Cannot Init Segment";
return false;
}
segment_->set_mode(mkvmuxer::Segment::kFile);
// Set segment info fields.
mkvmuxer::SegmentInfo* const segment_info = segment_->GetSegmentInfo();
if (!segment_info)
{
LOG(LS_ERROR) << "Segment has no SegmentInfo";
return false;
}
// Set writing application name.
segment_info->set_writing_app("WebmFileMuxer");
initialized_ = true;
return true;
}
bool WebmFileMuxer::addAudioTrack(int sample_rate, int channels, std::string_view codec_id)
{
if (audio_track_num_ != 0)
{
LOG(LS_ERROR) << "Cannot add audio track: it already exists";
return false;
}
if (codec_id.empty())
{
LOG(LS_ERROR) << "Cannot AddAudioTrack with empty codec_id";
return false;
}
audio_track_num_ = segment_->AddAudioTrack(sample_rate, channels, 0);
if (!audio_track_num_)
{
LOG(LS_ERROR) << "Cannot AddAudioTrack on segment";
return false;
}
mkvmuxer::AudioTrack* const audio_track = static_cast<mkvmuxer::AudioTrack*>(
segment_->GetTrackByNumber(audio_track_num_));
if (!audio_track)
{
LOG(LS_ERROR) << "Unable to set audio codec_id: Track look up failed";
return false;
}
audio_track->set_codec_id(codec_id.data());
return true;
}
bool WebmFileMuxer::addVideoTrack(int width, int height, std::string_view codec_id)
{
if (video_track_num_ != 0)
{
LOG(LS_ERROR) << "Cannot add video track: it already exists";
return false;
}
if (codec_id.empty())
{
LOG(LS_ERROR) << "Cannot AddVideoTrack with empty codec_id";
return false;
}
video_track_num_ = segment_->AddVideoTrack(width, height, 0);
if (!video_track_num_)
{
LOG(LS_ERROR) << "Cannot AddVideoTrack on segment";
return false;
}
mkvmuxer::VideoTrack* const video_track = static_cast<mkvmuxer::VideoTrack*>(
segment_->GetTrackByNumber(video_track_num_));
if (!video_track)
{
LOG(LS_ERROR) << "Unable to set video codec_id: Track look up failed";
return false;
}
video_track->set_codec_id(codec_id.data());
return true;
}
bool WebmFileMuxer::finalize()
{
if (!segment_->Finalize())
{
LOG(LS_ERROR) << "libwebm mkvmuxer Finalize failed";
return false;
}
return true;
}
bool WebmFileMuxer::writeAudioFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp)
{
if (audio_track_num_ == 0)
{
LOG(LS_ERROR) << "Cannot WriteAudioFrame without an audio track";
return false;
}
return writeFrame(frame, timestamp, audio_track_num_, false);
}
bool WebmFileMuxer::writeVideoFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp,
bool is_key)
{
if (video_track_num_ == 0)
{
LOG(LS_ERROR) << "Cannot WriteVideoFrame without a video track";
return false;
}
return writeFrame(frame, timestamp, video_track_num_, is_key);
}
bool WebmFileMuxer::writeFrame(std::string_view frame,
const std::chrono::nanoseconds& timestamp,
uint64_t track_num, bool is_key)
{
if (!segment_->AddFrame(reinterpret_cast<const uint8_t*>(frame.data()), frame.size(),
track_num, static_cast<uint64_t>(timestamp.count()), is_key))
{
LOG(LS_ERROR) << "AddFrame failed";
return false;
}
return true;
}
} // namespace base
<|endoftext|> |
<commit_before>
#include "ksp_plugin/interface.hpp"
#include "base/array.hpp"
#include "base/status.hpp"
#include "base/status_or.hpp"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "physics/apsides.hpp"
namespace principia {
namespace interface {
using base::Error;
using base::Status;
using base::StatusOr;
using base::UniqueBytes;
using geometry::AngularVelocity;
using ksp_plugin::FlightPlan;
using ksp_plugin::Navigation;
using ksp_plugin::Vessel;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::ComputeApsides;
using physics::DiscreteTrajectory;
using physics::RigidMotion;
using physics::RigidTransformation;
namespace {
char const* release_string(const std::string& s) {
UniqueBytes allocated_string(s.size() + 1);
std::memcpy(allocated_string.data.get(), s.data(), s.size() + 1);
return reinterpret_cast<char const*>(allocated_string.data.release());
}
int set_error(Status status, char const** error_message) {
*error_message = release_string(status.message());
return static_cast<int>(status.error());
}
} // namespace
int principia__ExternalFlowFreefall(
Plugin const* const plugin,
int const central_body_index,
QP const world_body_centred_initial_degrees_of_freedom,
double const t_initial,
double const t_final,
QP* const world_body_centred_final_degrees_of_freedom,
char const** const error_message) {
journal::Method<journal::ExternalFlowFreefall> m{
{plugin,
central_body_index,
world_body_centred_initial_degrees_of_freedom,
t_initial,
t_final},
{world_body_centred_final_degrees_of_freedom, error_message}};
if (plugin == nullptr) {
return m.Return(
set_error(Status(Error::INVALID_ARGUMENT, "|plugin| must not be null"),
error_message));
}
return set_error(Status(Error::UNIMPLEMENTED,
"|ExternalFlowFreefall| is not yet implemented"),
error_message);
}
int principia__ExternalGetNearestPlannedCoastDegreesOfFreedom(
Plugin const* const plugin,
int const central_body_index,
char const* const vessel_guid,
int manoeuvre_index,
XYZ world_body_centred_reference_position,
QP* world_body_centred_nearest_degrees_of_freedom,
char const** const error_message) {
journal::Method<journal::ExternalGetNearestPlannedCoastDegreesOfFreedom> m{
{plugin,
central_body_index,
vessel_guid,
manoeuvre_index,
world_body_centred_reference_position},
{world_body_centred_nearest_degrees_of_freedom, error_message}};
if (plugin == nullptr) {
return m.Return(
set_error(Status(Error::INVALID_ARGUMENT, "|plugin| must not be null"),
error_message));
}
if (manoeuvre_index < 0) {
return m.Return(set_error(Status(Error::INVALID_ARGUMENT,
"Invalid negative |manoeuvre_index|" +
std::to_string(manoeuvre_index)),
error_message));
}
if (!plugin->HasCelestial(central_body_index)) {
return m.Return(set_error(
Status(Error::NOT_FOUND,
"No celestial with index " + std::to_string(central_body_index)),
error_message));
}
if (!plugin->HasVessel(vessel_guid)) {
return m.Return(
set_error(Status(Error::NOT_FOUND,
"No vessel with GUID " + std::string(vessel_guid)),
error_message));
}
Vessel const& vessel = *plugin->GetVessel(vessel_guid);
if (!vessel.has_flight_plan()) {
return m.Return(set_error(
Status(Error::FAILED_PRECONDITION,
"Vessel " + vessel.ShortDebugString() + " has no flight plan"),
error_message));
}
FlightPlan const& flight_plan = vessel.flight_plan();
if (manoeuvre_index >= flight_plan.number_of_manuvres()) {
return m.Return(set_error(
Status(Error::OUT_OF_RANGE,
"|manoeuvre_index| " + std::to_string(manoeuvre_index) +
" out of range, vessel " + vessel.ShortDebugString() +
" has " + std::to_string(flight_plan.number_of_manuvres()) +
u8" planned manuvres"),
error_message));
}
// The index of the coast segment following the desired manuvre.
int const segment_index = manoeuvre_index * 2 + 3;
if (segment_index >= flight_plan.number_of_segments()) {
return m.Return(set_error(Status(Error::FAILED_PRECONDITION,
u8"A singularity occurs within manuvre " +
std::to_string(manoeuvre_index) +
" of " + vessel.ShortDebugString()),
error_message));
}
DiscreteTrajectory<Barycentric>::Iterator coast_begin;
DiscreteTrajectory<Barycentric>::Iterator coast_end;
flight_plan.GetSegment(segment_index, coast_begin, coast_end);
auto const body_centred_inertial =
plugin->NewBodyCentredNonRotatingNavigationFrame(central_body_index);
DiscreteTrajectory<Navigation> coast;
for (auto it = coast_begin; it != coast_end; ++it) {
coast.Append(it.time(),
body_centred_inertial->ToThisFrameAtTime(it.time())(
it.degrees_of_freedom()));
}
Instant const current_time = plugin->CurrentTime();
// The given |World| position and requested |World| degrees of freedom are
// body-centred inertial, so |body_centred_inertial| up to an orthogonal map
// to world coordinates. Do the conversion directly.
// NOTE(eggrobin): it is correct to use the orthogonal map at |current_time|,
// because |body_centred_inertial| does not rotate with respect to
// |Barycentric|, so the orthogonal map does not depend on time.
RigidMotion<Navigation, World> to_world_body_centred_inertial(
RigidTransformation<Navigation, World>(
Navigation::origin,
World::origin,
plugin->renderer().BarycentricToWorld(plugin->PlanetariumRotation()) *
body_centred_inertial->FromThisFrameAtTime(
current_time).orthogonal_map()),
AngularVelocity<Navigation>{},
Velocity<Navigation>{});
auto const from_world_body_centred_inertial =
to_world_body_centred_inertial.Inverse();
Position<Navigation> reference_position =
from_world_body_centred_inertial.rigid_transformation()(
FromXYZ<Position<World>>(world_body_centred_reference_position));
DiscreteTrajectory<Navigation> immobile_reference;
immobile_reference.Append(coast.Begin().time(),
{reference_position, Velocity<Navigation>{}});
if (coast.Begin() !=
coast.last()) {
immobile_reference.Append(coast.last().time(),
{reference_position, Velocity<Navigation>{}});
}
DiscreteTrajectory<Navigation> apoapsides;
DiscreteTrajectory<Navigation> periapsides;
ComputeApsides(/*reference=*/immobile_reference,
coast.Begin(),
coast.End(),
apoapsides,
periapsides);
if (periapsides.Empty()) {
bool const coasting_away =
(coast.Begin().degrees_of_freedom().position() -
reference_position).Norm() <
(coast.last().degrees_of_freedom().position() -
reference_position).Norm();
*world_body_centred_nearest_degrees_of_freedom =
ToQP(to_world_body_centred_inertial(
coasting_away ? coast.Begin().degrees_of_freedom()
: coast.last().degrees_of_freedom()));
}
*world_body_centred_nearest_degrees_of_freedom = ToQP(
to_world_body_centred_inertial(periapsides.Begin().degrees_of_freedom()));
return m.Return(set_error(Status::OK, error_message));
}
} // namespace interface
} // namespace principia
<commit_msg>not returning, so needs an else<commit_after>
#include "ksp_plugin/interface.hpp"
#include "base/array.hpp"
#include "base/status.hpp"
#include "base/status_or.hpp"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "physics/apsides.hpp"
namespace principia {
namespace interface {
using base::Error;
using base::Status;
using base::StatusOr;
using base::UniqueBytes;
using geometry::AngularVelocity;
using ksp_plugin::FlightPlan;
using ksp_plugin::Navigation;
using ksp_plugin::Vessel;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::ComputeApsides;
using physics::DiscreteTrajectory;
using physics::RigidMotion;
using physics::RigidTransformation;
namespace {
char const* release_string(const std::string& s) {
UniqueBytes allocated_string(s.size() + 1);
std::memcpy(allocated_string.data.get(), s.data(), s.size() + 1);
return reinterpret_cast<char const*>(allocated_string.data.release());
}
int set_error(Status status, char const** error_message) {
*error_message = release_string(status.message());
return static_cast<int>(status.error());
}
} // namespace
int principia__ExternalFlowFreefall(
Plugin const* const plugin,
int const central_body_index,
QP const world_body_centred_initial_degrees_of_freedom,
double const t_initial,
double const t_final,
QP* const world_body_centred_final_degrees_of_freedom,
char const** const error_message) {
journal::Method<journal::ExternalFlowFreefall> m{
{plugin,
central_body_index,
world_body_centred_initial_degrees_of_freedom,
t_initial,
t_final},
{world_body_centred_final_degrees_of_freedom, error_message}};
if (plugin == nullptr) {
return m.Return(
set_error(Status(Error::INVALID_ARGUMENT, "|plugin| must not be null"),
error_message));
}
return set_error(Status(Error::UNIMPLEMENTED,
"|ExternalFlowFreefall| is not yet implemented"),
error_message);
}
int principia__ExternalGetNearestPlannedCoastDegreesOfFreedom(
Plugin const* const plugin,
int const central_body_index,
char const* const vessel_guid,
int manoeuvre_index,
XYZ world_body_centred_reference_position,
QP* world_body_centred_nearest_degrees_of_freedom,
char const** const error_message) {
journal::Method<journal::ExternalGetNearestPlannedCoastDegreesOfFreedom> m{
{plugin,
central_body_index,
vessel_guid,
manoeuvre_index,
world_body_centred_reference_position},
{world_body_centred_nearest_degrees_of_freedom, error_message}};
if (plugin == nullptr) {
return m.Return(
set_error(Status(Error::INVALID_ARGUMENT, "|plugin| must not be null"),
error_message));
}
if (manoeuvre_index < 0) {
return m.Return(set_error(Status(Error::INVALID_ARGUMENT,
"Invalid negative |manoeuvre_index|" +
std::to_string(manoeuvre_index)),
error_message));
}
if (!plugin->HasCelestial(central_body_index)) {
return m.Return(set_error(
Status(Error::NOT_FOUND,
"No celestial with index " + std::to_string(central_body_index)),
error_message));
}
if (!plugin->HasVessel(vessel_guid)) {
return m.Return(
set_error(Status(Error::NOT_FOUND,
"No vessel with GUID " + std::string(vessel_guid)),
error_message));
}
Vessel const& vessel = *plugin->GetVessel(vessel_guid);
if (!vessel.has_flight_plan()) {
return m.Return(set_error(
Status(Error::FAILED_PRECONDITION,
"Vessel " + vessel.ShortDebugString() + " has no flight plan"),
error_message));
}
FlightPlan const& flight_plan = vessel.flight_plan();
if (manoeuvre_index >= flight_plan.number_of_manuvres()) {
return m.Return(set_error(
Status(Error::OUT_OF_RANGE,
"|manoeuvre_index| " + std::to_string(manoeuvre_index) +
" out of range, vessel " + vessel.ShortDebugString() +
" has " + std::to_string(flight_plan.number_of_manuvres()) +
u8" planned manuvres"),
error_message));
}
// The index of the coast segment following the desired manuvre.
int const segment_index = manoeuvre_index * 2 + 3;
if (segment_index >= flight_plan.number_of_segments()) {
return m.Return(set_error(Status(Error::FAILED_PRECONDITION,
u8"A singularity occurs within manuvre " +
std::to_string(manoeuvre_index) +
" of " + vessel.ShortDebugString()),
error_message));
}
DiscreteTrajectory<Barycentric>::Iterator coast_begin;
DiscreteTrajectory<Barycentric>::Iterator coast_end;
flight_plan.GetSegment(segment_index, coast_begin, coast_end);
auto const body_centred_inertial =
plugin->NewBodyCentredNonRotatingNavigationFrame(central_body_index);
DiscreteTrajectory<Navigation> coast;
for (auto it = coast_begin; it != coast_end; ++it) {
coast.Append(it.time(),
body_centred_inertial->ToThisFrameAtTime(it.time())(
it.degrees_of_freedom()));
}
Instant const current_time = plugin->CurrentTime();
// The given |World| position and requested |World| degrees of freedom are
// body-centred inertial, so |body_centred_inertial| up to an orthogonal map
// to world coordinates. Do the conversion directly.
// NOTE(eggrobin): it is correct to use the orthogonal map at |current_time|,
// because |body_centred_inertial| does not rotate with respect to
// |Barycentric|, so the orthogonal map does not depend on time.
RigidMotion<Navigation, World> to_world_body_centred_inertial(
RigidTransformation<Navigation, World>(
Navigation::origin,
World::origin,
plugin->renderer().BarycentricToWorld(plugin->PlanetariumRotation()) *
body_centred_inertial->FromThisFrameAtTime(
current_time).orthogonal_map()),
AngularVelocity<Navigation>{},
Velocity<Navigation>{});
auto const from_world_body_centred_inertial =
to_world_body_centred_inertial.Inverse();
Position<Navigation> reference_position =
from_world_body_centred_inertial.rigid_transformation()(
FromXYZ<Position<World>>(world_body_centred_reference_position));
DiscreteTrajectory<Navigation> immobile_reference;
immobile_reference.Append(coast.Begin().time(),
{reference_position, Velocity<Navigation>{}});
if (coast.Begin() !=
coast.last()) {
immobile_reference.Append(coast.last().time(),
{reference_position, Velocity<Navigation>{}});
}
DiscreteTrajectory<Navigation> apoapsides;
DiscreteTrajectory<Navigation> periapsides;
ComputeApsides(/*reference=*/immobile_reference,
coast.Begin(),
coast.End(),
apoapsides,
periapsides);
if (periapsides.Empty()) {
bool const coasting_away =
(coast.Begin().degrees_of_freedom().position() -
reference_position).Norm() <
(coast.last().degrees_of_freedom().position() -
reference_position).Norm();
*world_body_centred_nearest_degrees_of_freedom =
ToQP(to_world_body_centred_inertial(
coasting_away ? coast.Begin().degrees_of_freedom()
: coast.last().degrees_of_freedom()));
} else {
*world_body_centred_nearest_degrees_of_freedom =
ToQP(to_world_body_centred_inertial(
periapsides.Begin().degrees_of_freedom()));
}
return m.Return(set_error(Status::OK, error_message));
}
} // namespace interface
} // namespace principia
<|endoftext|> |
<commit_before>/*
Copyright: © 2018 SIL International.
Description: Internal keyboard class and adaptor class for the API.
Create Date: 2 Oct 2018
Authors: Tim Eves (TSE)
History: 2 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp
*/
#pragma once
#include <string>
#include <keyman/keyboardprocessor.h>
#include "kmx/kmx_processevent.h"
#include "keyboard.hpp"
#include "processor.hpp"
namespace km {
namespace kbp
{
class kmx_processor : public abstract_processor
{
private:
bool _valid;
kmx::KMX_ProcessEvent _kmx;
km_kbp_status
internal_process_queued_actions(
km_kbp_state *state
);
public:
kmx_processor(path);
km_kbp_status
process_event(
km_kbp_state *state,
km_kbp_virtual_key vk,
uint16_t modifier_state,
uint8_t is_key_down
) override;
km_kbp_attr const & attributes() const override;
km_kbp_status validate() const override;
char16_t const *
lookup_option(
km_kbp_option_scope,
std::u16string const & key
) const override;
option
update_option(
km_kbp_option_scope scope,
std::u16string const & key,
std::u16string const & value
) override;
km_kbp_status
process_queued_actions(
km_kbp_state *state
) override;
bool
kmx_processor::queue_action(
km_kbp_state * state,
km_kbp_action_item const* action_item
) override;
km_kbp_context_item * get_intermediate_context() override;
km_kbp_keyboard_key * get_key_list() const override;
km_kbp_keyboard_imx * get_imx_list() const override;
};
} // namespace kbp
} // namespace km
<commit_msg>feat(windows): remove extra qual from header<commit_after>/*
Copyright: © 2018 SIL International.
Description: Internal keyboard class and adaptor class for the API.
Create Date: 2 Oct 2018
Authors: Tim Eves (TSE)
History: 2 Oct 2018 - TSE - Refactored out of km_kbp_keyboard_api.cpp
*/
#pragma once
#include <string>
#include <keyman/keyboardprocessor.h>
#include "kmx/kmx_processevent.h"
#include "keyboard.hpp"
#include "processor.hpp"
namespace km {
namespace kbp
{
class kmx_processor : public abstract_processor
{
private:
bool _valid;
kmx::KMX_ProcessEvent _kmx;
km_kbp_status
internal_process_queued_actions(
km_kbp_state *state
);
public:
kmx_processor(path);
km_kbp_status
process_event(
km_kbp_state *state,
km_kbp_virtual_key vk,
uint16_t modifier_state,
uint8_t is_key_down
) override;
km_kbp_attr const & attributes() const override;
km_kbp_status validate() const override;
char16_t const *
lookup_option(
km_kbp_option_scope,
std::u16string const & key
) const override;
option
update_option(
km_kbp_option_scope scope,
std::u16string const & key,
std::u16string const & value
) override;
km_kbp_status
process_queued_actions(
km_kbp_state *state
) override;
bool
queue_action(
km_kbp_state * state,
km_kbp_action_item const* action_item
) override;
km_kbp_context_item * get_intermediate_context() override;
km_kbp_keyboard_key * get_key_list() const override;
km_kbp_keyboard_imx * get_imx_list() const override;
};
} // namespace kbp
} // namespace km
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_CONCURRENCY_PROMISE_HPP
#define CRUNCH_CONCURRENCY_PROMISE_HPP
#include "crunch/base/intrusive_ptr.hpp"
#include "crunch/concurrency/future.hpp"
#include <exception>
#include <utility>
namespace Crunch { namespace Concurrency {
template<typename T>
class Promise
{
public:
Promise()
: mData(new DataType())
{}
Promise(Promise&& rhs)
: mData(std::move(rhs))
{}
Promise& operator= (Promise&& rhs)
{
mData = std::move(rhs.mData);
return *this;
}
void SetValue(T const& value)
{
mData->Set(value);
}
void SetValue(T&& value)
{
mData->Set(value);
}
void SetException(std::exception_ptr const& exception)
{
mData->SetException(exception);
}
Future<T> GetFuture()
{
return Future<T>(mData);
}
private:
typedef Detail::FutureData<T> DataType;
typedef IntrusivePtr<DataType> DataPtr;
DataPtr mData;
};
template<>
class Promise<void>
{
};
template<typename T>
class Promise<T&>
{
};
}}
#endif
<commit_msg>Implemented Promise<void><commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_CONCURRENCY_PROMISE_HPP
#define CRUNCH_CONCURRENCY_PROMISE_HPP
#include "crunch/base/intrusive_ptr.hpp"
#include "crunch/base/noncopyable.hpp"
#include "crunch/concurrency/future.hpp"
#include <exception>
#include <utility>
namespace Crunch { namespace Concurrency {
template<typename T>
class Promise : NonCopyable
{
public:
Promise()
: mData(new DataType())
{}
Promise(Promise&& rhs)
: mData(std::move(rhs.mData))
{}
Promise& operator= (Promise&& rhs)
{
mData = std::move(rhs.mData);
return *this;
}
void SetValue(T const& value)
{
mData->Set(value);
}
void SetValue(T&& value)
{
mData->Set(value);
}
void SetException(std::exception_ptr const& exception)
{
mData->SetException(exception);
}
Future<T> GetFuture()
{
return Future<T>(mData);
}
private:
typedef Detail::FutureData<T> DataType;
typedef IntrusivePtr<DataType> DataPtr;
DataPtr mData;
};
template<>
class Promise<void>
{
public:
Promise()
: mData(new DataType())
{}
Promise(Promise&& rhs)
: mData(std::move(rhs.mData))
{}
Promise& operator= (Promise&& rhs)
{
mData = std::move(rhs.mData);
return *this;
}
void SetValue()
{
mData->Set();
}
void SetException(std::exception_ptr const& exception)
{
mData->SetException(exception);
}
Future<void> GetFuture()
{
return Future<void>(mData);
}
private:
typedef Detail::FutureData<void> DataType;
typedef IntrusivePtr<DataType> DataPtr;
DataPtr mData;
};
template<typename T>
class Promise<T&>
{
};
}}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvtables.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:19:13 $
*
* 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_vcl.hxx"
#include <vcl/salframe.hxx>
#include <vcl/salinst.hxx>
#include <vcl/salvd.hxx>
#include <vcl/salprn.hxx>
#include <vcl/saltimer.hxx>
#include <vcl/salsound.hxx>
#include <vcl/salogl.hxx>
#include <vcl/salimestatus.hxx>
#include <vcl/salsys.hxx>
#include <vcl/salbmp.hxx>
#include <vcl/salobj.hxx>
#include <vcl/salmenu.hxx>
#include <vcl/salctrlhandle.hxx>
// this file contains the virtual destructors of the sal interface
// compilers ususally put their vtables where the destructor is
SalFrame::~SalFrame()
{
}
SalInstance::~SalInstance()
{
}
SalSound::~SalSound()
{
}
SalTimer::~SalTimer()
{
}
SalOpenGL::~SalOpenGL()
{
}
SalBitmap::~SalBitmap()
{
}
SalI18NImeStatus::~SalI18NImeStatus()
{
}
SalSystem::~SalSystem()
{
}
SalPrinter::~SalPrinter()
{
}
BOOL SalPrinter::StartJob( const String*, const String&,
ImplJobSetup*, ImplQPrinter* )
{
return FALSE;
}
SalInfoPrinter::~SalInfoPrinter()
{
}
SalVirtualDevice::~SalVirtualDevice()
{
}
SalObject::~SalObject()
{
}
SalMenu::~SalMenu()
{
}
SalMenuItem::~SalMenuItem()
{
}
SalControlHandle::~SalControlHandle()
{
}
<commit_msg>INTEGRATION: CWS aquavcl05_DEV300 (1.9.90); FILE MERGED 2008/02/18 15:46:38 pl 1.9.90.2: #i86095# better optimization of invalidate rects 2008/02/14 21:31:53 pl 1.9.90.1: optimize flush operations for e.g. gradient<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvtables.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:06:48 $
*
* 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_vcl.hxx"
#include <vcl/salframe.hxx>
#include <vcl/salinst.hxx>
#include <vcl/salvd.hxx>
#include <vcl/salprn.hxx>
#include <vcl/saltimer.hxx>
#include <vcl/salsound.hxx>
#include <vcl/salogl.hxx>
#include <vcl/salimestatus.hxx>
#include <vcl/salsys.hxx>
#include <vcl/salbmp.hxx>
#include <vcl/salobj.hxx>
#include <vcl/salmenu.hxx>
#include <vcl/salctrlhandle.hxx>
// this file contains the virtual destructors of the sal interface
// compilers ususally put their vtables where the destructor is
SalFrame::~SalFrame()
{
}
// -----------------------------------------------------------------------
// default to full-frame flushes
// on ports where partial-flushes are much cheaper this method should be overridden
void SalFrame::Flush( const Rectangle& )
{
Flush();
}
// -----------------------------------------------------------------------
SalInstance::~SalInstance()
{
}
SalSound::~SalSound()
{
}
SalTimer::~SalTimer()
{
}
SalOpenGL::~SalOpenGL()
{
}
SalBitmap::~SalBitmap()
{
}
SalI18NImeStatus::~SalI18NImeStatus()
{
}
SalSystem::~SalSystem()
{
}
SalPrinter::~SalPrinter()
{
}
BOOL SalPrinter::StartJob( const String*, const String&,
ImplJobSetup*, ImplQPrinter* )
{
return FALSE;
}
SalInfoPrinter::~SalInfoPrinter()
{
}
SalVirtualDevice::~SalVirtualDevice()
{
}
SalObject::~SalObject()
{
}
SalMenu::~SalMenu()
{
}
SalMenuItem::~SalMenuItem()
{
}
SalControlHandle::~SalControlHandle()
{
}
<|endoftext|> |
<commit_before><commit_msg>Related: fdo#66817 pressing space on a DisclosureButton should toggle it<commit_after><|endoftext|> |
<commit_before><commit_msg>implement GtkAdjustment import + apply<commit_after><|endoftext|> |
<commit_before><commit_msg>strip customproperty from name of Mnemonic Widget target<commit_after><|endoftext|> |
<commit_before><commit_msg>Add flags for syst. studies. from track variations<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2012 Troels Blum <troels@blum.dk>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB 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.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <stdexcept>
#include "GenerateSourceCode.hpp"
void generateGIDSource(std::vector<cphvb_index> shape, std::ostream& source)
{
size_t ndim = shape.size();
assert(ndim > 0);
if (ndim > 2)
{
source << "\tconst size_t gidz = get_global_id(2);\n";
source << "\tif (gidz >= " << shape[ndim-3] << ")\n\t\treturn;\n";
}
if (ndim > 1)
{
source << "\tconst size_t gidy = get_global_id(1);\n";
source << "\tif (gidy >= " << shape[ndim-2] << ")\n\t\treturn;\n";
}
source << "\tconst size_t gidx = get_global_id(0);\n";
source << "\tif (gidx >= " << shape[ndim-1] << ")\n\t\treturn;\n";
}
void generateOffsetSource(const cphvb_array* operand, std::ostream& source)
{
cphvb_index ndim = operand->ndim;
assert(ndim > 0);
if (ndim > 2)
{
source << "gidz*" << operand->stride[ndim-3] << " + ";
}
if (ndim > 1)
{
source << "gidy*" << operand->stride[ndim-2] << " + ";
}
source << "gidx*" << operand->stride[ndim-1] << " + " << operand->start;
}
void generateInstructionSource(cphvb_opcode opcode,
OCLtype returnType,
std::vector<std::string>& parameters,
std::ostream& source)
{
assert(parameters.size() == (size_t)cphvb_operands(opcode));
switch(opcode)
{
case CPHVB_ADD:
source << "\t" << parameters[0] << " = " << parameters[1] << " + " << parameters[2] << ";\n";
break;
case CPHVB_SUBTRACT:
source << "\t" << parameters[0] << " = " << parameters[1] << " - " << parameters[2] << ";\n";
break;
case CPHVB_MULTIPLY:
source << "\t" << parameters[0] << " = " << parameters[1] << " * " << parameters[2] << ";\n";
break;
case CPHVB_DIVIDE:
source << "\t" << parameters[0] << " = " << parameters[1] << " / " << parameters[2] << ";\n";
break;
case CPHVB_NEGATIVE:
source << "\t" << parameters[0] << " = -" << parameters[1] << ";\n";
break;
case CPHVB_POWER:
source << "\t" << parameters[0] << " = pow(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_MOD:
if (isFloat(returnType))
source << "\t" << parameters[0] << " = fmod(" << parameters[1] << ", " << parameters[2] << ");\n";
else
source << "\t" << parameters[0] << " = " << parameters[1] << " % " << parameters[2] << ";\n";
break;
case CPHVB_ABSOLUTE:
if (isFloat(returnType))
source << "\t" << parameters[0] << " = fabs(" << parameters[1] << ");\n";
else
source << "\t" << parameters[0] << " = abs(" << parameters[1] << ");\n";
break;
case CPHVB_RINT:
source << "\t" << parameters[0] << " = rint(" << parameters[1] << ");\n";
break;
case CPHVB_SIGN:
source << "\t" << parameters[0] << " = " << parameters[1] << "<0?-1:1;\n";
break;
case CPHVB_EXP:
source << "\t" << parameters[0] << " = exp(" << parameters[1] << ");\n";
break;
case CPHVB_EXP2:
source << "\t" << parameters[0] << " = exp2(" << parameters[1] << ");\n";
break;
case CPHVB_LOG:
source << "\t" << parameters[0] << " = log(" << parameters[1] << ");\n";
break;
case CPHVB_LOG10:
source << "\t" << parameters[0] << " = log10(" << parameters[1] << ");\n";
break;
case CPHVB_EXPM1:
source << "\t" << parameters[0] << " = expm1(" << parameters[1] << ");\n";
break;
case CPHVB_LOG1P:
source << "\t" << parameters[0] << " = log1p(" << parameters[1] << ");\n";
break;
case CPHVB_SQRT:
source << "\t" << parameters[0] << " = sqrt(" << parameters[1] << ");\n";
break;
case CPHVB_SQUARE:
source << "\t" << parameters[0] << " = " << parameters[1] << " * " << parameters[1] << ";\n";
break;
case CPHVB_RECIPROCAL:
if (returnType == OCL_FLOAT16)
source << "\t" << parameters[0] << " = half_recip(" << parameters[1] << ");\n";
else
source << "\t" << parameters[0] << " = native_recip(" << parameters[1] << ");\n";
break;
case CPHVB_SIN:
source << "\t" << parameters[0] << " = sin(" << parameters[1] << ");\n";
break;
case CPHVB_COS:
source << "\t" << parameters[0] << " = cos(" << parameters[1] << ");\n";
break;
case CPHVB_TAN:
source << "\t" << parameters[0] << " = tan(" << parameters[1] << ");\n";
break;
case CPHVB_ARCSIN:
source << "\t" << parameters[0] << " = asin(" << parameters[1] << ");\n";
break;
case CPHVB_ARCCOS:
source << "\t" << parameters[0] << " = acos(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTAN:
source << "\t" << parameters[0] << " = atan(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTAN2:
source << "\t" << parameters[0] << " = atan2(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_HYPOT:
source << "\t" << parameters[0] << " = hypot(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_SINH:
source << "\t" << parameters[0] << " = sinh(" << parameters[1] << ");\n";
break;
case CPHVB_COSH:
source << "\t" << parameters[0] << " = cosh(" << parameters[1] << ");\n";
break;
case CPHVB_TANH:
source << "\t" << parameters[0] << " = tanh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCSINH:
source << "\t" << parameters[0] << " = asinh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCCOSH:
source << "\t" << parameters[0] << " = acosh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTANH:
source << "\t" << parameters[0] << " = atanh(" << parameters[1] << ");\n";
break;
case CPHVB_BITWISE_AND:
source << "\t" << parameters[0] << " = " << parameters[1] << " & " << parameters[2] << ";\n";
break;
case CPHVB_BITWISE_OR:
source << "\t" << parameters[0] << " = " << parameters[1] << " | " << parameters[2] << ";\n";
break;
case CPHVB_BITWISE_XOR:
source << "\t" << parameters[0] << " = " << parameters[1] << " ^ " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_NOT:
source << "\t" << parameters[0] << " = !" << parameters[1] << ";\n";
break;
case CPHVB_LOGICAL_AND:
source << "\t" << parameters[0] << " = " << parameters[1] << " && " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_OR:
source << "\t" << parameters[0] << " = " << parameters[1] << " || " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_XOR:
source << "\t" << parameters[0] << " = !" << parameters[1] << " != !" << parameters[2] << ";\n";
break;
case CPHVB_INVERT:
source << "\t" << parameters[0] << " = ~" << parameters[1] << ";\n";
break;
case CPHVB_LEFT_SHIFT:
source << "\t" << parameters[0] << " = " << parameters[1] << " << " << parameters[2] << ";\n";
break;
case CPHVB_RIGHT_SHIFT:
source << "\t" << parameters[0] << " = " << parameters[1] << " >> " << parameters[2] << ";\n";
break;
case CPHVB_GREATER:
source << "\t" << parameters[0] << " = " << parameters[1] << " > " << parameters[2] << ";\n";
break;
case CPHVB_GREATER_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " >= " << parameters[2] << ";\n";
break;
case CPHVB_LESS:
source << "\t" << parameters[0] << " = " << parameters[1] << " < " << parameters[2] << ";\n";
break;
case CPHVB_LESS_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " <= " << parameters[2] << ";\n";
break;
case CPHVB_NOT_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " != " << parameters[2] << ";\n";
break;
case CPHVB_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " == " << parameters[2] << ";\n";
break;
case CPHVB_MAXIMUM:
source << "\t" << parameters[0] << " = max(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_MINIMUM:
source << "\t" << parameters[0] << " = min(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_IDENTITY:
source << "\t" << parameters[0] << " = " << parameters[1] << ";\n";
break;
case CPHVB_SIGNBIT:
source << "\t" << parameters[0] << " = " << parameters[1] << " < 0;\n";
break;
case CPHVB_FLOOR:
source << "\t" << parameters[0] << " = floor(" << parameters[1] << ");\n";
break;
case CPHVB_CEIL:
source << "\t" << parameters[0] << " = ceil(" << parameters[1] << ");\n";
break;
case CPHVB_TRUNC:
source << "\t" << parameters[0] << " = trunc(" << parameters[1] << ");\n";
break;
case CPHVB_LOG2:
source << "\t" << parameters[0] << " = log2(" << parameters[1] << ");\n";
break;
default:
#ifdef DEBUG
std::cerr << "Instruction \"" << cphvb_opcode_text(opcode) << "\" not supported." << std::endl;
#endif
throw std::runtime_error("Instruction not supported.");
}
}
<commit_msg>Fixed pow(x,y) for integers<commit_after>/*
* Copyright 2012 Troels Blum <troels@blum.dk>
*
* This file is part of cphVB <http://code.google.com/p/cphvb/>.
*
* cphVB 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.
*
* cphVB 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 cphVB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <stdexcept>
#include "GenerateSourceCode.hpp"
void generateGIDSource(std::vector<cphvb_index> shape, std::ostream& source)
{
size_t ndim = shape.size();
assert(ndim > 0);
if (ndim > 2)
{
source << "\tconst size_t gidz = get_global_id(2);\n";
source << "\tif (gidz >= " << shape[ndim-3] << ")\n\t\treturn;\n";
}
if (ndim > 1)
{
source << "\tconst size_t gidy = get_global_id(1);\n";
source << "\tif (gidy >= " << shape[ndim-2] << ")\n\t\treturn;\n";
}
source << "\tconst size_t gidx = get_global_id(0);\n";
source << "\tif (gidx >= " << shape[ndim-1] << ")\n\t\treturn;\n";
}
void generateOffsetSource(const cphvb_array* operand, std::ostream& source)
{
cphvb_index ndim = operand->ndim;
assert(ndim > 0);
if (ndim > 2)
{
source << "gidz*" << operand->stride[ndim-3] << " + ";
}
if (ndim > 1)
{
source << "gidy*" << operand->stride[ndim-2] << " + ";
}
source << "gidx*" << operand->stride[ndim-1] << " + " << operand->start;
}
void generateInstructionSource(cphvb_opcode opcode,
OCLtype returnType,
std::vector<std::string>& parameters,
std::ostream& source)
{
assert(parameters.size() == (size_t)cphvb_operands(opcode));
switch(opcode)
{
case CPHVB_ADD:
source << "\t" << parameters[0] << " = " << parameters[1] << " + " << parameters[2] << ";\n";
break;
case CPHVB_SUBTRACT:
source << "\t" << parameters[0] << " = " << parameters[1] << " - " << parameters[2] << ";\n";
break;
case CPHVB_MULTIPLY:
source << "\t" << parameters[0] << " = " << parameters[1] << " * " << parameters[2] << ";\n";
break;
case CPHVB_DIVIDE:
source << "\t" << parameters[0] << " = " << parameters[1] << " / " << parameters[2] << ";\n";
break;
case CPHVB_NEGATIVE:
source << "\t" << parameters[0] << " = -" << parameters[1] << ";\n";
break;
case CPHVB_POWER:
if (isFloat(returnType))
source << "\t" << parameters[0] << " = pow(" << parameters[1] << ", " << parameters[2] << ");\n";
else
source << "\t" << parameters[0] << " = pow((float)" << parameters[1] << ", (float)" << parameters[2] << ");\n";
break;
case CPHVB_MOD:
if (isFloat(returnType))
source << "\t" << parameters[0] << " = fmod(" << parameters[1] << ", " << parameters[2] << ");\n";
else
source << "\t" << parameters[0] << " = " << parameters[1] << " % " << parameters[2] << ";\n";
break;
case CPHVB_ABSOLUTE:
if (isFloat(returnType))
source << "\t" << parameters[0] << " = fabs(" << parameters[1] << ");\n";
else
source << "\t" << parameters[0] << " = abs(" << parameters[1] << ");\n";
break;
case CPHVB_RINT:
source << "\t" << parameters[0] << " = rint(" << parameters[1] << ");\n";
break;
case CPHVB_SIGN:
source << "\t" << parameters[0] << " = " << parameters[1] << "<0?-1:1;\n";
break;
case CPHVB_EXP:
source << "\t" << parameters[0] << " = exp(" << parameters[1] << ");\n";
break;
case CPHVB_EXP2:
source << "\t" << parameters[0] << " = exp2(" << parameters[1] << ");\n";
break;
case CPHVB_LOG:
source << "\t" << parameters[0] << " = log(" << parameters[1] << ");\n";
break;
case CPHVB_LOG10:
source << "\t" << parameters[0] << " = log10(" << parameters[1] << ");\n";
break;
case CPHVB_EXPM1:
source << "\t" << parameters[0] << " = expm1(" << parameters[1] << ");\n";
break;
case CPHVB_LOG1P:
source << "\t" << parameters[0] << " = log1p(" << parameters[1] << ");\n";
break;
case CPHVB_SQRT:
source << "\t" << parameters[0] << " = sqrt(" << parameters[1] << ");\n";
break;
case CPHVB_SQUARE:
source << "\t" << parameters[0] << " = " << parameters[1] << " * " << parameters[1] << ";\n";
break;
case CPHVB_RECIPROCAL:
if (returnType == OCL_FLOAT16)
source << "\t" << parameters[0] << " = half_recip(" << parameters[1] << ");\n";
else
source << "\t" << parameters[0] << " = native_recip(" << parameters[1] << ");\n";
break;
case CPHVB_SIN:
source << "\t" << parameters[0] << " = sin(" << parameters[1] << ");\n";
break;
case CPHVB_COS:
source << "\t" << parameters[0] << " = cos(" << parameters[1] << ");\n";
break;
case CPHVB_TAN:
source << "\t" << parameters[0] << " = tan(" << parameters[1] << ");\n";
break;
case CPHVB_ARCSIN:
source << "\t" << parameters[0] << " = asin(" << parameters[1] << ");\n";
break;
case CPHVB_ARCCOS:
source << "\t" << parameters[0] << " = acos(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTAN:
source << "\t" << parameters[0] << " = atan(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTAN2:
source << "\t" << parameters[0] << " = atan2(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_HYPOT:
source << "\t" << parameters[0] << " = hypot(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_SINH:
source << "\t" << parameters[0] << " = sinh(" << parameters[1] << ");\n";
break;
case CPHVB_COSH:
source << "\t" << parameters[0] << " = cosh(" << parameters[1] << ");\n";
break;
case CPHVB_TANH:
source << "\t" << parameters[0] << " = tanh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCSINH:
source << "\t" << parameters[0] << " = asinh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCCOSH:
source << "\t" << parameters[0] << " = acosh(" << parameters[1] << ");\n";
break;
case CPHVB_ARCTANH:
source << "\t" << parameters[0] << " = atanh(" << parameters[1] << ");\n";
break;
case CPHVB_BITWISE_AND:
source << "\t" << parameters[0] << " = " << parameters[1] << " & " << parameters[2] << ";\n";
break;
case CPHVB_BITWISE_OR:
source << "\t" << parameters[0] << " = " << parameters[1] << " | " << parameters[2] << ";\n";
break;
case CPHVB_BITWISE_XOR:
source << "\t" << parameters[0] << " = " << parameters[1] << " ^ " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_NOT:
source << "\t" << parameters[0] << " = !" << parameters[1] << ";\n";
break;
case CPHVB_LOGICAL_AND:
source << "\t" << parameters[0] << " = " << parameters[1] << " && " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_OR:
source << "\t" << parameters[0] << " = " << parameters[1] << " || " << parameters[2] << ";\n";
break;
case CPHVB_LOGICAL_XOR:
source << "\t" << parameters[0] << " = !" << parameters[1] << " != !" << parameters[2] << ";\n";
break;
case CPHVB_INVERT:
source << "\t" << parameters[0] << " = ~" << parameters[1] << ";\n";
break;
case CPHVB_LEFT_SHIFT:
source << "\t" << parameters[0] << " = " << parameters[1] << " << " << parameters[2] << ";\n";
break;
case CPHVB_RIGHT_SHIFT:
source << "\t" << parameters[0] << " = " << parameters[1] << " >> " << parameters[2] << ";\n";
break;
case CPHVB_GREATER:
source << "\t" << parameters[0] << " = " << parameters[1] << " > " << parameters[2] << ";\n";
break;
case CPHVB_GREATER_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " >= " << parameters[2] << ";\n";
break;
case CPHVB_LESS:
source << "\t" << parameters[0] << " = " << parameters[1] << " < " << parameters[2] << ";\n";
break;
case CPHVB_LESS_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " <= " << parameters[2] << ";\n";
break;
case CPHVB_NOT_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " != " << parameters[2] << ";\n";
break;
case CPHVB_EQUAL:
source << "\t" << parameters[0] << " = " << parameters[1] << " == " << parameters[2] << ";\n";
break;
case CPHVB_MAXIMUM:
source << "\t" << parameters[0] << " = max(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_MINIMUM:
source << "\t" << parameters[0] << " = min(" << parameters[1] << ", " << parameters[2] << ");\n";
break;
case CPHVB_IDENTITY:
source << "\t" << parameters[0] << " = " << parameters[1] << ";\n";
break;
case CPHVB_SIGNBIT:
source << "\t" << parameters[0] << " = " << parameters[1] << " < 0;\n";
break;
case CPHVB_FLOOR:
source << "\t" << parameters[0] << " = floor(" << parameters[1] << ");\n";
break;
case CPHVB_CEIL:
source << "\t" << parameters[0] << " = ceil(" << parameters[1] << ");\n";
break;
case CPHVB_TRUNC:
source << "\t" << parameters[0] << " = trunc(" << parameters[1] << ");\n";
break;
case CPHVB_LOG2:
source << "\t" << parameters[0] << " = log2(" << parameters[1] << ");\n";
break;
default:
#ifdef DEBUG
std::cerr << "Instruction \"" << cphvb_opcode_text(opcode) << "\" not supported." << std::endl;
#endif
throw std::runtime_error("Instruction not supported.");
}
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <QmitkColoredNodeDescriptor.h>
#include <mitkNodePredicateDataType.h>
static QString ConvertRGBTripletToHexColorCode(float rgbTriplet[3])
{
return QString("#%1%2%3")
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[0] * 255))), 2, 16, QLatin1Char('0'))
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[1] * 255))), 2, 16, QLatin1Char('0'))
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[2] * 255))), 2, 16, QLatin1Char('0'));
}
struct QmitkColoredNodeDescriptor::Impl
{
void CreateCachedIcon(const QString &hexColorCode);
QHash<QString, QIcon> IconCache;
QString IconTemplate;
};
void QmitkColoredNodeDescriptor::Impl::CreateCachedIcon(const QString &hexColorCode)
{
auto icon = this->IconTemplate;
icon.replace(QStringLiteral("#00ff00"), hexColorCode, Qt::CaseInsensitive);
this->IconCache[hexColorCode] = QPixmap::fromImage(QImage::fromData(icon.toLatin1()));
}
QmitkColoredNodeDescriptor::QmitkColoredNodeDescriptor(const QString &className, const QString &pathToIcon, mitk::NodePredicateBase *predicate, QObject *parent)
: QmitkNodeDescriptor(className, QStringLiteral(""), predicate, parent),
m_Impl(new Impl)
{
QFile iconTemplateFile(pathToIcon);
if (iconTemplateFile.open(QIODevice::ReadOnly))
m_Impl->IconTemplate = iconTemplateFile.readAll();
}
QmitkColoredNodeDescriptor::~QmitkColoredNodeDescriptor()
{
delete m_Impl;
}
QIcon QmitkColoredNodeDescriptor::GetIcon(const mitk::DataNode *node) const
{
if (nullptr == node)
return QIcon();
float rgbTriplet[] = { 1.0f, 1.0f, 1.0f };
node->GetColor(rgbTriplet);
auto hexColorCode = ConvertRGBTripletToHexColorCode(rgbTriplet);
if (!m_Impl->IconCache.contains(hexColorCode))
m_Impl->CreateCachedIcon(hexColorCode);
return m_Impl->IconCache[hexColorCode];
}
<commit_msg>Add missing include directive<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include <QmitkColoredNodeDescriptor.h>
#include <mitkNodePredicateDataType.h>
#include <QFile>
static QString ConvertRGBTripletToHexColorCode(float rgbTriplet[3])
{
return QString("#%1%2%3")
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[0] * 255))), 2, 16, QLatin1Char('0'))
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[1] * 255))), 2, 16, QLatin1Char('0'))
.arg(std::max(0, std::min(255, static_cast<int>(rgbTriplet[2] * 255))), 2, 16, QLatin1Char('0'));
}
struct QmitkColoredNodeDescriptor::Impl
{
void CreateCachedIcon(const QString &hexColorCode);
QHash<QString, QIcon> IconCache;
QString IconTemplate;
};
void QmitkColoredNodeDescriptor::Impl::CreateCachedIcon(const QString &hexColorCode)
{
auto icon = this->IconTemplate;
icon.replace(QStringLiteral("#00ff00"), hexColorCode, Qt::CaseInsensitive);
this->IconCache[hexColorCode] = QPixmap::fromImage(QImage::fromData(icon.toLatin1()));
}
QmitkColoredNodeDescriptor::QmitkColoredNodeDescriptor(const QString &className, const QString &pathToIcon, mitk::NodePredicateBase *predicate, QObject *parent)
: QmitkNodeDescriptor(className, QStringLiteral(""), predicate, parent),
m_Impl(new Impl)
{
QFile iconTemplateFile(pathToIcon);
if (iconTemplateFile.open(QIODevice::ReadOnly))
m_Impl->IconTemplate = iconTemplateFile.readAll();
}
QmitkColoredNodeDescriptor::~QmitkColoredNodeDescriptor()
{
delete m_Impl;
}
QIcon QmitkColoredNodeDescriptor::GetIcon(const mitk::DataNode *node) const
{
if (nullptr == node)
return QIcon();
float rgbTriplet[] = { 1.0f, 1.0f, 1.0f };
node->GetColor(rgbTriplet);
auto hexColorCode = ConvertRGBTripletToHexColorCode(rgbTriplet);
if (!m_Impl->IconCache.contains(hexColorCode))
m_Impl->CreateCachedIcon(hexColorCode);
return m_Impl->IconCache[hexColorCode];
}
<|endoftext|> |
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 32
#define BUILD_NUMBER 0
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>Fast forward V8 to version 4.2<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 4
#define MINOR_VERSION 2
#define BUILD_NUMBER 0
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|> |
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 29
#define BUILD_NUMBER 21
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.22.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 29
#define BUILD_NUMBER 22
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <formatString.h>
TEST(TextTest, IndentationTest) {
ASSERT_TRUE(true);
}
<commit_msg>增加formatText 的测试<commit_after>#include <gtest/gtest.h>
#include <string>
#include <formatString.h>
void pushString(text::FormatString &formatString, const std::string &str) {
for (char c: str)
formatString.normalCharProcess(c);
}
void setLineFeed(text::FormatString &formatString, int count) {
for (int i = 0; i < count; i++)
formatString.lineFeedProcess();
}
void setBackSpace(text::FormatString &formatString, int count) {
for (int i = 0; i < count; i++)
formatString.backSpaceProcess();
}
TEST(FormatTextTest, NormalCharTest) {
text::FormatString formatString;
pushString(formatString, "Hello world!");
ASSERT_STREQ("Hello world!\n", formatString.toString().c_str());
}
TEST(FormatTextTest, lineFeedTest) {
text::FormatString formatString;
pushString(formatString, "(");
setLineFeed(formatString, 3);
pushString(formatString, ")");
ASSERT_STREQ(""
"(\n"
" \n"
" \n"
" )\n", formatString.toString().c_str());
}
TEST(FormatTextTest, backSpaceTest) {
text::FormatString formatString;
pushString(formatString, "(");
formatString.lineFeedProcess();
pushString(formatString, "bcd)");
formatString.backSpaceProcess();
formatString.backSpaceProcess();
formatString.lineFeedProcess();
formatString.normalCharProcess(')');
ASSERT_STREQ(""
"(\n"
" bc\n"
" )\n", formatString.toString().c_str());
}
TEST(FormatTextTest, multiBracketLineFeedTest) {
text::FormatString formatString;
pushString(formatString, "(((");
setLineFeed(formatString, 3);
pushString(formatString, ")");
formatString.lineFeedProcess();
pushString(formatString, ")");
formatString.lineFeedProcess();
pushString(formatString, ")");
ASSERT_STREQ(""
"(((\n"
" \n"
" \n"
" )\n"
" )\n"
" )\n", formatString.toString().c_str());
}
TEST(FormatTextTest, MultiBracketBackSpaceTest) {
text::FormatString formatString;
pushString(formatString, "(((");
setLineFeed(formatString, 3);
pushString(formatString, ")");
formatString.lineFeedProcess();
pushString(formatString, ")");
formatString.lineFeedProcess();
pushString(formatString, ")");
setBackSpace(formatString, 4);
pushString(formatString, ")");
formatString.lineFeedProcess();
pushString(formatString, ")");
ASSERT_STREQ(""
"(((\n"
" \n"
" \n"
" ))\n"
" )\n", formatString.toString().c_str());
}
<|endoftext|> |
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "exception.h"
#include "controller_context.h"
#include "mocks/task_list.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace Controller {
namespace UnitTests {
using You::Controller::ContextRequiredException;
TEST_CLASS(ControllerContextTests) {
public:
TEST_METHOD(defaultIsADefaultContext) {
Assert::IsTrue(Controller::Context::DEFAULT.isDefault());
}
TEST_METHOD(taskListIsNotADefaultContext) {
TaskList list;
Controller::Context controllerContext(list);
Assert::IsFalse(controllerContext.isDefault());
}
TEST_METHOD(throwsContextRequiredExceptionWhenDefaultIsUsed) {
Assert::ExpectException<ContextRequiredException>([]() {
Controller::Context::DEFAULT.at(0);
}, L"Default context throws exception when used.");
Assert::ExpectException<ContextRequiredException>([]() {
Controller::Context::DEFAULT[0];
}, L"Default context throws exception when used.");
}
TEST_METHOD(atThrowsOutOfRangeWhenUsedWithInvalidIndex) {
TaskList list;
Controller::Context controllerContext(list);
Assert::ExpectException<std::out_of_range>([&]() {
controllerContext.at(0);
}, L"at throws exception when used with invalid index.");
}
TEST_METHOD(atAndArrayAccessReturnsCorrectItem) {
Mocks::TaskList taskList;
Controller::Context context(taskList);
// TODO(lowjoel): Use AreEqual when there's an accessible ToString
Assert::IsTrue(taskList.front() == context[0]);
Assert::IsTrue(taskList.front() == context.at(0));
}
};
} // namespace UnitTests
} // namespace Controller
} // namespace You
<commit_msg>More binds.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "exception.h"
#include "controller_context.h"
#include "mocks/task_list.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace You {
namespace Controller {
namespace UnitTests {
using You::Controller::ContextRequiredException;
TEST_CLASS(ControllerContextTests) {
public:
TEST_METHOD(defaultIsADefaultContext) {
Assert::IsTrue(Controller::Context::DEFAULT.isDefault());
}
TEST_METHOD(taskListIsNotADefaultContext) {
TaskList list;
Controller::Context controllerContext(list);
Assert::IsFalse(controllerContext.isDefault());
}
TEST_METHOD(throwsContextRequiredExceptionWhenDefaultIsUsed) {
Assert::ExpectException<ContextRequiredException>(
std::bind(
&Controller::Context::at,
Controller::Context::DEFAULT,
0),
L"Default context throws exception when used.");
Assert::ExpectException<ContextRequiredException>(
std::bind(
&Controller::Context::operator[],
Controller::Context::DEFAULT,
0),
L"Default context throws exception when used.");
}
TEST_METHOD(atThrowsOutOfRangeWhenUsedWithInvalidIndex) {
TaskList list;
Controller::Context controllerContext(list);
Assert::ExpectException<std::out_of_range>(
std::bind(&Controller::Context::at, controllerContext, 0),
L"at throws exception when used with invalid index.");
}
TEST_METHOD(atAndArrayAccessReturnsCorrectItem) {
Mocks::TaskList taskList;
Controller::Context context(taskList);
// TODO(lowjoel): Use AreEqual when there's an accessible ToString
Assert::IsTrue(taskList.front() == context[0]);
Assert::IsTrue(taskList.front() == context.at(0));
}
};
} // namespace UnitTests
} // namespace Controller
} // namespace You
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright (c) 2014-2015 Kohei Yoshida
*
* 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 <cstring>
namespace mdds {
template<typename _ValueT>
sorted_string_map<_ValueT>::sorted_string_map(const entry* entries, size_type entry_size, value_type null_value) :
m_entries(entries),
m_null_value(null_value),
m_entry_size(entry_size),
m_entry_end(m_entries+m_entry_size) {}
template<typename _ValueT>
typename sorted_string_map<_ValueT>::value_type
sorted_string_map<_ValueT>::find(const char* input, size_type len) const
{
const entry* p = m_entries;
size_type pos = 0;
for (; p != m_entry_end; ++p)
{
const char* key = p->key;
size_type keylen = p->keylen;
for (; pos < len && pos < keylen; ++pos)
{
if (input[pos] != key[pos])
// Move to the next entry.
break;
}
if (pos == len && len == keylen)
{
// Potential match found! Parse the whole string to make sure
// it's really a match.
if (std::memcmp(input, key, len))
// Not a match.
return m_null_value;
return p->value;
}
}
return m_null_value;
}
template<typename _ValueT>
typename sorted_string_map<_ValueT>::size_type
sorted_string_map<_ValueT>::size() const
{
return m_entry_size;
}
}
<commit_msg>play with O(m*log n) algorithm for search<commit_after>/*************************************************************************
*
* Copyright (c) 2014-2015 Kohei Yoshida
*
* 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 <cstring>
#include <algorithm>
namespace mdds {
template<typename _ValueT>
sorted_string_map<_ValueT>::sorted_string_map(const entry* entries, size_type entry_size, value_type null_value) :
m_entries(entries),
m_null_value(null_value),
m_entry_size(entry_size),
m_entry_end(m_entries+m_entry_size) {}
template<typename _ValueT>
typename sorted_string_map<_ValueT>::value_type
sorted_string_map<_ValueT>::find(const char* input, size_type len) const
{
if (m_entry_size == 0)
return m_null_value;
entry ent;
ent.key = input;
ent.keylen = len;
auto comp = [](const entry& entry1, const entry* entry2)
{
if (entry1.keylen != entry2->keylen)
{
size_type keylen = std::min(entry1.keylen, entry2->keylen);
int ret = std::memcmp(entry1.key, entry2->key, keylen);
if (ret == 0)
return entry1.keylen < entry2->keylen;
return ret < 0;
}
else
{
return std::memcmp(entry1.key, entry2->key, entry1.keylen) < 0;
}
};
const entry* val = std::lower_bound(m_entries, m_entry_end, &ent, comp);
if (val == m_entry_end || val->keylen != len || std::memcmp(val->key, input, len))
return m_null_value;
return val->value;
}
template<typename _ValueT>
typename sorted_string_map<_ValueT>::size_type
sorted_string_map<_ValueT>::size() const
{
return m_entry_size;
}
}
<|endoftext|> |
<commit_before>/**********
* The MIT License (MIT)
*
* Copyright (c) 2014 Samuel Bear Powell
*
* 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.
\**********/
// H5TLTest.cpp : Defines the entry point for the console application.
//
#include "../H5TL/H5TL.hpp"
#include <vector>
#include <set>
#include <array>
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
//#include "blitz/Array.h"
template<typename T, size_t N>
ostream& operator<<(ostream& os, const array<T,N>& vec) {
os << "array{";
bool first = true;
for(auto t : vec) {
if(first) {os << t; first = false;}
else {os << ", " << t;}
}
os << "}" << endl;
return os;
}
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
os << "vector{";
bool first = true;
for(auto t : vec) {
if(first) {os << t; first = false;}
else {os << ", " << t;}
}
os << "}" << endl;
return os;
}
int main(int argc, char* argv[]) {
try {
H5TL::File f("test.h5",H5TL::File::TRUNCATE);
f.write("note","This file was created using H5TL");
vector<int> a(10,1);
partial_sum(a.begin(),a.end(),a.begin());
cout << "a: " << a;
f.write("data/a",a);
vector<float> b = f.read<vector<float>>("data/a");
cout << "b: " << b;
vector<double> c(10,1.1);
partial_sum(c.begin(),c.end(),c.begin());
cout << "c: " << c;
hsize_t dims[] = {10}, maxdims[] = {H5TL::DSpace::UNL};
H5TL::DSpace cs(dims,maxdims);
H5TL::Dataset cds = f.write("data/c",c,cs);
int x[] = {25,26,27};
cds.append(x);
c.resize(13);
cds.read(c);
cout << "c: " << c;
//vector<bool> doesn't work because the standard is weird
array<bool,10> d;
for(size_t i = 0; i < d.size(); ++i)
d[i] = (i % 2 == 0);
cout << boolalpha << "d: " << d;
f.write("d",d);
array<bool,10> e = f.read<array<bool,10>>("d");
cout << "e: " << e;
return 0;
} catch(H5TL::h5tl_error &e) {
cerr << e.what();
}
}
<commit_msg>Added dataset property list to example/test code<commit_after>/**********
* The MIT License (MIT)
*
* Copyright (c) 2014 Samuel Bear Powell
*
* 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.
\**********/
// H5TLTest.cpp : Defines the entry point for the console application.
//
#include "../H5TL/H5TL.hpp"
#include <vector>
#include <set>
#include <array>
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
//#include "blitz/Array.h"
template<typename T, size_t N>
ostream& operator<<(ostream& os, const array<T,N>& vec) {
os << "array{";
bool first = true;
for(auto t : vec) {
if(first) {os << t; first = false;}
else {os << ", " << t;}
}
os << "}" << endl;
return os;
}
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
os << "vector{";
bool first = true;
for(auto t : vec) {
if(first) {os << t; first = false;}
else {os << ", " << t;}
}
os << "}" << endl;
return os;
}
int main(int argc, char* argv[]) {
try {
H5TL::File f("test.h5",H5TL::File::TRUNCATE);
f.write("note","This file was created using H5TL");
vector<int> a(10,1);
partial_sum(a.begin(),a.end(),a.begin());
cout << "a: " << a;
f.write("data/a",a);
vector<float> b = f.read<vector<float>>("data/a");
cout << "b: " << b;
vector<double> c(10,1.1);
partial_sum(c.begin(),c.end(),c.begin());
cout << "c: " << c;
hsize_t dims[] = {10}, maxdims[] = {H5TL::DSpace::UNL};
H5TL::DSpace cs(dims,maxdims);
H5TL::DProps cp = H5TL::DProps().chunked().deflate(3).fill(1);
H5TL::Dataset cds = f.write("data/c",c,cs,cp);
int x[] = {25,26,27};
cds.append(x);
c.resize(13);
cds.read(c);
cout << "c: " << c;
//vector<bool> doesn't work because the standard is weird
array<bool,10> d;
for(size_t i = 0; i < d.size(); ++i)
d[i] = (i % 2 == 0);
cout << boolalpha << "d: " << d;
f.write("d",d);
array<bool,10> e = f.read<array<bool,10>>("d");
cout << "e: " << e;
return 0;
} catch(H5TL::h5tl_error &e) {
cerr << e.what();
}
}
<|endoftext|> |
<commit_before>/**
* @file neons.cpp
*
* @date Nov 20, 2012
* @author partio
*/
#include "neons.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
once_flag oflag;
neons::neons() : itsInit(false), itsNeonsDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("neons"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::neons::InitPool, this);
}
void neons::InitPool()
{
NFmiNeonsDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
char* base = getenv("MASALA_BASE");
if (string(base) == "/masala")
{
NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true);
NFmiNeonsDBPool::Instance()->Username("wetodb");
NFmiNeonsDBPool::Instance()->Password("3loHRgdio");
}
else
{
itsLogger->Warning("Program executed as uid 1459 ('weto') but MASALA_BASE not set");
}
}
}
vector<string> neons::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y%m%d%H%M%S");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string dset = gridgeoms[i][2];
/// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined
string parm_name = options.param.Name();
if (parm_name == "T-K" && no_vers == 2)
{
parm_name = "T-C";
}
string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server "
"FROM "+tablename+" "
"WHERE dset_id = "+dset+" "
"AND parm_name = upper('"+parm_name+"') "
"AND lvl_type = upper('"+level_name+"') "
"AND lvl1_lvl2 = " +levelvalue+" "
"AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" "
"ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2";
itsNeonsDB->Query(query);
vector<string> values = itsNeonsDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from neons geometry " + gridgeoms[i][0]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool neons::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to neons for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
/*
* pas_latitude and pas_longitude cannot be checked programmatically
* since f.ex. in the case for GFS in neons we have value 500 and
* by calculating we have value 498. But not check these columns should
* not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match
* (since pas_latitude and pas_longitude are derived from these anyway)
*/
query << "SELECT geom_name "
<< "FROM grid_reg_geom "
<< "WHERE row_cnt = " << g->Nj()
<< " AND col_cnt = " << g->Ni()
<< " AND lat_orig = " << (firstGridPoint.Y() * 1e3)
<< " AND long_orig = " << (firstGridPoint.X() * 1e3);
// << " AND pas_latitude = " << static_cast<long> (resultInfo.Dj() * 1e3)
// << " AND pas_longitude = " << static_cast<long> (resultInfo.Di() * 1e3);
itsNeonsDB->Query(query.str());
vector<string> row;
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from neons");
return false;
}
string geom_name = row[0];
query.str("");
query << "SELECT "
<< "nu.model_id AS process, "
<< "nu.ident_id AS centre, "
<< "m.model_name, "
<< "m.model_type, "
<< "type_smt "
<< "FROM "
<< "grid_num_model_grib nu, "
<< "grid_model m, "
<< "grid_model_name na, "
<< "fmi_producers f "
<< "WHERE f.producer_id = " << resultInfo.Producer().Id()
<< " AND m.model_type = f.ref_prod "
<< " AND nu.model_name = m.model_name "
<< " AND m.flag_mod = 0 "
<< " AND nu.model_name = na.model_name "
<< " AND m.model_name = na.model_name ";
itsNeonsDB->Query(query.str());
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Producer definition not found from neons (id: " + boost::lexical_cast<string> (resultInfo.Producer().Id()) + ")");
return false;
}
// string process = row[0];
//string centre = row[1];
//string model_name = row[2];
string model_type = row[3];
/*
query << "SELECT "
<< "m.model_name, "
<< "model_type, "
<< "type_smt "
<< "FROM grid_num_model_grib nu, "
<< "grid_model m, "
<< "grid_model_name na "
<< "WHERE nu.model_id = " << info.process
<< " AND nu.ident_id = " << info.centre
<< " AND m.flag_mod = 0 "
<< " AND nu.model_name = na.model_name "
<< " AND m.model_name = na.model_name";
*/
query.str("");
query << "SELECT "
<< "dset_id, "
<< "table_name, "
<< "rec_cnt_dset "
<< "FROM as_grid "
<< "WHERE "
<< "model_type = '" << model_type << "'"
<< " AND geom_name = '" << geom_name << "'"
<< " AND dset_name = 'AF'"
<< " AND base_date = '" << resultInfo.OriginDateTime().String("%Y%m%d%H%M") << "'";
itsNeonsDB->Query(query.str());
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from neons");
return false;
}
string table_name = row[1];
string dset_id = row[0];
string eps_specifier = "0";
query.str("");
query << "UPDATE as_grid "
<< "SET rec_cnt_dset = "
<< "rec_cnt_dset + 1, "
<< "date_maj_dset = sysdate "
<< "WHERE dset_id = " << dset_id;
try
{
itsNeonsDB->Execute(query.str());
}
catch (int e)
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsNeonsDB->Rollback();
return false;
}
query.str("");
string host = "undetermined host";
char* hostname = getenv("HOSTNAME");
if (hostname != NULL)
{
host = string(hostname);
}
/*
* We have our own error loggings for unique key violations
*/
itsNeonsDB->Verbose(false);
query << "INSERT INTO " << table_name
<< " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) "
<< "VALUES ("
<< dset_id << ", "
<< "'" << resultInfo.Param().Name() << "', "
<< "upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "'), "
<< resultInfo.Level().Value() << ", "
<< resultInfo.Time().Step() << ", "
<< "'" << eps_specifier << "', "
<< "'" << theFileName << "', "
<< "'" << host << "')";
try
{
itsNeonsDB->Execute(query.str());
itsNeonsDB->Commit();
}
catch (int e)
{
if (e == 1)
{
// unique key violation
try
{
/*
* Neons table definition has invalid primary key definition:
*
* file_location and file_server are a part of the primary key meaning that
* a table can have multiple versions of a single file from multiple servers.
* This is unfortunate and to bypass it we must first delete all versions
* of the file and then INSERT again.
*/
query.str("");
query << "DELETE FROM " << table_name << " WHERE "
<< "dset_id = " << dset_id
<< " AND parm_name = '" << resultInfo.Param().Name() << "'"
<< " AND lvl_type = upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "')"
<< " AND lvl1_lvl2 = " << resultInfo.Level().Value()
<< " AND fcst_per = " << resultInfo.Time().Step();
itsNeonsDB->Execute(query.str());
query.str("");
query << "INSERT INTO " << table_name
<< " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) "
<< "VALUES ("
<< dset_id << ", "
<< "'" << resultInfo.Param().Name() << "', "
<< "upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "'), "
<< resultInfo.Level().Value() << ", "
<< resultInfo.Time().Step() << ", "
<< "'" << eps_specifier << "', "
<< "'" << theFileName << "', "
<< "'" << host << "')";
itsNeonsDB->Execute(query.str());
itsNeonsDB->Commit();
}
catch (int e)
{
itsLogger->Fatal("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Fatal("Query: " + query.str());
itsNeonsDB->Rollback();
exit(1);
}
}
else
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsNeonsDB->Rollback();
return false;
}
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to neons");
return true;
}
string neons::GribParameterName(long fmiParameterId, long codeTableVersion, long timeRangeIndicator)
{
Init();
string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, codeTableVersion, codeTableVersion, timeRangeIndicator);
return paramName;
}
string neons::GribParameterName(long fmiParameterId, long category, long discipline, long producer)
{
Init();
string paramName = itsNeonsDB->GetGridParameterNameForGrib2(fmiParameterId, category, discipline, producer);
return paramName;
}
string neons::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<commit_msg>Fixing issues reported by gcc 4.8<commit_after>/**
* @file neons.cpp
*
* @date Nov 20, 2012
* @author partio
*/
#include "neons.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
once_flag oflag;
neons::neons() : itsInit(false), itsNeonsDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("neons"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::neons::InitPool, this);
}
void neons::InitPool()
{
NFmiNeonsDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
char* base = getenv("MASALA_BASE");
if (base && string(base) == "/masala")
{
NFmiNeonsDBPool::Instance()->ReadWriteTransaction(true);
NFmiNeonsDBPool::Instance()->Username("wetodb");
NFmiNeonsDBPool::Instance()->Password("3loHRgdio");
}
else
{
itsLogger->Warning("Program executed as uid 1459 ('weto') but MASALA_BASE not set");
}
}
}
vector<string> neons::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y%m%d%H%M%S");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsNeonsDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string dset = gridgeoms[i][2];
/// @todo GFS (or in fact codetable 2) has wrong temperature parameter defined
string parm_name = options.param.Name();
if (parm_name == "T-K" && no_vers == 2)
{
parm_name = "T-C";
}
string query = "SELECT parm_name, lvl_type, lvl1_lvl2, fcst_per, file_location, file_server "
"FROM "+tablename+" "
"WHERE dset_id = "+dset+" "
"AND parm_name = upper('"+parm_name+"') "
"AND lvl_type = upper('"+level_name+"') "
"AND lvl1_lvl2 = " +levelvalue+" "
"AND fcst_per = "+boost::lexical_cast<string> (options.time.Step())+" "
"ORDER BY dset_id, fcst_per, lvl_type, lvl1_lvl2";
itsNeonsDB->Query(query);
vector<string> values = itsNeonsDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from neons geometry " + gridgeoms[i][0]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool neons::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to neons for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
/*
* pas_latitude and pas_longitude cannot be checked programmatically
* since f.ex. in the case for GFS in neons we have value 500 and
* by calculating we have value 498. But not check these columns should
* not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match
* (since pas_latitude and pas_longitude are derived from these anyway)
*/
query << "SELECT geom_name "
<< "FROM grid_reg_geom "
<< "WHERE row_cnt = " << g->Nj()
<< " AND col_cnt = " << g->Ni()
<< " AND lat_orig = " << (firstGridPoint.Y() * 1e3)
<< " AND long_orig = " << (firstGridPoint.X() * 1e3);
// << " AND pas_latitude = " << static_cast<long> (resultInfo.Dj() * 1e3)
// << " AND pas_longitude = " << static_cast<long> (resultInfo.Di() * 1e3);
itsNeonsDB->Query(query.str());
vector<string> row;
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from neons");
return false;
}
string geom_name = row[0];
query.str("");
query << "SELECT "
<< "nu.model_id AS process, "
<< "nu.ident_id AS centre, "
<< "m.model_name, "
<< "m.model_type, "
<< "type_smt "
<< "FROM "
<< "grid_num_model_grib nu, "
<< "grid_model m, "
<< "grid_model_name na, "
<< "fmi_producers f "
<< "WHERE f.producer_id = " << resultInfo.Producer().Id()
<< " AND m.model_type = f.ref_prod "
<< " AND nu.model_name = m.model_name "
<< " AND m.flag_mod = 0 "
<< " AND nu.model_name = na.model_name "
<< " AND m.model_name = na.model_name ";
itsNeonsDB->Query(query.str());
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Producer definition not found from neons (id: " + boost::lexical_cast<string> (resultInfo.Producer().Id()) + ")");
return false;
}
// string process = row[0];
//string centre = row[1];
//string model_name = row[2];
string model_type = row[3];
/*
query << "SELECT "
<< "m.model_name, "
<< "model_type, "
<< "type_smt "
<< "FROM grid_num_model_grib nu, "
<< "grid_model m, "
<< "grid_model_name na "
<< "WHERE nu.model_id = " << info.process
<< " AND nu.ident_id = " << info.centre
<< " AND m.flag_mod = 0 "
<< " AND nu.model_name = na.model_name "
<< " AND m.model_name = na.model_name";
*/
query.str("");
query << "SELECT "
<< "dset_id, "
<< "table_name, "
<< "rec_cnt_dset "
<< "FROM as_grid "
<< "WHERE "
<< "model_type = '" << model_type << "'"
<< " AND geom_name = '" << geom_name << "'"
<< " AND dset_name = 'AF'"
<< " AND base_date = '" << resultInfo.OriginDateTime().String("%Y%m%d%H%M") << "'";
itsNeonsDB->Query(query.str());
row = itsNeonsDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from neons");
return false;
}
string table_name = row[1];
string dset_id = row[0];
string eps_specifier = "0";
query.str("");
query << "UPDATE as_grid "
<< "SET rec_cnt_dset = "
<< "rec_cnt_dset + 1, "
<< "date_maj_dset = sysdate "
<< "WHERE dset_id = " << dset_id;
try
{
itsNeonsDB->Execute(query.str());
}
catch (int e)
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsNeonsDB->Rollback();
return false;
}
query.str("");
string host = "undetermined host";
char* hostname = getenv("HOSTNAME");
if (hostname != NULL)
{
host = string(hostname);
}
/*
* We have our own error loggings for unique key violations
*/
itsNeonsDB->Verbose(false);
query << "INSERT INTO " << table_name
<< " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) "
<< "VALUES ("
<< dset_id << ", "
<< "'" << resultInfo.Param().Name() << "', "
<< "upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "'), "
<< resultInfo.Level().Value() << ", "
<< resultInfo.Time().Step() << ", "
<< "'" << eps_specifier << "', "
<< "'" << theFileName << "', "
<< "'" << host << "')";
try
{
itsNeonsDB->Execute(query.str());
itsNeonsDB->Commit();
}
catch (int e)
{
if (e == 1)
{
// unique key violation
try
{
/*
* Neons table definition has invalid primary key definition:
*
* file_location and file_server are a part of the primary key meaning that
* a table can have multiple versions of a single file from multiple servers.
* This is unfortunate and to bypass it we must first delete all versions
* of the file and then INSERT again.
*/
query.str("");
query << "DELETE FROM " << table_name << " WHERE "
<< "dset_id = " << dset_id
<< " AND parm_name = '" << resultInfo.Param().Name() << "'"
<< " AND lvl_type = upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "')"
<< " AND lvl1_lvl2 = " << resultInfo.Level().Value()
<< " AND fcst_per = " << resultInfo.Time().Step();
itsNeonsDB->Execute(query.str());
query.str("");
query << "INSERT INTO " << table_name
<< " (dset_id, parm_name, lvl_type, lvl1_lvl2, fcst_per, eps_specifier, file_location, file_server) "
<< "VALUES ("
<< dset_id << ", "
<< "'" << resultInfo.Param().Name() << "', "
<< "upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "'), "
<< resultInfo.Level().Value() << ", "
<< resultInfo.Time().Step() << ", "
<< "'" << eps_specifier << "', "
<< "'" << theFileName << "', "
<< "'" << host << "')";
itsNeonsDB->Execute(query.str());
itsNeonsDB->Commit();
}
catch (int e)
{
itsLogger->Fatal("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Fatal("Query: " + query.str());
itsNeonsDB->Rollback();
exit(1);
}
}
else
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsNeonsDB->Rollback();
return false;
}
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to neons");
return true;
}
string neons::GribParameterName(long fmiParameterId, long codeTableVersion, long timeRangeIndicator)
{
Init();
string paramName = itsNeonsDB->GetGridParameterName(fmiParameterId, codeTableVersion, codeTableVersion, timeRangeIndicator);
return paramName;
}
string neons::GribParameterName(long fmiParameterId, long category, long discipline, long producer)
{
Init();
string paramName = itsNeonsDB->GetGridParameterNameForGrib2(fmiParameterId, category, discipline, producer);
return paramName;
}
string neons::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<|endoftext|> |
<commit_before>/**
* @file radon.cpp
*
* @date Oct 28, 2012
* @author tack
*/
#include "radon.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
once_flag oflag;
radon::radon() : itsInit(false), itsRadonDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::radon::InitPool, this);
}
void radon::InitPool()
{
NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
char* base = getenv("MASALA_BASE");
if (string(base) == "/masala")
{
NFmiRadonDBPool::Instance()->Username("wetodb");
NFmiRadonDBPool::Instance()->Password("3loHRgdio");
}
else
{
itsLogger->Warning("Program executed as uid 1459 ('weto') but MASALA_BASE not set");
}
}
}
vector<string> radon::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y%m%d%H%M%S");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
// long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string parm_name = options.param.Name();
string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server "
"FROM "+tablename+"_v "
"WHERE analysis_time = "+analtime+" "
"AND param_name = "+parm_name+" "
"AND level_name = "+level_name+" "
"AND level_value = " +levelvalue+" "
"AND forecast_period = "+boost::lexical_cast<string> (options.time.Step())+" "
"ORDER BY forecast_period, level_id, level_value";
itsRadonDB->Query(query);
vector<string> values = itsRadonDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][0]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool radon::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to neons for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
/*
* pas_latitude and pas_longitude cannot be checked programmatically
* since f.ex. in the case for GFS in radon we have value 500 and
* by calculating we have value 498. But not check these columns should
* not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match
* (since pas_latitude and pas_longitude are derived from these anyway)
*/
query << "SELECT geom_id "
<< "FROM geom_v "
<< "WHERE nj = " << g->Nj()
<< " AND ni = " << g->Ni()
<< " AND first_lat = " << (firstGridPoint.Y() * 1e-2)
<< " AND first_lon = " << (firstGridPoint.X() * 1e-2);
itsRadonDB->Query(query.str());
vector<string> row;
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from radon");
return false;
}
string geom_id = row[0];
query.str("");
query << "SELECT "
<< "id, table_name "
<< "FROM as_grid "
<< "WHERE geometry_id = '" << geom_id << "'"
<< " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'"
<< " AND producer_id = " << resultInfo.Producer().Id();
itsRadonDB->Query(query.str());
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from radon");
return false;
}
string table_name = row[1];
string dset_id = row[0];
string eps_specifier = "0";
query.str("");
string host = "undetermined host";
char* hostname = getenv("HOSTNAME");
if (hostname != NULL)
{
host = string(hostname);
}
/*
* We have our own error loggings for unique key violations
*/
// itsRadonDB->Verbose(false);
query << "INSERT INTO data." << table_name
<< " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, file_location, file_server) "
<< "SELECT " << resultInfo.Producer().Id() << ", "
<< "'" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "', "
<< "'" << geom_id << "', "
<< "param.id, level.id, "
<< resultInfo.Level().Value() << ", "
<< "'" << boost::lexical_cast<string>(resultInfo.Time().Step()) << " hour', "
<< "1, "
<< "'" << theFileName << "', "
<< "'" << host << "' "
<< "FROM param, level "
<< "WHERE param.name = '" << resultInfo.Param().Name() << "' "
<< "AND level.name = upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "')";
try
{
itsRadonDB->Execute(query.str());
itsRadonDB->Commit();
}
catch (int e)
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsRadonDB->Rollback();
return false;
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to radon");
return true;
}
map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->ParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value);
return paramName;
}
map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->ParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value);
return paramName;
}
string radon::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<commit_msg>Fix format for analtime in Files function<commit_after>/**
* @file radon.cpp
*
* @date Oct 28, 2012
* @author tack
*/
#include "radon.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include <thread>
#include <sstream>
#include "util.h"
#include "unistd.h" // getuid())
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
const int MAX_WORKERS = 16;
once_flag oflag;
radon::radon() : itsInit(false), itsRadonDB()
{
itsLogger = unique_ptr<logger> (logger_factory::Instance()->GetLog("radon"));
// no lambda functions for gcc 4.4 :(
// call_once(oflag, [](){ NFmiNeonsDBPool::MaxWorkers(MAX_WORKERS); });
call_once(oflag, &himan::plugin::radon::InitPool, this);
}
void radon::InitPool()
{
NFmiRadonDBPool::Instance()->MaxWorkers(MAX_WORKERS);
uid_t uid = getuid();
if (uid == 1459) // weto
{
char* base = getenv("MASALA_BASE");
if (string(base) == "/masala")
{
NFmiRadonDBPool::Instance()->Username("wetodb");
NFmiRadonDBPool::Instance()->Password("3loHRgdio");
}
else
{
itsLogger->Warning("Program executed as uid 1459 ('weto') but MASALA_BASE not set");
}
}
}
vector<string> radon::Files(search_options& options)
{
Init();
vector<string> files;
string analtime = options.time.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00");
string levelvalue = boost::lexical_cast<string> (options.level.Value());
string ref_prod = options.prod.Name();
// long no_vers = options.prod.TableVersion();
string level_name = HPLevelTypeToString.at(options.level.Type());
vector<vector<string> > gridgeoms;
vector<string> sourceGeoms = options.configuration->SourceGeomNames();
if (sourceGeoms.empty())
{
// Get all geometries
gridgeoms = itsRadonDB->GetGridGeoms(ref_prod, analtime);
}
else
{
for (size_t i = 0; i < sourceGeoms.size(); i++)
{
vector<vector<string>> geoms = itsRadonDB->GetGridGeoms(ref_prod, analtime, sourceGeoms[i]);
gridgeoms.insert(gridgeoms.end(), geoms.begin(), geoms.end());
}
}
if (gridgeoms.empty())
{
itsLogger->Warning("No geometries found for producer " + ref_prod +
", analysistime " + analtime + ", source geom name(s) '" + util::Join(sourceGeoms, ",") +"', param " + options.param.Name());
return files;
}
for (size_t i = 0; i < gridgeoms.size(); i++)
{
string tablename = gridgeoms[i][1];
string parm_name = options.param.Name();
string query = "SELECT param_id, level_id, level_value, forecast_period, file_location, file_server "
"FROM "+tablename+"_v "
"WHERE analysis_time = "+analtime+" "
"AND param_name = "+parm_name+" "
"AND level_name = "+level_name+" "
"AND level_value = " +levelvalue+" "
"AND forecast_period = "+boost::lexical_cast<string> (options.time.Step())+" "
"ORDER BY forecast_period, level_id, level_value";
itsRadonDB->Query(query);
vector<string> values = itsRadonDB->FetchRow();
if (values.empty())
{
continue;
}
itsLogger->Trace("Found data for parameter " + parm_name + " from radon geometry " + gridgeoms[i][0]);
files.push_back(values[4]);
break; // discontinue loop on first positive match
}
return files;
}
bool radon::Save(const info& resultInfo, const string& theFileName)
{
Init();
stringstream query;
if (resultInfo.Grid()->Type() != kRegularGrid)
{
itsLogger->Error("Only grid data can be stored to neons for now");
return false;
}
const regular_grid* g = dynamic_cast<regular_grid*> (resultInfo.Grid());
/*
* 1. Get grid information
* 2. Get model information
* 3. Get data set information (ie model run)
* 4. Insert or update
*/
himan::point firstGridPoint = g->FirstGridPoint();
/*
* pas_latitude and pas_longitude cannot be checked programmatically
* since f.ex. in the case for GFS in radon we have value 500 and
* by calculating we have value 498. But not check these columns should
* not matter as long as row_cnt, col_cnt, lat_orig and lon_orig match
* (since pas_latitude and pas_longitude are derived from these anyway)
*/
query << "SELECT geom_id "
<< "FROM geom_v "
<< "WHERE nj = " << g->Nj()
<< " AND ni = " << g->Ni()
<< " AND first_lat = " << (firstGridPoint.Y() * 1e-2)
<< " AND first_lon = " << (firstGridPoint.X() * 1e-2);
itsRadonDB->Query(query.str());
vector<string> row;
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Grid geometry not found from radon");
return false;
}
string geom_id = row[0];
query.str("");
query << "SELECT "
<< "id, table_name "
<< "FROM as_grid "
<< "WHERE geometry_id = '" << geom_id << "'"
<< " AND analysis_time = '" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "'"
<< " AND producer_id = " << resultInfo.Producer().Id();
itsRadonDB->Query(query.str());
row = itsRadonDB->FetchRow();
if (row.empty())
{
itsLogger->Warning("Data set definition not found from radon");
return false;
}
string table_name = row[1];
string dset_id = row[0];
string eps_specifier = "0";
query.str("");
string host = "undetermined host";
char* hostname = getenv("HOSTNAME");
if (hostname != NULL)
{
host = string(hostname);
}
/*
* We have our own error loggings for unique key violations
*/
// itsRadonDB->Verbose(false);
query << "INSERT INTO data." << table_name
<< " (producer_id, analysis_time, geometry_id, param_id, level_id, level_value, forecast_period, forecast_type_id, file_location, file_server) "
<< "SELECT " << resultInfo.Producer().Id() << ", "
<< "'" << resultInfo.OriginDateTime().String("%Y-%m-%d %H:%M:%S+00") << "', "
<< "'" << geom_id << "', "
<< "param.id, level.id, "
<< resultInfo.Level().Value() << ", "
<< "'" << boost::lexical_cast<string>(resultInfo.Time().Step()) << " hour', "
<< "1, "
<< "'" << theFileName << "', "
<< "'" << host << "' "
<< "FROM param, level "
<< "WHERE param.name = '" << resultInfo.Param().Name() << "' "
<< "AND level.name = upper('" << HPLevelTypeToString.at(resultInfo.Level().Type()) << "')";
try
{
itsRadonDB->Execute(query.str());
itsRadonDB->Commit();
}
catch (int e)
{
itsLogger->Error("Error code: " + boost::lexical_cast<string> (e));
itsLogger->Error("Query: " + query.str());
itsRadonDB->Rollback();
return false;
}
itsLogger->Trace("Saved information on file '" + theFileName + "' to radon");
return true;
}
map<string,string> radon::Grib1ParameterName(long producer, long fmiParameterId, long codeTableVersion, long timeRangeIndicator, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->ParameterFromGrib1(producer, codeTableVersion, fmiParameterId, timeRangeIndicator, levelId, level_value);
return paramName;
}
map<string,string> radon::Grib2ParameterName(long fmiParameterId, long category, long discipline, long producer, long levelId, double level_value)
{
Init();
map<string,string> paramName = itsRadonDB->ParameterFromGrib2(producer, discipline, category, fmiParameterId, levelId, level_value);
return paramName;
}
string radon::ProducerMetaData(long producerId, const string& attribute) const
{
string ret;
if (attribute == "last hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "65";
break;
case 131:
case 240:
ret = "137";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else if (attribute == "first hybrid level number")
{
switch (producerId)
{
case 1:
case 199:
case 210:
case 230:
ret = "1";
break;
case 131:
case 240:
ret = "24";
break;
default:
throw runtime_error(ClassName() + ": Producer not supported");
break;
}
}
else
{
throw runtime_error(ClassName() + ": Attribute not recognized");
}
return ret;
// In the future maybe something like this:
//Init();
//string query = "SELECT value FROM producers_eav WHERE producer_id = " + boost::lexical_cast<string> (producerId) + " AND attribute = '" + attribute + "'";
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
using namespace v8;
using namespace node;
static Handle<Value> Waitpid(const Arguments& args) {
HandleScope scope;
int r, child, status;
if (args[0]->IsInt32()) {
child = args[0]->Int32Value();
do {
r = waitpid(child, &status, WNOHANG);
} while (r != -1);
Local<Object> result = Object::New();
if (WIFEXITED(status)) {
result->Set(String::New("exitCode"), Integer::New(WEXITSTATUS(status)));
result->Set(String::New("signalCode"), Null());
return scope.Close(result);
}
else if (WIFSIGNALED(status)) {
result->Set(String::New("exitCode"), Null());
result->Set(String::New("signalCode"), Integer::New(WTERMSIG(status)));
return scope.Close(result);
}
return scope.Close(Undefined());
}
else {
return ThrowException(Exception::Error(String::New("Not an integer.")));
}
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "waitpid", Waitpid);
}
NODE_MODULE(waitpid, init)
<commit_msg>Fix busy-looping<commit_after>#include <v8.h>
#include <node.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
using namespace v8;
using namespace node;
static Handle<Value> Waitpid(const Arguments& args) {
HandleScope scope;
int r, child, status;
if (args[0]->IsInt32()) {
child = args[0]->Int32Value();
do {
r = waitpid(child, &status, 0);
} while (r != -1);
Local<Object> result = Object::New();
if (WIFEXITED(status)) {
result->Set(String::New("exitCode"), Integer::New(WEXITSTATUS(status)));
result->Set(String::New("signalCode"), Null());
return scope.Close(result);
}
else if (WIFSIGNALED(status)) {
result->Set(String::New("exitCode"), Null());
result->Set(String::New("signalCode"), Integer::New(WTERMSIG(status)));
return scope.Close(result);
}
return scope.Close(Undefined());
}
else {
return ThrowException(Exception::Error(String::New("Not an integer.")));
}
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "waitpid", Waitpid);
}
NODE_MODULE(waitpid, init)
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "iconthemeconfig.h"
#include <qtxdg/xdgdesktopfile.h>
#include <qtxdg/xdgicon.h>
#include <razorqt/razorsettings.h>
#include <QtCore/QStringList>
#include <QtGui/QIcon>
#include <QtCore/QDebug>
IconThemeConfig::IconThemeConfig(RazorSettings* settings):
m_settings(settings)
{
setupUi(this);
initIconsThemes();
initControls();
connect(iconThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(iconThemeSelected(QTreeWidgetItem*,int)));
connect(RazorSettings::globalSettings(), SIGNAL(settigsChanged()),
this, SLOT(update()));
}
void IconThemeConfig::initIconsThemes()
{
QStringList processed;
QStringList baseDirs = QIcon::themeSearchPaths();
foreach (QString baseDirName, baseDirs)
{
QDir baseDir(baseDirName);
if (!baseDir.exists())
continue;
QFileInfoList dirs = baseDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name);
foreach (QFileInfo dir, dirs)
{
if (!processed.contains(dir.canonicalFilePath()))
{
processed << dir.canonicalFilePath();
IconThemeInfo theme(QDir(dir.canonicalFilePath()));
if (theme.isValid() && (!theme.isHidden()))
{
QTreeWidgetItem *item = new QTreeWidgetItem(iconThemeList);
item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
item->setData(0, Qt::UserRole, theme.name());
item->setIcon(0, theme.icon("document-open"));
item->setIcon(1, theme.icon("document-new"));
item->setIcon(2, theme.icon("edit-undo"));
item->setIcon(3, theme.icon("media-playback-start"));
item->setText(4, theme.comment().isEmpty() ? theme.text() : theme.text() + " ( " + theme.comment() + " )");
}
}
}
}
iconThemeList->setColumnCount(5);
for (int i=0; i<iconThemeList->header()->count()-1; ++i)
{
iconThemeList->resizeColumnToContents(i);
}
}
void IconThemeConfig::initControls()
{
QString currentTheme = RazorSettings::globalSettings()->value("icon_theme").toString();
XdgIcon::setThemeName(currentTheme);
QTreeWidgetItemIterator it(iconThemeList);
while (*it) {
if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
{
iconThemeList->setCurrentItem((*it));
break;
}
++it;
}
update();
}
IconThemeConfig::~IconThemeConfig()
{
}
void IconThemeConfig::iconThemeSelected(QTreeWidgetItem *item, int column)
{
Q_UNUSED(column);
QString theme = item->data(0, Qt::UserRole).toString();
if (!theme.isEmpty())
{
XdgIcon::setThemeName(theme);
m_settings->setValue("icon_theme", theme);
m_settings->sync();
}
}
<commit_msg>Typos in code. Thanks Aaron Lewis. * In razor-runner , providers item: title() was typed as tile() * For RazorSettings class , settingsChanged() was typed as settigsChanged()<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Petr Vanek <petr@scribus.info>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "iconthemeconfig.h"
#include <qtxdg/xdgdesktopfile.h>
#include <qtxdg/xdgicon.h>
#include <razorqt/razorsettings.h>
#include <QtCore/QStringList>
#include <QtGui/QIcon>
#include <QtCore/QDebug>
IconThemeConfig::IconThemeConfig(RazorSettings* settings):
m_settings(settings)
{
setupUi(this);
initIconsThemes();
initControls();
connect(iconThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(iconThemeSelected(QTreeWidgetItem*,int)));
connect(RazorSettings::globalSettings(), SIGNAL(settingsChanged()),
this, SLOT(update()));
}
void IconThemeConfig::initIconsThemes()
{
QStringList processed;
QStringList baseDirs = QIcon::themeSearchPaths();
foreach (QString baseDirName, baseDirs)
{
QDir baseDir(baseDirName);
if (!baseDir.exists())
continue;
QFileInfoList dirs = baseDir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name);
foreach (QFileInfo dir, dirs)
{
if (!processed.contains(dir.canonicalFilePath()))
{
processed << dir.canonicalFilePath();
IconThemeInfo theme(QDir(dir.canonicalFilePath()));
if (theme.isValid() && (!theme.isHidden()))
{
QTreeWidgetItem *item = new QTreeWidgetItem(iconThemeList);
item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
item->setData(0, Qt::UserRole, theme.name());
item->setIcon(0, theme.icon("document-open"));
item->setIcon(1, theme.icon("document-new"));
item->setIcon(2, theme.icon("edit-undo"));
item->setIcon(3, theme.icon("media-playback-start"));
item->setText(4, theme.comment().isEmpty() ? theme.text() : theme.text() + " ( " + theme.comment() + " )");
}
}
}
}
iconThemeList->setColumnCount(5);
for (int i=0; i<iconThemeList->header()->count()-1; ++i)
{
iconThemeList->resizeColumnToContents(i);
}
}
void IconThemeConfig::initControls()
{
QString currentTheme = RazorSettings::globalSettings()->value("icon_theme").toString();
XdgIcon::setThemeName(currentTheme);
QTreeWidgetItemIterator it(iconThemeList);
while (*it) {
if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
{
iconThemeList->setCurrentItem((*it));
break;
}
++it;
}
update();
}
IconThemeConfig::~IconThemeConfig()
{
}
void IconThemeConfig::iconThemeSelected(QTreeWidgetItem *item, int column)
{
Q_UNUSED(column);
QString theme = item->data(0, Qt::UserRole).toString();
if (!theme.isEmpty())
{
XdgIcon::setThemeName(theme);
m_settings->setValue("icon_theme", theme);
m_settings->sync();
}
}
<|endoftext|> |
<commit_before>#ifndef TYPE_HXX_PHQ9E7V1
#define TYPE_HXX_PHQ9E7V1
#include "ptr.hxx"
#include "id.hxx"
#include "ppr.hxx"
namespace miniml
{
enum class TypeType
{
ID,
INT,
ARROW,
};
class Type: public Pretty
{
public:
virtual ~Type() {}
virtual TypeType type() const = 0;
virtual bool operator==(const Type &other) const = 0;
};
class IdType final: public Type
{
public:
IdType(const IdType &other) = default;
IdType(IdType &&other) = default;
IdType(Ptr<Id> id): m_id(id) {}
virtual TypeType type() const override { return TypeType::ID; }
virtual bool operator==(const Type &other) const override;
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override;
const Ptr<Id> id() const { return m_id; }
private:
Ptr<Id> m_id;
};
class IntType final: public Type
{
virtual TypeType type() const override { return TypeType::INT; }
virtual bool operator==(const Type &other) const override
{ return other.type() == type(); }
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override
{ return "int"_p; }
};
class ArrowType final: public Type
{
public:
ArrowType(const ArrowType &other) = default;
ArrowType(ArrowType &&other) = default;
ArrowType(Ptr<Type> left, Ptr<Type> right):
m_left(left), m_right(right)
{}
virtual TypeType type() const override { return TypeType::ARROW; }
virtual bool operator==(const Type &other) const override;
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override;
Ptr<Type> left() const { return m_left; }
Ptr<Type> right() const { return m_right; }
private:
Ptr<Type> m_left, m_right;
};
}
#endif /* end of include guard: TYPE_HXX_PHQ9E7V1 */
<commit_msg>TypeVisitor<commit_after>#ifndef TYPE_HXX_PHQ9E7V1
#define TYPE_HXX_PHQ9E7V1
#include "ptr.hxx"
#include "id.hxx"
#include "ppr.hxx"
#include "env.hxx"
#include "visitor.hxx"
namespace miniml
{
enum class TypeType
{
ID,
INT,
ARROW,
};
class Type: public Pretty
{
public:
virtual ~Type() {}
virtual TypeType type() const = 0;
virtual bool operator==(const Type &other) const = 0;
};
class IdType final: public Type
{
public:
IdType(const IdType &other) = default;
IdType(IdType &&other) = default;
IdType(Ptr<Id> id): m_id(id) {}
virtual TypeType type() const override { return TypeType::ID; }
virtual bool operator==(const Type &other) const override;
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override;
const Ptr<Id> id() const { return m_id; }
private:
Ptr<Id> m_id;
};
class IntType final: public Type
{
virtual TypeType type() const override { return TypeType::INT; }
virtual bool operator==(const Type &other) const override
{ return other.type() == type(); }
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override
{ return "int"_p; }
};
class ArrowType final: public Type
{
public:
ArrowType(const ArrowType &other) = default;
ArrowType(ArrowType &&other) = default;
ArrowType(Ptr<Type> left, Ptr<Type> right):
m_left(left), m_right(right)
{}
virtual TypeType type() const override { return TypeType::ARROW; }
virtual bool operator==(const Type &other) const override;
virtual Ptr<Ppr> ppr(unsigned prec = 0) const override;
Ptr<Type> left() const { return m_left; }
Ptr<Type> right() const { return m_right; }
private:
Ptr<Type> m_left, m_right;
};
template <typename T, typename... Args>
struct TypeVisitor
{
virtual Ptr<T> operator()(Ptr<Type>, Args...)
{ throw AbstractVisit("Type"); }
virtual Ptr<T> operator()(Ptr<IdType>, Args...) = 0;
virtual Ptr<T> operator()(Ptr<IntType>, Args...) = 0;
virtual Ptr<T> operator()(Ptr<ArrowType>, Args...) = 0;
};
}
#endif /* end of include guard: TYPE_HXX_PHQ9E7V1 */
<|endoftext|> |
<commit_before>#ifndef ITER_PERMUTATIONS_HPP_
#define ITER_PERMUTATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <algorithm>
#include <initializer_list>
#include <vector>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container>
class Permuter {
private:
Container container;
using IndexVector = std::vector<iterator_type<Container>>;
using Permutable = IterIterWrapper<IndexVector>;
public:
Permuter(Container&& in_container)
: container(std::forward<Container>(in_container)) {}
class Iterator : public std::iterator<std::input_iterator_tag, Permutable> {
private:
static constexpr const int COMPLETE = -1;
static bool cmp_iters(const iterator_type<Container>& lhs,
const iterator_type<Container>& rhs) noexcept {
return *lhs < *rhs;
}
Permutable working_set;
int steps{};
public:
Iterator(iterator_type<Container>&& sub_iter,
iterator_type<Container>&& sub_end)
: steps{sub_iter != sub_end ? 0 : COMPLETE} {
// done like this instead of using vector ctor with
// two iterators because that causes a substitution
// failure when the iterator is minimal
while (sub_iter != sub_end) {
this->working_set.get().push_back(sub_iter);
++sub_iter;
}
std::sort(std::begin(working_set.get()), std::end(working_set.get()),
cmp_iters);
}
Permutable& operator*() {
return this->working_set;
}
Permutable* operator->() {
return &this->working_set;
}
Iterator& operator++() {
++this->steps;
if (!std::next_permutation(std::begin(working_set.get()),
std::end(working_set.get()), cmp_iters)) {
this->steps = COMPLETE;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container)};
}
};
template <typename Container>
Permuter<Container> permutations(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Permuter<std::initializer_list<T>> permutations(std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<commit_msg>makes Permuter ctor private, moves into impl { }<commit_after>#ifndef ITER_PERMUTATIONS_HPP_
#define ITER_PERMUTATIONS_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <algorithm>
#include <initializer_list>
#include <vector>
#include <utility>
#include <iterator>
namespace iter {
namespace impl {
template <typename Container>
class Permuter;
}
template <typename Container>
impl::Permuter<Container> permutations(Container&&);
template <typename T>
impl::Permuter<std::initializer_list<T>> permutations(
std::initializer_list<T>);
}
template <typename Container>
class iter::impl::Permuter {
private:
Container container;
using IndexVector = std::vector<iterator_type<Container>>;
using Permutable = IterIterWrapper<IndexVector>;
friend Permuter iter::permutations<Container>(Container&&);
template <typename T>
friend Permuter<std::initializer_list<T>> iter::permutations(
std::initializer_list<T>);
Permuter(Container&& in_container)
: container(std::forward<Container>(in_container)) {}
public:
class Iterator : public std::iterator<std::input_iterator_tag, Permutable> {
private:
static constexpr const int COMPLETE = -1;
static bool cmp_iters(const iterator_type<Container>& lhs,
const iterator_type<Container>& rhs) noexcept {
return *lhs < *rhs;
}
Permutable working_set;
int steps{};
public:
Iterator(
iterator_type<Container>&& sub_iter, iterator_type<Container>&& sub_end)
: steps{sub_iter != sub_end ? 0 : COMPLETE} {
// done like this instead of using vector ctor with
// two iterators because that causes a substitution
// failure when the iterator is minimal
while (sub_iter != sub_end) {
this->working_set.get().push_back(sub_iter);
++sub_iter;
}
std::sort(std::begin(working_set.get()), std::end(working_set.get()),
cmp_iters);
}
Permutable& operator*() {
return this->working_set;
}
Permutable* operator->() {
return &this->working_set;
}
Iterator& operator++() {
++this->steps;
if (!std::next_permutation(std::begin(working_set.get()),
std::end(working_set.get()), cmp_iters)) {
this->steps = COMPLETE;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->steps == other.steps;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container)};
}
};
template <typename Container>
iter::impl::Permuter<Container> iter::permutations(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
iter::impl::Permuter<std::initializer_list<T>> iter::permutations(
std::initializer_list<T> il) {
return {std::move(il)};
}
#endif
<|endoftext|> |
<commit_before>#ifndef QRW_SID_HPP
#define QRW_SID_HPP
#include <functional>
namespace qrw
{
class SID
{
public:
SID(const std::string& identifier)
: m_stringId(identifier),
m_hashId(std::hash<std::string>{}(identifier))
{
}
SID(const SID& rhs) = delete;
bool operator==(const SID& rhs) const
{
return m_hashId == rhs.m_hashId;
}
private:
const std::string m_stringId;
const std::size_t m_hashId;
};
} // namespace qrw
#endif // QRW_SID_HPP
<commit_msg>Added operator<< to SID<commit_after>#ifndef QRW_SID_HPP
#define QRW_SID_HPP
#include <functional>
#include <iostream>
namespace qrw
{
class SID
{
public:
SID(const std::string& identifier)
: m_stringId(identifier),
m_hashId(std::hash<std::string>{}(identifier))
{
}
SID(const SID& rhs) = delete;
bool operator==(const SID& rhs) const
{
return m_hashId == rhs.m_hashId;
}
friend std::ostream& operator<<(std::ostream& os, const SID& sid)
{
os << sid.m_stringId;
return os;
}
private:
const std::string m_stringId;
const std::size_t m_hashId;
};
} // namespace qrw
#endif // QRW_SID_HPP
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
#include <type_traits>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localevaluation/swipdg.hh>
#include <dune/gdt/localoperator/codim0.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/assembler/system.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Operators {
// forwards
template< class DiffusionType
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType >
class EllipticSWIPDG;
namespace internal {
template< class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp >
class EllipticSWIPDGTraits
{
static_assert(std::is_base_of< Stuff::LocalizableFunctionInterface< typename DiffusionType::EntityType
, typename DiffusionType::DomainFieldType
, DiffusionType::dimDomain
, typename DiffusionType::RangeFieldType
, DiffusionType::dimRange
, DiffusionType::dimRangeCols >
, DiffusionType >::value,
"DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::LA::MatrixInterface< typename MatrixImp::Traits >, MatrixImp >::value,
"MatrixImp has to be derived from Stuff::LA::MatrixInterface!");
static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value,
"SourceSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value,
"RangeSpaceImp has to be derived from SpaceInterface!");
public:
typedef EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > derived_type;
typedef MatrixImp MatrixType;
typedef SourceSpaceImp SourceSpaceType;
typedef RangeSpaceImp RangeSpaceType;
typedef GridViewImp GridViewType;
}; // class EllipticSWIPDGTraits
} // namespace internal
template< class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp >
class EllipticSWIPDG
: public Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > >
, public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp >
{
typedef SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType;
typedef Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > >
OperatorBaseType;
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > VolumeOperatorType;
typedef LocalAssembler::Codim0Matrix< VolumeOperatorType > VolumeAssemblerType;
typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::SWIPDG::Inner< DiffusionType > > CouplingOperatorType;
typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > CouplingAssemblerType;
typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionType > >
DirichletBoundaryOperatorType;
typedef LocalAssembler::Codim1BoundaryMatrix< DirichletBoundaryOperatorType > DirichletBoundaryAssemblerType;
typedef typename MatrixImp::ScalarType ScalarType;
public:
typedef internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType;
using OperatorBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_face_and_volume_pattern(grid_view, source_space);
}
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const GridViewType& grid_view,
const ScalarType beta = 1.0)
: OperatorBaseType(matrix, source_space, range_space, grid_view)
, AssemblerBaseType(range_space, grid_view, source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const ScalarType beta = 1.0)
: OperatorBaseType(matrix, source_space, range_space)
, AssemblerBaseType(range_space, source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const ScalarType beta = 1.0)
: OperatorBaseType(matrix, source_space)
, AssemblerBaseType(source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
virtual ~EllipticSWIPDG() {}
virtual void assemble() DS_OVERRIDE DS_FINAL
{
AssemblerBaseType::assemble();
}
private:
const DiffusionType& diffusion_;
const BoundaryInfoType& boundary_info_;
const VolumeOperatorType volume_operator_;
const VolumeAssemblerType volume_assembler_;
const CouplingOperatorType coupling_operator_;
const CouplingAssemblerType coupling_assembler_;
const DirichletBoundaryOperatorType dirichlet_boundary_operator_;
const DirichletBoundaryAssemblerType dirichlet_boundary_assembler_;
}; // class EllipticSWIPDG
} // namespace Operators
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
<commit_msg>[operators.elliptic-swipdg] * use correct default_beta * prepare for specialization with an additional diffusion tensor<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
#include <type_traits>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localevaluation/swipdg.hh>
#include <dune/gdt/localoperator/codim0.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/assembler/system.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Operators {
// forwards
template< class DiffusionFactorType
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType
, class DiffusionTensorType = void >
class EllipticSWIPDG;
namespace internal {
template< class DiffusionFactorType
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp
, class GridViewImp
, class DiffusionTensorType = void >
class EllipticSWIPDGTraits
{
static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionFactorType >::value,
"DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionTensorType >::value,
"DiffusionTensorType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::LA::MatrixInterface< typename MatrixImp::Traits >, MatrixImp >::value,
"MatrixImp has to be derived from Stuff::LA::MatrixInterface!");
static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value,
"SourceSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value,
"RangeSpaceImp has to be derived from SpaceInterface!");
public:
typedef EllipticSWIPDG< DiffusionFactorType, MatrixImp, SourceSpaceImp
, RangeSpaceImp, GridViewImp, DiffusionTensorType > derived_type;
typedef MatrixImp MatrixType;
typedef SourceSpaceImp SourceSpaceType;
typedef RangeSpaceImp RangeSpaceType;
typedef GridViewImp GridViewType;
}; // class EllipticSWIPDGTraits
template< class DiffusionType
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp
, class GridViewImp >
class EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void >
{
static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionType >::value,
"DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::LA::MatrixInterface< typename MatrixImp::Traits >, MatrixImp >::value,
"MatrixImp has to be derived from Stuff::LA::MatrixInterface!");
static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value,
"SourceSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value,
"RangeSpaceImp has to be derived from SpaceInterface!");
public:
typedef EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void > derived_type;
typedef MatrixImp MatrixType;
typedef SourceSpaceImp SourceSpaceType;
typedef RangeSpaceImp RangeSpaceType;
typedef GridViewImp GridViewType;
}; // class EllipticSWIPDGTraits
} // namespace internal
template< class DiffusionType, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp >
class EllipticSWIPDG< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void >
: public Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp
, RangeSpaceImp, GridViewImp, void > >
, public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp >
{
typedef SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType;
typedef Operators::MatrixBased< internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp
, SourceSpaceImp, RangeSpaceImp
, GridViewImp, void > > OperatorBaseType;
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > VolumeOperatorType;
typedef LocalAssembler::Codim0Matrix< VolumeOperatorType > VolumeAssemblerType;
typedef LocalOperator::Codim1CouplingIntegral< LocalEvaluation::SWIPDG::Inner< DiffusionType > >
CouplingOperatorType;
typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType >
CouplingAssemblerType;
typedef LocalOperator::Codim1BoundaryIntegral< LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionType > >
DirichletBoundaryOperatorType;
typedef LocalAssembler::Codim1BoundaryMatrix< DirichletBoundaryOperatorType > DirichletBoundaryAssemblerType;
typedef typename MatrixImp::ScalarType ScalarType;
public:
typedef internal::EllipticSWIPDGTraits< DiffusionType, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp, void >
Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType;
using OperatorBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_face_and_volume_pattern(grid_view, source_space);
}
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const GridViewType& grid_view,
const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
: OperatorBaseType(matrix, source_space, range_space, grid_view)
, AssemblerBaseType(range_space, grid_view, source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
: OperatorBaseType(matrix, source_space, range_space)
, AssemblerBaseType(range_space, source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
EllipticSWIPDG(const DiffusionType& diffusion,
const BoundaryInfoType& boundary_info,
MatrixType& matrix,
const SourceSpaceType& source_space,
const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
: OperatorBaseType(matrix, source_space)
, AssemblerBaseType(source_space)
, diffusion_(diffusion)
, boundary_info_(boundary_info)
, volume_operator_(diffusion_)
, volume_assembler_(volume_operator_)
, coupling_operator_(diffusion_, beta)
, coupling_assembler_(coupling_operator_)
, dirichlet_boundary_operator_(diffusion_, beta)
, dirichlet_boundary_assembler_(dirichlet_boundary_operator_)
{
this->add(volume_assembler_, this->matrix());
this->add(coupling_assembler_, this->matrix(), new ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(dirichlet_boundary_assembler_,
this->matrix(),
new ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
} // EllipticSWIPDG(...)
virtual ~EllipticSWIPDG() {}
virtual void assemble() DS_OVERRIDE DS_FINAL
{
AssemblerBaseType::assemble();
}
private:
const DiffusionType& diffusion_;
const BoundaryInfoType& boundary_info_;
const VolumeOperatorType volume_operator_;
const VolumeAssemblerType volume_assembler_;
const CouplingOperatorType coupling_operator_;
const CouplingAssemblerType coupling_assembler_;
const DirichletBoundaryOperatorType dirichlet_boundary_operator_;
const DirichletBoundaryAssemblerType dirichlet_boundary_assembler_;
}; // class EllipticSWIPDG
} // namespace Operators
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ELLIPTIC_SWIPDG_HH
<|endoftext|> |
<commit_before>#include "LRLayersPack.h"
#include "check_params.h"
#include <lr/dataset/Grids.h>
#include <lr/dataset/CharacterFileName.h>
#include <easyshape.h>
namespace edb
{
std::string LRLayersPack::Command() const
{
return "lr-pack";
}
std::string LRLayersPack::Description() const
{
return "create shape table from lr file";
}
std::string LRLayersPack::Usage() const
{
// lr-pack e:/test2/test_lr.json
std::string usage = Command() + " [filepath]";
return usage;
}
void LRLayersPack::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 3)) return;
if (!check_file(argv[2])) return;
Run(argv[2]);
}
void LRLayersPack::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();
std::string dir = d2d::FilenameTools::getFileDir(filepath) + "\\";
Json::Value out_val;
out_val["width"] = lr_val["size"]["width"];
out_val["height"] = lr_val["size"]["height"];
lr::Grids grids;
int w = lr_val["size"]["width"].asUInt(),
h = lr_val["size"]["height"].asUInt();
grids.Build(w, h);
int col, row;
grids.GetGridSize(col, row);
out_val["col"] = col;
out_val["row"] = row;
ParserCharacter(lr_val, 2, "character", out_val);
ParserPoint(lr_val, dir, 3, "point", out_val);
ParserPolygon(lr_val, dir, grids, 4, "path", out_val);
ParserPolygon(lr_val, dir, grids, 5, "region", out_val);
ParserPolygon(lr_val, dir, grids, 6, "collision region", out_val);
ParserCamera(lr_val, 7, "camera", out_val);
std::string outfile = filepath.substr(0, filepath.find_last_of('_')) + ".json";
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outfile.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, out_val);
fout.close();
}
void LRLayersPack::ParserPolyShape(d2d::IShape* shape, const d2d::Vector& offset,
const lr::Grids& grids, Json::Value& out_val)
{
if (libshape::PolygonShape* poly = dynamic_cast<libshape::PolygonShape*>(shape))
{
std::vector<int> grid_idx;
std::vector<d2d::Vector> bound = poly->GetVertices();
for (int i = 0, n = bound.size(); i < n; ++i) {
bound[i] += offset;
}
grid_idx = grids.IntersectPolygon(bound);
for (int i = 0, n = grid_idx.size(); i < n; ++i) {
int sz = out_val["grid"].size();
out_val["grid"][sz] = grid_idx[i];
}
}
else if (libshape::ChainShape* chain = dynamic_cast<libshape::ChainShape*>(shape))
{
std::vector<d2d::Vector> bound = chain->GetVertices();
for (int i = 0, n = bound.size(); i < n; ++i) {
bound[i] += offset;
}
d2d::JsonIO::Store(bound, out_val["pos"]);
}
else
{
throw d2d::Exception("LRLayersPack::ParserPolyLayer error shape type");
}
}
void LRLayersPack::ParserPolygon(const Json::Value& src_val, const std::string& dir,
const lr::Grids& grids, int layer_idx, const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!src_spr_val.isNull())
{
wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(dir, src_spr_val);
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(spr_path);
assert(symbol);
Json::Value dst_val;
dst_val["name"] = src_spr_val["name"];
d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
sprite->load(src_spr_val);
libshape::Sprite* shape_spr = dynamic_cast<libshape::Sprite*>(sprite);
assert(shape_spr);
const std::vector<d2d::IShape*>& shapes = shape_spr->getSymbol().GetShapes();
for (int i = 0, n = shapes.size(); i < n; ++i) {
ParserPolyShape(shapes[i], sprite->getPosition(), grids, dst_val);
}
int sz = out_val[name].size();
out_val[name][sz] = dst_val;
sprite->Release();
symbol->Release();
src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
idx = 0;
Json::Value src_shape_val = src_val["layer"][layer_idx]["shape"][idx++];
while (!src_shape_val.isNull())
{
d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(src_shape_val, dir);
Json::Value dst_val;
dst_val["name"] = src_shape_val["name"];
ParserPolyShape(shape, d2d::Vector(0, 0), grids, dst_val);
int sz = out_val[name].size();
out_val[name][sz] = dst_val;
shape->Release();
src_shape_val = src_val["layer"][layer_idx]["shape"][idx++];
}
}
void LRLayersPack::ParserPoint(const Json::Value& src_val, const std::string& dir,
int layer_idx, const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(dir, spr_val);
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(spr_path);
assert(symbol);
Json::Value shape_val;
shape_val["name"] = spr_val["name"];
d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
sprite->load(spr_val);
shape_val["x"] = sprite->getPosition().x;
shape_val["y"] = sprite->getPosition().y;
int sz = out_val[name].size();
out_val[name][sz] = shape_val;
sprite->Release();
symbol->Release();
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
void LRLayersPack::ParserCamera(const Json::Value& src_val, int layer_idx,
const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
Json::Value cam_val;
cam_val["name"] = spr_val["name"];
cam_val["x"] = spr_val["position"]["x"];
cam_val["y"] = spr_val["position"]["y"];
cam_val["scale"] = spr_val["x scale"];
int sz = out_val[name].size();
out_val[name][sz] = cam_val;
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
void LRLayersPack::ParserCharacter(const Json::Value& src_val, int layer_idx,
const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
Json::Value char_val;
char_val["name"] = spr_val["name"];
char_val["x"] = spr_val["position"]["x"];
char_val["y"] = spr_val["position"]["y"];
// tags
std::string tag = spr_val["tag"].asString();
std::vector<std::string> tags;
int pos = tag.find_first_of(';');
tags.push_back(tag.substr(0, pos));
do
{
int next_pos = tag.find_first_of(';', pos + 1);
tags.push_back(tag.substr(pos + 1, next_pos - pos - 1));
pos = next_pos;
} while (pos != std::string::npos);
for (int i = 0, n = tags.size(); i < n; ++i) {
const std::string& str = tags[i];
int pos = str.find_first_of('=');
std::string key = str.substr(0, pos);
std::string val = str.substr(pos+1);
char_val["tag"][key] = val;
}
// filename
std::string filename = d2d::FilenameTools::getFilename(spr_val["filepath"].asString());
lr::CharacterFileName out_name(filename);
char_val["filename"] = out_name.GetOutputName();
// angle
int dir = 1 + (out_name.GetField(lr::CharacterFileName::FT_DIRECTION)[0] - '1');
if (spr_val["x mirror"].asBool()) {
dir = 10 - dir;
}
dir = (dir + 7) % 8;
char_val["angle"] = dir + 1;
int sz = out_val[name].size();
out_val[name][sz] = char_val;
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
}<commit_msg>[FIXED] lr输出view size<commit_after>#include "LRLayersPack.h"
#include "check_params.h"
#include <lr/dataset/Grids.h>
#include <lr/dataset/CharacterFileName.h>
#include <easyshape.h>
namespace edb
{
std::string LRLayersPack::Command() const
{
return "lr-pack";
}
std::string LRLayersPack::Description() const
{
return "create shape table from lr file";
}
std::string LRLayersPack::Usage() const
{
// lr-pack e:/test2/test_lr.json
std::string usage = Command() + " [filepath]";
return usage;
}
void LRLayersPack::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 3)) return;
if (!check_file(argv[2])) return;
Run(argv[2]);
}
void LRLayersPack::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();
std::string dir = d2d::FilenameTools::getFileDir(filepath) + "\\";
Json::Value out_val;
out_val["width"] = lr_val["size"]["width"];
out_val["height"] = lr_val["size"]["height"];
out_val["view width"] = lr_val["size"]["view width"];
out_val["view height"] = lr_val["size"]["view height"];
lr::Grids grids;
int w = lr_val["size"]["width"].asUInt(),
h = lr_val["size"]["height"].asUInt();
grids.Build(w, h);
int col, row;
grids.GetGridSize(col, row);
out_val["col"] = col;
out_val["row"] = row;
ParserCharacter(lr_val, 2, "character", out_val);
ParserPoint(lr_val, dir, 3, "point", out_val);
ParserPolygon(lr_val, dir, grids, 4, "path", out_val);
ParserPolygon(lr_val, dir, grids, 5, "region", out_val);
ParserPolygon(lr_val, dir, grids, 6, "collision region", out_val);
ParserCamera(lr_val, 7, "camera", out_val);
std::string outfile = filepath.substr(0, filepath.find_last_of('_')) + ".json";
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outfile.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, out_val);
fout.close();
}
void LRLayersPack::ParserPolyShape(d2d::IShape* shape, const d2d::Vector& offset,
const lr::Grids& grids, Json::Value& out_val)
{
if (libshape::PolygonShape* poly = dynamic_cast<libshape::PolygonShape*>(shape))
{
std::vector<int> grid_idx;
std::vector<d2d::Vector> bound = poly->GetVertices();
for (int i = 0, n = bound.size(); i < n; ++i) {
bound[i] += offset;
}
grid_idx = grids.IntersectPolygon(bound);
for (int i = 0, n = grid_idx.size(); i < n; ++i) {
int sz = out_val["grid"].size();
out_val["grid"][sz] = grid_idx[i];
}
}
else if (libshape::ChainShape* chain = dynamic_cast<libshape::ChainShape*>(shape))
{
std::vector<d2d::Vector> bound = chain->GetVertices();
for (int i = 0, n = bound.size(); i < n; ++i) {
bound[i] += offset;
}
d2d::JsonIO::Store(bound, out_val["pos"]);
}
else
{
throw d2d::Exception("LRLayersPack::ParserPolyLayer error shape type");
}
}
void LRLayersPack::ParserPolygon(const Json::Value& src_val, const std::string& dir,
const lr::Grids& grids, int layer_idx, const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!src_spr_val.isNull())
{
wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(dir, src_spr_val);
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(spr_path);
assert(symbol);
Json::Value dst_val;
dst_val["name"] = src_spr_val["name"];
d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
sprite->load(src_spr_val);
libshape::Sprite* shape_spr = dynamic_cast<libshape::Sprite*>(sprite);
assert(shape_spr);
const std::vector<d2d::IShape*>& shapes = shape_spr->getSymbol().GetShapes();
for (int i = 0, n = shapes.size(); i < n; ++i) {
ParserPolyShape(shapes[i], sprite->getPosition(), grids, dst_val);
}
int sz = out_val[name].size();
out_val[name][sz] = dst_val;
sprite->Release();
symbol->Release();
src_spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
idx = 0;
Json::Value src_shape_val = src_val["layer"][layer_idx]["shape"][idx++];
while (!src_shape_val.isNull())
{
d2d::IShape* shape = libshape::ShapeFactory::CreateShapeFromFile(src_shape_val, dir);
Json::Value dst_val;
dst_val["name"] = src_shape_val["name"];
ParserPolyShape(shape, d2d::Vector(0, 0), grids, dst_val);
int sz = out_val[name].size();
out_val[name][sz] = dst_val;
shape->Release();
src_shape_val = src_val["layer"][layer_idx]["shape"][idx++];
}
}
void LRLayersPack::ParserPoint(const Json::Value& src_val, const std::string& dir,
int layer_idx, const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
wxString spr_path = d2d::SymbolSearcher::GetSymbolPath(dir, spr_val);
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(spr_path);
assert(symbol);
Json::Value shape_val;
shape_val["name"] = spr_val["name"];
d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol);
sprite->load(spr_val);
shape_val["x"] = sprite->getPosition().x;
shape_val["y"] = sprite->getPosition().y;
int sz = out_val[name].size();
out_val[name][sz] = shape_val;
sprite->Release();
symbol->Release();
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
void LRLayersPack::ParserCamera(const Json::Value& src_val, int layer_idx,
const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
Json::Value cam_val;
cam_val["name"] = spr_val["name"];
cam_val["x"] = spr_val["position"]["x"];
cam_val["y"] = spr_val["position"]["y"];
cam_val["scale"] = spr_val["x scale"];
int sz = out_val[name].size();
out_val[name][sz] = cam_val;
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
void LRLayersPack::ParserCharacter(const Json::Value& src_val, int layer_idx,
const char* name, Json::Value& out_val)
{
int idx = 0;
Json::Value spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
while (!spr_val.isNull())
{
Json::Value char_val;
char_val["name"] = spr_val["name"];
char_val["x"] = spr_val["position"]["x"];
char_val["y"] = spr_val["position"]["y"];
// tags
std::string tag = spr_val["tag"].asString();
std::vector<std::string> tags;
int pos = tag.find_first_of(';');
tags.push_back(tag.substr(0, pos));
do
{
int next_pos = tag.find_first_of(';', pos + 1);
tags.push_back(tag.substr(pos + 1, next_pos - pos - 1));
pos = next_pos;
} while (pos != std::string::npos);
for (int i = 0, n = tags.size(); i < n; ++i) {
const std::string& str = tags[i];
int pos = str.find_first_of('=');
std::string key = str.substr(0, pos);
std::string val = str.substr(pos+1);
char_val["tag"][key] = val;
}
// filename
std::string filename = d2d::FilenameTools::getFilename(spr_val["filepath"].asString());
lr::CharacterFileName out_name(filename);
char_val["filename"] = out_name.GetOutputName();
// angle
int dir = 1 + (out_name.GetField(lr::CharacterFileName::FT_DIRECTION)[0] - '1');
if (spr_val["x mirror"].asBool()) {
dir = 10 - dir;
}
dir = (dir + 7) % 8;
char_val["angle"] = dir + 1;
int sz = out_val[name].size();
out_val[name][sz] = char_val;
spr_val = src_val["layer"][layer_idx]["sprite"][idx++];
}
}
}<|endoftext|> |
<commit_before>#include "Event.hpp"
#include "ObjectState.hpp"
#include "SimulationObject.hpp"<commit_msg>Added Simulation include<commit_after>#include "Event.hpp"
#include "ObjectState.hpp"
#include "Simulation.hpp"
#include "SimulationObject.hpp"<|endoftext|> |
<commit_before>#include <atomic>
#include "percpu.hh"
#include "ref.hh"
class filetable : public referenced {
private:
static const int cpushift = 16;
static const int fdmask = (1 << cpushift) - 1;
public:
static sref<filetable> alloc() {
return sref<filetable>::transfer(new filetable());
}
sref<filetable> copy() {
filetable* t = new filetable(false);
scoped_gc_epoch gc;
for(int cpu = 0; cpu < NCPU; cpu++) {
for(int fd = 0; fd < NOFILE; fd++) {
file *f = ofile_[cpu][fd];
if (f) {
f->inc();
t->ofile_[cpu][fd].store(f, std::memory_order_relaxed);
} else {
t->ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed);
}
}
}
std::atomic_thread_fence(std::memory_order_release);
return sref<filetable>::transfer(t);
}
bool getfile(int fd, sref<file> *sf) {
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU)
return false;
if (fd < 0 || fd >= NOFILE)
return false;
scoped_gc_epoch gc;
file* f = ofile_[cpu][fd];
if (!f || !sf->init_nonzero(f))
return false;
return true;
}
int allocfd(struct file *f, bool percpu = false) {
int cpu = percpu ? myid() : 0;
for (int fd = 0; fd < NOFILE; fd++)
if (ofile_[cpu][fd] == nullptr && cmpxch(&ofile_[cpu][fd], (file*)nullptr, f))
return (cpu << cpushift) | fd;
cprintf("filetable::allocfd: failed\n");
return -1;
}
void close(int fd) {
// XXX(sbw) if f->ref_ > 1 the kernel will not actually close
// the file when this function returns (i.e. sys_close can return
// while the file/pipe/socket is still open).
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU) {
cprintf("filetable::close: bad fd cpu %u\n", cpu);
return;
}
if (fd < 0 || fd >= NOFILE) {
cprintf("filetable::close: bad fd %u\n", fd);
return;
}
file* f = ofile_[cpu][fd].exchange(nullptr);
if (f != nullptr)
f->dec();
else
cprintf("filetable::close: bad fd %u\n", fd);
}
bool replace(int fd, struct file* newf) {
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU) {
cprintf("filetable::replace: bad fd cpu %u\n", cpu);
return false;
}
if (fd < 0 || fd >= NOFILE) {
cprintf("filetable::replace: bad fd %u\n", fd);
return false;
}
file* oldf = ofile_[cpu][fd].exchange(newf);
if (oldf != nullptr)
oldf->dec();
return true;
}
private:
filetable(bool clear = true) {
if (!clear)
return;
for(int cpu = 0; cpu < NCPU; cpu++)
for(int fd = 0; fd < NOFILE; fd++)
ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
}
~filetable() {
for(int cpu = 0; cpu < NCPU; cpu++){
for(int fd = 0; fd < NOFILE; fd++){
if (ofile_[cpu][fd].load() != nullptr) {
ofile_[cpu][fd].load()->dec();
ofile_[cpu][fd] = nullptr;
}
}
}
}
filetable& operator=(const filetable&);
filetable(const filetable& x);
NEW_DELETE_OPS(filetable);
percpu<std::atomic<file*>[NOFILE]> ofile_;
};
<commit_msg>filetable: Remove GC epochs<commit_after>#include <atomic>
#include "percpu.hh"
#include "ref.hh"
class filetable : public referenced {
private:
static const int cpushift = 16;
static const int fdmask = (1 << cpushift) - 1;
public:
static sref<filetable> alloc() {
return sref<filetable>::transfer(new filetable());
}
sref<filetable> copy() {
filetable* t = new filetable(false);
for(int cpu = 0; cpu < NCPU; cpu++) {
for(int fd = 0; fd < NOFILE; fd++) {
file *f = ofile_[cpu][fd];
if (f) {
f->inc();
t->ofile_[cpu][fd].store(f, std::memory_order_relaxed);
} else {
t->ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed);
}
}
}
std::atomic_thread_fence(std::memory_order_release);
return sref<filetable>::transfer(t);
}
bool getfile(int fd, sref<file> *sf) {
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU)
return false;
if (fd < 0 || fd >= NOFILE)
return false;
file* f = ofile_[cpu][fd];
if (!f || !sf->init_nonzero(f))
return false;
return true;
}
int allocfd(struct file *f, bool percpu = false) {
int cpu = percpu ? myid() : 0;
for (int fd = 0; fd < NOFILE; fd++)
if (ofile_[cpu][fd] == nullptr && cmpxch(&ofile_[cpu][fd], (file*)nullptr, f))
return (cpu << cpushift) | fd;
cprintf("filetable::allocfd: failed\n");
return -1;
}
void close(int fd) {
// XXX(sbw) if f->ref_ > 1 the kernel will not actually close
// the file when this function returns (i.e. sys_close can return
// while the file/pipe/socket is still open).
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU) {
cprintf("filetable::close: bad fd cpu %u\n", cpu);
return;
}
if (fd < 0 || fd >= NOFILE) {
cprintf("filetable::close: bad fd %u\n", fd);
return;
}
file* f = ofile_[cpu][fd].exchange(nullptr);
if (f != nullptr)
f->dec();
else
cprintf("filetable::close: bad fd %u\n", fd);
}
bool replace(int fd, struct file* newf) {
int cpu = fd >> cpushift;
fd = fd & fdmask;
if (cpu < 0 || cpu >= NCPU) {
cprintf("filetable::replace: bad fd cpu %u\n", cpu);
return false;
}
if (fd < 0 || fd >= NOFILE) {
cprintf("filetable::replace: bad fd %u\n", fd);
return false;
}
file* oldf = ofile_[cpu][fd].exchange(newf);
if (oldf != nullptr)
oldf->dec();
return true;
}
private:
filetable(bool clear = true) {
if (!clear)
return;
for(int cpu = 0; cpu < NCPU; cpu++)
for(int fd = 0; fd < NOFILE; fd++)
ofile_[cpu][fd].store(nullptr, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
}
~filetable() {
for(int cpu = 0; cpu < NCPU; cpu++){
for(int fd = 0; fd < NOFILE; fd++){
if (ofile_[cpu][fd].load() != nullptr) {
ofile_[cpu][fd].load()->dec();
ofile_[cpu][fd] = nullptr;
}
}
}
}
filetable& operator=(const filetable&);
filetable(const filetable& x);
NEW_DELETE_OPS(filetable);
percpu<std::atomic<file*>[NOFILE]> ofile_;
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
using namespace std;
enum class Turn
{
toSay = 0,
toAnswer = 1,
toEnd = 2
};
std::mutex mux;
std::condition_variable dataReady;
bool notified = false;
auto turnType = Turn::toSay;
void say(std::string word, bool infinite, int times)
{
for (int i = 0; i < times || infinite; ++i)
{
std::unique_lock<std::mutex> lock(mux);
std::cout << word << ' ';
turnType = Turn::toAnswer;
notified = true;
dataReady.notify_one();
dataReady.wait(lock, []{return !notified;}); // condition to avoid spurious wakeups
}
turnType = Turn::toEnd;
notified = true;
dataReady.notify_one();
}
void listen_and_answer(std::string word)
{
std::unique_lock<std::mutex> lock(mux);
while (!(turnType == Turn::toEnd))
{
dataReady.wait(lock, []{return notified;}); // condition to avoid spurious wakeups
while (turnType == Turn::toAnswer)
{
std::cout << word << ' ';
turnType = Turn::toSay;
}
notified = false;
dataReady.notify_one();
}
std::cout << std::endl;
}
int main(int argc, char *argv[])
{
bool infinite = true;
int times = 10;
if(argc > 1)
{
times = atoi(argv[1]);
if(times > 0)
infinite = false;
}
std::thread t1(say, "ping", infinite, times);
std::thread t2(listen_and_answer, "pong");
t1.join();
t2.join();
return 0;
}
<commit_msg>Remove superfluous variable<commit_after>#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
using namespace std;
enum class Turn
{
toSay = 0,
toAnswer = 1,
toEnd = 2
};
std::mutex mux;
std::condition_variable dataReady;
auto turnType = Turn::toSay;
void say(std::string word, bool infinite, int times)
{
for (int i = 0; i < times || infinite; ++i)
{
std::unique_lock<std::mutex> lock(mux);
std::cout << word << ' ';
turnType = Turn::toAnswer;
dataReady.notify_one();
dataReady.wait(lock, []{return (turnType == Turn::toSay);}); // condition to avoid spurious wakeups
}
turnType = Turn::toEnd;
dataReady.notify_one();
}
void listen_and_answer(std::string word)
{
std::unique_lock<std::mutex> lock(mux);
while (!(turnType == Turn::toEnd))
{
dataReady.wait(lock, []{return !(turnType == Turn::toSay);}); // condition to avoid spurious wakeups
while (turnType == Turn::toAnswer)
{
std::cout << word << ' ';
turnType = Turn::toSay;
}
dataReady.notify_one();
}
std::cout << std::endl;
}
int main(int argc, char *argv[])
{
bool infinite = true;
int times = 10;
if(argc > 1)
{
times = atoi(argv[1]);
if(times > 0)
infinite = false;
}
std::thread t1(say, "ping", infinite, times);
std::thread t2(listen_and_answer, "pong");
t1.join();
t2.join();
return 0;
}
<|endoftext|> |
<commit_before>// A C++ interface to POSIX functions.
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
// Disable bogus MSVC warnings.
#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "posix.h"
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#else
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <io.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
# ifndef S_IRUSR
# define S_IRUSR _S_IREAD
# endif
# ifndef S_IWUSR
# define S_IWUSR _S_IWRITE
# endif
# ifdef __MINGW32__
# define _SH_DENYNO 0x40
# endif
#endif // _WIN32
#ifdef fileno
# undef fileno
#endif
namespace {
#ifdef _WIN32
// Return type of read and write functions.
typedef int RWResult;
// On Windows the count argument to read and write is unsigned, so convert
// it from size_t preventing integer overflow.
inline unsigned convert_rwcount(std::size_t count) {
return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
}
#else
// Return type of read and write functions.
typedef ssize_t RWResult;
inline std::size_t convert_rwcount(std::size_t count) { return count; }
#endif
}
fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT {
if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
fmt::report_system_error(errno, "cannot close file");
}
fmt::BufferedFile::BufferedFile(
fmt::cstring_view filename, fmt::cstring_view mode) {
FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0);
if (!file_)
FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
}
void fmt::BufferedFile::close() {
if (!file_)
return;
int result = FMT_SYSTEM(fclose(file_));
file_ = FMT_NULL;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
// A macro used to prevent expansion of fileno on broken versions of MinGW.
#define FMT_ARGS
int fmt::BufferedFile::fileno() const {
int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
if (fd == -1)
FMT_THROW(system_error(errno, "cannot get file descriptor"));
return fd;
}
fmt::File::File(fmt::cstring_view path, int oflag) {
int mode = S_IRUSR | S_IWUSR;
#if defined(_WIN32) && !defined(__MINGW32__)
fd_ = -1;
FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
#else
FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
#endif
if (fd_ == -1)
FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
}
fmt::File::~File() FMT_NOEXCEPT {
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
fmt::report_system_error(errno, "cannot close file");
}
void fmt::File::close() {
if (fd_ == -1)
return;
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
int result = FMT_POSIX_CALL(close(fd_));
fd_ = -1;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
long long fmt::File::size() const {
#ifdef _WIN32
// Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
// is less than 0x0500 as is the case with some default MinGW builds.
// Both functions support large file sizes.
DWORD size_upper = 0;
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
if (size_lower == INVALID_FILE_SIZE) {
DWORD error = GetLastError();
if (error != NO_ERROR)
FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
}
unsigned long long long_size = size_upper;
return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
#else
typedef struct stat Stat;
Stat file_stat = Stat();
if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
FMT_THROW(system_error(errno, "cannot get file attributes"));
static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
"return type of File::size is not large enough");
return file_stat.st_size;
#endif
}
std::size_t fmt::File::read(void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot read from file"));
return internal::to_unsigned(result);
}
std::size_t fmt::File::write(const void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot write to file"));
return internal::to_unsigned(result);
}
fmt::File fmt::File::dup(int fd) {
// Don't retry as dup doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
int new_fd = FMT_POSIX_CALL(dup(fd));
if (new_fd == -1)
FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
return File(new_fd);
}
void fmt::File::dup2(int fd) {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1) {
throw system_error(errno,
"cannot duplicate file descriptor {} to {}", fd_, fd);
}
}
void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1)
ec = ErrorCode(errno);
}
void fmt::File::pipe(File &read_end, File &write_end) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_end.close();
write_end.close();
int fds[2] = {};
#ifdef _WIN32
// Make the default pipe capacity same as on Linux 2.6.11+.
enum { DEFAULT_CAPACITY = 65536 };
int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
#else
// Don't retry as the pipe function doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
int result = FMT_POSIX_CALL(pipe(fds));
#endif
if (result != 0)
FMT_THROW(system_error(errno, "cannot create pipe"));
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_end = File(fds[0]);
write_end = File(fds[1]);
}
fmt::BufferedFile fmt::File::fdopen(const char *mode) {
// Don't retry as fdopen doesn't return EINTR.
FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
if (!f)
FMT_THROW(system_error(errno,
"cannot associate stream with file descriptor"));
BufferedFile file(f);
fd_ = -1;
return file;
}
long fmt::getpagesize() {
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwPageSize;
#else
long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
if (size < 0)
FMT_THROW(system_error(errno, "cannot get memory page size"));
return size;
#endif
}
<commit_msg>posix.cc: Fix compilation with -fno-exceptions<commit_after>// A C++ interface to POSIX functions.
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
// Disable bogus MSVC warnings.
#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif
#include "posix.h"
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32
# include <unistd.h>
#else
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <io.h>
# define O_CREAT _O_CREAT
# define O_TRUNC _O_TRUNC
# ifndef S_IRUSR
# define S_IRUSR _S_IREAD
# endif
# ifndef S_IWUSR
# define S_IWUSR _S_IWRITE
# endif
# ifdef __MINGW32__
# define _SH_DENYNO 0x40
# endif
#endif // _WIN32
#ifdef fileno
# undef fileno
#endif
namespace {
#ifdef _WIN32
// Return type of read and write functions.
typedef int RWResult;
// On Windows the count argument to read and write is unsigned, so convert
// it from size_t preventing integer overflow.
inline unsigned convert_rwcount(std::size_t count) {
return count <= UINT_MAX ? static_cast<unsigned>(count) : UINT_MAX;
}
#else
// Return type of read and write functions.
typedef ssize_t RWResult;
inline std::size_t convert_rwcount(std::size_t count) { return count; }
#endif
}
fmt::BufferedFile::~BufferedFile() FMT_NOEXCEPT {
if (file_ && FMT_SYSTEM(fclose(file_)) != 0)
fmt::report_system_error(errno, "cannot close file");
}
fmt::BufferedFile::BufferedFile(
fmt::cstring_view filename, fmt::cstring_view mode) {
FMT_RETRY_VAL(file_, FMT_SYSTEM(fopen(filename.c_str(), mode.c_str())), 0);
if (!file_)
FMT_THROW(system_error(errno, "cannot open file {}", filename.c_str()));
}
void fmt::BufferedFile::close() {
if (!file_)
return;
int result = FMT_SYSTEM(fclose(file_));
file_ = FMT_NULL;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
// A macro used to prevent expansion of fileno on broken versions of MinGW.
#define FMT_ARGS
int fmt::BufferedFile::fileno() const {
int fd = FMT_POSIX_CALL(fileno FMT_ARGS(file_));
if (fd == -1)
FMT_THROW(system_error(errno, "cannot get file descriptor"));
return fd;
}
fmt::File::File(fmt::cstring_view path, int oflag) {
int mode = S_IRUSR | S_IWUSR;
#if defined(_WIN32) && !defined(__MINGW32__)
fd_ = -1;
FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
#else
FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
#endif
if (fd_ == -1)
FMT_THROW(system_error(errno, "cannot open file {}", path.c_str()));
}
fmt::File::~File() FMT_NOEXCEPT {
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
if (fd_ != -1 && FMT_POSIX_CALL(close(fd_)) != 0)
fmt::report_system_error(errno, "cannot close file");
}
void fmt::File::close() {
if (fd_ == -1)
return;
// Don't retry close in case of EINTR!
// See http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
int result = FMT_POSIX_CALL(close(fd_));
fd_ = -1;
if (result != 0)
FMT_THROW(system_error(errno, "cannot close file"));
}
long long fmt::File::size() const {
#ifdef _WIN32
// Use GetFileSize instead of GetFileSizeEx for the case when _WIN32_WINNT
// is less than 0x0500 as is the case with some default MinGW builds.
// Both functions support large file sizes.
DWORD size_upper = 0;
HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd_));
DWORD size_lower = FMT_SYSTEM(GetFileSize(handle, &size_upper));
if (size_lower == INVALID_FILE_SIZE) {
DWORD error = GetLastError();
if (error != NO_ERROR)
FMT_THROW(windows_error(GetLastError(), "cannot get file size"));
}
unsigned long long long_size = size_upper;
return (long_size << sizeof(DWORD) * CHAR_BIT) | size_lower;
#else
typedef struct stat Stat;
Stat file_stat = Stat();
if (FMT_POSIX_CALL(fstat(fd_, &file_stat)) == -1)
FMT_THROW(system_error(errno, "cannot get file attributes"));
static_assert(sizeof(long long) >= sizeof(file_stat.st_size),
"return type of File::size is not large enough");
return file_stat.st_size;
#endif
}
std::size_t fmt::File::read(void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(read(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot read from file"));
return internal::to_unsigned(result);
}
std::size_t fmt::File::write(const void *buffer, std::size_t count) {
RWResult result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(write(fd_, buffer, convert_rwcount(count))));
if (result < 0)
FMT_THROW(system_error(errno, "cannot write to file"));
return internal::to_unsigned(result);
}
fmt::File fmt::File::dup(int fd) {
// Don't retry as dup doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009695399/functions/dup.html
int new_fd = FMT_POSIX_CALL(dup(fd));
if (new_fd == -1)
FMT_THROW(system_error(errno, "cannot duplicate file descriptor {}", fd));
return File(new_fd);
}
void fmt::File::dup2(int fd) {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1) {
FMT_THROW(system_error(errno,
"cannot duplicate file descriptor {} to {}", fd_, fd));
}
}
void fmt::File::dup2(int fd, ErrorCode &ec) FMT_NOEXCEPT {
int result = 0;
FMT_RETRY(result, FMT_POSIX_CALL(dup2(fd_, fd)));
if (result == -1)
ec = ErrorCode(errno);
}
void fmt::File::pipe(File &read_end, File &write_end) {
// Close the descriptors first to make sure that assignments don't throw
// and there are no leaks.
read_end.close();
write_end.close();
int fds[2] = {};
#ifdef _WIN32
// Make the default pipe capacity same as on Linux 2.6.11+.
enum { DEFAULT_CAPACITY = 65536 };
int result = FMT_POSIX_CALL(pipe(fds, DEFAULT_CAPACITY, _O_BINARY));
#else
// Don't retry as the pipe function doesn't return EINTR.
// http://pubs.opengroup.org/onlinepubs/009696799/functions/pipe.html
int result = FMT_POSIX_CALL(pipe(fds));
#endif
if (result != 0)
FMT_THROW(system_error(errno, "cannot create pipe"));
// The following assignments don't throw because read_fd and write_fd
// are closed.
read_end = File(fds[0]);
write_end = File(fds[1]);
}
fmt::BufferedFile fmt::File::fdopen(const char *mode) {
// Don't retry as fdopen doesn't return EINTR.
FILE *f = FMT_POSIX_CALL(fdopen(fd_, mode));
if (!f)
FMT_THROW(system_error(errno,
"cannot associate stream with file descriptor"));
BufferedFile file(f);
fd_ = -1;
return file;
}
long fmt::getpagesize() {
#ifdef _WIN32
SYSTEM_INFO si;
GetSystemInfo(&si);
return si.dwPageSize;
#else
long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE));
if (size < 0)
FMT_THROW(system_error(errno, "cannot get memory page size"));
return size;
#endif
}
<|endoftext|> |
<commit_before>/**
* pty.js
* Copyright (c) 2013, Christopher Jeffrey, Peter Sunde (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*/
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <stdlib.h>
#include <winpty.h>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace v8;
using namespace std;
using namespace node;
/**
* Misc
*/
extern "C" void init(Handle<Object>);
#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
/**
* winpty
*/
static std::vector<winpty_t *> ptyHandles;
static volatile LONG ptyCounter;
struct winpty_s {
winpty_s();
HANDLE controlPipe;
HANDLE dataPipe;
};
winpty_s::winpty_s() :
controlPipe(nullptr),
dataPipe(nullptr)
{
}
/**
* Helpers
*/
const wchar_t* to_wstring(const String::Utf8Value& str)
{
auto bytes = *str;
auto sizeOfStr = MultiByteToWideChar(CP_ACP, 0, bytes, -1, NULL, 0);
auto output = new wchar_t[sizeOfStr];
MultiByteToWideChar(CP_ACP, 0, bytes, -1, output, sizeOfStr);
return output;
}
static winpty_t *get_pipe_handle(int handle) {
for(auto &ptyHandle : ptyHandles) {
int cmp = (int)ptyHandle->controlPipe;
if(cmp == handle) {
return ptyHandle;
}
}
return nullptr;
}
static bool remove_pipe_handle(int handle) {
for(auto *ptyHandle : ptyHandles) {
if((int)ptyHandle->controlPipe == handle) {
delete ptyHandle;
ptyHandle = nullptr;
return true;
}
}
return false;
}
/*
* PtyOpen
* pty.open(dataPipe, cols, rows)
*
* If you need to debug winpty-agent.exe do the following:
* ======================================================
*
* 1) Install python 2.7
* 2) Install win32pipe
x86) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download
x64) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
* 3) Start deps/winpty/misc/DebugServer.py (Before you start node)
*
* Then you'll see output from winpty-agent.exe.
*
* Important part:
* ===============
* CreateProcess: success 8896 0 (Windows error code)
*
* Create test.js:
* ===============
*
* var pty = require('./');
*
* var term = pty.fork('cmd', [], {
* name: 'Windows Shell',
* cols: 80,
* rows: 30,
* cwd: process.env.HOME,
* env: process.env,
* debug: true
* });
*
* term.on('data', function(data) {
* console.log(data);
* });
*
*/
static Handle<Value> PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 4
|| !args[0]->IsString() // dataPipe
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber() // rows
|| !args[3]->IsBoolean()) // debug
{
return ThrowException(Exception::Error(
String::New("Usage: pty.open(dataPipe, cols, rows, debug)")));
}
auto pipeName = to_wstring(String::Utf8Value(args[0]->ToString()));
auto cols = args[1]->Int32Value();
auto rows = args[2]->Int32Value();
auto debug = args[3]->ToBoolean()->IsTrue();
// Enable/disable debugging
SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
// Open a new pty session.
winpty_t *pc = winpty_open_use_own_datapipe(pipeName, rows, cols);
// Error occured during startup of agent process.
assert(pc != nullptr);
// Save pty struct fpr later use.
ptyHandles.insert(ptyHandles.end(), pc);
// Pty object values.
auto marshal = Object::New();
marshal->Set(String::New("pid"), Number::New((int)pc->controlPipe));
marshal->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter)));
marshal->Set(String::New("fd"), Number::New(-1));
delete pipeName;
return scope.Close(marshal);
}
/*
* PtyStartProcess
* pty.startProcess(pid, file, env, cwd);
*/
static Handle<Value> PtyStartProcess(const Arguments& args) {
HandleScope scope;
if (args.Length() != 5
|| !args[0]->IsNumber() // pid
|| !args[1]->IsString() // file
|| !args[2]->IsString() // cmdline
|| !args[3]->IsString() // env
|| !args[4]->IsString()) // cwd
{
return ThrowException(Exception::Error(
String::New("Usage: pty.startProcess(pid, file, cmdline, env, cwd)")));
}
// Native values.
auto pid = args[0]->Int32Value();
auto file = to_wstring(String::Utf8Value(args[1]->ToString()));
auto cmdline = to_wstring(String::Utf8Value(args[2]->ToString()));
auto env = to_wstring(String::Utf8Value(args[3]->ToString()));
auto cwd = to_wstring(String::Utf8Value(args[4]->ToString()));
// disabled, see: https://github.com/rprichard/winpty/issues/13
env = NULL;
// Get winpty_t by control pipe handle
auto pc = get_pipe_handle(pid);
// Start new terminal
assert(pc != nullptr);
auto result = winpty_start_process(pc, file, cmdline, cwd, env);
assert(0 == result);
return scope.Close(Undefined());
}
/*
* PtyResize
* pty.resize(pid, cols, rows);
*/
static Handle<Value> PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber() // pid
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber()) // rows
{
return ThrowException(Exception::Error(String::New("Usage: pty.resize(pid, cols, rows)")));
}
auto handle = args[0]->Int32Value();
auto cols = args[1]->Int32Value();
auto rows = args[2]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
assert(0 == winpty_set_size(pc, cols, rows));
return scope.Close(Undefined());
}
/*
* PtyKill
* pty.kill(pid);
*/
static Handle<Value> PtyKill(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1
|| !args[0]->IsNumber()) // pid
{
return ThrowException(Exception::Error(String::New("Usage: pty.kill(pid)")));
}
auto handle = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
winpty_exit(pc);
assert(true == remove_pipe_handle(handle));
return scope.Close(Undefined());
}
/**
* Init
*/
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "startProcess", PtyStartProcess);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "kill", PtyKill);
};
NODE_MODULE(pty, init);<commit_msg>bugfix: set correct cols, rows values when starting a new pty session<commit_after>/**
* pty.js
* Copyright (c) 2013, Christopher Jeffrey, Peter Sunde (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*/
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <stdlib.h>
#include <winpty.h>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace v8;
using namespace std;
using namespace node;
/**
* Misc
*/
extern "C" void init(Handle<Object>);
#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
/**
* winpty
*/
static std::vector<winpty_t *> ptyHandles;
static volatile LONG ptyCounter;
struct winpty_s {
winpty_s();
HANDLE controlPipe;
HANDLE dataPipe;
};
winpty_s::winpty_s() :
controlPipe(nullptr),
dataPipe(nullptr)
{
}
/**
* Helpers
*/
const wchar_t* to_wstring(const String::Utf8Value& str)
{
auto bytes = *str;
auto sizeOfStr = MultiByteToWideChar(CP_ACP, 0, bytes, -1, NULL, 0);
auto output = new wchar_t[sizeOfStr];
MultiByteToWideChar(CP_ACP, 0, bytes, -1, output, sizeOfStr);
return output;
}
static winpty_t *get_pipe_handle(int handle) {
for(auto &ptyHandle : ptyHandles) {
int cmp = (int)ptyHandle->controlPipe;
if(cmp == handle) {
return ptyHandle;
}
}
return nullptr;
}
static bool remove_pipe_handle(int handle) {
for(auto *ptyHandle : ptyHandles) {
if((int)ptyHandle->controlPipe == handle) {
delete ptyHandle;
ptyHandle = nullptr;
return true;
}
}
return false;
}
/*
* PtyOpen
* pty.open(dataPipe, cols, rows)
*
* If you need to debug winpty-agent.exe do the following:
* ======================================================
*
* 1) Install python 2.7
* 2) Install win32pipe
x86) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download
x64) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
* 3) Start deps/winpty/misc/DebugServer.py (Before you start node)
*
* Then you'll see output from winpty-agent.exe.
*
* Important part:
* ===============
* CreateProcess: success 8896 0 (Windows error code)
*
* Create test.js:
* ===============
*
* var pty = require('./');
*
* var term = pty.fork('cmd', [], {
* name: 'Windows Shell',
* cols: 80,
* rows: 30,
* cwd: process.env.HOME,
* env: process.env,
* debug: true
* });
*
* term.on('data', function(data) {
* console.log(data);
* });
*
*/
static Handle<Value> PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 4
|| !args[0]->IsString() // dataPipe
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber() // rows
|| !args[3]->IsBoolean()) // debug
{
return ThrowException(Exception::Error(
String::New("Usage: pty.open(dataPipe, cols, rows, debug)")));
}
auto pipeName = to_wstring(String::Utf8Value(args[0]->ToString()));
auto cols = args[1]->Int32Value();
auto rows = args[2]->Int32Value();
auto debug = args[3]->ToBoolean()->IsTrue();
// Enable/disable debugging
SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
// Open a new pty session.
winpty_t *pc = winpty_open_use_own_datapipe(pipeName, cols, rows);
// Error occured during startup of agent process.
assert(pc != nullptr);
// Save pty struct fpr later use.
ptyHandles.insert(ptyHandles.end(), pc);
// Pty object values.
auto marshal = Object::New();
marshal->Set(String::New("pid"), Number::New((int)pc->controlPipe));
marshal->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter)));
marshal->Set(String::New("fd"), Number::New(-1));
delete pipeName;
return scope.Close(marshal);
}
/*
* PtyStartProcess
* pty.startProcess(pid, file, env, cwd);
*/
static Handle<Value> PtyStartProcess(const Arguments& args) {
HandleScope scope;
if (args.Length() != 5
|| !args[0]->IsNumber() // pid
|| !args[1]->IsString() // file
|| !args[2]->IsString() // cmdline
|| !args[3]->IsString() // env
|| !args[4]->IsString()) // cwd
{
return ThrowException(Exception::Error(
String::New("Usage: pty.startProcess(pid, file, cmdline, env, cwd)")));
}
// Native values.
auto pid = args[0]->Int32Value();
auto file = to_wstring(String::Utf8Value(args[1]->ToString()));
auto cmdline = to_wstring(String::Utf8Value(args[2]->ToString()));
auto env = to_wstring(String::Utf8Value(args[3]->ToString()));
auto cwd = to_wstring(String::Utf8Value(args[4]->ToString()));
// disabled, see: https://github.com/rprichard/winpty/issues/13
env = NULL;
// Get winpty_t by control pipe handle
auto pc = get_pipe_handle(pid);
// Start new terminal
assert(pc != nullptr);
auto result = winpty_start_process(pc, file, cmdline, cwd, env);
assert(0 == result);
return scope.Close(Undefined());
}
/*
* PtyResize
* pty.resize(pid, cols, rows);
*/
static Handle<Value> PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber() // pid
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber()) // rows
{
return ThrowException(Exception::Error(String::New("Usage: pty.resize(pid, cols, rows)")));
}
auto handle = args[0]->Int32Value();
auto cols = args[1]->Int32Value();
auto rows = args[2]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
assert(0 == winpty_set_size(pc, cols, rows));
return scope.Close(Undefined());
}
/*
* PtyKill
* pty.kill(pid);
*/
static Handle<Value> PtyKill(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1
|| !args[0]->IsNumber()) // pid
{
return ThrowException(Exception::Error(String::New("Usage: pty.kill(pid)")));
}
auto handle = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
winpty_exit(pc);
assert(true == remove_pipe_handle(handle));
return scope.Close(Undefined());
}
/**
* Init
*/
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "startProcess", PtyStartProcess);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "kill", PtyKill);
};
NODE_MODULE(pty, init);<|endoftext|> |
<commit_before>#include <cmath>
#include <cstring>
#include <string>
#include "catch.hpp"
#include "calculate/binding.h"
TEST_CASE("Bindings", "[bindings]") {
SECTION("Well constructed expression - No error checking") {
Expression expr1 = calculate_c.build("1", "");
Expression expr2 = calculate_c.build("1 + x", "x");
Expression expr3 = calculate_c.build("x + y", "x, y");
double x = 2., *xp = &x;
char output[256];
CHECK(get_calculate_reference() == &calculate_c);
calculate_c.expression(expr1, output);
CHECK(strcmp(output, "1") == 0);
calculate_c.variables(expr1, output);
CHECK(strcmp(output, "") == 0);
CHECK(static_cast<int>(calculate_c.value(expr1)) == 1);
calculate_c.expression(expr2, output);
CHECK(strcmp(output, "1 + x") == 0);
calculate_c.variables(expr2, output);
CHECK(strcmp(output, "x") == 0);
CHECK(static_cast<int>(calculate_c.value(expr2, x)) == 3);
CHECK(static_cast<int>(calculate_c.eval(expr2, xp, 1)) == 3);
calculate_c.expression(expr3, output);
CHECK(strcmp(output, "x + y") == 0);
calculate_c.variables(expr3, output);
CHECK(strcmp(output, "x,y") == 0);
calculate_c.infix(expr3, output);
CHECK(strcmp(output, "x + y") == 0);
calculate_c.postfix(expr3, output);
CHECK(strcmp(output, "x y +") == 0);
calculate_c.tree(expr3, output);
CHECK(strcmp(output, "[+]\n \\_[x]\n \\_[y]") == 0);
calculate_c.free(expr3);
calculate_c.free(expr2);
calculate_c.free(expr1);
}
SECTION("Bad constructed expression - No error checking") {
Expression expr1 = calculate_c.build("1 + x", "");
Expression expr2 = calculate_c.build("1 + x", "");
double *xp = nullptr;
char output[256];
calculate_c.expression(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.variables(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.infix(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.postfix(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.tree(expr1, output);
CHECK(strcmp(output, "") == 0);
CHECK(std::isnan(calculate_c.value(expr1, 2.)));
CHECK(std::isnan(calculate_c.eval(expr1, xp, 0)));
calculate_c.free(expr2);
calculate_c.free(expr1);
}
SECTION("Error checking") {
Expression expr;
double values[] = {1., 2.};
char error[64];
calculate_c.create("x", "", error);
CHECK(std::string(error) == std::string("Undefined symbol 'x'"));
expr = calculate_c.create("x", "x", error);
CHECK(std::string(error) == std::string(""));
calculate_c.evaluate(expr, values, 2, error);
CHECK(std::string(error) == std::string("Variables mismatch"));
}
SECTION("Query functions") {
char output[4096];
calculate_c.constants(output);
CHECK(strlen(output) == 14);
calculate_c.operators(output);
CHECK(strlen(output) == 14);
calculate_c.functions(output);
CHECK(strlen(output) == 256);
}
}
<commit_msg>Increase code coverage<commit_after>#include <cmath>
#include <cstring>
#include <string>
#include "catch.hpp"
#include "calculate/binding.h"
TEST_CASE("Bindings", "[bindings]") {
SECTION("Well constructed expression - No error checking") {
Expression expr1 = calculate_c.build("1", "");
Expression expr2 = calculate_c.build("1 + x", "x");
Expression expr3 = calculate_c.build("x + y", "x, y");
double x = 2., *xp = &x;
char output[256];
CHECK(get_calculate_reference() == &calculate_c);
calculate_c.expression(expr1, output);
CHECK(strcmp(output, "1") == 0);
calculate_c.variables(expr1, output);
CHECK(strcmp(output, "") == 0);
CHECK(static_cast<int>(calculate_c.value(expr1)) == 1);
calculate_c.expression(expr2, output);
CHECK(strcmp(output, "1 + x") == 0);
calculate_c.variables(expr2, output);
CHECK(strcmp(output, "x") == 0);
CHECK(static_cast<int>(calculate_c.value(expr2, x)) == 3);
CHECK(static_cast<int>(calculate_c.eval(expr2, xp, 1)) == 3);
calculate_c.expression(expr3, output);
CHECK(strcmp(output, "x + y") == 0);
calculate_c.variables(expr3, output);
CHECK(strcmp(output, "x,y") == 0);
calculate_c.infix(expr3, output);
CHECK(strcmp(output, "x + y") == 0);
calculate_c.postfix(expr3, output);
CHECK(strcmp(output, "x y +") == 0);
calculate_c.tree(expr3, output);
CHECK(strcmp(output, "[+]\n \\_[x]\n \\_[y]") == 0);
calculate_c.free(expr3);
calculate_c.free(expr2);
calculate_c.free(expr1);
}
SECTION("Bad constructed expression - No error checking") {
Expression expr1 = calculate_c.build("1 + x", "");
Expression expr2 = calculate_c.build("1 + x", "");
double *xp = nullptr;
char output[256];
calculate_c.expression(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.variables(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.infix(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.postfix(expr1, output);
CHECK(strcmp(output, "") == 0);
calculate_c.tree(expr1, output);
CHECK(strcmp(output, "") == 0);
CHECK(std::isnan(calculate_c.value(expr1, 2.)));
CHECK(std::isnan(calculate_c.eval(expr1, xp, 0)));
calculate_c.free(expr2);
calculate_c.free(expr1);
}
SECTION("Error checking") {
Expression expr;
double values[] = {1., 2.};
char error[64];
calculate_c.create("x", "", error);
CHECK(std::string(error) == std::string("Undefined symbol 'x'"));
expr = calculate_c.create("x", "x", error);
CHECK(std::string(error) == std::string(""));
calculate_c.evaluate(expr, values, 2, error);
CHECK(std::string(error) == std::string("Variables mismatch"));
calculate_c.parse("x", error);
CHECK(std::string(error) == std::string(""));
calculate_c.parse("hypot(x, y)", error);
CHECK(std::string(error) == std::string(""));
calculate_c.parse("+", error);
CHECK(std::string(error) == std::string("Syntax error"));
}
SECTION("Query functions") {
char output[4096];
calculate_c.constants(output);
CHECK(strlen(output) == 14);
calculate_c.operators(output);
CHECK(strlen(output) == 14);
calculate_c.functions(output);
CHECK(strlen(output) == 256);
}
}
<|endoftext|> |
<commit_before>#include <copy_on_write.hpp>
namespace value {
hi_printable small_rval ()
{ return hi_printable(); }
const hi_printable small_const_rval ()
{ return hi_printable(); }
hi_printable & small_lval ()
{
static hi_printable retval;
return retval;
}
const hi_printable & small_const_lval ()
{
static const hi_printable retval = {};
return retval;
}
large_printable large_rval ()
{ return large_printable(); }
const large_printable large_const_rval ()
{ return large_printable(); }
large_printable & large_lval ()
{
static large_printable retval;
return retval;
}
const large_printable & large_const_lval ()
{
static const large_printable retval;
return retval;
}
}
namespace erased_value {
erased_type small_rval ()
{ return erased_type(hi_printable()); }
const erased_type small_const_rval ()
{ return erased_type(hi_printable()); }
erased_type & small_lval ()
{
static erased_type retval{hi_printable()};
return retval;
}
const erased_type & small_const_lval ()
{
static const erased_type retval{hi_printable()};
return retval;
}
erased_type large_rval ()
{ return erased_type(large_printable()); }
const erased_type large_const_rval ()
{ return erased_type(large_printable()); }
erased_type & large_lval ()
{
static erased_type retval{large_printable()};
return retval;
}
const erased_type & large_const_lval ()
{
static const erased_type retval{large_printable()};
return retval;
}
}
#define BOOST_TEST_MODULE TypeErasure
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(hand_rolled)
{
value::small_lval();
value::small_const_lval();
value::large_lval();
value::large_const_lval();
erased_value::small_lval();
erased_value::small_const_lval();
erased_value::large_lval();
erased_value::large_const_lval();
reset_allocations();
std::cout << "sizeof(erased_type) = " << sizeof(erased_type) << "\n";
// CONSTRUCTION
{
hi_printable value_small_rval = value::small_rval();
reset_allocations();
erased_type value_small_rval_move(std::move(value_small_rval));
const std::size_t value_small_rval_move_count = allocations();
reset_allocations();
const hi_printable value_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type value_small_const_rval_copy(std::move(value_small_const_rval));
const std::size_t value_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_small_lval_copy(value::small_lval());
const std::size_t value_small_lval_copy_count = allocations();
reset_allocations();
erased_type value_small_const_lval_copy(value::small_const_lval());
const std::size_t value_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_lval_copy_count);
BOOST_CHECK(value_small_rval_move_count == value_small_lval_copy_count);
}
{
large_printable value_large_rval = value::large_rval();
reset_allocations();
erased_type value_large_rval_move(std::move(value_large_rval));
const std::size_t value_large_rval_move_count = allocations();
reset_allocations();
const large_printable value_large_const_rval = value::large_const_rval();
reset_allocations();
erased_type value_large_const_rval_copy(std::move(value_large_const_rval));
const std::size_t value_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_large_lval_copy(value::large_lval());
const std::size_t value_large_lval_copy_count = allocations();
reset_allocations();
erased_type value_large_const_lval_copy(value::large_const_lval());
const std::size_t value_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_lval_copy_count);
BOOST_CHECK(value_large_rval_move_count < value_large_lval_copy_count);
}
{
erased_type erased_small_rval = erased_value::small_rval();
reset_allocations();
erased_type erased_small_rval_move(std::move(erased_small_rval));
const std::size_t erased_small_rval_move_count = allocations();
reset_allocations();
const erased_type erased_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type erased_small_const_rval_copy(std::move(erased_small_const_rval));
const std::size_t erased_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_small_lval_copy(erased_value::small_lval());
const std::size_t erased_small_lval_copy_count = allocations();
reset_allocations();
erased_type erased_small_const_lval_copy(erased_value::small_const_lval());
const std::size_t erased_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_lval_copy_count);
BOOST_CHECK(erased_small_rval_move_count < erased_small_lval_copy_count);
}
{
erased_type erased_large_rval = erased_value::large_rval();
reset_allocations();
erased_type erased_large_rval_move(std::move(erased_large_rval));
const std::size_t erased_large_rval_move_count = allocations();
reset_allocations();
const erased_type erased_large_const_rval = erased_value::large_const_rval();
reset_allocations();
erased_type erased_large_const_rval_copy(std::move(erased_large_const_rval));
const std::size_t erased_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_large_lval_copy(erased_value::large_lval());
const std::size_t erased_large_lval_copy_count = allocations();
reset_allocations();
erased_type erased_large_const_lval_copy(erased_value::large_const_lval());
const std::size_t erased_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_lval_copy_count);
BOOST_CHECK(erased_large_rval_move_count < erased_large_lval_copy_count);
}
// ASSIGNMENT
{
hi_printable value_small_rval = value::small_rval();
reset_allocations();
erased_type value_small_rval_move = std::move(value_small_rval);
const std::size_t value_small_rval_move_count = allocations();
reset_allocations();
const hi_printable value_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type value_small_const_rval_copy = std::move(value_small_const_rval);
const std::size_t value_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_small_lval_copy = value::small_lval();
const std::size_t value_small_lval_copy_count = allocations();
reset_allocations();
erased_type value_small_const_lval_copy = value::small_const_lval();
const std::size_t value_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_lval_copy_count);
BOOST_CHECK(value_small_rval_move_count == value_small_lval_copy_count);
}
{
large_printable value_large_rval = value::large_rval();
reset_allocations();
erased_type value_large_rval_move = std::move(value_large_rval);
const std::size_t value_large_rval_move_count = allocations();
reset_allocations();
const large_printable value_large_const_rval = value::large_const_rval();
reset_allocations();
erased_type value_large_const_rval_copy = std::move(value_large_const_rval);
const std::size_t value_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_large_lval_copy = value::large_lval();
const std::size_t value_large_lval_copy_count = allocations();
reset_allocations();
erased_type value_large_const_lval_copy = value::large_const_lval();
const std::size_t value_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_lval_copy_count);
BOOST_CHECK(value_large_rval_move_count < value_large_lval_copy_count);
}
{
erased_type erased_small_rval = erased_value::small_rval();
reset_allocations();
erased_type erased_small_rval_move = std::move(erased_small_rval);
const std::size_t erased_small_rval_move_count = allocations();
reset_allocations();
const erased_type erased_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type erased_small_const_rval_copy = std::move(erased_small_const_rval);
const std::size_t erased_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_small_lval_copy = erased_value::small_lval();
const std::size_t erased_small_lval_copy_count = allocations();
reset_allocations();
erased_type erased_small_const_lval_copy = erased_value::small_const_lval();
const std::size_t erased_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_lval_copy_count);
BOOST_CHECK(erased_small_rval_move_count < erased_small_lval_copy_count);
}
{
erased_type erased_large_rval = erased_value::large_rval();
reset_allocations();
erased_type erased_large_rval_move = std::move(erased_large_rval);
const std::size_t erased_large_rval_move_count = allocations();
reset_allocations();
const erased_type erased_large_const_rval = erased_value::large_const_rval();
reset_allocations();
erased_type erased_large_const_rval_copy = std::move(erased_large_const_rval);
const std::size_t erased_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_large_lval_copy = erased_value::large_lval();
const std::size_t erased_large_lval_copy_count = allocations();
reset_allocations();
erased_type erased_large_const_lval_copy = erased_value::large_const_lval();
const std::size_t erased_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_lval_copy_count);
BOOST_CHECK(erased_large_rval_move_count < erased_large_lval_copy_count);
}
}
<commit_msg>Add Emacs modeline to top of coverage.ipp.<commit_after>// -*- C++ -*-
#include <copy_on_write.hpp>
namespace value {
hi_printable small_rval ()
{ return hi_printable(); }
const hi_printable small_const_rval ()
{ return hi_printable(); }
hi_printable & small_lval ()
{
static hi_printable retval;
return retval;
}
const hi_printable & small_const_lval ()
{
static const hi_printable retval = {};
return retval;
}
large_printable large_rval ()
{ return large_printable(); }
const large_printable large_const_rval ()
{ return large_printable(); }
large_printable & large_lval ()
{
static large_printable retval;
return retval;
}
const large_printable & large_const_lval ()
{
static const large_printable retval;
return retval;
}
}
namespace erased_value {
erased_type small_rval ()
{ return erased_type(hi_printable()); }
const erased_type small_const_rval ()
{ return erased_type(hi_printable()); }
erased_type & small_lval ()
{
static erased_type retval{hi_printable()};
return retval;
}
const erased_type & small_const_lval ()
{
static const erased_type retval{hi_printable()};
return retval;
}
erased_type large_rval ()
{ return erased_type(large_printable()); }
const erased_type large_const_rval ()
{ return erased_type(large_printable()); }
erased_type & large_lval ()
{
static erased_type retval{large_printable()};
return retval;
}
const erased_type & large_const_lval ()
{
static const erased_type retval{large_printable()};
return retval;
}
}
#define BOOST_TEST_MODULE TypeErasure
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(hand_rolled)
{
value::small_lval();
value::small_const_lval();
value::large_lval();
value::large_const_lval();
erased_value::small_lval();
erased_value::small_const_lval();
erased_value::large_lval();
erased_value::large_const_lval();
reset_allocations();
std::cout << "sizeof(erased_type) = " << sizeof(erased_type) << "\n";
// CONSTRUCTION
{
hi_printable value_small_rval = value::small_rval();
reset_allocations();
erased_type value_small_rval_move(std::move(value_small_rval));
const std::size_t value_small_rval_move_count = allocations();
reset_allocations();
const hi_printable value_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type value_small_const_rval_copy(std::move(value_small_const_rval));
const std::size_t value_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_small_lval_copy(value::small_lval());
const std::size_t value_small_lval_copy_count = allocations();
reset_allocations();
erased_type value_small_const_lval_copy(value::small_const_lval());
const std::size_t value_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_lval_copy_count);
BOOST_CHECK(value_small_rval_move_count == value_small_lval_copy_count);
}
{
large_printable value_large_rval = value::large_rval();
reset_allocations();
erased_type value_large_rval_move(std::move(value_large_rval));
const std::size_t value_large_rval_move_count = allocations();
reset_allocations();
const large_printable value_large_const_rval = value::large_const_rval();
reset_allocations();
erased_type value_large_const_rval_copy(std::move(value_large_const_rval));
const std::size_t value_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_large_lval_copy(value::large_lval());
const std::size_t value_large_lval_copy_count = allocations();
reset_allocations();
erased_type value_large_const_lval_copy(value::large_const_lval());
const std::size_t value_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_lval_copy_count);
BOOST_CHECK(value_large_rval_move_count < value_large_lval_copy_count);
}
{
erased_type erased_small_rval = erased_value::small_rval();
reset_allocations();
erased_type erased_small_rval_move(std::move(erased_small_rval));
const std::size_t erased_small_rval_move_count = allocations();
reset_allocations();
const erased_type erased_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type erased_small_const_rval_copy(std::move(erased_small_const_rval));
const std::size_t erased_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_small_lval_copy(erased_value::small_lval());
const std::size_t erased_small_lval_copy_count = allocations();
reset_allocations();
erased_type erased_small_const_lval_copy(erased_value::small_const_lval());
const std::size_t erased_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_lval_copy_count);
BOOST_CHECK(erased_small_rval_move_count < erased_small_lval_copy_count);
}
{
erased_type erased_large_rval = erased_value::large_rval();
reset_allocations();
erased_type erased_large_rval_move(std::move(erased_large_rval));
const std::size_t erased_large_rval_move_count = allocations();
reset_allocations();
const erased_type erased_large_const_rval = erased_value::large_const_rval();
reset_allocations();
erased_type erased_large_const_rval_copy(std::move(erased_large_const_rval));
const std::size_t erased_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_large_lval_copy(erased_value::large_lval());
const std::size_t erased_large_lval_copy_count = allocations();
reset_allocations();
erased_type erased_large_const_lval_copy(erased_value::large_const_lval());
const std::size_t erased_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_lval_copy_count);
BOOST_CHECK(erased_large_rval_move_count < erased_large_lval_copy_count);
}
// ASSIGNMENT
{
hi_printable value_small_rval = value::small_rval();
reset_allocations();
erased_type value_small_rval_move = std::move(value_small_rval);
const std::size_t value_small_rval_move_count = allocations();
reset_allocations();
const hi_printable value_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type value_small_const_rval_copy = std::move(value_small_const_rval);
const std::size_t value_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_small_lval_copy = value::small_lval();
const std::size_t value_small_lval_copy_count = allocations();
reset_allocations();
erased_type value_small_const_lval_copy = value::small_const_lval();
const std::size_t value_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_small_lval_copy_count, value_small_const_lval_copy_count);
BOOST_CHECK(value_small_rval_move_count == value_small_lval_copy_count);
}
{
large_printable value_large_rval = value::large_rval();
reset_allocations();
erased_type value_large_rval_move = std::move(value_large_rval);
const std::size_t value_large_rval_move_count = allocations();
reset_allocations();
const large_printable value_large_const_rval = value::large_const_rval();
reset_allocations();
erased_type value_large_const_rval_copy = std::move(value_large_const_rval);
const std::size_t value_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type value_large_lval_copy = value::large_lval();
const std::size_t value_large_lval_copy_count = allocations();
reset_allocations();
erased_type value_large_const_lval_copy = value::large_const_lval();
const std::size_t value_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(value_large_lval_copy_count, value_large_const_lval_copy_count);
BOOST_CHECK(value_large_rval_move_count < value_large_lval_copy_count);
}
{
erased_type erased_small_rval = erased_value::small_rval();
reset_allocations();
erased_type erased_small_rval_move = std::move(erased_small_rval);
const std::size_t erased_small_rval_move_count = allocations();
reset_allocations();
const erased_type erased_small_const_rval = value::small_const_rval();
reset_allocations();
erased_type erased_small_const_rval_copy = std::move(erased_small_const_rval);
const std::size_t erased_small_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_small_lval_copy = erased_value::small_lval();
const std::size_t erased_small_lval_copy_count = allocations();
reset_allocations();
erased_type erased_small_const_lval_copy = erased_value::small_const_lval();
const std::size_t erased_small_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_small_lval_copy_count, erased_small_const_lval_copy_count);
BOOST_CHECK(erased_small_rval_move_count < erased_small_lval_copy_count);
}
{
erased_type erased_large_rval = erased_value::large_rval();
reset_allocations();
erased_type erased_large_rval_move = std::move(erased_large_rval);
const std::size_t erased_large_rval_move_count = allocations();
reset_allocations();
const erased_type erased_large_const_rval = erased_value::large_const_rval();
reset_allocations();
erased_type erased_large_const_rval_copy = std::move(erased_large_const_rval);
const std::size_t erased_large_const_rval_copy_count = allocations();
reset_allocations();
erased_type erased_large_lval_copy = erased_value::large_lval();
const std::size_t erased_large_lval_copy_count = allocations();
reset_allocations();
erased_type erased_large_const_lval_copy = erased_value::large_const_lval();
const std::size_t erased_large_const_lval_copy_count = allocations();
reset_allocations();
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_rval_copy_count);
BOOST_CHECK_EQUAL(erased_large_lval_copy_count, erased_large_const_lval_copy_count);
BOOST_CHECK(erased_large_rval_move_count < erased_large_lval_copy_count);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/cpu.h"
#include <intrin.h>
#include <string>
namespace base {
CPU::CPU()
: type_(0),
family_(0),
model_(0),
stepping_(0),
ext_model_(0),
ext_family_(0),
cpu_vendor_("unknown") {
Initialize();
}
void CPU::Initialize() {
int cpu_info[4] = {-1};
char cpu_string[0x20];
// __cpuid with an InfoType argument of 0 returns the number of
// valid Ids in CPUInfo[0] and the CPU identification string in
// the other three array elements. The CPU identification string is
// not in linear order. The code below arranges the information
// in a human readable form.
//
// More info can be found here:
// http://msdn.microsoft.com/en-us/library/hskdteyh.aspx
__cpuid(cpu_info, 0);
int num_ids = cpu_info[0];
memset(cpu_string, 0, sizeof(cpu_string));
*(reinterpret_cast<int*>(cpu_string)) = cpu_info[1];
*(reinterpret_cast<int*>(cpu_string+4)) = cpu_info[3];
*(reinterpret_cast<int*>(cpu_string+8)) = cpu_info[2];
// Interpret CPU feature information.
__cpuid(cpu_info, 1);
stepping_ = cpu_info[0] & 0xf;
model_ = (cpu_info[0] >> 4) & 0xf;
family_ = (cpu_info[0] >> 8) & 0xf;
type_ = (cpu_info[0] >> 12) & 0x3;
ext_model_ = (cpu_info[0] >> 16) & 0xf;
ext_family_ = (cpu_info[0] >> 20) & 0xff;
cpu_vendor_ = cpu_string;
}
} // namespace base
<commit_msg>Check for cpu items before assuming it will work.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/cpu.h"
#include <intrin.h>
#include <string>
namespace base {
CPU::CPU()
: type_(0),
family_(0),
model_(0),
stepping_(0),
ext_model_(0),
ext_family_(0),
cpu_vendor_("unknown") {
Initialize();
}
void CPU::Initialize() {
int cpu_info[4] = {-1};
char cpu_string[0x20];
// __cpuid with an InfoType argument of 0 returns the number of
// valid Ids in CPUInfo[0] and the CPU identification string in
// the other three array elements. The CPU identification string is
// not in linear order. The code below arranges the information
// in a human readable form.
//
// More info can be found here:
// http://msdn.microsoft.com/en-us/library/hskdteyh.aspx
__cpuid(cpu_info, 0);
int num_ids = cpu_info[0];
memset(cpu_string, 0, sizeof(cpu_string));
*(reinterpret_cast<int*>(cpu_string)) = cpu_info[1];
*(reinterpret_cast<int*>(cpu_string+4)) = cpu_info[3];
*(reinterpret_cast<int*>(cpu_string+8)) = cpu_info[2];
// Interpret CPU feature information.
if (num_ids > 0) {
__cpuid(cpu_info, 1);
stepping_ = cpu_info[0] & 0xf;
model_ = (cpu_info[0] >> 4) & 0xf;
family_ = (cpu_info[0] >> 8) & 0xf;
type_ = (cpu_info[0] >> 12) & 0x3;
ext_model_ = (cpu_info[0] >> 16) & 0xf;
ext_family_ = (cpu_info[0] >> 20) & 0xff;
cpu_vendor_ = cpu_string;
}
}
} // namespace base
<|endoftext|> |
<commit_before>/*
* IceWM - Colored cursor support
*
* Copyright (C) 2002 The Authors of IceWM
*
* initially by Oleastre
* C++ style implementation by tbf
*/
#include "config.h"
#include "yfull.h"
#include "default.h"
#include "yxapp.h"
#include "wmprog.h"
#ifndef LITE
#include <limits.h>
#include <stdlib.h>
#ifdef CONFIG_XPM
#include "X11/xpm.h"
#endif
#ifdef CONFIG_IMLIB
#include <Imlib.h>
extern ImlibData *hImlib;
#endif
#include "ycursor.h"
#include "intl.h"
class YCursorPixmap {
public:
YCursorPixmap(upath path);
~YCursorPixmap();
Pixmap pixmap() const { return fPixmap; }
Pixmap mask() const { return fMask; }
const XColor& background() const { return fBackground; }
const XColor& foreground() const { return fForeground; }
#ifdef CONFIG_XPM
bool isValid() { return fValid; }
unsigned int width() const { return fAttributes.width; }
unsigned int height() const { return fAttributes.height; }
unsigned int hotspotX() const { return fAttributes.x_hotspot; }
unsigned int hotspotY() const { return fAttributes.y_hotspot; }
#endif
#ifdef CONFIG_IMLIB
bool isValid() { return fImage; }
unsigned int width() const { return fImage ? fImage->rgb_width : 0; }
unsigned int height() const { return fImage ? fImage->rgb_height : 0; }
unsigned int hotspotX() const { return fHotspotX; }
unsigned int hotspotY() const { return fHotspotY; }
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
bool isValid() { return false; }
unsigned int width() const { return 0; }
unsigned int height() const { return 0; }
unsigned int hotspotX() const { return fHotspotX; }
unsigned int hotspotY() const { return fHotspotY; }
#endif
private:
Pixmap fPixmap, fMask;
XColor fForeground, fBackground;
#ifdef CONFIG_XPM
bool fValid;
XpmAttributes fAttributes;
#endif
#ifdef CONFIG_IMLIB
unsigned int fHotspotX, fHotspotY;
ImlibImage *fImage;
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
bool fValid;
unsigned int fHotspotX, fHotspotY;
#endif
operator bool();
};
#ifdef CONFIG_XPM // ================== use libXpm to load the cursor pixmap ===
YCursorPixmap::YCursorPixmap(upath path): fValid(false) {
fAttributes.colormap = xapp->colormap();
fAttributes.closeness = 65535;
fAttributes.valuemask = XpmColormap|XpmCloseness|
XpmReturnPixels|XpmSize|XpmHotspot;
fAttributes.x_hotspot = 0;
fAttributes.y_hotspot = 0;
int const rc(XpmReadFileToPixmap(xapp->display(), desktop->handle(),
(char *)REDIR_ROOT(cstring(path.path()).c_str()), // !!!
&fPixmap, &fMask, &fAttributes));
if (rc != XpmSuccess)
warn(_("Loading of pixmap \"%s\" failed: %s"),
path, XpmGetErrorString(rc));
else if (fAttributes.npixels != 2)
warn(_("Invalid cursor pixmap: \"%s\" contains too many unique colors"),
path);
else {
fBackground.pixel = fAttributes.pixels[0];
fForeground.pixel = fAttributes.pixels[1];
XQueryColor(xapp->display(), xapp->colormap(), &fBackground);
XQueryColor(xapp->display(), xapp->colormap(), &fForeground);
fValid = true;
}
}
#endif
#ifdef CONFIG_IMLIB // ================= use Imlib to load the cursor pixmap ===
YCursorPixmap::YCursorPixmap(upath path):
fHotspotX(0), fHotspotY(0)
{
cstring cs(path.path());
fImage = Imlib_load_image(hImlib, (char *)REDIR_ROOT(cs.c_str()));
if (fImage == NULL) {
warn(_("Loading of pixmap \"%s\" failed"), cs.c_str());
return;
}
Imlib_render(hImlib, fImage, fImage->rgb_width, fImage->rgb_height);
fPixmap = (Pixmap)Imlib_move_image(hImlib, fImage);
fMask = (Pixmap)Imlib_move_mask(hImlib, fImage);
struct Pixel { // ----------------- find the background/foreground color ---
bool operator!= (const Pixel& o) {
return (r != o.r || g != o.g || b != o.b); }
bool operator!= (const ImlibColor& o) {
return (r != o.r || g != o.g || b != o.b); }
unsigned char r,g,b;
};
Pixel fg = { 0xFF, 0xFF, 0xFF }, bg = { 0, 0, 0 }, *pp((Pixel*) fImage->rgb_data);
unsigned ccnt = 0;
for (unsigned n = fImage->rgb_width * fImage->rgb_height; n > 0; --n, ++pp)
if (*pp != fImage->shape_color)
switch (ccnt) {
case 0:
bg = *pp; ++ccnt;
break;
case 1:
if (*pp != bg) { fg = *pp; ++ccnt; }
break;
default:
if (*pp != bg && *pp != fg) {
warn(_("Invalid cursor pixmap: \"%s\" contains too "
"much unique colors"), cs.c_str());
Imlib_destroy_image(hImlib, fImage);
fImage = NULL;
return;
}
}
fForeground.red = fg.r << 8; // -- alloc the background/foreground color ---
fForeground.green = fg.g << 8;
fForeground.blue = fg.b << 8;
XAllocColor(xapp->display(), xapp->colormap(), &fForeground);
fBackground.red = bg.r << 8;
fBackground.green = bg.g << 8;
fBackground.blue = bg.b << 8;
XAllocColor(xapp->display(), xapp->colormap(), &fBackground);
// ----------------- find the hotspot by reading the xpm header manually ---
FILE *xpm = fopen((char *)REDIR_ROOT(cs.c_str()), "rb");
if (xpm == NULL)
warn(_("BUG? Imlib was able to read \"%s\""), cs.c_str());
else {
while (fgetc(xpm) != '{'); // ----- that's safe since imlib accepted ---
for (int c;;) switch (c = fgetc(xpm)) {
case '/':
if ((c == fgetc(xpm)) == '/') // ------ eat C++ line comment ---
while (fgetc(xpm) != '\n');
else { // -------------------------------- eat block comment ---
int pc; do { pc = c; c = fgetc(xpm); }
while (c != '/' && pc != '*');
}
break;
case ' ': case '\t': case '\r': case '\n': // ------- whitespace ---
break;
case '"': { // ---------------------------------- the XPM header ---
unsigned foo; int x, y;
int tokens = fscanf(xpm, "%u %u %u %u %u %u",
&foo, &foo, &foo, &foo, &x, &y);
if (tokens == 6) {
fHotspotX = (x < 0 ? 0 : x);
fHotspotY = (y < 0 ? 0 : y);
} else if (tokens != 4)
warn(_("BUG? Malformed XPM header but Imlib "
"was able to parse \"%s\""), cs.c_str());
fclose(xpm);
return;
}
default:
if (c == EOF)
warn(_("BUG? Unexpected end of XPM file but Imlib "
"was able to parse \"%s\""), cs.c_str());
else
warn(_("BUG? Unexpected characted but Imlib "
"was able to parse \"%s\""), cs.c_str());
fclose(xpm);
return;
}
}
}
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
YCursorPixmap::YCursorPixmap(upath path):
fHotspotX(0), fHotspotY(0)
{
}
#endif
YCursorPixmap::~YCursorPixmap() {
XFreePixmap(xapp->display(), fPixmap);
XFreePixmap(xapp->display(), fMask);
#ifdef CONFIG_XPM
XpmFreeAttributes(&fAttributes);
#endif
#ifdef CONFIG_IMLIB
Imlib_destroy_image(hImlib, fImage);
#endif
}
#endif
YCursor::~YCursor() {
if(fOwned && fCursor && app)
XFreeCursor(xapp->display(), fCursor);
}
#ifndef LITE
static Pixmap createMask(int w, int h) {
return XCreatePixmap(xapp->display(), desktop->handle(), w, h, 1);
}
void YCursor::load(upath path) {
YCursorPixmap pixmap(path);
if (pixmap.isValid()) { // ============ convert coloured pixmap into a bilevel one ===
Pixmap bilevel(createMask(pixmap.width(), pixmap.height()));
// -------------------------- figure out which plane we have to copy ---
unsigned long pmask(1 << (xapp->depth() - 1));
if (pixmap.foreground().pixel &&
pixmap.foreground().pixel != pixmap.background().pixel)
while ((pixmap.foreground().pixel & pmask) ==
(pixmap.background().pixel & pmask)) pmask >>= 1;
else if (pixmap.background().pixel)
while ((pixmap.background().pixel & pmask) == 0) pmask >>= 1;
GC gc; XGCValues gcv; // ------ copy one plane by using a bilevel GC ---
gcv.function = (pixmap.foreground().pixel &&
(pixmap.foreground().pixel & pmask))
? GXcopyInverted : GXcopy;
gc = XCreateGC (xapp->display(), bilevel, GCFunction, &gcv);
XFillRectangle(xapp->display(), bilevel, gc, 0, 0,
pixmap.width(), pixmap.height());
XCopyPlane(xapp->display(), pixmap.pixmap(), bilevel, gc,
0, 0, pixmap.width(), pixmap.height(), 0, 0, pmask);
XFreeGC(xapp->display(), gc);
// ==================================== allocate a new pixmap cursor ===
XColor foreground(pixmap.foreground()),
background(pixmap.background());
fCursor = XCreatePixmapCursor(xapp->display(),
bilevel, pixmap.mask(),
&foreground, &background,
pixmap.hotspotX(), pixmap.hotspotY());
XFreePixmap(xapp->display(), bilevel);
}
}
#endif
#ifndef LITE
void YCursor::load(upath name, unsigned int fallback) {
#else
void YCursor::load(upath /*name*/, unsigned int fallback) {
#endif
if(fCursor && fOwned)
XFreeCursor(xapp->display(), fCursor);
#ifndef LITE
char const *cursors = "cursors/";
ref<YResourcePaths> paths = YResourcePaths::subdirs(cursors);
for (int i = 0; i < paths->getCount(); i++) {
upath path = paths->getPath(i)->joinPath(cursors, name);
if (path.fileExists())
load(path.path());
}
if (fCursor == None)
#endif
fCursor = XCreateFontCursor(xapp->display(), fallback);
fOwned = true;
}
<commit_msg>fix crash in cursor code (which is broken)<commit_after>/*
* IceWM - Colored cursor support
*
* Copyright (C) 2002 The Authors of IceWM
*
* initially by Oleastre
* C++ style implementation by tbf
*/
#include "config.h"
#include "yfull.h"
#include "default.h"
#include "yxapp.h"
#include "wmprog.h"
#ifndef LITE
#include <limits.h>
#include <stdlib.h>
#ifdef CONFIG_XPM
#include "X11/xpm.h"
#endif
#ifdef CONFIG_IMLIB
#include <Imlib.h>
extern ImlibData *hImlib;
#endif
#include "ycursor.h"
#include "intl.h"
class YCursorPixmap {
public:
YCursorPixmap(upath path);
~YCursorPixmap();
Pixmap pixmap() const { return fPixmap; }
Pixmap mask() const { return fMask; }
const XColor& background() const { return fBackground; }
const XColor& foreground() const { return fForeground; }
#ifdef CONFIG_XPM
bool isValid() { return fValid; }
unsigned int width() const { return fAttributes.width; }
unsigned int height() const { return fAttributes.height; }
unsigned int hotspotX() const { return fAttributes.x_hotspot; }
unsigned int hotspotY() const { return fAttributes.y_hotspot; }
#endif
#ifdef CONFIG_IMLIB
bool isValid() { return fImage; }
unsigned int width() const { return fImage ? fImage->rgb_width : 0; }
unsigned int height() const { return fImage ? fImage->rgb_height : 0; }
unsigned int hotspotX() const { return fHotspotX; }
unsigned int hotspotY() const { return fHotspotY; }
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
bool isValid() { return false; }
unsigned int width() const { return 0; }
unsigned int height() const { return 0; }
unsigned int hotspotX() const { return fHotspotX; }
unsigned int hotspotY() const { return fHotspotY; }
#endif
private:
Pixmap fPixmap, fMask;
XColor fForeground, fBackground;
#ifdef CONFIG_XPM
bool fValid;
XpmAttributes fAttributes;
#endif
#ifdef CONFIG_IMLIB
unsigned int fHotspotX, fHotspotY;
ImlibImage *fImage;
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
bool fValid;
unsigned int fHotspotX, fHotspotY;
#endif
operator bool();
};
#ifdef CONFIG_XPM // ================== use libXpm to load the cursor pixmap ===
YCursorPixmap::YCursorPixmap(upath path): fValid(false) {
fAttributes.colormap = xapp->colormap();
fAttributes.closeness = 65535;
fAttributes.valuemask = XpmColormap|XpmCloseness|
XpmReturnPixels|XpmSize|XpmHotspot;
fAttributes.x_hotspot = 0;
fAttributes.y_hotspot = 0;
int const rc(XpmReadFileToPixmap(xapp->display(), desktop->handle(),
(char *)REDIR_ROOT(cstring(path.path()).c_str()), // !!!
&fPixmap, &fMask, &fAttributes));
if (rc != XpmSuccess)
warn(_("Loading of pixmap \"%s\" failed: %s"),
path, XpmGetErrorString(rc));
else if (fAttributes.npixels != 2)
warn(_("Invalid cursor pixmap: \"%s\" contains too many unique colors"),
path);
else {
fBackground.pixel = fAttributes.pixels[0];
fForeground.pixel = fAttributes.pixels[1];
XQueryColor(xapp->display(), xapp->colormap(), &fBackground);
XQueryColor(xapp->display(), xapp->colormap(), &fForeground);
fValid = true;
}
}
#endif
#ifdef CONFIG_IMLIB // ================= use Imlib to load the cursor pixmap ===
YCursorPixmap::YCursorPixmap(upath path):
fHotspotX(0), fHotspotY(0)
{
cstring cs(path.path());
fImage = Imlib_load_image(hImlib, (char *)REDIR_ROOT(cs.c_str()));
if (fImage == NULL) {
warn(_("Loading of pixmap \"%s\" failed"), cs.c_str());
return;
}
Imlib_render(hImlib, fImage, fImage->rgb_width, fImage->rgb_height);
fPixmap = (Pixmap)Imlib_move_image(hImlib, fImage);
fMask = (Pixmap)Imlib_move_mask(hImlib, fImage);
struct Pixel { // ----------------- find the background/foreground color ---
bool operator!= (const Pixel& o) {
return (r != o.r || g != o.g || b != o.b); }
bool operator!= (const ImlibColor& o) {
return (r != o.r || g != o.g || b != o.b); }
unsigned char r,g,b;
};
Pixel fg = { 0xFF, 0xFF, 0xFF }, bg = { 0, 0, 0 }, *pp((Pixel*) fImage->rgb_data);
unsigned ccnt = 0;
for (unsigned n = fImage->rgb_width * fImage->rgb_height; n > 0; --n, ++pp)
if (*pp != fImage->shape_color)
switch (ccnt) {
case 0:
bg = *pp; ++ccnt;
break;
case 1:
if (*pp != bg) { fg = *pp; ++ccnt; }
break;
default:
if (*pp != bg && *pp != fg) {
warn(_("Invalid cursor pixmap: \"%s\" contains too "
"much unique colors"), cs.c_str());
Imlib_destroy_image(hImlib, fImage);
fImage = NULL;
return;
}
}
fForeground.red = fg.r << 8; // -- alloc the background/foreground color ---
fForeground.green = fg.g << 8;
fForeground.blue = fg.b << 8;
XAllocColor(xapp->display(), xapp->colormap(), &fForeground);
fBackground.red = bg.r << 8;
fBackground.green = bg.g << 8;
fBackground.blue = bg.b << 8;
XAllocColor(xapp->display(), xapp->colormap(), &fBackground);
// ----------------- find the hotspot by reading the xpm header manually ---
FILE *xpm = fopen((char *)REDIR_ROOT(cs.c_str()), "rb");
if (xpm == NULL)
warn(_("BUG? Imlib was able to read \"%s\""), cs.c_str());
else {
while (fgetc(xpm) != '{'); // ----- that's safe since imlib accepted ---
for (int c;;) switch (c = fgetc(xpm)) {
case '/':
if ((c == fgetc(xpm)) == '/') // ------ eat C++ line comment ---
while (fgetc(xpm) != '\n');
else { // -------------------------------- eat block comment ---
int pc; do { pc = c; c = fgetc(xpm); }
while (c != '/' && pc != '*');
}
break;
case ' ': case '\t': case '\r': case '\n': // ------- whitespace ---
break;
case '"': { // ---------------------------------- the XPM header ---
unsigned foo; int x, y;
int tokens = fscanf(xpm, "%u %u %u %u %u %u",
&foo, &foo, &foo, &foo, &x, &y);
if (tokens == 6) {
fHotspotX = (x < 0 ? 0 : x);
fHotspotY = (y < 0 ? 0 : y);
} else if (tokens != 4)
warn(_("BUG? Malformed XPM header but Imlib "
"was able to parse \"%s\""), cs.c_str());
fclose(xpm);
return;
}
default:
if (c == EOF)
warn(_("BUG? Unexpected end of XPM file but Imlib "
"was able to parse \"%s\""), cs.c_str());
else
warn(_("BUG? Unexpected characted but Imlib "
"was able to parse \"%s\""), cs.c_str());
fclose(xpm);
return;
}
}
}
#endif
#ifdef CONFIG_GDK_PIXBUF_XLIB
YCursorPixmap::YCursorPixmap(upath path):
fHotspotX(0), fHotspotY(0), fPixmap(None), fMask(None)
{
}
#endif
YCursorPixmap::~YCursorPixmap() {
if (fPixmap != None)
XFreePixmap(xapp->display(), fPixmap);
if (fMask != None)
XFreePixmap(xapp->display(), fMask);
#ifdef CONFIG_XPM
XpmFreeAttributes(&fAttributes);
#endif
#ifdef CONFIG_IMLIB
Imlib_destroy_image(hImlib, fImage);
#endif
}
#endif
YCursor::~YCursor() {
if(fOwned && fCursor && app)
XFreeCursor(xapp->display(), fCursor);
}
#ifndef LITE
static Pixmap createMask(int w, int h) {
return XCreatePixmap(xapp->display(), desktop->handle(), w, h, 1);
}
void YCursor::load(upath path) {
YCursorPixmap pixmap(path);
if (pixmap.isValid()) { // ============ convert coloured pixmap into a bilevel one ===
Pixmap bilevel(createMask(pixmap.width(), pixmap.height()));
// -------------------------- figure out which plane we have to copy ---
unsigned long pmask(1 << (xapp->depth() - 1));
if (pixmap.foreground().pixel &&
pixmap.foreground().pixel != pixmap.background().pixel)
while ((pixmap.foreground().pixel & pmask) ==
(pixmap.background().pixel & pmask)) pmask >>= 1;
else if (pixmap.background().pixel)
while ((pixmap.background().pixel & pmask) == 0) pmask >>= 1;
GC gc; XGCValues gcv; // ------ copy one plane by using a bilevel GC ---
gcv.function = (pixmap.foreground().pixel &&
(pixmap.foreground().pixel & pmask))
? GXcopyInverted : GXcopy;
gc = XCreateGC (xapp->display(), bilevel, GCFunction, &gcv);
XFillRectangle(xapp->display(), bilevel, gc, 0, 0,
pixmap.width(), pixmap.height());
XCopyPlane(xapp->display(), pixmap.pixmap(), bilevel, gc,
0, 0, pixmap.width(), pixmap.height(), 0, 0, pmask);
XFreeGC(xapp->display(), gc);
// ==================================== allocate a new pixmap cursor ===
XColor foreground(pixmap.foreground()),
background(pixmap.background());
fCursor = XCreatePixmapCursor(xapp->display(),
bilevel, pixmap.mask(),
&foreground, &background,
pixmap.hotspotX(), pixmap.hotspotY());
XFreePixmap(xapp->display(), bilevel);
}
}
#endif
#ifndef LITE
void YCursor::load(upath name, unsigned int fallback) {
#else
void YCursor::load(upath /*name*/, unsigned int fallback) {
#endif
if(fCursor && fOwned)
XFreeCursor(xapp->display(), fCursor);
#ifndef LITE
char const *cursors = "cursors/";
ref<YResourcePaths> paths = YResourcePaths::subdirs(cursors);
for (int i = 0; i < paths->getCount(); i++) {
upath path = paths->getPath(i)->joinPath(cursors, name);
if (path.fileExists())
load(path.path());
}
if (fCursor == None)
#endif
fCursor = XCreateFontCursor(xapp->display(), fallback);
fOwned = true;
}
<|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>
#include <silicium/transform_if_initialized.hpp>
#include <silicium/empty.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/for_each.hpp>
namespace bf
{
enum class command
{
ptr_increment,
ptr_decrement,
value_increment,
value_decrement,
write,
read,
begin_loop,
end_loop
};
boost::optional<command> detect_command(char c)
{
switch (c)
{
case '>': return command::ptr_increment;
case '<': return command::ptr_decrement;
case '+': return command::value_increment;
case '-': return command::value_decrement;
case '.': return command::write;
case ',': return command::read;
case '[': return command::begin_loop;
case ']': return command::end_loop;
default: return boost::none;
}
}
template <class Source>
auto scan(Source &&source)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::conditional_transformer<command, typename std::decay<Source>::type, boost::optional<command>(*)(char)>
#endif
{
return Si::transform_if_initialized(std::forward<Source>(source), detect_command);
}
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
# define SILICIUM_CAPTURE(x) = (x)
#else
# define SILICIUM_CAPTURE(x)
#endif
template <class Input, class CommandRange, class MemoryRange>
auto execute(Input &&input, CommandRange const &program, MemoryRange &memory, std::size_t original_pointer)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::coroutine_observable<char>
#endif
{
return Si::make_coroutine<char>([
input SILICIUM_CAPTURE(std::forward<Input>(input)),
program,
&memory,
original_pointer
](Si::yield_context<char> &yield) mutable
{
auto pointer = original_pointer;
for (command com : program)
{
switch (com)
{
case command::ptr_increment:
++pointer;
if (pointer == boost::size(memory))
{
pointer = 0;
}
break;
case command::ptr_decrement:
if (pointer == 0)
{
pointer = boost::size(memory) - 1;
}
else
{
--pointer;
}
break;
case command::value_increment:
++memory[pointer];
break;
case command::value_decrement:
--memory[pointer];
break;
case command::write:
yield(static_cast<char>(memory[pointer]));
break;
case command::read:
{
auto in = yield.get_one(input);
if (!in)
{
return;
}
memory[pointer] = *in;
break;
}
}
}
});
}
}
BOOST_AUTO_TEST_CASE(bf_empty)
{
Si::empty<char> source;
std::array<char, 1> memory{{}};
auto interpreter = bf::execute(source, boost::iterator_range<bf::command const *>(), memory, 0);
auto done = Si::for_each(std::move(interpreter), [](char output)
{
boost::ignore_unused_variable_warning(output);
BOOST_FAIL("no output expected");
});
done.start();
}
<commit_msg>brainfuck hello world works<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/optional.hpp>
#include <silicium/transform_if_initialized.hpp>
#include <silicium/empty.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/source.hpp>
#include <silicium/for_each.hpp>
#include <boost/unordered_map.hpp>
#include <unordered_map>
namespace bf
{
enum class command
{
ptr_increment,
ptr_decrement,
value_increment,
value_decrement,
write,
read,
begin_loop,
end_loop
};
boost::optional<command> detect_command(char c)
{
switch (c)
{
case '>': return command::ptr_increment;
case '<': return command::ptr_decrement;
case '+': return command::value_increment;
case '-': return command::value_decrement;
case '.': return command::write;
case ',': return command::read;
case '[': return command::begin_loop;
case ']': return command::end_loop;
default: return boost::none;
}
}
template <class Source>
auto scan(Source &&source)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::conditional_transformer<command, typename std::decay<Source>::type, boost::optional<command>(*)(char)>
#endif
{
return Si::transform_if_initialized(std::forward<Source>(source), detect_command);
}
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
# define SILICIUM_CAPTURE(x) = (x)
#else
# define SILICIUM_CAPTURE(x)
#endif
template <class CommandRange>
typename CommandRange::const_iterator find_loop_begin(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const end_)
{
using std::begin;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), end_));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = end_;
for (;;)
{
assert(i != begin(program));
--i;
if (*i == command::end_loop)
{
++current_depth;
}
else if (*i == command::begin_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), end_), i));
return i;
}
template <class CommandRange>
typename CommandRange::const_iterator find_loop_end(
CommandRange const &program,
std::unordered_map<std::ptrdiff_t, typename CommandRange::const_iterator> &cached_loop_pairs,
typename CommandRange::const_iterator const begin)
{
using std::end;
auto cached = cached_loop_pairs.find(std::distance(program.begin(), begin));
if (cached != end(cached_loop_pairs))
{
return cached->second;
}
std::size_t current_depth = 0;
auto i = begin;
for (;; ++i)
{
assert(i != end(program));
if (*i == command::begin_loop)
{
++current_depth;
}
else if (*i == command::end_loop)
{
if (current_depth == 0)
{
break;
}
--current_depth;
}
}
assert(current_depth == 0);
cached_loop_pairs.insert(std::make_pair(std::distance(program.begin(), begin), i));
return i;
}
template <class Input, class CommandRange, class MemoryRange>
auto execute(Input &&input, CommandRange const &program, MemoryRange &memory, std::size_t original_pointer)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> Si::coroutine_observable<char>
#endif
{
return Si::make_coroutine<char>([
input SILICIUM_CAPTURE(std::forward<Input>(input)),
program,
&memory,
original_pointer
](Si::yield_context<char> &yield) mutable
{
std::unordered_map<std::ptrdiff_t, CommandRange::const_iterator> loop_pairs;
auto pointer = original_pointer;
auto pc = boost::begin(program);
for (; pc != boost::end(program);)
{
switch (*pc)
{
case command::ptr_increment:
++pointer;
if (pointer == boost::size(memory))
{
pointer = 0;
}
++pc;
break;
case command::ptr_decrement:
if (pointer == 0)
{
pointer = boost::size(memory) - 1;
}
else
{
--pointer;
}
++pc;
break;
case command::value_increment:
++memory[pointer];
++pc;
break;
case command::value_decrement:
--memory[pointer];
++pc;
break;
case command::write:
yield(static_cast<char>(memory[pointer]));
++pc;
break;
case command::read:
{
auto in = yield.get_one(input);
if (!in)
{
return;
}
memory[pointer] = *in;
++pc;
break;
}
case command::begin_loop:
if (memory[pointer])
{
++pc;
}
else
{
pc = find_loop_end(program, loop_pairs, pc) + 1;
}
break;
case command::end_loop:
if (memory[pointer])
{
pc = find_loop_begin(program, loop_pairs, pc) + 1;
}
else
{
++pc;
}
break;
}
}
});
}
}
namespace Si
{
template <class Element, class Source>
struct source_observable
{
using element_type = Element;
source_observable()
{
}
explicit source_observable(Source source)
: source(std::move(source))
{
}
void async_get_one(observer<Element> &receiver)
{
boost::optional<Element> value = Si::get(source);
if (value)
{
receiver.got_element(std::move(*value));
}
else
{
receiver.ended();
}
}
private:
Source source;
};
template <class Element, class Source>
auto make_source_observable(Source &&source)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> source_observable<Element, typename std::decay<Source>::type>
#endif
{
return source_observable<Element, typename std::decay<Source>::type>(std::forward<Source>(source));
}
}
BOOST_AUTO_TEST_CASE(bf_empty)
{
Si::empty<char> input;
std::array<char, 1> memory{{}};
auto interpreter = bf::execute(input, boost::iterator_range<bf::command const *>(), memory, 0);
auto done = Si::for_each(std::move(interpreter), [](char output)
{
boost::ignore_unused_variable_warning(output);
BOOST_FAIL("no output expected");
});
done.start();
}
namespace
{
template <class CharSource>
std::vector<bf::command> scan_all(CharSource code)
{
std::vector<bf::command> result;
auto decoded = Si::make_transforming_source<boost::optional<bf::command>>(code, bf::detect_command);
for (;;)
{
auto cmd = Si::get(decoded);
if (!cmd)
{
break;
}
if (*cmd)
{
result.emplace_back(**cmd);
}
}
return result;
}
}
BOOST_AUTO_TEST_CASE(bf_hello_world)
{
std::string const hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
std::array<char, 100> memory{ {} };
Si::empty<char> input;
auto interpreter = bf::execute(input, scan_all(Si::make_container_source(hello_world)), memory, 0);
std::string printed;
auto done = Si::for_each(std::move(interpreter), [&printed](char output)
{
printed.push_back(output);
});
done.start();
BOOST_CHECK_EQUAL("Hello World!\n", printed);
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////
//
// Under windows, when multiple versions of maya are installed,
// maya2egg can accidentally use the wrong version of OpenMaya.dll.
// This small wrapper program alters your PATH and MAYA_LOCATION
// environment variables in order to ensure that maya2egg finds the
// right DLLs.
//
// To use this wrapper, maya2egg.exe must be renamed to
// maya2egg-wrapped.exe. Then, this wrapper program must be
// installed as maya2egg.exe
//
///////////////////////////////////////////////////////////////////////
#ifndef MAYAVERSION
#error You must define the symbol MAYAVERSION when compiling mayawrapper.
#endif
#define QUOTESTR(x) #x
#define TOSTRING(x) QUOTESTR(x)
#define _CRT_SECURE_NO_DEPRECATE 1
#ifdef _WIN32
#include <windows.h>
#include <winuser.h>
#include <process.h>
#else
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define _putenv putenv
#endif
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <signal.h>
#define PATH_MAX 1024
#ifdef __APPLE__
// This is for _NSGetExecutablePath().
#include <mach-o/dyld.h>
#endif
#if defined(_WIN32)
struct { char *ver, *key; } reg_keys[] = {
{ "MAYA6", "6.0" },
{ "MAYA65", "6.5" },
{ "MAYA7", "7.0" },
{ "MAYA8", "8.0" },
{ "MAYA85", "8.5" },
{ "MAYA2008", "2008" },
{ "MAYA2009", "2009" },
{ 0, 0 },
};
char *getRegistryKey(char *ver) {
for (int i=0; reg_keys[i].ver != 0; i++) {
if (strcmp(reg_keys[i].ver, ver)==0) {
return reg_keys[i].key;
}
}
return 0;
}
void getMayaLocation(char *ver, char *loc)
{
char fullkey[1024], *developer;
HKEY hkey; DWORD size, dtype; LONG res; int dev, hive;
for (dev=0; dev<3; dev++) {
switch (dev) {
case 0: developer="Alias|Wavefront"; break;
case 1: developer="Alias"; break;
case 2: developer="Autodesk"; break;
}
sprintf(fullkey, "SOFTWARE\\%s\\Maya\\%s\\Setup\\InstallPath", developer, ver);
for (hive=0; hive<2; hive++) {
loc[0] = 0;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fullkey, 0, KEY_READ | (hive ? 256:0), &hkey);
if (res == ERROR_SUCCESS) {
size=1024;
res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", NULL, &dtype, (LPBYTE)loc, &size);
if ((res == ERROR_SUCCESS)&&(dtype == REG_SZ)) {
loc[size] = 0;
return;
} else {
loc[0] = 0;
}
RegCloseKey(hkey);
}
}
}
}
void getWrapperName(char *prog)
{
DWORD res;
res = GetModuleFileName(NULL, prog, 1000);
if (res == 0) {
prog[0] = 0;
return;
}
int len = strlen(prog);
if (_stricmp(prog+len-4, ".exe")) {
prog[0] = 0;
return;
}
prog[len-4] = 0;
}
#elif defined(__APPLE__)
void getWrapperName(char *prog)
{
char *pathbuf = new char[PATH_MAX];
uint32_t *bufsize;
if (_NSGetExecutablePath(pathbuf, bufsize) == 0) {
strcpy(prog, pathbuf);
}
delete[] pathbuf;
}
#else
void getWrapperName(char *prog)
{
char readlinkbuf[PATH_MAX];
int pathlen = readlink("/proc/self/exe", readlinkbuf, PATH_MAX-1);
if (pathlen > 0) {
readlinkbuf[pathlen] = 0;
strcpy(prog, readlinkbuf);
}
}
#endif
int main(int argc, char **argv)
{
char loc[1024], prog[1024];
char *path, *env1, *env2, *env3, *env4; int len;
#ifdef _WIN32
STARTUPINFO si; PROCESS_INFORMATION pi;
char *key, *cmd;
key = getRegistryKey(TOSTRING(MAYAVERSION));
if (key == 0) {
printf("MayaWrapper: unknown maya version %s\n", TOSTRING(MAYAVERSION));
exit(1);
}
getMayaLocation(key, loc);
if (loc[0]==0) {
printf("Cannot locate %s - it does not appear to be installed\n", TOSTRING(MAYAVERSION));
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
strcat(prog, "-wrapped.exe");
#else
loc = getenv("MAYA_LOCATION");
if (loc == NULL) {
printf("$MAYA_LOCATION is not set!\n");
exit(1);
}
struct stat st;
if(stat(loc, &st) != 0) {
printf("The directory referred to by $MAYA_LOCATION does not exist!\n");
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
strcat(prog, "-wrapped");
#endif
path = getenv("PATH");
if (path == 0) path = "";
#ifdef _WIN32
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s\\bin;%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(300 + 5*strlen(loc));
sprintf(env3, "PYTHONPATH=%s\\bin;%s\\Python;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\site-packages", loc, loc, loc, loc, loc);
#else
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s/bin:%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s", loc);
env4 = (char*)malloc(100 + strlen(loc));
sprintf(env4, "LD_LIBRARY_PATH=%s/lib", loc);
_putenv(env3);
_putenv(env4);
#endif
_putenv(env1);
_putenv(env2);
// _putenv(env3);
#ifdef _WIN32
cmd = GetCommandLine();
memset(&si, 0, sizeof(si));
si.cb = sizeof(STARTUPINFO);
if (CreateProcess(prog, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#else
if (execvp(prog, argv) == 0) {
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#endif
}
<commit_msg>Fix from Ben Chang<commit_after>///////////////////////////////////////////////////////////////////////
//
// Under windows, when multiple versions of maya are installed,
// maya2egg can accidentally use the wrong version of OpenMaya.dll.
// This small wrapper program alters your PATH and MAYA_LOCATION
// environment variables in order to ensure that maya2egg finds the
// right DLLs.
//
// To use this wrapper, maya2egg.exe must be renamed to
// maya2egg-wrapped.exe. Then, this wrapper program must be
// installed as maya2egg.exe
//
///////////////////////////////////////////////////////////////////////
#ifndef MAYAVERSION
#error You must define the symbol MAYAVERSION when compiling mayawrapper.
#endif
#define QUOTESTR(x) #x
#define TOSTRING(x) QUOTESTR(x)
#define _CRT_SECURE_NO_DEPRECATE 1
#ifdef _WIN32
#include <windows.h>
#include <winuser.h>
#include <process.h>
#else
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define _putenv putenv
#endif
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <signal.h>
#define PATH_MAX 1024
#ifdef __APPLE__
// This is for _NSGetExecutablePath().
#include <mach-o/dyld.h>
#endif
#if defined(_WIN32)
struct { char *ver, *key; } reg_keys[] = {
{ "MAYA6", "6.0" },
{ "MAYA65", "6.5" },
{ "MAYA7", "7.0" },
{ "MAYA8", "8.0" },
{ "MAYA85", "8.5" },
{ "MAYA2008", "2008" },
{ "MAYA2009", "2009" },
{ 0, 0 },
};
char *getRegistryKey(char *ver) {
for (int i=0; reg_keys[i].ver != 0; i++) {
if (strcmp(reg_keys[i].ver, ver)==0) {
return reg_keys[i].key;
}
}
return 0;
}
void getMayaLocation(char *ver, char *loc)
{
char fullkey[1024], *developer;
HKEY hkey; DWORD size, dtype; LONG res; int dev, hive;
for (dev=0; dev<3; dev++) {
switch (dev) {
case 0: developer="Alias|Wavefront"; break;
case 1: developer="Alias"; break;
case 2: developer="Autodesk"; break;
}
sprintf(fullkey, "SOFTWARE\\%s\\Maya\\%s\\Setup\\InstallPath", developer, ver);
for (hive=0; hive<2; hive++) {
loc[0] = 0;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, fullkey, 0, KEY_READ | (hive ? 256:0), &hkey);
if (res == ERROR_SUCCESS) {
size=1024;
res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", NULL, &dtype, (LPBYTE)loc, &size);
if ((res == ERROR_SUCCESS)&&(dtype == REG_SZ)) {
loc[size] = 0;
return;
} else {
loc[0] = 0;
}
RegCloseKey(hkey);
}
}
}
}
void getWrapperName(char *prog)
{
DWORD res;
res = GetModuleFileName(NULL, prog, 1000);
if (res == 0) {
prog[0] = 0;
return;
}
int len = strlen(prog);
if (_stricmp(prog+len-4, ".exe")) {
prog[0] = 0;
return;
}
prog[len-4] = 0;
}
#elif defined(__APPLE__)
void getWrapperName(char *prog)
{
char *pathbuf = new char[PATH_MAX];
uint32_t *bufsize;
if (_NSGetExecutablePath(pathbuf, bufsize) == 0) {
strcpy(prog, pathbuf);
}
delete[] pathbuf;
}
#else
void getWrapperName(char *prog)
{
char readlinkbuf[PATH_MAX];
int pathlen = readlink("/proc/self/exe", readlinkbuf, PATH_MAX-1);
if (pathlen > 0) {
readlinkbuf[pathlen] = 0;
strcpy(prog, readlinkbuf);
}
}
#endif
int main(int argc, char **argv)
{
char loc[1024], prog[1024];
char *path, *env1, *env2, *env3, *env4; int len;
#ifdef _WIN32
STARTUPINFO si; PROCESS_INFORMATION pi;
char *key, *cmd;
key = getRegistryKey(TOSTRING(MAYAVERSION));
if (key == 0) {
printf("MayaWrapper: unknown maya version %s\n", TOSTRING(MAYAVERSION));
exit(1);
}
getMayaLocation(key, loc);
if (loc[0]==0) {
printf("Cannot locate %s - it does not appear to be installed\n", TOSTRING(MAYAVERSION));
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
strcat(prog, "-wrapped.exe");
#else
if (getenv("MAYA_LOCATION") == NULL) {
printf("$MAYA_LOCATION is not set!\n");
exit(1);
} else {
strcpy(loc, getenv("MAYA_LOCATION"));
}
struct stat st;
if(stat(loc, &st) != 0) {
printf("The directory referred to by $MAYA_LOCATION does not exist!\n");
exit(1);
}
getWrapperName(prog);
if (prog[0]==0) {
printf("mayaWrapper cannot determine its own filename (bug)\n");
exit(1);
}
strcat(prog, "-wrapped");
#endif
path = getenv("PATH");
if (path == 0) path = "";
#ifdef _WIN32
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s\\bin;%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(300 + 5*strlen(loc));
sprintf(env3, "PYTHONPATH=%s\\bin;%s\\Python;%s\\Python\\DLLs;%s\\Python\\lib;%s\\Python\\lib\\site-packages", loc, loc, loc, loc, loc);
#else
env1 = (char*)malloc(100 + strlen(loc) + strlen(path));
sprintf(env1, "PATH=%s/bin:%s", loc, path);
env2 = (char*)malloc(100 + strlen(loc));
sprintf(env2, "MAYA_LOCATION=%s", loc);
env3 = (char*)malloc(100 + strlen(loc));
sprintf(env3, "PYTHONHOME=%s", loc);
env4 = (char*)malloc(100 + strlen(loc));
sprintf(env4, "LD_LIBRARY_PATH=%s/lib", loc);
_putenv(env3);
_putenv(env4);
#endif
_putenv(env1);
_putenv(env2);
// _putenv(env3);
#ifdef _WIN32
cmd = GetCommandLine();
memset(&si, 0, sizeof(si));
si.cb = sizeof(STARTUPINFO);
if (CreateProcess(prog, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#else
if (execvp(prog, argv) == 0) {
exit(0);
} else {
printf("Could not launch %s\n", prog);
exit(1);
}
#endif
}
<|endoftext|> |
<commit_before>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include "phiostats.h"
#include "phIO.h"
#include "phstream.h" //for makeRStream and makeGRStream
#include "syncio.h"
#include "posixio.h"
#include "streamio.h"
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if( argc != 2 ) {
fprintf(stderr, "Usage: %s <numSyncFiles>\n",argv[0]);
MPI_Finalize();
return 1;
}
const char* phrase = "number of fishes";
const char* type = "double";
const char* iotype = "binary";
int zero = 0;
int one = 1;
int numFish = 0;
double fishWeight = 1.23;
int nfiles = 1;
int ppf = size/nfiles;
const char* filename[2] = {"water-dat.", "water.dat."};
rstream rs = makeRStream();
phio_fp file[3];
const char* modes[3]={"syncio", "posixio", "streamio"};
syncio_setup_write(nfiles, one, ppf, &(file[0]));
posixio_setup(&(file[1]), 'w');
streamio_setup_r(&(file[2]), rs, 'w');
fprintf(stderr, "%s\n" ,"Outside loop 1.0");
for(int i=0; i<3; i++) {
fprintf(stderr, "%s\n" ,"Within the i loop");
if(!rank) fprintf(stderr, "%s\n", modes[i]);
fprintf(stderr, "%s\n" ,"Before phastaio");
phastaio_initStats();
fprintf(stderr, "%s\n" ,"Opening files with ", filename[i], file[i] );
phio_openfile(filename[i], file[i]);
fprintf(stderr, "%s\n" ,"Entering for loop for ", atoi(argv[1]) );
// const char* str = "Number of times "+ nfiles ;
for (int j = 0; j < nfiles ; j++) {
fprintf(stderr,"%s\n", "Inside loop");
fprintf(stderr,"%d\n",atoi(argv[1]));
const char* str = "Number of times " +j;
fprintf(stderr,"%s\n", "Writing the header time - " );
fprintf(stderr,"%d\n",zero);
fprintf(stderr,"%d\n",one);
fprintf(stderr,"%s\n",file[i] );
fprintf(stderr,"%s\n","Should have printed the file" );
fprintf(stderr,"%s\n",type);
fprintf(stderr,"%s\n",iotype);
fprintf(stderr,"%s\n","Opening the file" );
phio_writeheader(file[i], str, &zero, &one, &zero, type, iotype);
fprintf(stderr,"%s\n",str );
fprintf(stderr,"%d\n",j );
fprintf(stderr,"%s\n", "Writing the data block time - ");
fprintf(stderr,"%d\n",j );
phio_writedatablock(file[i], str, &fishWeight, &zero, type, iotype);
}
phio_closefile(file[i]);
phastaio_printStats();
}
syncio_setup_read(nfiles, &(file[0]));
posixio_setup(&(file[1]), 'r');
streamio_setup_r(&(file[2]), rs, 'r');
for(int i=0; i<3; i++) {
if(!rank) fprintf(stderr, "%s\n", modes[i]);
phastaio_initStats();
phio_openfile(filename[i], file[i]);
//Str was added
// const char* str = "Number of times "+ nfiles ;
// for (int j = 0; j < nfiles ; j++) {
phio_readheader(file[i], phrase, &numFish, &one, type, iotype);
// phio_readheader(file[i], str, &numFish, &one, type, iotype);
//Changing argument from file[i] to file[j]
assert(!numFish);
phio_readdatablock(file[i], phrase, &fishWeight, &numFish, type, iotype);
// phio_readdatablock(file[i], str, &fishWeight, &numFish, type, iotype);
assert(fishWeight == 1.23);
phio_closefile(file[i]);
phastaio_printStats();
}
MPI_Finalize();
return 0;
}
<commit_msg>Step 5 working version with several print statements and nfiles = 1<commit_after>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include "phiostats.h"
#include "phIO.h"
#include "phstream.h" //for makeRStream and makeGRStream
#include "syncio.h"
#include "posixio.h"
#include "streamio.h"
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if( argc != 2 ) {
fprintf(stderr, "Usage: %s <numSyncFiles>\n",argv[0]);
MPI_Finalize();
return 1;
}
const char* phrase = "number of fishes";
const char* type = "double";
const char* iotype = "binary";
int zero = 0;
int one = 1;
int numFish = 0;
double fishWeight = 1.23;
int nfiles = 1;
int ppf = size/nfiles;
const char* filename[2] = {"water-dat.", "water.dat."};
rstream rs = makeRStream();
phio_fp file[3];
const char* modes[3]={"syncio", "posixio", "streamio"};
syncio_setup_write(nfiles, one, ppf, &(file[0]));
posixio_setup(&(file[1]), 'w');
streamio_setup_r(&(file[2]), rs, 'w');
fprintf(stderr, "%s\n" ,"Outside loop 1.0");
for(int i=0; i<3; i++) {
fprintf(stderr, "%s\n" ,"Within the i loop");
if(!rank) fprintf(stderr, "%s\n", modes[i]);
fprintf(stderr, "%s\n" ,"Before phastaio");
phastaio_initStats();
fprintf(stderr, "%s\n" ,"Opening files with ", filename[i], file[i] );
phio_openfile(filename[i], file[i]);
fprintf(stderr, "%s\n" ,"Entering for loop for ", atoi(argv[1]) );
// const char* str = "Number of times "+ nfiles ;
for (int j = 0; j < nfiles ; j++) {
fprintf(stderr,"%s\n", "Inside loop");
//fprintf(stderr,"%d\n",atoi(argv[1]));
const char* str = "Number of times " +j;
fprintf(stderr,"%s\n", "Writing the header time - " );
fprintf(stderr,"%d\n","Printing the int zero");
fprintf(stderr,"%d\n",zero);
fprintf(stderr,"%d\n","Printing the int one");
fprintf(stderr,"%d\n",one);
fprintf(stderr,"%d\n","Printing the file[i]");
fprintf(stderr,"%s\n",file[i] );
fprintf(stderr,"%s\n","Should have printed the file" );
fprintf(stderr,"%d\n","Printing the const char type, this is set to double");
fprintf(stderr,"%s\n",type);
fprintf(stderr,"%d\n","Printing the const char iotype, this is set to binary");
fprintf(stderr,"%s\n",iotype);
fprintf(stderr,"%s\n","Opening the file" );
phio_writeheader(file[i], str, &zero, &one, &zero, type, iotype);
fprintf(stderr,"%d\n","Printing the created string after writing the header ");
fprintf(stderr,"%s\n",str );
fprintf(stderr,"%s\n","Printing the loop number" );
fprintf(stderr,"%d\n",j );
fprintf(stderr,"%s\n", "Writing the data block time - ");
// fprintf(stderr,"%d\n",j );
phio_writedatablock(file[i], str, &fishWeight, &zero, type, iotype);
fprintf(stderr,"%s\n","Printing the file[i] after writing the data block" );
fprintf(stderr,"%s\n",file[i] );
fprintf(stderr,"%s\n","Printing the string that has been created " );
fprintf(stderr,"%s\n",str );
}
phio_closefile(file[i]);
phastaio_printStats();
}
syncio_setup_read(nfiles, &(file[0]));
posixio_setup(&(file[1]), 'r');
streamio_setup_r(&(file[2]), rs, 'r');
for(int i=0; i<3; i++) {
if(!rank) fprintf(stderr, "%s\n", modes[i]);
phastaio_initStats();
phio_openfile(filename[i], file[i]);
//Str was added
// const char* str = "Number of times "+ nfiles ;
// for (int j = 0; j < nfiles ; j++) {
phio_readheader(file[i], phrase, &numFish, &one, type, iotype);
// phio_readheader(file[i], str, &numFish, &one, type, iotype);
//Changing argument from file[i] to file[j]
assert(!numFish);
phio_readdatablock(file[i], phrase, &fishWeight, &numFish, type, iotype);
// phio_readdatablock(file[i], str, &fishWeight, &numFish, type, iotype);
assert(fishWeight == 1.23);
phio_closefile(file[i]);
phastaio_printStats();
}
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include "phiostats.h"
#include "phIO.h"
#include "phstream.h" //for makeRStream and makeGRStream
#include "syncio.h"
#include "posixio.h"
#include "streamio.h"
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if( argc != 2 ) {
fprintf(stderr, "Usage: %s <numSyncFiles>\n",argv[0]);
MPI_Finalize();
return 1;
}
const char* phrase = "number of fishes";
const char* type = "double";
const char* iotype = "binary";
double blockArray[4] = {2.0,4.0,8.0,16.0};
int blockEntries = 4;
int one = 1;
int numFish = 0;
double fishWeight = 1.23;
int nfiles = 1;
int ppf = size/nfiles;
const char* filename[2] = {"water-dat.", "water.dat."};
rstream rs = makeRStream();
phio_fp file[3];
const char* modes[3]={"syncio", "posixio", "streamio"};
syncio_setup_write(nfiles, one, ppf, &(file[0]));
posixio_setup(&(file[1]), 'w');
streamio_setup_r(&(file[2]), rs, 'w');
fprintf(stderr, "%s\n" ,"Outside loop 1.0");
for(int i=0; i<3; i++) {
fprintf(stderr, "%s\n" ,"Within the i loop");
if(!rank) fprintf(stderr, "%s\n", modes[i]);
fprintf(stderr, "%s\n" ,"Before phastaio");
phastaio_initStats();
fprintf(stderr, "%s\n" ,"Opening files with ", filename[i], file[i] );
phio_openfile(filename[i], file[i]);
fprintf(stderr, "%s\n" ,"Entering for loop for ", atoi(argv[1]) );
// const char* str = "Number of times "+ nfiles ;
for (int j = 0; j < 2 ; j++) {
fprintf(stderr,"%s\n", "Inside loop");
//fprintf(stderr,"%d\n",atoi(argv[1]));
const char* str = "Number of times " + 10;
fprintf(stderr,"%s\n", "Writing the header time - " );
fprintf(stderr,"%s\n","Printing the int zero");
fprintf(stderr,"%d\n",zero);
fprintf(stderr,"%s\n","Printing the int one");
fprintf(stderr,"%d\n",one);
fprintf(stderr,"%s\n","Printing the file[i]");
fprintf(stderr,"%s\n",file[i] );
fprintf(stderr,"%s\n","Should have printed the file" );
fprintf(stderr,"%s\n","Printing the const char type, this is set to double");
fprintf(stderr,"%s\n",type);
fprintf(stderr,"%s\n","Printing the const char iotype, this is set to binary");
fprintf(stderr,"%s\n",iotype);
fprintf(stderr,"%s\n","Opening the file" );
phio_writeheader(file[i], str, &blockEntries, &one, &blockEntries, "integer", iotype);
fprintf(stderr,"%s\n","Printing the created string after writing the header ");
fprintf(stderr,"%s\n",str );
fprintf(stderr,"%s\n","Printing the loop number" );
fprintf(stderr,"%d\n",j );
fprintf(stderr,"%s\n", "Writing the data block time - ");
// fprintf(stderr,"%d\n",j );
phio_writedatablock(file[i], str, blockArray, &blockEntries, type, iotype);
fprintf(stderr,"%s\n","Printing the file[i] after writing the data block" );
fprintf(stderr,"%s\n",file[i] );
fprintf(stderr,"%s\n","Printing the string that has been created " );
fprintf(stderr,"%s\n",str );
}
phio_closefile(file[i]);
phastaio_printStats();
}
syncio_setup_read(nfiles, &(file[0]));
posixio_setup(&(file[1]), 'r');
streamio_setup_r(&(file[2]), rs, 'r');
for(int i=0; i<3; i++) {
if(!rank) fprintf(stderr, "%s\n", modes[i]);
phastaio_initStats();
phio_openfile(filename[i], file[i]);
//Str was added
// const char* str = "Number of times "+ nfiles ;
// for (int j = 0; j < nfiles ; j++) {
phio_readheader(file[i], phrase, &numFish, &one, type, iotype);
// phio_readheader(file[i], str, &numFish, &one, type, iotype);
//Changing argument from file[i] to file[j]
assert(!numFish);
phio_readdatablock(file[i], phrase, &fishWeight, &numFish, type, iotype);
// phio_readdatablock(file[i], str, &fishWeight, &numFish, type, iotype);
assert(fishWeight == 1.23);
phio_closefile(file[i]);
phastaio_printStats();
}
MPI_Finalize();
return 0;
}
<commit_msg>Cleaned up print statements and printed variables<commit_after>#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include "phiostats.h"
#include "phIO.h"
#include "phstream.h" //for makeRStream and makeGRStream
#include "syncio.h"
#include "posixio.h"
#include "streamio.h"
int main(int argc, char* argv[]) {
MPI_Init(&argc,&argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if( argc != 2 ) {
fprintf(stderr, "Usage: %s <numSyncFiles>\n",argv[0]);
MPI_Finalize();
return 1;
}
const char* phrase = "number of fishes";
const char* type = "double";
const char* iotype = "binary";
double blockArray[4] = {2.0,4.0,8.0,16.0};
int blockEntries = 4;
int one = 1;
int zero = 0;
int numFish = 0;
double fishWeight = 1.23;
int nfiles = 1;
int ppf = size/nfiles;
const char* filename[3] = {"water-dat.", "water.dat.", "water."};
rstream rs = makeRStream();
phio_fp file[3];
const char* modes[3]={"syncio", "posixio", "streamio"};
fprintf(stderr,"nfiles %d\n", nfiles);
fprintf(stderr,"ppf %d\n", ppf);
syncio_setup_write(nfiles, one, ppf, &(file[0]));
posixio_setup(&(file[1]), 'w');
streamio_setup_r(&(file[2]), rs, 'w');//Check this _r? work
fprintf(stderr, "%s\n" ,"Outside loop 1.0");
for(int i=0; i<3; i++) {
fprintf(stderr, "%s\n" ,"Within the i loop");
if(!rank) fprintf(stderr, "%s\n", modes[i]);
fprintf(stderr, "%s\n" ,"Before phastaio");
phastaio_initStats();
fprintf(stderr, "Opening files with %s\n", filename[i]);
phio_openfile(filename[i], file[i]);
char str [50];
int n;
for (int j = 0; j < 2 ; j++) {
fprintf(stderr,"%s\n", "Inside loop");
n = sprintf(str, " Number of times %d ", j);
assert(n);
fprintf(stderr,"str \'%s\'\n", str);
fprintf(stderr,"Printing the int zero %d\n", zero);
fprintf(stderr,"Printing the int one %d\n", one);
fprintf(stderr,"blockentries %d\n",blockEntries);
fprintf(stderr,"Printing the const char type %s\n", type);
fprintf(stderr,"Printing the const char iotype %s\n", iotype);
fprintf(stderr,"Calling writeheader\n");
phio_writeheader(file[i], str, &blockEntries, &one, &blockEntries, "integer", iotype);
fprintf(stderr,"Done calling writeheader\n");
fprintf(stderr,"Calling writedatablock\n");
phio_writedatablock(file[i], str, blockArray, &blockEntries, type, iotype);
fprintf(stderr,"Done Calling writedatablock\n");
}
phio_closefile(file[i]);
phastaio_printStats();
}
syncio_setup_read(nfiles, &(file[0]));
posixio_setup(&(file[1]), 'r');
streamio_setup_r(&(file[2]), rs, 'r');
for(int i=0; i<3; i++) {
if(!rank) fprintf(stderr, "%s\n", modes[i]);
phastaio_initStats();
phio_openfile(filename[i], file[i]);
//Str was added
// const char* str = "Number of times "+ nfiles ;
// for (int j = 0; j < nfiles ; j++) {
phio_readheader(file[i], phrase, &numFish, &one, type, iotype);
// phio_readheader(file[i], str, &numFish, &one, type, iotype);
//Changing argument from file[i] to file[j]
assert(!numFish);
phio_readdatablock(file[i], phrase, &fishWeight, &numFish, type, iotype);
// phio_readdatablock(file[i], str, &fishWeight, &numFish, type, iotype);
assert(fishWeight == 1.23);
phio_closefile(file[i]);
phastaio_printStats();
}
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>#include "libs/catch/include/catch.hpp"
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <memory>
#include <random>
#include <thread>
#include <iostream>
#include "src/client.h"
#include "src/config.h"
#include "src/file.h"
void aux_read_test_worker(std::shared_ptr<giga::File> file, std::shared_ptr<std::atomic<int>> result) {
int res = 0;
std::shared_ptr<giga::Client> c = file->open();
res += (file->get_n_clients() > 0);
std::shared_ptr<std::string> buffer (new std::string);
res += (c->get_pos() == 0);
res += (c->read(buffer, 0) == 0);
res += (buffer->compare("") == 0);
res += (c->read(buffer, 1) == 1);
res += (buffer->compare("a") == 0);
res += (c->read(buffer, 10) == 4);
res += (buffer->compare("bcd\n") == 0);
res += (c->read(buffer, 1) == 0);
res += (buffer->compare("") == 0);
res += (file->get_n_clients() > 0);
file->close(c);
try {
c->read(buffer, 1);
} catch(const giga::InvalidOperation& e) {
res++;
}
int expected = 12;
*result += (int) (res == expected);
}
TEST_CASE("concurrent|read") {
int n_threads = 4;
int n_attempts = 50000;
std::shared_ptr<std::atomic<int>> result (new std::atomic<int>());
for(int attempt = 0; attempt < n_attempts; attempt++) {
std::shared_ptr<std::string> buffer (new std::string);
std::vector<std::thread> threads;
std::shared_ptr<giga::File> file (new giga::File("test/files/five.txt", "ro", std::shared_ptr<giga::Config> (new giga::Config(2, 2, 1))));
for(int i = 0; i < n_threads; i++) {
threads.push_back(std::thread (aux_read_test_worker, file, result));
}
while(file->get_n_clients()) {
// cf. http://bit.ly/1pLvXct
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
for(int i = 0; i < n_threads; i++) {
threads.at(i).join();
}
}
REQUIRE(*result == n_attempts * n_threads);
}
<commit_msg>concurrency test changes<commit_after>#include "libs/catch/include/catch.hpp"
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <memory>
#include <random>
#include <thread>
#include <iostream>
#include "src/client.h"
#include "src/config.h"
#include "src/file.h"
void aux_read_test_worker(std::shared_ptr<giga::File> file, std::shared_ptr<std::atomic<int>> result) {
int res = 0;
std::shared_ptr<giga::Client> c = file->open();
res += (file->get_n_clients() > 0);
std::shared_ptr<std::string> buffer (new std::string);
res += (c->get_pos() == 0);
res += (c->read(buffer, 0) == 0);
res += (buffer->compare("") == 0);
res += (c->read(buffer, 1) == 1);
res += (buffer->compare("a") == 0);
res += (c->read(buffer, 10) == 4);
res += (buffer->compare("bcd\n") == 0);
res += (c->read(buffer, 1) == 0);
res += (buffer->compare("") == 0);
res += (file->get_n_clients() > 0);
file->close(c);
try {
c->read(buffer, 1);
} catch(const giga::InvalidOperation& e) {
res++;
}
int expected = 12;
*result += (int) (res == expected);
}
TEST_CASE("concurrent|read") {
int n_threads = 50;
int n_attempts = 50000;
std::shared_ptr<std::atomic<int>> result (new std::atomic<int>());
for(int attempt = 0; attempt < n_attempts; attempt++) {
std::shared_ptr<std::string> buffer (new std::string);
std::vector<std::thread> threads;
std::shared_ptr<giga::File> file (new giga::File("test/files/five.txt", "ro", std::shared_ptr<giga::Config> (new giga::Config(2, 2, 1))));
for(int i = 0; i < n_threads; i++) {
threads.push_back(std::thread (aux_read_test_worker, file, result));
}
while(file->get_n_clients()) {
// cf. http://bit.ly/1pLvXct
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
for(int i = 0; i < n_threads; i++) {
threads.at(i).join();
}
}
REQUIRE(*result == n_attempts * n_threads);
}
<|endoftext|> |
<commit_before>#include "wave2data.h"
void showHelp() {
std::cout << "\t-h \t" << "show help" << std::endl;
std::cout << "\t-v \t" << "show version" << std::endl;
std::cout << "\t-f <filename>\t" << "set input filename" << std::endl;
std::cout << "\t-o <filename>\t" << "set output filename" << std::endl;
}
bool setopts(int argc, char* argv[], std::string &fn, std::string &output) {
int result;
auto odef = "output.dat";
fn = "";
output = odef;
if (argc < 2) {
return false;
}
while ((result=getopt(argc, argv, "hvf:o:"))!=-1) {
switch (result) {
case 'h':
// help
showHelp();
break;
case 'v':
// version
std::cout << "wave2data 0.1" << std::endl;
break;
case 'f':
fn = std::string(optarg);
if (output == odef) {
output = fn + ".dat";
}
break;
case 'o':
output = std::string(optarg);
break;
default:
break;
}
}
return true;
}
std::string file2string(std::string fn) {
std::ifstream ifs(fn, std::ios::in | std::ios::binary);
if (!ifs) {
std::perror(fn.c_str());
return std::string();
}
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
ifs.close();
return str;
}
bool dataCheck(std::string data, std::string fn) {
if (data.empty()) {
std::cout << fn << ": Unknown Error" << std::endl;
return false;
}
// RIFF Check
if (data.substr(0,4) != "RIFF") {
std::cout << fn << ": not RIFF File." << std::endl;
return false;
}
// Wave Check
if (data.substr(8, 4) != "WAVE") {
std::cout << fn << ": not Wave File." << std::endl;
return false;
}
return true;
}
int getDataSize(std::string s_hex) {
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += static_cast<unsigned char>(s_hex.at(i)) << (8*i);
}
return sum;
}
bool createData(std::string fn, std::string data) {
std::ofstream ofs(fn, std::ios::out | std::ios::binary);
if (!ofs) {
std::perror(fn.c_str());
return false;
}
ofs << data;
ofs.close();
return true;
}
<commit_msg>change HELP message<commit_after>#include "wave2data.h"
void showHelp() {
std::cout << "Arguments:" << std::endl;
std::cout << "\t-h \t" << "show help" << std::endl;
std::cout << "\t-v \t" << "show version" << std::endl;
std::cout << "\t-f <filename>\t" << "set input filename" << std::endl;
std::cout << "\t-o <filename>\t" << "set output filename" << std::endl;
}
bool setopts(int argc, char* argv[], std::string &fn, std::string &output) {
int result;
auto odef = "output.dat";
fn = "";
output = odef;
auto version = "wave2data 0.1.1";
if (argc < 2) {
return false;
}
while ((result=getopt(argc, argv, "hvf:o:"))!=-1) {
switch (result) {
case 'h':
// help
showHelp();
break;
case 'v':
// version
std::cout << version << std::endl;
break;
case 'f':
fn = std::string(optarg);
if (output == odef) {
output = fn + ".dat";
}
break;
case 'o':
output = std::string(optarg);
break;
default:
break;
}
}
return true;
}
std::string file2string(std::string fn) {
std::ifstream ifs(fn, std::ios::in | std::ios::binary);
if (!ifs) {
std::perror(fn.c_str());
return std::string();
}
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
ifs.close();
return str;
}
bool dataCheck(std::string data, std::string fn) {
if (data.empty()) {
std::cout << fn << ": Unknown Error" << std::endl;
return false;
}
// RIFF Check
if (data.substr(0,4) != "RIFF") {
std::cout << fn << ": not RIFF File." << std::endl;
return false;
}
// Wave Check
if (data.substr(8, 4) != "WAVE") {
std::cout << fn << ": not Wave File." << std::endl;
return false;
}
return true;
}
int getDataSize(std::string s_hex) {
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += static_cast<unsigned char>(s_hex.at(i)) << (8*i);
}
return sum;
}
bool createData(std::string fn, std::string data) {
std::ofstream ofs(fn, std::ios::out | std::ios::binary);
if (!ofs) {
std::perror(fn.c_str());
return false;
}
ofs << data;
ofs.close();
return true;
}
<|endoftext|> |
<commit_before>/* 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 <ncurses.h>
#include "catch.hpp"
#include "../src/join.hh"
using namespace vick;
using namespace vick::join;
TEST_CASE("join_two_lines") {
contents contents;
contents.push_back("hi man");
contents.push_back("bye man");
initscr();
auto change = join_two_lines(contents);
CHECK(contents.cont[0] == "hi man"
"bye man");
CHECK(contents.cont.size() == 1);
CHECK(change);
change.get()->undo(contents);
CHECK(contents.cont[0] == "hi man");
CHECK(contents.cont[1] == "bye man");
CHECK(contents.cont.size() == 2);
endwin();
}
TEST_CASE("join_two_lines: join lines testing") {
contents contents;
contents.push_back("hello");
contents.push_back("goodbye");
contents.push_back("wow");
contents.push_back("vick");
contents.y = 1;
initscr();
auto first = join_two_lines(contents);
auto second = join_two_lines(contents);
CHECK(contents.cont[1] == "goodbye"
"wow"
"vick");
CHECK(contents.cont.size() == 2);
CHECK(second);
if (!second)
goto end;
second.get()->undo(contents);
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
CHECK(first);
if (!first)
goto end;
first.get()->undo(contents);
CHECK(contents.cont[1] == "goodbye");
CHECK(contents.cont[2] == "wow");
CHECK(contents.cont[3] == "vick");
end:
endwin();
}
TEST_CASE("join_two_lines: undo testing") {
contents contents;
contents.push_back("hello");
contents.push_back("goodbye");
contents.push_back("wow");
contents.push_back("vick");
initscr();
contents.y = 1;
auto first = join_two_lines(contents);
contents.y = 1;
auto second = join_two_lines(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow"
"vick");
CHECK(contents.cont.size() == 2);
CHECK(second);
if (!second)
goto end;
second.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
{
contents.y = 0;
auto third = join_two_lines(contents);
CHECK(contents.cont[0] == "hello"
"goodbye"
"wow");
CHECK(contents.cont[1] == "vick");
CHECK(contents.cont.size() == 2);
CHECK(third);
if (!third)
goto end;
third.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
}
CHECK(first);
if (!first)
goto end;
first.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye");
CHECK(contents.cont[2] == "wow");
CHECK(contents.cont[3] == "vick");
CHECK(contents.cont.size() == 4);
end:
endwin();
}
<commit_msg>clang-format<commit_after>/* 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 <ncurses.h>
#include "../src/join.hh"
#include "catch.hpp"
using namespace vick;
using namespace vick::join;
TEST_CASE("join_two_lines") {
contents contents;
contents.push_back("hi man");
contents.push_back("bye man");
initscr();
auto change = join_two_lines(contents);
CHECK(contents.cont[0] == "hi man"
"bye man");
CHECK(contents.cont.size() == 1);
CHECK(change);
change.get()->undo(contents);
CHECK(contents.cont[0] == "hi man");
CHECK(contents.cont[1] == "bye man");
CHECK(contents.cont.size() == 2);
endwin();
}
TEST_CASE("join_two_lines: join lines testing") {
contents contents;
contents.push_back("hello");
contents.push_back("goodbye");
contents.push_back("wow");
contents.push_back("vick");
contents.y = 1;
initscr();
auto first = join_two_lines(contents);
auto second = join_two_lines(contents);
CHECK(contents.cont[1] == "goodbye"
"wow"
"vick");
CHECK(contents.cont.size() == 2);
CHECK(second);
if (!second)
goto end;
second.get()->undo(contents);
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
CHECK(first);
if (!first)
goto end;
first.get()->undo(contents);
CHECK(contents.cont[1] == "goodbye");
CHECK(contents.cont[2] == "wow");
CHECK(contents.cont[3] == "vick");
end:
endwin();
}
TEST_CASE("join_two_lines: undo testing") {
contents contents;
contents.push_back("hello");
contents.push_back("goodbye");
contents.push_back("wow");
contents.push_back("vick");
initscr();
contents.y = 1;
auto first = join_two_lines(contents);
contents.y = 1;
auto second = join_two_lines(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow"
"vick");
CHECK(contents.cont.size() == 2);
CHECK(second);
if (!second)
goto end;
second.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
{
contents.y = 0;
auto third = join_two_lines(contents);
CHECK(contents.cont[0] == "hello"
"goodbye"
"wow");
CHECK(contents.cont[1] == "vick");
CHECK(contents.cont.size() == 2);
CHECK(third);
if (!third)
goto end;
third.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye"
"wow");
CHECK(contents.cont[2] == "vick");
CHECK(contents.cont.size() == 3);
}
CHECK(first);
if (!first)
goto end;
first.get()->undo(contents);
CHECK(contents.cont[0] == "hello");
CHECK(contents.cont[1] == "goodbye");
CHECK(contents.cont[2] == "wow");
CHECK(contents.cont[3] == "vick");
CHECK(contents.cont.size() == 4);
end:
endwin();
}
<|endoftext|> |
<commit_before>#include "acmacs-base/pybind11.hh"
// chart
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/factory-export.hh"
#include "acmacs-chart-2/chart-modify.hh"
// ======================================================================
inline void chart_relax(acmacs::chart::ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough,
size_t number_of_best_distinct_projections_to_keep)
{
using namespace acmacs::chart;
if (number_of_optimizations == 0)
number_of_optimizations = 100;
chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions},
use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}});
}
// ----------------------------------------------------------------------
inline void py_chart(py::module_& mdl)
{
using namespace pybind11::literals;
using namespace acmacs::chart;
py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart")
.def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file"))
.def(
"make_name", [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, //
py::doc("returns name of the chart"))
.def(
"make_name", [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, "projection_no"_a, //
py::doc("returns name of the chart with the stress of the passed projection"))
.def("description", &Chart::description, py::doc("returns chart one line description"))
.def("number_of_antigens", &Chart::number_of_antigens)
.def("number_of_sera", &Chart::number_of_sera)
.def("number_of_projections", &Chart::number_of_projections)
.def(
"lineage", [](const ChartModify& chart) { return *chart.lineage(); }, py::doc("returns chart lineage: VICTORIA, YAMAGATA"))
.def("relax", &chart_relax, "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false,
"number_of_best_distinct_projections_to_keep"_a = 5, py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"});
}
// ----------------------------------------------------------------------
// https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time
PYBIND11_MODULE(acmacs, mdl)
{
mdl.doc() = "Acmacs backend";
py_chart(mdl);
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>acmacs python module<commit_after>#include "acmacs-base/pybind11.hh"
// chart
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/factory-export.hh"
#include "acmacs-chart-2/chart-modify.hh"
// ======================================================================
inline void chart_relax(acmacs::chart::ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough,
size_t number_of_best_distinct_projections_to_keep)
{
using namespace acmacs::chart;
if (number_of_optimizations == 0)
number_of_optimizations = 100;
chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions},
use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}});
chart.projections_modify().sort();
}
// ----------------------------------------------------------------------
inline void py_chart(py::module_& mdl)
{
using namespace pybind11::literals;
using namespace acmacs::chart;
py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart")
.def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file"))
.def(
"make_name", [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, //
py::doc("returns name of the chart"))
.def(
"make_name", [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, "projection_no"_a, //
py::doc("returns name of the chart with the stress of the passed projection"))
.def("description", &Chart::description, py::doc("returns chart one line description"))
.def("make_info", &Chart::make_info, "max_number_of_projections_to_show"_a=20, "flags"_a = 3, py::doc("returns detailed chart description"))
.def("number_of_antigens", &Chart::number_of_antigens)
.def("number_of_sera", &Chart::number_of_sera)
.def("number_of_projections", &Chart::number_of_projections)
.def(
"lineage", [](const ChartModify& chart) { return *chart.lineage(); }, py::doc("returns chart lineage: VICTORIA, YAMAGATA"))
.def("relax", &chart_relax, "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false,
"number_of_best_distinct_projections_to_keep"_a = 5, py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"});
}
// ----------------------------------------------------------------------
// https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time
PYBIND11_MODULE(acmacs, mdl)
{
mdl.doc() = "Acmacs backend";
py_chart(mdl);
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014-2015 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : scene/primitive/sphere.hpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
#if !defined(UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP)
#define UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP
// includes, system
//#include <>
// includes, project
#include <scene/node/geometry.hpp>
namespace scene {
namespace primitive {
// types, exported (class, enum, struct, union, typedef)
class DCS08961_SCENE_EXPORT sphere : public node::geometry {
public:
using subject_inherited = node::geometry;
explicit sphere();
field::value::single<unsigned> subdivision; ///< sub-disviion levels
virtual void accept(visitor::base&);
protected:
virtual void do_changed(field::base&);
};
// variables, exported (extern)
// functions, inlined (inline)
// functions, exported (extern)
} // namespace primitive {
} // namespace scene {
#endif // #if !defined(UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP)
<commit_msg>added: subdivision default<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014-2015 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : scene/primitive/sphere.hpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
#if !defined(UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP)
#define UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP
// includes, system
//#include <>
// includes, project
#include <scene/node/geometry.hpp>
namespace scene {
namespace primitive {
// types, exported (class, enum, struct, union, typedef)
class DCS08961_SCENE_EXPORT sphere : public node::geometry {
public:
using subject_inherited = node::geometry;
static unsigned const dflt_subdivision; // == 4
explicit sphere(unsigned = dflt_subdivision);
field::value::single<unsigned> subdivision; ///< sub-disviion levels
virtual void accept(visitor::base&);
protected:
virtual void do_changed(field::base&);
};
// variables, exported (extern)
// functions, inlined (inline)
// functions, exported (extern)
} // namespace primitive {
} // namespace scene {
#endif // #if !defined(UKACHULLDCS_08961_SCENE_PRIMITIVE_SPHERE_HPP)
<|endoftext|> |
<commit_before>/*
* This file is part of SKATRAK Playground.
*
* SKATRAK Playground is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> or
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*
* Sergio M. Afonso Fumero <theSkatrak@gmail.com>
*/
#ifndef __SKATRAK_PLAYGROUND__
#define __SKATRAK_PLAYGROUND__
/* Incluimos las libreras estndar que necesitamos y las libreras SDL */
#include <string>
#include <fstream>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <SDL/SDL_ttf.h>
using std::string;
/* Incluimos las cabeceras generales compartidas por todos los minijuegos */
#include "./system.hpp"
#include "./music.hpp"
#include "./sfx.hpp"
#include "./image.hpp"
#include "./timekeeper.hpp"
#include "./font.hpp"
#include "./inifile.hpp"
/* Rutas por defecto de los recursos */
extern const char* MUS_PATH;
extern const char* SFX_PATH;
extern const char* FONT_PATH;
extern const char* IMG_PATH;
extern const char* INI_PATH;
#endif
<commit_msg>#define para evitar quejas del compilador de Visual Studio<commit_after>/*
* This file is part of SKATRAK Playground.
*
* SKATRAK Playground is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> or
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*
* Sergio M. Afonso Fumero <theSkatrak@gmail.com>
*/
#ifndef __SKATRAK_PLAYGROUND__
#define __SKATRAK_PLAYGROUND__
/* Incluimos las libreras estndar que necesitamos y las libreras SDL */
#include <string>
#include <fstream>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <SDL/SDL_ttf.h>
using std::string;
/* Evitar Warnings en Microsoft Visual Studio */
#ifdef _MSC_VER
#define sprintf sprintf_s
#endif
/* Incluimos las cabeceras generales compartidas por todos los minijuegos */
#include "./system.hpp"
#include "./music.hpp"
#include "./sfx.hpp"
#include "./image.hpp"
#include "./timekeeper.hpp"
#include "./font.hpp"
#include "./inifile.hpp"
/* Rutas por defecto de los recursos */
extern const char* MUS_PATH;
extern const char* SFX_PATH;
extern const char* FONT_PATH;
extern const char* IMG_PATH;
extern const char* INI_PATH;
#endif
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_COROUTINE_HXX
#define _ABACLADE_COROUTINE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <abaclade/thread.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine
namespace abc {
/*! Subroutine for use in non-preemptive multitasking, enabling asynchronous I/O in most abc::io
classes. */
class ABACLADE_SYM coroutine : public noncopyable {
private:
friend class coroutine_scheduler;
public:
//! OS-dependent execution context for the coroutine.
class context;
public:
/*! Constructor.
@param fnMain
Function to invoke once the coroutine is first scheduled.
@param coro
Source object.
*/
coroutine();
explicit coroutine(std::function<void ()> fnMain);
coroutine(coroutine && coro) :
m_pctx(std::move(coro.m_pctx)) {
}
//! Destructor.
~coroutine();
private:
//! Pointer to the coroutine’s execution context.
std::shared_ptr<context> m_pctx;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine_scheduler
namespace abc {
// Forward declaration.
class coroutine_scheduler;
namespace this_thread {
/*! Attaches a coroutine scheduler to the current thread, and performs and necessary initialization
required for the current thread to run coroutines.
@return
Coroutine scheduler associated to this thread. If pcorosched was non-nullptr, this is the same as
pcorosched.
*/
ABACLADE_SYM std::shared_ptr<coroutine_scheduler> const & attach_coroutine_scheduler(
std::shared_ptr<coroutine_scheduler> pcorosched = nullptr
);
/*! Returns the coroutine scheduler associated to the current thread, if any.
@return
Coroutine scheduler associated to this thread. May be nullptr if attach_coroutine_scheduler() was
never called for the current thread.
*/
ABACLADE_SYM std::shared_ptr<coroutine_scheduler> const & get_coroutine_scheduler();
} //namespace this_thread
//! Schedules coroutine execution.
class ABACLADE_SYM coroutine_scheduler : public noncopyable {
private:
friend std::shared_ptr<coroutine_scheduler> const & this_thread::attach_coroutine_scheduler(
std::shared_ptr<coroutine_scheduler> pcorosched /*= nullptr*/
);
friend std::shared_ptr<coroutine_scheduler> const & this_thread::get_coroutine_scheduler();
public:
//! Destructor.
virtual ~coroutine_scheduler();
void add(coroutine const & coro);
/*! Begins scheduling and running coroutines on the current thread. Only returns after every
coroutine added with add_coroutine() returns. */
virtual void run() = 0;
/*! Allows other coroutines to run, preventing this coroutine from being rescheduled until at
least iMillisecs milliseconds have passed.
@param iMillisecs
Minimum duration for which to yield to other coroutines.
*/
virtual void yield_for(unsigned iMillisecs) = 0;
/*! Allows other coroutines to run while the asynchronous I/O operation completes, as an
alternative to blocking while waiting for its completion.
@param fd
File descriptor that the calling coroutine is waiting for I/O on.
@param bWrite
true if the coroutine is waiting to write to fd, or false if it’s waiting to read from it.
*/
virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) = 0;
protected:
//! Constructor.
coroutine_scheduler();
protected:
//! Pointer to the active (current) coroutine, or nullptr if none is active.
std::shared_ptr<coroutine::context> m_pcoroctxActive;
//! List of coroutines that have been scheduled, but have not been started yet.
collections::list<std::shared_ptr<coroutine::context>> m_listStartingCoros;
//! Pointer to the coroutine_scheduler for the current thread.
static thread_local_value<std::shared_ptr<coroutine_scheduler>> sm_pcorosched;
};
// Now this can be defined.
namespace this_thread {
inline std::shared_ptr<class coroutine_scheduler> const & get_coroutine_scheduler() {
return coroutine_scheduler::sm_pcorosched;
}
} //namespace this_thread
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_COROUTINE_HXX
<commit_msg>Fix code documentation<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#ifndef _ABACLADE_COROUTINE_HXX
#define _ABACLADE_COROUTINE_HXX
#ifndef _ABACLADE_HXX
#error "Please #include <abaclade.hxx> before this file"
#endif
#ifdef ABC_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <abaclade/thread.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine
namespace abc {
/*! Subroutine for use in non-preemptive multitasking, enabling asynchronous I/O in most abc::io
classes. */
class ABACLADE_SYM coroutine : public noncopyable {
private:
friend class coroutine_scheduler;
public:
//! OS-dependent execution context for the coroutine.
class context;
public:
/*! Constructor.
@param fnMain
Function to invoke once the coroutine is first scheduled.
@param coro
Source object.
*/
coroutine();
explicit coroutine(std::function<void ()> fnMain);
coroutine(coroutine && coro) :
m_pctx(std::move(coro.m_pctx)) {
}
//! Destructor.
~coroutine();
private:
//! Pointer to the coroutine’s execution context.
std::shared_ptr<context> m_pctx;
};
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::coroutine_scheduler
namespace abc {
// Forward declaration.
class coroutine_scheduler;
namespace this_thread {
/*! Attaches a coroutine scheduler to the current thread, and performs and necessary initialization
required for the current thread to run coroutines.
@return
Coroutine scheduler associated to this thread. If pcorosched was non-nullptr, this is the same as
pcorosched.
*/
ABACLADE_SYM std::shared_ptr<coroutine_scheduler> const & attach_coroutine_scheduler(
std::shared_ptr<coroutine_scheduler> pcorosched = nullptr
);
/*! Returns the coroutine scheduler associated to the current thread, if any.
@return
Coroutine scheduler associated to this thread. May be nullptr if attach_coroutine_scheduler() was
never called for the current thread.
*/
ABACLADE_SYM std::shared_ptr<coroutine_scheduler> const & get_coroutine_scheduler();
} //namespace this_thread
//! Schedules coroutine execution.
class ABACLADE_SYM coroutine_scheduler : public noncopyable {
private:
friend std::shared_ptr<coroutine_scheduler> const & this_thread::attach_coroutine_scheduler(
std::shared_ptr<coroutine_scheduler> pcorosched /*= nullptr*/
);
friend std::shared_ptr<coroutine_scheduler> const & this_thread::get_coroutine_scheduler();
public:
//! Destructor.
virtual ~coroutine_scheduler();
void add(coroutine const & coro);
/*! Begins scheduling and running coroutines on the current thread. Only returns after every
coroutine added with add_coroutine() returns. */
virtual void run() = 0;
/*! Allows other coroutines to run, preventing the calling coroutine from being rescheduled until
at least iMillisecs milliseconds have passed.
@param iMillisecs
Minimum duration for which to yield to other coroutines.
*/
virtual void yield_for(unsigned iMillisecs) = 0;
/*! Allows other coroutines to run while the asynchronous I/O operation completes, as an
alternative to blocking while waiting for its completion.
@param fd
File descriptor that the calling coroutine is waiting for I/O on.
@param bWrite
true if the coroutine is waiting to write to fd, or false if it’s waiting to read from it.
*/
virtual void yield_while_async_pending(io::filedesc const & fd, bool bWrite) = 0;
protected:
//! Constructor.
coroutine_scheduler();
protected:
//! Pointer to the active (current) coroutine, or nullptr if none is active.
std::shared_ptr<coroutine::context> m_pcoroctxActive;
//! List of coroutines that have been scheduled, but have not been started yet.
collections::list<std::shared_ptr<coroutine::context>> m_listStartingCoros;
//! Pointer to the coroutine_scheduler for the current thread.
static thread_local_value<std::shared_ptr<coroutine_scheduler>> sm_pcorosched;
};
// Now this can be defined.
namespace this_thread {
inline std::shared_ptr<class coroutine_scheduler> const & get_coroutine_scheduler() {
return coroutine_scheduler::sm_pcorosched;
}
} //namespace this_thread
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _ABACLADE_COROUTINE_HXX
<|endoftext|> |
<commit_before>/**
@file unistrcompare.hpp
@author Tim Howard
@section LICENSE
Copyright (c) 2010-2012 Tim Howard
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.
@section DESCRIPTION
duct++ icu::UnicodeString* comparison class.
*/
#ifndef _DUCT_UNISTRCOMPARE_HPP
#define _DUCT_UNISTRCOMPARE_HPP
#include <duct/config.hpp>
#include <unicode/unistr.h>
namespace duct {
/**
icu::UnicodeString* comparison class.
*/
class DUCT_API icu::UnicodeStringPCompare {
public:
bool operator()(icu::UnicodeString const* x, icu::UnicodeString const* y) const {
return x->compare(*y)<0;
};
};
} // namespace duct
#endif // _DUCT_UNISTRCOMPARE_HPP
<commit_msg>Corrected UnicodeStringPCompare class name ('icu::' prefix caused by mass-replace in daea44bf).<commit_after>/**
@file unistrcompare.hpp
@author Tim Howard
@section LICENSE
Copyright (c) 2010-2012 Tim Howard
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.
@section DESCRIPTION
duct++ icu::UnicodeString* comparison class.
*/
#ifndef _DUCT_UNISTRCOMPARE_HPP
#define _DUCT_UNISTRCOMPARE_HPP
#include <duct/config.hpp>
#include <unicode/unistr.h>
namespace duct {
/**
icu::UnicodeString* comparison class.
*/
class DUCT_API UnicodeStringPCompare {
public:
bool operator()(icu::UnicodeString const* x, icu::UnicodeString const* y) const {
return x->compare(*y)<0;
};
};
} // namespace duct
#endif // _DUCT_UNISTRCOMPARE_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2014-2019, CNRS
* Copyright 2018-2019, INRIA
*/
#ifndef __eigenpy_quaternion_hpp__
#define __eigenpy_quaternion_hpp__
#include "eigenpy/fwd.hpp"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "eigenpy/exception.hpp"
#include "eigenpy/registration.hpp"
namespace eigenpy
{
class ExceptionIndex : public Exception
{
public:
ExceptionIndex(int index,int imin,int imax) : Exception("")
{
std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<".";
message = oss.str();
}
};
namespace bp = boost::python;
template<typename QuaternionDerived> class QuaternionVisitor;
template<typename Scalar, int Options>
struct call< Eigen::Quaternion<Scalar,Options> >
{
typedef Eigen::Quaternion<Scalar,Options> Quaternion;
static inline void expose()
{
QuaternionVisitor<Quaternion>::expose();
}
static inline bool isApprox(const Quaternion & self, const Quaternion & other,
const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
{
return self.isApprox(other,prec);
}
};
BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxQuaternion_overload,call<Eigen::Quaterniond>::isApprox,2,3)
template<typename Quaternion>
class QuaternionVisitor
: public bp::def_visitor< QuaternionVisitor<Quaternion> >
{
typedef Eigen::QuaternionBase<Quaternion> QuaternionBase;
typedef typename QuaternionBase::Scalar Scalar;
typedef typename Quaternion::Coefficients Coefficients;
typedef typename QuaternionBase::Vector3 Vector3;
typedef typename Eigen::Matrix<Scalar,4,1> Vector4;
typedef typename QuaternionBase::Matrix3 Matrix3;
typedef typename QuaternionBase::AngleAxisType AngleAxis;
public:
template<class PyClass>
void visit(PyClass& cl) const
{
cl
.def(bp::init<>("Default constructor"))
.def(bp::init<Vector4>((bp::arg("vec4")),
"Initialize from a vector 4D.\n"
"\tvec4 : a 4D vector representing quaternion coefficients in the order xyzw."))
.def(bp::init<Matrix3>((bp::arg("R")),
"Initialize from rotation matrix.\n"
"\tR : a rotation matrix 3x3."))
.def(bp::init<AngleAxis>((bp::arg("aa")),
"Initialize from an angle axis.\n"
"\taa: angle axis object."))
.def(bp::init<Quaternion>((bp::arg("quat")),
"Copy constructor.\n"
"\tquat: a quaternion."))
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors,
bp::default_call_policies(),
(bp::arg("u: a 3D vector"),bp::arg("v: a 3D vector"))),
"Initialize from two vectors u and v")
.def(bp::init<Scalar,Scalar,Scalar,Scalar>
((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")),
"Initialize from coefficients.\n\n"
"... note:: The order of coefficients is *w*, *x*, *y*, *z*. "
"The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!"))
.add_property("x",
&QuaternionVisitor::getCoeff<0>,
&QuaternionVisitor::setCoeff<0>,"The x coefficient.")
.add_property("y",
&QuaternionVisitor::getCoeff<1>,
&QuaternionVisitor::setCoeff<1>,"The y coefficient.")
.add_property("z",
&QuaternionVisitor::getCoeff<2>,
&QuaternionVisitor::setCoeff<2>,"The z coefficient.")
.add_property("w",
&QuaternionVisitor::getCoeff<3>,
&QuaternionVisitor::setCoeff<3>,"The w coefficient.")
.def("isApprox",
&call<Quaternion>::isApprox,
isApproxQuaternion_overload(bp::args("other","prec"),
"Returns true if *this is approximately equal to other, within the precision determined by prec."))
/* --- Methods --- */
.def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs,
bp::return_value_policy<bp::copy_const_reference>())
.def("matrix",&Quaternion::matrix,"Returns an equivalent 3x3 rotation matrix. Similar to toRotationMatrix.")
.def("toRotationMatrix",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.")
.def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transforms a into b through a rotation."
,bp::return_self<>())
.def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.")
.def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.")
.def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.")
.def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.")
.def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.")
.def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.")
.def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.")
.def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other"
"Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.")
.def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.")
.def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).")
.def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.")
.def("slerp",&slerp,bp::args("t","other"),
"Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].")
/* --- Operators --- */
.def(bp::self * bp::self)
.def(bp::self *= bp::self)
.def(bp::self * bp::other<Vector3>())
.def("__eq__",&QuaternionVisitor::__eq__)
.def("__ne__",&QuaternionVisitor::__ne__)
.def("__abs__",&Quaternion::norm)
.def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__")
.def("__setitem__",&QuaternionVisitor::__setitem__)
.def("__getitem__",&QuaternionVisitor::__getitem__)
.def("assign",&assign<Quaternion>,
bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>())
.def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=,
bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>())
.def("__str__",&print)
.def("__repr__",&print)
// .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>,
// bp::args("a","b"),
// "Returns the quaternion which transform a into b through a rotation.")
.def("FromTwoVectors",&FromTwoVectors,
bp::args("a","b"),
"Returns the quaternion which transforms a into b through a rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("FromTwoVectors")
.def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.")
.staticmethod("Identity")
;
}
private:
template<int i>
static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; }
template<int i>
static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; }
static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b)
{ return self.setFromTwoVectors(a,b); }
template<typename OtherQuat>
static Quaternion & assign(Quaternion & self, const OtherQuat & quat)
{ return self = quat; }
static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v)
{
Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v);
return q;
}
static bool __eq__(const Quaternion & u, const Quaternion & v)
{
return u.coeffs() == v.coeffs();
}
static bool __ne__(const Quaternion& u, const Quaternion& v)
{
return !__eq__(u,v);
}
static Scalar __getitem__(const Quaternion & self, int idx)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
return self.coeffs()[idx];
}
static void __setitem__(Quaternion& self, int idx, const Scalar value)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
self.coeffs()[idx] = value;
}
static int __len__() { return 4; }
static Vector3 vec(const Quaternion & self) { return self.vec(); }
static std::string print(const Quaternion & self)
{
std::stringstream ss;
ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl;
return ss.str();
}
static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other)
{ return self.slerp(t,other); }
public:
static void expose()
{
bp::class_<Quaternion>("Quaternion",
"Quaternion representing rotation.\n\n"
"Supported operations "
"('q is a Quaternion, 'v' is a Vector3): "
"'q*q' (rotation composition), "
"'q*=q', "
"'q*v' (rotating 'v' by 'q'), "
"'q==q', 'q!=q', 'q[0..3]'.",
bp::no_init)
.def(QuaternionVisitor<Quaternion>())
;
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_quaternion_hpp__
<commit_msg>geometry: fix Quaternion arguments<commit_after>/*
* Copyright 2014-2019, CNRS
* Copyright 2018-2019, INRIA
*/
#ifndef __eigenpy_quaternion_hpp__
#define __eigenpy_quaternion_hpp__
#include "eigenpy/fwd.hpp"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "eigenpy/exception.hpp"
#include "eigenpy/registration.hpp"
namespace eigenpy
{
class ExceptionIndex : public Exception
{
public:
ExceptionIndex(int index,int imin,int imax) : Exception("")
{
std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<".";
message = oss.str();
}
};
namespace bp = boost::python;
template<typename QuaternionDerived> class QuaternionVisitor;
template<typename Scalar, int Options>
struct call< Eigen::Quaternion<Scalar,Options> >
{
typedef Eigen::Quaternion<Scalar,Options> Quaternion;
static inline void expose()
{
QuaternionVisitor<Quaternion>::expose();
}
static inline bool isApprox(const Quaternion & self, const Quaternion & other,
const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
{
return self.isApprox(other,prec);
}
};
BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxQuaternion_overload,call<Eigen::Quaterniond>::isApprox,2,3)
template<typename Quaternion>
class QuaternionVisitor
: public bp::def_visitor< QuaternionVisitor<Quaternion> >
{
typedef Eigen::QuaternionBase<Quaternion> QuaternionBase;
typedef typename QuaternionBase::Scalar Scalar;
typedef typename Quaternion::Coefficients Coefficients;
typedef typename QuaternionBase::Vector3 Vector3;
typedef typename Eigen::Matrix<Scalar,4,1> Vector4;
typedef typename QuaternionBase::Matrix3 Matrix3;
typedef typename QuaternionBase::AngleAxisType AngleAxis;
public:
template<class PyClass>
void visit(PyClass& cl) const
{
cl
.def(bp::init<>(bp::arg("self"),"Default constructor"))
.def(bp::init<Vector4>((bp::arg("self"),bp::arg("vec4")),
"Initialize from a vector 4D.\n"
"\tvec4 : a 4D vector representing quaternion coefficients in the order xyzw."))
.def(bp::init<Matrix3>((bp::arg("self"),bp::arg("R")),
"Initialize from rotation matrix.\n"
"\tR : a rotation matrix 3x3."))
.def(bp::init<AngleAxis>((bp::arg("self"),bp::arg("aa")),
"Initialize from an angle axis.\n"
"\taa: angle axis object."))
.def(bp::init<Quaternion>((bp::arg("self"),bp::arg("quat")),
"Copy constructor.\n"
"\tquat: a quaternion."))
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors,
bp::default_call_policies(),
(bp::arg("u: a 3D vector"),bp::arg("v: a 3D vector"))),
"Initialize from two vectors u and v")
.def(bp::init<Scalar,Scalar,Scalar,Scalar>
((bp::arg("self"),bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")),
"Initialize from coefficients.\n\n"
"... note:: The order of coefficients is *w*, *x*, *y*, *z*. "
"The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!"))
.add_property("x",
&QuaternionVisitor::getCoeff<0>,
&QuaternionVisitor::setCoeff<0>,"The x coefficient.")
.add_property("y",
&QuaternionVisitor::getCoeff<1>,
&QuaternionVisitor::setCoeff<1>,"The y coefficient.")
.add_property("z",
&QuaternionVisitor::getCoeff<2>,
&QuaternionVisitor::setCoeff<2>,"The z coefficient.")
.add_property("w",
&QuaternionVisitor::getCoeff<3>,
&QuaternionVisitor::setCoeff<3>,"The w coefficient.")
.def("isApprox",
&call<Quaternion>::isApprox,
isApproxQuaternion_overload(bp::args("self","other","prec"),
"Returns true if *this is approximately equal to other, within the precision determined by prec."))
/* --- Methods --- */
.def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs,
bp::arg("self"),
"Returns a vector of the coefficients (x,y,z,w)",
bp::return_value_policy<bp::copy_const_reference>())
.def("matrix",&Quaternion::matrix,
bp::arg("self"),
"Returns an equivalent 3x3 rotation matrix. Similar to toRotationMatrix.")
.def("toRotationMatrix",&Quaternion::toRotationMatrix,
bp::arg("self"),
"Returns an equivalent 3x3 rotation matrix.")
.def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("self"),bp::arg("a"),bp::arg("b"))),
"Set *this to be the quaternion which transforms a into b through a rotation."
,bp::return_self<>())
.def("conjugate",&Quaternion::conjugate,
bp::arg("self"),
"Returns the conjugated quaternion.\n"
"The conjugate of a quaternion represents the opposite rotation.")
.def("inverse",&Quaternion::inverse,
bp::arg("self"),
"Returns the quaternion describing the inverse rotation.")
.def("setIdentity",&Quaternion::setIdentity,
bp::arg("self"),
"Set *this to the idendity rotation.",bp::return_self<>())
.def("norm",&Quaternion::norm,
bp::arg("self"),
"Returns the norm of the quaternion's coefficients.")
.def("normalize",&Quaternion::normalize,
bp::arg("self"),
"Normalizes the quaternion *this.")
.def("normalized",&Quaternion::normalized,
bp::arg("self"),
"Returns a normalized copy of *this.")
.def("squaredNorm",&Quaternion::squaredNorm,
bp::arg("self"),
"Returns the squared norm of the quaternion's coefficients.")
.def("dot",&Quaternion::template dot<Quaternion>,
(bp::arg("self"),bp::arg("other")),
"Returns the dot product of *this with an other Quaternion.\n"
"Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.")
.def("_transformVector",&Quaternion::_transformVector,
(bp::arg("self"),bp::arg("vector")),
"Rotation of a vector by a quaternion.")
.def("vec",&vec,
bp::arg("self"),
"Returns a vector expression of the imaginary part (x,y,z).")
.def("angularDistance",
(bp::arg("self"),bp::arg("other")),
&Quaternion::template angularDistance<Quaternion>,
"Returns the angle (in radian) between two rotations.")
.def("slerp",&slerp,bp::args("self","t","other"),
"Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].")
/* --- Operators --- */
.def(bp::self * bp::self)
.def(bp::self *= bp::self)
.def(bp::self * bp::other<Vector3>())
.def("__eq__",&QuaternionVisitor::__eq__)
.def("__ne__",&QuaternionVisitor::__ne__)
.def("__abs__",&Quaternion::norm)
.def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__")
.def("__setitem__",&QuaternionVisitor::__setitem__)
.def("__getitem__",&QuaternionVisitor::__getitem__)
.def("assign",&assign<Quaternion>,
bp::args("self","quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>())
.def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=,
bp::args("self","aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>())
.def("__str__",&print)
.def("__repr__",&print)
// .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>,
// bp::args("a","b"),
// "Returns the quaternion which transform a into b through a rotation.")
.def("FromTwoVectors",&FromTwoVectors,
bp::args("a","b"),
"Returns the quaternion which transforms a into b through a rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("FromTwoVectors")
.def("Identity",&Quaternion::Identity,
"Returns a quaternion representing an identity rotation.")
.staticmethod("Identity")
;
}
private:
template<int i>
static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; }
template<int i>
static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; }
static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b)
{ return self.setFromTwoVectors(a,b); }
template<typename OtherQuat>
static Quaternion & assign(Quaternion & self, const OtherQuat & quat)
{ return self = quat; }
static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v)
{
Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v);
return q;
}
static bool __eq__(const Quaternion & u, const Quaternion & v)
{
return u.coeffs() == v.coeffs();
}
static bool __ne__(const Quaternion& u, const Quaternion& v)
{
return !__eq__(u,v);
}
static Scalar __getitem__(const Quaternion & self, int idx)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
return self.coeffs()[idx];
}
static void __setitem__(Quaternion& self, int idx, const Scalar value)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
self.coeffs()[idx] = value;
}
static int __len__() { return 4; }
static Vector3 vec(const Quaternion & self) { return self.vec(); }
static std::string print(const Quaternion & self)
{
std::stringstream ss;
ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl;
return ss.str();
}
static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other)
{ return self.slerp(t,other); }
public:
static void expose()
{
bp::class_<Quaternion>("Quaternion",
"Quaternion representing rotation.\n\n"
"Supported operations "
"('q is a Quaternion, 'v' is a Vector3): "
"'q*q' (rotation composition), "
"'q*=q', "
"'q*v' (rotating 'v' by 'q'), "
"'q==q', 'q!=q', 'q[0..3]'.",
bp::no_init)
.def(QuaternionVisitor<Quaternion>())
;
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_quaternion_hpp__
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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.
*/
#ifndef FLUSSPFERD_CONTEXT_HPP
#define FLUSSPFERD_CONTEXT_HPP
#include "object.hpp"
#include <boost/shared_ptr.hpp>
#include <string>
namespace flusspferd {
class value;
class object;
class context {
class impl;
boost::shared_ptr<impl> p;
struct context_private;
public:
struct detail;
friend struct detail;
context();
context(detail const&);
~context();
bool is_valid() const;
bool operator==(context const &o) const {
return p == o.p;
}
static context create();
object global();
object scope_chain();
value evaluate(char const *source, std::size_t n,
char const *file = 0x0, unsigned int line = 0);
value evaluateInScope(char const* source, std::size_t n,
char const* file, unsigned int line,
object const &scope);
value evaluate(char const *source, char const *file = 0x0,
unsigned int line = 0);
value evaluate(std::string const &source, char const *file = 0x0,
unsigned int line = 0);
value execute(char const *file, object const &scope);
void gc();
void add_prototype(std::string const &name, object const &proto);
object get_prototype(std::string const &name) const;
template<typename T>
void add_prototype(object const &proto) {
add_prototype(T::class_info::full_name(), proto);
}
template<typename T>
object get_prototype() const {
return get_prototype(T::class_info::full_name());
}
void add_constructor(std::string const &name, object const &ctor);
object get_constructor(std::string const &name) const;
template<typename T>
void add_constructor(object const &ctor) {
add_constructor(T::class_info::full_name(), ctor);
}
template<typename T>
object get_constructor() const {
return get_constructor(T::class_info::full_name());
}
};
inline bool operator!=(context const &a, context const &b) {
return !(a == b);
}
}
#endif /* FLUSSPFERD_CONTEXT_HPP */
<commit_msg>Core: add default parameter to context::execute<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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.
*/
#ifndef FLUSSPFERD_CONTEXT_HPP
#define FLUSSPFERD_CONTEXT_HPP
#include "object.hpp"
#include <boost/shared_ptr.hpp>
#include <string>
namespace flusspferd {
class value;
class object;
class context {
class impl;
boost::shared_ptr<impl> p;
struct context_private;
public:
struct detail;
friend struct detail;
context();
context(detail const&);
~context();
bool is_valid() const;
bool operator==(context const &o) const {
return p == o.p;
}
static context create();
object global();
object scope_chain();
value evaluate(char const *source, std::size_t n,
char const *file = 0x0, unsigned int line = 0);
value evaluateInScope(char const* source, std::size_t n,
char const* file, unsigned int line,
object const &scope);
value evaluate(char const *source, char const *file = 0x0,
unsigned int line = 0);
value evaluate(std::string const &source, char const *file = 0x0,
unsigned int line = 0);
value execute(char const *file, object const &scope = object());
void gc();
void add_prototype(std::string const &name, object const &proto);
object get_prototype(std::string const &name) const;
template<typename T>
void add_prototype(object const &proto) {
add_prototype(T::class_info::full_name(), proto);
}
template<typename T>
object get_prototype() const {
return get_prototype(T::class_info::full_name());
}
void add_constructor(std::string const &name, object const &ctor);
object get_constructor(std::string const &name) const;
template<typename T>
void add_constructor(object const &ctor) {
add_constructor(T::class_info::full_name(), ctor);
}
template<typename T>
object get_constructor() const {
return get_constructor(T::class_info::full_name());
}
};
inline bool operator!=(context const &a, context const &b) {
return !(a == b);
}
}
#endif /* FLUSSPFERD_CONTEXT_HPP */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009, 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_ADDRESS_HPP_INCLUDED
#define TORRENT_ADDRESS_HPP_INCLUDED
#include <boost/version.hpp>
#ifdef __OBJC__
#define Protocol Protocol_
#endif
#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
// asio assumes that the windows error codes are defined already
#include <winsock2.h>
#endif
#if BOOST_VERSION < 103500
#include <asio/ip/address.hpp>
#else
#include <boost/asio/ip/address.hpp>
#endif
#ifdef __OBJC__
#undef Protocol
#endif
namespace libtorrent
{
#if BOOST_VERSION < 103500
typedef ::asio::ip::address address;
typedef ::asio::ip::address_v4 address_v4;
#if TORRENT_USE_IPV6
typedef ::asio::ip::address_v6 address_v6;
#endif
#else
typedef boost::asio::ip::address address;
typedef boost::asio::ip::address_v4 address_v4;
#if TORRENT_USE_IPV6
typedef boost::asio::ip::address_v6 address_v6;
#endif
#endif
}
#endif
<commit_msg>include config.hpp<commit_after>/*
Copyright (c) 2009, 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_ADDRESS_HPP_INCLUDED
#define TORRENT_ADDRESS_HPP_INCLUDED
#include <boost/version.hpp>
#include "libtorrent/config.hpp"
#ifdef __OBJC__
#define Protocol Protocol_
#endif
#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
// asio assumes that the windows error codes are defined already
#include <winsock2.h>
#endif
#if BOOST_VERSION < 103500
#include <asio/ip/address.hpp>
#else
#include <boost/asio/ip/address.hpp>
#endif
#ifdef __OBJC__
#undef Protocol
#endif
namespace libtorrent
{
#if BOOST_VERSION < 103500
typedef ::asio::ip::address address;
typedef ::asio::ip::address_v4 address_v4;
#if TORRENT_USE_IPV6
typedef ::asio::ip::address_v6 address_v6;
#endif
#else
typedef boost::asio::ip::address address;
typedef boost::asio::ip::address_v4 address_v4;
#if TORRENT_USE_IPV6
typedef boost::asio::ip::address_v6 address_v6;
#endif
#endif
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, 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_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED
/*
* This file declares the following functions:
*
*----------------------------------
* template<class OutIt>
* void libtorrent::bencode(OutIt out, const libtorrent::entry& e);
*
* Encodes a message entry with bencoding into the output
* iterator given. The bencoding is described in the BitTorrent
* protocol description document OutIt must be an OutputIterator
* of type char. This may throw libtorrent::invalid_encoding if
* the entry contains invalid nodes (undefined_t for example).
*
*----------------------------------
* template<class InIt>
* libtorrent::entry libtorrent::bdecode(InIt start, InIt end);
*
* Decodes the buffer given by the start and end iterators
* and returns the decoded entry. InIt must be an InputIterator
* of type char. May throw libtorrent::invalid_encoding if
* the string is not correctly bencoded.
*
*/
#include <cstdlib>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/lexical_cast.hpp>
#include <boost/static_assert.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isdigit;
using ::atoi;
};
#define for if (false) {} else for
#endif
namespace libtorrent
{
struct TORRENT_EXPORT invalid_encoding: std::exception
{
virtual const char* what() const throw() { return "invalid bencoding"; }
};
namespace detail
{
template <class OutIt>
void write_string(OutIt& out, const std::string& val)
{
std::string::const_iterator end = val.begin() + val.length();
std::copy(val.begin(), end, out);
}
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val);
template <class OutIt>
void write_integer(OutIt& out, entry::integer_type val)
{
// the stack allocated buffer for keeping the
// decimal representation of the number can
// not hold number bigger than this:
BOOST_STATIC_ASSERT(sizeof(entry::integer_type) <= 8);
char buf[21];
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
{
*out = *str;
++out;
}
}
template <class OutIt>
void write_char(OutIt& out, char c)
{
*out = c;
++out;
}
template <class InIt>
std::string read_until(InIt& in, InIt end, char end_token)
{
if (in == end) throw invalid_encoding();
std::string ret;
while (*in != end_token)
{
ret += *in;
++in;
if (in == end) throw invalid_encoding();
}
return ret;
}
template<class InIt>
void read_string(InIt& in, InIt end, int len, std::string& str)
{
TORRENT_ASSERT(len >= 0);
for (int i = 0; i < len; ++i)
{
if (in == end) throw invalid_encoding();
str += *in;
++in;
}
}
template<class OutIt>
void bencode_recursive(OutIt& out, const entry& e)
{
switch(e.type())
{
case entry::int_t:
write_char(out, 'i');
write_integer(out, e.integer());
write_char(out, 'e');
break;
case entry::string_t:
write_integer(out, e.string().length());
write_char(out, ':');
write_string(out, e.string());
break;
case entry::list_t:
write_char(out, 'l');
for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i)
bencode_recursive(out, *i);
write_char(out, 'e');
break;
case entry::dictionary_t:
write_char(out, 'd');
for (entry::dictionary_type::const_iterator i = e.dict().begin();
i != e.dict().end(); ++i)
{
// write key
write_integer(out, i->first.length());
write_char(out, ':');
write_string(out, i->first);
// write value
bencode_recursive(out, i->second);
}
write_char(out, 'e');
break;
default:
// do nothing
break;
}
}
template<class InIt>
void bdecode_recursive(InIt& in, InIt end, entry& ret)
{
if (in == end) throw invalid_encoding();
switch (*in)
{
// ----------------------------------------------
// integer
case 'i':
{
++in; // 'i'
std::string val = read_until(in, end, 'e');
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
ret = entry(entry::int_t);
ret.integer() = boost::lexical_cast<entry::integer_type>(val);
} break;
// ----------------------------------------------
// list
case 'l':
{
ret = entry(entry::list_t);
++in; // 'l'
while (*in != 'e')
{
ret.list().push_back(entry());
entry& e = ret.list().back();
bdecode_recursive(in, end, e);
if (in == end) throw invalid_encoding();
}
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// dictionary
case 'd':
{
ret = entry(entry::dictionary_t);
++in; // 'd'
while (*in != 'e')
{
entry key;
bdecode_recursive(in, end, key);
entry& e = ret[key.string()];
bdecode_recursive(in, end, e);
if (in == end) throw invalid_encoding();
}
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// string
default:
if (isdigit((unsigned char)*in))
{
std::string len_s = read_until(in, end, ':');
TORRENT_ASSERT(*in == ':');
++in; // ':'
int len = std::atoi(len_s.c_str());
ret = entry(entry::string_t);
read_string(in, end, len, ret.string());
}
else
{
throw invalid_encoding();
}
}
}
}
template<class OutIt>
void bencode(OutIt out, const entry& e)
{
detail::bencode_recursive(out, e);
}
template<class InIt>
entry bdecode(InIt start, InIt end)
{
try
{
entry e;
detail::bdecode_recursive(start, end, e);
return e;
}
catch(type_error&)
{
throw invalid_encoding();
}
}
}
#endif // TORRENT_BENCODE_HPP_INCLUDED
<commit_msg>made bdecoder not require exception support<commit_after>/*
Copyright (c) 2003, 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_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED
/*
* This file declares the following functions:
*
*----------------------------------
* template<class OutIt>
* void libtorrent::bencode(OutIt out, const libtorrent::entry& e);
*
* Encodes a message entry with bencoding into the output
* iterator given. The bencoding is described in the BitTorrent
* protocol description document OutIt must be an OutputIterator
* of type char. This may throw libtorrent::invalid_encoding if
* the entry contains invalid nodes (undefined_t for example).
*
*----------------------------------
* template<class InIt>
* libtorrent::entry libtorrent::bdecode(InIt start, InIt end);
*
* Decodes the buffer given by the start and end iterators
* and returns the decoded entry. InIt must be an InputIterator
* of type char. May throw libtorrent::invalid_encoding if
* the string is not correctly bencoded.
*
*/
#include <cstdlib>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/lexical_cast.hpp>
#include <boost/static_assert.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isdigit;
using ::atoi;
};
#define for if (false) {} else for
#endif
namespace libtorrent
{
struct TORRENT_EXPORT invalid_encoding: std::exception
{
virtual const char* what() const throw() { return "invalid bencoding"; }
};
namespace detail
{
template <class OutIt>
void write_string(OutIt& out, const std::string& val)
{
std::string::const_iterator end = val.begin() + val.length();
std::copy(val.begin(), end, out);
}
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val);
template <class OutIt>
void write_integer(OutIt& out, entry::integer_type val)
{
// the stack allocated buffer for keeping the
// decimal representation of the number can
// not hold number bigger than this:
BOOST_STATIC_ASSERT(sizeof(entry::integer_type) <= 8);
char buf[21];
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
{
*out = *str;
++out;
}
}
template <class OutIt>
void write_char(OutIt& out, char c)
{
*out = c;
++out;
}
template <class InIt>
std::string read_until(InIt& in, InIt end, char end_token, bool& err)
{
std::string ret;
if (in == end)
{
err = true;
return ret;
}
while (*in != end_token)
{
ret += *in;
++in;
if (in == end)
{
err = true;
return ret;
}
}
return ret;
}
template<class InIt>
void read_string(InIt& in, InIt end, int len, std::string& str, bool& err)
{
TORRENT_ASSERT(len >= 0);
for (int i = 0; i < len; ++i)
{
if (in == end)
{
err = true;
return;
}
str += *in;
++in;
}
}
template<class OutIt>
void bencode_recursive(OutIt& out, const entry& e)
{
switch(e.type())
{
case entry::int_t:
write_char(out, 'i');
write_integer(out, e.integer());
write_char(out, 'e');
break;
case entry::string_t:
write_integer(out, e.string().length());
write_char(out, ':');
write_string(out, e.string());
break;
case entry::list_t:
write_char(out, 'l');
for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i)
bencode_recursive(out, *i);
write_char(out, 'e');
break;
case entry::dictionary_t:
write_char(out, 'd');
for (entry::dictionary_type::const_iterator i = e.dict().begin();
i != e.dict().end(); ++i)
{
// write key
write_integer(out, i->first.length());
write_char(out, ':');
write_string(out, i->first);
// write value
bencode_recursive(out, i->second);
}
write_char(out, 'e');
break;
default:
// do nothing
break;
}
}
template<class InIt>
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err)
{
if (in == end)
{
err = true;
return;
}
switch (*in)
{
// ----------------------------------------------
// integer
case 'i':
{
++in; // 'i'
std::string val = read_until(in, end, 'e', err);
if (err) return;
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
ret = entry(entry::int_t);
ret.integer() = boost::lexical_cast<entry::integer_type>(val);
} break;
// ----------------------------------------------
// list
case 'l':
{
ret = entry(entry::list_t);
++in; // 'l'
while (*in != 'e')
{
ret.list().push_back(entry());
entry& e = ret.list().back();
bdecode_recursive(in, end, e, err);
if (err) return;
if (in == end)
{
err = true;
return;
}
}
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// dictionary
case 'd':
{
ret = entry(entry::dictionary_t);
++in; // 'd'
while (*in != 'e')
{
entry key;
bdecode_recursive(in, end, key, err);
if (err) return;
entry& e = ret[key.string()];
bdecode_recursive(in, end, e, err);
if (err) return;
if (in == end)
{
err = true;
return;
}
}
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// string
default:
if (isdigit((unsigned char)*in))
{
std::string len_s = read_until(in, end, ':', err);
if (err) return;
TORRENT_ASSERT(*in == ':');
++in; // ':'
int len = std::atoi(len_s.c_str());
ret = entry(entry::string_t);
read_string(in, end, len, ret.string(), err);
if (err) return;
}
else
{
err = true;
return;
}
}
}
}
template<class OutIt>
void bencode(OutIt out, const entry& e)
{
detail::bencode_recursive(out, e);
}
template<class InIt>
entry bdecode(InIt start, InIt end)
{
entry e;
bool err = false;
detail::bdecode_recursive(start, end, e, err);
if (err)
{
#ifdef BOOST_NO_EXCEPTIONS
return entry();
#else
throw invalid_encoding();
#endif
}
return e;
}
}
#endif // TORRENT_BENCODE_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, 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_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED
/*
* This file declares the following functions:
*
*----------------------------------
* template<class OutIt>
* void libtorrent::bencode(OutIt out, const libtorrent::entry& e);
*
* Encodes a message entry with bencoding into the output
* iterator given. The bencoding is described in the BitTorrent
* protocol description document OutIt must be an OutputIterator
* of type char. This may throw libtorrent::invalid_encoding if
* the entry contains invalid nodes (undefined_t for example).
*
*----------------------------------
* template<class InIt>
* libtorrent::entry libtorrent::bdecode(InIt start, InIt end);
*
* Decodes the buffer given by the start and end iterators
* and returns the decoded entry. InIt must be an InputIterator
* of type char. May throw libtorrent::invalid_encoding if
* the string is not correctly bencoded.
*
*/
#include <cstdlib>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/lexical_cast.hpp>
#include <boost/static_assert.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isdigit;
using ::atoi;
};
#define for if (false) {} else for
#endif
namespace libtorrent
{
struct TORRENT_EXPORT invalid_encoding: std::exception
{
virtual const char* what() const throw() { return "invalid bencoding"; }
};
namespace detail
{
template <class OutIt>
int write_string(OutIt& out, const std::string& val)
{
int ret = val.length();
std::string::const_iterator end = val.begin() + ret;
for (std::string::const_iterator i = val.begin()
, end(val.begin() + ret); i != end; ++i)
*out++ = *i;
return ret;
}
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val);
template <class OutIt>
int write_integer(OutIt& out, entry::integer_type val)
{
// the stack allocated buffer for keeping the
// decimal representation of the number can
// not hold number bigger than this:
BOOST_STATIC_ASSERT(sizeof(entry::integer_type) <= 8);
char buf[21];
int ret = 0;
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
{
*out = *str;
++out;
++ret;
}
return ret;
}
template <class OutIt>
void write_char(OutIt& out, char c)
{
*out = c;
++out;
}
template <class InIt>
std::string read_until(InIt& in, InIt end, char end_token, bool& err)
{
std::string ret;
if (in == end)
{
err = true;
return ret;
}
while (*in != end_token)
{
ret += *in;
++in;
if (in == end)
{
err = true;
return ret;
}
}
return ret;
}
template<class InIt>
void read_string(InIt& in, InIt end, int len, std::string& str, bool& err)
{
TORRENT_ASSERT(len >= 0);
for (int i = 0; i < len; ++i)
{
if (in == end)
{
err = true;
return;
}
str += *in;
++in;
}
}
// returns the number of bytes written
template<class OutIt>
int bencode_recursive(OutIt& out, const entry& e)
{
int ret = 0;
switch(e.type())
{
case entry::int_t:
write_char(out, 'i');
ret += write_integer(out, e.integer());
write_char(out, 'e');
ret += 2;
break;
case entry::string_t:
ret += write_integer(out, e.string().length());
write_char(out, ':');
ret += write_string(out, e.string());
ret += 1;
break;
case entry::list_t:
write_char(out, 'l');
for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i)
ret += bencode_recursive(out, *i);
write_char(out, 'e');
ret += 2;
break;
case entry::dictionary_t:
write_char(out, 'd');
for (entry::dictionary_type::const_iterator i = e.dict().begin();
i != e.dict().end(); ++i)
{
// write key
ret += write_integer(out, i->first.length());
write_char(out, ':');
ret += write_string(out, i->first);
// write value
ret += bencode_recursive(out, i->second);
ret += 1;
}
write_char(out, 'e');
ret += 2;
break;
default:
// do nothing
break;
}
return ret;
}
template<class InIt>
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
{
if (depth >= 100)
{
err = true;
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
switch (*in)
{
// ----------------------------------------------
// integer
case 'i':
{
++in; // 'i'
std::string val = read_until(in, end, 'e', err);
if (err) return;
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
ret = entry(entry::int_t);
ret.integer() = boost::lexical_cast<entry::integer_type>(val);
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
} break;
// ----------------------------------------------
// list
case 'l':
{
ret = entry(entry::list_t);
++in; // 'l'
while (*in != 'e')
{
ret.list().push_back(entry());
entry& e = ret.list().back();
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// dictionary
case 'd':
{
ret = entry(entry::dictionary_t);
++in; // 'd'
while (*in != 'e')
{
entry key;
bdecode_recursive(in, end, key, err, depth + 1);
if (err || key.type() != entry::string_t)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
entry& e = ret[key.string()];
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// string
default:
if (isdigit((unsigned char)*in))
{
std::string len_s = read_until(in, end, ':', err);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
TORRENT_ASSERT(*in == ':');
++in; // ':'
int len = std::atoi(len_s.c_str());
ret = entry(entry::string_t);
read_string(in, end, len, ret.string(), err);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
else
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
}
}
}
template<class OutIt>
int bencode(OutIt out, const entry& e)
{
return detail::bencode_recursive(out, e);
}
template<class InIt>
entry bdecode(InIt start, InIt end)
{
entry e;
bool err = false;
detail::bdecode_recursive(start, end, e, err, 0);
TORRENT_ASSERT(e.m_type_queried == false);
if (err) return entry();
return e;
}
template<class InIt>
entry bdecode(InIt start, InIt end, int& len)
{
entry e;
bool err = false;
InIt s = start;
detail::bdecode_recursive(start, end, e, err, 0);
len = std::distance(s, start);
TORRENT_ASSERT(len >= 0);
if (err) return entry();
return e;
}
}
#endif // TORRENT_BENCODE_HPP_INCLUDED
<commit_msg>fixed warnings in bencode<commit_after>/*
Copyright (c) 2003, 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_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED
/*
* This file declares the following functions:
*
*----------------------------------
* template<class OutIt>
* void libtorrent::bencode(OutIt out, const libtorrent::entry& e);
*
* Encodes a message entry with bencoding into the output
* iterator given. The bencoding is described in the BitTorrent
* protocol description document OutIt must be an OutputIterator
* of type char. This may throw libtorrent::invalid_encoding if
* the entry contains invalid nodes (undefined_t for example).
*
*----------------------------------
* template<class InIt>
* libtorrent::entry libtorrent::bdecode(InIt start, InIt end);
*
* Decodes the buffer given by the start and end iterators
* and returns the decoded entry. InIt must be an InputIterator
* of type char. May throw libtorrent::invalid_encoding if
* the string is not correctly bencoded.
*
*/
#include <cstdlib>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/lexical_cast.hpp>
#include <boost/static_assert.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#if defined(_MSC_VER)
namespace std
{
using ::isdigit;
using ::atoi;
};
#define for if (false) {} else for
#endif
namespace libtorrent
{
struct TORRENT_EXPORT invalid_encoding: std::exception
{
virtual const char* what() const throw() { return "invalid bencoding"; }
};
namespace detail
{
template <class OutIt>
int write_string(OutIt& out, const std::string& val)
{
for (std::string::const_iterator i = val.begin()
, end(val.end()); i != end; ++i)
*out++ = *i;
return val.length();
}
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val);
template <class OutIt>
int write_integer(OutIt& out, entry::integer_type val)
{
// the stack allocated buffer for keeping the
// decimal representation of the number can
// not hold number bigger than this:
BOOST_STATIC_ASSERT(sizeof(entry::integer_type) <= 8);
char buf[21];
int ret = 0;
for (char const* str = integer_to_str(buf, 21, val);
*str != 0; ++str)
{
*out = *str;
++out;
++ret;
}
return ret;
}
template <class OutIt>
void write_char(OutIt& out, char c)
{
*out = c;
++out;
}
template <class InIt>
std::string read_until(InIt& in, InIt end, char end_token, bool& err)
{
std::string ret;
if (in == end)
{
err = true;
return ret;
}
while (*in != end_token)
{
ret += *in;
++in;
if (in == end)
{
err = true;
return ret;
}
}
return ret;
}
template<class InIt>
void read_string(InIt& in, InIt end, int len, std::string& str, bool& err)
{
TORRENT_ASSERT(len >= 0);
for (int i = 0; i < len; ++i)
{
if (in == end)
{
err = true;
return;
}
str += *in;
++in;
}
}
// returns the number of bytes written
template<class OutIt>
int bencode_recursive(OutIt& out, const entry& e)
{
int ret = 0;
switch(e.type())
{
case entry::int_t:
write_char(out, 'i');
ret += write_integer(out, e.integer());
write_char(out, 'e');
ret += 2;
break;
case entry::string_t:
ret += write_integer(out, e.string().length());
write_char(out, ':');
ret += write_string(out, e.string());
ret += 1;
break;
case entry::list_t:
write_char(out, 'l');
for (entry::list_type::const_iterator i = e.list().begin(); i != e.list().end(); ++i)
ret += bencode_recursive(out, *i);
write_char(out, 'e');
ret += 2;
break;
case entry::dictionary_t:
write_char(out, 'd');
for (entry::dictionary_type::const_iterator i = e.dict().begin();
i != e.dict().end(); ++i)
{
// write key
ret += write_integer(out, i->first.length());
write_char(out, ':');
ret += write_string(out, i->first);
// write value
ret += bencode_recursive(out, i->second);
ret += 1;
}
write_char(out, 'e');
ret += 2;
break;
default:
// do nothing
break;
}
return ret;
}
template<class InIt>
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
{
if (depth >= 100)
{
err = true;
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
switch (*in)
{
// ----------------------------------------------
// integer
case 'i':
{
++in; // 'i'
std::string val = read_until(in, end, 'e', err);
if (err) return;
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
ret = entry(entry::int_t);
ret.integer() = boost::lexical_cast<entry::integer_type>(val);
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
} break;
// ----------------------------------------------
// list
case 'l':
{
ret = entry(entry::list_t);
++in; // 'l'
while (*in != 'e')
{
ret.list().push_back(entry());
entry& e = ret.list().back();
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// dictionary
case 'd':
{
ret = entry(entry::dictionary_t);
++in; // 'd'
while (*in != 'e')
{
entry key;
bdecode_recursive(in, end, key, err, depth + 1);
if (err || key.type() != entry::string_t)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
entry& e = ret[key.string()];
bdecode_recursive(in, end, e, err, depth + 1);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
if (in == end)
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
TORRENT_ASSERT(*in == 'e');
++in; // 'e'
} break;
// ----------------------------------------------
// string
default:
if (isdigit((unsigned char)*in))
{
std::string len_s = read_until(in, end, ':', err);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
TORRENT_ASSERT(*in == ':');
++in; // ':'
int len = std::atoi(len_s.c_str());
ret = entry(entry::string_t);
read_string(in, end, len, ret.string(), err);
if (err)
{
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
}
else
{
err = true;
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
return;
}
#ifndef NDEBUG
ret.m_type_queried = false;
#endif
}
}
}
template<class OutIt>
int bencode(OutIt out, const entry& e)
{
return detail::bencode_recursive(out, e);
}
template<class InIt>
entry bdecode(InIt start, InIt end)
{
entry e;
bool err = false;
detail::bdecode_recursive(start, end, e, err, 0);
TORRENT_ASSERT(e.m_type_queried == false);
if (err) return entry();
return e;
}
template<class InIt>
entry bdecode(InIt start, InIt end, int& len)
{
entry e;
bool err = false;
InIt s = start;
detail::bdecode_recursive(start, end, e, err, 0);
len = std::distance(s, start);
TORRENT_ASSERT(len >= 0);
if (err) return entry();
return e;
}
}
#endif // TORRENT_BENCODE_HPP_INCLUDED
<|endoftext|> |
<commit_before>#define START 0
#define ENTRY 0
#include "timings.h"
#include <inttypes.h>
#include <cinttypes>
#define START_NO 1000000000
#include <libcpu.h>
#include "arch/arm/arm_types.h"
#include "arch/m88k/m88k_isa.h"
#define RET_MAGIC 0x4D495354
static void
debug_function(cpu_t *cpu) {
fprintf(stderr, "%s:%u\n", __FILE__, __LINE__);
}
int fib(int n)
{
int f2=0;
int f1=1;
int fib=0;
int i;
if (n==0 || n==1)
return n;
for(i=2;i<=n;i++){
fib=f1+f2; /*sum*/
f2=f1;
f1=fib;
}
return fib;
}
//////////////////////////////////////////////////////////////////////
#define SINGLESTEP_NONE 0
#define SINGLESTEP_STEP 1
#define SINGLESTEP_BB 2
//////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
char *s_arch;
char *executable;
cpu_arch_t arch;
cpu_t *cpu;
uint8_t *RAM;
FILE *f;
int ramsize;
int r1, r2;
uint64_t t1, t2, t3, t4;
unsigned start_no = START_NO;
int singlestep = SINGLESTEP_NONE;
int log = 1;
int print_ir = 1;
/* parameter parsing */
if (argc < 3) {
printf("Usage: %s executable [arch] [itercount] [entries]\n", argv[0]);
return 0;
}
s_arch = argv[1];
executable = argv[2];
if (argc >= 4)
start_no = atoi(argv[3]);
if (!strcmp("mips", s_arch))
arch = CPU_ARCH_MIPS;
else if (!strcmp("m88k", s_arch))
arch = CPU_ARCH_M88K;
else if (!strcmp("arm", s_arch))
arch = CPU_ARCH_ARM;
else if (!strcmp("fapra", s_arch))
arch = CPU_ARCH_FAPRA;
else {
printf("unknown architecture '%s'!\n", s_arch);
return 0;
}
ramsize = 5*1024*1024;
RAM = (uint8_t*)malloc(ramsize);
cpu = cpu_new(arch, 0, 0);
cpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);
cpu_set_flags_debug(cpu, 0
| (print_ir? CPU_DEBUG_PRINT_IR : 0)
| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)
| (log? CPU_DEBUG_LOG :0)
| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP : 0)
| (singlestep == SINGLESTEP_BB? CPU_DEBUG_SINGLESTEP_BB : 0)
);
cpu_set_ram(cpu, RAM);
/* load code */
if (!(f = fopen(executable, "rb"))) {
printf("Could not open %s!\n", executable);
return 2;
}
cpu->code_start = START;
cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);
fclose(f);
cpu->code_entry = cpu->code_start + ENTRY;
cpu_tag(cpu, cpu->code_entry);
cpu_translate(cpu); /* force translation now */
printf("\n*** Executing...\n");
printf("number of iterations: %u\n", start_no);
uint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;
switch (arch) {
case CPU_ARCH_M88K:
reg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;
reg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];
reg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];
reg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];
break;
case CPU_ARCH_MIPS:
reg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];
reg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];
reg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];
break;
case CPU_ARCH_ARM:
reg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];
reg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];
reg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];
break;
case CPU_ARCH_FAPRA:
reg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];
reg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
reg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
break;
default:
fprintf(stderr, "architecture %u not handled.\n", arch);
exit(EXIT_FAILURE);
}
*reg_pc = cpu->code_entry;
*reg_lr = RET_MAGIC;
*reg_param = start_no;
printf("GUEST run..."); fflush(stdout);
t1 = abs_time();
cpu_run(cpu, debug_function);
t2 = abs_time();
r1 = *reg_result;
printf("done!\n");
printf("HOST run..."); fflush(stdout);
t3 = abs_time();
r2 = fib(start_no);
t4 = abs_time();
printf("done!\n");
cpu_free(cpu);
printf("Time GUEST: %" PRId64 "\n", t2-t1);
printf("Time HOST: %" PRId64 "\n", t4-t3);
printf("Result HOST: %d\n", r2);
printf("Result GUEST: %d\n", r1);
printf("GUEST required \033[1m%.2f%%\033[22m of HOST time.\n", (float)(t2-t1)/(float)(t4-t3)*100);
if (r1 == r2)
printf("\033[1mSUCCESS!\033[22m\n\n");
else
printf("\033[1mFAILED!\033[22m\n\n");
return 0;
}
//printf("%d\n", __LINE__);
<commit_msg>fix build<commit_after>#define START 0
#define ENTRY 0
#include "timings.h"
#include <inttypes.h>
#define START_NO 1000000000
#include <libcpu.h>
#include "arch/arm/arm_types.h"
#include "arch/m88k/m88k_isa.h"
#define RET_MAGIC 0x4D495354
static void
debug_function(cpu_t *cpu) {
fprintf(stderr, "%s:%u\n", __FILE__, __LINE__);
}
int fib(int n)
{
int f2=0;
int f1=1;
int fib=0;
int i;
if (n==0 || n==1)
return n;
for(i=2;i<=n;i++){
fib=f1+f2; /*sum*/
f2=f1;
f1=fib;
}
return fib;
}
//////////////////////////////////////////////////////////////////////
#define SINGLESTEP_NONE 0
#define SINGLESTEP_STEP 1
#define SINGLESTEP_BB 2
//////////////////////////////////////////////////////////////////////
int
main(int argc, char **argv)
{
char *s_arch;
char *executable;
cpu_arch_t arch;
cpu_t *cpu;
uint8_t *RAM;
FILE *f;
int ramsize;
int r1, r2;
uint64_t t1, t2, t3, t4;
unsigned start_no = START_NO;
int singlestep = SINGLESTEP_NONE;
int log = 1;
int print_ir = 1;
/* parameter parsing */
if (argc < 3) {
printf("Usage: %s executable [arch] [itercount] [entries]\n", argv[0]);
return 0;
}
s_arch = argv[1];
executable = argv[2];
if (argc >= 4)
start_no = atoi(argv[3]);
if (!strcmp("mips", s_arch))
arch = CPU_ARCH_MIPS;
else if (!strcmp("m88k", s_arch))
arch = CPU_ARCH_M88K;
else if (!strcmp("arm", s_arch))
arch = CPU_ARCH_ARM;
else if (!strcmp("fapra", s_arch))
arch = CPU_ARCH_FAPRA;
else {
printf("unknown architecture '%s'!\n", s_arch);
return 0;
}
ramsize = 5*1024*1024;
RAM = (uint8_t*)malloc(ramsize);
cpu = cpu_new(arch, 0, 0);
cpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);
cpu_set_flags_debug(cpu, 0
| (print_ir? CPU_DEBUG_PRINT_IR : 0)
| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)
| (log? CPU_DEBUG_LOG :0)
| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP : 0)
| (singlestep == SINGLESTEP_BB? CPU_DEBUG_SINGLESTEP_BB : 0)
);
cpu_set_ram(cpu, RAM);
/* load code */
if (!(f = fopen(executable, "rb"))) {
printf("Could not open %s!\n", executable);
return 2;
}
cpu->code_start = START;
cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);
fclose(f);
cpu->code_entry = cpu->code_start + ENTRY;
cpu_tag(cpu, cpu->code_entry);
cpu_translate(cpu); /* force translation now */
printf("\n*** Executing...\n");
printf("number of iterations: %u\n", start_no);
uint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;
switch (arch) {
case CPU_ARCH_M88K:
reg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;
reg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];
reg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];
reg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];
break;
case CPU_ARCH_MIPS:
reg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];
reg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];
reg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];
break;
case CPU_ARCH_ARM:
reg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];
reg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];
reg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];
break;
case CPU_ARCH_FAPRA:
reg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;
reg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];
reg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
reg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
break;
default:
fprintf(stderr, "architecture %u not handled.\n", arch);
exit(EXIT_FAILURE);
}
*reg_pc = cpu->code_entry;
*reg_lr = RET_MAGIC;
*reg_param = start_no;
printf("GUEST run..."); fflush(stdout);
t1 = abs_time();
cpu_run(cpu, debug_function);
t2 = abs_time();
r1 = *reg_result;
printf("done!\n");
printf("HOST run..."); fflush(stdout);
t3 = abs_time();
r2 = fib(start_no);
t4 = abs_time();
printf("done!\n");
cpu_free(cpu);
printf("Time GUEST: %" PRId64 "\n", t2-t1);
printf("Time HOST: %" PRId64 "\n", t4-t3);
printf("Result HOST: %d\n", r2);
printf("Result GUEST: %d\n", r1);
printf("GUEST required \033[1m%.2f%%\033[22m of HOST time.\n", (float)(t2-t1)/(float)(t4-t3)*100);
if (r1 == r2)
printf("\033[1mSUCCESS!\033[22m\n\n");
else
printf("\033[1mFAILED!\033[22m\n\n");
return 0;
}
//printf("%d\n", __LINE__);
<|endoftext|> |
<commit_before>#include "quad_factor_animator.h"
#include "p_rect.h"
#include "action.h"
#include "stack_action.h"
#include "algebra.h"
#include <typeinfo> //debug
#include <cassert> //debug
quad_factor_animator::quad_factor_animator(int a_, int b_, int c_) : animator(),
a(a_),
b(b_),
c(c_),
var_name(default_var_name),
var_val(default_var_val)
{
// set_up_scene();
// set_up_actions();
}
void quad_factor_animator::set_up_scene() {
// set up scene
// 3 p_rects to start
// 1st column: 1x by a x's
// 2nd column: 1x by b 1's
// 3rd column: 1 by c 1's
v.scn = std::make_shared<scene>();
auto r = std::make_shared<node>();
v.scn->set_root(r);
length x{var_name,var_val};
length unit_length{};
col1 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(a,x));
col2 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(b,unit_length));
col3 = std::make_shared<p_rect>(std::vector<length>(1,unit_length),std::vector<length>(c,unit_length));
col2->set_location(col1->width() + p_rect::unit_size,0,0);
col3->set_location(col1->width() + col2->width() + 2 * p_rect::unit_size,0,0);
v.scn->get_root()->add_child(col1);
v.scn->get_root()->add_child(col2);
v.scn->get_root()->add_child(col3);
}
std::shared_ptr<animation<wchar_t>> quad_factor_animator::animate() {
set_up_scene();
animation_ = std::make_shared<animation<wchar_t>>();
int unit_size = p_rect::unit_size;
// factors ax^2 + bx + c into (a0x + b0)(a1x + b1)
std::tuple<bool,int,int,int,int> f = algebra::quad_factor(a,b,c);
bool is_factorable = std::get<0>(f);
if (!is_factorable) {throw std::runtime_error("not factorable");}
int a0 = std::get<1>(f);
int b0 = std::get<2>(f);
int a1 = std::get<3>(f);
int b1 = std::get<4>(f);
// split first column into a0 columns, each of which is 1x wide and a1 x's high (group 1)
group1 = col1->split(dimension::y,a0);
// first split second column into two sub-columns
// col 2a: 1x wide by a0*b1 1's high
// col 2b: 1x wide by a1*b0 1's high
// call the parent of these two sub-columns group2
std::set<int> split_points = {a0 * b1};
group2 = col2->split(dimension::y,split_points);
col2a = std::dynamic_pointer_cast<p_rect>(group2->get_children()[0]);
col2b = std::dynamic_pointer_cast<p_rect>(group2->get_children()[1]);
// split subcolumns 2a and 2b into two groups of columns:
// group 2a: a0 columns, each of which is 1x wide and b1 1's high
// group 2b: a1 columns, each of which is 1x wide and b0 1's high
group2a = col2a->split(dimension::y,a0);
group2b = col2b->split(dimension::y,a1);
// split 3rd column into b0 p_rects, each of which is 1 wide and b1 1's high (group 3)
// set parent of resulting collection of p_rects to group3
group3 = col3->split(dimension::y,b0);
// shift group3 right to make room for stacking and swapping x's and y's for group2
// increase in width of group2 after these actions = unit_size + group2b->bounding_rect().height - 1
render_action(std::make_shared<shift>(group3,1,unit_size + group2b->bounding_rect().height - 1,0));
// stack_horizontal group2 (since its children are group2a and group2b,
// only those groups will separate and stack)
// space group2's children vertically
// space group2's children horizontally
// settle group2's children down
render_action(std::make_shared<stack_action>(group2,0,dimension::x,unit_size,4));
// merge group2b into a single p_rect
auto rect2b = p_rect::merge(group2b, dimension::y);
// swap x lengths and y lengths for group2b
rect2b->swap_x_y();
snapshot();
if (b0 > 1) {
// stack_horizontal group3
// space group3's children vertically
// space group3's children horizontally
// settle group3's children down
render_action(std::make_shared<stack_action>(group3,0,dimension::x,2,0));
}
if (a1 > 1) {
// shift group3 right to make room for stacking of group2b
// after stacking, group2b will increase by (a1 - 1) * var_val * p_rect::unit_size
render_action(std::make_shared<shift>(group3,0,(a1 - 1) * var_val * unit_size,0));
// stack group2b horizontally
render_action(std::make_shared<stack_action>(group2b,0,dimension::x,4,0));
}
// group 2b and 3 under a common parent, preserving scene locations
auto group_2b_3 = std::make_shared<node>();
group_2b_3->set_location(rect2b->get_scene_location());
v.scn->get_root()->add_child(group_2b_3,true);
group_2b_3->add_child(rect2b,true);
group_2b_3->add_child(group3,true);
// group 1 and 2a under a common parent, preserving scene locations
auto group_1_2a = std::make_shared<node>();
v.scn->get_root()->add_child(group_1_2a,true);
group_1_2a->add_child(group1,true);
group_1_2a->add_child(group2a,true);
if (a0 > 1) {
// shift group2b and group3 right to make room for stacking of group2a
render_action(std::make_shared<shift>(group_2b_3,0,(a0 - 1) * var_val * unit_size,0));
// stack group2a horizontally
render_action(std::make_shared<stack_action>(group2a,0,dimension::x,unit_size));
}
if (a0 > 1) {
// shift group2a, group 2b, and group3 right
// to make room for stacking of group1
render_action(std::make_shared<shift>(group_2b_3,0,(a0 - 1) * var_val * unit_size, 0));
render_action(std::make_shared<shift>(group2a,0,(a0 - 1) * var_val * unit_size, 0));
// stack group1 horizontally
render_action(std::make_shared<stack_action>(group1,0,dimension::x,unit_size));
}
// stack group_1_2a vertically
render_action(std::make_shared<stack_action>(group_1_2a,0,dimension::y));
// stack group_2b_3 vertically
render_action(std::make_shared<stack_action>(group_2b_3,0,dimension::y));
// join left and right
render_action(std::make_shared<shift>(group_2b_3,0,-(group_2b_3->get_location().x - group_1_2a->bounding_rect().width + 1),0));
return animation_;
}
<commit_msg>fixes to quad_factor_animator::animate()<commit_after>#include "quad_factor_animator.h"
#include "p_rect.h"
#include "action.h"
#include "stack_action.h"
#include "algebra.h"
#include <typeinfo> //debug
#include <cassert> //debug
quad_factor_animator::quad_factor_animator(int a_, int b_, int c_) : animator(),
a(a_),
b(b_),
c(c_),
var_name(default_var_name),
var_val(default_var_val)
{
// set_up_scene();
// set_up_actions();
}
void quad_factor_animator::set_up_scene() {
// set up scene
// 3 p_rects to start
// 1st column: 1x by a x's
// 2nd column: 1x by b 1's
// 3rd column: 1 by c 1's
v.scn = std::make_shared<scene>();
auto r = std::make_shared<node>();
v.scn->set_root(r);
length x{var_name,var_val};
length unit_length{};
col1 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(a,x));
col2 = std::make_shared<p_rect>(std::vector<length>(1,x),std::vector<length>(b,unit_length));
col3 = std::make_shared<p_rect>(std::vector<length>(1,unit_length),std::vector<length>(c,unit_length));
col2->set_location(col1->width() + p_rect::unit_size,0,0);
col3->set_location(col1->width() + col2->width() + 2 * p_rect::unit_size,0,0);
v.scn->get_root()->add_child(col1);
v.scn->get_root()->add_child(col2);
v.scn->get_root()->add_child(col3);
}
std::shared_ptr<animation<wchar_t>> quad_factor_animator::animate() {
set_up_scene();
animation_ = std::make_shared<animation<wchar_t>>();
int unit_size = p_rect::unit_size;
// factors ax^2 + bx + c into (a0x + b0)(a1x + b1)
std::tuple<bool,int,int,int,int> f = algebra::quad_factor(a,b,c);
bool is_factorable = std::get<0>(f);
if (!is_factorable) {throw std::runtime_error("not factorable");}
int a0 = std::get<1>(f);
int b0 = std::get<2>(f);
int a1 = std::get<3>(f);
int b1 = std::get<4>(f);
// split first column into a0 columns, each of which is 1x wide and a1 x's high (group 1)
group1 = col1->split(dimension::y,a0);
// first split second column into two sub-columns
// col 2a: 1x wide by a0*b1 1's high
// col 2b: 1x wide by a1*b0 1's high
// call the parent of these two sub-columns group2
std::set<int> split_points = {a0 * b1};
group2 = col2->split(dimension::y,split_points);
col2a = std::dynamic_pointer_cast<p_rect>(group2->get_children()[0]);
col2b = std::dynamic_pointer_cast<p_rect>(group2->get_children()[1]);
// split subcolumns 2a and 2b into two groups of columns:
// group 2a: a0 columns, each of which is 1x wide and b1 1's high
// group 2b: a1 columns, each of which is 1x wide and b0 1's high
group2a = col2a->split(dimension::y,a0);
group2b = col2b->split(dimension::y,a1);
// split 3rd column into b0 p_rects, each of which is 1 wide and b1 1's high (group 3)
// set parent of resulting collection of p_rects to group3
group3 = col3->split(dimension::y,b0);
// shift group 3 to allow space for
// stacking group 2.
render_action(std::make_shared<shift>(group3,1,unit_size + var_val * unit_size,0));
// stack_horizontal group2 (since its children are group2a and group2b,
// only those groups will separate and stack)
// space group2's children vertically
// space group2's children horizontally
// settle group2's children down
render_action(std::make_shared<stack_action>(group2,0,dimension::x,unit_size / 2,unit_size));
if (b0 > 1) {
// stack_horizontal group3
// space group3's children vertically
// space group3's children horizontally
// settle group3's children down
render_action(std::make_shared<stack_action>(group3,0,dimension::x,unit_size / 2,0));
}
if (a1 > 1) {
// shift group3 right to make space for stacking of group2b
render_action(std::make_shared<shift>(group3,0, (a1 - 1) * var_val * unit_size,0));
// stack group2b horizontally
render_action(std::make_shared<stack_action>(group2b,0,dimension::x,unit_size / 2,0));
}
// merge group2b into a single p_rect
auto rect2b = p_rect::merge(group2b, dimension::y);
// if necessary, move group3 to make space
// for swapping group2b's x's and y's
int height_2b = rect2b->height();
int width_2b = rect2b->width();
if (height_2b > width_2b) {
render_action(std::make_shared<shift>(group3,0,height_2b - width_2b,0));
}
// swap x lengths and y lengths for group2b
rect2b->swap_x_y();
snapshot();
// group 2b and 3 under a common parent, preserving scene locations
auto group_2b_3 = std::make_shared<node>();
group_2b_3->set_location(rect2b->get_scene_location());
v.scn->get_root()->add_child(group_2b_3,true);
group_2b_3->add_child(rect2b,true);
group_2b_3->add_child(group3,true);
// group 1 and 2a under a common parent, preserving scene locations
auto group_1_2a = std::make_shared<node>();
v.scn->get_root()->add_child(group_1_2a,true);
group_1_2a->add_child(group1,true);
group_1_2a->add_child(group2a,true);
if (a0 > 1) {
// shift group2b and group3 right to make room for stacking of group2a
render_action(std::make_shared<shift>(group_2b_3,0,(a0 - 1) * var_val * unit_size,0));
// stack group2a horizontally
render_action(std::make_shared<stack_action>(group2a,0,dimension::x,unit_size));
}
if (a0 > 1) {
// shift group2a, group 2b, and group3 right
// to make room for stacking of group1
auto shift_2b_3 = std::make_shared<shift>(group_2b_3,0,(a0 - 1) * var_val * unit_size, 0);
auto shift_2a = std::make_shared<shift>(group2a,0,(a0 - 1) * var_val * unit_size, 0);
auto shift_2a_2b_3 = std::make_shared<action>();
shift_2a_2b_3->add_child(shift_2a);
shift_2a_2b_3->add_child(shift_2b_3);
render_action(shift_2a_2b_3);
// stack group1 horizontally
render_action(std::make_shared<stack_action>(group1,0,dimension::x,unit_size));
}
// stack group_1_2a vertically
render_action(std::make_shared<stack_action>(group_1_2a,0,dimension::y));
// stack group_2b_3 vertically
render_action(std::make_shared<stack_action>(group_2b_3,0,dimension::y));
// join left and right
render_action(std::make_shared<shift>(group_2b_3,0,-(group_2b_3->get_location().x - group_1_2a->bounding_rect().width + 1),0));
return animation_;
}
<|endoftext|> |
<commit_before>#pragma once
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
public:
explicit bitnode(void) : zero{nullptr}, one{nullptr}, data{nullptr} {}
private:
bitnode* zero;
bitnode* one;
A* data;
};
}
}<commit_msg>make default constructor inline<commit_after>#pragma once
namespace despairagus {
namespace bitnode {
template <typename A>
class bitnode {
template<typename B>
using conref = const B &;
using byte = unsigned char;
using bit = bool;
public:
inline explicit bitnode(void) : zero{nullptr}, one{nullptr}, data{nullptr} {}
private:
bitnode* zero;
bitnode* one;
A* data;
};
}
}<|endoftext|> |
<commit_before>#ifndef TOKEN_PARSER_HPP
#define TOKEN_PARSER_HPP
#include <string>
#include <vector>
#include <algorithm>
#include "utils/util.hpp"
#include "utils/error.hpp"
#include "parser/baseParser.hpp"
#include "ast.hpp"
#include "token.hpp"
#include "operator.hpp"
// The compiler was whining about some move assignments for virtual bases
// The classes it mentioned don't actually have anything to assign, so I don't care
#pragma GCC diagnostic ignored "-Wvirtual-move-assign"
/*
EBNF-ish format of a program:
program = block ;
block = [ statement, ";", { statement, ";" } ] ;
statement = declaration | ( "define", function ) | for_loop | while_loop | block | if_statement | try_catch | throw_statement | expression ;
declaration = "define" | type_list, ident, [ "=", expression ] ;
for_loop = "for", expression, ";", expression, ";", expression, "do", block, "end" ;
while_loop = "while", expression, "do", block, "end" ;
if_statement = "if", expression, "do", block, [ "else", block | if_statement ] | "end" ;
type_definition = "define", "type", ident, [ "inherits", type_list ], "do", [ contructor_definition ], [ { method_definition | member_definition } ], "end" ;
constructor_definition = "define", "constructor", [ argument, {",", argument } ], "do", block, "end" ;
method_definition = "define", [ visibility_specifier ], [ "static" ], function ;
member_definition = "define", [ visibility_specifier ], [ "static" ], ident, [ "=", expression ] ;
try_catch = "try", block, "catch", type_list, ident, "do", block, "end" ;
throw_statement = "throw", expression ;
function = "function", ident, [ argument, {",", argument } ], [ "=>", type_list ], "do", block, "end" ;
visibility_specifier = "public" | "private" | "protected" ;
type_list = ident, {",", ident} ;
argument = ( "[", type_list, ident, "]" ) | ( "[", ident, ":", type_list, "]" ) ;
expression = primary, { binary_op, primary } ;
primary = { prefix_op }, terminal, { postfix_op } ;
binary_op = ? binary operator ? ;
prefix_op = ? prefix operator ? ;
postfix_op = ? postfix operator ? ;
terminal = ? see Token's isTerminal method ? ;
function_call = ident, "(", expression, { ",", expression }, ")" ;
ident = ? any valid identifier ? ;
*/
/**
\brief Base of TokenParser. Maintains all of its state, and provides convenience methods for manipulating it.
*/
class TokenBaseParser: public BaseParser {
protected:
std::vector<Token> input;
uint64 pos = 0;
TokenBaseParser() {}
virtual ~TokenBaseParser() = 0;
/// Get token at current position
inline Token current() {
return input[pos];
}
/// Skip a number of tokens, usually just advances to the next one
inline void skip(int by = 1) {
pos += by;
}
/// Accept a TokenType
inline bool accept(TokenType tok) {
return tok == current().type;
}
/// Accept a Operator::Symbol
inline bool accept(Operator::Symbol operatorSymbol) {
if (!current().isOperator()) return false;
if (current().hasOperatorSymbol(operatorSymbol)) return true;
return false;
}
/// Accept a Fixity
inline bool accept(Fixity fixity) {
return current().isOperator() && current().hasFixity(fixity);
}
/// Accept only terminals
inline bool acceptTerminal() {
return current().isTerminal();
}
/// Accept anything that ends an expression
inline bool acceptEndOfExpression() {
return accept(C_SEMI) || accept(C_PAREN_RIGHT) || accept(FILE_END) || accept(K_DO);
}
/// Expect certain tokens to appear (throw otherwise)
bool expect(TokenType tok, std::string errorMessage = "Unexpected symbol");
/// Expect a semicolon \see expect
void expectSemi();
};
/**
\brief Provides the \link expression \endlink method for parsing an expression.
*/
class ExpressionParser: virtual public TokenBaseParser {
protected:
ExpressionParser() {}
private:
/// Creates an ExpressionNode from the current Token
Node<ExpressionNode>::Link exprFromCurrent();
/**
\brief Parse a primary in the expression
';' is an empty expression for example
\returns an ExpressionNode, or nullptr if the expression is empty (terminates immediately)
*/
Node<ExpressionNode>::Link parseExpressionPrimary();
/**
\brief Implementation detail of expression
This method exists to allow recursion.
*/
Node<ExpressionNode>::Link expressionImpl(Node<ExpressionNode>::Link lhs, int minPrecedence);
public:
/**
\brief Parse an expression starting at the current token
\param throwIfEmpty throws an error on empty expressions; if set to false, empty expressions return nullptr
*/
Node<ExpressionNode>::Link expression(bool throwIfEmpty = true);
};
/**
\brief Provides the \link declaration \endlink method for parsing a declaration.
Depends on ExpressionParser for expression parsing.
*/
class DeclarationParser: virtual public ExpressionParser {
protected:
DeclarationParser() {}
private:
/// Creates a DeclarationNode from a list of types, handles initialization if available
Node<DeclarationNode>::Link declarationFromTypes(TypeList typeList);
public:
/**
\brief Parse a declaration starting at the current token
\param throwIfEmpty throws an error on empty declarations; if set to false, empty declarations return nullptr
*/
Node<DeclarationNode>::Link declaration(bool throwIfEmpty = true);
};
class StatementParser;
/**
\brief Provides the \link block \endlink method for parsing a block.
Depends on StatementParser for parsing individual statements.
*/
class BlockParser: virtual public TokenBaseParser {
protected:
/// Storing this pointer avoids circular inheritance between BlockParser and StatementParser
StatementParser* stp;
/// \copydoc stp
BlockParser(StatementParser* stp);
public:
/**
\brief Parse a block, depending on its type
Normal code blocks are enclosed in K_DO/K_END.
Root blocks aren't expected to be enclosed, and instead they end at the file end.
If blocks can also be ended with K_ELSE besides K_END.
*/
Node<BlockNode>::Link block(BlockType type);
};
/**
\brief Provides the \link ifStatement \endlink method for parsing an if statement.
Depends on ExpressionParser for parsing expressions.
Depends on BlockParser for parsing blocks.
*/
class IfStatementParser: virtual public ExpressionParser, virtual public BlockParser {
protected:
/// \copydoc BlockNode(StatementParser*)
IfStatementParser(StatementParser* stp);
public:
/**
\brief Parse an if statement starting at the current token
This function assumes K_IF has been skipped.
*/
Node<BranchNode>::Link ifStatement();
};
/**
\brief Provides the \link statement \endlink method for parsing an a statement.
Depends on ExpressionParser for parsing expressions.
Depends on IfStatementParser for parsing if statements.
Depends on BlockParser for parsing blocks.
Depends on DeclarationParser for parsing declarations.
*/
class StatementParser: virtual public IfStatementParser, virtual public DeclarationParser {
protected:
/// \see BlockNode(StatementParser*)
StatementParser();
public:
/**
\brief Parse a statement
\returns whatever node was parsed
*/
ASTNode::Link statement();
};
/**
\brief Parses a list of tokens, and produces an AST.
*/
class TokenParser: public StatementParser {
public:
TokenParser();
/**
\brief Call this method to actually do the parsing before using getTree
\param input list of tokens from lexer
*/
void parse(std::vector<Token> input);
};
#endif
<commit_msg>Fix link errors<commit_after>#ifndef TOKEN_PARSER_HPP
#define TOKEN_PARSER_HPP
#include <string>
#include <vector>
#include <algorithm>
#include "utils/util.hpp"
#include "utils/error.hpp"
#include "parser/baseParser.hpp"
#include "ast.hpp"
#include "token.hpp"
#include "operator.hpp"
// The compiler was whining about some move assignments for virtual bases
// The classes it mentioned don't actually have anything to assign, so I don't care
#pragma GCC diagnostic ignored "-Wvirtual-move-assign"
/*
EBNF-ish format of a program:
program = block ;
block = [ statement, ";", { statement, ";" } ] ;
statement = declaration | ( "define", function ) | for_loop | while_loop | block | if_statement | try_catch | throw_statement | expression ;
declaration = "define" | type_list, ident, [ "=", expression ] ;
for_loop = "for", expression, ";", expression, ";", expression, "do", block, "end" ;
while_loop = "while", expression, "do", block, "end" ;
if_statement = "if", expression, "do", block, [ "else", block | if_statement ] | "end" ;
type_definition = "define", "type", ident, [ "inherits", type_list ], "do", [ contructor_definition ], [ { method_definition | member_definition } ], "end" ;
constructor_definition = "define", "constructor", [ argument, {",", argument } ], "do", block, "end" ;
method_definition = "define", [ visibility_specifier ], [ "static" ], function ;
member_definition = "define", [ visibility_specifier ], [ "static" ], ident, [ "=", expression ] ;
try_catch = "try", block, "catch", type_list, ident, "do", block, "end" ;
throw_statement = "throw", expression ;
function = "function", ident, [ argument, {",", argument } ], [ "=>", type_list ], "do", block, "end" ;
visibility_specifier = "public" | "private" | "protected" ;
type_list = ident, {",", ident} ;
argument = ( "[", type_list, ident, "]" ) | ( "[", ident, ":", type_list, "]" ) ;
expression = primary, { binary_op, primary } ;
primary = { prefix_op }, terminal, { postfix_op } ;
binary_op = ? binary operator ? ;
prefix_op = ? prefix operator ? ;
postfix_op = ? postfix operator ? ;
terminal = ? see Token's isTerminal method ? ;
function_call = ident, "(", expression, { ",", expression }, ")" ;
ident = ? any valid identifier ? ;
*/
/**
\brief Base of TokenParser. Maintains all of its state, and provides convenience methods for manipulating it.
*/
class TokenBaseParser: public BaseParser {
protected:
std::vector<Token> input;
uint64 pos = 0;
TokenBaseParser() {}
virtual ~TokenBaseParser() = 0;
/// Get token at current position
inline Token current() {
return input[pos];
}
/// Skip a number of tokens, usually just advances to the next one
inline void skip(int by = 1) {
pos += by;
}
/// Accept a TokenType
inline bool accept(TokenType tok) {
return tok == current().type;
}
/// Accept a Operator::Symbol
inline bool accept(Operator::Symbol operatorSymbol) {
if (!current().isOperator()) return false;
if (current().hasOperatorSymbol(operatorSymbol)) return true;
return false;
}
/// Accept a Fixity
inline bool accept(Fixity fixity) {
return current().isOperator() && current().hasFixity(fixity);
}
/// Accept only terminals
inline bool acceptTerminal() {
return current().isTerminal();
}
/// Accept anything that ends an expression
inline bool acceptEndOfExpression() {
return accept(C_SEMI) || accept(C_PAREN_RIGHT) || accept(FILE_END) || accept(K_DO);
}
/// Expect certain tokens to appear (throw otherwise)
bool expect(TokenType tok, std::string errorMessage = "Unexpected symbol");
/// Expect a semicolon \see expect
void expectSemi();
};
inline TokenBaseParser::~TokenBaseParser() {}
/**
\brief Provides the \link expression \endlink method for parsing an expression.
*/
class ExpressionParser: virtual public TokenBaseParser {
protected:
ExpressionParser() {}
private:
/// Creates an ExpressionNode from the current Token
Node<ExpressionNode>::Link exprFromCurrent();
/**
\brief Parse a primary in the expression
';' is an empty expression for example
\returns an ExpressionNode, or nullptr if the expression is empty (terminates immediately)
*/
Node<ExpressionNode>::Link parseExpressionPrimary();
/**
\brief Implementation detail of expression
This method exists to allow recursion.
*/
Node<ExpressionNode>::Link expressionImpl(Node<ExpressionNode>::Link lhs, int minPrecedence);
public:
/**
\brief Parse an expression starting at the current token
\param throwIfEmpty throws an error on empty expressions; if set to false, empty expressions return nullptr
*/
Node<ExpressionNode>::Link expression(bool throwIfEmpty = true);
};
/**
\brief Provides the \link declaration \endlink method for parsing a declaration.
Depends on ExpressionParser for expression parsing.
*/
class DeclarationParser: virtual public ExpressionParser {
protected:
DeclarationParser() {}
private:
/// Creates a DeclarationNode from a list of types, handles initialization if available
Node<DeclarationNode>::Link declarationFromTypes(TypeList typeList);
public:
/**
\brief Parse a declaration starting at the current token
\param throwIfEmpty throws an error on empty declarations; if set to false, empty declarations return nullptr
*/
Node<DeclarationNode>::Link declaration(bool throwIfEmpty = true);
};
class StatementParser;
/**
\brief Provides the \link block \endlink method for parsing a block.
Depends on StatementParser for parsing individual statements.
*/
class BlockParser: virtual public TokenBaseParser {
protected:
/// Storing this pointer avoids circular inheritance between BlockParser and StatementParser
StatementParser* stp;
/// \copydoc stp
BlockParser(StatementParser* stp);
public:
/**
\brief Parse a block, depending on its type
Normal code blocks are enclosed in K_DO/K_END.
Root blocks aren't expected to be enclosed, and instead they end at the file end.
If blocks can also be ended with K_ELSE besides K_END.
*/
Node<BlockNode>::Link block(BlockType type);
};
/**
\brief Provides the \link ifStatement \endlink method for parsing an if statement.
Depends on ExpressionParser for parsing expressions.
Depends on BlockParser for parsing blocks.
*/
class IfStatementParser: virtual public ExpressionParser, virtual public BlockParser {
protected:
/// \copydoc BlockNode(StatementParser*)
IfStatementParser(StatementParser* stp);
public:
/**
\brief Parse an if statement starting at the current token
This function assumes K_IF has been skipped.
*/
Node<BranchNode>::Link ifStatement();
};
/**
\brief Provides the \link statement \endlink method for parsing an a statement.
Depends on ExpressionParser for parsing expressions.
Depends on IfStatementParser for parsing if statements.
Depends on BlockParser for parsing blocks.
Depends on DeclarationParser for parsing declarations.
*/
class StatementParser: virtual public IfStatementParser, virtual public DeclarationParser {
protected:
/// \see BlockNode(StatementParser*)
StatementParser();
public:
/**
\brief Parse a statement
\returns whatever node was parsed
*/
ASTNode::Link statement();
};
/**
\brief Parses a list of tokens, and produces an AST.
*/
class TokenParser: public StatementParser {
public:
TokenParser();
/**
\brief Call this method to actually do the parsing before using getTree
\param input list of tokens from lexer
*/
void parse(std::vector<Token> input);
};
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <utility>
#include <type_traits>
#include <string>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
}
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
}
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
metamusil::void_t<
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>>
{
static any
dispatch(const any& src)
{
TargetType temp = (TargetType)src.get<SourceType>();
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
}
}
<commit_msg>Add typedefs for function signatures for string de-/serialization. modified: include/reflection_binding.hpp<commit_after>#pragma once
#include <utility>
#include <type_traits>
#include <string>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
}
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
}
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
metamusil::void_t<
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>>
{
static any
dispatch(const any& src)
{
TargetType temp = (TargetType)src.get<SourceType>();
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/thread_impl.hh>
#include <seastar/core/future.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/timer.hh>
#include <seastar/core/scheduling.hh>
#include <memory>
#include <setjmp.h>
#include <type_traits>
#include <chrono>
#include <seastar/util/std-compat.hh>
#include <ucontext.h>
#include <boost/intrusive/list.hpp>
/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
/// - seastar threads are cooperative; they are never preempted except
/// at blocking points (see below)
/// - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future<>.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
/// seastar::thread th([] {
/// sleep(5s).get(); // blocking point
/// });
/// \endcode
///
/// An easy way to launch a thread and carry out some computation, and return a
/// result from this execution is by using the \ref seastar::async() function.
/// The result is returned as a future, so that non-threaded code can wait for
/// the thread to terminate and yield a result.
/// Seastar API namespace
namespace seastar {
/// \addtogroup thread-module
/// @{
class thread;
class thread_attributes;
/// Class that holds attributes controling the behavior of a thread.
class thread_attributes {
public:
std::optional<seastar::scheduling_group> sched_group;
// For stack_size 0, a default value will be used (128KiB when writing this comment)
size_t stack_size = 0;
};
/// \cond internal
extern thread_local jmp_buf_link g_unthreaded_context;
// Internal class holding thread state. We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context final : private task {
struct stack_deleter {
void operator()(char *ptr) const noexcept;
int valgrind_id;
stack_deleter(int valgrind_id);
};
using stack_holder = std::unique_ptr<char[], stack_deleter>;
stack_holder _stack;
noncopyable_function<void ()> _func;
jmp_buf_link _context;
promise<> _done;
bool _joined = false;
boost::intrusive::list_member_hook<> _all_link;
using all_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_all_link>,
boost::intrusive::constant_time_size<false>>;
static thread_local all_thread_list _all_threads;
private:
static void s_main(int lo, int hi); // all parameters MUST be 'int' for makecontext
void setup(size_t stack_size);
void main();
stack_holder make_stack(size_t stack_size);
virtual void run_and_dispose() noexcept override; // from task class
public:
thread_context(thread_attributes attr, noncopyable_function<void ()> func);
~thread_context();
void switch_in();
void switch_out();
bool should_yield() const;
void reschedule();
void yield();
task* waiting_task() noexcept override { return _done.waiting_task(); }
friend class thread;
friend void thread_impl::switch_in(thread_context*);
friend void thread_impl::switch_out(thread_context*);
friend scheduling_group thread_impl::sched_group(const thread_context*);
};
/// \endcond
/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future. When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
std::unique_ptr<thread_context> _context;
static thread_local thread* _current;
public:
/// \brief Constructs a \c thread object that does not represent a thread
/// of execution.
thread() = default;
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(Func func);
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param attr Attributes describing the new thread.
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(thread_attributes attr, Func func);
/// \brief Moves a thread object.
thread(thread&& x) noexcept = default;
/// \brief Move-assigns a thread object.
thread& operator=(thread&& x) noexcept = default;
/// \brief Destroys a \c thread object.
///
/// The thread must not represent a running thread of execution (see join()).
~thread() { assert(!_context || _context->_joined); }
/// \brief Waits for thread execution to terminate.
///
/// Waits for thread execution to terminate, and marks the thread object as not
/// representing a running thread of execution.
future<> join();
/// \brief Voluntarily defer execution of current thread.
///
/// Gives other threads/fibers a chance to run on current CPU.
/// The current thread will resume execution promptly.
static void yield();
/// \brief Checks whether this thread ought to call yield() now.
///
/// Useful where we cannot call yield() immediately because we
/// Need to take some cleanup action first.
static bool should_yield();
/// \brief Yield if this thread ought to call yield() now.
///
/// Useful where a code does long running computation and does
/// not want to hog cpu for more then its share
static void maybe_yield();
static bool running_in_thread() {
return thread_impl::get() != nullptr;
}
};
template <typename Func>
inline
thread::thread(thread_attributes attr, Func func)
: _context(std::make_unique<thread_context>(std::move(attr), std::move(func))) {
}
template <typename Func>
inline
thread::thread(Func func)
: thread(thread_attributes(), std::move(func)) {
}
inline
future<>
thread::join() {
_context->_joined = true;
return _context->_done.get_future();
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param attr a \ref thread_attributes instance
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
///
/// Example:
/// \code
/// future<int> compute_sum(int a, int b) {
/// thread_attributes attr = {};
/// attr.sched_group = some_scheduling_group_ptr;
/// return seastar::async(attr, [a, b] {
/// // some blocking code:
/// sleep(1s).get();
/// return a + b;
/// });
/// }
/// \endcode
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(thread_attributes attr, Func&& func, Args&&... args) noexcept {
using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
struct work {
thread_attributes attr;
Func func;
std::tuple<Args...> args;
promise<return_type> pr;
thread th;
};
try {
auto wp = std::make_unique<work>(work{std::move(attr), std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)});
auto& w = *wp;
auto ret = w.pr.get_future();
w.th = thread(std::move(w.attr), [&w] {
futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
});
return w.th.join().then([ret = std::move(ret)] () mutable {
return std::move(ret);
}).finally([wp = std::move(wp)] {});
} catch (...) {
return futurize<return_type>::make_exception_future(std::current_exception());
}
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) noexcept {
return async(thread_attributes{}, std::forward<Func>(func), std::forward<Args>(args)...);
}
/// @}
}
<commit_msg>doc: thread: fix \ref future<><commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/thread_impl.hh>
#include <seastar/core/future.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/timer.hh>
#include <seastar/core/scheduling.hh>
#include <memory>
#include <setjmp.h>
#include <type_traits>
#include <chrono>
#include <seastar/util/std-compat.hh>
#include <ucontext.h>
#include <boost/intrusive/list.hpp>
/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
/// - seastar threads are cooperative; they are never preempted except
/// at blocking points (see below)
/// - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
/// seastar::thread th([] {
/// sleep(5s).get(); // blocking point
/// });
/// \endcode
///
/// An easy way to launch a thread and carry out some computation, and return a
/// result from this execution is by using the \ref seastar::async() function.
/// The result is returned as a future, so that non-threaded code can wait for
/// the thread to terminate and yield a result.
/// Seastar API namespace
namespace seastar {
/// \addtogroup thread-module
/// @{
class thread;
class thread_attributes;
/// Class that holds attributes controling the behavior of a thread.
class thread_attributes {
public:
std::optional<seastar::scheduling_group> sched_group;
// For stack_size 0, a default value will be used (128KiB when writing this comment)
size_t stack_size = 0;
};
/// \cond internal
extern thread_local jmp_buf_link g_unthreaded_context;
// Internal class holding thread state. We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context final : private task {
struct stack_deleter {
void operator()(char *ptr) const noexcept;
int valgrind_id;
stack_deleter(int valgrind_id);
};
using stack_holder = std::unique_ptr<char[], stack_deleter>;
stack_holder _stack;
noncopyable_function<void ()> _func;
jmp_buf_link _context;
promise<> _done;
bool _joined = false;
boost::intrusive::list_member_hook<> _all_link;
using all_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_all_link>,
boost::intrusive::constant_time_size<false>>;
static thread_local all_thread_list _all_threads;
private:
static void s_main(int lo, int hi); // all parameters MUST be 'int' for makecontext
void setup(size_t stack_size);
void main();
stack_holder make_stack(size_t stack_size);
virtual void run_and_dispose() noexcept override; // from task class
public:
thread_context(thread_attributes attr, noncopyable_function<void ()> func);
~thread_context();
void switch_in();
void switch_out();
bool should_yield() const;
void reschedule();
void yield();
task* waiting_task() noexcept override { return _done.waiting_task(); }
friend class thread;
friend void thread_impl::switch_in(thread_context*);
friend void thread_impl::switch_out(thread_context*);
friend scheduling_group thread_impl::sched_group(const thread_context*);
};
/// \endcond
/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future. When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
std::unique_ptr<thread_context> _context;
static thread_local thread* _current;
public:
/// \brief Constructs a \c thread object that does not represent a thread
/// of execution.
thread() = default;
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(Func func);
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param attr Attributes describing the new thread.
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(thread_attributes attr, Func func);
/// \brief Moves a thread object.
thread(thread&& x) noexcept = default;
/// \brief Move-assigns a thread object.
thread& operator=(thread&& x) noexcept = default;
/// \brief Destroys a \c thread object.
///
/// The thread must not represent a running thread of execution (see join()).
~thread() { assert(!_context || _context->_joined); }
/// \brief Waits for thread execution to terminate.
///
/// Waits for thread execution to terminate, and marks the thread object as not
/// representing a running thread of execution.
future<> join();
/// \brief Voluntarily defer execution of current thread.
///
/// Gives other threads/fibers a chance to run on current CPU.
/// The current thread will resume execution promptly.
static void yield();
/// \brief Checks whether this thread ought to call yield() now.
///
/// Useful where we cannot call yield() immediately because we
/// Need to take some cleanup action first.
static bool should_yield();
/// \brief Yield if this thread ought to call yield() now.
///
/// Useful where a code does long running computation and does
/// not want to hog cpu for more then its share
static void maybe_yield();
static bool running_in_thread() {
return thread_impl::get() != nullptr;
}
};
template <typename Func>
inline
thread::thread(thread_attributes attr, Func func)
: _context(std::make_unique<thread_context>(std::move(attr), std::move(func))) {
}
template <typename Func>
inline
thread::thread(Func func)
: thread(thread_attributes(), std::move(func)) {
}
inline
future<>
thread::join() {
_context->_joined = true;
return _context->_done.get_future();
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param attr a \ref thread_attributes instance
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
///
/// Example:
/// \code
/// future<int> compute_sum(int a, int b) {
/// thread_attributes attr = {};
/// attr.sched_group = some_scheduling_group_ptr;
/// return seastar::async(attr, [a, b] {
/// // some blocking code:
/// sleep(1s).get();
/// return a + b;
/// });
/// }
/// \endcode
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(thread_attributes attr, Func&& func, Args&&... args) noexcept {
using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
struct work {
thread_attributes attr;
Func func;
std::tuple<Args...> args;
promise<return_type> pr;
thread th;
};
try {
auto wp = std::make_unique<work>(work{std::move(attr), std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)});
auto& w = *wp;
auto ret = w.pr.get_future();
w.th = thread(std::move(w.attr), [&w] {
futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
});
return w.th.join().then([ret = std::move(ret)] () mutable {
return std::move(ret);
}).finally([wp = std::move(wp)] {});
} catch (...) {
return futurize<return_type>::make_exception_future(std::current_exception());
}
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) noexcept {
return async(thread_attributes{}, std::forward<Func>(func), std::forward<Args>(args)...);
}
/// @}
}
<|endoftext|> |
<commit_before>
template<
class LockType,
template <class> class CreationPolicy>
Logger& Launcher<LockType, CreationPolicy>::logger_ = LoggerFactory::getLogger( "Framework" );
template<
class LockType,
template <class> class CreationPolicy>
Launcher<LockType, CreationPolicy>::Launcher()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#ctor] Called." );
this->registry_ = this->createRegistry();
}
template<
class LockType,
template <class> class CreationPolicy>
Launcher<LockType, CreationPolicy>::~Launcher()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#destructor] Called." );
delete (this->registry_);
}
template<
class LockType,
template <class> class CreationPolicy>
IRegistry& Launcher<LockType, CreationPolicy>::getRegistry()
{
return (*(this->registry_));
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::setLogLevel( Logger::LogLevel level )
{
LoggerFactory::setLogLevel( level );
}
template<
class LockType,
template <class> class CreationPolicy>
IRegistry* Launcher<LockType, CreationPolicy>::createRegistry()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#createRegistry] Called." );
return new IRegistryImpl<LockType>;
}
template<
class LockType,
template <class> class CreationPolicy>
IBundleContext* Launcher<LockType, CreationPolicy>::createBundleContext( const std::string& bundleName )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#createBundleContext] Called." );
return new IBundleContextImpl( bundleName, (*(this->registry_)) );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::start( std::vector<BundleConfiguration> &configVector )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Called." );
std::vector<BundleConfiguration>::iterator itVectorData;
itVectorData = configVector.begin();
for (itVectorData = configVector.begin(); itVectorData != configVector.end(); itVectorData++)
{
BundleConfiguration bundleConfig = *(itVectorData);
this->objectCreator_.setSearchConfiguration( true,
bundleConfig.getLibraryPath(), bundleConfig.getLibraryName() );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Reading configuration: Library path: %1, class name: %2",
bundleConfig.getLibraryPath(), bundleConfig.getClassName() );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Loading bundle activator: Library path: %1, class name: %2",
bundleConfig.getLibraryPath(), bundleConfig.getClassName() );
IBundleActivator* bundleActivator;
try
{
bundleActivator = this->objectCreator_.createObject( bundleConfig.getClassName() );
}
catch ( ObjectCreationException &exc )
{
std::string msg( exc.what() );
logger_.log( Logger::LOG_ERROR, "[Launcher#start] Error during loading bundle activator, exc: %1", msg );
continue;
}
IBundleContext* bundleCtxt = this->createBundleContext( bundleConfig.getBundleName() );
BundleInfoBase* bundleInfo = new BundleInfo( bundleConfig.getBundleName(), false, bundleActivator, bundleCtxt );
this->registry_->addBundleInfo( (*bundleInfo) );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Start bundle." );
bundleActivator->start( bundleCtxt );
}
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::startAdministrationBundle()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#startAdministrationBundle] Called." );
IBundleActivator* adminBundleActivator = this->objectCreator_.createObject( "sof::services::admin::AdministrationActivator" );
IBundleContext* bundleCtxt = this->createBundleContext( "AdministrationBundle" );
BundleInfoBase* bundleInfo = new BundleInfo( "AdministrationBundle", true, adminBundleActivator, bundleCtxt );
this->registry_->addBundleInfo( (*bundleInfo) );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Start bundle." );
AdministrationActivator* adminActivator = static_cast<AdministrationActivator*> (adminBundleActivator);
adminActivator->setAdministrationProvider( this );
adminActivator->start( bundleCtxt );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::stop()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#stop] Called." );
this->registry_->removeAllBundleInfos();
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::startBundle( BundleConfiguration bundleConfig )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#startBundle] Called, bundle config: %1", bundleConfig.toString() );
std::vector<BundleConfiguration> vec;
vec.push_back( bundleConfig );
this->start( vec );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::stopBundle( const std::string& bundleName )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#stopBundle] Called, bundle name: %1", bundleName );
this->registry_->removeBundleInfo( bundleName );
}
template<
class LockType,
template <class> class CreationPolicy>
std::vector<std::string> Launcher<LockType, CreationPolicy>::getBundleNames()
{
std::vector<std::string> bundleNameVec;
std::vector<BundleInfoBase*> vec = this->registry_->getBundleInfos();
std::vector<BundleInfoBase*>::iterator iter;
for ( iter = vec.begin(); iter != vec.end(); iter++ )
{
bundleNameVec.push_back( (*iter)->getBundleName() );
}
return bundleNameVec;
}
template<
class LockType,
template <class> class CreationPolicy>
std::string Launcher<LockType, CreationPolicy>::dumpBundleInfo( const std::string& bundleName )
{
BundleInfoBase* bi = this->registry_->getBundleInfo( bundleName );
if ( bi == 0 )
{
return "Bundle not available!";
}
else
{
return bi->toString();
}
}
template<
class LockType,
template <class> class CreationPolicy>
std::string Launcher<LockType, CreationPolicy>::dumpAllBundleNames()
{
std::vector<BundleInfoBase*> vec = this->registry_->getBundleInfos();
std::vector<BundleInfoBase*>::iterator it;
std::ostringstream stream;
stream << "*** Started Bundles *** " << endl;
for ( it = vec.begin(); it != vec.end(); it++ )
{
stream << (*it)->getBundleName() << endl;
}
stream << endl;
return stream.str();
}
template<
class LockType,
template <class> class CreationPolicy>
BundleInfoBase& Launcher<LockType, CreationPolicy>::getBundleInfo( const std::string& bundleName )
{
return ( * ( this->registry_->getBundleInfo( bundleName ) ) );
}
<commit_msg>add interface to osgi laucher<commit_after>
template<
class LockType,
template <class> class CreationPolicy>
Logger& Launcher<LockType, CreationPolicy>::logger_ = LoggerFactory::getLogger( "Framework" );
template<
class LockType,
template <class> class CreationPolicy>
Launcher<LockType, CreationPolicy>::Launcher()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#ctor] Called." );
this->registry_ = this->createRegistry();
}
template<
class LockType,
template <class> class CreationPolicy>
Launcher<LockType, CreationPolicy>::~Launcher()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#destructor] Called." );
delete (this->registry_);
}
template<
class LockType,
template <class> class CreationPolicy>
IRegistry& Launcher<LockType, CreationPolicy>::getRegistry()
{
return (*(this->registry_));
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::setLogLevel( Logger::LogLevel level )
{
LoggerFactory::setLogLevel( level );
}
template<
class LockType,
template <class> class CreationPolicy>
IRegistry* Launcher<LockType, CreationPolicy>::createRegistry()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#createRegistry] Called." );
return new IRegistryImpl<LockType>;
}
template<
class LockType,
template <class> class CreationPolicy>
IBundleContext* Launcher<LockType, CreationPolicy>::createBundleContext( const std::string& bundleName )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#createBundleContext] Called." );
return new IBundleContextImpl( bundleName, (*(this->registry_)) );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::start( std::vector<BundleConfiguration> &configVector )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Called." );
std::vector<BundleConfiguration>::iterator itVectorData;
itVectorData = configVector.begin();
for (itVectorData = configVector.begin(); itVectorData != configVector.end(); itVectorData++)
{
BundleConfiguration bundleConfig = *(itVectorData);
this->objectCreator_.setSearchConfiguration( true,
bundleConfig.getLibraryPath(), bundleConfig.getLibraryName() );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Reading configuration: Library path: %1, class name: %2",
bundleConfig.getLibraryPath(), bundleConfig.getClassName() );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Loading bundle activator: Library path: %1, class name: %2",
bundleConfig.getLibraryPath(), bundleConfig.getClassName() );
IBundleActivator* bundleActivator = NULL;
try
{
bundleActivator = this->objectCreator_.createObject( bundleConfig.getClassName() );
}
catch ( ObjectCreationException &exc )
{
std::string msg( exc.what() );
logger_.log( Logger::LOG_ERROR, "[Launcher#start] Error during loading bundle activator, exc: %1", msg );
try{
bundleActivator = this->objectCreator_.createObject( bundleConfig.getBundleName() );
}catch ( ObjectCreationException &exc )
{
std::string msg( exc.what() );
logger_.log( Logger::LOG_ERROR, "[Launcher#start] Error during loading bundle activator, exc: %1", msg );
continue;
}
}
IBundleContext* bundleCtxt = this->createBundleContext( bundleConfig.getBundleName() );
BundleInfoBase* bundleInfo = new BundleInfo( bundleConfig.getBundleName(), false, bundleActivator, bundleCtxt );
this->registry_->addBundleInfo( (*bundleInfo) );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Start bundle." );
bundleActivator->start( bundleCtxt );
}
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::startAdministrationBundle()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#startAdministrationBundle] Called." );
IBundleActivator* adminBundleActivator = this->objectCreator_.createObject( "sof::services::admin::AdministrationActivator" );
IBundleContext* bundleCtxt = this->createBundleContext( "AdministrationBundle" );
BundleInfoBase* bundleInfo = new BundleInfo( "AdministrationBundle", true, adminBundleActivator, bundleCtxt );
this->registry_->addBundleInfo( (*bundleInfo) );
logger_.log( Logger::LOG_DEBUG, "[Launcher#start] Start bundle." );
AdministrationActivator* adminActivator = static_cast<AdministrationActivator*> (adminBundleActivator);
adminActivator->setAdministrationProvider( this );
adminActivator->start( bundleCtxt );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::stop()
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#stop] Called." );
this->registry_->removeAllBundleInfos();
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::startBundle( BundleConfiguration bundleConfig )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#startBundle] Called, bundle config: %1", bundleConfig.toString() );
std::vector<BundleConfiguration> vec;
vec.push_back( bundleConfig );
this->start( vec );
}
template<
class LockType,
template <class> class CreationPolicy>
void Launcher<LockType, CreationPolicy>::stopBundle( const std::string& bundleName )
{
logger_.log( Logger::LOG_DEBUG, "[Launcher#stopBundle] Called, bundle name: %1", bundleName );
this->registry_->removeBundleInfo( bundleName );
}
template<
class LockType,
template <class> class CreationPolicy>
std::vector<std::string> Launcher<LockType, CreationPolicy>::getBundleNames()
{
std::vector<std::string> bundleNameVec;
std::vector<BundleInfoBase*> vec = this->registry_->getBundleInfos();
std::vector<BundleInfoBase*>::iterator iter;
for ( iter = vec.begin(); iter != vec.end(); iter++ )
{
bundleNameVec.push_back( (*iter)->getBundleName() );
}
return bundleNameVec;
}
template<
class LockType,
template <class> class CreationPolicy>
std::string Launcher<LockType, CreationPolicy>::dumpBundleInfo( const std::string& bundleName )
{
BundleInfoBase* bi = this->registry_->getBundleInfo( bundleName );
if ( bi == 0 )
{
return "Bundle not available!";
}
else
{
return bi->toString();
}
}
template<
class LockType,
template <class> class CreationPolicy>
std::string Launcher<LockType, CreationPolicy>::dumpAllBundleNames()
{
std::vector<BundleInfoBase*> vec = this->registry_->getBundleInfos();
std::vector<BundleInfoBase*>::iterator it;
std::ostringstream stream;
stream << "*** Started Bundles *** " << endl;
for ( it = vec.begin(); it != vec.end(); it++ )
{
stream << (*it)->getBundleName() << endl;
}
stream << endl;
return stream.str();
}
template<
class LockType,
template <class> class CreationPolicy>
BundleInfoBase& Launcher<LockType, CreationPolicy>::getBundleInfo( const std::string& bundleName )
{
return ( * ( this->registry_->getBundleInfo( bundleName ) ) );
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtDeclarative/qdeclarativeextensionplugin.h>
#include <QtDeclarative/qdeclarative.h>
#include <qsensorbackend.h>
#include <qaccelerometer.h>
#include <qambientlightsensor.h>
#include <qcompass.h>
#include <qmagnetometer.h>
#include <qorientationsensor.h>
#include <qproximitysensor.h>
#include <qrotationsensor.h>
#include <qtapsensor.h>
QT_BEGIN_NAMESPACE
QTM_USE_NAMESPACE
class QSensorsDeclarativeModule : public QDeclarativeExtensionPlugin
{
Q_OBJECT
public:
virtual void registerTypes(const char *uri)
{
Q_ASSERT(QLatin1String(uri) == QLatin1String("QtMobility.sensors"));
qmlRegisterType<QSensorReading>();
qmlRegisterType<QAccelerometer>("QtMobility.sensors", 1, 1, "Accelerometer");
qmlRegisterType<QAccelerometerReading>("QtMobility.sensors", 1, 1, "AccelerometerReading");
qmlRegisterType<QAmbientLightSensor>("QtMobility.sensors", 1, 1, "AmbientLightSensor");
qmlRegisterType<QAmbientLightReading>("QtMobility.sensors", 1, 1, "AmbientLightReading");
qmlRegisterType<QCompass>("QtMobility.sensors", 1, 1, "Compass");
qmlRegisterType<QCompassReading>("QtMobility.sensors", 1, 1, "CompassReading");
qmlRegisterType<QMagnetometer>("QtMobility.sensors", 1, 1, "Magnetometer");
qmlRegisterType<QMagnetometerReading>("QtMobility.sensors", 1, 1, "MagnetometerReading");
qmlRegisterType<QOrientationSensor>("QtMobility.sensors", 1, 1, "OrientationSensor");
qmlRegisterType<QOrientationReading>("QtMobility.sensors", 1, 1, "OrientationReading");
qmlRegisterType<QProximitySensor>("QtMobility.sensors", 1, 1, "ProximitySensor");
qmlRegisterType<QProximityReading>("QtMobility.sensors", 1, 1, "ProximityReading");
qmlRegisterType<QRotationSensor>("QtMobility.sensors", 1, 1, "RotationSensor");
qmlRegisterType<QRotationReading>("QtMobility.sensors", 1, 1, "RotationReading");
qmlRegisterType<QTapSensor>("QtMobility.sensors", 1, 1, "TapSensor");
qmlRegisterType<QTapReading>("QtMobility.sensors", 1, 1, "TapReading");
}
};
QT_END_NAMESPACE
#include "sensors.moc"
Q_EXPORT_PLUGIN2(qsensorsdeclarativemodule, QT_PREPEND_NAMESPACE(QSensorsDeclarativeModule));
// =====================================================================
/*!
\qmlclass Accelerometer QAccelerometer
\brief The Accelerometer element wraps the QAccelerometer class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAccelerometer, QAccelerometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AccelerometerReading QAccelerometerReading
\brief The AccelerometerReading element wraps the QAccelerometerReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAccelerometer, QAccelerometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AmbientLightSensor QAmbientLightSensor
\brief The AmbientLightSensor element wraps the QAmbientLightSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAmbientLightSensor, QAmbientLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AmbientLightReading QAmbientLightReading
\brief The AmbientLightReading element wraps the QAmbientLightReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAmbientLightSensor, QAmbientLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass Compass QCompass
\brief The Compass element wraps the QCompass class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QCompass, QCompassReading, {Sensors QML Limitations}
*/
/*!
\qmlclass CompassReading QCompassReading
\brief The CompassReading element wraps the QCompassReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QCompass, QCompassReading, {Sensors QML Limitations}
*/
/*!
\qmlclass Magnetometer QMagnetometer
\brief The Magnetometer element wraps the QMagnetometer class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QMagnetometer, QMagnetometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass MagnetometerReading QMagnetometerReading
\brief The MagnetometerReading element wraps the QMagnetometerReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QMagnetometer, QMagnetometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass OrientationSensor QOrientationSensor
\brief The OrientationSensor element wraps the QOrientationSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QOrientationSensor, QOrientationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass OrientationReading QOrientationReading
\brief The OrientationReading element wraps the QOrientationReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QOrientationSensor, QOrientationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass ProximitySensor QProximitySensor
\brief The ProximitySensor element wraps the QProximitySensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QProximitySensor, QProximityReading, {Sensors QML Limitations}
*/
/*!
\qmlclass ProximityReading QProximityReading
\brief The ProximityReading element wraps the QProximityReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QProximitySensor, QProximityReading, {Sensors QML Limitations}
*/
/*!
\qmlclass RotationSensor QRotationSensor
\brief The RotationSensor element wraps the QRotationSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QRotationSensor, QRotationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass RotationReading QRotationReading
\brief The RotationReading element wraps the QRotationReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QRotationSensor, QRotationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass TapSensor QTapSensor
\brief The TapSensor element wraps the QTapSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QTapSensor, QTapReading, {Sensors QML Limitations}
*/
/*!
\qmlclass TapReading QTapReading
\brief The TapReading element wraps the QTapReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QTapSensor, QTapReading, {Sensors QML Limitations}
*/
<commit_msg>Add missing QML elements for Sensors<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtDeclarative/qdeclarativeextensionplugin.h>
#include <QtDeclarative/qdeclarative.h>
#include <qsensorbackend.h>
#include <qaccelerometer.h>
#include <qambientlightsensor.h>
#include <qcompass.h>
#include <qmagnetometer.h>
#include <qorientationsensor.h>
#include <qproximitysensor.h>
#include <qrotationsensor.h>
#include <qtapsensor.h>
#include <qlightsensor.h>
#include <qgyroscope.h>
QT_BEGIN_NAMESPACE
QTM_USE_NAMESPACE
class QSensorsDeclarativeModule : public QDeclarativeExtensionPlugin
{
Q_OBJECT
public:
virtual void registerTypes(const char *uri)
{
Q_ASSERT(QLatin1String(uri) == QLatin1String("QtMobility.sensors"));
qmlRegisterType<QSensorReading>();
for (int minor = 1; minor <= 2; minor++) {
qmlRegisterType<QAccelerometer>("QtMobility.sensors", 1, minor, "Accelerometer");
qmlRegisterType<QAccelerometerReading>("QtMobility.sensors", 1, minor, "AccelerometerReading");
qmlRegisterType<QAmbientLightSensor>("QtMobility.sensors", 1, minor, "AmbientLightSensor");
qmlRegisterType<QAmbientLightReading>("QtMobility.sensors", 1, minor, "AmbientLightReading");
qmlRegisterType<QCompass>("QtMobility.sensors", 1, minor, "Compass");
qmlRegisterType<QCompassReading>("QtMobility.sensors", 1, minor, "CompassReading");
qmlRegisterType<QMagnetometer>("QtMobility.sensors", 1, minor, "Magnetometer");
qmlRegisterType<QMagnetometerReading>("QtMobility.sensors", 1, minor, "MagnetometerReading");
qmlRegisterType<QOrientationSensor>("QtMobility.sensors", 1, minor, "OrientationSensor");
qmlRegisterType<QOrientationReading>("QtMobility.sensors", 1, minor, "OrientationReading");
qmlRegisterType<QProximitySensor>("QtMobility.sensors", 1, minor, "ProximitySensor");
qmlRegisterType<QProximityReading>("QtMobility.sensors", 1, minor, "ProximityReading");
qmlRegisterType<QRotationSensor>("QtMobility.sensors", 1, minor, "RotationSensor");
qmlRegisterType<QRotationReading>("QtMobility.sensors", 1, minor, "RotationReading");
qmlRegisterType<QTapSensor>("QtMobility.sensors", 1, minor, "TapSensor");
qmlRegisterType<QTapReading>("QtMobility.sensors", 1, minor, "TapReading");
}
qmlRegisterType<QLightSensor>("QtMobility.sensors", 1, 2, "LightSensor");
qmlRegisterType<QLightReading>("QtMobility.sensors", 1, 2, "LightReading");
qmlRegisterType<QGyroscope>("QtMobility.sensors", 1, 2, "Gyroscope");
qmlRegisterType<QGyroscopeReading>("QtMobility.sensors", 1, 2, "GyroscopeReading");
}
};
QT_END_NAMESPACE
#include "sensors.moc"
Q_EXPORT_PLUGIN2(qsensorsdeclarativemodule, QT_PREPEND_NAMESPACE(QSensorsDeclarativeModule));
// =====================================================================
/*!
\qmlclass Accelerometer QAccelerometer
\brief The Accelerometer element wraps the QAccelerometer class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAccelerometer, QAccelerometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AccelerometerReading QAccelerometerReading
\brief The AccelerometerReading element wraps the QAccelerometerReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAccelerometer, QAccelerometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AmbientLightSensor QAmbientLightSensor
\brief The AmbientLightSensor element wraps the QAmbientLightSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAmbientLightSensor, QAmbientLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass AmbientLightReading QAmbientLightReading
\brief The AmbientLightReading element wraps the QAmbientLightReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QAmbientLightSensor, QAmbientLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass Compass QCompass
\brief The Compass element wraps the QCompass class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QCompass, QCompassReading, {Sensors QML Limitations}
*/
/*!
\qmlclass CompassReading QCompassReading
\brief The CompassReading element wraps the QCompassReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QCompass, QCompassReading, {Sensors QML Limitations}
*/
/*!
\qmlclass Magnetometer QMagnetometer
\brief The Magnetometer element wraps the QMagnetometer class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QMagnetometer, QMagnetometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass MagnetometerReading QMagnetometerReading
\brief The MagnetometerReading element wraps the QMagnetometerReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QMagnetometer, QMagnetometerReading, {Sensors QML Limitations}
*/
/*!
\qmlclass OrientationSensor QOrientationSensor
\brief The OrientationSensor element wraps the QOrientationSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QOrientationSensor, QOrientationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass OrientationReading QOrientationReading
\brief The OrientationReading element wraps the QOrientationReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QOrientationSensor, QOrientationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass ProximitySensor QProximitySensor
\brief The ProximitySensor element wraps the QProximitySensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QProximitySensor, QProximityReading, {Sensors QML Limitations}
*/
/*!
\qmlclass ProximityReading QProximityReading
\brief The ProximityReading element wraps the QProximityReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QProximitySensor, QProximityReading, {Sensors QML Limitations}
*/
/*!
\qmlclass RotationSensor QRotationSensor
\brief The RotationSensor element wraps the QRotationSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QRotationSensor, QRotationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass RotationReading QRotationReading
\brief The RotationReading element wraps the QRotationReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QRotationSensor, QRotationReading, {Sensors QML Limitations}
*/
/*!
\qmlclass TapSensor QTapSensor
\brief The TapSensor element wraps the QTapSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QTapSensor, QTapReading, {Sensors QML Limitations}
*/
/*!
\qmlclass TapReading QTapReading
\brief The TapReading element wraps the QTapReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QTapSensor, QTapReading, {Sensors QML Limitations}
*/
/*!
\qmlclass LightSensor QLightSensor
\brief The LightSensor element wraps the QLightSensor class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QLightSensor, QLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass LightReading QLightReading
\brief The LightReading element wraps the QLightReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QLightSensor, QLightReading, {Sensors QML Limitations}
*/
/*!
\qmlclass Gyroscope QGyroscope
\brief The Gyroscope element wraps the QGyroscope class.
\ingroup qml-sensors_type
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QGyroscope, QGyroscopeReading, {Sensors QML Limitations}
*/
/*!
\qmlclass GyroscopeReading QGyroscopeReading
\brief The GyroscopeReading element wraps the QGyroscopeReading class.
\ingroup qml-sensors_reading
This element is part of the \bold{QtMobility.sensors 1.1} module.
\sa QGyroscope, QGyroscopeReading, {Sensors QML Limitations}
*/
<|endoftext|> |
<commit_before>/**
* @file lluilistener.cpp
* @author Nat Goodspeed
* @date 2009-08-18
* @brief Implementation for lluilistener.
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
// Precompiled header
#include "llviewerprecompiledheaders.h"
// associated header
#include "lluilistener.h"
// STL headers
// std headers
// external library headers
// other Linden headers
#include "lluictrl.h"
#include "llerror.h"
LLUIListener::LLUIListener():
LLEventAPI("UI",
"LLUICtrl::CommitCallbackRegistry listener.\n"
"Capable of invoking any function (with parameter) you can specify in XUI.")
{
add("call",
"Invoke the operation named by [\"function\"], passing [\"parameter\"],\n"
"as if from a user gesture on a menu -- or a button click.",
&LLUIListener::call,
LLSD().with("function", LLSD()));
add("getValue",
"For the UI control identified by the path in [\"path\"], return the control's\n"
"current value as [\"value\"] reply.",
&LLUIListener::getValue,
LLSD().with("path", LLSD()));
}
void LLUIListener::call(const LLSD& event) const
{
LLUICtrl::commit_callback_t* func =
LLUICtrl::CommitCallbackRegistry::getValue(event["function"]);
if (! func)
{
// This API is intended for use by a script. It's a fire-and-forget
// API: we provide no reply. Therefore, a typo in the script will
// provide no feedback whatsoever to that script. To rub the coder's
// nose in such an error, crump rather than quietly ignoring it.
LL_ERRS("LLUIListener") << "function '" << event["function"] << "' not found" << LL_ENDL;
}
else
{
// Interestingly, view_listener_t::addMenu() (addCommit(),
// addEnable()) constructs a commit_callback_t callable that accepts
// two parameters but discards the first. Only the second is passed to
// handleEvent(). Therefore we feel completely safe passing NULL for
// the first parameter.
(*func)(NULL, event["parameter"]);
}
}
const LLUICtrl* resolve_path(const LLUICtrl* base, const std::string path)
{
// *TODO: walk the path
return NULL;
}
void LLUIListener::getValue(const LLSD&event) const
{
LLSD reply;
const LLUICtrl* root = NULL; // *TODO: look this up
const LLUICtrl* ctrl = resolve_path(root, event["path"].asString());
if (ctrl)
{
reply["value"] = ctrl->getValue();
}
else
{
// *TODO: ??? return something indicating failure to resolve
}
sendReply(reply, event, "reply");
}
<commit_msg>Implemented path resolution. Should be able to test this now.<commit_after>/**
* @file lluilistener.cpp
* @author Nat Goodspeed
* @date 2009-08-18
* @brief Implementation for lluilistener.
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
// Precompiled header
#include "llviewerprecompiledheaders.h"
// associated header
#include "lluilistener.h"
// STL headers
// std headers
// external library headers
// other Linden headers
#include "llviewerwindow.h" // to get root view
#include "lluictrl.h"
#include "llerror.h"
LLUIListener::LLUIListener():
LLEventAPI("UI",
"LLUICtrl::CommitCallbackRegistry listener.\n"
"Capable of invoking any function (with parameter) you can specify in XUI.")
{
add("call",
"Invoke the operation named by [\"function\"], passing [\"parameter\"],\n"
"as if from a user gesture on a menu -- or a button click.",
&LLUIListener::call,
LLSD().with("function", LLSD()));
add("getValue",
"For the UI control identified by the path in [\"path\"], return the control's\n"
"current value as [\"value\"] reply.",
&LLUIListener::getValue,
LLSD().with("path", LLSD()));
}
void LLUIListener::call(const LLSD& event) const
{
LLUICtrl::commit_callback_t* func =
LLUICtrl::CommitCallbackRegistry::getValue(event["function"]);
if (! func)
{
// This API is intended for use by a script. It's a fire-and-forget
// API: we provide no reply. Therefore, a typo in the script will
// provide no feedback whatsoever to that script. To rub the coder's
// nose in such an error, crump rather than quietly ignoring it.
LL_ERRS("LLUIListener") << "function '" << event["function"] << "' not found" << LL_ENDL;
}
else
{
// Interestingly, view_listener_t::addMenu() (addCommit(),
// addEnable()) constructs a commit_callback_t callable that accepts
// two parameters but discards the first. Only the second is passed to
// handleEvent(). Therefore we feel completely safe passing NULL for
// the first parameter.
(*func)(NULL, event["parameter"]);
}
}
const LLView* resolve_path(const LLView* context, const std::string path)
{
std::vector<std::string> parts;
const std::string delims("/");
LLStringUtilBase<char>::getTokens(path, parts, delims);
bool recurse = false;
for (std::vector<std::string>::iterator it = parts.begin();
it != parts.end() && context; it++)
{
std::string part = *it;
if (part.length() == 0)
{
// Allow "foo//bar" meaning "descendant named bar"
recurse = true;
}
else
{
const LLView* found = context->findChildView(part, recurse);
if (!found)
{
return NULL;
}
else
{
context = found;
}
recurse = false;
}
}
return NULL;
}
void LLUIListener::getValue(const LLSD&event) const
{
LLSD reply;
const LLView* root = (LLView*)(gViewerWindow->getRootView());
const LLView* view = resolve_path(root, event["path"].asString());
const LLUICtrl* ctrl(dynamic_cast<const LLUICtrl*>(view));
if (ctrl)
{
reply["value"] = ctrl->getValue();
}
else
{
// *TODO: ??? return something indicating failure to resolve
}
sendReply(reply, event, "reply");
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Luca Zanconato
*
* 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 <gtest/gtest.h>
#include <fstream>
#include <saltpack.h>
#include <sodium.h>
TEST(signature, attached) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg;
saltpack::MessageReader *dec = new saltpack::MessageReader(in);
while (dec->hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec->getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
delete dec;
ASSERT_EQ(msg.str(), "a signed message");
}
TEST(signature, attached_failure) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
out.flush();
delete sig;
try {
// verify message
std::string mmsg = out.str();
mmsg[mmsg.size() - 80] = (char)((int)mmsg[mmsg.size() - 80] + 1);
std::stringstream in(mmsg);
std::stringstream msg;
saltpack::MessageReader dec(in);
while (dec.hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec.getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
TEST(signature, attached_armor) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_ATTACHED_SIGNATURE);
saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' '});
sig->addBlock({'m', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
aOut.finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
saltpack::ArmoredInputStream is(in);
std::stringstream msg;
saltpack::MessageReader *dec = new saltpack::MessageReader(is);
while (dec->hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec->getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
delete dec;
ASSERT_EQ(msg.str(), "a signed message");
}
TEST(signature, detached) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true);
sig->addBlock({'T', 'h', '3', ' ', 'm'});
sig->addBlock({'E', '$', 's', '4', 'g', '['});
sig->finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg("Th3 mE$s4g[");
saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg);
delete dec;
try {
std::stringstream in2(out.str());
std::stringstream msg2("Wrong");
saltpack::MessageReader(in2, msg2);
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
TEST(signature, detached_armor) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_DETACHED_SIGNATURE);
saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, true);
sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'});
sig->finalise();
aOut.finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg("Th3 mE$s4g!");
saltpack::ArmoredInputStream is(in);
saltpack::MessageReader *dec = new saltpack::MessageReader(is, msg);
delete dec;
try {
std::stringstream in2(out.str());
saltpack::ArmoredInputStream is2(in2);
std::stringstream msg2("Wrong");
saltpack::MessageReader(is2, msg2);
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
<commit_msg>Added sender getter in decrypted/verified message<commit_after>/*
* Copyright 2016 Luca Zanconato
*
* 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 <gtest/gtest.h>
#include <fstream>
#include <saltpack.h>
#include <sodium.h>
TEST(signature, attached) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg;
saltpack::MessageReader *dec = new saltpack::MessageReader(in);
while (dec->hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec->getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
ASSERT_EQ(signer_publickey, dec->getSender());
delete dec;
ASSERT_EQ(msg.str(), "a signed message");
}
TEST(signature, attached_failure) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
out.flush();
delete sig;
try {
// verify message
std::string mmsg = out.str();
mmsg[mmsg.size() - 80] = (char)((int)mmsg[mmsg.size() - 80] + 1);
std::stringstream in(mmsg);
std::stringstream msg;
saltpack::MessageReader dec(in);
while (dec.hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec.getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
TEST(signature, attached_armor) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_ATTACHED_SIGNATURE);
saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, false);
sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' '});
sig->addBlock({'m', 'e', 's', 's', 'a', 'g', 'e'});
sig->finalise();
aOut.finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
saltpack::ArmoredInputStream is(in);
std::stringstream msg;
saltpack::MessageReader *dec = new saltpack::MessageReader(is);
while (dec->hasMoreBlocks()) {
saltpack::BYTE_ARRAY message = dec->getBlock();
msg.write(reinterpret_cast<const char *>(message.data()), message.size());
}
ASSERT_EQ(signer_publickey, dec->getSender());
delete dec;
ASSERT_EQ(msg.str(), "a signed message");
}
TEST(signature, detached) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true);
sig->addBlock({'T', 'h', '3', ' ', 'm'});
sig->addBlock({'E', '$', 's', '4', 'g', '['});
sig->finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg("Th3 mE$s4g[");
saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg);
ASSERT_EQ(signer_publickey, dec->getSender());
delete dec;
try {
std::stringstream in2(out.str());
std::stringstream msg2("Wrong");
saltpack::MessageReader(in2, msg2);
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
TEST(signature, detached_armor) {
saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES);
saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES);
saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey);
// sign message
std::stringstream out;
saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_DETACHED_SIGNATURE);
saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, true);
sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'});
sig->finalise();
aOut.finalise();
out.flush();
delete sig;
// verify message
std::stringstream in(out.str());
std::stringstream msg("Th3 mE$s4g!");
saltpack::ArmoredInputStream is(in);
saltpack::MessageReader *dec = new saltpack::MessageReader(is, msg);
ASSERT_EQ(signer_publickey, dec->getSender());
delete dec;
try {
std::stringstream in2(out.str());
saltpack::ArmoredInputStream is2(in2);
std::stringstream msg2("Wrong");
saltpack::MessageReader(is2, msg2);
throw std::bad_exception();
} catch (const saltpack::SaltpackException ex) {
ASSERT_STREQ(ex.what(), "Signature was forged or corrupt.");
}
}
<|endoftext|> |
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Clifford Wolf <clifford@symbioticeda.com>
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* 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 THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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.
*
*/
#ifndef NO_PYTHON
#include "arch_pybindings.h"
#include "nextpnr.h"
#include "pybindings.h"
NEXTPNR_NAMESPACE_BEGIN
void arch_wrap_python()
{
using namespace PythonConversion;
class_<ArchArgs>("ArchArgs").def_readwrite("type", &ArchArgs::type);
enum_<decltype(std::declval<ArchArgs>().type)>("iCE40Type")
.value("NONE", ArchArgs::NONE)
.value("LP384", ArchArgs::LP384)
.value("LP1K", ArchArgs::LP1K)
.value("LP8K", ArchArgs::LP8K)
.value("HX1K", ArchArgs::HX1K)
.value("HX8K", ArchArgs::HX8K)
.value("UP5K", ArchArgs::UP5K)
.export_values();
class_<BelId>("BelId").def_readwrite("index", &BelId::index);
class_<WireId>("WireId").def_readwrite("index", &WireId::index);
class_<PipId>("PipId").def_readwrite("index", &PipId::index);
class_<BelPin>("BelPin").def_readwrite("bel", &BelPin::bel).def_readwrite("pin", &BelPin::pin);
enum_<PortPin>("PortPin")
#define X(t) .value("PIN_" #t, PIN_##t)
#include "portpins.inc"
;
#undef X
auto arch_cls = class_<Arch, Arch *, bases<BaseCtx>, boost::noncopyable>("Arch", init<ArchArgs>());
auto ctx_cls = class_<Context, Context *, bases<Arch>, boost::noncopyable>("Context", no_init)
.def("checksum", &Context::checksum)
.def("pack", &Context::pack)
.def("place", &Context::place)
.def("route", &Context::route);
fn_wrapper_1a<Context, decltype(&Context::getBelType), &Context::getBelType, conv_to_str<BelType>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelType");
//fn_wrapper_1a<Context, decltype(&Context::checkBelAvail), &Context::checkBelAvail, pass_through<bool>,
// conv_from_str<BelId>>::def_wrap(ctx_cls, "checkBelAvail");
fn_wrapper_1a<Context, decltype(&Context::getBelChecksum), &Context::getBelChecksum, pass_through<uint32_t>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelChecksum");
//fn_wrapper_3a_v<Context, decltype(&Context::bindBel), &Context::bindBel, conv_from_str<BelId>,
// conv_from_str<IdString>, pass_through<PlaceStrength>>::def_wrap(ctx_cls, "bindBel");
//fn_wrapper_1a_v<Context, decltype(&Context::unbindBel), &Context::unbindBel, conv_from_str<BelId>>::def_wrap(
// ctx_cls, "unbindBel");
//fn_wrapper_1a<Context, decltype(&Context::getBoundBelCell), &Context::getBoundBelCell, conv_to_str<IdString>,
// conv_from_str<BelId>>::def_wrap(ctx_cls, "getBoundBelCell");
//fn_wrapper_1a<Context, decltype(&Context::getConflictingBelCell), &Context::getConflictingBelCell,
// conv_to_str<IdString>, conv_from_str<BelId>>::def_wrap(ctx_cls, "getConflictingBelCell");
fn_wrapper_0a<Context, decltype(&Context::getBels), &Context::getBels, wrap_context<BelRange>>::def_wrap(ctx_cls,
"getBels");
fn_wrapper_1a<Context, decltype(&Context::getBelsAtSameTile), &Context::getBelsAtSameTile, wrap_context<BelRange>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelsAtSameTile");
//fn_wrapper_2a<Context, decltype(&Context::getWireBelPin), &Context::getWireBelPin, conv_to_str<WireId>,
// conv_from_str<BelId>, conv_from_str<PortPin>>::def_wrap(ctx_cls, "getWireBelPin");
fn_wrapper_1a<Context, decltype(&Context::getBelPinUphill), &Context::getBelPinUphill, wrap_context<BelPin>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getBelPinUphill");
fn_wrapper_1a<Context, decltype(&Context::getBelPinsDownhill), &Context::getBelPinsDownhill,
wrap_context<BelPinRange>, conv_from_str<WireId>>::def_wrap(ctx_cls, "getBelPinsDownhill");
fn_wrapper_1a<Context, decltype(&Context::getWireChecksum), &Context::getWireChecksum, pass_through<uint32_t>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getWireChecksum");
//fn_wrapper_3a_v<Context, decltype(&Context::bindWire), &Context::bindWire, conv_from_str<WireId>,
// conv_from_str<IdString>, pass_through<PlaceStrength>>::def_wrap(ctx_cls, "bindWire");
//fn_wrapper_1a_v<Context, decltype(&Context::unbindWire), &Context::unbindWire, conv_from_str<WireId>>::def_wrap(
// ctx_cls, "unbindWire");
//fn_wrapper_1a<Context, decltype(&Context::checkWireAvail), &Context::checkWireAvail, pass_through<bool>,
// conv_from_str<WireId>>::def_wrap(ctx_cls, "checkWireAvail");
//fn_wrapper_1a<Context, decltype(&Context::getBoundWireNet), &Context::getBoundWireNet, conv_to_str<IdString>,
// conv_from_str<WireId>>::def_wrap(ctx_cls, "getBoundWireNet");
//fn_wrapper_1a<Context, decltype(&Context::getConflictingWireNet), &Context::getConflictingWireNet,
// conv_to_str<IdString>, conv_from_str<WireId>>::def_wrap(ctx_cls, "getConflictingWireNet");
fn_wrapper_0a<Context, decltype(&Context::getWires), &Context::getWires, wrap_context<WireRange>>::def_wrap(
ctx_cls, "getWires");
fn_wrapper_0a<Context, decltype(&Context::getPips), &Context::getPips, wrap_context<AllPipRange>>::def_wrap(
ctx_cls, "getPips");
fn_wrapper_1a<Context, decltype(&Context::getPipChecksum), &Context::getPipChecksum, pass_through<uint32_t>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipChecksum");
//fn_wrapper_3a_v<Context, decltype(&Context::bindPip), &Context::bindPip, conv_from_str<PipId>,
// conv_from_str<IdString>, pass_through<PlaceStrength>>::def_wrap(ctx_cls, "bindPip");
//fn_wrapper_1a_v<Context, decltype(&Context::unbindPip), &Context::unbindPip, conv_from_str<PipId>>::def_wrap(
// ctx_cls, "unbindPip");
//fn_wrapper_1a<Context, decltype(&Context::checkPipAvail), &Context::checkPipAvail, pass_through<bool>,
// conv_from_str<PipId>>::def_wrap(ctx_cls, "checkPipAvail");
//fn_wrapper_1a<Context, decltype(&Context::getBoundPipNet), &Context::getBoundPipNet, conv_to_str<IdString>,
// conv_from_str<PipId>>::def_wrap(ctx_cls, "getBoundPipNet");
//fn_wrapper_1a<Context, decltype(&Context::getConflictingPipNet), &Context::getConflictingPipNet,
// conv_to_str<IdString>, conv_from_str<PipId>>::def_wrap(ctx_cls, "getConflictingPipNet");
fn_wrapper_1a<Context, decltype(&Context::getPipsDownhill), &Context::getPipsDownhill, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getPipsDownhill");
fn_wrapper_1a<Context, decltype(&Context::getPipsUphill), &Context::getPipsUphill, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getPipsUphill");
fn_wrapper_1a<Context, decltype(&Context::getWireAliases), &Context::getWireAliases, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getWireAliases");
fn_wrapper_1a<Context, decltype(&Context::getPipSrcWire), &Context::getPipSrcWire, conv_to_str<WireId>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipSrcWire");
fn_wrapper_1a<Context, decltype(&Context::getPipDstWire), &Context::getPipDstWire, conv_to_str<WireId>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipDstWire");
fn_wrapper_1a<Context, decltype(&Context::getPipDelay), &Context::getPipDelay, pass_through<DelayInfo>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipDelay");
fn_wrapper_1a<Context, decltype(&Context::getPackagePinBel), &Context::getPackagePinBel, conv_to_str<BelId>,
pass_through<std::string>>::def_wrap(ctx_cls, "getPackagePinBel");
fn_wrapper_1a<Context, decltype(&Context::getBelPackagePin), &Context::getBelPackagePin, pass_through<std::string>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelPackagePin");
fn_wrapper_0a<Context, decltype(&Context::getChipName), &Context::getChipName, pass_through<std::string>>::def_wrap(
ctx_cls, "getChipName");
fn_wrapper_0a<Context, decltype(&Context::archId), &Context::archId, conv_to_str<IdString>>::def_wrap(ctx_cls,
"archId");
typedef std::unordered_map<IdString, std::unique_ptr<CellInfo>> CellMap;
typedef std::unordered_map<IdString, std::unique_ptr<NetInfo>> NetMap;
readonly_wrapper<Context, decltype(&Context::cells), &Context::cells, wrap_context<CellMap &>>::def_wrap(ctx_cls,
"cells");
readonly_wrapper<Context, decltype(&Context::nets), &Context::nets, wrap_context<NetMap &>>::def_wrap(ctx_cls,
"nets");
WRAP_RANGE(Bel, conv_to_str<BelId>);
WRAP_RANGE(Wire, conv_to_str<WireId>);
WRAP_RANGE(AllPip, conv_to_str<PipId>);
WRAP_RANGE(Pip, conv_to_str<PipId>);
WRAP_MAP_UPTR(CellMap, "IdCellMap");
WRAP_MAP_UPTR(NetMap, "IdNetMap");
}
NEXTPNR_NAMESPACE_END
#endif // NO_PYTHON
<commit_msg>Remove unimplemented pybindings (for now)<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 Clifford Wolf <clifford@symbioticeda.com>
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* 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 THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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.
*
*/
#ifndef NO_PYTHON
#include "arch_pybindings.h"
#include "nextpnr.h"
#include "pybindings.h"
NEXTPNR_NAMESPACE_BEGIN
void arch_wrap_python()
{
using namespace PythonConversion;
class_<ArchArgs>("ArchArgs").def_readwrite("type", &ArchArgs::type);
enum_<decltype(std::declval<ArchArgs>().type)>("iCE40Type")
.value("NONE", ArchArgs::NONE)
.value("LP384", ArchArgs::LP384)
.value("LP1K", ArchArgs::LP1K)
.value("LP8K", ArchArgs::LP8K)
.value("HX1K", ArchArgs::HX1K)
.value("HX8K", ArchArgs::HX8K)
.value("UP5K", ArchArgs::UP5K)
.export_values();
class_<BelId>("BelId").def_readwrite("index", &BelId::index);
class_<WireId>("WireId").def_readwrite("index", &WireId::index);
class_<PipId>("PipId").def_readwrite("index", &PipId::index);
class_<BelPin>("BelPin").def_readwrite("bel", &BelPin::bel).def_readwrite("pin", &BelPin::pin);
enum_<PortPin>("PortPin")
#define X(t) .value("PIN_" #t, PIN_##t)
#include "portpins.inc"
;
#undef X
auto arch_cls = class_<Arch, Arch *, bases<BaseCtx>, boost::noncopyable>("Arch", init<ArchArgs>());
auto ctx_cls = class_<Context, Context *, bases<Arch>, boost::noncopyable>("Context", no_init)
.def("checksum", &Context::checksum)
.def("pack", &Context::pack)
.def("place", &Context::place)
.def("route", &Context::route);
fn_wrapper_1a<Context, decltype(&Context::getBelType), &Context::getBelType, conv_to_str<BelType>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelType");
fn_wrapper_1a<Context, decltype(&Context::getBelChecksum), &Context::getBelChecksum, pass_through<uint32_t>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelChecksum");
fn_wrapper_0a<Context, decltype(&Context::getBels), &Context::getBels, wrap_context<BelRange>>::def_wrap(ctx_cls,
"getBels");
fn_wrapper_1a<Context, decltype(&Context::getBelsAtSameTile), &Context::getBelsAtSameTile, wrap_context<BelRange>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelsAtSameTile");
fn_wrapper_1a<Context, decltype(&Context::getBelPinUphill), &Context::getBelPinUphill, wrap_context<BelPin>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getBelPinUphill");
fn_wrapper_1a<Context, decltype(&Context::getBelPinsDownhill), &Context::getBelPinsDownhill,
wrap_context<BelPinRange>, conv_from_str<WireId>>::def_wrap(ctx_cls, "getBelPinsDownhill");
fn_wrapper_1a<Context, decltype(&Context::getWireChecksum), &Context::getWireChecksum, pass_through<uint32_t>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getWireChecksum");
fn_wrapper_0a<Context, decltype(&Context::getWires), &Context::getWires, wrap_context<WireRange>>::def_wrap(
ctx_cls, "getWires");
fn_wrapper_0a<Context, decltype(&Context::getPips), &Context::getPips, wrap_context<AllPipRange>>::def_wrap(
ctx_cls, "getPips");
fn_wrapper_1a<Context, decltype(&Context::getPipChecksum), &Context::getPipChecksum, pass_through<uint32_t>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipChecksum");
fn_wrapper_1a<Context, decltype(&Context::getPipsDownhill), &Context::getPipsDownhill, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getPipsDownhill");
fn_wrapper_1a<Context, decltype(&Context::getPipsUphill), &Context::getPipsUphill, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getPipsUphill");
fn_wrapper_1a<Context, decltype(&Context::getWireAliases), &Context::getWireAliases, wrap_context<PipRange>,
conv_from_str<WireId>>::def_wrap(ctx_cls, "getWireAliases");
fn_wrapper_1a<Context, decltype(&Context::getPipSrcWire), &Context::getPipSrcWire, conv_to_str<WireId>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipSrcWire");
fn_wrapper_1a<Context, decltype(&Context::getPipDstWire), &Context::getPipDstWire, conv_to_str<WireId>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipDstWire");
fn_wrapper_1a<Context, decltype(&Context::getPipDelay), &Context::getPipDelay, pass_through<DelayInfo>,
conv_from_str<PipId>>::def_wrap(ctx_cls, "getPipDelay");
fn_wrapper_1a<Context, decltype(&Context::getPackagePinBel), &Context::getPackagePinBel, conv_to_str<BelId>,
pass_through<std::string>>::def_wrap(ctx_cls, "getPackagePinBel");
fn_wrapper_1a<Context, decltype(&Context::getBelPackagePin), &Context::getBelPackagePin, pass_through<std::string>,
conv_from_str<BelId>>::def_wrap(ctx_cls, "getBelPackagePin");
fn_wrapper_0a<Context, decltype(&Context::getChipName), &Context::getChipName, pass_through<std::string>>::def_wrap(
ctx_cls, "getChipName");
fn_wrapper_0a<Context, decltype(&Context::archId), &Context::archId, conv_to_str<IdString>>::def_wrap(ctx_cls,
"archId");
typedef std::unordered_map<IdString, std::unique_ptr<CellInfo>> CellMap;
typedef std::unordered_map<IdString, std::unique_ptr<NetInfo>> NetMap;
readonly_wrapper<Context, decltype(&Context::cells), &Context::cells, wrap_context<CellMap &>>::def_wrap(ctx_cls,
"cells");
readonly_wrapper<Context, decltype(&Context::nets), &Context::nets, wrap_context<NetMap &>>::def_wrap(ctx_cls,
"nets");
WRAP_RANGE(Bel, conv_to_str<BelId>);
WRAP_RANGE(Wire, conv_to_str<WireId>);
WRAP_RANGE(AllPip, conv_to_str<PipId>);
WRAP_RANGE(Pip, conv_to_str<PipId>);
WRAP_MAP_UPTR(CellMap, "IdCellMap");
WRAP_MAP_UPTR(NetMap, "IdNetMap");
}
NEXTPNR_NAMESPACE_END
#endif // NO_PYTHON
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: log.cpp
* Purpose: Implementation of wxExLog class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/app.h>
#include <wx/file.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h>
#include <wx/extension/log.h>
wxExLog* wxExLog::m_Self = NULL;
wxExLog::wxExLog(const wxFileName& filename, bool logging)
: m_FileName(filename)
{
SetLogging(logging);
}
wxExLog* wxExLog::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
wxFileName filename;
if (wxTheApp == NULL)
{
filename = wxFileName("app.log");
}
else
{
#ifdef wxExUSE_PORTABLE
filename = wxFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()),
wxTheApp->GetAppName().Lower() + ".log");
#else
filename = wxFileName(
wxStandardPaths::Get().GetUserDataDir(),
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
m_Self = new wxExLog(filename, false); // no logging
}
return m_Self;
}
bool wxExLog::Log(const wxString& text, bool add_timestamp ) const
{
if (m_Logging)
{
wxFile file(m_FileName.GetFullPath(), wxFile::write_append);
const wxString log = (add_timestamp ? wxDateTime::Now().Format() + " ": "")
+ text + wxTextFile::GetEOL();
return file.Write(log);
}
return false;
}
wxExLog* wxExLog::Set(wxExLog* log)
{
wxExLog* old = m_Self;
m_Self = log;
return old;
}
void wxExLog::SetLogging(bool logging)
{
if (logging)
{
if (!m_FileName.FileExists())
{
m_Logging = wxFile().Create(m_FileName.GetFullPath());
}
else
{
m_Logging = true;
}
}
else
{
m_Logging = false;
}
}
<commit_msg>minor improvement<commit_after>/******************************************************************************\
* File: log.cpp
* Purpose: Implementation of wxExLog class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/app.h>
#include <wx/file.h>
#include <wx/stdpaths.h>
#include <wx/textfile.h>
#include <wx/extension/log.h>
wxExLog* wxExLog::m_Self = NULL;
wxExLog::wxExLog(const wxFileName& filename, bool logging)
: m_FileName(filename)
{
SetLogging(logging);
}
wxExLog* wxExLog::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
wxFileName filename;
if (wxTheApp == NULL)
{
filename = wxFileName("app.log");
}
else
{
#ifdef wxExUSE_PORTABLE
filename = wxFileName(
wxPathOnly(wxStandardPaths::Get().GetExecutablePath()),
wxTheApp->GetAppName().Lower() + ".log");
#else
filename = wxFileName(
wxStandardPaths::Get().GetUserDataDir(),
wxTheApp->GetAppName().Lower() + ".log");
#endif
}
m_Self = new wxExLog(filename, false); // no logging
}
return m_Self;
}
bool wxExLog::Log(const wxString& text, bool add_timestamp ) const
{
if (m_Logging)
{
wxFile file(m_FileName.GetFullPath(), wxFile::write_append);
return
file.IsOpened() &&
file.Write((add_timestamp ? wxDateTime::Now().Format() + " ": "")
+ text + wxTextFile::GetEOL());
}
return false;
}
wxExLog* wxExLog::Set(wxExLog* log)
{
wxExLog* old = m_Self;
m_Self = log;
return old;
}
void wxExLog::SetLogging(bool logging)
{
if (logging)
{
if (!m_FileName.FileExists())
{
m_Logging = wxFile().Create(m_FileName.GetFullPath());
}
else
{
m_Logging = true;
}
}
else
{
m_Logging = false;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: svn.cpp
* Purpose: Implementation of wxExSVN class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/svn.h>
#include <wx/extension/app.h> // for wxExApp
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;
wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
: m_Type(GetType(command_id))
, m_FullPath(fullpath)
{
Initialize();
}
wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
: m_Type(type)
, m_FullPath(fullpath)
{
Initialize();
}
bool wxExSVN::DirExists(const wxFileName& filename)
{
wxFileName path(filename);
path.AppendDir(".svn");
return path.DirExists();
}
wxStandardID wxExSVN::Execute(wxWindow* parent)
{
const wxString svn_flags_name = wxString::Format("svn/flags%d", m_Type);
const wxString svn_flags_contents = wxExApp::GetConfig(svn_flags_name);
if (parent != NULL)
{
std::vector<wxExConfigItem> v;
if (m_Type == SVN_COMMIT)
{
v.push_back(wxExConfigItem(
_("Revision comment"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
if (m_FullPath.empty() && m_Type != SVN_HELP)
{
v.push_back(wxExConfigItem(
_("Base folder"),
CONFIG_COMBOBOXDIR,
wxEmptyString,
true)); // required
}
// SVN_UPDATE and SVN_HELP have no flags to ask for.
if (m_Type != SVN_UPDATE && m_Type != SVN_HELP)
{
wxExApp::SetConfig(_("Flags"), svn_flags_contents);
v.push_back(wxExConfigItem(_("Flags")));
}
// Instead, SVN_HELP has an extra subcommand.
if (m_Type == SVN_HELP)
{
v.push_back(wxExConfigItem(_("Subcommand")));
}
m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,
wxExApp::GetConfig(),
v,
m_Caption).ShowModal();
if (m_ReturnCode == wxID_CANCEL)
{
return m_ReturnCode;
}
}
const wxString cwd = wxGetCwd();
wxString file;
if (m_FullPath.empty())
{
wxSetWorkingDirectory(wxExApp::GetConfig(_("Base folder")));
}
else
{
file = " \"" + m_FullPath + "\"";
}
wxString comment;
if (m_Type == SVN_COMMIT)
{
comment = " -m \"" + wxExApp::GetConfig(_("Revision comment")) + "\"";
}
wxString flags;
wxString subcommand;
if (m_Type == SVN_HELP)
{
subcommand = wxExApp::GetConfig(_("Subcommand"));
if (!subcommand.empty())
{
subcommand = " " + subcommand;
}
}
else
{
flags = wxExApp::GetConfig(_("Flags"));
wxExApp::SetConfig(svn_flags_name, flags);
m_CommandWithFlags = m_Command + " " + flags;
if (!flags.empty())
{
flags += " ";
}
}
const wxString command =
"svn " + flags + m_Command + subcommand + comment + file;
wxArrayString output;
wxArrayString errors;
m_Output.clear();
if (wxExecute(
command,
output,
errors) == -1)
{
if (m_Output.empty())
{
m_Output = "Could not execute: " + command;
}
m_ReturnCode = wxID_ABORT;
return m_ReturnCode;
}
wxExApp::Log(command);
if (m_FullPath.empty())
{
wxSetWorkingDirectory(cwd);
}
// First output the errors.
for (size_t i = 0; i < errors.GetCount(); i++)
{
m_Output += errors[i] + "\n";
}
// Then the normal output, will be empty if there are errors.
for (size_t j = 0; j < output.GetCount(); j++)
{
m_Output += output[j] + "\n";
}
return wxID_OK;
}
wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)
{
Execute(parent);
ShowOutput(parent);
return m_ReturnCode;
}
wxExSVNType wxExSVN::GetType(int command_id) const
{
switch (command_id)
{
case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
case ID_EDIT_SVN_CAT: return SVN_CAT; break;
case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
case ID_EDIT_SVN_HELP: return SVN_HELP; break;
case ID_EDIT_SVN_INFO: return SVN_INFO; break;
case ID_EDIT_SVN_LOG: return SVN_LOG; break;
case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;
case ID_EDIT_SVN_STAT: return SVN_STAT; break;
case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;
default:
wxFAIL;
return SVN_STAT;
break;
}
}
void wxExSVN::Initialize()
{
switch (m_Type)
{
case SVN_BLAME: m_Caption = "SVN Blame"; break;
case SVN_CAT: m_Caption = "SVN Cat"; break;
case SVN_COMMIT: m_Caption = "SVN Commit"; break;
case SVN_DIFF: m_Caption = "SVN Diff"; break;
case SVN_HELP: m_Caption = "SVN Help"; break;
case SVN_INFO: m_Caption = "SVN Info"; break;
case SVN_LOG: m_Caption = "SVN Log"; break;
case SVN_REVERT: m_Caption = "SVN Revert"; break;
case SVN_STAT: m_Caption = "SVN Stat"; break;
case SVN_UPDATE: m_Caption = "SVN Update"; break;
default:
wxFAIL;
break;
}
m_Command = m_Caption.AfterFirst(' ').Lower();
// Currently no flags, as no command was executed.
m_CommandWithFlags = m_Command;
m_Output.clear();
m_ReturnCode = wxID_NONE;
wxASSERT(wxExApp::GetConfig() != NULL);
}
void wxExSVN::ShowOutput(wxWindow* parent) const
{
switch (m_ReturnCode)
{
case wxID_CANCEL:
break;
case wxID_ABORT:
wxMessageBox(m_Output);
break;
case wxID_OK:
{
const wxString caption = m_Caption +
(!m_FullPath.empty() ? " " + wxFileName(m_FullPath).GetFullName(): wxString(wxEmptyString));
// Create a dialog for contents.
if (m_STCEntryDialog == NULL)
{
m_STCEntryDialog = new wxExSTCEntryDialog(
parent,
caption,
m_Output,
wxEmptyString,
wxOK,
wxID_ANY,
wxDefaultPosition, wxSize(575, 250));
}
else
{
m_STCEntryDialog->SetText(m_Output);
m_STCEntryDialog->SetTitle(caption);
// Reset a previous lexer.
if (!m_STCEntryDialog->GetLexer().empty())
{
m_STCEntryDialog->SetLexer(wxEmptyString);
}
}
// Add a lexer if we specified a path, asked for cat or blame
// and there is a lexer.
if (
!m_FullPath.empty() &&
(m_Type == SVN_CAT || m_Type == SVN_BLAME))
{
const wxExFileName fn(m_FullPath);
if (!fn.GetLexer().GetScintillaLexer().empty())
{
m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
}
}
m_STCEntryDialog->Show();
}
break;
default:
wxFAIL;
break;
}
}
#endif
<commit_msg>don't show errors twice<commit_after>/******************************************************************************\
* File: svn.cpp
* Purpose: Implementation of wxExSVN class
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/svn.h>
#include <wx/extension/app.h> // for wxExApp
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExSTCEntryDialog* wxExSVN::m_STCEntryDialog = NULL;
wxExSVN::wxExSVN(int command_id, const wxString& fullpath)
: m_Type(GetType(command_id))
, m_FullPath(fullpath)
{
Initialize();
}
wxExSVN::wxExSVN(wxExSVNType type, const wxString& fullpath)
: m_Type(type)
, m_FullPath(fullpath)
{
Initialize();
}
bool wxExSVN::DirExists(const wxFileName& filename)
{
wxFileName path(filename);
path.AppendDir(".svn");
return path.DirExists();
}
wxStandardID wxExSVN::Execute(wxWindow* parent)
{
const wxString svn_flags_name = wxString::Format("svn/flags%d", m_Type);
const wxString svn_flags_contents = wxExApp::GetConfig(svn_flags_name);
if (parent != NULL)
{
std::vector<wxExConfigItem> v;
if (m_Type == SVN_COMMIT)
{
v.push_back(wxExConfigItem(
_("Revision comment"),
CONFIG_COMBOBOX,
wxEmptyString,
true)); // required
}
if (m_FullPath.empty() && m_Type != SVN_HELP)
{
v.push_back(wxExConfigItem(
_("Base folder"),
CONFIG_COMBOBOXDIR,
wxEmptyString,
true)); // required
}
// SVN_UPDATE and SVN_HELP have no flags to ask for.
if (m_Type != SVN_UPDATE && m_Type != SVN_HELP)
{
wxExApp::SetConfig(_("Flags"), svn_flags_contents);
v.push_back(wxExConfigItem(_("Flags")));
}
// Instead, SVN_HELP has an extra subcommand.
if (m_Type == SVN_HELP)
{
v.push_back(wxExConfigItem(_("Subcommand")));
}
m_ReturnCode = (wxStandardID)wxExConfigDialog(parent,
wxExApp::GetConfig(),
v,
m_Caption).ShowModal();
if (m_ReturnCode == wxID_CANCEL)
{
return m_ReturnCode;
}
}
const wxString cwd = wxGetCwd();
wxString file;
if (m_FullPath.empty())
{
wxSetWorkingDirectory(wxExApp::GetConfig(_("Base folder")));
}
else
{
file = " \"" + m_FullPath + "\"";
}
wxString comment;
if (m_Type == SVN_COMMIT)
{
comment = " -m \"" + wxExApp::GetConfig(_("Revision comment")) + "\"";
}
wxString flags;
wxString subcommand;
if (m_Type == SVN_HELP)
{
subcommand = wxExApp::GetConfig(_("Subcommand"));
if (!subcommand.empty())
{
subcommand = " " + subcommand;
}
}
else
{
flags = wxExApp::GetConfig(_("Flags"));
wxExApp::SetConfig(svn_flags_name, flags);
m_CommandWithFlags = m_Command + " " + flags;
if (!flags.empty())
{
flags += " ";
}
}
const wxString command =
"svn " + flags + m_Command + subcommand + comment + file;
wxArrayString output;
wxArrayString errors;
m_Output.clear();
if (wxExecute(
command,
output,
errors) == -1)
{
if (m_Output.empty())
{
m_Output = "Could not execute: " + command;
}
m_ReturnCode = wxID_ABORT;
return m_ReturnCode;
}
wxExApp::Log(command);
if (m_FullPath.empty())
{
wxSetWorkingDirectory(cwd);
}
// First output the errors.
for (size_t i = 0; i < errors.GetCount(); i++)
{
m_Output += errors[i] + "\n";
}
// Then the normal output, will be empty if there are errors.
for (size_t j = 0; j < output.GetCount(); j++)
{
m_Output += output[j] + "\n";
}
return wxID_OK;
}
wxStandardID wxExSVN::ExecuteAndShowOutput(wxWindow* parent)
{
// If an error occurred, already shown by wxExecute itself.
if (Execute(parent) == wxID_OK)
{
ShowOutput(parent);
}
return m_ReturnCode;
}
wxExSVNType wxExSVN::GetType(int command_id) const
{
switch (command_id)
{
case ID_EDIT_SVN_BLAME: return SVN_BLAME; break;
case ID_EDIT_SVN_CAT: return SVN_CAT; break;
case ID_EDIT_SVN_COMMIT: return SVN_COMMIT; break;
case ID_EDIT_SVN_DIFF: return SVN_DIFF; break;
case ID_EDIT_SVN_HELP: return SVN_HELP; break;
case ID_EDIT_SVN_INFO: return SVN_INFO; break;
case ID_EDIT_SVN_LOG: return SVN_LOG; break;
case ID_EDIT_SVN_REVERT: return SVN_REVERT; break;
case ID_EDIT_SVN_STAT: return SVN_STAT; break;
case ID_EDIT_SVN_UPDATE: return SVN_UPDATE; break;
default:
wxFAIL;
return SVN_STAT;
break;
}
}
void wxExSVN::Initialize()
{
switch (m_Type)
{
case SVN_BLAME: m_Caption = "SVN Blame"; break;
case SVN_CAT: m_Caption = "SVN Cat"; break;
case SVN_COMMIT: m_Caption = "SVN Commit"; break;
case SVN_DIFF: m_Caption = "SVN Diff"; break;
case SVN_HELP: m_Caption = "SVN Help"; break;
case SVN_INFO: m_Caption = "SVN Info"; break;
case SVN_LOG: m_Caption = "SVN Log"; break;
case SVN_REVERT: m_Caption = "SVN Revert"; break;
case SVN_STAT: m_Caption = "SVN Stat"; break;
case SVN_UPDATE: m_Caption = "SVN Update"; break;
default:
wxFAIL;
break;
}
m_Command = m_Caption.AfterFirst(' ').Lower();
// Currently no flags, as no command was executed.
m_CommandWithFlags = m_Command;
m_Output.clear();
m_ReturnCode = wxID_NONE;
wxASSERT(wxExApp::GetConfig() != NULL);
}
void wxExSVN::ShowOutput(wxWindow* parent) const
{
switch (m_ReturnCode)
{
case wxID_CANCEL:
break;
case wxID_ABORT:
wxMessageBox(m_Output);
break;
case wxID_OK:
{
const wxString caption = m_Caption +
(!m_FullPath.empty() ? " " + wxFileName(m_FullPath).GetFullName(): wxString(wxEmptyString));
// Create a dialog for contents.
if (m_STCEntryDialog == NULL)
{
m_STCEntryDialog = new wxExSTCEntryDialog(
parent,
caption,
m_Output,
wxEmptyString,
wxOK,
wxID_ANY,
wxDefaultPosition, wxSize(575, 250));
}
else
{
m_STCEntryDialog->SetText(m_Output);
m_STCEntryDialog->SetTitle(caption);
// Reset a previous lexer.
if (!m_STCEntryDialog->GetLexer().empty())
{
m_STCEntryDialog->SetLexer(wxEmptyString);
}
}
// Add a lexer if we specified a path, asked for cat or blame
// and there is a lexer.
if (
!m_FullPath.empty() &&
(m_Type == SVN_CAT || m_Type == SVN_BLAME))
{
const wxExFileName fn(m_FullPath);
if (!fn.GetLexer().GetScintillaLexer().empty())
{
m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());
}
}
m_STCEntryDialog->Show();
}
break;
default:
wxFAIL;
break;
}
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <zlib.h>
#include "mszreader.hh"
#include "math/dataset.hh"
#include "math/forwardselection.hh"
#include "math/ridgeregression.hh"
using std::vector;
using std::string;
using std::cerr;
using namespace iomsz;
/**
* Main function for MaxSATzilla training.
* This function received 3 arguments:
* - Forward Selection Threshold;
* - Ridge Regression Scalar Delta;
* - Name of the file with training set;
* - Prefix for header output;
*/
int main(int argc, char *argv[]) {
if (argc <= 1 || argc >= 6) {
cerr << "usage: coach <fsthreshold> <delta> <trainingset> <headerprefix>\n";
exit(EXIT_FAILURE);
}
unsigned int nbSolvers, nbFeatures, nbInstances, timeOut;
string *solversNames;
string *featuresNames;
string *instancesNames;
double **data;
double threshold = atof(argv[1]);
double delta = atof(argv[2]);
char *inputFileName = argv[3];
char *headerPrefix = argv[4];
gzFile in=(inputFileName==NULL? gzdopen(0,"rb"): gzopen(inputFileName,"rb"));
if (in==NULL) {
cerr<<"Error: Could not open file: "
<<(inputFileName==NULL? "<stdin>": inputFileName)
<<endl;
exit(1);
}
parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, data);
cerr << "\n\n\nPOCM part... from now, all problems are MINE! :)\n";
cerr << "Read file: " << inputFileName << "\n"
<< "Number of Solvers: " << nbSolvers << "\n"
<< "Number of Features: " << nbFeatures << "\n"
<< "Number of Instances: " << nbInstances << "\n"
<< "Timeout: " << timeOut << "\n";
cerr << "Solver Names: ";
for(size_t i = 0; i < nbSolvers; i++)
cerr << solversNames[i] << " ";
cerr << "\nFeature Names: ";
for(size_t i = 0; i < nbFeatures; i++)
cerr << featuresNames[i] << " ";
cerr << "\nInstance Names: ";
for(size_t i = 0; i < nbInstances; i++)
cerr << instancesNames[i] << " ";
cerr << "\n";
MSZDataSet *ds = createDataSet(data, nbInstances, nbFeatures+nbSolvers, nbSolvers);
vector<string> snames;
for(size_t s = 0; s < nbSolvers; s++) snames.push_back(solversNames[s]);
ds->printSolverStats(timeOut, snames);
// Lets create the plot files
vector<string> labels;
for(size_t i = 0; i < nbSolvers; i++)
labels.push_back(solversNames[i]);
for(size_t i = 0; i < nbFeatures; i++)
labels.push_back(featuresNames[i]);
cerr << "Created labels for solvers and features of size : " << labels.size() << "\n";
cerr << "features (" << nbFeatures << ") + solvers(" << nbSolvers << ") = " << labels.size() << "\n";
ds->dumpPlotFiles(labels, "./coach");
// Let's apply dataset transformations
ds->standardize();
ds->standardizeOutputs();
ds->expand(1); // always calls standardize() if you didn't before
// Lets do a forward selection
ForwardSelection fs(*ds, 1);
vector<size_t> res = fs.run(threshold);
ds->removeFeatures(res);
RidgeRegression rr(*ds);
rr.run(delta, 1, headerPrefix);
// Let's not forget to delete the dataset
delete ds;
return 0;
}
<commit_msg>By default now coach does a quadratic expansion.<commit_after>#include <iostream>
#include <vector>
#include <zlib.h>
#include "mszreader.hh"
#include "math/dataset.hh"
#include "math/forwardselection.hh"
#include "math/ridgeregression.hh"
using std::vector;
using std::string;
using std::cerr;
using namespace iomsz;
/**
* Main function for MaxSATzilla training.
* This function received 3 arguments:
* - Forward Selection Threshold;
* - Ridge Regression Scalar Delta;
* - Name of the file with training set;
* - Prefix for header output;
*/
int main(int argc, char *argv[]) {
if (argc <= 1 || argc >= 6) {
cerr << "usage: coach <fsthreshold> <delta> <trainingset> <headerprefix>\n";
exit(EXIT_FAILURE);
}
unsigned int nbSolvers, nbFeatures, nbInstances, timeOut;
string *solversNames;
string *featuresNames;
string *instancesNames;
double **data;
double threshold = atof(argv[1]);
double delta = atof(argv[2]);
char *inputFileName = argv[3];
char *headerPrefix = argv[4];
gzFile in=(inputFileName==NULL? gzdopen(0,"rb"): gzopen(inputFileName,"rb"));
if (in==NULL) {
cerr<<"Error: Could not open file: "
<<(inputFileName==NULL? "<stdin>": inputFileName)
<<endl;
exit(1);
}
parse_DIMACS(in, nbSolvers, nbFeatures, nbInstances, timeOut, solversNames, featuresNames, instancesNames, data);
cerr << "\n\n\nPOCM part... from now, all problems are MINE! :)\n";
cerr << "Read file: " << inputFileName << "\n"
<< "Number of Solvers: " << nbSolvers << "\n"
<< "Number of Features: " << nbFeatures << "\n"
<< "Number of Instances: " << nbInstances << "\n"
<< "Timeout: " << timeOut << "\n";
cerr << "Solver Names: ";
for(size_t i = 0; i < nbSolvers; i++)
cerr << solversNames[i] << " ";
cerr << "\nFeature Names: ";
for(size_t i = 0; i < nbFeatures; i++)
cerr << featuresNames[i] << " ";
cerr << "\nInstance Names: ";
for(size_t i = 0; i < nbInstances; i++)
cerr << instancesNames[i] << " ";
cerr << "\n";
MSZDataSet *ds = createDataSet(data, nbInstances, nbFeatures+nbSolvers, nbSolvers);
vector<string> snames;
for(size_t s = 0; s < nbSolvers; s++) snames.push_back(solversNames[s]);
ds->printSolverStats(timeOut, snames);
// Lets create the plot files
vector<string> labels;
for(size_t i = 0; i < nbSolvers; i++)
labels.push_back(solversNames[i]);
for(size_t i = 0; i < nbFeatures; i++)
labels.push_back(featuresNames[i]);
cerr << "Created labels for solvers and features of size : " << labels.size() << "\n";
cerr << "features (" << nbFeatures << ") + solvers(" << nbSolvers << ") = " << labels.size() << "\n";
ds->dumpPlotFiles(labels, "./coach");
// Let's apply dataset transformations
ds->standardize();
ds->standardizeOutputs();
ds->expand(2); // always calls standardize() if you didn't before
// Lets do a forward selection
ForwardSelection fs(*ds, 1);
vector<size_t> res = fs.run(threshold);
ds->removeFeatures(res);
RidgeRegression rr(*ds);
rr.run(delta, 1, headerPrefix);
// Let's not forget to delete the dataset
delete ds;
return 0;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test.hpp"
TEMPLATE_TEST_CASE_2("alias/1", "[alias]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a;
etl::dyn_matrix<Z> b(3, 3);
REQUIRE(a.alias(a));
REQUIRE(b.alias(b));
REQUIRE(!b.alias(a));
REQUIRE(!a.alias(b));
REQUIRE(a.alias(a + a));
REQUIRE(a.alias(a + 1));
REQUIRE(!a.alias(b + 1));
REQUIRE((a + a).alias(a + a));
REQUIRE(!a.alias(b >> b));
REQUIRE(a.alias(a(0)));
REQUIRE(a(0).alias(a(0)));
REQUIRE(!a(0).alias(a(1)));
REQUIRE(a.alias(a(0) + a(1)));
}
TEMPLATE_TEST_CASE_2("alias/traits/1", "[alias][traits]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
//Test linear operations
REQUIRE(etl::decay_traits<decltype(a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a * a)>::is_linear);
REQUIRE(etl::decay_traits<decltype((a >> a) + a - a / a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a(0))>::is_linear);
//Test non linear operations
REQUIRE(!etl::decay_traits<decltype(transpose(a))>::is_linear);
REQUIRE(!etl::decay_traits<decltype(fflip(a))>::is_linear);
REQUIRE(!etl::decay_traits<decltype(a + fflip(a))>::is_linear);
}
TEMPLATE_TEST_CASE_2("alias/transpose/1", "[alias][transpose]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
a = transpose(a);
REQUIRE(a(0, 0) == 1.0);
REQUIRE(a(0, 1) == 4.0);
REQUIRE(a(0, 2) == 7.0);
REQUIRE(a(1, 0) == 2.0);
REQUIRE(a(1, 1) == 5.0);
REQUIRE(a(1, 2) == 8.0);
REQUIRE(a(2, 0) == 3.0);
REQUIRE(a(2, 1) == 6.0);
REQUIRE(a(2, 2) == 9.0);
}
<commit_msg>New aliasing test<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "test.hpp"
TEMPLATE_TEST_CASE_2("alias/1", "[alias]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a;
etl::dyn_matrix<Z> b(3, 3);
REQUIRE(a.alias(a));
REQUIRE(b.alias(b));
REQUIRE(!b.alias(a));
REQUIRE(!a.alias(b));
REQUIRE(a.alias(a + a));
REQUIRE(a.alias(a + 1));
REQUIRE(!a.alias(b + 1));
REQUIRE((a + a).alias(a + a));
REQUIRE(!a.alias(b >> b));
REQUIRE(a.alias(a(0)));
REQUIRE(a(0).alias(a(0)));
REQUIRE(!a(0).alias(a(1)));
REQUIRE(a.alias(a(0) + a(1)));
}
TEMPLATE_TEST_CASE_2("alias/traits/1", "[alias][traits]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
//Test linear operations
REQUIRE(etl::decay_traits<decltype(a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a * a)>::is_linear);
REQUIRE(etl::decay_traits<decltype((a >> a) + a - a / a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a)>::is_linear);
REQUIRE(etl::decay_traits<decltype(a(0))>::is_linear);
//Test non linear operations
REQUIRE(!etl::decay_traits<decltype(transpose(a))>::is_linear);
REQUIRE(!etl::decay_traits<decltype(fflip(a))>::is_linear);
REQUIRE(!etl::decay_traits<decltype(a + fflip(a))>::is_linear);
}
TEMPLATE_TEST_CASE_2("alias/transpose/1", "[alias][transpose]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
a = transpose(a);
REQUIRE(a(0, 0) == 1.0);
REQUIRE(a(0, 1) == 4.0);
REQUIRE(a(0, 2) == 7.0);
REQUIRE(a(1, 0) == 2.0);
REQUIRE(a(1, 1) == 5.0);
REQUIRE(a(1, 2) == 8.0);
REQUIRE(a(2, 0) == 3.0);
REQUIRE(a(2, 1) == 6.0);
REQUIRE(a(2, 2) == 9.0);
}
TEMPLATE_TEST_CASE_2("alias/transpose/2", "[alias][transpose]", Z, float, double) {
etl::fast_matrix<Z, 3, 3> a({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0});
a = (transpose(a) >> 2.0) + (transpose(a) >> 3.0);
REQUIRE(a(0, 0) == 5.0);
REQUIRE(a(0, 1) == 20.0);
REQUIRE(a(0, 2) == 35.0);
REQUIRE(a(1, 0) == 10.0);
REQUIRE(a(1, 1) == 25.0);
REQUIRE(a(1, 2) == 40.0);
REQUIRE(a(2, 0) == 15.0);
REQUIRE(a(2, 1) == 30.0);
REQUIRE(a(2, 2) == 45.0);
}
<|endoftext|> |
<commit_before><commit_msg>forgot this file<commit_after><|endoftext|> |
<commit_before>#include <armadillo>
#include "compute/edflib.h"
#include "compute/eeg_spectrogram.hpp"
#include "compute/eeg_change_point.hpp"
#include "json11/json11.hpp"
#include "wslib/server_ws.hpp"
using namespace arma;
using namespace std;
using namespace SimpleWeb;
using namespace json11;
#define NUM_THREADS 4
#define PORT 8080
#define TEXT_OPCODE 129
#define BINARY_OPCODE 130
const char* CH_NAME_MAP[] = {"LL", "LP", "RP", "RL"};
void send_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection,
std::string msg_type, Json content, float* data, size_t data_size)
{
Json msg = Json::object
{
{"type", msg_type},
{"content", content}
};
std::string header = msg.dump();
uint32_t header_len = header.size() + (8 - ((header.size() + 4) % 8));
// append enough spaces so that the payload starts at an 8-byte
// aligned position. The first four bytes will be the length of
// the header, encoded as a 32 bit signed integer:
header.resize(header_len, ' ');
stringstream data_ss;
data_ss.write((char*) &header_len, sizeof(uint32_t));
data_ss.write(header.c_str(), header_len);
if (data != NULL)
{
data_ss.write((char*) data, data_size);
}
// server.send is an asynchronous function
server->send(connection, data_ss, [](const boost::system::error_code & ec)
{
if (ec)
{
cout << "Server: Error sending message. " <<
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html
// Error Codes for error code meanings
"Error: " << ec << ", error message: " << ec.message() << endl;
}
}, BINARY_OPCODE);
}
void log_json(Json content) {
cout << "Sending content " << content.dump() << endl;
}
void send_frowvec(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
std::string canvasId, std::string type,
frowvec* vector)
{
Json content = Json::object
{
{"action", "change_points"},
{"type", type},
{"canvasId", canvasId}
};
log_json(content);
send_message(server, connection, "spectrogram", content, vector->memptr(), vector->n_elem);
}
void send_spectrogram_new(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
spec_params_t spec_params, std::string canvasId)
{
Json content = Json::object
{
{"action", "new"},
{"nblocks", spec_params.nblocks},
{"nfreqs", spec_params.nfreqs},
{"fs", spec_params.fs},
{"length", spec_params.spec_len},
{"canvasId", canvasId}
};
log_json(content);
send_message(server, connection, "spectrogram", content, NULL, -1);
}
void send_spectrogram_update(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
spec_params_t spec_params, std::string canvasId,
fmat& spec_mat)
{
Json content = Json::object
{
{"action", "update"},
{"nblocks", spec_params.nblocks},
{"nfreqs", spec_params.nfreqs},
{"canvasId", canvasId}
};
size_t data_size = sizeof(float) * spec_mat.n_elem;
float* spec_arr = (float*) malloc(data_size);
serialize_spec_mat(&spec_params, spec_mat, spec_arr);
log_json(content);
send_message(server, connection, "spectrogram", content, spec_arr, data_size);
free(spec_arr);
}
void send_change_points(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
std::string canvasId,
cp_data_t* cp_data)
{
send_frowvec(server, connection, canvasId, "change_points", cp_data->cp);
send_frowvec(server, connection, canvasId, "summed_signal", cp_data->m);
}
void on_file_spectrogram(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, Json data)
{
std::string filename = data["filename"].string_value();
float duration = data["duration"].number_value();
spec_params_t spec_params;
char *filename_c = new char[filename.length() + 1];
strcpy(filename_c, filename.c_str());
get_eeg_spectrogram_params(&spec_params, filename_c, duration);
print_spec_params_t(&spec_params);
const char* ch_name;
for (int ch = 0; ch < NUM_CH; ch++)
{
ch_name = CH_NAME_MAP[ch];
send_spectrogram_new(server, connection, spec_params, ch_name);
fmat spec_mat = fmat(spec_params.nfreqs, spec_params.nblocks);
eeg_spectrogram(&spec_params, ch, spec_mat);
cp_data_t cp_data;
get_change_points(spec_mat, &cp_data);
send_spectrogram_update(server, connection, spec_params, ch_name, spec_mat);
send_change_points(server, connection, ch_name, &cp_data);
this_thread::sleep_for(chrono::seconds(5)); // TODO(joshblum): fix this..
}
close_edf(filename_c);
}
void receive_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string type, Json content)
{
if (type == "request_file_spectrogram")
{
on_file_spectrogram(server, connection, content);
}
else if (type == "information")
{
cout << content.string_value() << endl;
}
else
{
cout << "Unknown type: " << type << " and content: " << content.string_value() << endl;
}
}
int main()
{
//WebSocket (WS)-server at PORT using NUM_THREADS threads
SocketServer<WS> server(PORT, NUM_THREADS);
auto& ws = server.endpoint["^/compute/spectrogram/?$"];
//C++14, lambda parameters declared with auto
//For C++11 use: (shared_ptr<SocketServer<WS>::Connection> connection, shared_ptr<SocketServer<WS>::Message> message)
ws.onmessage = [&server](auto connection, auto message)
{
//To receive message from client as string (data_ss.str())
stringstream data_ss;
message->data >> data_ss.rdbuf();
std::string data_s, err;
data_s = data_ss.str();
Json json = Json::parse(data_s, err);
// TODO add error checking for null fields
std::string type = json["type"].string_value();
Json content = json["content"];
receive_message(&server, connection, type, content);
};
ws.onopen = [](auto connection)
{
cout << "WebSocket opened" << endl;
};
//See RFC 6455 7.4.1. for status codes
ws.onclose = [](auto connection, int status, const string & reason)
{
cout << "Server: Closed connection " << (size_t)connection.get() << " with status code " << status << endl;
};
//See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
ws.onerror = [](auto connection, const boost::system::error_code & ec)
{
cout << "Server: Error in connection " << (size_t)connection.get() << ". " <<
"Error: " << ec << ", error message: " << ec.message() << endl;
};
thread server_thread([&server]()
{
cout << "WebSocket Server started at port: " << PORT << endl;
//Start WS-server
server.start();
});
server_thread.join();
return 0;
}
<commit_msg>add locking to solve concurreny bug<commit_after>#include <armadillo>
#include <mutex>
#include "compute/edflib.h"
#include "compute/eeg_spectrogram.hpp"
#include "compute/eeg_change_point.hpp"
#include "json11/json11.hpp"
#include "wslib/server_ws.hpp"
using namespace arma;
using namespace std;
using namespace SimpleWeb;
using namespace json11;
#define NUM_THREADS 4
#define PORT 8080
#define TEXT_OPCODE 129
#define BINARY_OPCODE 130
const char* CH_NAME_MAP[] = {"LL", "LP", "RP", "RL"};
std::mutex server_send_mutex;
void send_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection,
std::string msg_type, Json content, float* data, size_t data_size)
{
server_send_mutex.lock();
Json msg = Json::object
{
{"type", msg_type},
{"content", content}
};
std::string header = msg.dump();
uint32_t header_len = header.size() + (8 - ((header.size() + 4) % 8));
// append enough spaces so that the payload starts at an 8-byte
// aligned position. The first four bytes will be the length of
// the header, encoded as a 32 bit signed integer:
header.resize(header_len, ' ');
stringstream data_ss;
data_ss.write((char*) &header_len, sizeof(uint32_t));
data_ss.write(header.c_str(), header_len);
if (data != NULL)
{
data_ss.write((char*) data, data_size);
}
// server.send is an asynchronous function
server->send(connection, data_ss, [](const boost::system::error_code & ec)
{
server_send_mutex.unlock();
if (ec)
{
cout << "Server: Error sending message. " <<
// See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html
// Error Codes for error code meanings
"Error: " << ec << ", error message: " << ec.message() << endl;
}
}, BINARY_OPCODE);
}
void log_json(Json content) {
cout << "Sending content " << content.dump() << endl;
}
void send_frowvec(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
std::string canvasId, std::string type,
frowvec* vector)
{
Json content = Json::object
{
{"action", "change_points"},
{"type", type},
{"canvasId", canvasId}
};
log_json(content);
send_message(server, connection, "spectrogram", content, vector->memptr(), vector->n_elem);
}
void send_spectrogram_new(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
spec_params_t spec_params, std::string canvasId)
{
Json content = Json::object
{
{"action", "new"},
{"nblocks", spec_params.nblocks},
{"nfreqs", spec_params.nfreqs},
{"fs", spec_params.fs},
{"length", spec_params.spec_len},
{"canvasId", canvasId}
};
log_json(content);
send_message(server, connection, "spectrogram", content, NULL, -1);
}
void send_spectrogram_update(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
spec_params_t spec_params, std::string canvasId,
fmat& spec_mat)
{
Json content = Json::object
{
{"action", "update"},
{"nblocks", spec_params.nblocks},
{"nfreqs", spec_params.nfreqs},
{"canvasId", canvasId}
};
size_t data_size = sizeof(float) * spec_mat.n_elem;
float* spec_arr = (float*) malloc(data_size);
serialize_spec_mat(&spec_params, spec_mat, spec_arr);
log_json(content);
send_message(server, connection, "spectrogram", content, spec_arr, data_size);
free(spec_arr);
}
void send_change_points(SocketServer<WS>* server,
shared_ptr<SocketServer<WS>::Connection> connection,
std::string canvasId,
cp_data_t* cp_data)
{
send_frowvec(server, connection, canvasId, "change_points", cp_data->cp);
send_frowvec(server, connection, canvasId, "summed_signal", cp_data->m);
}
void on_file_spectrogram(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, Json data)
{
std::string filename = data["filename"].string_value();
float duration = data["duration"].number_value();
spec_params_t spec_params;
char *filename_c = new char[filename.length() + 1];
strcpy(filename_c, filename.c_str());
get_eeg_spectrogram_params(&spec_params, filename_c, duration);
print_spec_params_t(&spec_params);
const char* ch_name;
for (int ch = 0; ch < NUM_CH; ch++)
{
ch_name = CH_NAME_MAP[ch];
send_spectrogram_new(server, connection, spec_params, ch_name);
fmat spec_mat = fmat(spec_params.nfreqs, spec_params.nblocks);
eeg_spectrogram(&spec_params, ch, spec_mat);
cp_data_t cp_data;
get_change_points(spec_mat, &cp_data);
send_spectrogram_update(server, connection, spec_params, ch_name, spec_mat);
send_change_points(server, connection, ch_name, &cp_data);
}
close_edf(filename_c);
}
void receive_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string type, Json content)
{
if (type == "request_file_spectrogram")
{
on_file_spectrogram(server, connection, content);
}
else if (type == "information")
{
cout << content.string_value() << endl;
}
else
{
cout << "Unknown type: " << type << " and content: " << content.string_value() << endl;
}
}
int main()
{
//WebSocket (WS)-server at PORT using NUM_THREADS threads
SocketServer<WS> server(PORT, NUM_THREADS);
auto& ws = server.endpoint["^/compute/spectrogram/?$"];
//C++14, lambda parameters declared with auto
//For C++11 use: (shared_ptr<SocketServer<WS>::Connection> connection, shared_ptr<SocketServer<WS>::Message> message)
ws.onmessage = [&server](auto connection, auto message)
{
//To receive message from client as string (data_ss.str())
stringstream data_ss;
message->data >> data_ss.rdbuf();
std::string data_s, err;
data_s = data_ss.str();
Json json = Json::parse(data_s, err);
// TODO add error checking for null fields
std::string type = json["type"].string_value();
Json content = json["content"];
receive_message(&server, connection, type, content);
};
ws.onopen = [](auto connection)
{
cout << "WebSocket opened" << endl;
};
//See RFC 6455 7.4.1. for status codes
ws.onclose = [](auto connection, int status, const string & reason)
{
cout << "Server: Closed connection " << (size_t)connection.get() << " with status code " << status << endl;
};
//See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings
ws.onerror = [](auto connection, const boost::system::error_code & ec)
{
cout << "Server: Error in connection " << (size_t)connection.get() << ". " <<
"Error: " << ec << ", error message: " << ec.message() << endl;
};
thread server_thread([&server]()
{
cout << "WebSocket Server started at port: " << PORT << endl;
//Start WS-server
server.start();
});
server_thread.join();
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* 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/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public:
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
private:
/** Detect if the end of a kmer is equal to the begin of other
* \param[in] begin first kmer
* \param[in] end the other kmer
* \return The size of repetition
*/
unsigned int fuzzy_site(std::string begin, std::string end);
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = this->fuzzy_site(begin, end);
if(repeat_size > (unsigned)this->_find->max_repeat())
{
return false;
}
if(repeat_size != 0)
{
begin = begin.substr(0, begin.length() - repeat_size);
}
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size + 1;
// Create a sequence maybe is in graphe
std::string seq = begin + end;
// Create variable required for iterate on kmer
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
// Init this variable
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
bool is_deletion = true;
for(local_it.first(); !local_it.isDone(); local_it.next())
{
std::cout<<std::boolalpha<<this->contains(local_it->forward())<<" "<<this->_find->model().toString(local_it->forward())<<std::endl;
if(!this->contains(local_it->forward()))
{
is_deletion = false;
break;
}
}
if(is_deletion == false)
{
if(repeat_size == 0)
{
return false;
}
else // Maybee isn't a fuzzy deletion
{
seq = this->_find->model().toString(this->_find->kmer_begin().forward()) + end;
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
std::cout<<"Is a false fuzzy deletion"<<std::endl;
del_size -= repeat_size;
repeat_size = 0;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 1, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
/*
with max_repeat = 5
good case 1 + 5 + 1 = 6 operation exemple AAAAATTCGG TTCGGCCCCC
*/
template<size_t span>
unsigned int FindDeletion<span>::fuzzy_site(std::string begin, std::string end)
{
for(unsigned int i = this->_find->max_repeat(); i != 0; i--)
for(unsigned int j = 1; begin.substr(begin.length() - i, j) == end.substr(0, j); j++)
if(i == j)
return j;
return 0;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<commit_msg>MTG: clean debug instruction<commit_after>/*****************************************************************************
* MindTheGap: Integrated detection and assembly of insertion variants
* A tool from the GATB (Genome Assembly Tool Box)
* Copyright (C) 2014 INRIA
* Authors: C.Lemaitre, G.Rizk, P.Marijon
*
* 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/>.
*****************************************************************************/
#ifndef _TOOL_FindDeletion_HPP_
#define _TOOL_FindDeletion_HPP_
/*****************************************************************************/
#include <IFindObserver.hpp>
#include <FindBreakpoints.hpp>
template<size_t span>
class FindDeletion : public IFindObserver<span>
{
public :
typedef typename gatb::core::kmer::impl::Kmer<span> Kmer;
typedef typename Kmer::ModelCanonical KmerModel;
typedef typename KmerModel::Iterator KmerIterator;
public:
/** \copydoc IFindObserver<span>
*/
FindDeletion(FindBreakpoints<span> * find);
/** \copydoc IFindObserver::IFindObserver
*/
bool update();
private:
/** Detect if the end of a kmer is equal to the begin of other
* \param[in] begin first kmer
* \param[in] end the other kmer
* \return The size of repetition
*/
unsigned int fuzzy_site(std::string begin, std::string end);
};
template<size_t span>
FindDeletion<span>::FindDeletion(FindBreakpoints<span> * find) : IFindObserver<span>(find){}
template<size_t span>
bool FindDeletion<span>::update()
{
if((this->_find->kmer_begin().isValid() && this->_find->kmer_end().isValid()) == false)
{
return false;
}
// Test if deletion is a fuzzy deletion
std::string begin = this->_find->model().toString(this->_find->kmer_begin().forward());
std::string end = this->_find->model().toString(this->_find->kmer_end().forward());
unsigned int repeat_size = this->fuzzy_site(begin, end);
if(repeat_size > (unsigned)this->_find->max_repeat())
{
return false;
}
if(repeat_size != 0)
{
begin = begin.substr(0, begin.length() - repeat_size);
}
// Compute del_size
unsigned int del_size = this->_find->gap_stretch_size() - this->_find->kmer_size() + repeat_size + 1;
// Create a sequence maybe is in graphe
std::string seq = begin + end;
// Create variable required for iterate on kmer
KmerModel local_m(this->_find->kmer_size());
KmerIterator local_it(local_m);
Data local_d(const_cast<char*>(seq.c_str()));
// Init this variable
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
bool is_deletion = true;
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
is_deletion = false;
break;
}
}
if(is_deletion == false)
{
if(repeat_size == 0)
{
return false;
}
else // Maybee isn't a fuzzy deletion
{
seq = this->_find->model().toString(this->_find->kmer_begin().forward()) + end;
local_d.setRef(const_cast<char*>(seq.c_str()), (size_t)seq.length());
local_it.setData(local_d);
for(local_it.first(); !local_it.isDone(); local_it.next())
{
if(!this->contains(local_it->forward()))
{
return false;
}
}
std::cout<<"Is a false fuzzy deletion"<<std::endl;
del_size -= repeat_size;
repeat_size = 0;
}
}
// Write the breakpoint
this->_find->writeBreakpoint(this->_find->breakpoint_id(), this->_find->chrom_name(), this->_find->position() - del_size - 1, begin, end, repeat_size, STR_DEL_TYPE);
this->_find->breakpoint_id_iterate();
if(repeat_size != 0)
this->_find->fuzzy_deletion_iterate();
else
this->_find->clean_deletion_iterate();
return true;
}
/*
with max_repeat = 5
good case 1 + 5 + 1 = 6 operation exemple AAAAATTCGG TTCGGCCCCC
*/
template<size_t span>
unsigned int FindDeletion<span>::fuzzy_site(std::string begin, std::string end)
{
for(unsigned int i = this->_find->max_repeat(); i != 0; i--)
for(unsigned int j = 1; begin.substr(begin.length() - i, j) == end.substr(0, j); j++)
if(i == j)
return j;
return 0;
}
#endif /* _TOOL_FindDeletion_HPP_ */
<|endoftext|> |
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "TensorFwd.hpp"
#include "Exceptions.hpp"
#include "Optional.hpp"
#include "Types.hpp"
#include <array>
#include <initializer_list>
#include <vector>
namespace armnn
{
class TensorShape
{
public:
/// Empty (invalid) constructor.
TensorShape();
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param initDimensionsSpecificity (optional) - value to initialize the specificity of each dimension size.
explicit TensorShape(unsigned int numDimensions, bool initDimensionsSpecificity = true);
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param dimensionSizes - Size of each of dimension.
TensorShape(unsigned int numDimensions, const unsigned int* dimensionSizes);
/// Constructor for TensorShape
/// @param dimensionSizeList - Size of each of dimension.
TensorShape(std::initializer_list<unsigned int> dimensionSizeList);
/// Copy Constructor for TensorShape
/// @param other - TensorShape to copy from.
TensorShape(const TensorShape& other);
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param dimensionSizes - Size of each of dimension.
/// @param dimensionsSpecificity - Flags to indicate which dimension has its size specified.
TensorShape(unsigned int numDimensions, const unsigned int* dimensionSizes, const bool* dimensionsSpecificity);
/// Constructor for TensorShape
/// @param dimensionSizeList - Size of each of dimension.
/// @param dimensionsSpecificityList - Flags to indicate which dimension size is specified.
TensorShape(std::initializer_list<unsigned int> dimensionSizeList,
std::initializer_list<bool> dimensionsSpecificityList);
/// Constructor for TensorShape
/// @param dimensionality - Parameter to indicate if the Tensor is a Scalar, a Tensor of known dimensionality
/// or a Tensor of unknown dimensionality.
explicit TensorShape(Dimensionality dimensionality);
/// Assignation function
/// @param other - TensorShape to copy from.
TensorShape& operator=(const TensorShape& other);
/// Read only operator
/// @param i - Dimension index.
unsigned int operator[](unsigned int i) const;
/// Read and write operator
/// @param i - Dimension index.
unsigned int& operator[](unsigned int i);
/// Equality comparison operator
/// @param other - TensorShape to compare with.
bool operator==(const TensorShape& other) const;
/// Inequality comparison operator
/// @param other - TensorShape to compare with.
bool operator!=(const TensorShape& other) const;
/// Function that returns the tensor rank.
/// @return - Tensor rank.
unsigned int GetNumDimensions() const;
/// Function that calculates the tensor elements by multiplying all dimension size which are Specified.
/// @return - Total number of elements in the tensor.
unsigned int GetNumElements() const;
/// Function that returns the tensor type.
/// @return - Parameter to indicate if the Tensor is a scalar, a Tensor of known dimensionality or
/// a Tensor of unknown dimensionality
Dimensionality GetDimensionality() const { return m_Dimensionality; }
/// Gets information about if the dimension size has been specified or not
/// @param i - Dimension index.
/// @return - Flag to indicate if the dimension "i" has a specified size.
bool GetDimensionSpecificity(unsigned int i) const;
/// Sets the tensor rank and therefore the Dimensionality is set to Specified if it was not.
/// @param numDimensions - Tensor rank.
/// @param initDimensionsSpecificity (optional) - value to initialize the specificity of each dimension size.
void SetNumDimensions(unsigned int numDimensions, bool initDimensionsSpecificity = false);
/// Sets the size of the indicated dimension and Specificity for that dimension is set to true.
/// @param i - Dimension index.
/// @param dimensionSize - size of one dimension.
void SetDimensionSize(unsigned int i, unsigned int dimensionSize);
/// Checks if there is at least one dimension not specified. AND of all array elements.
/// @return - True when all dimension sizes are specified. False when at least one dimension size is not specified.
bool AreAllDimensionsSpecified() const;
/// Checks if there is at least one dimension specified. OR of all array elements.
/// @return - True at least one dimension sizes is specified. False when all dimension sizes are not specified.
bool IsAtLeastOneDimensionSpecified() const;
private:
/// Array of the dimension sizes.
std::array<unsigned int, MaxNumOfTensorDimensions> m_Dimensions{};
/// Array of flags to indicate if the size of each of the dimensions is specified or not
std::array<bool, MaxNumOfTensorDimensions> m_DimensionsSpecificity = { {true} };
/// Tensor rank
unsigned int m_NumDimensions{};
/// Tensor type: Specified, NotSpecified or Scalar.
Dimensionality m_Dimensionality = Dimensionality::Specified;
/// Checks if the dimension index given is within range.
/// @param i - Dimension index.
void CheckDimensionIndex(unsigned int i) const;
/// Checks if the tensor rank given is within range.
/// @param numDimensions - Tensor rank.
static void CheckValidNumDimensions(unsigned int numDimensions) ;
/// Checks if the size of the dimension index given is specified.
/// @param i - Dimension index.
void CheckDimensionSpecified(unsigned int i) const;
/// Checks if this is a scalar.
void CheckScalar() const;
/// Checks if the number of dimensions is unknown, i.e. rank is unspecified.
void CheckUnspecifiedNumDimensions() const;
/// Checks if the number of dimensions is known, i.e. rank is specified.
void CheckSpecifiedNumDimensions() const;
};
class TensorInfo
{
public:
/// Empty (invalid) constructor.
TensorInfo();
TensorInfo(const TensorShape& shape,
DataType dataType,
float quantizationScale = 0.0f,
int32_t quantizationOffset = 0);
TensorInfo(unsigned int numDimensions,
const unsigned int* dimensionSizes,
DataType dataType,
float quantizationScale = 0.0f,
int32_t quantizationOffset = 0);
TensorInfo(const TensorShape& shape,
DataType dataType,
const std::vector<float>& quantizationScales,
unsigned int quantizationDim);
TensorInfo(unsigned int numDimensions,
const unsigned int* dimensionSizes,
DataType dataType,
const std::vector<float>& quantizationScales,
unsigned int quantizationDim);
TensorInfo(const TensorInfo& other);
TensorInfo& operator=(const TensorInfo& other);
bool operator==(const TensorInfo& other) const;
bool operator!=(const TensorInfo& other) const;
const TensorShape& GetShape() const { return m_Shape; }
TensorShape& GetShape() { return m_Shape; }
void SetShape(const TensorShape& newShape) { m_Shape = newShape; }
unsigned int GetNumDimensions() const { return m_Shape.GetNumDimensions(); }
unsigned int GetNumElements() const { return m_Shape.GetNumElements(); }
DataType GetDataType() const { return m_DataType; }
void SetDataType(DataType type) { m_DataType = type; }
bool HasMultipleQuantizationScales() const { return m_Quantization.m_Scales.size() > 1; }
bool HasPerAxisQuantization() const;
std::vector<float> GetQuantizationScales() const;
void SetQuantizationScales(const std::vector<float>& scales);
float GetQuantizationScale() const;
void SetQuantizationScale(float scale);
int32_t GetQuantizationOffset() const;
void SetQuantizationOffset(int32_t offset);
Optional<unsigned int> GetQuantizationDim() const;
void SetQuantizationDim(const Optional<unsigned int>& quantizationDim);
bool IsQuantized() const;
/// Check that the types are the same and, if quantize, that the quantization parameters are the same.
bool IsTypeSpaceMatch(const TensorInfo& other) const;
unsigned int GetNumBytes() const;
private:
TensorShape m_Shape;
DataType m_DataType;
/// Vectors of scale and offset are used for per-axis quantization.
struct Quantization
{
Quantization()
: m_Scales{}
, m_Offset(EmptyOptional())
, m_QuantizationDim(EmptyOptional()) {}
bool operator==(const Quantization& other) const
{
return ((m_Scales == other.m_Scales) && (m_Offset == other.m_Offset) &&
(m_QuantizationDim == other.m_QuantizationDim));
}
Quantization& operator=(const Quantization& other)
{
if(!(*this == other))
{
m_Scales = other.m_Scales;
m_Offset = other.m_Offset;
m_QuantizationDim = other.m_QuantizationDim;
}
return *this;
}
std::vector<float> m_Scales;
Optional<int32_t> m_Offset;
Optional<unsigned int> m_QuantizationDim;
} m_Quantization;
};
using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
template<typename MemoryType>
class BaseTensor
{
public:
/// Empty (invalid) constructor.
BaseTensor();
/// Constructor from a raw memory pointer.
/// @param memoryArea - Region of CPU-addressable memory where tensor data will be stored. Must be valid while
/// workloads are on the fly. Tensor instances do not claim ownership of referenced memory regions, that is,
/// no attempt will be made by ArmNN to free these memory regions automatically.
BaseTensor(const TensorInfo& info, MemoryType memoryArea);
/// Tensors are copyable.
BaseTensor(const BaseTensor& other);
/// Tensors are copyable.
BaseTensor& operator=(const BaseTensor&);
const TensorInfo& GetInfo() const { return m_Info; }
TensorInfo& GetInfo() { return m_Info; }
const TensorShape& GetShape() const { return m_Info.GetShape(); }
TensorShape& GetShape() { return m_Info.GetShape(); }
DataType GetDataType() const { return m_Info.GetDataType(); }
unsigned int GetNumDimensions() const { return m_Info.GetNumDimensions(); }
unsigned int GetNumBytes() const { return m_Info.GetNumBytes(); }
unsigned int GetNumElements() const { return m_Info.GetNumElements(); }
MemoryType GetMemoryArea() const { return m_MemoryArea; }
protected:
/// Protected destructor to stop users from making these
/// (could still new one on the heap and then leak it...)
~BaseTensor() {}
MemoryType m_MemoryArea;
private:
TensorInfo m_Info;
};
/// A tensor defined by a TensorInfo (shape and data type) and a mutable backing store.
class Tensor : public BaseTensor<void*>
{
public:
/// Brings in the constructors and assignment operator.
using BaseTensor<void*>::BaseTensor;
};
/// A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
class ConstTensor : public BaseTensor<const void*>
{
public:
/// Brings in the constructors and assignment operator.
using BaseTensor<const void*>::BaseTensor;
ConstTensor() : BaseTensor<const void*>() {} // This needs to be redefined explicitly??
/// Can be implicitly constructed from non-const Tensor.
ConstTensor(const Tensor& other) : BaseTensor<const void*>(other.GetInfo(), other.GetMemoryArea()) {}
/// Constructor from a backing container.
/// @param container - An stl-like container type which implements data() and size() methods.
/// Presence of data() and size() is a strong indicator of the continuous memory layout of the container,
/// which is a requirement for Tensor data. Tensor instances do not claim ownership of referenced memory regions,
/// that is, no attempt will be made by ArmNN to free these memory regions automatically.
template < template<typename, typename...> class ContainerType, typename T, typename...ContainerArgs >
ConstTensor(const TensorInfo& info, const ContainerType<T, ContainerArgs...>& container)
: BaseTensor<const void*>(info, container.data())
{
if (container.size() * sizeof(T) != info.GetNumBytes())
{
throw InvalidArgumentException("Container size is not correct");
}
}
};
using InputTensors = std::vector<std::pair<LayerBindingId, class ConstTensor>>;
using OutputTensors = std::vector<std::pair<LayerBindingId, class Tensor>>;
} // namespace armnn
<commit_msg>Quantization copy constructor<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "TensorFwd.hpp"
#include "Exceptions.hpp"
#include "Optional.hpp"
#include "Types.hpp"
#include <array>
#include <initializer_list>
#include <vector>
namespace armnn
{
class TensorShape
{
public:
/// Empty (invalid) constructor.
TensorShape();
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param initDimensionsSpecificity (optional) - value to initialize the specificity of each dimension size.
explicit TensorShape(unsigned int numDimensions, bool initDimensionsSpecificity = true);
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param dimensionSizes - Size of each of dimension.
TensorShape(unsigned int numDimensions, const unsigned int* dimensionSizes);
/// Constructor for TensorShape
/// @param dimensionSizeList - Size of each of dimension.
TensorShape(std::initializer_list<unsigned int> dimensionSizeList);
/// Copy Constructor for TensorShape
/// @param other - TensorShape to copy from.
TensorShape(const TensorShape& other);
/// Constructor for TensorShape
/// @param numDimensions - Tensor rank.
/// @param dimensionSizes - Size of each of dimension.
/// @param dimensionsSpecificity - Flags to indicate which dimension has its size specified.
TensorShape(unsigned int numDimensions, const unsigned int* dimensionSizes, const bool* dimensionsSpecificity);
/// Constructor for TensorShape
/// @param dimensionSizeList - Size of each of dimension.
/// @param dimensionsSpecificityList - Flags to indicate which dimension size is specified.
TensorShape(std::initializer_list<unsigned int> dimensionSizeList,
std::initializer_list<bool> dimensionsSpecificityList);
/// Constructor for TensorShape
/// @param dimensionality - Parameter to indicate if the Tensor is a Scalar, a Tensor of known dimensionality
/// or a Tensor of unknown dimensionality.
explicit TensorShape(Dimensionality dimensionality);
/// Assignation function
/// @param other - TensorShape to copy from.
TensorShape& operator=(const TensorShape& other);
/// Read only operator
/// @param i - Dimension index.
unsigned int operator[](unsigned int i) const;
/// Read and write operator
/// @param i - Dimension index.
unsigned int& operator[](unsigned int i);
/// Equality comparison operator
/// @param other - TensorShape to compare with.
bool operator==(const TensorShape& other) const;
/// Inequality comparison operator
/// @param other - TensorShape to compare with.
bool operator!=(const TensorShape& other) const;
/// Function that returns the tensor rank.
/// @return - Tensor rank.
unsigned int GetNumDimensions() const;
/// Function that calculates the tensor elements by multiplying all dimension size which are Specified.
/// @return - Total number of elements in the tensor.
unsigned int GetNumElements() const;
/// Function that returns the tensor type.
/// @return - Parameter to indicate if the Tensor is a scalar, a Tensor of known dimensionality or
/// a Tensor of unknown dimensionality
Dimensionality GetDimensionality() const { return m_Dimensionality; }
/// Gets information about if the dimension size has been specified or not
/// @param i - Dimension index.
/// @return - Flag to indicate if the dimension "i" has a specified size.
bool GetDimensionSpecificity(unsigned int i) const;
/// Sets the tensor rank and therefore the Dimensionality is set to Specified if it was not.
/// @param numDimensions - Tensor rank.
/// @param initDimensionsSpecificity (optional) - value to initialize the specificity of each dimension size.
void SetNumDimensions(unsigned int numDimensions, bool initDimensionsSpecificity = false);
/// Sets the size of the indicated dimension and Specificity for that dimension is set to true.
/// @param i - Dimension index.
/// @param dimensionSize - size of one dimension.
void SetDimensionSize(unsigned int i, unsigned int dimensionSize);
/// Checks if there is at least one dimension not specified. AND of all array elements.
/// @return - True when all dimension sizes are specified. False when at least one dimension size is not specified.
bool AreAllDimensionsSpecified() const;
/// Checks if there is at least one dimension specified. OR of all array elements.
/// @return - True at least one dimension sizes is specified. False when all dimension sizes are not specified.
bool IsAtLeastOneDimensionSpecified() const;
private:
/// Array of the dimension sizes.
std::array<unsigned int, MaxNumOfTensorDimensions> m_Dimensions{};
/// Array of flags to indicate if the size of each of the dimensions is specified or not
std::array<bool, MaxNumOfTensorDimensions> m_DimensionsSpecificity = { {true} };
/// Tensor rank
unsigned int m_NumDimensions{};
/// Tensor type: Specified, NotSpecified or Scalar.
Dimensionality m_Dimensionality = Dimensionality::Specified;
/// Checks if the dimension index given is within range.
/// @param i - Dimension index.
void CheckDimensionIndex(unsigned int i) const;
/// Checks if the tensor rank given is within range.
/// @param numDimensions - Tensor rank.
static void CheckValidNumDimensions(unsigned int numDimensions) ;
/// Checks if the size of the dimension index given is specified.
/// @param i - Dimension index.
void CheckDimensionSpecified(unsigned int i) const;
/// Checks if this is a scalar.
void CheckScalar() const;
/// Checks if the number of dimensions is unknown, i.e. rank is unspecified.
void CheckUnspecifiedNumDimensions() const;
/// Checks if the number of dimensions is known, i.e. rank is specified.
void CheckSpecifiedNumDimensions() const;
};
class TensorInfo
{
public:
/// Empty (invalid) constructor.
TensorInfo();
TensorInfo(const TensorShape& shape,
DataType dataType,
float quantizationScale = 0.0f,
int32_t quantizationOffset = 0);
TensorInfo(unsigned int numDimensions,
const unsigned int* dimensionSizes,
DataType dataType,
float quantizationScale = 0.0f,
int32_t quantizationOffset = 0);
TensorInfo(const TensorShape& shape,
DataType dataType,
const std::vector<float>& quantizationScales,
unsigned int quantizationDim);
TensorInfo(unsigned int numDimensions,
const unsigned int* dimensionSizes,
DataType dataType,
const std::vector<float>& quantizationScales,
unsigned int quantizationDim);
TensorInfo(const TensorInfo& other);
TensorInfo& operator=(const TensorInfo& other);
bool operator==(const TensorInfo& other) const;
bool operator!=(const TensorInfo& other) const;
const TensorShape& GetShape() const { return m_Shape; }
TensorShape& GetShape() { return m_Shape; }
void SetShape(const TensorShape& newShape) { m_Shape = newShape; }
unsigned int GetNumDimensions() const { return m_Shape.GetNumDimensions(); }
unsigned int GetNumElements() const { return m_Shape.GetNumElements(); }
DataType GetDataType() const { return m_DataType; }
void SetDataType(DataType type) { m_DataType = type; }
bool HasMultipleQuantizationScales() const { return m_Quantization.m_Scales.size() > 1; }
bool HasPerAxisQuantization() const;
std::vector<float> GetQuantizationScales() const;
void SetQuantizationScales(const std::vector<float>& scales);
float GetQuantizationScale() const;
void SetQuantizationScale(float scale);
int32_t GetQuantizationOffset() const;
void SetQuantizationOffset(int32_t offset);
Optional<unsigned int> GetQuantizationDim() const;
void SetQuantizationDim(const Optional<unsigned int>& quantizationDim);
bool IsQuantized() const;
/// Check that the types are the same and, if quantize, that the quantization parameters are the same.
bool IsTypeSpaceMatch(const TensorInfo& other) const;
unsigned int GetNumBytes() const;
private:
TensorShape m_Shape;
DataType m_DataType;
/// Vectors of scale and offset are used for per-axis quantization.
struct Quantization
{
Quantization()
: m_Scales{}
, m_Offset(EmptyOptional())
, m_QuantizationDim(EmptyOptional()) {}
Quantization(const Quantization& other)
: m_Scales(other.m_Scales)
, m_Offset(other.m_Offset)
, m_QuantizationDim(other.m_QuantizationDim) {}
bool operator==(const Quantization& other) const
{
return ((m_Scales == other.m_Scales) && (m_Offset == other.m_Offset) &&
(m_QuantizationDim == other.m_QuantizationDim));
}
Quantization& operator=(const Quantization& other)
{
if(this != &other)
{
m_Scales = other.m_Scales;
m_Offset = other.m_Offset;
m_QuantizationDim = other.m_QuantizationDim;
}
return *this;
}
std::vector<float> m_Scales;
Optional<int32_t> m_Offset;
Optional<unsigned int> m_QuantizationDim;
} m_Quantization;
};
using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
template<typename MemoryType>
class BaseTensor
{
public:
/// Empty (invalid) constructor.
BaseTensor();
/// Constructor from a raw memory pointer.
/// @param memoryArea - Region of CPU-addressable memory where tensor data will be stored. Must be valid while
/// workloads are on the fly. Tensor instances do not claim ownership of referenced memory regions, that is,
/// no attempt will be made by ArmNN to free these memory regions automatically.
BaseTensor(const TensorInfo& info, MemoryType memoryArea);
/// Tensors are copyable.
BaseTensor(const BaseTensor& other);
/// Tensors are copyable.
BaseTensor& operator=(const BaseTensor&);
const TensorInfo& GetInfo() const { return m_Info; }
TensorInfo& GetInfo() { return m_Info; }
const TensorShape& GetShape() const { return m_Info.GetShape(); }
TensorShape& GetShape() { return m_Info.GetShape(); }
DataType GetDataType() const { return m_Info.GetDataType(); }
unsigned int GetNumDimensions() const { return m_Info.GetNumDimensions(); }
unsigned int GetNumBytes() const { return m_Info.GetNumBytes(); }
unsigned int GetNumElements() const { return m_Info.GetNumElements(); }
MemoryType GetMemoryArea() const { return m_MemoryArea; }
protected:
/// Protected destructor to stop users from making these
/// (could still new one on the heap and then leak it...)
~BaseTensor() {}
MemoryType m_MemoryArea;
private:
TensorInfo m_Info;
};
/// A tensor defined by a TensorInfo (shape and data type) and a mutable backing store.
class Tensor : public BaseTensor<void*>
{
public:
/// Brings in the constructors and assignment operator.
using BaseTensor<void*>::BaseTensor;
};
/// A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
class ConstTensor : public BaseTensor<const void*>
{
public:
/// Brings in the constructors and assignment operator.
using BaseTensor<const void*>::BaseTensor;
ConstTensor() : BaseTensor<const void*>() {} // This needs to be redefined explicitly??
/// Can be implicitly constructed from non-const Tensor.
ConstTensor(const Tensor& other) : BaseTensor<const void*>(other.GetInfo(), other.GetMemoryArea()) {}
/// Constructor from a backing container.
/// @param container - An stl-like container type which implements data() and size() methods.
/// Presence of data() and size() is a strong indicator of the continuous memory layout of the container,
/// which is a requirement for Tensor data. Tensor instances do not claim ownership of referenced memory regions,
/// that is, no attempt will be made by ArmNN to free these memory regions automatically.
template < template<typename, typename...> class ContainerType, typename T, typename...ContainerArgs >
ConstTensor(const TensorInfo& info, const ContainerType<T, ContainerArgs...>& container)
: BaseTensor<const void*>(info, container.data())
{
if (container.size() * sizeof(T) != info.GetNumBytes())
{
throw InvalidArgumentException("Container size is not correct");
}
}
};
using InputTensors = std::vector<std::pair<LayerBindingId, class ConstTensor>>;
using OutputTensors = std::vector<std::pair<LayerBindingId, class Tensor>>;
} // namespace armnn
<|endoftext|> |
<commit_before>//
// Created by manu343726 on 4/08/15.
//
#ifndef CTTI_HASH_HPP
#define CTTI_HASH_HPP
#include <functional>
#include "detail/hash.hpp"
#include "detail/pretty_function.hpp"
#include "detail/string.hpp"
#ifdef CTTI_DEBUG_ID_FUNCTIONS
#include <iostream>
#include <string>
#ifndef CTTI_CONSTEXPR_ID
#define CTTI_CONSTEXPR_ID
#endif
#else
#ifndef CTTI_CONSTEXPR_ID
#define CTTI_CONSTEXPR_ID constexpr
#endif
#endif
namespace ctti
{
struct type_id_t
{
constexpr type_id_t(const detail::string& name) :
name_{name}
{}
type_id_t& operator=(const type_id_t&) = default;
constexpr detail::hash_t hash() const
{
return name_.hash();
}
// note: name().c_str() isn't null-terminated properly!
constexpr detail::string name() const
{
return name_;
}
friend constexpr bool operator==(const type_id_t& lhs, const type_id_t& rhs)
{
return lhs.hash() == rhs.hash();
}
friend constexpr bool operator!=(const type_id_t& lhs, const type_id_t& rhs)
{
return !(lhs == rhs);
}
private:
detail::string name_;
};
struct unnamed_type_id_t
{
constexpr unnamed_type_id_t(const detail::hash_t hash) :
_hash{hash}
{}
unnamed_type_id_t& operator=(const unnamed_type_id_t&) = default;
constexpr detail::hash_t hash() const
{
return _hash;
}
friend constexpr bool operator==(const unnamed_type_id_t& lhs, const unnamed_type_id_t& rhs)
{
return lhs.hash() == rhs.hash();
}
friend constexpr bool operator!=(const unnamed_type_id_t& lhs, const unnamed_type_id_t& rhs)
{
return !(lhs == rhs);
}
private:
detail::hash_t _hash;
};
using type_index = unnamed_type_id_t; // To mimic std::type_index when using maps
template<std::size_t N>
constexpr ctti::unnamed_type_id_t id_from_name(const char (&typeName)[N])
{
return detail::sid_hash(N - 1, typeName);
}
constexpr ctti::unnamed_type_id_t id_from_name(const char* typeName, std::size_t length)
{
return detail::sid_hash(length, typeName);
}
ctti::unnamed_type_id_t id_from_name(const std::string& typeName)
{
return detail::sid_hash(typeName.size(), typeName.data());
}
namespace detail
{
template<typename T>
CTTI_CONSTEXPR_ID ctti::type_id_t type_id()
{
static_assert(CTTI_TYPE_ID_PRETTY_FUNCTION_END - CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN <= max_string_length, "CTTI_PRETTY_FUNCTION out of range");
#ifdef CTTI_DEBUG_ID_FUNCTIONS
std::string name{ CTTI_TYPE_ID_PRETTY_FUNCTION + CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_TYPE_ID_PRETTY_FUNCTION_END - CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1};
std::cout << "PRETTY_FUNCTION: " << CTTI_TYPE_ID_PRETTY_FUNCTION << std::endl;
std::cout << "Range: [" << CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN << "," << CTTI_TYPE_ID_PRETTY_FUNCTION_END << ")" << std::endl;
std::cout << "Name: " << name << std::endl;
#endif
// one-liner required by MSVC :(
return detail::make_string<CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_TYPE_ID_PRETTY_FUNCTION_END>(CTTI_TYPE_ID_PRETTY_FUNCTION);
}
template<typename T>
CTTI_CONSTEXPR_ID ctti::unnamed_type_id_t unnamed_type_id()
{
// one-liner required by MSVC :(
static_assert(CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN < CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END, "CTTI unnamed type id wrong range");
#ifdef CTTI_DEBUG_ID_FUNCTIONS
std::string name{ CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION + CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1};
std::cout << "PRETTY_FUNCTION: " << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION << std::endl;
std::cout << "Range: [" << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN << "," << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END << ")" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Name size: " << name.size() << std::endl;
std::cout << "Name size (computed from range): " << (CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1) << std::endl;
return id_from_name(name);
#else
return id_from_name(
CTTI_TYPE_ID_PRETTY_FUNCTION + CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN,
CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1
);
#endif
}
}
/**
* Returns type information at compile-time for a value
* of type T. Decay is applied to argument type first, use
* ctti::type_id<decltype(arg)>() to preserve references and cv qualifiers.
*/
template<typename T>
constexpr type_id_t type_id(T&&)
{
return detail::type_id<typename std::decay<T>::type>();
}
/**
* Returns type information at compile-time for type T.
*/
template<typename T>
constexpr type_id_t type_id()
{
return detail::type_id<T>();
}
/**
* Returns unnamed type information at compile-time for a value
* of type T. Decay is applied to argument type first, use
* ctti::type_id<decltype(arg)>() to preserve references and cv qualifiers.
*/
template<typename T>
constexpr unnamed_type_id_t unnamed_type_id(T&&)
{
return detail::unnamed_type_id<typename std::decay<T>::type>();
}
/**
* Returns unnamed type information at compile-time for type T.
*/
template<typename T>
constexpr unnamed_type_id_t unnamed_type_id()
{
return detail::unnamed_type_id<T>();
}
//assert commented out, GCC 5.2.0 ICE here.
//static_assert(type_id<void>() == type_id<void>(), "ctti::type_id_t instances must be constant expressions");
}
namespace std
{
template<>
struct hash<ctti::type_id_t>
{
constexpr std::size_t operator()(const ctti::type_id_t& id) const
{
// quiet warning about possible loss of data
return std::size_t(id.hash());
}
};
template<>
struct hash<ctti::unnamed_type_id_t>
{
constexpr std::size_t operator()(const ctti::unnamed_type_id_t& id) const
{
// quiet warning about possible loss of data
return std::size_t(id.hash());
}
};
}
#endif //CTTI_HASH_HPP
<commit_msg>Fix ODR violation with the only no inline function of the library...<commit_after>//
// Created by manu343726 on 4/08/15.
//
#ifndef CTTI_HASH_HPP
#define CTTI_HASH_HPP
#include <functional>
#include "detail/hash.hpp"
#include "detail/pretty_function.hpp"
#include "detail/string.hpp"
#ifdef CTTI_DEBUG_ID_FUNCTIONS
#include <iostream>
#include <string>
#ifndef CTTI_CONSTEXPR_ID
#define CTTI_CONSTEXPR_ID
#endif
#else
#ifndef CTTI_CONSTEXPR_ID
#define CTTI_CONSTEXPR_ID constexpr
#endif
#endif
namespace ctti
{
struct type_id_t
{
constexpr type_id_t(const detail::string& name) :
name_{name}
{}
type_id_t& operator=(const type_id_t&) = default;
constexpr detail::hash_t hash() const
{
return name_.hash();
}
// note: name().c_str() isn't null-terminated properly!
constexpr detail::string name() const
{
return name_;
}
friend constexpr bool operator==(const type_id_t& lhs, const type_id_t& rhs)
{
return lhs.hash() == rhs.hash();
}
friend constexpr bool operator!=(const type_id_t& lhs, const type_id_t& rhs)
{
return !(lhs == rhs);
}
private:
detail::string name_;
};
struct unnamed_type_id_t
{
constexpr unnamed_type_id_t(const detail::hash_t hash) :
_hash{hash}
{}
unnamed_type_id_t& operator=(const unnamed_type_id_t&) = default;
constexpr detail::hash_t hash() const
{
return _hash;
}
friend constexpr bool operator==(const unnamed_type_id_t& lhs, const unnamed_type_id_t& rhs)
{
return lhs.hash() == rhs.hash();
}
friend constexpr bool operator!=(const unnamed_type_id_t& lhs, const unnamed_type_id_t& rhs)
{
return !(lhs == rhs);
}
private:
detail::hash_t _hash;
};
using type_index = unnamed_type_id_t; // To mimic std::type_index when using maps
template<std::size_t N>
constexpr ctti::unnamed_type_id_t id_from_name(const char (&typeName)[N])
{
return detail::sid_hash(N - 1, typeName);
}
constexpr ctti::unnamed_type_id_t id_from_name(const char* typeName, std::size_t length)
{
return detail::sid_hash(length, typeName);
}
// Inline to prevent ODR violation
inline ctti::unnamed_type_id_t id_from_name(const std::string& typeName)
{
return detail::sid_hash(typeName.size(), typeName.data());
}
namespace detail
{
template<typename T>
CTTI_CONSTEXPR_ID ctti::type_id_t type_id()
{
static_assert(CTTI_TYPE_ID_PRETTY_FUNCTION_END - CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN <= max_string_length, "CTTI_PRETTY_FUNCTION out of range");
#ifdef CTTI_DEBUG_ID_FUNCTIONS
std::string name{ CTTI_TYPE_ID_PRETTY_FUNCTION + CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_TYPE_ID_PRETTY_FUNCTION_END - CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1};
std::cout << "PRETTY_FUNCTION: " << CTTI_TYPE_ID_PRETTY_FUNCTION << std::endl;
std::cout << "Range: [" << CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN << "," << CTTI_TYPE_ID_PRETTY_FUNCTION_END << ")" << std::endl;
std::cout << "Name: " << name << std::endl;
#endif
// one-liner required by MSVC :(
return detail::make_string<CTTI_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_TYPE_ID_PRETTY_FUNCTION_END>(CTTI_TYPE_ID_PRETTY_FUNCTION);
}
template<typename T>
CTTI_CONSTEXPR_ID ctti::unnamed_type_id_t unnamed_type_id()
{
// one-liner required by MSVC :(
static_assert(CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN < CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END, "CTTI unnamed type id wrong range");
#ifdef CTTI_DEBUG_ID_FUNCTIONS
std::string name{ CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION + CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN, CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1};
std::cout << "PRETTY_FUNCTION: " << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION << std::endl;
std::cout << "Range: [" << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN << "," << CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END << ")" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Name size: " << name.size() << std::endl;
std::cout << "Name size (computed from range): " << (CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1) << std::endl;
return id_from_name(name);
#else
return id_from_name(
CTTI_TYPE_ID_PRETTY_FUNCTION + CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN,
CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_END - CTTI_UNNAMED_TYPE_ID_PRETTY_FUNCTION_BEGIN - 1
);
#endif
}
}
/**
* Returns type information at compile-time for a value
* of type T. Decay is applied to argument type first, use
* ctti::type_id<decltype(arg)>() to preserve references and cv qualifiers.
*/
template<typename T>
constexpr type_id_t type_id(T&&)
{
return detail::type_id<typename std::decay<T>::type>();
}
/**
* Returns type information at compile-time for type T.
*/
template<typename T>
constexpr type_id_t type_id()
{
return detail::type_id<T>();
}
/**
* Returns unnamed type information at compile-time for a value
* of type T. Decay is applied to argument type first, use
* ctti::type_id<decltype(arg)>() to preserve references and cv qualifiers.
*/
template<typename T>
constexpr unnamed_type_id_t unnamed_type_id(T&&)
{
return detail::unnamed_type_id<typename std::decay<T>::type>();
}
/**
* Returns unnamed type information at compile-time for type T.
*/
template<typename T>
constexpr unnamed_type_id_t unnamed_type_id()
{
return detail::unnamed_type_id<T>();
}
//assert commented out, GCC 5.2.0 ICE here.
//static_assert(type_id<void>() == type_id<void>(), "ctti::type_id_t instances must be constant expressions");
}
namespace std
{
template<>
struct hash<ctti::type_id_t>
{
constexpr std::size_t operator()(const ctti::type_id_t& id) const
{
// quiet warning about possible loss of data
return std::size_t(id.hash());
}
};
template<>
struct hash<ctti::unnamed_type_id_t>
{
constexpr std::size_t operator()(const ctti::unnamed_type_id_t& id) const
{
// quiet warning about possible loss of data
return std::size_t(id.hash());
}
};
}
#endif //CTTI_HASH_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <sstream>
#include <utility>
#include <memory>
#include <cstddef>
// Macro for verifying expressions at run-time. Calls assert() with 'expr'.
// Allows turning assertions off, even if -DNDEBUG wasn't given at
// compile-time. This macro does nothing unless EWS_ENABLE_ASSERTS was defined
// during compilation.
#define EWS_ASSERT(expr) ((void)0)
#ifndef NDEBUG
# ifdef EWS_ENABLE_ASSERTS
# include <cassert>
# undef EWS_ASSERT
# define EWS_ASSERT(expr) assert(expr)
# endif
#endif // !NDEBUG
// Visual Studio 12 does not support noexcept specifier.
#ifndef _MSC_VER
# define EWS_NOEXCEPT noexcept
#else
# define EWS_NOEXCEPT
#endif
namespace ews
{
// Wrapper around curl.h header file. Wraps everything in that header file
// with C++ namespace ews::curl; also defines exception for cURL related
// runtime errors and some RAII classes.
namespace curl
{
#include <curl/curl.h>
class curl_error final : public std::runtime_error
{
public:
explicit curl_error(const std::string& what)
: std::runtime_error(what)
{
}
explicit curl_error(const char* what) : std::runtime_error(what) {}
};
// Helper function; constructs an exception with a meaningful error
// message from the given result code for the most recent cURL API call.
//
// msg: A string that prepends the actual cURL error message.
// rescode: The result code of a failed cURL operation.
inline curl_error make_error(const std::string& msg, CURLcode rescode)
{
std::string reason{curl_easy_strerror(rescode)};
return curl_error(msg + ": \'" + reason + "\'");
}
// RAII helper class for CURL* handles.
class curl_ptr final
{
public:
curl_ptr() : handle_{curl_easy_init()}
{
if (!handle_)
{
throw curl_error{"Could not start libcurl session"};
}
}
~curl_ptr() { curl_easy_cleanup(handle_); }
// Could use curl_easy_duphandle for copying
curl_ptr(const curl_ptr&) = delete;
curl_ptr& operator=(const curl_ptr&) = delete;
CURL* get() const EWS_NOEXCEPT { return handle_; }
private:
CURL* handle_;
};
// RAII wrapper class around cURLs slist construct.
class curl_string_list final
{
public:
curl_string_list() EWS_NOEXCEPT : slist_{nullptr} {}
~curl_string_list() { curl_slist_free_all(slist_); }
void append(const char* str) EWS_NOEXCEPT
{
slist_ = curl_slist_append(slist_, str);
}
curl_slist* get() const EWS_NOEXCEPT { return slist_; }
private:
curl_slist* slist_;
};
} // curl
namespace plumbing
{
class http_web_request;
// This ought to be a DOM wrapper; usually around a web response
class xml_document final
{
};
class credentials
{
public:
virtual ~credentials() = default;
virtual void certify(http_web_request*) const = 0;
};
class ntlm_credentials : public credentials
{
public:
ntlm_credentials(std::string username, std::string password,
std::string domain)
: username_(std::move(username)),
password_(std::move(password)),
domain_(std::move(domain))
{
}
private:
void certify(http_web_request*) const override; // implemented below
std::string username_;
std::string password_;
std::string domain_;
};
class http_web_request final
{
public:
enum class method
{
POST
};
// Create a new HTTP request to the given URL.
explicit http_web_request(const std::string& url)
{
set_option(curl::CURLOPT_URL, url.c_str());
}
// Set the HTTP method (only POST supported).
void set_method(method)
{
// Method can only be a regular POST in our use case
set_option(curl::CURLOPT_POST, 1);
}
// Set this HTTP request's content type.
void set_content_type(const std::string& content_type)
{
const std::string str = "Content-Type: " + content_type;
headers_.append(str.c_str());
}
// Set credentials for authentication.
void set_credentials(const credentials& creds)
{
creds.certify(this);
}
// Small wrapper around curl_easy_setopt(3).
//
// Converts return codes to exceptions of type curl_error and allows
// objects other than http_web_requests to set transfer options
// without direct access to the internal CURL handle.
template <typename... Args>
void set_option(curl::CURLoption option, Args... args)
{
auto retcode = curl::curl_easy_setopt(
handle_.get(), option, std::forward<Args>(args)...);
switch (retcode)
{
case curl::CURLE_OK:
return;
case curl::CURLE_FAILED_INIT:
{
throw curl::make_error(
"curl_easy_setopt: unsupported option", retcode);
}
default:
{
throw curl::make_error(
"curl_easy_setopt: failed setting option", retcode);
}
};
}
// Perform the HTTP request.
//
// request: The complete request string; you must make sure that the
// data is encoded the way you want the server to receive it.
// response_handler: A callable function or function pointer that
// takes a std::string (the response) object as only argument. The
// function is invoked as soon as a response is received.
//
// Throws curl_error if operation could not be completed.
template <typename Function>
void send(const std::string& request, Function response_handler)
{
#ifndef NDEBUG
// Print HTTP headers to stderr
set_option(curl::CURLOPT_VERBOSE, 1L);
#endif
// Some servers don't like requests that are made without a
// user-agent field, so we provide one
set_option(curl::CURLOPT_USERAGENT, "libcurl-agent/1.0");
// Set complete request string for HTTP POST method; note: no
// encoding here
set_option(curl::CURLOPT_POSTFIELDS, request.c_str());
set_option(curl::CURLOPT_POSTFIELDSIZE, request.length());
set_option(curl::CURLOPT_HTTPHEADER, headers_.get());
// Set response handler; wrap passed handler function in
// something that we can cast to a void* (we cannot cast
// function pointers to void*) to make sure this works with
// lambdas, std::function instances, function pointers, and
// functors
struct wrapper
{
Function callable;
explicit wrapper(Function function) : callable(function) {}
};
wrapper wrp{response_handler};
auto callback =
[](char* ptr, std::size_t size, std::size_t nmemb,
void* userdata) -> std::size_t
{
// Call user supplied response handler with a std::string
// (contains the complete response). Always indicate
// success; user has no chance of indicating an error to the
// cURL library.
wrapper* w = reinterpret_cast<wrapper*>(userdata);
const auto count = size * nmemb;
std::string response{ptr, count};
w->callable(std::move(response));
return count;
};
set_option(
curl::CURLOPT_WRITEFUNCTION,
static_cast<std::size_t (*)(char*, std::size_t, std::size_t,
void*)>(callback));
set_option(curl::CURLOPT_WRITEDATA, std::addressof(wrp));
#ifndef NDEBUG
// Turn-off verification of the server's authenticity
set_option(curl::CURLOPT_SSL_VERIFYPEER, 0);
#endif
auto retcode = curl::curl_easy_perform(handle_.get());
if (retcode != 0)
{
throw curl::make_error("curl_easy_perform", retcode);
}
}
private:
curl::curl_ptr handle_;
curl::curl_string_list headers_;
};
// Makes a raw SOAP request.
//
// url: The URL of the server to talk to.
// username: The username of user.
// password: The user's secret password, plain-text.
// domain: The user's Windows domain.
// soap_body: The contents of the SOAP body (minus the body element);
// this is the actual EWS request.
// soap_headers: Any SOAP headers to add.
//
// Returns a DOM wrapper around the response.
inline xml_document make_raw_soap_request(
const std::string& url, const std::string& username,
const std::string& password, const std::string& domain,
const std::string& soap_body,
const std::vector<std::string>& soap_headers)
{
http_web_request request{url};
request.set_method(http_web_request::method::POST);
request.set_content_type("text/xml; charset=UTF-8");
ntlm_credentials creds{username, password, domain};
request.set_credentials(creds);
std::stringstream request_stream;
request_stream << R"(
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
>
)";
// Add SOAP headers if present
if (!soap_headers.empty())
{
request_stream << "<soap:Header>\n";
for (const auto& header : soap_headers)
{
request_stream << header;
}
request_stream << "</soap:Header>\n";
}
request_stream << "<soap:Body>\n";
// Add the passed request
request_stream << soap_body;
request_stream << "</soap:Body>\n";
request_stream << "</soap:Envelope>\n";
xml_document doc;
request.send(request_stream.str(), [&doc](std::string response)
{
// TODO: load XML from response into doc
// Note: response is a copy and can therefore be moved
(void)response;
});
return doc;
}
// Implementations
void ntlm_credentials::certify(http_web_request* request) const
{
EWS_ASSERT(request != nullptr);
// CURLOPT_USERPWD: domain\username:password
std::string login = domain_ + "\\" + username_ + ":" + password_;
request->set_option(curl::CURLOPT_USERPWD, login.c_str());
request->set_option(curl::CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
}
}
}
<commit_msg>Request shouldn't start with a CRLF :-)<commit_after>#pragma once
#include <stdexcept>
#include <string>
#include <vector>
#include <sstream>
#include <utility>
#include <memory>
#include <cstddef>
// Macro for verifying expressions at run-time. Calls assert() with 'expr'.
// Allows turning assertions off, even if -DNDEBUG wasn't given at
// compile-time. This macro does nothing unless EWS_ENABLE_ASSERTS was defined
// during compilation.
#define EWS_ASSERT(expr) ((void)0)
#ifndef NDEBUG
# ifdef EWS_ENABLE_ASSERTS
# include <cassert>
# undef EWS_ASSERT
# define EWS_ASSERT(expr) assert(expr)
# endif
#endif // !NDEBUG
// Visual Studio 12 does not support noexcept specifier.
#ifndef _MSC_VER
# define EWS_NOEXCEPT noexcept
#else
# define EWS_NOEXCEPT
#endif
namespace ews
{
// Wrapper around curl.h header file. Wraps everything in that header file
// with C++ namespace ews::curl; also defines exception for cURL related
// runtime errors and some RAII classes.
namespace curl
{
#include <curl/curl.h>
class curl_error final : public std::runtime_error
{
public:
explicit curl_error(const std::string& what)
: std::runtime_error(what)
{
}
explicit curl_error(const char* what) : std::runtime_error(what) {}
};
// Helper function; constructs an exception with a meaningful error
// message from the given result code for the most recent cURL API call.
//
// msg: A string that prepends the actual cURL error message.
// rescode: The result code of a failed cURL operation.
inline curl_error make_error(const std::string& msg, CURLcode rescode)
{
std::string reason{curl_easy_strerror(rescode)};
return curl_error(msg + ": \'" + reason + "\'");
}
// RAII helper class for CURL* handles.
class curl_ptr final
{
public:
curl_ptr() : handle_{curl_easy_init()}
{
if (!handle_)
{
throw curl_error{"Could not start libcurl session"};
}
}
~curl_ptr() { curl_easy_cleanup(handle_); }
// Could use curl_easy_duphandle for copying
curl_ptr(const curl_ptr&) = delete;
curl_ptr& operator=(const curl_ptr&) = delete;
CURL* get() const EWS_NOEXCEPT { return handle_; }
private:
CURL* handle_;
};
// RAII wrapper class around cURLs slist construct.
class curl_string_list final
{
public:
curl_string_list() EWS_NOEXCEPT : slist_{nullptr} {}
~curl_string_list() { curl_slist_free_all(slist_); }
void append(const char* str) EWS_NOEXCEPT
{
slist_ = curl_slist_append(slist_, str);
}
curl_slist* get() const EWS_NOEXCEPT { return slist_; }
private:
curl_slist* slist_;
};
} // curl
namespace plumbing
{
class http_web_request;
// This ought to be a DOM wrapper; usually around a web response
class xml_document final
{
};
class credentials
{
public:
virtual ~credentials() = default;
virtual void certify(http_web_request*) const = 0;
};
class ntlm_credentials : public credentials
{
public:
ntlm_credentials(std::string username, std::string password,
std::string domain)
: username_(std::move(username)),
password_(std::move(password)),
domain_(std::move(domain))
{
}
private:
void certify(http_web_request*) const override; // implemented below
std::string username_;
std::string password_;
std::string domain_;
};
class http_web_request final
{
public:
enum class method
{
POST
};
// Create a new HTTP request to the given URL.
explicit http_web_request(const std::string& url)
{
set_option(curl::CURLOPT_URL, url.c_str());
}
// Set the HTTP method (only POST supported).
void set_method(method)
{
// Method can only be a regular POST in our use case
set_option(curl::CURLOPT_POST, 1);
}
// Set this HTTP request's content type.
void set_content_type(const std::string& content_type)
{
const std::string str = "Content-Type: " + content_type;
headers_.append(str.c_str());
}
// Set credentials for authentication.
void set_credentials(const credentials& creds)
{
creds.certify(this);
}
// Small wrapper around curl_easy_setopt(3).
//
// Converts return codes to exceptions of type curl_error and allows
// objects other than http_web_requests to set transfer options
// without direct access to the internal CURL handle.
template <typename... Args>
void set_option(curl::CURLoption option, Args... args)
{
auto retcode = curl::curl_easy_setopt(
handle_.get(), option, std::forward<Args>(args)...);
switch (retcode)
{
case curl::CURLE_OK:
return;
case curl::CURLE_FAILED_INIT:
{
throw curl::make_error(
"curl_easy_setopt: unsupported option", retcode);
}
default:
{
throw curl::make_error(
"curl_easy_setopt: failed setting option", retcode);
}
};
}
// Perform the HTTP request.
//
// request: The complete request string; you must make sure that the
// data is encoded the way you want the server to receive it.
// response_handler: A callable function or function pointer that
// takes a std::string (the response) object as only argument. The
// function is invoked as soon as a response is received.
//
// Throws curl_error if operation could not be completed.
template <typename Function>
void send(const std::string& request, Function response_handler)
{
#ifndef NDEBUG
// Print HTTP headers to stderr
set_option(curl::CURLOPT_VERBOSE, 1L);
#endif
// Some servers don't like requests that are made without a
// user-agent field, so we provide one
set_option(curl::CURLOPT_USERAGENT, "libcurl-agent/1.0");
// Set complete request string for HTTP POST method; note: no
// encoding here
set_option(curl::CURLOPT_POSTFIELDS, request.c_str());
set_option(curl::CURLOPT_POSTFIELDSIZE, request.length());
set_option(curl::CURLOPT_HTTPHEADER, headers_.get());
// Set response handler; wrap passed handler function in
// something that we can cast to a void* (we cannot cast
// function pointers to void*) to make sure this works with
// lambdas, std::function instances, function pointers, and
// functors
struct wrapper
{
Function callable;
explicit wrapper(Function function) : callable(function) {}
};
wrapper wrp{response_handler};
auto callback =
[](char* ptr, std::size_t size, std::size_t nmemb,
void* userdata) -> std::size_t
{
// Call user supplied response handler with a std::string
// (contains the complete response). Always indicate
// success; user has no chance of indicating an error to the
// cURL library.
wrapper* w = reinterpret_cast<wrapper*>(userdata);
const auto count = size * nmemb;
std::string response{ptr, count};
w->callable(std::move(response));
return count;
};
set_option(
curl::CURLOPT_WRITEFUNCTION,
static_cast<std::size_t (*)(char*, std::size_t, std::size_t,
void*)>(callback));
set_option(curl::CURLOPT_WRITEDATA, std::addressof(wrp));
#ifndef NDEBUG
// Turn-off verification of the server's authenticity
set_option(curl::CURLOPT_SSL_VERIFYPEER, 0);
#endif
auto retcode = curl::curl_easy_perform(handle_.get());
if (retcode != 0)
{
throw curl::make_error("curl_easy_perform", retcode);
}
}
private:
curl::curl_ptr handle_;
curl::curl_string_list headers_;
};
// Makes a raw SOAP request.
//
// url: The URL of the server to talk to.
// username: The username of user.
// password: The user's secret password, plain-text.
// domain: The user's Windows domain.
// soap_body: The contents of the SOAP body (minus the body element);
// this is the actual EWS request.
// soap_headers: Any SOAP headers to add.
//
// Returns a DOM wrapper around the response.
inline xml_document make_raw_soap_request(
const std::string& url, const std::string& username,
const std::string& password, const std::string& domain,
const std::string& soap_body,
const std::vector<std::string>& soap_headers)
{
http_web_request request{url};
request.set_method(http_web_request::method::POST);
request.set_content_type("text/xml; charset=utf-8");
ntlm_credentials creds{username, password, domain};
request.set_credentials(creds);
std::stringstream request_stream;
request_stream <<
R"(<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
>)";
// Add SOAP headers if present
if (!soap_headers.empty())
{
request_stream << "<soap:Header>\n";
for (const auto& header : soap_headers)
{
request_stream << header;
}
request_stream << "</soap:Header>\n";
}
request_stream << "<soap:Body>\n";
// Add the passed request
request_stream << soap_body;
request_stream << "</soap:Body>\n";
request_stream << "</soap:Envelope>\n";
xml_document doc;
request.send(request_stream.str(), [&doc](std::string response)
{
// TODO: load XML from response into doc
// Note: response is a copy and can therefore be moved
(void)response;
});
return doc;
}
// Implementations
void ntlm_credentials::certify(http_web_request* request) const
{
EWS_ASSERT(request != nullptr);
// CURLOPT_USERPWD: domain\username:password
std::string login = domain_ + "\\" + username_ + ":" + password_;
request->set_option(curl::CURLOPT_USERPWD, login.c_str());
request->set_option(curl::CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
}
}
}
<|endoftext|> |
<commit_before>#ifndef INC_METTLE_SUITE_HPP
#define INC_METTLE_SUITE_HPP
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace mettle {
namespace detail {
template<size_t ...>
struct index_sequence {};
template<size_t N, size_t ...S>
struct make_index_seq_impl : make_index_seq_impl<N-1, N-1, S...> { };
template<size_t ...S>
struct make_index_seq_impl<0, S...> {
typedef index_sequence<S...> type;
};
template<size_t I>
using make_index_sequence = typename make_index_seq_impl<I>::type;
template <typename F, typename Tuple, size_t... I>
auto apply_impl(F &&f, Tuple &&t, index_sequence<I...>) {
return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}
template<typename F, typename Tuple>
auto apply(F &&f, Tuple &&t) {
using Indices = make_index_sequence<
std::tuple_size<typename std::decay<Tuple>::type>::value
>;
return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());
}
template<typename F, typename Tuple>
void run_test(F &&setup, F &&teardown, F&&test, Tuple &fixtures) {
if(setup)
detail::apply(std::forward<F>(setup), fixtures);
try {
detail::apply(std::forward<F>(test), fixtures);
}
catch(...) {
if(teardown)
detail::apply(std::forward<F>(teardown), fixtures);
throw;
}
if(teardown)
detail::apply(std::forward<F>(teardown), fixtures);
}
}
struct test_result {
bool passed;
std::string message;
};
template<typename Ret, typename ...T>
struct compiled_suite {
struct test_info {
using function_type = std::function<Ret(T&...)>;
test_info(const std::string &name, const function_type &function,
bool skip = false)
: name(name), function(function), skip(skip) {}
std::string name;
function_type function;
bool skip;
};
using iterator = typename std::vector<test_info>::const_iterator;
template<typename U, typename V, typename Func>
compiled_suite(const std::string &name, const U &tests, const V &subsuites,
const Func &f) : name_(name) {
for(auto &test : tests)
tests_.push_back(f(test));
for(auto &ss : subsuites)
subsuites_.push_back(compiled_suite(ss, f));
}
template<typename Ret2, typename ...T2, typename Func>
compiled_suite(const compiled_suite<Ret2, T2...> &suite, const Func &f)
: name_(suite.name()) {
for(auto &test : suite)
tests_.push_back(f(test));
for(auto &ss : suite.subsuites())
subsuites_.push_back(compiled_suite(ss, f));
}
const std::string & name() const {
return name_;
}
iterator begin() const {
return tests_.begin();
}
iterator end() const {
return tests_.end();
}
size_t size() const {
return tests_.size();
}
const std::vector<compiled_suite> & subsuites() const {
return subsuites_;
}
private:
std::string name_;
std::vector<test_info> tests_;
std::vector<compiled_suite> subsuites_;
};
using runnable_suite = compiled_suite<test_result>;
template<typename Parent, typename ...T>
class subsuite_builder;
template<typename ...T>
class suite_builder_base {
public:
using raw_function_type = void(T&...);
using function_type = std::function<raw_function_type>;
using tuple_type = std::tuple<T...>;
suite_builder_base(const std::string &name) : name_(name) {}
suite_builder_base(const suite_builder_base &) = delete;
suite_builder_base & operator =(const suite_builder_base &) = delete;
void setup(const function_type &f) {
setup_ = f;
}
void teardown(const function_type &f) {
teardown_ = f;
}
void skip_test(const std::string &name, const function_type &f) {
tests_.push_back({name, f, true});
}
void test(const std::string &name, const function_type &f) {
tests_.push_back({name, f, false});
}
void subsuite(const compiled_suite<void, T...> &subsuite) {
subsuites_.push_back(subsuite);
}
void subsuite(compiled_suite<void, T...> &&subsuite) {
subsuites_.push_back(std::move(subsuite));
}
template<typename ...U, typename F>
void subsuite(const std::string &name, const F &f) {
subsuite_builder<tuple_type, U...> builder(name);
f(builder);
subsuite(builder.finalize());
}
protected:
struct test_info {
std::string name;
function_type function;
bool skip;
};
std::string name_;
function_type setup_, teardown_;
std::vector<test_info> tests_;
std::vector<compiled_suite<void, T...>> subsuites_;
};
template<typename ...T, typename ...U>
class subsuite_builder<std::tuple<T...>, U...>
: public suite_builder_base<T..., U...> {
private:
using compiled_suite_type = compiled_suite<void, T...>;
using base = suite_builder_base<T..., U...>;
public:
using base::base;
compiled_suite_type finalize() const {
return compiled_suite_type(
base::name_, base::tests_, base::subsuites_,
[this](const auto &a) { return wrap_test(a); }
);
}
private:
template<typename V>
typename compiled_suite_type::test_info wrap_test(const V &test) const {
auto &setup = base::setup_;
auto &teardown = base::teardown_;
auto &f = test.function;
typename compiled_suite_type::test_info::function_type test_function = [
setup, teardown, f
](T &...args) -> void {
std::tuple<T&..., U...> fixtures(args..., U()...);
detail::run_test(setup, teardown, f, fixtures);
};
return { test.name, test_function, test.skip };
}
};
template<typename Exception, typename ...T>
class suite_builder : public suite_builder_base<T...> {
private:
using base = suite_builder_base<T...>;
public:
using exception_type = Exception;
using base::base;
runnable_suite finalize() const {
return runnable_suite(
base::name_, base::tests_, base::subsuites_,
[this](const auto &a) { return wrap_test(a); }
);
}
private:
template<typename U>
runnable_suite::test_info wrap_test(const U &test) const {
auto &setup = base::setup_;
auto &teardown = base::teardown_;
auto &f = test.function;
runnable_suite::test_info::function_type test_function = [
setup, teardown, f
]() -> test_result {
bool passed = false;
std::string message;
try {
std::tuple<T...> fixtures;
detail::run_test(setup, teardown, f, fixtures);
passed = true;
}
catch(const exception_type &e) {
message = e.what();
}
catch(const std::exception &e) {
message = std::string("Uncaught exception: ") + e.what();
}
catch(...) {
message = "Unknown exception";
}
return { passed, message };
};
return { test.name, test_function, test.skip };
}
};
template<typename Exception, typename ...T, typename F>
runnable_suite make_basic_suite(const std::string &name, const F &f) {
suite_builder<Exception, T...> builder(name);
f(builder);
return builder.finalize();
}
template<typename T, typename ...U, typename F>
auto make_subsuite(const std::string &name, const F &f) {
subsuite_builder<T, U...> builder(name);
f(builder);
return builder.finalize();
}
template<typename ...T, typename Parent, typename F>
auto make_subsuite(const Parent &, const std::string &name, const F &f) {
return make_subsuite<typename Parent::tuple_type, T...>(name, f);
}
template<typename ...T, typename Parent, typename F>
void subsuite(Parent &builder, const std::string &name, const F &f) {
builder.subsuite(make_subsuite<T...>(builder, name, f));
}
} // namespace mettle
#endif
<commit_msg>Use std::make_index_sequence instead of our homegrown version<commit_after>#ifndef INC_METTLE_SUITE_HPP
#define INC_METTLE_SUITE_HPP
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace mettle {
namespace detail {
template <typename F, typename Tuple, size_t... I>
auto apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {
return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}
template<typename F, typename Tuple>
auto apply(F &&f, Tuple &&t) {
using Indices = std::make_index_sequence<
std::tuple_size<typename std::decay<Tuple>::type>::value
>;
return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());
}
template<typename F, typename Tuple>
void run_test(F &&setup, F &&teardown, F&&test, Tuple &fixtures) {
if(setup)
detail::apply(std::forward<F>(setup), fixtures);
try {
detail::apply(std::forward<F>(test), fixtures);
}
catch(...) {
if(teardown)
detail::apply(std::forward<F>(teardown), fixtures);
throw;
}
if(teardown)
detail::apply(std::forward<F>(teardown), fixtures);
}
}
struct test_result {
bool passed;
std::string message;
};
template<typename Ret, typename ...T>
struct compiled_suite {
struct test_info {
using function_type = std::function<Ret(T&...)>;
test_info(const std::string &name, const function_type &function,
bool skip = false)
: name(name), function(function), skip(skip) {}
std::string name;
function_type function;
bool skip;
};
using iterator = typename std::vector<test_info>::const_iterator;
template<typename U, typename V, typename Func>
compiled_suite(const std::string &name, const U &tests, const V &subsuites,
const Func &f) : name_(name) {
for(auto &test : tests)
tests_.push_back(f(test));
for(auto &ss : subsuites)
subsuites_.push_back(compiled_suite(ss, f));
}
template<typename Ret2, typename ...T2, typename Func>
compiled_suite(const compiled_suite<Ret2, T2...> &suite, const Func &f)
: name_(suite.name()) {
for(auto &test : suite)
tests_.push_back(f(test));
for(auto &ss : suite.subsuites())
subsuites_.push_back(compiled_suite(ss, f));
}
const std::string & name() const {
return name_;
}
iterator begin() const {
return tests_.begin();
}
iterator end() const {
return tests_.end();
}
size_t size() const {
return tests_.size();
}
const std::vector<compiled_suite> & subsuites() const {
return subsuites_;
}
private:
std::string name_;
std::vector<test_info> tests_;
std::vector<compiled_suite> subsuites_;
};
using runnable_suite = compiled_suite<test_result>;
template<typename Parent, typename ...T>
class subsuite_builder;
template<typename ...T>
class suite_builder_base {
public:
using raw_function_type = void(T&...);
using function_type = std::function<raw_function_type>;
using tuple_type = std::tuple<T...>;
suite_builder_base(const std::string &name) : name_(name) {}
suite_builder_base(const suite_builder_base &) = delete;
suite_builder_base & operator =(const suite_builder_base &) = delete;
void setup(const function_type &f) {
setup_ = f;
}
void teardown(const function_type &f) {
teardown_ = f;
}
void skip_test(const std::string &name, const function_type &f) {
tests_.push_back({name, f, true});
}
void test(const std::string &name, const function_type &f) {
tests_.push_back({name, f, false});
}
void subsuite(const compiled_suite<void, T...> &subsuite) {
subsuites_.push_back(subsuite);
}
void subsuite(compiled_suite<void, T...> &&subsuite) {
subsuites_.push_back(std::move(subsuite));
}
template<typename ...U, typename F>
void subsuite(const std::string &name, const F &f) {
subsuite_builder<tuple_type, U...> builder(name);
f(builder);
subsuite(builder.finalize());
}
protected:
struct test_info {
std::string name;
function_type function;
bool skip;
};
std::string name_;
function_type setup_, teardown_;
std::vector<test_info> tests_;
std::vector<compiled_suite<void, T...>> subsuites_;
};
template<typename ...T, typename ...U>
class subsuite_builder<std::tuple<T...>, U...>
: public suite_builder_base<T..., U...> {
private:
using compiled_suite_type = compiled_suite<void, T...>;
using base = suite_builder_base<T..., U...>;
public:
using base::base;
compiled_suite_type finalize() const {
return compiled_suite_type(
base::name_, base::tests_, base::subsuites_,
[this](const auto &a) { return wrap_test(a); }
);
}
private:
template<typename V>
typename compiled_suite_type::test_info wrap_test(const V &test) const {
auto &setup = base::setup_;
auto &teardown = base::teardown_;
auto &f = test.function;
typename compiled_suite_type::test_info::function_type test_function = [
setup, teardown, f
](T &...args) -> void {
std::tuple<T&..., U...> fixtures(args..., U()...);
detail::run_test(setup, teardown, f, fixtures);
};
return { test.name, test_function, test.skip };
}
};
template<typename Exception, typename ...T>
class suite_builder : public suite_builder_base<T...> {
private:
using base = suite_builder_base<T...>;
public:
using exception_type = Exception;
using base::base;
runnable_suite finalize() const {
return runnable_suite(
base::name_, base::tests_, base::subsuites_,
[this](const auto &a) { return wrap_test(a); }
);
}
private:
template<typename U>
runnable_suite::test_info wrap_test(const U &test) const {
auto &setup = base::setup_;
auto &teardown = base::teardown_;
auto &f = test.function;
runnable_suite::test_info::function_type test_function = [
setup, teardown, f
]() -> test_result {
bool passed = false;
std::string message;
try {
std::tuple<T...> fixtures;
detail::run_test(setup, teardown, f, fixtures);
passed = true;
}
catch(const exception_type &e) {
message = e.what();
}
catch(const std::exception &e) {
message = std::string("Uncaught exception: ") + e.what();
}
catch(...) {
message = "Unknown exception";
}
return { passed, message };
};
return { test.name, test_function, test.skip };
}
};
template<typename Exception, typename ...T, typename F>
runnable_suite make_basic_suite(const std::string &name, const F &f) {
suite_builder<Exception, T...> builder(name);
f(builder);
return builder.finalize();
}
template<typename T, typename ...U, typename F>
auto make_subsuite(const std::string &name, const F &f) {
subsuite_builder<T, U...> builder(name);
f(builder);
return builder.finalize();
}
template<typename ...T, typename Parent, typename F>
auto make_subsuite(const Parent &, const std::string &name, const F &f) {
return make_subsuite<typename Parent::tuple_type, T...>(name, f);
}
template<typename ...T, typename Parent, typename F>
void subsuite(Parent &builder, const std::string &name, const F &f) {
builder.subsuite(make_subsuite<T...>(builder, name, f));
}
} // namespace mettle
#endif
<|endoftext|> |
<commit_before>// Copyright © 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#ifndef NIX_DATATYPE_H
#define NIX_DATATYPE_H
#include <cstdint>
#include <ostream>
#include <nix/Platform.hpp>
namespace nix {
NIXAPI enum class DataType {
Bool,
Char,
Float,
Double,
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
String,
Date,
DateTime,
Nothing = -1
};
template<typename T>
struct to_data_type {
static const bool is_valid = false;
};
template<>
struct to_data_type<bool> {
static const bool is_valid = true;
static const DataType value = DataType::Bool;
};
template<>
struct to_data_type<char> {
static const bool is_valid = true;
static const DataType value = DataType::Char;
};
template<>
struct to_data_type<float> {
static const bool is_valid = true;
static const DataType value = DataType::Float;
};
template<>
struct to_data_type<double> {
static const bool is_valid = true;
static const DataType value = DataType::Double;
};
template<>
struct to_data_type<int8_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int8;
};
template<>
struct to_data_type<uint8_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt8;
};
template<>
struct to_data_type<int16_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int16;
};
template<>
struct to_data_type<uint16_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt16;
};
template<>
struct to_data_type<int32_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int32;
};
template<>
struct to_data_type<uint32_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt32;
};
template<>
struct to_data_type<int64_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int64;
};
template<>
struct to_data_type<uint64_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt64;
};
template<>
struct to_data_type<std::string> {
static const bool is_valid = true;
static const DataType value = DataType::String;
};
NIXAPI size_t data_type_to_size(DataType dtype);
NIXAPI std::string data_type_to_string(DataType dtype);
NIXAPI std::ostream& operator<<(std::ostream &out, const DataType dtype);
} // nix::
#endif
<commit_msg>Documentation: doc added for DataType<commit_after>// Copyright © 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#ifndef NIX_DATATYPE_H
#define NIX_DATATYPE_H
#include <cstdint>
#include <ostream>
#include <nix/Platform.hpp>
namespace nix {
/**
* @brief Enumeration providing constants for all valid data types.
*
* Those data types are used by {@link nix::DataArray} and {@link nix::Property}
* in order to indicate of what type the stored data of value is.
*/
NIXAPI enum class DataType {
Bool,
Char,
Float,
Double,
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
String,
Date,
DateTime,
Nothing = -1
};
/**
* @brief Determine if a type is a valid data type.
*/
template<typename T>
struct to_data_type {
static const bool is_valid = false;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<bool> {
static const bool is_valid = true;
static const DataType value = DataType::Bool;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<char> {
static const bool is_valid = true;
static const DataType value = DataType::Char;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<float> {
static const bool is_valid = true;
static const DataType value = DataType::Float;
};
/**
* @brief Determine if a type is a valid data type.
*
* @internal
*/
template<>
struct to_data_type<double> {
static const bool is_valid = true;
static const DataType value = DataType::Double;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int8_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint8_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int16_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint16_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int32_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint32_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int64_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint64_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<std::string> {
static const bool is_valid = true;
static const DataType value = DataType::String;
};
/**
* @brief Determine the size of a data type.
*
* @param dtype The data type.
*
* @return The size of the type.
*/
NIXAPI size_t data_type_to_size(DataType dtype);
/**
* @brief Convert a data type into string representation.
*
* @param dtype The data type.
*
* @return A human readable name for the given type.
*/
NIXAPI std::string data_type_to_string(DataType dtype);
/**
* @brief Output operator for data type.
*
* Prints a human readable string representation of the
* data type to an output stream.
*
* @param out The output stream.
* @param dtype The data type to print.
*
* @return The output stream.
*/
NIXAPI std::ostream& operator<<(std::ostream &out, const DataType dtype);
} // nix::
#endif
<|endoftext|> |
<commit_before>/** @file optimisation.hpp
* @brief Contains numerical methods for optimisation and root-finding
* @author Oliver W. Laslett
* @date 2016
*/
#ifndef OPTIM_H
#define OPTIM_H
#include <functional>
#ifdef USEMKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
/** @file optimisation.cpp
* @brief Numerical methods for optimisation and root finding.
* @details Contains Newton Raphson methods for root finding.
*/
namespace optimisation {
/// Optimisation success return code
const int SUCCESS = 0b0;
/// Optimisation maximum iterations reached error code
const int MAX_ITERATIONS_ERR = 0b1;
/// Otimisation internal LAPACK error code
/**
* This error code indicates an error ocurred in an internal
* LAPACK call. Further investigation will be needed to determine the
* cause.
*/
const int LAPACK_ERR = 0b10;
int newton_raphson_1( double *x_root,
const std::function<double(const double) > f,
const std::function<double(const double) > fdash,
const double x0,
const double eps=1e-7,
const size_t max_iter=1000 );
int newton_raphson_noinv(
double *x_root,
double *x_tmp,
double *jac_out,
lapack_int *ipiv,
int *lapack_err_code,
const std::function<void(double*,double*,const double* )> func_and_jacobian,
const double *x0, const lapack_int dim,
const double eps=1e-7,
const size_t max_iter=1000 );
}
#endif
<commit_msg>remove binary numbers not c++11 compatible<commit_after>/** @file optimisation.hpp
* @brief Contains numerical methods for optimisation and root-finding
* @author Oliver W. Laslett
* @date 2016
*/
#ifndef OPTIM_H
#define OPTIM_H
#include <functional>
#ifdef USEMKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
/** @file optimisation.cpp
* @brief Numerical methods for optimisation and root finding.
* @details Contains Newton Raphson methods for root finding.
*/
namespace optimisation {
/// Optimisation success return code
const int SUCCESS = 0; //0b00
/// Optimisation maximum iterations reached error code
const int MAX_ITERATIONS_ERR = 1; //0b01
/// Otimisation internal LAPACK error code
/**
* This error code indicates an error ocurred in an internal
* LAPACK call. Further investigation will be needed to determine the
* cause.
*/
const int LAPACK_ERR = 2; //0b10
int newton_raphson_1( double *x_root,
const std::function<double(const double) > f,
const std::function<double(const double) > fdash,
const double x0,
const double eps=1e-7,
const size_t max_iter=1000 );
int newton_raphson_noinv(
double *x_root,
double *x_tmp,
double *jac_out,
lapack_int *ipiv,
int *lapack_err_code,
const std::function<void(double*,double*,const double* )> func_and_jacobian,
const double *x0, const lapack_int dim,
const double eps=1e-7,
const size_t max_iter=1000 );
}
#endif
<|endoftext|> |
<commit_before>#ifndef PROTON_TUPLE_HEADER
#define PROTON_TUPLE_HEADER
/** @file tuple.hpp
* @brief tuple support.
* Please include this header instead of \<tuple\>.
*/
#include <tuple>
#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
#include <limits>
#include <proton/base.hpp>
namespace proton{
namespace detail{
constexpr long fix_index(long i, long size)
{
return (i>size)?
size
:(
(i<0)?
(i+size < 0 ?
0
:
i+size
)
:
i
);
}
constexpr long sub_index(long i, long size)
{
return (i>=size)?
size-1
:(
(i<0)?
(i+size < 0 ?
0
:
i+size
)
:
i
);
}
constexpr long get_index(long i, long size)
{
return (i>=size)?
-1
:(
(i<0)?
(i+size < 0 ?
-1
:
i+size
)
:
i
);
}
template<long i, typename ...T>
struct at_index{
const std::tuple<T...>* p;
typedef decltype(std::get<get_index(i,sizeof...(T))>(*p)) type;
};
constexpr long fix_size(long begin, long end, long size)
{
return fix_index(begin,size)>fix_index(end,size) ?
0
:
fix_index(end,size)-fix_index(begin,size);
}
template<typename ...T>
struct len_t<std::tuple<T...> >{
static size_t result(const std::tuple<T...>& x)
{
return sizeof...(T);
}
};
template<typename T>
class tuple_size;
template<typename ...T>
class tuple_size<std::tuple<T...> >{
public:
static constexpr size_t value=sizeof...(T);
};
////////////////////
// build index_tuple<start, ... start+size-1>
////////////////////
template<long... _Indexes>
struct index_tuple;
template<>
struct index_tuple<>
{};
template<long start, long... _Indexes>
struct index_tuple<start, _Indexes...>
{
typedef index_tuple<start, _Indexes..., start+1+sizeof...(_Indexes)> next;
};
// Builds an _Index_tuple<0, 1, 2, ..., _Num-1>.
template<long begin, long size>
struct build_index_tuple
{
typedef typename build_index_tuple<begin, size - 1>::type::next type;
};
template<long start>
struct build_index_tuple<start, 1>
{
typedef index_tuple<start> type;
};
template<long start>
struct build_index_tuple<start, 0>
{
typedef index_tuple<> type;
};
///////////////////////
///////////////////////
// get the sub type
///////////////////////
template<long, long, typename, typename>
struct make_tuple_impl;
template<long start, long size, typename T, typename... _Tp>
struct make_tuple_impl<start, size, T, std::tuple<_Tp...> >
{
typedef typename make_tuple_impl<start + 1, size-1,
T, std::tuple<_Tp..., typename std::tuple_element<start, T>::type>
>::type
type;
};
template<long start, typename T, typename... _Tp>
struct make_tuple_impl<start, 0, T, std::tuple<_Tp...>>
{
typedef std::tuple<_Tp...> type;
};
template<typename T, long start, long size>
struct sub_tuple_type{
typedef typename make_tuple_impl<start, size, T, std::tuple<> >::type type;
};
//////////////////////
template<typename retT, typename tupT, typename I>
struct sub_tuple;
template<typename retT, typename tupT, long... i>
struct sub_tuple<retT, tupT, index_tuple<i...> >{
static retT sub(const tupT& t)
{
return retT(std::get<i>(t)...);
}
};
//////////////////////
} // ns detail
/** @addtogroup tuple
* @{
*/
/** like x[index] in python
*/
template<long index, typename ...T>
typename detail::at_index<index,T...>::type
at(const std::tuple<T...>& x)
{
return std::get<detail::get_index(index,sizeof...(T))>(x);
}
namespace detail{
// helper function to print a tuple of any size
template<typename T, long I>
struct output_tuple {
static void output(std::ostream& s, const T& t)
{
s << at<-I>(t) << ", ";
output_tuple<T, I-1>::output(s,t);
}
};
template<typename T>
struct output_tuple<T, 1> {
static void output(std::ostream& s, const T& t)
{
s << at<-1>(t);
}
};
template<typename T>
struct output_tuple<T, 0> {
static void output(std::ostream& s, const T& t)
{
}
};
} // ns detail
/** get a slice of tuple x[begin:end] in python
*/
template<long begin, long end=std::numeric_limits<long>::max(), typename T>
typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type sub(const T& t)
{
typedef typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type retT;
return detail::sub_tuple<retT, T,
typename detail::build_index_tuple<detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type
>::sub(t);
}
/** general output for tuple.
* @param s the output stream
* @param x the tuple to be outputed
* @return s
*/
template <typename ...T>
std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x)
{
s << "(";
detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
s << ")";
return s;
}
template <typename ...T>
std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x)
{
s << L"(";
detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
s << L")";
return s;
}
/** tuple + tuple
*/
template<typename T2, typename ...T1>
auto operator+(const std::tuple<T1...>& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
return std::tuple_cat(x,y);
}
template<typename T2, typename ...T1>
auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
return std::tuple_cat(x,y);
}
/** eq to make_tuple
*/
template<typename ...T>
auto _t(T&& ...x) -> decltype(std::make_tuple(x...))
{
return std::make_tuple(x...);
}
/** eq to forward_as_tuple
*/
template<typename ...T>
auto _f(T&& ...x) -> decltype(std::forward_as_tuple(x...))
{
return std::forward_as_tuple(x...);
}
#if 0
/* vector_ * n
*/
template<typename T, typename A>
vector_<T,A> operator*(const std::vector<T,A>& s, size_t n)
{
vector_<T,A> r;
r.reserve(s.size()*n);
for(size_t i=0; i<n; i++)
r.extend(s);
return r;
}
/* n * vector_
*/
template<typename T, typename A>
vector_<T,A> operator*(size_t n, const std::vector<T,A>& s)
{
return s*n;
}
#endif
/**
* @example tuple.cpp
* @}
*/
}
#endif // PROTON_TUPLE_HEADER
<commit_msg>remove unused func<commit_after>#ifndef PROTON_TUPLE_HEADER
#define PROTON_TUPLE_HEADER
/** @file tuple.hpp
* @brief tuple support.
* Please include this header instead of \<tuple\>.
*/
#include <tuple>
#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <algorithm>
#include <stdexcept>
#include <limits>
#include <proton/base.hpp>
namespace proton{
namespace detail{
constexpr long fix_index(long i, long size)
{
return (i>size)?
size
:(
(i<0)?
(i+size < 0 ?
0
:
i+size
)
:
i
);
}
constexpr long get_index(long i, long size)
{
return (i>=size)?
-1
:(
(i<0)?
(i+size < 0 ?
-1
:
i+size
)
:
i
);
}
template<long i, typename ...T>
struct at_index{
const std::tuple<T...>* p;
typedef decltype(std::get<get_index(i,sizeof...(T))>(*p)) type;
};
constexpr long fix_size(long begin, long end, long size)
{
return fix_index(begin,size)>fix_index(end,size) ?
0
:
fix_index(end,size)-fix_index(begin,size);
}
template<typename ...T>
struct len_t<std::tuple<T...> >{
static size_t result(const std::tuple<T...>& x)
{
return sizeof...(T);
}
};
//////////////////
// a simpler tuple_size, to avoid triggering some bugs of clang
//////////////////
template<typename T>
class tuple_size;
template<typename ...T>
class tuple_size<std::tuple<T...> >{
public:
static constexpr size_t value=sizeof...(T);
};
////////////////////
// build index_tuple<start, ... start+size-1>
////////////////////
template<long... _Indexes>
struct index_tuple;
template<>
struct index_tuple<>
{};
template<long start, long... _Indexes>
struct index_tuple<start, _Indexes...>
{
typedef index_tuple<start, _Indexes..., start+1+sizeof...(_Indexes)> next;
};
// Builds an _Index_tuple<0, 1, 2, ..., _Num-1>.
template<long begin, long size>
struct build_index_tuple
{
typedef typename build_index_tuple<begin, size - 1>::type::next type;
};
template<long start>
struct build_index_tuple<start, 1>
{
typedef index_tuple<start> type;
};
template<long start>
struct build_index_tuple<start, 0>
{
typedef index_tuple<> type;
};
///////////////////////
///////////////////////
// get the sub type
///////////////////////
template<long, long, typename, typename>
struct make_tuple_impl;
template<long start, long size, typename T, typename... _Tp>
struct make_tuple_impl<start, size, T, std::tuple<_Tp...> >
{
typedef typename make_tuple_impl<start + 1, size-1,
T, std::tuple<_Tp..., typename std::tuple_element<start, T>::type>
>::type
type;
};
template<long start, typename T, typename... _Tp>
struct make_tuple_impl<start, 0, T, std::tuple<_Tp...>>
{
typedef std::tuple<_Tp...> type;
};
template<typename T, long start, long size>
struct sub_tuple_type{
typedef typename make_tuple_impl<start, size, T, std::tuple<> >::type type;
};
//////////////////////
template<typename retT, typename tupT, typename I>
struct sub_tuple;
template<typename retT, typename tupT, long... i>
struct sub_tuple<retT, tupT, index_tuple<i...> >{
static retT sub(const tupT& t)
{
return retT(std::get<i>(t)...);
}
};
//////////////////////
} // ns detail
/** @addtogroup tuple
* @{
*/
/** like x[index] in python
*/
template<long index, typename ...T>
typename detail::at_index<index,T...>::type
at(const std::tuple<T...>& x)
{
return std::get<detail::get_index(index,sizeof...(T))>(x);
}
namespace detail{
// helper function to print a tuple of any size
template<typename T, long I>
struct output_tuple {
static void output(std::ostream& s, const T& t)
{
s << at<-I>(t) << ", ";
output_tuple<T, I-1>::output(s,t);
}
};
template<typename T>
struct output_tuple<T, 1> {
static void output(std::ostream& s, const T& t)
{
s << at<-1>(t);
}
};
template<typename T>
struct output_tuple<T, 0> {
static void output(std::ostream& s, const T& t)
{
}
};
} // ns detail
/** get a slice of tuple x[begin:end] in python
*/
template<long begin, long end=std::numeric_limits<long>::max(), typename T>
typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type sub(const T& t)
{
typedef typename detail::sub_tuple_type<T, detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type retT;
return detail::sub_tuple<retT, T,
typename detail::build_index_tuple<detail::fix_index(begin, detail::tuple_size<T>::value),
detail::fix_size(begin, end, detail::tuple_size<T>::value)>::type
>::sub(t);
}
/** general output for tuple.
* @param s the output stream
* @param x the tuple to be outputed
* @return s
*/
template <typename ...T>
std::ostream& operator<<(std::ostream& s, const std::tuple<T...>& x)
{
s << "(";
detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
s << ")";
return s;
}
template <typename ...T>
std::wostream& operator<<(std::wostream& s, const std::tuple<T...>& x)
{
s << L"(";
detail::output_tuple<decltype(x), sizeof...(T)>::output(s,x);
s << L")";
return s;
}
/** tuple + tuple
*/
template<typename T2, typename ...T1>
auto operator+(const std::tuple<T1...>& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
return std::tuple_cat(x,y);
}
template<typename T2, typename ...T1>
auto operator+(std::tuple<T1...>&& x, T2&& y) -> decltype(std::tuple_cat(x,y))
{
return std::tuple_cat(x,y);
}
/** eq to make_tuple
*/
template<typename ...T>
auto _t(T&& ...x) -> decltype(std::make_tuple(x...))
{
return std::make_tuple(x...);
}
/** eq to forward_as_tuple
*/
template<typename ...T>
auto _f(T&& ...x) -> decltype(std::forward_as_tuple(x...))
{
return std::forward_as_tuple(x...);
}
/**
* @example tuple.cpp
* @}
*/
}
#endif // PROTON_TUPLE_HEADER
<|endoftext|> |
<commit_before>#ifndef TABLE_HPP
#define TABLE_HPP
#include <iostream>
#include <vector>
#include <limits>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <stdint.h>
#include "util.hpp"
#include "arpTable.hpp"
using nh_index = uint16_t;
/*! Abstract Routing Table class.
* This class should be inherited from, when implementing a source of routing information.
*/
class RoutingTable {
public:
/*! One route.
* This struct holds all the necessary information to decribe one specific route.
*/
struct route {
uint32_t base; //!< base address of the route
uint32_t next_hop; //!< next hop IPv4 address
uint32_t prefix_length; //!< prefix length of the route
uint16_t interface; //!< interface number
nh_index index; //!< Index of the next Hop
#define NH_INVALID uint16_t_max
#define NH_DIRECTLY_CONNECTED (uint16_t_max -1)
route() :
base(uint32_t_max),
next_hop(uint32_t_max),
prefix_length(uint32_t_max),
interface(uint16_t_max) {};
/*! Copy Constructor
*/
route(const route& route) :
base(route.base),
next_hop(route.next_hop),
prefix_length(route.prefix_length),
interface(route.interface),
index(route.index) {};
/*! Return if this route is valid
* Valid routes have a base address of not all 1s
*/
operator bool(){
if(base == uint32_t_max){
return false;
} else {
return true;
}
};
};
static const route invalidRoute; //!< invalid Route
protected:
/*! All of the routing information is contained here
*/
std::shared_ptr<std::vector<std::vector<route>>>
entries = std::make_shared<std::vector<std::vector<route>>>();
/*! Mapping from next hop index to IPv4 addresses
*/
std::shared_ptr<std::vector<uint32_t>>
nextHopMapping = std::make_shared<std::vector<uint32_t>>();
/*! Update the underlying routing infomation
* Implementation is up to the child class
*/
virtual void updateInfo() {};
private:
void buildNextHopList();
void aggregate();
std::unordered_set<uint16_t> interfaces;
public:
/*! Print the routing table.
* Similiar to "ip r"
*/
void print_table();
/*! Get the routes currently held inside the routing table
* \return routes sorted by prefix length (first index), and base address
*/
std::shared_ptr<std::vector<std::vector<route>>> getSortedRoutes();
/*! From index to IPv4.
* Get a mapping from the next hop index to an IPv4 address
* \return mapping
*/
std::shared_ptr<std::vector<uint32_t>> getNextHopMapping();
/*! Get the set of used interfaces
* Return the set of used interface
* \return set of interfaces
*/
std::unordered_set<uint16_t> getInterfaceSet();
/*! Update the routing information
* This function updates the routing information and preprocesses it for further usage.
*/
void update(){
updateInfo();
aggregate();
buildNextHopList();
};
};
#endif /* ROUTINGTABLE_HPP */
<commit_msg>add missing getter implementation to arpTable.hpp<commit_after>#ifndef TABLE_HPP
#define TABLE_HPP
#include <iostream>
#include <vector>
#include <limits>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <stdint.h>
#include "util.hpp"
#include "arpTable.hpp"
using nh_index = uint16_t;
/*! Abstract Routing Table class.
* This class should be inherited from, when implementing a source of routing information.
*/
class RoutingTable {
public:
/*! One route.
* This struct holds all the necessary information to decribe one specific route.
*/
struct route {
uint32_t base; //!< base address of the route
uint32_t next_hop; //!< next hop IPv4 address
uint32_t prefix_length; //!< prefix length of the route
uint16_t interface; //!< interface number
nh_index index; //!< Index of the next Hop
#define NH_INVALID uint16_t_max
#define NH_DIRECTLY_CONNECTED (uint16_t_max -1)
route() :
base(uint32_t_max),
next_hop(uint32_t_max),
prefix_length(uint32_t_max),
interface(uint16_t_max) {};
/*! Copy Constructor
*/
route(const route& route) :
base(route.base),
next_hop(route.next_hop),
prefix_length(route.prefix_length),
interface(route.interface),
index(route.index) {};
/*! Return if this route is valid
* Valid routes have a base address of not all 1s
*/
operator bool(){
if(base == uint32_t_max){
return false;
} else {
return true;
}
};
};
static const route invalidRoute; //!< invalid Route
protected:
/*! All of the routing information is contained here
*/
std::shared_ptr<std::vector<std::vector<route>>>
entries = std::make_shared<std::vector<std::vector<route>>>();
/*! Mapping from next hop index to IPv4 addresses
*/
std::shared_ptr<std::vector<uint32_t>>
nextHopMapping = std::make_shared<std::vector<uint32_t>>();
/*! Update the underlying routing infomation
* Implementation is up to the child class
*/
virtual void updateInfo() {};
private:
void buildNextHopList();
void aggregate();
std::unordered_set<uint16_t> interfaces;
public:
/*! Print the routing table.
* Similiar to "ip r"
*/
void print_table();
/*! Get the routes currently held inside the routing table
* \return routes sorted by prefix length (first index), and base address
*/
std::shared_ptr<std::vector<std::vector<route>>> getSortedRoutes();
/*! From index to IPv4.
* Get a mapping from the next hop index to an IPv4 address
* \return mapping
*/
std::shared_ptr<std::vector<uint32_t>> getNextHopMapping(){
return nextHopMapping;
};
/*! Get the set of used interfaces
* Return the set of used interface
* \return set of interfaces
*/
std::unordered_set<uint16_t> getInterfaceSet();
/*! Update the routing information
* This function updates the routing information and preprocesses it for further usage.
*/
void update(){
updateInfo();
aggregate();
buildNextHopList();
};
};
#endif /* ROUTINGTABLE_HPP */
<|endoftext|> |
<commit_before>/*!
@file NinfoReader.hpp
@brief definition of NinfoReader class.
NinfoReader reads a ninfo file and store the data as NinfoData.
@author Toru Niina (niina.toru.68u@gmail.com)
@date 2016-06-10 10:00
@copyright Toru Niina 2016 on MIT License
*/
#ifndef COFFEE_MILL_NINFO_READER
#define COFFEE_MILL_NINFO_READER
#include "NinfoData.hpp"
namespace coffeemill
{
template<typename T = DefaultTraits>
class NinfoReader
{
public:
using char_type = typename T::char_type;
using data_type = NinfoData<T>;
public:
NinfoReader() = default;
~NinfoReader() = default;
data_type read(const std::basic_string<char_type>& filename);
data_type read(std::basic_istream<char_type>& is);
private:
void read_line(data_type& data, const std::basic_string<char_type>& line);
};
template<typename T_traits>
NinfoData<T_Traits>
NinfoReader<T_traits>::read(std::basic_string<char_type>& filename)
{
std::basic_ifstream<char_type> filestream(filename);
if(!filestream.good()) throw std::runtime_error("file open error");
return this->read(filestream);
}
template<typename T_traits>
NinfoData<T_traits>
NinfoReader<T_traits>::read(std::basic_istream<char_type>& is)
{
NinfoData<T_traits> data;
std::size_t lineindex = 0;
while(!is.eof())
{
std::basic_string<char_type> line;
std::getline(is, line); ++lineindex;
if(line.empty()) continue;
line = remove_indent(line);
try{
if(line.empty()) continue;
else if(line.front() == '*') continue;
else if(line.substr(0, 4) == "<<<<") continue;
else if(line.substr(0, 4) == ">>>>") continue;
else read_line(data, line);
}
catch(std::exception& except)
{
throw std::runtime_error( "invalid ninfo line found at line #" +
std::to_string(lineindex));
}
}
return data;
}
template<typename T_traits>
void NinfoReader<T_traits>::read_line(
data_type& data, const std::basic_string<char_type>& line)
{
std::basic_istringstream<char_type> iss(line);
std::basic_string<char_type> prefix;
const auto line_head = iss.tellg();
iss >> prefix;
iss.seekg(line_head);
NinfoKind kind;
std::shared_ptr<NinfoBase<T_traits>> ninfo;
// switch with prefix: set kind and ninfo {{{
if(prefix == "bond")
{
kind = NinfoKind::Bond;
ninfo = std::make_shared<NinfoBond>();
}
else if(prefix == "angl")
{
kind = NinfoKind::Angl;
ninfo = std::make_shared<NinfoAngl>();
}
else if(prefix == "aicg13")
{
kind = NinfoKind::Aicg13;
ninfo = std::make_shared<NinfoAicg13>();
}
else if(prefix == "dihd")
{
kind = NinfoKind::Dihd;
ninfo = std::make_shared<NinfoDihd>();
}
else if(prefix == "aicg14")
{
kind = NinfoKind::Aicg14;
ninfo = std::make_shared<NinfoAicg14>();
}
else if(prefix == "aicgdih")
{
kind = NinfoKind::Aicgdih;
ninfo = std::make_shared<NinfoAicgdih>();
}
else if(prefix == "contact")
{
kind = NinfoKind::Contact;
ninfo = std::make_shared<NinfoContact>();
}
else if(prefix == "basepair")
{
kind = NinfoKind::BasePair;
ninfo = std::make_shared<NinfoBasePair>();
}
else if(prefix == "basestack")
{
kind = NinfoKind::BaseStack;
ninfo = std::make_shared<NinfoBaseStack>();
}
else
{
throw std::logic_error("invalid line");
}
//}}}
iss >> (*ninfo);
if(data.count(kind) == 0)
{
std::vector<std::shared_ptr<NinfoBase<T_Traits>>> block{ninfo};
data.emplace(kind, block);
}
else
{
data[kind].push_back(ninfo);
}
return;
}
}
#endif //COFFEE_MILL_NINFO_READER
<commit_msg>add file close<commit_after>/*!
@file NinfoReader.hpp
@brief definition of NinfoReader class.
NinfoReader reads a ninfo file and store the data as NinfoData.
@author Toru Niina (niina.toru.68u@gmail.com)
@date 2016-06-10 10:00
@copyright Toru Niina 2016 on MIT License
*/
#ifndef COFFEE_MILL_NINFO_READER
#define COFFEE_MILL_NINFO_READER
#include "NinfoData.hpp"
namespace coffeemill
{
template<typename T = DefaultTraits>
class NinfoReader
{
public:
using char_type = typename T::char_type;
using data_type = NinfoData<T>;
public:
NinfoReader() = default;
~NinfoReader() = default;
data_type read(const std::basic_string<char_type>& filename);
data_type read(std::basic_istream<char_type>& is);
private:
void read_line(data_type& data, const std::basic_string<char_type>& line);
};
template<typename T_traits>
NinfoData<T_Traits>
NinfoReader<T_traits>::read(std::basic_string<char_type>& filename)
{
std::basic_ifstream<char_type> filestream(filename);
if(!filestream.good()) throw std::runtime_error("file open error");
const auto retval = this->read(filestream);
filestream.close();
return retval;
}
template<typename T_traits>
NinfoData<T_traits>
NinfoReader<T_traits>::read(std::basic_istream<char_type>& is)
{
NinfoData<T_traits> data;
std::size_t lineindex = 0;
while(!is.eof())
{
std::basic_string<char_type> line;
std::getline(is, line); ++lineindex;
if(line.empty()) continue;
line = remove_indent(line);
try{
if(line.empty()) continue;
else if(line.front() == '*') continue;
else if(line.substr(0, 4) == "<<<<") continue;
else if(line.substr(0, 4) == ">>>>") continue;
else read_line(data, line);
}
catch(std::exception& except)
{
throw std::runtime_error( "invalid ninfo line found at line #" +
std::to_string(lineindex));
}
}
return data;
}
template<typename T_traits>
void NinfoReader<T_traits>::read_line(
data_type& data, const std::basic_string<char_type>& line)
{
std::basic_istringstream<char_type> iss(line);
std::basic_string<char_type> prefix;
const auto line_head = iss.tellg();
iss >> prefix;
iss.seekg(line_head);
NinfoKind kind;
std::shared_ptr<NinfoBase<T_traits>> ninfo;
// switch with prefix: set kind and ninfo {{{
if(prefix == "bond")
{
kind = NinfoKind::Bond;
ninfo = std::make_shared<NinfoBond>();
}
else if(prefix == "angl")
{
kind = NinfoKind::Angl;
ninfo = std::make_shared<NinfoAngl>();
}
else if(prefix == "aicg13")
{
kind = NinfoKind::Aicg13;
ninfo = std::make_shared<NinfoAicg13>();
}
else if(prefix == "dihd")
{
kind = NinfoKind::Dihd;
ninfo = std::make_shared<NinfoDihd>();
}
else if(prefix == "aicg14")
{
kind = NinfoKind::Aicg14;
ninfo = std::make_shared<NinfoAicg14>();
}
else if(prefix == "aicgdih")
{
kind = NinfoKind::Aicgdih;
ninfo = std::make_shared<NinfoAicgdih>();
}
else if(prefix == "contact")
{
kind = NinfoKind::Contact;
ninfo = std::make_shared<NinfoContact>();
}
else if(prefix == "basepair")
{
kind = NinfoKind::BasePair;
ninfo = std::make_shared<NinfoBasePair>();
}
else if(prefix == "basestack")
{
kind = NinfoKind::BaseStack;
ninfo = std::make_shared<NinfoBaseStack>();
}
else
{
throw std::logic_error("invalid line");
}
//}}}
iss >> (*ninfo);
if(data.count(kind) == 0)
{
std::vector<std::shared_ptr<NinfoBase<T_Traits>>> block{ninfo};
data.emplace(kind, block);
}
else
{
data[kind].push_back(ninfo);
}
return;
}
}
#endif //COFFEE_MILL_NINFO_READER
<|endoftext|> |
<commit_before>#pragma once
#include "indexer/cell_id.hpp"
#include "geometry/rect2d.hpp"
#include "base/buffer_vector.hpp"
#include <array>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
// TODO: Move neccessary functions to geometry/covering_utils.hpp and delete this file.
constexpr int SPLIT_RECT_CELLS_COUNT = 512;
template <typename Bounds, typename CellId>
inline size_t SplitRectCell(CellId const & id, m2::RectD const & rect,
std::array<std::pair<CellId, m2::RectD>, 4> & result)
{
size_t index = 0;
for (int8_t i = 0; i < 4; ++i)
{
auto const child = id.Child(i);
double minCellX, minCellY, maxCellX, maxCellY;
CellIdConverter<Bounds, CellId>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY);
m2::RectD const childRect(minCellX, minCellY, maxCellX, maxCellY);
if (rect.IsIntersect(childRect))
result[index++] = {child, childRect};
}
return index;
}
template <typename Bounds, typename CellId>
inline void CoverRect(m2::RectD rect, size_t cellsCount, int maxDepth, std::vector<CellId> & result)
{
ASSERT(result.empty(), ());
{
// Cut rect with world bound coordinates.
if (!rect.Intersect(Bounds::FullRect()))
return;
ASSERT(rect.IsValid(), ());
}
auto const commonCell = CellIdConverter<Bounds, CellId>::Cover2PointsWithCell(
rect.minX(), rect.minY(), rect.maxX(), rect.maxY());
std::priority_queue<CellId, buffer_vector<CellId, SPLIT_RECT_CELLS_COUNT>,
typename CellId::GreaterLevelOrder>
cellQueue;
cellQueue.push(commonCell);
maxDepth -= 1;
while (!cellQueue.empty() && cellQueue.size() + result.size() < cellsCount)
{
auto id = cellQueue.top();
cellQueue.pop();
while (id.Level() > maxDepth)
id = id.Parent();
if (id.Level() == maxDepth)
{
result.push_back(id);
break;
}
std::array<std::pair<CellId, m2::RectD>, 4> arr;
size_t const count = SplitRectCell<Bounds>(id, rect, arr);
if (cellQueue.size() + result.size() + count <= cellsCount)
{
for (size_t i = 0; i < count; ++i)
{
if (rect.IsRectInside(arr[i].second))
result.push_back(arr[i].first);
else
cellQueue.push(arr[i].first);
}
}
else
{
result.push_back(id);
}
}
for (; !cellQueue.empty(); cellQueue.pop())
{
auto id = cellQueue.top();
while (id.Level() < maxDepth)
{
std::array<std::pair<CellId, m2::RectD>, 4> arr;
size_t const count = SplitRectCell<Bounds>(id, rect, arr);
ASSERT_GREATER(count, 0, ());
if (count > 1)
break;
id = arr[0].first;
}
result.push_back(id);
}
}
// Covers rect with cells using spiral order starting from the rect center.
template <typename Bounds, typename CellId>
void CoverSpiral(m2::RectD rect, int maxDepth, std::vector<CellId> & result)
{
using Converter = CellIdConverter<Bounds, CellId>;
enum class Direction : uint8_t
{
Right = 0,
Down = 1,
Left = 2,
Up = 3
};
CHECK(result.empty(), ());
// Cut rect with world bound coordinates.
if (!rect.Intersect(Bounds::FullRect()))
return;
CHECK(rect.IsValid(), ());
auto centralCell = Converter::ToCellId(rect.Center().x, rect.Center().y);
while (centralCell.Level() > maxDepth && centralCell.Level() > 0)
centralCell = centralCell.Parent();
if (centralCell.Level() > maxDepth)
return;
result.push_back(centralCell);
// Area around CentralCell will be covered with surrounding cells.
//
// * -> * -> * -> *
// ^ |
// | V
// * C -> * *
// ^ | |
// | V V
// * <- * <- * *
//
// To get the best ranking quality we should use the smallest cell size but it's not
// efficient because it generates too many index requests. To get good quality-performance
// tradeoff we cover area with |maxCount| small cells, then increase cell size and cover
// area with |maxCount| bigger cells. We increase cell size until |rect| is covered.
// We start covering from the center each time and it's ok for ranking because each object
// appears in result at most once.
// |maxCount| may be adjusted after testing to ensure better quality-performance tradeoff.
uint32_t constexpr maxCount = 64;
auto const nextDirection = [](Direction direction) {
return static_cast<Direction>((static_cast<uint8_t>(direction) + 1) % 4);
};
auto const nextCoords = [](std::pair<int32_t, int32_t> const & xy, Direction direction, uint32_t step) {
auto res = xy;
switch (direction)
{
case Direction::Right: res.first += step; break;
case Direction::Down: res.second -= step; break;
case Direction::Left: res.first -= step; break;
case Direction::Up: res.second += step; break;
}
return res;
};
auto const coordsAreValid = [](std::pair<int32_t, int32_t> const & xy) {
return xy.first >= 0 && xy.second >= 0 &&
static_cast<decltype(CellId::MAX_COORD)>(xy.first) <= CellId::MAX_COORD &&
static_cast<decltype(CellId::MAX_COORD)>(xy.second) <= CellId::MAX_COORD;
};
m2::RectD coveredRect;
static_assert(CellId::MAX_COORD == static_cast<int32_t>(CellId::MAX_COORD), "");
while (centralCell.Level() > 0 && !coveredRect.IsRectInside(rect))
{
uint32_t count = 0;
auto const centerXY = centralCell.XY();
// We support negative coordinates while covering and check coordinates validity before pushing
// cell to |result|.
std::pair<int32_t, int32_t> xy{centerXY.first, centerXY.second};
auto direction = Direction::Right;
int sideLength = 1;
// Indicates whether it is the first pass with current |sideLength|. We use spiral cells order and
// must increment |sideLength| every second side pass. |sideLength| and |direction| will behave like:
// 1 right, 1 down, 2 left, 2 up, 3 right, 3 down, etc.
bool evenPass = true;
while (count <= maxCount && !coveredRect.IsRectInside(rect))
{
for (int i = 0; i < sideLength; ++i)
{
xy = nextCoords(xy, direction, centralCell.Radius() * 2);
if (coordsAreValid(xy))
{
auto const cell = CellId::FromXY(xy.first, xy.second, centralCell.Level());
double minCellX, minCellY, maxCellX, maxCellY;
Converter::GetCellBounds(cell, minCellX, minCellY, maxCellX, maxCellY);
auto const cellRect = m2::RectD(minCellX, minCellY, maxCellX, maxCellY);
coveredRect.Add(cellRect);
if (rect.IsIntersect(cellRect))
result.push_back(cell);
}
++count;
}
if (!evenPass)
++sideLength;
direction = nextDirection(direction);
evenPass = !evenPass;
}
centralCell = centralCell.Parent();
}
}
<commit_msg>[indexer] Fix cell depth for spiral coverer<commit_after>#pragma once
#include "indexer/cell_id.hpp"
#include "geometry/rect2d.hpp"
#include "base/buffer_vector.hpp"
#include <array>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
// TODO: Move neccessary functions to geometry/covering_utils.hpp and delete this file.
constexpr int SPLIT_RECT_CELLS_COUNT = 512;
template <typename Bounds, typename CellId>
inline size_t SplitRectCell(CellId const & id, m2::RectD const & rect,
std::array<std::pair<CellId, m2::RectD>, 4> & result)
{
size_t index = 0;
for (int8_t i = 0; i < 4; ++i)
{
auto const child = id.Child(i);
double minCellX, minCellY, maxCellX, maxCellY;
CellIdConverter<Bounds, CellId>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY);
m2::RectD const childRect(minCellX, minCellY, maxCellX, maxCellY);
if (rect.IsIntersect(childRect))
result[index++] = {child, childRect};
}
return index;
}
template <typename Bounds, typename CellId>
inline void CoverRect(m2::RectD rect, size_t cellsCount, int maxDepth, std::vector<CellId> & result)
{
ASSERT(result.empty(), ());
{
// Cut rect with world bound coordinates.
if (!rect.Intersect(Bounds::FullRect()))
return;
ASSERT(rect.IsValid(), ());
}
auto const commonCell = CellIdConverter<Bounds, CellId>::Cover2PointsWithCell(
rect.minX(), rect.minY(), rect.maxX(), rect.maxY());
std::priority_queue<CellId, buffer_vector<CellId, SPLIT_RECT_CELLS_COUNT>,
typename CellId::GreaterLevelOrder>
cellQueue;
cellQueue.push(commonCell);
maxDepth -= 1;
while (!cellQueue.empty() && cellQueue.size() + result.size() < cellsCount)
{
auto id = cellQueue.top();
cellQueue.pop();
while (id.Level() > maxDepth)
id = id.Parent();
if (id.Level() == maxDepth)
{
result.push_back(id);
break;
}
std::array<std::pair<CellId, m2::RectD>, 4> arr;
size_t const count = SplitRectCell<Bounds>(id, rect, arr);
if (cellQueue.size() + result.size() + count <= cellsCount)
{
for (size_t i = 0; i < count; ++i)
{
if (rect.IsRectInside(arr[i].second))
result.push_back(arr[i].first);
else
cellQueue.push(arr[i].first);
}
}
else
{
result.push_back(id);
}
}
for (; !cellQueue.empty(); cellQueue.pop())
{
auto id = cellQueue.top();
while (id.Level() < maxDepth)
{
std::array<std::pair<CellId, m2::RectD>, 4> arr;
size_t const count = SplitRectCell<Bounds>(id, rect, arr);
ASSERT_GREATER(count, 0, ());
if (count > 1)
break;
id = arr[0].first;
}
result.push_back(id);
}
}
// Covers rect with cells using spiral order starting from the rect center.
template <typename Bounds, typename CellId>
void CoverSpiral(m2::RectD rect, int maxDepth, std::vector<CellId> & result)
{
using Converter = CellIdConverter<Bounds, CellId>;
enum class Direction : uint8_t
{
Right = 0,
Down = 1,
Left = 2,
Up = 3
};
CHECK(result.empty(), ());
// Cut rect with world bound coordinates.
if (!rect.Intersect(Bounds::FullRect()))
return;
CHECK(rect.IsValid(), ());
auto centralCell = Converter::ToCellId(rect.Center().x, rect.Center().y);
auto levelMax = maxDepth - 1;
while (levelMax < centralCell.Level() && centralCell.Level() > 0)
centralCell = centralCell.Parent();
if (levelMax < centralCell.Level())
return;
result.push_back(centralCell);
// Area around CentralCell will be covered with surrounding cells.
//
// * -> * -> * -> *
// ^ |
// | V
// * C -> * *
// ^ | |
// | V V
// * <- * <- * *
//
// To get the best ranking quality we should use the smallest cell size but it's not
// efficient because it generates too many index requests. To get good quality-performance
// tradeoff we cover area with |maxCount| small cells, then increase cell size and cover
// area with |maxCount| bigger cells. We increase cell size until |rect| is covered.
// We start covering from the center each time and it's ok for ranking because each object
// appears in result at most once.
// |maxCount| may be adjusted after testing to ensure better quality-performance tradeoff.
uint32_t constexpr maxCount = 64;
auto const nextDirection = [](Direction direction) {
return static_cast<Direction>((static_cast<uint8_t>(direction) + 1) % 4);
};
auto const nextCoords = [](std::pair<int32_t, int32_t> const & xy, Direction direction, uint32_t step) {
auto res = xy;
switch (direction)
{
case Direction::Right: res.first += step; break;
case Direction::Down: res.second -= step; break;
case Direction::Left: res.first -= step; break;
case Direction::Up: res.second += step; break;
}
return res;
};
auto const coordsAreValid = [](std::pair<int32_t, int32_t> const & xy) {
return xy.first >= 0 && xy.second >= 0 &&
static_cast<decltype(CellId::MAX_COORD)>(xy.first) <= CellId::MAX_COORD &&
static_cast<decltype(CellId::MAX_COORD)>(xy.second) <= CellId::MAX_COORD;
};
m2::RectD coveredRect;
static_assert(CellId::MAX_COORD == static_cast<int32_t>(CellId::MAX_COORD), "");
while (centralCell.Level() > 0 && !coveredRect.IsRectInside(rect))
{
uint32_t count = 0;
auto const centerXY = centralCell.XY();
// We support negative coordinates while covering and check coordinates validity before pushing
// cell to |result|.
std::pair<int32_t, int32_t> xy{centerXY.first, centerXY.second};
auto direction = Direction::Right;
int sideLength = 1;
// Indicates whether it is the first pass with current |sideLength|. We use spiral cells order and
// must increment |sideLength| every second side pass. |sideLength| and |direction| will behave like:
// 1 right, 1 down, 2 left, 2 up, 3 right, 3 down, etc.
bool evenPass = true;
while (count <= maxCount && !coveredRect.IsRectInside(rect))
{
for (int i = 0; i < sideLength; ++i)
{
xy = nextCoords(xy, direction, centralCell.Radius() * 2);
if (coordsAreValid(xy))
{
auto const cell = CellId::FromXY(xy.first, xy.second, centralCell.Level());
double minCellX, minCellY, maxCellX, maxCellY;
Converter::GetCellBounds(cell, minCellX, minCellY, maxCellX, maxCellY);
auto const cellRect = m2::RectD(minCellX, minCellY, maxCellX, maxCellY);
coveredRect.Add(cellRect);
if (rect.IsIntersect(cellRect))
result.push_back(cell);
}
++count;
}
if (!evenPass)
++sideLength;
direction = nextDirection(direction);
evenPass = !evenPass;
}
centralCell = centralCell.Parent();
}
}
<|endoftext|> |
<commit_before>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
class BaxterDisplay
{
private:
ros::NodeHandle nh;
std::string name;
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h;
int w;
int w_delim;
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_DEBUG("Received callback! Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
int border = 20;
int max_width = 700; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontScale = 1.6;
thickness = 2;
textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
numLines = int(textSize.width/max_width);
}
ROS_DEBUG("Size of the text %i %i numLines %i", textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the rectangle container (line_heigth + interline)
int rec_width = 0; // Width of the rectangle container (max of the width of each of the lines)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFace, fontScale, thickness, &baseline));
if (size.back().width>rec_width) rec_width=size.back().width;
rec_height += interline + size.back().height;
ROS_DEBUG(" Line %i: size: %i %i\ttext: %s", i, size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols - rec_width)/2, (in.rows - rec_height)/2);
cv::Point rectEnd((in.cols + rec_width)/2, (in.rows + rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, CV_AA);
textOrgy += interline;
}
printf("\n");
}
};
cv::Mat createSubImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h,(w-w_delim)/2,CV_8UC3,cv::Scalar::all(255));
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_state = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_state = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFace, fontScale, thickness, &baseline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFace, fontScale, col, thickness, CV_AA);
if (state.state !="")
{
putText(img, "state:", cv::Point(20,300), fontFace, fontScale/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300), fontFace, fontScale, col_state, thickness, CV_AA);
}
if (state.action !="")
{
putText(img, "action:", cv::Point(20,400), fontFace, fontScale/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
if (false)
{
putText(img, "object:", cv::Point(20,500), fontFace, fontScale/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
return img;
};
public:
explicit BaxterDisplay(string _name) : name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
h = 600;
w = 1024;
w_delim = 8;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
};
void setSpeech(const std::string &s)
{
speech = s;
}
void speechCb(const std_msgs::String& msg)
{
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
void deleteSpeechCb(const ros::TimerEvent&)
{
setSpeech("");
displayArmStates();
};
bool displayArmStates()
{
cv::Mat l = createSubImage("LEFT");
cv::Mat r = createSubImage("RIGHT");
cv::Mat d(h,w_delim,CV_8UC3,cv::Scalar::all(80));
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
// Move right boundary to the left.
res.adjustROI(0,0,0,-(w+w_delim)/2);
r.copyTo(res);
// Move the left boundary to the right, right boundary to the right.
res.adjustROI(0, 0, -(w-w_delim)/2, w_delim);
d.copyTo(res);
// Move the left boundary to the right, right boundary to the right.
res.adjustROI(0, 0, -w_delim, (w-w_delim)/2);
l.copyTo(res);
res.adjustROI(0, 0, (w+w_delim)/2, 0);
displaySpeech(res);
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<commit_msg>[baxter_display] Reverted back the quick fix<commit_after>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
class BaxterDisplay
{
private:
ros::NodeHandle nh;
std::string name;
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h;
int w;
int w_delim;
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_DEBUG("Received callback! Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
int border = 20;
int max_width = 700; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontScale = 1.6;
thickness = 2;
textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
numLines = int(textSize.width/max_width);
}
ROS_DEBUG("Size of the text %i %i numLines %i", textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the rectangle container (line_heigth + interline)
int rec_width = 0; // Width of the rectangle container (max of the width of each of the lines)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFace, fontScale, thickness, &baseline));
if (size.back().width>rec_width) rec_width=size.back().width;
rec_height += interline + size.back().height;
ROS_DEBUG(" Line %i: size: %i %i\ttext: %s", i, size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols - rec_width)/2, (in.rows - rec_height)/2);
cv::Point rectEnd((in.cols + rec_width)/2, (in.rows + rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, CV_AA);
textOrgy += interline;
}
printf("\n");
}
};
cv::Mat createSubImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h,(w-w_delim)/2,CV_8UC3,cv::Scalar::all(255));
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_state = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_state = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFace, fontScale, thickness, &baseline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFace, fontScale, col, thickness, CV_AA);
if (state.state !="")
{
putText(img, "state:", cv::Point(20,300), fontFace, fontScale/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300), fontFace, fontScale, col_state, thickness, CV_AA);
}
if (state.action !="")
{
putText(img, "action:", cv::Point(20,400), fontFace, fontScale/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
if (state.object !="")
{
putText(img, "object:", cv::Point(20,500), fontFace, fontScale/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
return img;
};
public:
explicit BaxterDisplay(string _name) : name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
h = 600;
w = 1024;
w_delim = 8;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
};
void setSpeech(const std::string &s)
{
speech = s;
}
void speechCb(const std_msgs::String& msg)
{
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
void deleteSpeechCb(const ros::TimerEvent&)
{
setSpeech("");
displayArmStates();
};
bool displayArmStates()
{
cv::Mat l = createSubImage("LEFT");
cv::Mat r = createSubImage("RIGHT");
cv::Mat d(h,w_delim,CV_8UC3,cv::Scalar::all(80));
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
// Move right boundary to the left.
res.adjustROI(0,0,0,-(w+w_delim)/2);
r.copyTo(res);
// Move the left boundary to the right, right boundary to the right.
res.adjustROI(0, 0, -(w-w_delim)/2, w_delim);
d.copyTo(res);
// Move the left boundary to the right, right boundary to the right.
res.adjustROI(0, 0, -w_delim, (w-w_delim)/2);
l.copyTo(res);
res.adjustROI(0, 0, (w+w_delim)/2, 0);
displaySpeech(res);
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
/**
* Class that manages the output to the baxter display. By default, it publishes an image
*/
class BaxterDisplay
{
private:
ros::NodeHandle nh;
int print_level; // Print level to be used throughout the code
std::string name; // Name of the node
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h; // height of the image to be shown (equal to the height of the baxter display)
int w; // width of the image to be shown (equal to the width of the baxter display)
int w_d; // width of the delimiter between sub-screens
int w_b; // width of the bottom sub-screen
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
/**
* Callback for the left arm state
* @param msg the left arm state
*/
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
/**
* Callback for the right arm state
* @param msg the right arm state
*/
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
/**
* Unified callback manager for both arm states
* @param msg the arm state
* @param _limb the arm it is referred to
*/
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_INFO_COND(print_level>=2, "Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
/**
* Callback from the speech
* @param msg the speech
*/
void speechCb(const std_msgs::String& msg)
{
ROS_INFO_COND(print_level>=2, "Text: %s", msg.data.c_str());
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
/**
* Callback to delete the speech from the screen (after t=speech_duration)
*/
void deleteSpeechCb(const ros::TimerEvent&)
{
ROS_INFO_COND(print_level>=2, "Deleting speech");
setSpeech("");
displayArmStates();
};
/**
* Function to display speech on top of the generated image
* @param in the already generated image ready to be sent to the robot
*/
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
ROS_INFO_COND(print_level>=3, "Displaying speech: %s", speech.c_str());
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
int border = 20;
int max_width = 800; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontSc = 1.6;
thickn = 2;
textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
numLines = int(textSize.width/max_width);
}
ROS_INFO_COND(print_level>=4, "Size of the text %i %i numLines %i",
textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the container (line_heigth + interline)
int rec_width = 0; // Width of the container (max width of each line)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFc, fontSc, thickn, &bsline));
if (size.back().width>rec_width) { rec_width=size.back().width; }
rec_height += interline + size.back().height;
ROS_INFO_COND(print_level>=6, " Line %i: size: %i %i\ttext: %s", i,
size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols-rec_width)/2, (in.rows-w_d/2-w_b-rec_height)/2);
cv::Point rectEnd((in.cols+rec_width)/2, (in.rows-w_d/2-w_b+rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFc, fontSc, cv::Scalar::all(255), thickn, CV_AA);
textOrgy += interline;
}
}
};
/**
* Function to create sub-image for either arm
* @param _limb the arm to create the image for
* @return the sub-image
*/
cv::Mat createArmImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h-w_d/2-w_b,(w-w_d)/2,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created %s image with size %i %i",
_limb.c_str(), img.rows, img.cols);
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_s = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_s = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFc, fontSc, thickn, &bsline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFc, fontSc, col, thickn, CV_AA);
if (state.state !=" ")
{
putText(img, "state:", cv::Point( 20,300-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300-60), fontFc, fontSc, col, thickn, CV_AA);
}
if (state.action !=" ")
{
putText(img, "action:", cv::Point( 20,400-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
if (state.object !=" ")
{
putText(img, "object:", cv::Point( 20,500-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
return img;
};
/**
* Function to create sub-image for the bottom bar (to be filled with status icons)
* @return the sub-image
*/
cv::Mat createBtmImage()
{
cv::Mat res(w_b-w_d/2,w,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created BOTTOM image with size %i %i", res.rows, res.cols);
return res;
}
public:
/**
* Constructor
*/
explicit BaxterDisplay(string _name) : print_level(0), name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
nh.param<int> ("/print_level", print_level, 0);
h = 600;
w = 1024;
w_d = 8;
w_b = 80;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
ROS_INFO_COND(print_level>=3, "Subscribing to %s and %s", l_sub.getTopic().c_str(),
r_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Subscribing to %s", s_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Publishing to %s", im_pub.getTopic().c_str());
ROS_INFO_COND(print_level>=1, "Print Level set to %i", print_level);
ROS_INFO_COND(print_level>=1, "Speech Duration set to %g", speech_duration);
ROS_INFO_COND(print_level>=1, "Ready!!");
};
/**
* Function to set the speech to a specific value
* @param s the speech text
*/
void setSpeech(const std::string &s)
{
speech = s;
}
/**
* Function to display arm states into a single image. It combines each individual sub-image
* (the one for the left arm, the one for the right arm, and the bottom status bar)
* @return true/false if success/failure
*/
bool displayArmStates()
{
cv::Mat l = createArmImage("LEFT");
cv::Mat r = createArmImage("RIGHT");
cv::Mat b = createBtmImage();
cv::Mat d_v(r.rows,w_d,CV_8UC3,cv::Scalar::all(80)); // Vertical delimiter
cv::Mat d_h(w_d,w,CV_8UC3,cv::Scalar::all(80)); // Horizontal delimiter
ROS_INFO_COND(print_level>=5, "d_v size %i %i", d_v.rows, d_v.cols);
ROS_INFO_COND(print_level>=5, "d_h size %i %i", d_h.rows, d_h.cols);
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
// Draw sub-image for right arm
r.copyTo(res(cv::Rect(0, 0, r.cols, r.rows)));
// Draw sub-image for the vertical delimiter
d_v.copyTo(res(cv::Rect(r.cols, 0, d_v.cols, d_v.rows)));
// Draw sub-image for left arm
l.copyTo(res(cv::Rect(r.cols+d_v.cols, 0, l.cols, l.rows)));
// Draw sub-image for horizontal delimiter
d_h.copyTo(res(cv::Rect(0, r.rows, d_h.cols, d_h.rows)));
// Draw sub-image for bottom bar
b.copyTo(res(cv::Rect(0, r.rows+d_h.rows, b.cols, b.rows)));
// Eventually draw the speech on top of everything
displaySpeech(res);
// Publish the resulting image
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<commit_msg>[baxter_display] Improved printouts<commit_after>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
/**
* Class that manages the output to the baxter display. By default, it publishes an image
*/
class BaxterDisplay
{
private:
ros::NodeHandle nh;
int print_level; // Print level to be used throughout the code
std::string name; // Name of the node
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h; // height of the image to be shown (equal to the height of the baxter display)
int w; // width of the image to be shown (equal to the width of the baxter display)
int w_d; // width of the delimiter between sub-screens
int w_b; // width of the bottom sub-screen
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
/**
* Callback for the left arm state
* @param msg the left arm state
*/
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
/**
* Callback for the right arm state
* @param msg the right arm state
*/
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
/**
* Unified callback manager for both arm states
* @param msg the arm state
* @param _limb the arm it is referred to
*/
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_INFO_COND(print_level>=4, "Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
/**
* Callback from the speech
* @param msg the speech
*/
void speechCb(const std_msgs::String& msg)
{
ROS_INFO_COND(print_level>=4, "Text: %s", msg.data.c_str());
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
/**
* Callback to delete the speech from the screen (after t=speech_duration)
*/
void deleteSpeechCb(const ros::TimerEvent&)
{
ROS_INFO_COND(print_level>=4, "Deleting speech");
setSpeech("");
displayArmStates();
};
/**
* Function to display speech on top of the generated image
* @param in the already generated image ready to be sent to the robot
*/
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
ROS_INFO_COND(print_level>=5, "Displaying speech: %s", speech.c_str());
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
int border = 20;
int max_width = 800; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontSc = 1.6;
thickn = 2;
textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
numLines = int(textSize.width/max_width);
}
ROS_INFO_COND(print_level>=6, "Size of the text %i %i numLines %i",
textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the container (line_heigth + interline)
int rec_width = 0; // Width of the container (max width of each line)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFc, fontSc, thickn, &bsline));
if (size.back().width>rec_width) { rec_width=size.back().width; }
rec_height += interline + size.back().height;
ROS_INFO_COND(print_level>=7, " Line %i: size: %i %i\ttext: %s", i,
size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols-rec_width)/2, (in.rows-w_d/2-w_b-rec_height)/2);
cv::Point rectEnd((in.cols+rec_width)/2, (in.rows-w_d/2-w_b+rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFc, fontSc, cv::Scalar::all(255), thickn, CV_AA);
textOrgy += interline;
}
}
};
/**
* Function to create sub-image for either arm
* @param _limb the arm to create the image for
* @return the sub-image
*/
cv::Mat createArmImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h-w_d/2-w_b,(w-w_d)/2,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=6, "Created %s image with size %i %i",
_limb.c_str(), img.rows, img.cols);
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_s = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_s = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFc, fontSc, thickn, &bsline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFc, fontSc, col, thickn, CV_AA);
if (state.state !=" ")
{
putText(img, "state:", cv::Point( 20,300-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300-60), fontFc, fontSc, col, thickn, CV_AA);
}
if (state.action !=" ")
{
putText(img, "action:", cv::Point( 20,400-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
if (state.object !=" ")
{
putText(img, "object:", cv::Point( 20,500-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
return img;
};
/**
* Function to create sub-image for the bottom bar (to be filled with status icons)
* @return the sub-image
*/
cv::Mat createBtmImage()
{
cv::Mat res(w_b-w_d/2,w,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=6, "Created BOTTOM image with size %i %i", res.rows, res.cols);
return res;
}
public:
/**
* Constructor
*/
explicit BaxterDisplay(string _name) : print_level(0), name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
nh.param<int> ("/print_level", print_level, 0);
h = 600;
w = 1024;
w_d = 8;
w_b = 80;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
ROS_INFO_COND(print_level>=3, "Subscribing to %s and %s", l_sub.getTopic().c_str(),
r_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Subscribing to %s", s_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Publishing to %s", im_pub.getTopic().c_str());
ROS_INFO_COND(print_level>=1, "Print Level set to %i", print_level);
ROS_INFO_COND(print_level>=1, "Speech Duration set to %g", speech_duration);
ROS_INFO_COND(print_level>=1, "Ready!!");
};
/**
* Function to set the speech to a specific value
* @param s the speech text
*/
void setSpeech(const std::string &s)
{
speech = s;
}
/**
* Function to display arm states into a single image. It combines each individual sub-image
* (the one for the left arm, the one for the right arm, and the bottom status bar)
* @return true/false if success/failure
*/
bool displayArmStates()
{
cv::Mat l = createArmImage("LEFT");
cv::Mat r = createArmImage("RIGHT");
cv::Mat b = createBtmImage();
cv::Mat d_v(r.rows,w_d,CV_8UC3,cv::Scalar::all(80)); // Vertical delimiter
cv::Mat d_h(w_d,w,CV_8UC3,cv::Scalar::all(80)); // Horizontal delimiter
ROS_INFO_COND(print_level>=5, "d_v size %i %i", d_v.rows, d_v.cols);
ROS_INFO_COND(print_level>=5, "d_h size %i %i", d_h.rows, d_h.cols);
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
// Draw sub-image for right arm
r.copyTo(res(cv::Rect(0, 0, r.cols, r.rows)));
// Draw sub-image for the vertical delimiter
d_v.copyTo(res(cv::Rect(r.cols, 0, d_v.cols, d_v.rows)));
// Draw sub-image for left arm
l.copyTo(res(cv::Rect(r.cols+d_v.cols, 0, l.cols, l.rows)));
// Draw sub-image for horizontal delimiter
d_h.copyTo(res(cv::Rect(0, r.rows, d_h.cols, d_h.rows)));
// Draw sub-image for bottom bar
b.copyTo(res(cv::Rect(0, r.rows+d_h.rows, b.cols, b.rows)));
// Eventually draw the speech on top of everything
displaySpeech(res);
// Publish the resulting image
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Apex.AI 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 "iceoryx_posh/popo/wait_set.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "iceoryx_utils/cxx/optional.hpp"
#include <iostream>
#include <thread>
// The two events the MyTriggerClass offers
enum class MyTriggerClassEvents
{
PERFORMED_ACTION,
ACTIVATE
};
// Triggerable class which has two events an both events can be
// attached to a WaitSet.
class MyTriggerClass
{
public:
MyTriggerClass() = default;
~MyTriggerClass() = default;
// IMPORTANT: For now the WaitSet does not support that the origin is moved
// or copied. To support that we have to inform the waitset about
// our new origin, otherwise the WaitSet would end up in the wrong
// memory location when it calls the `hasTriggerCallback` with the
// old origin (already moved) origin pointer. The same goes for
// the resetCallback which is used when the WaitSet goes out of scope
// and is pointing also to the old origin.
MyTriggerClass(const MyTriggerClass&) = delete;
MyTriggerClass(MyTriggerClass&&) = delete;
MyTriggerClass& operator=(const MyTriggerClass&) = delete;
MyTriggerClass& operator=(MyTriggerClass&&) = delete;
// When you call this method you will trigger the ACTIVATE event
void activate(const int activationCode) noexcept
{
m_activationCode = activationCode;
m_isActivated = true;
m_activateTrigger.trigger();
}
// Calling this method will trigger the PERFORMED_ACTION event
void performAction() noexcept
{
m_hasPerformedAction = true;
m_actionTrigger.trigger();
}
uint64_t getActivationCode() const noexcept
{
return m_activationCode;
}
// required by the m_actionTrigger to ask the class if it was triggered
bool hasPerformedAction() const noexcept
{
return m_hasPerformedAction;
}
// required by the m_activateTrigger to ask the class if it was triggered
bool isActivated() const noexcept
{
return m_isActivated;
}
// reset PERFORMED_ACTION and ACTIVATE event
void reset(const MyTriggerClassEvents event) noexcept
{
switch (event)
{
case MyTriggerClassEvents::PERFORMED_ACTION:
m_hasPerformedAction = false;
break;
case MyTriggerClassEvents::ACTIVATE:
m_isActivated = false;
break;
}
}
// This method attaches an event of the class to a waitset.
// The event is choosen by the event parameter. Additionally, you can
// set a eventId to group multiple instances and a custom callback.
iox::cxx::expected<iox::popo::WaitSetError>
attachEvent(iox::popo::WaitSet<>& waitset,
const MyTriggerClassEvents event,
const uint64_t eventId,
const iox::popo::Trigger::Callback<MyTriggerClass> callback) noexcept
{
switch (event)
{
case MyTriggerClassEvents::PERFORMED_ACTION:
{
return waitset
.acquireTriggerHandle(this,
// trigger calls this method to ask if it was triggered
{*this, &MyTriggerClass::hasPerformedAction},
// method which will be called when the waitset goes out of scope
{*this, &MyTriggerClass::invalidateTrigger},
eventId,
callback)
// assigning the acquired trigger from the waitset to m_actionTrigger
.and_then([this](iox::popo::TriggerHandle& trigger) { m_actionTrigger = std::move(trigger); });
}
case MyTriggerClassEvents::ACTIVATE:
{
return waitset
.acquireTriggerHandle(this,
// trigger calls this method to ask if it was triggered
{*this, &MyTriggerClass::isActivated},
// method which will be called when the waitset goes out of scope
{*this, &MyTriggerClass::invalidateTrigger},
eventId,
callback)
// assigning the acquired trigger from the waitset to m_activateTrigger
.and_then([this](iox::popo::TriggerHandle& trigger) { m_activateTrigger = std::move(trigger); });
}
}
return iox::cxx::success<>();
}
// we offer the waitset a method to invalidate trigger if it goes
// out of scope
void invalidateTrigger(const uint64_t uniqueTriggerId)
{
if (m_actionTrigger.getUniqueId() == uniqueTriggerId)
{
m_actionTrigger.invalidate();
}
else if (m_activateTrigger.getUniqueId() == uniqueTriggerId)
{
m_activateTrigger.invalidate();
}
}
static void callOnAction(MyTriggerClass* const triggerClassPtr)
{
std::cout << "action performed" << std::endl;
}
private:
uint64_t m_activationCode = 0U;
bool m_hasPerformedAction = false;
bool m_isActivated = false;
iox::popo::TriggerHandle m_actionTrigger;
iox::popo::TriggerHandle m_activateTrigger;
};
iox::cxx::optional<iox::popo::WaitSet<>> waitset;
iox::cxx::optional<MyTriggerClass> triggerClass;
constexpr uint64_t ACTIVATE_ID = 0U;
constexpr uint64_t ACTION_ID = 1U;
void callOnActivate(MyTriggerClass* const triggerClassPtr)
{
std::cout << "activated with code: " << triggerClassPtr->getActivationCode() << std::endl;
}
// The global event loop. It will create an infinite loop and
// will work on the incoming events.
void eventLoop()
{
while (true)
{
auto eventInfoVector = waitset->wait();
for (auto& eventInfo : eventInfoVector)
{
if (eventInfo->getEventId() == ACTIVATE_ID)
{
// reset MyTriggerClass instance state
eventInfo->getOrigin<MyTriggerClass>()->reset(MyTriggerClassEvents::ACTIVATE);
// call the callback attached to the trigger
(*eventInfo)();
}
else if (eventInfo->getEventId() == ACTION_ID)
{
// reset MyTriggerClass instance state
eventInfo->getOrigin<MyTriggerClass>()->reset(MyTriggerClassEvents::PERFORMED_ACTION);
// call the callback attached to the trigger
(*eventInfo)();
}
}
}
}
int main()
{
iox::runtime::PoshRuntime::initRuntime("/iox-ex-waitset-trigger");
// we create a waitset and a triggerClass instance inside of the two
// global optional's
waitset.emplace();
triggerClass.emplace();
// attach both events to a waitset and assign a callback
triggerClass->attachEvent(*waitset, MyTriggerClassEvents::ACTIVATE, ACTIVATE_ID, callOnActivate);
triggerClass->attachEvent(
*waitset, MyTriggerClassEvents::PERFORMED_ACTION, ACTION_ID, MyTriggerClass::callOnAction);
// start the event loop which is handling the events
std::thread eventLoopThread(eventLoop);
// start a thread which will trigger a event every second
std::thread triggerThread([&] {
int activationCode = 1;
for (auto i = 0; i < 10; ++i)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
triggerClass->activate(activationCode++);
std::this_thread::sleep_for(std::chrono::seconds(1));
triggerClass->performAction();
}
});
triggerThread.join();
eventLoopThread.join();
return (EXIT_SUCCESS);
}
<commit_msg>iox-#341 adjusted trigger example to new API<commit_after>// Copyright (c) 2020 by Apex.AI 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 "iceoryx_posh/popo/wait_set.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "iceoryx_utils/cxx/optional.hpp"
#include <iostream>
#include <thread>
// The two events the MyTriggerClass offers
enum class MyTriggerClassEvents
{
PERFORMED_ACTION,
ACTIVATE
};
// Triggerable class which has two events an both events can be
// attached to a WaitSet.
class MyTriggerClass
{
public:
MyTriggerClass() = default;
~MyTriggerClass() = default;
// IMPORTANT: For now the WaitSet does not support that the origin is moved
// or copied. To support that we have to inform the waitset about
// our new origin, otherwise the WaitSet would end up in the wrong
// memory location when it calls the `hasTriggerCallback` with the
// old origin (already moved) origin pointer. The same goes for
// the resetCallback which is used when the WaitSet goes out of scope
// and is pointing also to the old origin.
MyTriggerClass(const MyTriggerClass&) = delete;
MyTriggerClass(MyTriggerClass&&) = delete;
MyTriggerClass& operator=(const MyTriggerClass&) = delete;
MyTriggerClass& operator=(MyTriggerClass&&) = delete;
// When you call this method you will trigger the ACTIVATE event
void activate(const int activationCode) noexcept
{
m_activationCode = activationCode;
m_isActivated = true;
m_activateTrigger.trigger();
}
// Calling this method will trigger the PERFORMED_ACTION event
void performAction() noexcept
{
m_hasPerformedAction = true;
m_actionTrigger.trigger();
}
uint64_t getActivationCode() const noexcept
{
return m_activationCode;
}
// required by the m_actionTrigger to ask the class if it was triggered
bool hasPerformedAction() const noexcept
{
return m_hasPerformedAction;
}
// required by the m_activateTrigger to ask the class if it was triggered
bool isActivated() const noexcept
{
return m_isActivated;
}
// reset PERFORMED_ACTION and ACTIVATE event
void reset(const MyTriggerClassEvents event) noexcept
{
switch (event)
{
case MyTriggerClassEvents::PERFORMED_ACTION:
m_hasPerformedAction = false;
break;
case MyTriggerClassEvents::ACTIVATE:
m_isActivated = false;
break;
}
}
static void callOnAction(MyTriggerClass* const triggerClassPtr)
{
std::cout << "action performed" << std::endl;
}
template <uint64_t>
friend class iox::popo::WaitSet;
private:
// This method attaches an event of the class to a waitset.
// The event is choosen by the event parameter. Additionally, you can
// set a eventId to group multiple instances and a custom callback.
iox::cxx::expected<iox::popo::WaitSetError>
enableEvent(iox::popo::WaitSet<>& waitset,
const MyTriggerClassEvents event,
const uint64_t eventId,
const iox::popo::Trigger::Callback<MyTriggerClass> callback) noexcept
{
switch (event)
{
case MyTriggerClassEvents::PERFORMED_ACTION:
{
return waitset
.acquireTriggerHandle(this,
// trigger calls this method to ask if it was triggered
{*this, &MyTriggerClass::hasPerformedAction},
// method which will be called when the waitset goes out of scope
{*this, &MyTriggerClass::disableEvent},
eventId,
callback)
// assigning the acquired trigger from the waitset to m_actionTrigger
.and_then([this](iox::popo::TriggerHandle& trigger) { m_actionTrigger = std::move(trigger); });
}
case MyTriggerClassEvents::ACTIVATE:
{
return waitset
.acquireTriggerHandle(this,
// trigger calls this method to ask if it was triggered
{*this, &MyTriggerClass::isActivated},
// method which will be called when the waitset goes out of scope
{*this, &MyTriggerClass::disableEvent},
eventId,
callback)
// assigning the acquired trigger from the waitset to m_activateTrigger
.and_then([this](iox::popo::TriggerHandle& trigger) { m_activateTrigger = std::move(trigger); });
}
}
return iox::cxx::success<>();
}
// we offer the waitset a method to invalidate trigger if it goes
// out of scope
void disableEvent(const uint64_t uniqueTriggerId)
{
if (m_actionTrigger.getUniqueId() == uniqueTriggerId)
{
m_actionTrigger.invalidate();
}
else if (m_activateTrigger.getUniqueId() == uniqueTriggerId)
{
m_activateTrigger.invalidate();
}
}
private:
uint64_t m_activationCode = 0U;
bool m_hasPerformedAction = false;
bool m_isActivated = false;
iox::popo::TriggerHandle m_actionTrigger;
iox::popo::TriggerHandle m_activateTrigger;
};
iox::cxx::optional<iox::popo::WaitSet<>> waitset;
iox::cxx::optional<MyTriggerClass> triggerClass;
constexpr uint64_t ACTIVATE_ID = 0U;
constexpr uint64_t ACTION_ID = 1U;
void callOnActivate(MyTriggerClass* const triggerClassPtr)
{
std::cout << "activated with code: " << triggerClassPtr->getActivationCode() << std::endl;
}
// The global event loop. It will create an infinite loop and
// will work on the incoming events.
void eventLoop()
{
while (true)
{
auto eventInfoVector = waitset->wait();
for (auto& eventInfo : eventInfoVector)
{
if (eventInfo->getEventId() == ACTIVATE_ID)
{
// reset MyTriggerClass instance state
eventInfo->getOrigin<MyTriggerClass>()->reset(MyTriggerClassEvents::ACTIVATE);
// call the callback attached to the trigger
(*eventInfo)();
}
else if (eventInfo->getEventId() == ACTION_ID)
{
// reset MyTriggerClass instance state
eventInfo->getOrigin<MyTriggerClass>()->reset(MyTriggerClassEvents::PERFORMED_ACTION);
// call the callback attached to the trigger
(*eventInfo)();
}
}
}
}
int main()
{
iox::runtime::PoshRuntime::initRuntime("/iox-ex-waitset-trigger");
// we create a waitset and a triggerClass instance inside of the two
// global optional's
waitset.emplace();
triggerClass.emplace();
// attach both events to a waitset and assign a callback
waitset->attachEvent(*triggerClass, MyTriggerClassEvents::ACTIVATE, ACTIVATE_ID, callOnActivate);
waitset->attachEvent(
*triggerClass, MyTriggerClassEvents::PERFORMED_ACTION, ACTION_ID, MyTriggerClass::callOnAction);
// start the event loop which is handling the events
std::thread eventLoopThread(eventLoop);
// start a thread which will trigger a event every second
std::thread triggerThread([&] {
int activationCode = 1;
for (auto i = 0; i < 10; ++i)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
triggerClass->activate(activationCode++);
std::this_thread::sleep_for(std::chrono::seconds(1));
triggerClass->performAction();
}
});
triggerThread.join();
eventLoopThread.join();
return (EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#ifndef OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
#define OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
#include "contractor/contractor_graph.hpp"
#include "util/log.hpp"
#include "util/percent.hpp"
#include <tbb/parallel_sort.h>
#include <vector>
namespace osrm
{
namespace contractor
{
// Make sure to move in the input edge list!
template <typename InputEdgeContainer>
ContractorGraph toContractorGraph(NodeID number_of_nodes, InputEdgeContainer input_edge_list)
{
std::vector<ContractorEdge> edges;
edges.reserve(input_edge_list.size() * 2);
for (const auto &input_edge : input_edge_list)
{
if (input_edge.data.weight == INVALID_EDGE_WEIGHT)
continue;
#ifndef NDEBUG
const unsigned int constexpr DAY_IN_DECI_SECONDS = 24 * 60 * 60 * 10;
if (static_cast<unsigned int>(std::max(input_edge.data.weight, 1)) > DAY_IN_DECI_SECONDS)
{
util::Log(logWARNING) << "Edge weight large -> "
<< static_cast<unsigned int>(std::max(input_edge.data.weight, 1))
<< " : " << static_cast<unsigned int>(input_edge.source) << " -> "
<< static_cast<unsigned int>(input_edge.target);
}
#endif
edges.emplace_back(input_edge.source,
input_edge.target,
std::max(input_edge.data.weight, 1),
input_edge.data.duration,
1,
input_edge.data.turn_id,
false,
input_edge.data.forward ? true : false,
input_edge.data.backward ? true : false);
edges.emplace_back(input_edge.target,
input_edge.source,
std::max(input_edge.data.weight, 1),
input_edge.data.duration,
1,
input_edge.data.turn_id,
false,
input_edge.data.backward ? true : false,
input_edge.data.forward ? true : false);
};
tbb::parallel_sort(edges.begin(), edges.end());
NodeID edge = 0;
for (NodeID i = 0; i < edges.size();)
{
const NodeID source = edges[i].source;
const NodeID target = edges[i].target;
const NodeID id = edges[i].data.id;
// remove eigenloops
if (source == target)
{
++i;
continue;
}
ContractorEdge forward_edge;
ContractorEdge reverse_edge;
forward_edge.source = reverse_edge.source = source;
forward_edge.target = reverse_edge.target = target;
forward_edge.data.forward = reverse_edge.data.backward = true;
forward_edge.data.backward = reverse_edge.data.forward = false;
forward_edge.data.shortcut = reverse_edge.data.shortcut = false;
forward_edge.data.id = reverse_edge.data.id = id;
forward_edge.data.originalEdges = reverse_edge.data.originalEdges = 1;
forward_edge.data.weight = reverse_edge.data.weight = INVALID_EDGE_WEIGHT;
forward_edge.data.duration = reverse_edge.data.duration = MAXIMAL_EDGE_DURATION;
// remove parallel edges
while (i < edges.size() && edges[i].source == source && edges[i].target == target)
{
if (edges[i].data.forward)
{
forward_edge.data.weight = std::min(edges[i].data.weight, forward_edge.data.weight);
forward_edge.data.duration =
std::min(edges[i].data.duration, forward_edge.data.duration);
}
if (edges[i].data.backward)
{
reverse_edge.data.weight = std::min(edges[i].data.weight, reverse_edge.data.weight);
reverse_edge.data.duration =
std::min(edges[i].data.duration, reverse_edge.data.duration);
}
++i;
}
// merge edges (s,t) and (t,s) into bidirectional edge
if (forward_edge.data.weight == reverse_edge.data.weight)
{
if ((int)forward_edge.data.weight != INVALID_EDGE_WEIGHT)
{
forward_edge.data.backward = true;
edges[edge++] = forward_edge;
}
}
else
{ // insert seperate edges
if (((int)forward_edge.data.weight) != INVALID_EDGE_WEIGHT)
{
edges[edge++] = forward_edge;
}
if ((int)reverse_edge.data.weight != INVALID_EDGE_WEIGHT)
{
edges[edge++] = reverse_edge;
}
}
}
util::Log() << "merged " << edges.size() - edge << " edges out of " << edges.size();
edges.resize(edge);
return ContractorGraph{number_of_nodes, edges};
}
template <class Edge, typename GraphT> inline std::vector<Edge> toEdges(GraphT graph)
{
std::vector<Edge> edges;
edges.reserve(graph.GetNumberOfEdges());
util::UnbufferedLog log;
log << "Getting edges of minimized graph ";
util::Percent p(log, graph.GetNumberOfNodes());
const NodeID number_of_nodes = graph.GetNumberOfNodes();
if (graph.GetNumberOfNodes())
{
Edge new_edge;
for (const auto node : util::irange(0u, number_of_nodes))
{
p.PrintStatus(node);
for (auto edge : graph.GetAdjacentEdgeRange(node))
{
const NodeID target = graph.GetTarget(edge);
const ContractorGraph::EdgeData &data = graph.GetEdgeData(edge);
new_edge.source = node;
new_edge.target = target;
BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.target, "Target id invalid");
new_edge.data.weight = data.weight;
new_edge.data.duration = data.duration;
new_edge.data.shortcut = data.shortcut;
new_edge.data.turn_id = data.id;
BOOST_ASSERT_MSG(new_edge.data.turn_id != INT_MAX, // 2^31
"edge id invalid");
new_edge.data.forward = data.forward;
new_edge.data.backward = data.backward;
edges.push_back(new_edge);
}
}
}
// sort and remove duplicates
tbb::parallel_sort(edges.begin(), edges.end());
auto new_end = std::unique(edges.begin(), edges.end());
edges.resize(new_end - edges.begin());
edges.shrink_to_fit();
return edges;
}
} // namespace contractor
} // namespace osrm
#endif // OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
<commit_msg>Simplify toEdges and make it more robust against accidental memory allocations<commit_after>#ifndef OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
#define OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
#include "contractor/contractor_graph.hpp"
#include "util/log.hpp"
#include "util/percent.hpp"
#include <tbb/parallel_sort.h>
#include <vector>
namespace osrm
{
namespace contractor
{
// Make sure to move in the input edge list!
template <typename InputEdgeContainer>
ContractorGraph toContractorGraph(NodeID number_of_nodes, InputEdgeContainer input_edge_list)
{
std::vector<ContractorEdge> edges;
edges.reserve(input_edge_list.size() * 2);
for (const auto &input_edge : input_edge_list)
{
if (input_edge.data.weight == INVALID_EDGE_WEIGHT)
continue;
#ifndef NDEBUG
const unsigned int constexpr DAY_IN_DECI_SECONDS = 24 * 60 * 60 * 10;
if (static_cast<unsigned int>(std::max(input_edge.data.weight, 1)) > DAY_IN_DECI_SECONDS)
{
util::Log(logWARNING) << "Edge weight large -> "
<< static_cast<unsigned int>(std::max(input_edge.data.weight, 1))
<< " : " << static_cast<unsigned int>(input_edge.source) << " -> "
<< static_cast<unsigned int>(input_edge.target);
}
#endif
edges.emplace_back(input_edge.source,
input_edge.target,
std::max(input_edge.data.weight, 1),
input_edge.data.duration,
1,
input_edge.data.turn_id,
false,
input_edge.data.forward ? true : false,
input_edge.data.backward ? true : false);
edges.emplace_back(input_edge.target,
input_edge.source,
std::max(input_edge.data.weight, 1),
input_edge.data.duration,
1,
input_edge.data.turn_id,
false,
input_edge.data.backward ? true : false,
input_edge.data.forward ? true : false);
};
tbb::parallel_sort(edges.begin(), edges.end());
NodeID edge = 0;
for (NodeID i = 0; i < edges.size();)
{
const NodeID source = edges[i].source;
const NodeID target = edges[i].target;
const NodeID id = edges[i].data.id;
// remove eigenloops
if (source == target)
{
++i;
continue;
}
ContractorEdge forward_edge;
ContractorEdge reverse_edge;
forward_edge.source = reverse_edge.source = source;
forward_edge.target = reverse_edge.target = target;
forward_edge.data.forward = reverse_edge.data.backward = true;
forward_edge.data.backward = reverse_edge.data.forward = false;
forward_edge.data.shortcut = reverse_edge.data.shortcut = false;
forward_edge.data.id = reverse_edge.data.id = id;
forward_edge.data.originalEdges = reverse_edge.data.originalEdges = 1;
forward_edge.data.weight = reverse_edge.data.weight = INVALID_EDGE_WEIGHT;
forward_edge.data.duration = reverse_edge.data.duration = MAXIMAL_EDGE_DURATION;
// remove parallel edges
while (i < edges.size() && edges[i].source == source && edges[i].target == target)
{
if (edges[i].data.forward)
{
forward_edge.data.weight = std::min(edges[i].data.weight, forward_edge.data.weight);
forward_edge.data.duration =
std::min(edges[i].data.duration, forward_edge.data.duration);
}
if (edges[i].data.backward)
{
reverse_edge.data.weight = std::min(edges[i].data.weight, reverse_edge.data.weight);
reverse_edge.data.duration =
std::min(edges[i].data.duration, reverse_edge.data.duration);
}
++i;
}
// merge edges (s,t) and (t,s) into bidirectional edge
if (forward_edge.data.weight == reverse_edge.data.weight)
{
if ((int)forward_edge.data.weight != INVALID_EDGE_WEIGHT)
{
forward_edge.data.backward = true;
edges[edge++] = forward_edge;
}
}
else
{ // insert seperate edges
if (((int)forward_edge.data.weight) != INVALID_EDGE_WEIGHT)
{
edges[edge++] = forward_edge;
}
if ((int)reverse_edge.data.weight != INVALID_EDGE_WEIGHT)
{
edges[edge++] = reverse_edge;
}
}
}
util::Log() << "merged " << edges.size() - edge << " edges out of " << edges.size();
edges.resize(edge);
return ContractorGraph{number_of_nodes, edges};
}
template <class Edge, typename GraphT> inline std::vector<Edge> toEdges(GraphT graph)
{
util::Log() << "Converting contracted graph with " << graph.GetNumberOfEdges()
<< " to edge list (" << (graph.GetNumberOfEdges() * sizeof(Edge)) << " bytes)";
std::vector<Edge> edges(graph.GetNumberOfEdges());
{
util::UnbufferedLog log;
log << "Getting edges of minimized graph ";
util::Percent p(log, graph.GetNumberOfNodes());
const NodeID number_of_nodes = graph.GetNumberOfNodes();
std::size_t edge_index = 0;
for (const auto node : util::irange(0u, number_of_nodes))
{
p.PrintStatus(node);
for (auto edge : graph.GetAdjacentEdgeRange(node))
{
const NodeID target = graph.GetTarget(edge);
const auto &data = graph.GetEdgeData(edge);
auto &new_edge = edges[edge_index++];
new_edge.source = node;
new_edge.target = target;
BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.target, "Target id invalid");
new_edge.data.weight = data.weight;
new_edge.data.duration = data.duration;
new_edge.data.shortcut = data.shortcut;
new_edge.data.turn_id = data.id;
BOOST_ASSERT_MSG(new_edge.data.turn_id != INT_MAX, // 2^31
"edge id invalid");
new_edge.data.forward = data.forward;
new_edge.data.backward = data.backward;
}
}
BOOST_ASSERT(edge_index == edges.size());
}
tbb::parallel_sort(edges.begin(), edges.end());
return edges;
}
} // namespace contractor
} // namespace osrm
#endif // OSRM_CONTRACTOR_GRAPH_CONTRACTION_ADAPTORS_HPP_
<|endoftext|> |
<commit_before>/**
* \file
* \brief SortedContainer class header
*
* \author Copyright (C) 2014-2015 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/.
*
* \date 2015-01-10
*/
#ifndef INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
#define INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
#include <algorithm>
namespace distortos
{
namespace containers
{
/**
* \brief SortedContainerBase class is a wrapper around Container which can be used as base of SortedContainer
*
* \param Container is the underlying container, it must provide following functions: begin(), emplace(), empty(),
* end(), pop_front() and splice(). It must contain following types: allocator_type, const_iterator, iterator and
* value_type. Optionally functions erase() and size() of Container are forwarded if they exist.
*/
template<typename Container>
class SortedContainerBase
{
public:
/// iterator
using iterator = typename Container::iterator;
/// const_iterator
using const_iterator = typename Container::const_iterator;
/// value_type
using value_type = typename Container::value_type;
/// allocator_type
using allocator_type = typename Container::allocator_type;
/**
* \brief Primary template used to test presence of C::splice()
*
* \param C is the type of container that will be tested
* \param Signature is the signature of C::splice() that will be tested
*/
template<typename C, typename Signature>
struct TestHasSplice;
/**
* \brief Template used to test presence of R C::splice(Args...)
*
* \param C is the type of container that will be tested
* \param R is the type returned by tested C::splice()
* \param Args are the types of arguments for tested C::splice()
*/
template<typename C, typename R, typename... Args>
struct TestHasSplice<C, R(Args...)>
{
/**
* \brief Overload selected when R C::splice(Args...) function is present.
*
* \return std::true_type
*/
template<typename CC = C>
constexpr static auto test(CC* p) ->
typename std::is_same<decltype(p->splice(std::declval<Args>()...)), R>::type;
/**
* \brief Overload selected when R C::splice(Args...) function is not present.
*
* \return std::false_type
*/
constexpr static auto test(...) -> std::false_type;
};
/**
* \brief Predicate telling whether void Container::splice(const_iterator, Container&, const_iterator) function is
* present (it inherits from std::true_type in that case) or not (inherits from std::false_type).
*/
using HasSplice = decltype(TestHasSplice<Container, void(const_iterator, Container&, const_iterator)>::
test(std::declval<Container*>()));
/**
* \brief SortedContainerBase's constructor
*
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainerBase(const allocator_type& allocator = allocator_type{}) :
container_{allocator}
{
}
/**
* \brief Forwarding of Container::begin()
*/
decltype(std::declval<Container>().begin()) begin()
{
return container_.begin();
}
/**
* \brief Forwarding of Container::begin() const
*/
decltype(std::declval<const Container>().begin()) begin() const
{
return container_.begin();
}
/**
* \brief Forwarding of Container::empty() const
*/
decltype(std::declval<Container>().empty()) empty() const
{
return container_.empty();
}
/**
* \brief Forwarding of Container::end()
*/
decltype(std::declval<Container>().end()) end()
{
return container_.end();
}
/**
* \brief Forwarding of Container::end() const
*/
decltype(std::declval<const Container>().end()) end() const
{
return container_.end();
}
/**
* \brief Forwarding of Container::erase(...)
*
* \note forwarded only if Container::erase(Args&&...) exists
*/
template<typename... Args, typename C = Container>
auto erase(Args&&... args) -> decltype(std::declval<C>().erase(std::forward<Args>(args)...))
{
return container_.erase(std::forward<Args>(args)...);
}
/**
* \brief Forwarding of Container::pop_front()
*/
decltype(std::declval<Container>().pop_front()) pop_front()
{
return container_.pop_front();
}
/**
* \brief Forwarding of Container::size() const
*
* \note forwarded only if Container::size() const exists
*/
template<typename C = Container>
decltype(std::declval<const C>().size()) size() const
{
return container_.size();
}
protected:
/// container used for keeping elements
Container container_;
};
/**
* \brief SortedContainer class is a container that keeps the elements sorted during emplace of transfer.
*
* \note The elements are sorted as long as the user does not modify the contents via iterators.
*
* \param Container is the underlying container, it must provide following functions: begin(), emplace(), empty(),
* end(), pop_front() and splice(). It must contain following types: allocator_type, const_iterator, iterator and
* value_type. Optionally functions erase() and size() of Container are forwarded if they exist.
* \param Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order.
* \param HasSplice selects implementation - std::true_type to use Container::emplace() and Container::splice();
* std::false_type to use Container::emplace_front(), Container::splice_after() and Container::before_begin()
*/
template<typename Container, typename Compare, typename HasSplice = typename SortedContainerBase<Container>::HasSplice>
class SortedContainer : public SortedContainerBase<Container>
{
public:
/// base of SortedContainer
using Base = SortedContainerBase<Container>;
/// import iterator type alias from Base
using typename Base::iterator;
/// import const_iterator type alias from Base
using typename Base::const_iterator;
/// import value_type type alias from Base
using typename Base::value_type;
/// import allocator_type type alias from Base
using typename Base::allocator_type;
/// import Base's constructor
using Base::Base;
/**
* \brief SortedContainer's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct comparison functor
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainer(const Compare& compare = Compare{}, const allocator_type& allocator = allocator_type{}) :
Base{allocator},
compare_(compare)
{
}
/**
* \brief Sorted emplace()
*
* \param Args are types of argument for value_type constructor
*
* \param [in] args are arguments for value_type constructor
*
* \return iterator to emplaced element
*/
template<typename... Args>
iterator sortedEmplace(Args&&... args)
{
const auto it = Base::container_.emplace(Base::begin(), std::forward<Args>(args)...);
sortedSplice(*this, it);
return it;
}
/**
* \brief Sorted splice()
*
* \param [in] other is the container from which the object is transfered
* \param [in] otherPosition is the position of the transfered object in the other container
*/
void sortedSplice(SortedContainer& other, const iterator otherPosition)
{
const auto insertPosition = findInsertPosition(*otherPosition);
Base::container_.splice(insertPosition, other.container_, otherPosition);
}
private:
/**
* \brief Finds insert position that satisfies sorting criteria.
*
* Finds the insert position where Compare of current element and provided value returns true.
*
* \param [in] value is the value that is going to be emplaced/transfered
*/
iterator findInsertPosition(const value_type& value)
{
return std::find_if(Base::begin(), Base::end(),
[this, &value](const value_type& element) -> bool
{
return compare_(element, value);
}
);
}
/// instance of functor used for comparison
Compare compare_;
};
/**
* \brief SortedContainer specialization for Containers that don't have Container::emplace() and Container::splice() -
* like std::forward_list. In this case Container::emplace_front(), Container::splice_after() and
* Container::before_begin() are used.
*/
template<typename Container, typename Compare>
class SortedContainer<Container, Compare, std::false_type> : public SortedContainerBase<Container>
{
public:
/// base of SortedContainer
using Base = SortedContainerBase<Container>;
/// import iterator type alias from Base
using typename Base::iterator;
/// import const_iterator type alias from Base
using typename Base::const_iterator;
/// import value_type type alias from Base
using typename Base::value_type;
/// import allocator_type type alias from Base
using typename Base::allocator_type;
/// import Base's constructor
using Base::Base;
/**
* \brief SortedContainer's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct comparison functor
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainer(const Compare& compare = Compare{}, const allocator_type& allocator = allocator_type{}) :
Base{allocator},
compare_(compare)
{
}
/**
* \brief Sorted emplace()
*
* \param Args are types of argument for value_type constructor
*
* \param [in] args are arguments for value_type constructor
*
* \return iterator to emplaced element
*/
template<typename... Args>
iterator sortedEmplace(Args&&... args)
{
Base::container_.emplace_front(std::forward<Args>(args)...);
const auto it = Base::container_.begin();
sortedSpliceAfter(*this, Base::container_.before_begin());
return it;
}
/**
* \brief Sorted splice_after()
*
* \param [in] other is the container from which the object is transfered
* \param [in] otherPositionBefore is the position before the transfered object in the other container
*/
void sortedSpliceAfter(SortedContainer& other, const iterator otherPositionBefore)
{
const auto next = std::next(otherPositionBefore);
const auto insertPositionBefore = findInsertPositionBefore(*next);
Base::container_.splice_after(insertPositionBefore, other.container_, otherPositionBefore);
}
private:
/**
* \brief Finds insert position "before" the position that satisfies sorting criteria.
*
* Finds the insert position "before" the position where Compare of current element and provided value returns true.
*
* \param [in] value is the value that is going to be emplaced/transfered
*/
iterator findInsertPositionBefore(const value_type& value)
{
auto it = Base::container_.before_begin();
auto next = Base::container_.begin();
const auto last = Base::container_.end();
while (next != last)
{
if (compare_(*next, value) == true)
return it;
it = next;
++next;
}
return it;
}
/// instance of functor used for comparison
Compare compare_;
};
} // namespace containers
} // namespace distortos
#endif // INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
<commit_msg>SortedContainer: use iterator instead of const_iterator in prototype of Container::splice() - this fixes compilation with GCC 4.8<commit_after>/**
* \file
* \brief SortedContainer class header
*
* \author Copyright (C) 2014-2015 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/.
*
* \date 2015-01-15
*/
#ifndef INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
#define INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
#include <algorithm>
namespace distortos
{
namespace containers
{
/**
* \brief SortedContainerBase class is a wrapper around Container which can be used as base of SortedContainer
*
* \param Container is the underlying container, it must provide following functions: begin(), emplace(), empty(),
* end(), pop_front() and splice(). It must contain following types: allocator_type, const_iterator, iterator and
* value_type. Optionally functions erase() and size() of Container are forwarded if they exist.
*/
template<typename Container>
class SortedContainerBase
{
public:
/// iterator
using iterator = typename Container::iterator;
/// const_iterator
using const_iterator = typename Container::const_iterator;
/// value_type
using value_type = typename Container::value_type;
/// allocator_type
using allocator_type = typename Container::allocator_type;
/**
* \brief Primary template used to test presence of C::splice()
*
* \param C is the type of container that will be tested
* \param Signature is the signature of C::splice() that will be tested
*/
template<typename C, typename Signature>
struct TestHasSplice;
/**
* \brief Template used to test presence of R C::splice(Args...)
*
* \param C is the type of container that will be tested
* \param R is the type returned by tested C::splice()
* \param Args are the types of arguments for tested C::splice()
*/
template<typename C, typename R, typename... Args>
struct TestHasSplice<C, R(Args...)>
{
/**
* \brief Overload selected when R C::splice(Args...) function is present.
*
* \return std::true_type
*/
template<typename CC = C>
constexpr static auto test(CC* p) ->
typename std::is_same<decltype(p->splice(std::declval<Args>()...)), R>::type;
/**
* \brief Overload selected when R C::splice(Args...) function is not present.
*
* \return std::false_type
*/
constexpr static auto test(...) -> std::false_type;
};
/**
* \brief Predicate telling whether void Container::splice(iterator, Container&, iterator) function is present (it
* inherits from std::true_type in that case) or not (inherits from std::false_type).
*
* \note Correct prototype should be <em>void Container::splice(const_iterator, Container&, const_iterator)</em>,
* but libstdc++v3 used \a iterator instead of \a const_iterator until release of GCC 4.9. The prototype used below
* works in any case, as \a iterator is convertible to \a const_iterator, but not the other way around.
*/
using HasSplice = decltype(TestHasSplice<Container, void(iterator, Container&, iterator)>::
test(std::declval<Container*>()));
/**
* \brief SortedContainerBase's constructor
*
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainerBase(const allocator_type& allocator = allocator_type{}) :
container_{allocator}
{
}
/**
* \brief Forwarding of Container::begin()
*/
decltype(std::declval<Container>().begin()) begin()
{
return container_.begin();
}
/**
* \brief Forwarding of Container::begin() const
*/
decltype(std::declval<const Container>().begin()) begin() const
{
return container_.begin();
}
/**
* \brief Forwarding of Container::empty() const
*/
decltype(std::declval<Container>().empty()) empty() const
{
return container_.empty();
}
/**
* \brief Forwarding of Container::end()
*/
decltype(std::declval<Container>().end()) end()
{
return container_.end();
}
/**
* \brief Forwarding of Container::end() const
*/
decltype(std::declval<const Container>().end()) end() const
{
return container_.end();
}
/**
* \brief Forwarding of Container::erase(...)
*
* \note forwarded only if Container::erase(Args&&...) exists
*/
template<typename... Args, typename C = Container>
auto erase(Args&&... args) -> decltype(std::declval<C>().erase(std::forward<Args>(args)...))
{
return container_.erase(std::forward<Args>(args)...);
}
/**
* \brief Forwarding of Container::pop_front()
*/
decltype(std::declval<Container>().pop_front()) pop_front()
{
return container_.pop_front();
}
/**
* \brief Forwarding of Container::size() const
*
* \note forwarded only if Container::size() const exists
*/
template<typename C = Container>
decltype(std::declval<const C>().size()) size() const
{
return container_.size();
}
protected:
/// container used for keeping elements
Container container_;
};
/**
* \brief SortedContainer class is a container that keeps the elements sorted during emplace of transfer.
*
* \note The elements are sorted as long as the user does not modify the contents via iterators.
*
* \param Container is the underlying container, it must provide following functions: begin(), emplace(), empty(),
* end(), pop_front() and splice(). It must contain following types: allocator_type, const_iterator, iterator and
* value_type. Optionally functions erase() and size() of Container are forwarded if they exist.
* \param Compare is a type of functor used for comparison, std::less results in descending order, std::greater - in
* ascending order.
* \param HasSplice selects implementation - std::true_type to use Container::emplace() and Container::splice();
* std::false_type to use Container::emplace_front(), Container::splice_after() and Container::before_begin()
*/
template<typename Container, typename Compare, typename HasSplice = typename SortedContainerBase<Container>::HasSplice>
class SortedContainer : public SortedContainerBase<Container>
{
public:
/// base of SortedContainer
using Base = SortedContainerBase<Container>;
/// import iterator type alias from Base
using typename Base::iterator;
/// import const_iterator type alias from Base
using typename Base::const_iterator;
/// import value_type type alias from Base
using typename Base::value_type;
/// import allocator_type type alias from Base
using typename Base::allocator_type;
/// import Base's constructor
using Base::Base;
/**
* \brief SortedContainer's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct comparison functor
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainer(const Compare& compare = Compare{}, const allocator_type& allocator = allocator_type{}) :
Base{allocator},
compare_(compare)
{
}
/**
* \brief Sorted emplace()
*
* \param Args are types of argument for value_type constructor
*
* \param [in] args are arguments for value_type constructor
*
* \return iterator to emplaced element
*/
template<typename... Args>
iterator sortedEmplace(Args&&... args)
{
const auto it = Base::container_.emplace(Base::begin(), std::forward<Args>(args)...);
sortedSplice(*this, it);
return it;
}
/**
* \brief Sorted splice()
*
* \param [in] other is the container from which the object is transfered
* \param [in] otherPosition is the position of the transfered object in the other container
*/
void sortedSplice(SortedContainer& other, const iterator otherPosition)
{
const auto insertPosition = findInsertPosition(*otherPosition);
Base::container_.splice(insertPosition, other.container_, otherPosition);
}
private:
/**
* \brief Finds insert position that satisfies sorting criteria.
*
* Finds the insert position where Compare of current element and provided value returns true.
*
* \param [in] value is the value that is going to be emplaced/transfered
*/
iterator findInsertPosition(const value_type& value)
{
return std::find_if(Base::begin(), Base::end(),
[this, &value](const value_type& element) -> bool
{
return compare_(element, value);
}
);
}
/// instance of functor used for comparison
Compare compare_;
};
/**
* \brief SortedContainer specialization for Containers that don't have Container::emplace() and Container::splice() -
* like std::forward_list. In this case Container::emplace_front(), Container::splice_after() and
* Container::before_begin() are used.
*/
template<typename Container, typename Compare>
class SortedContainer<Container, Compare, std::false_type> : public SortedContainerBase<Container>
{
public:
/// base of SortedContainer
using Base = SortedContainerBase<Container>;
/// import iterator type alias from Base
using typename Base::iterator;
/// import const_iterator type alias from Base
using typename Base::const_iterator;
/// import value_type type alias from Base
using typename Base::value_type;
/// import allocator_type type alias from Base
using typename Base::allocator_type;
/// import Base's constructor
using Base::Base;
/**
* \brief SortedContainer's constructor
*
* \param [in] compare is a reference to Compare object used to copy-construct comparison functor
* \param [in] allocator is a reference to allocator_type object used to copy-construct allocator of container
*/
explicit SortedContainer(const Compare& compare = Compare{}, const allocator_type& allocator = allocator_type{}) :
Base{allocator},
compare_(compare)
{
}
/**
* \brief Sorted emplace()
*
* \param Args are types of argument for value_type constructor
*
* \param [in] args are arguments for value_type constructor
*
* \return iterator to emplaced element
*/
template<typename... Args>
iterator sortedEmplace(Args&&... args)
{
Base::container_.emplace_front(std::forward<Args>(args)...);
const auto it = Base::container_.begin();
sortedSpliceAfter(*this, Base::container_.before_begin());
return it;
}
/**
* \brief Sorted splice_after()
*
* \param [in] other is the container from which the object is transfered
* \param [in] otherPositionBefore is the position before the transfered object in the other container
*/
void sortedSpliceAfter(SortedContainer& other, const iterator otherPositionBefore)
{
const auto next = std::next(otherPositionBefore);
const auto insertPositionBefore = findInsertPositionBefore(*next);
Base::container_.splice_after(insertPositionBefore, other.container_, otherPositionBefore);
}
private:
/**
* \brief Finds insert position "before" the position that satisfies sorting criteria.
*
* Finds the insert position "before" the position where Compare of current element and provided value returns true.
*
* \param [in] value is the value that is going to be emplaced/transfered
*/
iterator findInsertPositionBefore(const value_type& value)
{
auto it = Base::container_.before_begin();
auto next = Base::container_.begin();
const auto last = Base::container_.end();
while (next != last)
{
if (compare_(*next, value) == true)
return it;
it = next;
++next;
}
return it;
}
/// instance of functor used for comparison
Compare compare_;
};
} // namespace containers
} // namespace distortos
#endif // INCLUDE_DISTORTOS_CONTAINERS_SORTEDCONTAINER_HPP_
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Decodes the blocks generated by block_builder.cc.
#include "table/block.h"
#include <vector>
#include <algorithm>
#include "leveldb/comparator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
inline uint32_t Block::NumRestarts() const {
assert(size_ >= 2*sizeof(uint32_t));
return DecodeFixed32(data_ + size_ - sizeof(uint32_t));
}
Block::Block(const char* data, size_t size)
: data_(data),
size_(size) {
if (size_ < sizeof(uint32_t)) {
size_ = 0; // Error marker
} else {
restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t);
if (restart_offset_ > size_ - sizeof(uint32_t)) {
// The size is too small for NumRestarts() and therefore
// restart_offset_ wrapped around.
size_ = 0;
}
}
}
Block::~Block() {
delete[] data_;
}
// Helper routine: decode the next block entry starting at "p",
// storing the number of shared key bytes, non_shared key bytes,
// and the length of the value in "*shared", "*non_shared", and
// "*value_length", respectively. Will not derefence past "limit".
//
// If any errors are detected, returns NULL. Otherwise, returns a
// pointer to the key delta (just past the three decoded values).
static inline const char* DecodeEntry(const char* p, const char* limit,
uint32_t* shared,
uint32_t* non_shared,
uint32_t* value_length) {
if (limit - p < 3) return NULL;
*shared = reinterpret_cast<const unsigned char*>(p)[0];
*non_shared = reinterpret_cast<const unsigned char*>(p)[1];
*value_length = reinterpret_cast<const unsigned char*>(p)[2];
if ((*shared | *non_shared | *value_length) < 128) {
// Fast path: all three values are encoded in one byte each
p += 3;
} else {
if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL;
}
if (static_cast<uint32>(limit - p) < (*non_shared + *value_length)) {
return NULL;
}
return p;
}
class Block::Iter : public Iterator {
private:
const Comparator* const comparator_;
const char* const data_; // underlying block contents
uint32_t const restarts_; // Offset of restart array (list of fixed32)
uint32_t const num_restarts_; // Number of uint32_t entries in restart array
// current_ is offset in data_ of current entry. >= restarts_ if !Valid
uint32_t current_;
uint32_t restart_index_; // Index of restart block in which current_ falls
std::string key_;
Slice value_;
Status status_;
inline int Compare(const Slice& a, const Slice& b) const {
return comparator_->Compare(a, b);
}
// Return the offset in data_ just past the end of the current entry.
inline uint32_t NextEntryOffset() const {
return (value_.data() + value_.size()) - data_;
}
uint32_t GetRestartPoint(uint32_t index) {
assert(index < num_restarts_);
return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t));
}
void SeekToRestartPoint(uint32_t index) {
key_.clear();
restart_index_ = index;
// current_ will be fixed by ParseNextKey();
// ParseNextKey() starts at the end of value_, so set value_ accordingly
uint32_t offset = GetRestartPoint(index);
value_ = Slice(data_ + offset, 0);
}
public:
Iter(const Comparator* comparator,
const char* data,
uint32_t restarts,
uint32_t num_restarts)
: comparator_(comparator),
data_(data),
restarts_(restarts),
num_restarts_(num_restarts),
current_(restarts_),
restart_index_(num_restarts_) {
assert(num_restarts_ > 0);
}
virtual bool Valid() const { return current_ < restarts_; }
virtual Status status() const { return status_; }
virtual Slice key() const {
assert(Valid());
return key_;
}
virtual Slice value() const {
assert(Valid());
return value_;
}
virtual void Next() {
assert(Valid());
ParseNextKey();
}
virtual void Prev() {
assert(Valid());
// Scan backwards to a restart point before current_
const uint32_t original = current_;
while (GetRestartPoint(restart_index_) >= original) {
if (restart_index_ == 0) {
// No more entries
current_ = restarts_;
restart_index_ = num_restarts_;
return;
}
restart_index_--;
}
SeekToRestartPoint(restart_index_);
do {
// Loop until end of current entry hits the start of original entry
} while (ParseNextKey() && NextEntryOffset() < original);
}
virtual void Seek(const Slice& target) {
// Binary search in restart array to find the first restart point
// with a key >= target
uint32_t left = 0;
uint32_t right = num_restarts_ - 1;
while (left < right) {
uint32_t mid = (left + right + 1) / 2;
uint32_t region_offset = GetRestartPoint(mid);
uint32_t shared, non_shared, value_length;
const char* key_ptr = DecodeEntry(data_ + region_offset,
data_ + restarts_,
&shared, &non_shared, &value_length);
if (key_ptr == NULL || (shared != 0)) {
CorruptionError();
return;
}
Slice mid_key(key_ptr, non_shared);
if (Compare(mid_key, target) < 0) {
// Key at "mid" is smaller than "target". Therefore all
// blocks before "mid" are uninteresting.
left = mid;
} else {
// Key at "mid" is >= "target". Therefore all blocks at or
// after "mid" are uninteresting.
right = mid - 1;
}
}
// Linear search (within restart block) for first key >= target
SeekToRestartPoint(left);
while (true) {
if (!ParseNextKey()) {
return;
}
if (Compare(key_, target) >= 0) {
return;
}
}
}
virtual void SeekToFirst() {
SeekToRestartPoint(0);
ParseNextKey();
}
virtual void SeekToLast() {
SeekToRestartPoint(num_restarts_ - 1);
while (ParseNextKey() && NextEntryOffset() < restarts_) {
// Keep skipping
}
}
private:
void CorruptionError() {
current_ = restarts_;
restart_index_ = num_restarts_;
status_ = Status::Corruption("bad entry in block");
key_.clear();
value_.clear();
}
bool ParseNextKey() {
current_ = NextEntryOffset();
const char* p = data_ + current_;
const char* limit = data_ + restarts_; // Restarts come right after data
if (p >= limit) {
// No more entries to return. Mark as invalid.
current_ = restarts_;
restart_index_ = num_restarts_;
return false;
}
// Decode next entry
uint32_t shared, non_shared, value_length;
p = DecodeEntry(p, limit, &shared, &non_shared, &value_length);
if (p == NULL || key_.size() < shared) {
CorruptionError();
return false;
} else {
key_.resize(shared);
key_.append(p, non_shared);
value_ = Slice(p + non_shared, value_length);
while (restart_index_ + 1 < num_restarts_ &&
GetRestartPoint(restart_index_ + 1) < current_) {
++restart_index_;
}
return true;
}
}
};
Iterator* Block::NewIterator(const Comparator* cmp) {
if (size_ < 2*sizeof(uint32_t)) {
return NewErrorIterator(Status::Corruption("bad block contents"));
}
const uint32_t num_restarts = NumRestarts();
if (num_restarts == 0) {
return NewEmptyIterator();
} else {
return new Iter(cmp, data_, restart_offset_, num_restarts);
}
}
}
<commit_msg>fix build on at least linux<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Decodes the blocks generated by block_builder.cc.
#include "table/block.h"
#include <vector>
#include <algorithm>
#include "leveldb/comparator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
inline uint32_t Block::NumRestarts() const {
assert(size_ >= 2*sizeof(uint32_t));
return DecodeFixed32(data_ + size_ - sizeof(uint32_t));
}
Block::Block(const char* data, size_t size)
: data_(data),
size_(size) {
if (size_ < sizeof(uint32_t)) {
size_ = 0; // Error marker
} else {
restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t);
if (restart_offset_ > size_ - sizeof(uint32_t)) {
// The size is too small for NumRestarts() and therefore
// restart_offset_ wrapped around.
size_ = 0;
}
}
}
Block::~Block() {
delete[] data_;
}
// Helper routine: decode the next block entry starting at "p",
// storing the number of shared key bytes, non_shared key bytes,
// and the length of the value in "*shared", "*non_shared", and
// "*value_length", respectively. Will not derefence past "limit".
//
// If any errors are detected, returns NULL. Otherwise, returns a
// pointer to the key delta (just past the three decoded values).
static inline const char* DecodeEntry(const char* p, const char* limit,
uint32_t* shared,
uint32_t* non_shared,
uint32_t* value_length) {
if (limit - p < 3) return NULL;
*shared = reinterpret_cast<const unsigned char*>(p)[0];
*non_shared = reinterpret_cast<const unsigned char*>(p)[1];
*value_length = reinterpret_cast<const unsigned char*>(p)[2];
if ((*shared | *non_shared | *value_length) < 128) {
// Fast path: all three values are encoded in one byte each
p += 3;
} else {
if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL;
if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL;
}
if (static_cast<uint32_t>(limit - p) < (*non_shared + *value_length)) {
return NULL;
}
return p;
}
class Block::Iter : public Iterator {
private:
const Comparator* const comparator_;
const char* const data_; // underlying block contents
uint32_t const restarts_; // Offset of restart array (list of fixed32)
uint32_t const num_restarts_; // Number of uint32_t entries in restart array
// current_ is offset in data_ of current entry. >= restarts_ if !Valid
uint32_t current_;
uint32_t restart_index_; // Index of restart block in which current_ falls
std::string key_;
Slice value_;
Status status_;
inline int Compare(const Slice& a, const Slice& b) const {
return comparator_->Compare(a, b);
}
// Return the offset in data_ just past the end of the current entry.
inline uint32_t NextEntryOffset() const {
return (value_.data() + value_.size()) - data_;
}
uint32_t GetRestartPoint(uint32_t index) {
assert(index < num_restarts_);
return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t));
}
void SeekToRestartPoint(uint32_t index) {
key_.clear();
restart_index_ = index;
// current_ will be fixed by ParseNextKey();
// ParseNextKey() starts at the end of value_, so set value_ accordingly
uint32_t offset = GetRestartPoint(index);
value_ = Slice(data_ + offset, 0);
}
public:
Iter(const Comparator* comparator,
const char* data,
uint32_t restarts,
uint32_t num_restarts)
: comparator_(comparator),
data_(data),
restarts_(restarts),
num_restarts_(num_restarts),
current_(restarts_),
restart_index_(num_restarts_) {
assert(num_restarts_ > 0);
}
virtual bool Valid() const { return current_ < restarts_; }
virtual Status status() const { return status_; }
virtual Slice key() const {
assert(Valid());
return key_;
}
virtual Slice value() const {
assert(Valid());
return value_;
}
virtual void Next() {
assert(Valid());
ParseNextKey();
}
virtual void Prev() {
assert(Valid());
// Scan backwards to a restart point before current_
const uint32_t original = current_;
while (GetRestartPoint(restart_index_) >= original) {
if (restart_index_ == 0) {
// No more entries
current_ = restarts_;
restart_index_ = num_restarts_;
return;
}
restart_index_--;
}
SeekToRestartPoint(restart_index_);
do {
// Loop until end of current entry hits the start of original entry
} while (ParseNextKey() && NextEntryOffset() < original);
}
virtual void Seek(const Slice& target) {
// Binary search in restart array to find the first restart point
// with a key >= target
uint32_t left = 0;
uint32_t right = num_restarts_ - 1;
while (left < right) {
uint32_t mid = (left + right + 1) / 2;
uint32_t region_offset = GetRestartPoint(mid);
uint32_t shared, non_shared, value_length;
const char* key_ptr = DecodeEntry(data_ + region_offset,
data_ + restarts_,
&shared, &non_shared, &value_length);
if (key_ptr == NULL || (shared != 0)) {
CorruptionError();
return;
}
Slice mid_key(key_ptr, non_shared);
if (Compare(mid_key, target) < 0) {
// Key at "mid" is smaller than "target". Therefore all
// blocks before "mid" are uninteresting.
left = mid;
} else {
// Key at "mid" is >= "target". Therefore all blocks at or
// after "mid" are uninteresting.
right = mid - 1;
}
}
// Linear search (within restart block) for first key >= target
SeekToRestartPoint(left);
while (true) {
if (!ParseNextKey()) {
return;
}
if (Compare(key_, target) >= 0) {
return;
}
}
}
virtual void SeekToFirst() {
SeekToRestartPoint(0);
ParseNextKey();
}
virtual void SeekToLast() {
SeekToRestartPoint(num_restarts_ - 1);
while (ParseNextKey() && NextEntryOffset() < restarts_) {
// Keep skipping
}
}
private:
void CorruptionError() {
current_ = restarts_;
restart_index_ = num_restarts_;
status_ = Status::Corruption("bad entry in block");
key_.clear();
value_.clear();
}
bool ParseNextKey() {
current_ = NextEntryOffset();
const char* p = data_ + current_;
const char* limit = data_ + restarts_; // Restarts come right after data
if (p >= limit) {
// No more entries to return. Mark as invalid.
current_ = restarts_;
restart_index_ = num_restarts_;
return false;
}
// Decode next entry
uint32_t shared, non_shared, value_length;
p = DecodeEntry(p, limit, &shared, &non_shared, &value_length);
if (p == NULL || key_.size() < shared) {
CorruptionError();
return false;
} else {
key_.resize(shared);
key_.append(p, non_shared);
value_ = Slice(p + non_shared, value_length);
while (restart_index_ + 1 < num_restarts_ &&
GetRestartPoint(restart_index_ + 1) < current_) {
++restart_index_;
}
return true;
}
}
};
Iterator* Block::NewIterator(const Comparator* cmp) {
if (size_ < 2*sizeof(uint32_t)) {
return NewErrorIterator(Status::Corruption("bad block contents"));
}
const uint32_t num_restarts = NumRestarts();
if (num_restarts == 0) {
return NewEmptyIterator();
} else {
return new Iter(cmp, data_, restart_offset_, num_restarts);
}
}
}
<|endoftext|> |
<commit_before>#include "timezonecontainer.h"
#include "timezonelistitem.h"
#include "dcptimezoneconf.h"
#include "dcptimezonedata.h"
#include "dcpspaceritem.h"
#include "dcpicuconversions.h"
#include <unicode/timezone.h>
#include <duilayout.h>
#include <duilinearlayoutpolicy.h>
#include <duigridlayoutpolicy.h>
#include <qtimer.h>
#include <duiscenemanager.h>
#include <QDebug>
static const int FIRST_LOAD_COUNT = 20;
static const int COUNT_AFTER_PROCESSEVENTS = 5;
TimeZoneContainer::TimeZoneContainer(DuiWidget *parent)
:DuiWidget(parent),
m_CheckedItem(0),
m_BackPushed(false)
{
initWidget();
}
TimeZoneContainer::~TimeZoneContainer()
{
}
void TimeZoneContainer::backPushed(bool pushed)
{
m_BackPushed = pushed;
}
void TimeZoneContainer::updateLayout()
{
for (int i = m_MainLayout->count() - 1; i >= 0; i--) {
static_cast<TimeZoneListItem*>(m_MainLayout->itemAt(i))->setVisible(false);
m_MainLayout->removeAt(i);
}
// delete policies
delete m_MainLayoutPolicy;
delete m_MainVLayoutPolicy;
m_MainLayoutPolicy = new DuiGridLayoutPolicy(m_MainLayout);
m_MainLayoutPolicy->setSpacing(10);
int columnwidth = DuiSceneManager::instance()->visibleSceneSize(
Dui::Landscape).width() / 2 - 20;
m_MainLayoutPolicy->setColumnFixedWidth(0,columnwidth);
m_MainVLayoutPolicy = new DuiLinearLayoutPolicy(m_MainLayout, Qt::Vertical);
m_MainVLayoutPolicy->setSpacing(5);
// add Items to m_MainLayoutPolicy
QListIterator<TimeZoneListItem*> iter(m_ItemList);
while (iter.hasNext()) {
TimeZoneListItem *item = iter.next();
item->setVisibleSeparator(true);
addItemToPolicies(item);
}
orientationChanged();
}
void TimeZoneContainer::addItemToPolicies(TimeZoneListItem* item)
{
if (item->isFiltered()) {
int count = m_MainLayoutPolicy->count();
m_MainLayoutPolicy->addItemAtPosition(item, count / 2, count % 2);
m_MainVLayoutPolicy->addItemAtPosition(item, count++,
Qt::AlignLeft | Qt::AlignVCenter);
item->activate();
item->setVisible(true);
item->setVisibleSeparator(false);
if (count % 2 == 1 && count > 2) {
// makes separators of previous line visible:
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(count-2))->setVisibleSeparator(true);
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(count-3))->setVisibleSeparator(true);
}
}
}
void TimeZoneContainer::addMoreItems()
{
// add items to m_ItemMap
QMultiMap<QString, DcpTimeZoneData*> zoneMap = DcpTimeZoneConf::instance()->getMap();
QMapIterator<QString, DcpTimeZoneData*> zoneIter(zoneMap);
int count = -1;
while (zoneIter.hasNext()) {
if (m_BackPushed) {
break;
}
zoneIter.next();
count++;
TimeZoneListItem *item = new TimeZoneListItem(zoneIter.value()->timeZone(),
zoneIter.value()->country(),
zoneIter.value()->gmt(),
zoneIter.value()->city(),
this);
m_ItemList << item;
connect(item, SIGNAL(clicked(TimeZoneListItem*)),
this, SLOT(itemClicked(TimeZoneListItem*)));
item->setVisible(false);
if (!m_CheckedItem) {
QString current = DcpTimeZoneConf::instance()->defaultTimeZone().city();
if (item->city() == current) {
item->checked(true);
m_CheckedItem = item;
}
}
checkIfFiltered(item);
addItemToPolicies(item);
if (count > FIRST_LOAD_COUNT && (count % COUNT_AFTER_PROCESSEVENTS == 0)) {
qApp->processEvents();
}
}
orientationChanged();
}
void TimeZoneContainer::checkIfFiltered(TimeZoneListItem* item)
{
if (item->country().startsWith(m_FilterSample, Qt::CaseInsensitive) ||
item->city().startsWith(m_FilterSample, Qt::CaseInsensitive)) {
item->filtered(true);
} else {
item->filtered(false);
}
}
void TimeZoneContainer::filter(const QString& sample)
{
if (m_FilterSample == sample) return;
m_FilterSample = sample;
QListIterator<TimeZoneListItem*> iter(m_ItemList);
while (iter.hasNext()) {
TimeZoneListItem *item = iter.next();
checkIfFiltered(item);
}
updateLayout();
}
void TimeZoneContainer::initWidget()
{
// m_MainLayout
m_MainLayout = new DuiLayout(this);
m_MainLayout->setContentsMargins(0.0, 0.0, 0.0, 0.0);
m_MainLayout->setAnimator(0);
this->setLayout(m_MainLayout);
// m_MainLayoutPolicy
m_MainLayoutPolicy = new DuiGridLayoutPolicy(m_MainLayout);
m_MainLayoutPolicy->setSpacing(10);
// m_MainVLayoutPolicy
m_MainVLayoutPolicy = new DuiLinearLayoutPolicy(m_MainLayout, Qt::Vertical);
m_MainVLayoutPolicy->setSpacing(5);
m_MainLayout->setPolicy(m_MainLayoutPolicy);
// orientation change
connect(DuiSceneManager::instance(), SIGNAL(orientationChanged(const Dui::Orientation &)),
this, SLOT(orientationChanged()));
int columnwidth = DuiSceneManager::instance()->visibleSceneSize(
Dui::Landscape).width() / 2 - 25;
m_MainLayoutPolicy->setColumnFixedWidth(0, columnwidth);
}
void TimeZoneContainer::orientationChanged()
{
DuiSceneManager *manager = DuiSceneManager::instance();
if (manager == 0)
return;
switch (manager->orientation()) {
case Dui::Landscape:
// setMinimumWidth(manager->visibleSceneSize().width()-24);
m_MainLayout->setPolicy(m_MainLayoutPolicy);
updateGridSeparator();
break;
case Dui::Portrait:
// setMinimumWidth(manager->visibleSceneSize().width()-24);
m_MainLayout->setPolicy(m_MainVLayoutPolicy);
updateHSeparator();
break;
default:
break;
}
}
void TimeZoneContainer::itemClicked(TimeZoneListItem *item)
{
if (m_CheckedItem) m_CheckedItem->checked(false);
item->checked(true);
m_CheckedItem = item;
// set default time zone
DcpTimeZoneConf::instance()->setDefaultTimeZone(item->timeZone());
}
void TimeZoneContainer::updateGridSeparator()
{
if (m_MainLayout->count() > 2) {
if (m_MainLayout->count() % 2 == 0) {
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(m_MainLayout->count() - 2))->setVisibleSeparator(false);
}
}
}
void TimeZoneContainer::updateHSeparator()
{
if (m_MainLayout->count() > 2) {
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(m_MainLayout->count() - 2))->setVisibleSeparator(true);
}
}
<commit_msg>Fixes: timezonecontainer popped up in portrait mode (started landscape size)<commit_after>#include "timezonecontainer.h"
#include "timezonelistitem.h"
#include "dcptimezoneconf.h"
#include "dcptimezonedata.h"
#include "dcpspaceritem.h"
#include "dcpicuconversions.h"
#include <unicode/timezone.h>
#include <duilayout.h>
#include <duilinearlayoutpolicy.h>
#include <duigridlayoutpolicy.h>
#include <qtimer.h>
#include <duiscenemanager.h>
#include <QDebug>
static const int FIRST_LOAD_COUNT = 20;
static const int COUNT_AFTER_PROCESSEVENTS = 5;
TimeZoneContainer::TimeZoneContainer(DuiWidget *parent)
:DuiWidget(parent),
m_CheckedItem(0),
m_BackPushed(false)
{
initWidget();
}
TimeZoneContainer::~TimeZoneContainer()
{
}
void TimeZoneContainer::backPushed(bool pushed)
{
m_BackPushed = pushed;
}
void TimeZoneContainer::updateLayout()
{
for (int i = m_MainLayout->count() - 1; i >= 0; i--) {
static_cast<TimeZoneListItem*>(m_MainLayout->itemAt(i))->setVisible(false);
m_MainLayout->removeAt(i);
}
// delete policies
delete m_MainLayoutPolicy;
delete m_MainVLayoutPolicy;
m_MainLayoutPolicy = new DuiGridLayoutPolicy(m_MainLayout);
m_MainLayoutPolicy->setSpacing(10);
int columnwidth = DuiSceneManager::instance()->visibleSceneSize(
Dui::Landscape).width() / 2 - 20;
m_MainLayoutPolicy->setColumnFixedWidth(0,columnwidth);
m_MainVLayoutPolicy = new DuiLinearLayoutPolicy(m_MainLayout, Qt::Vertical);
m_MainVLayoutPolicy->setSpacing(5);
// add Items to m_MainLayoutPolicy
QListIterator<TimeZoneListItem*> iter(m_ItemList);
while (iter.hasNext()) {
TimeZoneListItem *item = iter.next();
item->setVisibleSeparator(true);
addItemToPolicies(item);
}
orientationChanged();
}
void TimeZoneContainer::addItemToPolicies(TimeZoneListItem* item)
{
if (item->isFiltered()) {
int count = m_MainLayoutPolicy->count();
m_MainLayoutPolicy->addItemAtPosition(item, count / 2, count % 2);
m_MainVLayoutPolicy->addItemAtPosition(item, count++,
Qt::AlignLeft | Qt::AlignVCenter);
item->activate();
item->setVisible(true);
item->setVisibleSeparator(false);
if (count % 2 == 1 && count > 2) {
// makes separators of previous line visible:
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(count-2))->setVisibleSeparator(true);
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(count-3))->setVisibleSeparator(true);
}
}
}
void TimeZoneContainer::addMoreItems()
{
// add items to m_ItemMap
QMultiMap<QString, DcpTimeZoneData*> zoneMap = DcpTimeZoneConf::instance()->getMap();
QMapIterator<QString, DcpTimeZoneData*> zoneIter(zoneMap);
int count = -1;
while (zoneIter.hasNext()) {
if (m_BackPushed) {
break;
}
zoneIter.next();
count++;
TimeZoneListItem *item = new TimeZoneListItem(zoneIter.value()->timeZone(),
zoneIter.value()->country(),
zoneIter.value()->gmt(),
zoneIter.value()->city(),
this);
m_ItemList << item;
connect(item, SIGNAL(clicked(TimeZoneListItem*)),
this, SLOT(itemClicked(TimeZoneListItem*)));
item->setVisible(false);
if (!m_CheckedItem) {
QString current = DcpTimeZoneConf::instance()->defaultTimeZone().city();
if (item->city() == current) {
item->checked(true);
m_CheckedItem = item;
}
}
checkIfFiltered(item);
addItemToPolicies(item);
if (count > FIRST_LOAD_COUNT && (count % COUNT_AFTER_PROCESSEVENTS == 0)) {
qApp->processEvents();
}
}
orientationChanged();
}
void TimeZoneContainer::checkIfFiltered(TimeZoneListItem* item)
{
if (item->country().startsWith(m_FilterSample, Qt::CaseInsensitive) ||
item->city().startsWith(m_FilterSample, Qt::CaseInsensitive)) {
item->filtered(true);
} else {
item->filtered(false);
}
}
void TimeZoneContainer::filter(const QString& sample)
{
if (m_FilterSample == sample) return;
m_FilterSample = sample;
QListIterator<TimeZoneListItem*> iter(m_ItemList);
while (iter.hasNext()) {
TimeZoneListItem *item = iter.next();
checkIfFiltered(item);
}
updateLayout();
}
void TimeZoneContainer::initWidget()
{
// m_MainLayout
m_MainLayout = new DuiLayout(this);
m_MainLayout->setContentsMargins(0.0, 0.0, 0.0, 0.0);
m_MainLayout->setAnimator(0);
this->setLayout(m_MainLayout);
// m_MainLayoutPolicy
m_MainLayoutPolicy = new DuiGridLayoutPolicy(m_MainLayout);
m_MainLayoutPolicy->setSpacing(10);
// m_MainVLayoutPolicy
m_MainVLayoutPolicy = new DuiLinearLayoutPolicy(m_MainLayout, Qt::Vertical);
m_MainVLayoutPolicy->setSpacing(5);
m_MainLayout->setPolicy(m_MainLayoutPolicy);
// orientation change
connect(DuiSceneManager::instance(), SIGNAL(orientationChanged(const Dui::Orientation &)),
this, SLOT(orientationChanged()));
int columnwidth = DuiSceneManager::instance()->visibleSceneSize(
Dui::Landscape).width() / 2 - 25;
m_MainLayoutPolicy->setColumnFixedWidth(0, columnwidth);
orientationChanged();
}
void TimeZoneContainer::orientationChanged()
{
DuiSceneManager *manager = DuiSceneManager::instance();
if (manager == 0)
return;
switch (manager->orientation()) {
case Dui::Landscape:
// setMinimumWidth(manager->visibleSceneSize().width()-24);
m_MainLayout->setPolicy(m_MainLayoutPolicy);
updateGridSeparator();
break;
case Dui::Portrait:
// setMinimumWidth(manager->visibleSceneSize().width()-24);
m_MainLayout->setPolicy(m_MainVLayoutPolicy);
updateHSeparator();
break;
default:
break;
}
}
void TimeZoneContainer::itemClicked(TimeZoneListItem *item)
{
if (m_CheckedItem) m_CheckedItem->checked(false);
item->checked(true);
m_CheckedItem = item;
// set default time zone
DcpTimeZoneConf::instance()->setDefaultTimeZone(item->timeZone());
}
void TimeZoneContainer::updateGridSeparator()
{
if (m_MainLayout->count() > 2) {
if (m_MainLayout->count() % 2 == 0) {
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(m_MainLayout->count() - 2))->setVisibleSeparator(false);
}
}
}
void TimeZoneContainer::updateHSeparator()
{
if (m_MainLayout->count() > 2) {
static_cast<TimeZoneListItem*>(
m_MainLayout->itemAt(m_MainLayout->count() - 2))->setVisibleSeparator(true);
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.