text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
namespace K3 {
using std::cout;
using std::endl;
using std::bind;
// "Trigger" Declarations
void start(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
ostringstream s;
s << "(" << n << ",0,1)";
Message m = Message(defaultAddress, "fibonacci", s.str());
engine->send(m);
}
void fibonacci(shared_ptr<Engine> engine, string message_contents) {
// "bind" the triple
static const boost::regex triple_regex("\\( *(.+) *, *(.+) *, *(.+) *\\)");
boost::cmatch triple_match;
if(boost::regex_match(message_contents.c_str(), triple_match, triple_regex)){
int n = std::stoi(triple_match[1]);
int a = std::stoi(triple_match[2]);
int b = std::stoi(triple_match[3]);
// Succesful bind: trigger body:
if (n <= 1) {
// send to result
Message m = Message(defaultAddress, "result", std::to_string(b));
engine->send(m);
}
else {
// Send the next message
int new_n = n - 1;
int new_a = b;
int new_b = a + b;
ostringstream s;
s << "(" << new_n << "," << new_a << "," << new_b << ")";
Message m = Message(defaultAddress, "fibonacci", s.str());
engine->send(m);
}
}
else {
cout << "Couldn't bind args in fibonacci!" << endl;
}
}
void result(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
cout << "Fibonacci Result: " << n << endl;
}
// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
TriggerDispatch table = TriggerDispatch();
table["start"] = bind(&K3::start, engine, std::placeholders::_1);
table["fibonacci"] = bind(&K3::fibonacci, engine, std::placeholders::_1);
table["result"] = bind(&K3::result, engine, std::placeholders::_1);
return table;
}
shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
auto table = buildTable(engine);
shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
return mp;
}
// Engine setup
shared_ptr<Engine> buildEngine() {
// Configure engine components
bool simulation = true;
SystemEnvironment s_env = defaultEnvironment();
shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());
// Construct an engine
Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
return make_shared<Engine>(engine);
}
}
int main(int argc, char * argv[]) {
if (argc < 2) {
std::cout << "usage: " << argv[0] << " num" << std::endl;
return -1;
}
std::string num = argv[1];
auto engine = K3::buildEngine();
auto mp = K3::buildMP(engine);
K3::Message m = K3::Message(K3::defaultAddress, "start", num);
engine->send(m);
// Run Engine
engine->runEngine(mp);
return 0;
}<commit_msg>FibonacciTest.cpp is now an actual unit test<commit_after>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>
#include <functional>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <xUnit++/xUnit++.h>
namespace K3 {
int final = -1;
using std::cout;
using std::endl;
using std::bind;
// "Trigger" Declarations
void start(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
ostringstream s;
s << "(" << n << ",0,1)";
Message m = Message(defaultAddress, "fibonacci", s.str());
engine->send(m);
}
void fibonacci(shared_ptr<Engine> engine, string message_contents) {
// "bind" the triple
static const boost::regex triple_regex("\\( *(.+) *, *(.+) *, *(.+) *\\)");
boost::cmatch triple_match;
if(boost::regex_match(message_contents.c_str(), triple_match, triple_regex)){
int n = std::stoi(triple_match[1]);
int a = std::stoi(triple_match[2]);
int b = std::stoi(triple_match[3]);
// Succesful bind: trigger body:
if (n <= 1) {
// send to result
Message m = Message(defaultAddress, "result", std::to_string(b));
engine->send(m);
}
else {
// Send the next message
int new_n = n - 1;
int new_a = b;
int new_b = a + b;
ostringstream s;
s << "(" << new_n << "," << new_a << "," << new_b << ")";
Message m = Message(defaultAddress, "fibonacci", s.str());
engine->send(m);
}
}
else {
cout << "Couldn't bind args in fibonacci!" << endl;
}
}
void result(shared_ptr<Engine> engine, string message_contents) {
int n = std::stoi(message_contents);
final = n;
}
// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
TriggerDispatch table = TriggerDispatch();
table["start"] = bind(&K3::start, engine, std::placeholders::_1);
table["fibonacci"] = bind(&K3::fibonacci, engine, std::placeholders::_1);
table["result"] = bind(&K3::result, engine, std::placeholders::_1);
return table;
}
shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
auto table = buildTable(engine);
shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
return mp;
}
// Engine setup
shared_ptr<Engine> buildEngine() {
// Configure engine components
bool simulation = true;
SystemEnvironment s_env = defaultEnvironment();
shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());
shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());
// Construct an engine
Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);
return make_shared<Engine>(engine);
}
}
FACT("The 6th fibonacci number = 8") {
std::string num = "6";
auto engine = K3::buildEngine();
auto mp = K3::buildMP(engine);
K3::Message m = K3::Message(K3::defaultAddress, "start", num);
engine->send(m);
// Run Engine
engine->runEngine(mp);
// Check the result (the 6th fib number should = 8)
Assert.Equal(8, K3::final);
}
<|endoftext|>
|
<commit_before>// -*-c++-*-
/*
* $Id$
*
* Loader for DirectX .x files.
* Copyright (c)2002-2006 Ulrich Hertlein <u.hertlein@sandbox.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
#pragma warning (disable : 4786)
#endif
#include "mesh.h"
#include "directx.h"
#include <iostream>
#include <osg/Notify>
using namespace DX;
using namespace std;
/**********************************************************************
*
* DirectX mesh.
*
**********************************************************************/
Mesh::Mesh(Object * obj)
{
_obj = obj;
_normals = 0;
_textureCoords = 0;
_materialList = 0;
}
void Mesh::clear()
{
if (_normals) {
delete _normals;
_normals = 0;
}
if (_textureCoords) {
delete _textureCoords;
_textureCoords = 0;
}
if (_materialList) {
delete _materialList;
_materialList = 0;
}
}
bool Mesh::generateNormals(float /*creaseAngle*/)
{
//cerr << "*** generateNormals\n";
// Forget old normals
if (_normals) {
delete _normals;
_normals = 0;
}
/*
* Calculate per-face normals from face vertices.
*/
vector<Vector> faceNormals;
faceNormals.resize(_faces.size());
unsigned int fi;
for (fi = 0; fi < _faces.size(); fi++) {
vector<Vector> poly;
unsigned int n = _faces[fi].size();
if (n < 3)
continue;
for (unsigned int i = 0; i < n; i++) {
unsigned int idx = _faces[fi][i];
poly.push_back(_vertices[idx]);
}
// Edge vectors
Vector e0;
e0.x = poly[1].x - poly[0].x;
e0.y = poly[1].y - poly[0].y;
e0.z = poly[1].z - poly[0].z;
Vector e1;
e1.x = poly[2].x - poly[0].x;
e1.y = poly[2].y - poly[0].y;
e1.z = poly[2].z - poly[0].z;
// Cross-product of e0,e1
Vector normal;
normal.x = e0.y * e1.z - e0.z * e1.y;
normal.y = e0.z * e1.x - e0.x * e1.z;
normal.z = e0.x * e1.y - e0.y * e1.x;
normal.normalize();
// Add to per-face normals
faceNormals[fi] = normal;
}
/*
* Calculate per-vertex normals as average of all per-face normals that
* share this vertex. The index of the vertex normal is identical to the
* vertex index for now. This means each vertex only has a single normal...
*/
_normals = new MeshNormals;
_normals->normals.resize(_vertices.size());
for (unsigned int vi = 0; vi < _vertices.size(); vi++) {
Vector normal = { 0.0f, 0.0f, 0.0f };
unsigned int polyCount = 0;
// Collect normals of polygons that share this vertex
for (unsigned int fi = 0; fi < _faces.size(); fi++)
for (unsigned int i = 0; i < _faces[fi].size(); i++) {
unsigned int idx = _faces[fi][i];
if (idx == vi) {
normal.x += faceNormals[fi].x;
normal.y += faceNormals[fi].y;
normal.z += faceNormals[fi].z;
polyCount++;
}
}
//osg::notify(osg::INFO) << "vertex " << vi << " used by " << polyCount << " faces\n";
if (polyCount > 1) {
float polyCountRecip = 1.0f / (float) polyCount;
normal.x *= polyCountRecip;
normal.y *= polyCountRecip;
normal.z *= polyCountRecip;
normal.normalize();
}
// Add vertex normal
_normals->normals[vi] = normal;
}
// Copy face mesh to normals mesh
_normals->faceNormals.resize(_faces.size());
for (fi = 0; fi < _faces.size(); fi++)
_normals->faceNormals[fi] = _faces[fi];
return true;
}
// Parse 'Mesh'
void Mesh::parseMesh(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nVertices = 0, nFaces = 0;
//cerr << "*** Mesh\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
//cerr << "*** Mesh token=" << token[0] << endl;
if (strrchr(buf, '}') != 0) {
break;
}
else if (strrchr(buf, '{') != 0) {
if (token[0] == "MeshMaterialList")
parseMeshMaterialList(fin);
else if (token[0] == "MeshNormals")
parseMeshNormals(fin);
else if (token[0] == "MeshTextureCoords")
readMeshTexCoords(fin);
else {
//cerr << "!!! Mesh: Begin section " << token[0] << endl;
_obj->parseSection(fin);
}
}
else if (nVertices == 0) {
// Vertices
nVertices = atoi(token[0].c_str());
readVector(fin, _vertices, nVertices);
if (nVertices != _vertices.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading vertices; " << _vertices.size() << " instead of " << nVertices << endl;
}
}
else if (nFaces == 0) {
// Faces
nFaces = atoi(token[0].c_str());
readMeshFace(fin, _faces, nFaces);
if (nFaces != _faces.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading mesh; " << _faces.size() << " instead of " << nFaces << endl;
}
}
else
osg::notify(osg::INFO) << "!!! " << buf << endl;
}
}
// Parse 'MeshMaterialList'
void Mesh::parseMeshMaterialList(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nMaterials = 0, nFaceIndices = 0;
//cerr << "*** MeshMaterialList\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
// dgm - check for "{ <material name> }" for a
// material which was declared globally
#if 1
Material * material = _obj->findMaterial(token[1]);
if (material) {
_materialList->material.push_back(*material);
continue;
}
#else
bool found = false;
if (token.size() > 2) {
std::vector<Material>::iterator itr;
for (itr = _globalMaterials.begin(); itr != _globalMaterials.end(); ++itr) {
if ( (*itr).name == token[1]) {
if (!_materialList)
_materialList = new MeshMaterialList;
_materialList->material.push_back(*itr);
found = true;
break;
}
}
}
if (found)
continue;
#endif
if (strrchr(buf, '}') != 0)
break;
else if (strrchr(buf, '{') != 0) {
if (token[0] == "Material") {
Material mm;
parseMaterial(fin, mm);
_materialList->material.push_back(mm);
//cerr << "num mat=" << _materialList->material.size() << endl;
}
else {
//cerr << "!!! MeshMaterialList: Begin section " << token[0] << endl;
_obj->parseSection(fin);
}
}
else if (nMaterials == 0) {
// Create MeshMaterialList
if (!_materialList)
_materialList = new MeshMaterialList;
// Materials
nMaterials = atoi(token[0].c_str());
//cerr << "expecting num Materials=" << nMaterials << endl;
}
else if (nFaceIndices == 0) {
// Face indices
nFaceIndices = atoi(token[0].c_str());
readIndexList(fin, _materialList->faceIndices, nFaceIndices);
if (nFaceIndices != _materialList->faceIndices.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading face indices; " << nFaceIndices << " instead of " << _materialList->faceIndices.size() << endl;
}
}
}
if (nMaterials != _materialList->material.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading material list; " << nMaterials << " instead of " << _materialList->material.size() << endl;
}
}
// Parse 'MeshNormals'
void Mesh::parseMeshNormals(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nNormals = 0, nFaceNormals = 0;
//cerr << "*** MeshNormals\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
if (strrchr(buf, '}') != 0)
break;
else if (nNormals == 0) {
// Create MeshNormals
if (!_normals)
_normals = new MeshNormals;
// Normals
nNormals = atoi(token[0].c_str());
readVector(fin, _normals->normals, nNormals);
if (nNormals != _normals->normals.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading normals; " << nNormals << " instead of " << _normals->normals.size() << endl;
}
#define NORMALIZE_NORMALS
#ifdef NORMALIZE_NORMALS
for (unsigned int i = 0; i < _normals->normals.size(); i++)
_normals->normals[i].normalize();
#endif
}
else if (nFaceNormals == 0) {
// Face normals
nFaceNormals = atoi(token[0].c_str());
readMeshFace(fin, _normals->faceNormals, nFaceNormals);
if (nFaceNormals != _normals->faceNormals.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading face normals; " << nFaceNormals << " instead of " << _normals->faceNormals.size() << endl;
}
}
}
}
// Read 'MeshTextureCoords'
void Mesh::readMeshTexCoords(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nTextureCoords = 0;
//cerr << "*** MeshTextureCoords\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
if (strrchr(buf, '}') != 0)
break;
// Create MeshTextureCoords
if (!_textureCoords)
_textureCoords = new MeshTextureCoords;
// Texture coords
nTextureCoords = atoi(token[0].c_str());
readCoords2d(fin, *_textureCoords, nTextureCoords);
if (nTextureCoords != _textureCoords->size())
{
osg::notify(osg::INFO) << "DirectX loader: Error reading texcoords; " << _textureCoords->size() << " instead of " << nTextureCoords << endl;
delete _textureCoords;
_textureCoords = 0;
}
}
}
<commit_msg>Changed the index value to 0 of the token vector, wheras original the 1 was used, the later causing a crash when only one token was available. Also clean up #if #else #endif block to help make the code more readable and maintainable. This bug and fix was found by Anders Backman, but final implementation done by Robert Osfield.<commit_after>// -*-c++-*-
/*
* $Id$
*
* Loader for DirectX .x files.
* Copyright (c)2002-2006 Ulrich Hertlein <u.hertlein@sandbox.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
#pragma warning (disable : 4786)
#endif
#include "mesh.h"
#include "directx.h"
#include <iostream>
#include <osg/Notify>
using namespace DX;
using namespace std;
/**********************************************************************
*
* DirectX mesh.
*
**********************************************************************/
Mesh::Mesh(Object * obj)
{
_obj = obj;
_normals = 0;
_textureCoords = 0;
_materialList = 0;
}
void Mesh::clear()
{
if (_normals) {
delete _normals;
_normals = 0;
}
if (_textureCoords) {
delete _textureCoords;
_textureCoords = 0;
}
if (_materialList) {
delete _materialList;
_materialList = 0;
}
}
bool Mesh::generateNormals(float /*creaseAngle*/)
{
//cerr << "*** generateNormals\n";
// Forget old normals
if (_normals) {
delete _normals;
_normals = 0;
}
/*
* Calculate per-face normals from face vertices.
*/
vector<Vector> faceNormals;
faceNormals.resize(_faces.size());
unsigned int fi;
for (fi = 0; fi < _faces.size(); fi++) {
vector<Vector> poly;
unsigned int n = _faces[fi].size();
if (n < 3)
continue;
for (unsigned int i = 0; i < n; i++) {
unsigned int idx = _faces[fi][i];
poly.push_back(_vertices[idx]);
}
// Edge vectors
Vector e0;
e0.x = poly[1].x - poly[0].x;
e0.y = poly[1].y - poly[0].y;
e0.z = poly[1].z - poly[0].z;
Vector e1;
e1.x = poly[2].x - poly[0].x;
e1.y = poly[2].y - poly[0].y;
e1.z = poly[2].z - poly[0].z;
// Cross-product of e0,e1
Vector normal;
normal.x = e0.y * e1.z - e0.z * e1.y;
normal.y = e0.z * e1.x - e0.x * e1.z;
normal.z = e0.x * e1.y - e0.y * e1.x;
normal.normalize();
// Add to per-face normals
faceNormals[fi] = normal;
}
/*
* Calculate per-vertex normals as average of all per-face normals that
* share this vertex. The index of the vertex normal is identical to the
* vertex index for now. This means each vertex only has a single normal...
*/
_normals = new MeshNormals;
_normals->normals.resize(_vertices.size());
for (unsigned int vi = 0; vi < _vertices.size(); vi++) {
Vector normal = { 0.0f, 0.0f, 0.0f };
unsigned int polyCount = 0;
// Collect normals of polygons that share this vertex
for (unsigned int fi = 0; fi < _faces.size(); fi++)
for (unsigned int i = 0; i < _faces[fi].size(); i++) {
unsigned int idx = _faces[fi][i];
if (idx == vi) {
normal.x += faceNormals[fi].x;
normal.y += faceNormals[fi].y;
normal.z += faceNormals[fi].z;
polyCount++;
}
}
//osg::notify(osg::INFO) << "vertex " << vi << " used by " << polyCount << " faces\n";
if (polyCount > 1) {
float polyCountRecip = 1.0f / (float) polyCount;
normal.x *= polyCountRecip;
normal.y *= polyCountRecip;
normal.z *= polyCountRecip;
normal.normalize();
}
// Add vertex normal
_normals->normals[vi] = normal;
}
// Copy face mesh to normals mesh
_normals->faceNormals.resize(_faces.size());
for (fi = 0; fi < _faces.size(); fi++)
_normals->faceNormals[fi] = _faces[fi];
return true;
}
// Parse 'Mesh'
void Mesh::parseMesh(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nVertices = 0, nFaces = 0;
//cerr << "*** Mesh\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
//cerr << "*** Mesh token=" << token[0] << endl;
if (strrchr(buf, '}') != 0) {
break;
}
else if (strrchr(buf, '{') != 0) {
if (token[0] == "MeshMaterialList")
parseMeshMaterialList(fin);
else if (token[0] == "MeshNormals")
parseMeshNormals(fin);
else if (token[0] == "MeshTextureCoords")
readMeshTexCoords(fin);
else {
//cerr << "!!! Mesh: Begin section " << token[0] << endl;
_obj->parseSection(fin);
}
}
else if (nVertices == 0) {
// Vertices
nVertices = atoi(token[0].c_str());
readVector(fin, _vertices, nVertices);
if (nVertices != _vertices.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading vertices; " << _vertices.size() << " instead of " << nVertices << endl;
}
}
else if (nFaces == 0) {
// Faces
nFaces = atoi(token[0].c_str());
readMeshFace(fin, _faces, nFaces);
if (nFaces != _faces.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading mesh; " << _faces.size() << " instead of " << nFaces << endl;
}
}
else
osg::notify(osg::INFO) << "!!! " << buf << endl;
}
}
// Parse 'MeshMaterialList'
void Mesh::parseMeshMaterialList(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nMaterials = 0, nFaceIndices = 0;
//cerr << "*** MeshMaterialList\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
// check for "{ <material name> }" for a
// material which was declared globally
Material * material = _obj->findMaterial(token[0]);
if (material)
{
_materialList->material.push_back(*material);
continue;
}
if (strrchr(buf, '}') != 0)
break;
else if (strrchr(buf, '{') != 0) {
if (token[0] == "Material") {
Material mm;
parseMaterial(fin, mm);
_materialList->material.push_back(mm);
//cerr << "num mat=" << _materialList->material.size() << endl;
}
else {
//cerr << "!!! MeshMaterialList: Begin section " << token[0] << endl;
_obj->parseSection(fin);
}
}
else if (nMaterials == 0) {
// Create MeshMaterialList
if (!_materialList)
_materialList = new MeshMaterialList;
// Materials
nMaterials = atoi(token[0].c_str());
//cerr << "expecting num Materials=" << nMaterials << endl;
}
else if (nFaceIndices == 0) {
// Face indices
nFaceIndices = atoi(token[0].c_str());
readIndexList(fin, _materialList->faceIndices, nFaceIndices);
if (nFaceIndices != _materialList->faceIndices.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading face indices; " << nFaceIndices << " instead of " << _materialList->faceIndices.size() << endl;
}
}
}
if (nMaterials != _materialList->material.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading material list; " << nMaterials << " instead of " << _materialList->material.size() << endl;
}
}
// Parse 'MeshNormals'
void Mesh::parseMeshNormals(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nNormals = 0, nFaceNormals = 0;
//cerr << "*** MeshNormals\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
if (strrchr(buf, '}') != 0)
break;
else if (nNormals == 0) {
// Create MeshNormals
if (!_normals)
_normals = new MeshNormals;
// Normals
nNormals = atoi(token[0].c_str());
readVector(fin, _normals->normals, nNormals);
if (nNormals != _normals->normals.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading normals; " << nNormals << " instead of " << _normals->normals.size() << endl;
}
#define NORMALIZE_NORMALS
#ifdef NORMALIZE_NORMALS
for (unsigned int i = 0; i < _normals->normals.size(); i++)
_normals->normals[i].normalize();
#endif
}
else if (nFaceNormals == 0) {
// Face normals
nFaceNormals = atoi(token[0].c_str());
readMeshFace(fin, _normals->faceNormals, nFaceNormals);
if (nFaceNormals != _normals->faceNormals.size())
{
osg::notify(osg::WARN) << "DirectX loader: Error reading face normals; " << nFaceNormals << " instead of " << _normals->faceNormals.size() << endl;
}
}
}
}
// Read 'MeshTextureCoords'
void Mesh::readMeshTexCoords(ifstream& fin)
{
char buf[256];
vector<string> token;
unsigned int nTextureCoords = 0;
//cerr << "*** MeshTextureCoords\n";
while (fin.getline(buf, sizeof(buf))) {
// Tokenize
token.clear();
tokenize(buf, token);
if (token.size() == 0)
continue;
if (strrchr(buf, '}') != 0)
break;
// Create MeshTextureCoords
if (!_textureCoords)
_textureCoords = new MeshTextureCoords;
// Texture coords
nTextureCoords = atoi(token[0].c_str());
readCoords2d(fin, *_textureCoords, nTextureCoords);
if (nTextureCoords != _textureCoords->size())
{
osg::notify(osg::INFO) << "DirectX loader: Error reading texcoords; " << _textureCoords->size() << " instead of " << nTextureCoords << endl;
delete _textureCoords;
_textureCoords = 0;
}
}
}
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include <osvr/Util/UniquePtr.h>
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Util/QuatlibInteropC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <vrpn_Tracker.h>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
template <typename Predicate> class VRPNTrackerRouter : public RouterEntry {
public:
VRPNTrackerRouter(ClientContext *ctx, vrpn_Connection *conn,
const char *src, const char *dest, Predicate p)
: RouterEntry(ctx, dest),
m_remote(new vrpn_Tracker_Remote(src, conn)), m_pred(p) {
m_remote->register_change_handler(this, &VRPNTrackerRouter::handle);
}
static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
VRPNTrackerRouter *self =
static_cast<VRPNTrackerRouter *>(userdata);
if (self->m_pred(info)) {
OSVR_PoseReport report;
report.sensor = info.sensor;
OSVR_TimeValue timestamp;
osvrStructTimevalToTimeValue(×tamp, &(info.msg_time));
osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
osvrVec3FromQuatlib(&(report.pose.translation), info.pos);
for (auto const &iface : self->getContext()->getInterfaces()) {
if (iface->getPath() == self->getDest()) {
iface->triggerCallbacks(timestamp, report);
}
}
}
}
void operator()() { m_remote->mainloop(); }
private:
unique_ptr<vrpn_Tracker_Remote> m_remote;
Predicate m_pred;
};
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice = "OSVR@" + m_host;
m_conn = vrpn_get_connection_by_name(contextDevice.c_str());
/// @todo this is hardcoded routing, and not well done - just a stop-gap
/// measure.
m_addTrackerRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", "/me/hands/left",
[](vrpn_TRACKERCB const &info) { return info.sensor == 0; });
m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",
"/me/hands/right", [](vrpn_TRACKERCB const &info) {
return info.sensor == 1;
});
m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",
"/me/hands",
[](vrpn_TRACKERCB const &) { return true; });
m_addTrackerRouter(
"org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0",
"/me/head",
[](vrpn_TRACKERCB const &info) { return info.sensor == 0; });
}
VRPNContext::~VRPNContext() {}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
template <typename Predicate>
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
m_routers.emplace_back(new VRPNTrackerRouter<Predicate>(
this, m_conn.get(), src, dest, pred));
}
} // namespace client
} // namespace osvr<commit_msg>Use tared orientation from YEI tracker for /me/head<commit_after>/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<ryan@sensics.com>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNContext.h"
#include <osvr/Util/UniquePtr.h>
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Util/QuatlibInteropC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <vrpn_Tracker.h>
// Standard includes
#include <cstring>
namespace osvr {
namespace client {
RouterEntry::~RouterEntry() {}
template <typename Predicate> class VRPNTrackerRouter : public RouterEntry {
public:
VRPNTrackerRouter(ClientContext *ctx, vrpn_Connection *conn,
const char *src, const char *dest, Predicate p)
: RouterEntry(ctx, dest),
m_remote(new vrpn_Tracker_Remote(src, conn)), m_pred(p) {
m_remote->register_change_handler(this, &VRPNTrackerRouter::handle);
}
static void VRPN_CALLBACK handle(void *userdata, vrpn_TRACKERCB info) {
VRPNTrackerRouter *self =
static_cast<VRPNTrackerRouter *>(userdata);
if (self->m_pred(info)) {
OSVR_PoseReport report;
report.sensor = info.sensor;
OSVR_TimeValue timestamp;
osvrStructTimevalToTimeValue(×tamp, &(info.msg_time));
osvrQuatFromQuatlib(&(report.pose.rotation), info.quat);
osvrVec3FromQuatlib(&(report.pose.translation), info.pos);
for (auto const &iface : self->getContext()->getInterfaces()) {
if (iface->getPath() == self->getDest()) {
iface->triggerCallbacks(timestamp, report);
}
}
}
}
void operator()() { m_remote->mainloop(); }
private:
unique_ptr<vrpn_Tracker_Remote> m_remote;
Predicate m_pred;
};
VRPNContext::VRPNContext(const char appId[], const char host[])
: ::OSVR_ClientContextObject(appId), m_host(host) {
std::string contextDevice = "OSVR@" + m_host;
m_conn = vrpn_get_connection_by_name(contextDevice.c_str());
/// @todo this is hardcoded routing, and not well done - just a stop-gap
/// measure.
m_addTrackerRouter(
"org_opengoggles_bundled_Multiserver/RazerHydra0", "/me/hands/left",
[](vrpn_TRACKERCB const &info) { return info.sensor == 0; });
m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",
"/me/hands/right", [](vrpn_TRACKERCB const &info) {
return info.sensor == 1;
});
m_addTrackerRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",
"/me/hands",
[](vrpn_TRACKERCB const &) { return true; });
m_addTrackerRouter(
"org_opengoggles_bundled_Multiserver/YEI_3Space_Sensor0",
"/me/head",
[](vrpn_TRACKERCB const &info) { return info.sensor == 1; });
}
VRPNContext::~VRPNContext() {}
void VRPNContext::m_update() {
// mainloop the VRPN connection.
m_conn->mainloop();
// Process each of the routers.
for (auto const &p : m_routers) {
(*p)();
}
}
template <typename Predicate>
void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
Predicate pred) {
OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
m_routers.emplace_back(new VRPNTrackerRouter<Predicate>(
this, m_conn.get(), src, dest, pred));
}
} // namespace client
} // namespace osvr<|endoftext|>
|
<commit_before>/*
* Debug.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 01.01.09.
* code under LGPL
*
*/
#include "Debug.h"
#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
void DumpCallstackPrintf(void* callpnt) {
void *callstack[128];
int framesC = backtrace(callstack, sizeof(callstack));
printf("backtrace() returned %d addresses\n", framesC);
if(framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
char** strs = backtrace_symbols(callstack, framesC);
for(int i = 0; i < framesC; ++i) {
if(strs[i])
printf("%s\n", strs[i]);
else
break;
}
free(strs);
}
void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
void *callstack[128];
int framesC = backtrace(callstack, sizeof(callstack));
(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
char** strs = backtrace_symbols(callstack, framesC);
for(int i = 0; i < framesC; ++i) {
if(strs[i])
(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
else
break;
}
free(strs);
}
#else
void DumpCallstackPrintf() { printf("DumpCallstackPrintf() not implemented in this version.\n"); }
void DumpCallstack(void (*LineOutFct) (const std::string&)) { (*LineOutFct) ("DumpCallstack() not implemented in this version."); }
#endif
Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");
#include <iostream>
#include <sstream>
#include <SDL_thread.h>
#include "Options.h"
#include "console.h"
#include "StringUtils.h"
Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
mutex = SDL_CreateMutex();
}
Logger::~Logger() {
SDL_DestroyMutex(mutex); mutex = NULL;
}
void Logger::lock() {
SDL_mutexP(mutex);
}
void Logger::unlock() {
SDL_mutexV(mutex);
}
static void CoutPrint(const std::string& str) {
std::cout << str;
}
template<int col> void ConPrint(const std::string& str) {
// TODO: Con_AddText adds a line but we only want to add str
std::string buf = str;
if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
Con_AddText(col, buf, false);
}
// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
bool ret = true;
if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
std::cout.flush();
}
if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
DumpCallstackPrintf();
}
if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
if(!strStartsWith(buf, "Ingame console: ")) {
// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
if(log.minIngameConVerb < 0)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
else if(log.minIngameConVerb == 0)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
else if(log.minIngameConVerb == 1)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
else if(log.minIngameConVerb < 5)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
else // >=5
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
}
if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
DumpCallstack(ConPrint<CNC_DEV>);
}
}
return ret;
}
Logger& Logger::flush() {
lock();
lastWasNewline = logger_output(*this, buffer);
buffer = "";
unlock();
return *this;
}
<commit_msg>Fixed non-compiling code<commit_after>/*
* Debug.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 01.01.09.
* code under LGPL
*
*/
#include "Debug.h"
#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
void DumpCallstackPrintf(void* callpnt) {
void *callstack[128];
int framesC = backtrace(callstack, sizeof(callstack));
printf("backtrace() returned %d addresses\n", framesC);
if(framesC > 3) callstack[3] = callpnt; // expected to be called from signal handler
char** strs = backtrace_symbols(callstack, framesC);
for(int i = 0; i < framesC; ++i) {
if(strs[i])
printf("%s\n", strs[i]);
else
break;
}
free(strs);
}
void DumpCallstack(void (*PrintOutFct) (const std::string&)) {
void *callstack[128];
int framesC = backtrace(callstack, sizeof(callstack));
(*PrintOutFct) ("DumpCallstack: " + itoa(framesC) + " addresses:");
char** strs = backtrace_symbols(callstack, framesC);
for(int i = 0; i < framesC; ++i) {
if(strs[i])
(*PrintOutFct) (std::string(" ") + strs[i] + "\n");
else
break;
}
free(strs);
}
#else
void DumpCallstackPrintf(void* callpnt) { printf("DumpCallstackPrintf() not implemented in this version.\n"); }
void DumpCallstack(void (*LineOutFct) (const std::string&)) { (*LineOutFct) ("DumpCallstack() not implemented in this version."); }
#endif
Logger notes(0,2,1000, "n: ");
Logger hints(0,1,100, "H: ");
Logger warnings(0,0,10, "W: ");
Logger errors(-1,-1,1, "E: ");
#include <iostream>
#include <sstream>
#include <SDL_thread.h>
#include "Options.h"
#include "console.h"
#include "StringUtils.h"
Logger::Logger(int o, int ingame, int callst, const std::string& p)
: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {
mutex = SDL_CreateMutex();
}
Logger::~Logger() {
SDL_DestroyMutex(mutex); mutex = NULL;
}
void Logger::lock() {
SDL_mutexP(mutex);
}
void Logger::unlock() {
SDL_mutexV(mutex);
}
static void CoutPrint(const std::string& str) {
std::cout << str;
}
template<int col> void ConPrint(const std::string& str) {
// TODO: Con_AddText adds a line but we only want to add str
std::string buf = str;
if(buf.size() > 0 && buf[buf.size()-1] == '\n') buf.erase(buf.size()-1);
Con_AddText(col, buf, false);
}
// true if last was newline
static bool logger_output(Logger& log, const std::string& buf) {
bool ret = true;
if(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {
ret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);
std::cout.flush();
}
if(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {
DumpCallstackPrintf();
}
if(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {
// the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this
if(!strStartsWith(buf, "Ingame console: ")) {
// we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level
if(log.minIngameConVerb < 0)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);
else if(log.minIngameConVerb == 0)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);
else if(log.minIngameConVerb == 1)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);
else if(log.minIngameConVerb < 5)
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);
else // >=5
ret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);
}
if(tLXOptions->iVerbosity >= log.minCallstackVerb) {
DumpCallstack(ConPrint<CNC_DEV>);
}
}
return ret;
}
Logger& Logger::flush() {
lock();
lastWasNewline = logger_output(*this, buffer);
buffer = "";
unlock();
return *this;
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "nlohmann/json.hpp"
#include "inja.hpp"
using json = nlohmann::json;
TEST_CASE("types") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
data["is_sad"] = false;
SECTION("basic") {
CHECK( env.render("", data) == "" );
CHECK( env.render("Hello World!", data) == "Hello World!" );
}
/* SECTION("variables") {
CHECK( env.render("Hello {{ name }}!", data) == "Hello Peter!" );
CHECK( env.render("{{ name }}", data) == "Peter" );
CHECK( env.render("{{name}}", data) == "Peter" );
CHECK( env.render("{{ name }} is {{ age }} years old.", data) == "Peter is 29 years old." );
CHECK( env.render("Hello {{ name }}! I come from {{ city }}.", data) == "Hello Peter! I come from Brunswick." );
CHECK( env.render("Hello {{ names/1 }}!", data) == "Hello Seb!" );
CHECK( env.render("Hello {{ brother/name }}!", data) == "Hello Chris!" );
CHECK( env.render("Hello {{ brother/daughter0/name }}!", data) == "Hello Maria!" );
CHECK_THROWS_WITH( env.render("{{unknown}}", data), "Did not found json element: unknown" );
}
SECTION("comments") {
CHECK( env.render("Hello{# This is a comment #}!", data) == "Hello!" );
CHECK( env.render("{# --- #Todo --- #}", data) == "" );
}
SECTION("loops") {
CHECK( env.render("{% for name in names %}a{% endfor %}", data) == "aa" );
CHECK( env.render("Hello {% for name in names %}{{ name }} {% endfor %}!", data) == "Hello Jeff Seb !" );
CHECK( env.render("Hello {% for name in names %}{{ index }}: {{ name }}, {% endfor %}!", data) == "Hello 0: Jeff, 1: Seb, !" );
}
SECTION("conditionals") {
CHECK( env.render("{% if is_happy %}Yeah!{% endif %}", data) == "Yeah!" );
CHECK( env.render("{% if is_sad %}Yeah!{% endif %}", data) == "" );
CHECK( env.render("{% if is_sad %}Yeah!{% else %}Nooo...{% endif %}", data) == "Nooo..." );
CHECK( env.render("{% if age == 29 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age > 29 %}Right{% else %}Wrong{% endif %}", data) == "Wrong" );
CHECK( env.render("{% if age <= 29 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age != 28 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age >= 30 %}Right{% else %}Wrong{% endif %}", data) == "Wrong" );
CHECK( env.render("{% if age in [28, 29, 30] %}True{% endif %}", data) == "True" );
CHECK( env.render("{% if age == 28 %}28{% else if age == 29 %}29{% endif %}", data) == "29" );
CHECK( env.render("{% if age == 26 %}26{% else if age == 27 %}27{% else if age == 28 %}28{% else %}29{% endif %}", data) == "29" );
} */
}
/* TEST_CASE("functions") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "New York";
data["names"] = {"Jeff", "Seb", "Peter", "Tom"};
data["temperature"] = 25.6789;
SECTION("upper") {
CHECK( env.render("{{ upper(name) }}", data) == "PETER" );
CHECK( env.render("{{ upper( name ) }}", data) == "PETER" );
CHECK( env.render("{{ upper(city) }}", data) == "NEW YORK" );
CHECK( env.render("{{ upper(upper(name)) }}", data) == "PETER" );
CHECK_THROWS_WITH( env.render("{{ upper(5) }}", data), "[json.exception.type_error.302] type must be string, but is number" );
CHECK_THROWS_WITH( env.render("{{ upper(true) }}", data), "[json.exception.type_error.302] type must be string, but is boolean" );
}
SECTION("lower") {
CHECK( env.render("{{ lower(name) }}", data) == "peter" );
CHECK( env.render("{{ lower(city) }}", data) == "new york" );
CHECK_THROWS_WITH( env.render("{{ lower(5.45) }}", data), "[json.exception.type_error.302] type must be string, but is number" );
}
SECTION("range") {
CHECK( env.render("{{ range(2) }}", data) == "[0,1]" );
CHECK( env.render("{{ range(4) }}", data) == "[0,1,2,3]" );
CHECK_THROWS_WITH( env.render("{{ range(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("length") {
CHECK( env.render("{{ length(names) }}", data) == "4" );
CHECK_THROWS_WITH( env.render("{{ length(5) }}", data), "[json.exception.type_error.302] type must be array, but is number" );
}
SECTION("round") {
CHECK( env.render("{{ round(4, 0) }}", data) == "4.0" );
CHECK( env.render("{{ round(temperature, 2) }}", data) == "25.68" );
CHECK_THROWS_WITH( env.render("{{ round(name, 2) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("divisibleBy") {
CHECK( env.render("{{ divisibleBy(50, 5) }}", data) == "true" );
CHECK( env.render("{{ divisibleBy(12, 3) }}", data) == "true" );
CHECK( env.render("{{ divisibleBy(11, 3) }}", data) == "false" );
CHECK_THROWS_WITH( env.render("{{ divisibleBy(name, 2) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("odd") {
CHECK( env.render("{{ odd(11) }}", data) == "true" );
CHECK( env.render("{{ odd(12) }}", data) == "false" );
CHECK_THROWS_WITH( env.render("{{ odd(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("even") {
CHECK( env.render("{{ even(11) }}", data) == "false" );
CHECK( env.render("{{ even(12) }}", data) == "true" );
CHECK_THROWS_WITH( env.render("{{ even(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
}
TEST_CASE("combinations") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
CHECK( env.render("{% if upper(\"Peter\") == \"PETER\" %}TRUE{% endif %}", data) == "TRUE" );
CHECK( env.render("{% if lower(upper(name)) == \"peter\" %}TRUE{% endif %}", data) == "TRUE" );
CHECK( env.render("{% for i in range(4) %}{{ index1 }}{% endfor %}", data) == "1234" );
}
TEST_CASE("templates") {
inja::Environment env = inja::Environment();
inja::Template temp = env.parse("{% if is_happy %}{{ name }}{% else %}{{ city }}{% endif %}");
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["is_happy"] = true;
CHECK( temp.render(data) == "Peter" );
data["is_happy"] = false;
CHECK( temp.render(data) == "Brunswick" );
}
TEST_CASE("other-syntax") {
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
SECTION("variables") {
inja::Environment env = inja::Environment();
env.setElementNotation(inja::ElementNotation::Dot);
CHECK( env.render("{{ name }}", data) == "Peter" );
CHECK( env.render("Hello {{ names.1 }}!", data) == "Hello Seb!" );
CHECK( env.render("Hello {{ brother.name }}!", data) == "Hello Chris!" );
CHECK( env.render("Hello {{ brother.daughter0.name }}!", data) == "Hello Maria!" );
CHECK_THROWS_WITH( env.render("{{unknown}}", data), "Did not found json element: unknown" );
}
SECTION("other expression syntax") {
inja::Environment env = inja::Environment();
CHECK( env.render("Hello {{ name }}!", data) == "Hello Peter!" );
env.setExpression("\\(&", "&\\)");
CHECK( env.render("Hello {{ name }}!", data) == "Hello {{ name }}!" );
CHECK( env.render("Hello (& name &)!", data) == "Hello Peter!" );
}
SECTION("other comment syntax") {
inja::Environment env = inja::Environment();
env.setComment("\\(&", "&\\)");
CHECK( env.render("Hello {# Test #}", data) == "Hello {# Test #}" );
CHECK( env.render("Hello (& Test &)", data) == "Hello " );
}
} */
<commit_msg>temp fix some unit test for mvsc<commit_after>#include "catch.hpp"
#include "nlohmann/json.hpp"
#include "inja.hpp"
using json = nlohmann::json;
TEST_CASE("types") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
data["is_sad"] = false;
SECTION("basic") {
CHECK( env.render("", data) == "" );
CHECK( env.render("Hello World!", data) == "Hello World!" );
}
SECTION("variables") {
CHECK( env.render("Hello {{ name }}!", data) == "Hello Peter!" );
CHECK( env.render("{{ name }}", data) == "Peter" );
CHECK( env.render("{{name}}", data) == "Peter" );
CHECK( env.render("{{ name }} is {{ age }} years old.", data) == "Peter is 29 years old." );
CHECK( env.render("Hello {{ name }}! I come from {{ city }}.", data) == "Hello Peter! I come from Brunswick." );
CHECK( env.render("Hello {{ names/1 }}!", data) == "Hello Seb!" );
CHECK( env.render("Hello {{ brother/name }}!", data) == "Hello Chris!" );
CHECK( env.render("Hello {{ brother/daughter0/name }}!", data) == "Hello Maria!" );
CHECK_THROWS_WITH( env.render("{{unknown}}", data), "Did not found json element: unknown" );
}
SECTION("comments") {
CHECK( env.render("Hello{# This is a comment #}!", data) == "Hello!" );
CHECK( env.render("{# --- #Todo --- #}", data) == "" );
}
/* SECTION("loops") {
CHECK( env.render("{% for name in names %}a{% endfor %}", data) == "aa" );
CHECK( env.render("Hello {% for name in names %}{{ name }} {% endfor %}!", data) == "Hello Jeff Seb !" );
CHECK( env.render("Hello {% for name in names %}{{ index }}: {{ name }}, {% endfor %}!", data) == "Hello 0: Jeff, 1: Seb, !" );
}
SECTION("conditionals") {
CHECK( env.render("{% if is_happy %}Yeah!{% endif %}", data) == "Yeah!" );
CHECK( env.render("{% if is_sad %}Yeah!{% endif %}", data) == "" );
CHECK( env.render("{% if is_sad %}Yeah!{% else %}Nooo...{% endif %}", data) == "Nooo..." );
CHECK( env.render("{% if age == 29 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age > 29 %}Right{% else %}Wrong{% endif %}", data) == "Wrong" );
CHECK( env.render("{% if age <= 29 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age != 28 %}Right{% else %}Wrong{% endif %}", data) == "Right" );
CHECK( env.render("{% if age >= 30 %}Right{% else %}Wrong{% endif %}", data) == "Wrong" );
CHECK( env.render("{% if age in [28, 29, 30] %}True{% endif %}", data) == "True" );
CHECK( env.render("{% if age == 28 %}28{% else if age == 29 %}29{% endif %}", data) == "29" );
CHECK( env.render("{% if age == 26 %}26{% else if age == 27 %}27{% else if age == 28 %}28{% else %}29{% endif %}", data) == "29" );
} */
}
/* TEST_CASE("functions") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "New York";
data["names"] = {"Jeff", "Seb", "Peter", "Tom"};
data["temperature"] = 25.6789;
SECTION("upper") {
CHECK( env.render("{{ upper(name) }}", data) == "PETER" );
CHECK( env.render("{{ upper( name ) }}", data) == "PETER" );
CHECK( env.render("{{ upper(city) }}", data) == "NEW YORK" );
CHECK( env.render("{{ upper(upper(name)) }}", data) == "PETER" );
CHECK_THROWS_WITH( env.render("{{ upper(5) }}", data), "[json.exception.type_error.302] type must be string, but is number" );
CHECK_THROWS_WITH( env.render("{{ upper(true) }}", data), "[json.exception.type_error.302] type must be string, but is boolean" );
}
SECTION("lower") {
CHECK( env.render("{{ lower(name) }}", data) == "peter" );
CHECK( env.render("{{ lower(city) }}", data) == "new york" );
CHECK_THROWS_WITH( env.render("{{ lower(5.45) }}", data), "[json.exception.type_error.302] type must be string, but is number" );
}
SECTION("range") {
CHECK( env.render("{{ range(2) }}", data) == "[0,1]" );
CHECK( env.render("{{ range(4) }}", data) == "[0,1,2,3]" );
CHECK_THROWS_WITH( env.render("{{ range(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("length") {
CHECK( env.render("{{ length(names) }}", data) == "4" );
CHECK_THROWS_WITH( env.render("{{ length(5) }}", data), "[json.exception.type_error.302] type must be array, but is number" );
}
SECTION("round") {
CHECK( env.render("{{ round(4, 0) }}", data) == "4.0" );
CHECK( env.render("{{ round(temperature, 2) }}", data) == "25.68" );
CHECK_THROWS_WITH( env.render("{{ round(name, 2) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("divisibleBy") {
CHECK( env.render("{{ divisibleBy(50, 5) }}", data) == "true" );
CHECK( env.render("{{ divisibleBy(12, 3) }}", data) == "true" );
CHECK( env.render("{{ divisibleBy(11, 3) }}", data) == "false" );
CHECK_THROWS_WITH( env.render("{{ divisibleBy(name, 2) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("odd") {
CHECK( env.render("{{ odd(11) }}", data) == "true" );
CHECK( env.render("{{ odd(12) }}", data) == "false" );
CHECK_THROWS_WITH( env.render("{{ odd(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
SECTION("even") {
CHECK( env.render("{{ even(11) }}", data) == "false" );
CHECK( env.render("{{ even(12) }}", data) == "true" );
CHECK_THROWS_WITH( env.render("{{ even(name) }}", data), "[json.exception.type_error.302] type must be number, but is string" );
}
}
TEST_CASE("combinations") {
inja::Environment env = inja::Environment();
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
CHECK( env.render("{% if upper(\"Peter\") == \"PETER\" %}TRUE{% endif %}", data) == "TRUE" );
CHECK( env.render("{% if lower(upper(name)) == \"peter\" %}TRUE{% endif %}", data) == "TRUE" );
CHECK( env.render("{% for i in range(4) %}{{ index1 }}{% endfor %}", data) == "1234" );
}
TEST_CASE("templates") {
inja::Environment env = inja::Environment();
inja::Template temp = env.parse("{% if is_happy %}{{ name }}{% else %}{{ city }}{% endif %}");
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["is_happy"] = true;
CHECK( temp.render(data) == "Peter" );
data["is_happy"] = false;
CHECK( temp.render(data) == "Brunswick" );
}
TEST_CASE("other-syntax") {
json data;
data["name"] = "Peter";
data["city"] = "Brunswick";
data["age"] = 29;
data["names"] = {"Jeff", "Seb"};
data["brother"]["name"] = "Chris";
data["brother"]["daughters"] = {"Maria", "Helen"};
data["brother"]["daughter0"] = { { "name", "Maria" } };
data["is_happy"] = true;
SECTION("variables") {
inja::Environment env = inja::Environment();
env.setElementNotation(inja::ElementNotation::Dot);
CHECK( env.render("{{ name }}", data) == "Peter" );
CHECK( env.render("Hello {{ names.1 }}!", data) == "Hello Seb!" );
CHECK( env.render("Hello {{ brother.name }}!", data) == "Hello Chris!" );
CHECK( env.render("Hello {{ brother.daughter0.name }}!", data) == "Hello Maria!" );
CHECK_THROWS_WITH( env.render("{{unknown}}", data), "Did not found json element: unknown" );
}
SECTION("other expression syntax") {
inja::Environment env = inja::Environment();
CHECK( env.render("Hello {{ name }}!", data) == "Hello Peter!" );
env.setExpression("\\(&", "&\\)");
CHECK( env.render("Hello {{ name }}!", data) == "Hello {{ name }}!" );
CHECK( env.render("Hello (& name &)!", data) == "Hello Peter!" );
}
SECTION("other comment syntax") {
inja::Environment env = inja::Environment();
env.setComment("\\(&", "&\\)");
CHECK( env.render("Hello {# Test #}", data) == "Hello {# Test #}" );
CHECK( env.render("Hello (& Test &)", data) == "Hello " );
}
} */
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// debug.cpp: Debugging utilities.
#include "common/debug.h"
#include <stdarg.h>
#include <array>
#include <cstdio>
#include <fstream>
#include <ostream>
#include <vector>
#include "common/angleutils.h"
#include "common/Optional.h"
namespace gl
{
namespace
{
DebugAnnotator *g_debugAnnotator = nullptr;
constexpr std::array<const char *, LOG_NUM_SEVERITIES> g_logSeverityNames = {
{"EVENT", "WARN", "ERR"}};
constexpr const char *LogSeverityName(int severity)
{
return (severity >= 0 && severity < LOG_NUM_SEVERITIES) ? g_logSeverityNames[severity]
: "UNKNOWN";
}
bool ShouldCreateLogMessage(LogSeverity severity)
{
#if defined(ANGLE_TRACE_ENABLED)
return true;
#elif defined(ANGLE_ENABLE_ASSERTS)
return severity == LOG_ERR;
#else
return false;
#endif
}
} // namespace
namespace priv
{
bool ShouldCreatePlatformLogMessage(LogSeverity severity)
{
#if defined(ANGLE_TRACE_ENABLED)
return true;
#else
return severity != LOG_EVENT;
#endif
}
} // namespace priv
bool DebugAnnotationsActive()
{
#if defined(ANGLE_ENABLE_DEBUG_ANNOTATIONS)
return g_debugAnnotator != nullptr && g_debugAnnotator->getStatus();
#else
return false;
#endif
}
bool DebugAnnotationsInitialized()
{
return g_debugAnnotator != nullptr;
}
void InitializeDebugAnnotations(DebugAnnotator *debugAnnotator)
{
UninitializeDebugAnnotations();
g_debugAnnotator = debugAnnotator;
}
void UninitializeDebugAnnotations()
{
// Pointer is not managed.
g_debugAnnotator = nullptr;
}
ScopedPerfEventHelper::ScopedPerfEventHelper(const char *format, ...)
{
#if !defined(ANGLE_ENABLE_DEBUG_TRACE)
if (!DebugAnnotationsActive())
{
return;
}
#endif // !ANGLE_ENABLE_DEBUG_TRACE
va_list vararg;
va_start(vararg, format);
std::vector<char> buffer(512);
size_t len = FormatStringIntoVector(format, vararg, buffer);
ANGLE_LOG(EVENT) << std::string(&buffer[0], len);
va_end(vararg);
}
ScopedPerfEventHelper::~ScopedPerfEventHelper()
{
if (DebugAnnotationsActive())
{
g_debugAnnotator->endEvent();
}
}
LogMessage::LogMessage(const char *function, int line, LogSeverity severity)
: mFunction(function), mLine(line), mSeverity(severity)
{
// EVENT() does not require additional function(line) info.
if (mSeverity != LOG_EVENT)
{
mStream << mFunction << "(" << mLine << "): ";
}
}
LogMessage::~LogMessage()
{
if (DebugAnnotationsInitialized() && (mSeverity == LOG_ERR || mSeverity == LOG_WARN))
{
g_debugAnnotator->logMessage(*this);
}
else
{
Trace(getSeverity(), getMessage().c_str());
}
}
void Trace(LogSeverity severity, const char *message)
{
if (!ShouldCreateLogMessage(severity))
{
return;
}
std::string str(message);
if (DebugAnnotationsActive())
{
std::wstring formattedWideMessage(str.begin(), str.end());
switch (severity)
{
case LOG_EVENT:
g_debugAnnotator->beginEvent(formattedWideMessage.c_str());
break;
default:
g_debugAnnotator->setMarker(formattedWideMessage.c_str());
break;
}
}
if (severity == LOG_ERR)
{
// Note: we use fprintf because <iostream> includes static initializers.
fprintf(stderr, "%s: %s\n", LogSeverityName(severity), str.c_str());
}
#if defined(ANGLE_PLATFORM_WINDOWS) && \
(defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER) || !defined(NDEBUG))
#if !defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER)
if (severity == LOG_ERR)
#endif // !defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER)
{
OutputDebugStringA(str.c_str());
}
#endif
#if defined(ANGLE_ENABLE_DEBUG_TRACE)
#if defined(NDEBUG)
if (severity == LOG_EVENT || severity == LOG_WARN)
{
return;
}
#endif // defined(NDEBUG)
static std::ofstream file(TRACE_OUTPUT_FILE, std::ofstream::app);
if (file)
{
file << LogSeverityName(severity) << ": " << str << std::endl;
file.flush();
}
#endif // defined(ANGLE_ENABLE_DEBUG_TRACE)
}
LogSeverity LogMessage::getSeverity() const
{
return mSeverity;
}
std::string LogMessage::getMessage() const
{
return mStream.str();
}
#if defined(ANGLE_PLATFORM_WINDOWS)
std::ostream &operator<<(std::ostream &os, const FmtHR &fmt)
{
os << "HRESULT: ";
return FmtHexInt(os, fmt.mHR);
}
std::ostream &operator<<(std::ostream &os, const FmtErr &fmt)
{
os << "error: ";
return FmtHexInt(os, fmt.mErr);
}
#endif // defined(ANGLE_PLATFORM_WINDOWS)
} // namespace gl
<commit_msg>Print more logs when using default Platform<commit_after>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// debug.cpp: Debugging utilities.
#include "common/debug.h"
#include <stdarg.h>
#include <array>
#include <cstdio>
#include <fstream>
#include <ostream>
#include <vector>
#if defined(ANGLE_PLATFORM_ANDROID)
#include <android/log.h>
#endif
#include "common/angleutils.h"
#include "common/Optional.h"
namespace gl
{
namespace
{
DebugAnnotator *g_debugAnnotator = nullptr;
constexpr std::array<const char *, LOG_NUM_SEVERITIES> g_logSeverityNames = {
{"EVENT", "WARN", "ERR"}};
constexpr const char *LogSeverityName(int severity)
{
return (severity >= 0 && severity < LOG_NUM_SEVERITIES) ? g_logSeverityNames[severity]
: "UNKNOWN";
}
bool ShouldCreateLogMessage(LogSeverity severity)
{
#if defined(ANGLE_TRACE_ENABLED)
return true;
#elif defined(ANGLE_ENABLE_ASSERTS)
return severity == LOG_ERR;
#else
return false;
#endif
}
} // namespace
namespace priv
{
bool ShouldCreatePlatformLogMessage(LogSeverity severity)
{
#if defined(ANGLE_TRACE_ENABLED)
return true;
#else
return severity != LOG_EVENT;
#endif
}
} // namespace priv
bool DebugAnnotationsActive()
{
#if defined(ANGLE_ENABLE_DEBUG_ANNOTATIONS)
return g_debugAnnotator != nullptr && g_debugAnnotator->getStatus();
#else
return false;
#endif
}
bool DebugAnnotationsInitialized()
{
return g_debugAnnotator != nullptr;
}
void InitializeDebugAnnotations(DebugAnnotator *debugAnnotator)
{
UninitializeDebugAnnotations();
g_debugAnnotator = debugAnnotator;
}
void UninitializeDebugAnnotations()
{
// Pointer is not managed.
g_debugAnnotator = nullptr;
}
ScopedPerfEventHelper::ScopedPerfEventHelper(const char *format, ...)
{
#if !defined(ANGLE_ENABLE_DEBUG_TRACE)
if (!DebugAnnotationsActive())
{
return;
}
#endif // !ANGLE_ENABLE_DEBUG_TRACE
va_list vararg;
va_start(vararg, format);
std::vector<char> buffer(512);
size_t len = FormatStringIntoVector(format, vararg, buffer);
ANGLE_LOG(EVENT) << std::string(&buffer[0], len);
va_end(vararg);
}
ScopedPerfEventHelper::~ScopedPerfEventHelper()
{
if (DebugAnnotationsActive())
{
g_debugAnnotator->endEvent();
}
}
LogMessage::LogMessage(const char *function, int line, LogSeverity severity)
: mFunction(function), mLine(line), mSeverity(severity)
{
// EVENT() does not require additional function(line) info.
if (mSeverity != LOG_EVENT)
{
mStream << mFunction << "(" << mLine << "): ";
}
}
LogMessage::~LogMessage()
{
if (DebugAnnotationsInitialized() && (mSeverity == LOG_ERR || mSeverity == LOG_WARN))
{
g_debugAnnotator->logMessage(*this);
}
else
{
Trace(getSeverity(), getMessage().c_str());
}
}
void Trace(LogSeverity severity, const char *message)
{
if (!ShouldCreateLogMessage(severity))
{
return;
}
std::string str(message);
if (DebugAnnotationsActive())
{
std::wstring formattedWideMessage(str.begin(), str.end());
switch (severity)
{
case LOG_EVENT:
g_debugAnnotator->beginEvent(formattedWideMessage.c_str());
break;
default:
g_debugAnnotator->setMarker(formattedWideMessage.c_str());
break;
}
}
if (severity == LOG_ERR || severity == LOG_WARN)
{
#if defined(ANGLE_PLATFORM_ANDROID)
__android_log_print((severity == LOG_ERR) ? ANDROID_LOG_ERROR : ANDROID_LOG_WARN, "ANGLE",
"%s: %s\n", LogSeverityName(severity), str.c_str());
#else
// Note: we use fprintf because <iostream> includes static initializers.
fprintf((severity == LOG_ERR) ? stderr : stdout, "%s: %s\n", LogSeverityName(severity),
str.c_str());
#endif
}
#if defined(ANGLE_PLATFORM_WINDOWS) && \
(defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER) || !defined(NDEBUG))
#if !defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER)
if (severity == LOG_ERR)
#endif // !defined(ANGLE_ENABLE_DEBUG_TRACE_TO_DEBUGGER)
{
OutputDebugStringA(str.c_str());
}
#endif
#if defined(ANGLE_ENABLE_DEBUG_TRACE)
#if defined(NDEBUG)
if (severity == LOG_EVENT || severity == LOG_WARN)
{
return;
}
#endif // defined(NDEBUG)
static std::ofstream file(TRACE_OUTPUT_FILE, std::ofstream::app);
if (file)
{
file << LogSeverityName(severity) << ": " << str << std::endl;
file.flush();
}
#endif // defined(ANGLE_ENABLE_DEBUG_TRACE)
}
LogSeverity LogMessage::getSeverity() const
{
return mSeverity;
}
std::string LogMessage::getMessage() const
{
return mStream.str();
}
#if defined(ANGLE_PLATFORM_WINDOWS)
std::ostream &operator<<(std::ostream &os, const FmtHR &fmt)
{
os << "HRESULT: ";
return FmtHexInt(os, fmt.mHR);
}
std::ostream &operator<<(std::ostream &os, const FmtErr &fmt)
{
os << "error: ";
return FmtHexInt(os, fmt.mErr);
}
#endif // defined(ANGLE_PLATFORM_WINDOWS)
} // namespace gl
<|endoftext|>
|
<commit_before>/**
* \file PancakeInstance.cpp
*
*
*
* \author eaburns
* \date 18-01-2010
*/
#include <boost/array.hpp>
#include "pancake/PancakeInstance.hpp"
#include "pancake/PancakeState.hpp"
#include <vector>
PancakeInstance14::PancakeInstance14 *PancakeInstance14::read(std::istream &in)
{
unsigned int ncakes;
in >> ncakes;
if (ncakes != 14) {
std::cerr << "Invalid number of pancakes, expected 14, "
<< "got " << ncakes << std::endl;
return NULL;
}
PancakeState14 *start = PancakeState14::read(in);
if (!start)
return NULL;
PancakeState14 cgoal = PancakeState14::canonical_goal();
PancakeState14 *goal = new PancakeState14(cgoal);
return new PancakeInstance14(*start, *goal);
}
// Compute a simple abstraction order that blanks out one more tile
// each level.
PancakeInstance14::AbstractionOrder
PancakeInstance14::simple_abstraction_order(const PancakeState14 &s)
{
AbstractionOrder abst;
unsigned int ncakes = abst[0].size();
for (unsigned int lvl = 0;
lvl <= PancakeInstance14::num_abstraction_levels;
lvl += 1) {
for (unsigned int i = 0; i < ncakes; i += 1) {
if (lvl == 0)
abst[lvl][i] = false;
else if (i < ncakes - (num_abstraction_levels - lvl))
abst[lvl][i] = true;
else
abst[lvl][i] = false;
}
}
return abst;
}
PancakeInstance14::PancakeInstance14(const PancakeState14 &s,
const PancakeState14 &g)
: start(s),
goal(g),
abstraction_order(simple_abstraction_order(s))
{ }
PancakeNode14 *PancakeInstance14::child(const PancakeState14 &new_state,
PancakeCost new_g,
const PancakeNode14 &parent,
boost::pool<> &node_pool)
{
assert(!(parent.get_state() == new_state));
assert((parent.get_parent() == NULL)
|| !(new_state == parent.get_parent()->get_state()));
PancakeNode14 *child_node =
new (node_pool.malloc()) PancakeNode14(new_state,
new_g,
0,
&parent);
return child_node;
}
void PancakeInstance14::compute_successors(const PancakeNode14 &node,
std::vector<PancakeNode14*> &succs,
boost::pool<> &node_pool)
{
const PancakeNode14 *gp = node.get_parent();
succs.clear();
for (unsigned int n = 2; n <= 14; n += 1) {
const PancakeState14 child_state = node.get_state().flip(n);
if (!(gp && gp->get_state() == child_state)) {
PancakeNode14 *child_node = child(child_state,
node.get_g() + 1,
node,
node_pool);
succs.push_back(child_node);
}
}
}
void
PancakeInstance14::compute_predecessors(const PancakeNode14 &n,
std::vector<PancakeNode14*> &succs,
boost::pool<> &node_pool)
{
compute_successors(n, succs, node_pool);
}
void PancakeInstance14::compute_heuristic(const PancakeNode14 &parent,
PancakeNode14 &child) const
{
compute_heuristic(child);
}
void PancakeInstance14::compute_heuristic(PancakeNode14 &child) const
{
// Just use h(n) = 0 for now, I guess.
child.set_h(0);
}
bool
PancakeInstance14::should_abstract(unsigned int level, unsigned int i) const
{
return abstraction_order[level][i - 1];
}
const PancakeState14 &PancakeInstance14::get_start_state() const
{
return start;
}
const PancakeState14 &PancakeInstance14::get_goal_state() const
{
return goal;
}
PancakeState14 PancakeInstance14::abstract(unsigned int level,
const PancakeState14 &s) const
{
std::vector<Pancake> cakes = s.get_cakes();
boost::array<Pancake, 14> new_cakes;
for (unsigned int i = 0; i < cakes.size(); i += 1) {
if (should_abstract(level, cakes[i]))
new_cakes[i] = -1;
else
new_cakes[i] = cakes[i];
}
return PancakeState14(new_cakes);
}
<commit_msg>Don't generate the parent state as a child state when abstraction.<commit_after>/**
* \file PancakeInstance.cpp
*
*
*
* \author eaburns
* \date 18-01-2010
*/
#include <boost/array.hpp>
#include "pancake/PancakeInstance.hpp"
#include "pancake/PancakeState.hpp"
#include <vector>
PancakeInstance14::PancakeInstance14 *PancakeInstance14::read(std::istream &in)
{
unsigned int ncakes;
in >> ncakes;
if (ncakes != 14) {
std::cerr << "Invalid number of pancakes, expected 14, "
<< "got " << ncakes << std::endl;
return NULL;
}
PancakeState14 *start = PancakeState14::read(in);
if (!start)
return NULL;
PancakeState14 cgoal = PancakeState14::canonical_goal();
PancakeState14 *goal = new PancakeState14(cgoal);
return new PancakeInstance14(*start, *goal);
}
// Compute a simple abstraction order that blanks out one more tile
// each level.
PancakeInstance14::AbstractionOrder
PancakeInstance14::simple_abstraction_order(const PancakeState14 &s)
{
AbstractionOrder abst;
unsigned int ncakes = abst[0].size();
for (unsigned int lvl = 0;
lvl <= PancakeInstance14::num_abstraction_levels;
lvl += 1) {
for (unsigned int i = 0; i < ncakes; i += 1) {
if (lvl == 0)
abst[lvl][i] = false;
else if (i < ncakes - (num_abstraction_levels - lvl))
abst[lvl][i] = true;
else
abst[lvl][i] = false;
}
}
return abst;
}
PancakeInstance14::PancakeInstance14(const PancakeState14 &s,
const PancakeState14 &g)
: start(s),
goal(g),
abstraction_order(simple_abstraction_order(s))
{ }
PancakeNode14 *PancakeInstance14::child(const PancakeState14 &new_state,
PancakeCost new_g,
const PancakeNode14 &parent,
boost::pool<> &node_pool)
{
assert(!(parent.get_state() == new_state));
assert((parent.get_parent() == NULL)
|| !(new_state == parent.get_parent()->get_state()));
PancakeNode14 *child_node =
new (node_pool.malloc()) PancakeNode14(new_state,
new_g,
0,
&parent);
return child_node;
}
void PancakeInstance14::compute_successors(const PancakeNode14 &node,
std::vector<PancakeNode14*> &succs,
boost::pool<> &node_pool)
{
const PancakeNode14 *gp = node.get_parent();
succs.clear();
for (unsigned int n = 2; n <= 14; n += 1) {
const PancakeState14 child_state = node.get_state().flip(n);
if ((!gp || gp->get_state() != child_state)
&& child_state != node.get_state()) {
PancakeNode14 *child_node = child(child_state,
node.get_g() + 1,
node,
node_pool);
succs.push_back(child_node);
}
}
}
void
PancakeInstance14::compute_predecessors(const PancakeNode14 &n,
std::vector<PancakeNode14*> &succs,
boost::pool<> &node_pool)
{
compute_successors(n, succs, node_pool);
}
void PancakeInstance14::compute_heuristic(const PancakeNode14 &parent,
PancakeNode14 &child) const
{
compute_heuristic(child);
}
void PancakeInstance14::compute_heuristic(PancakeNode14 &child) const
{
// Just use h(n) = 0 for now, I guess.
child.set_h(0);
}
bool
PancakeInstance14::should_abstract(unsigned int level, unsigned int i) const
{
return abstraction_order[level][i - 1];
}
const PancakeState14 &PancakeInstance14::get_start_state() const
{
return start;
}
const PancakeState14 &PancakeInstance14::get_goal_state() const
{
return goal;
}
PancakeState14 PancakeInstance14::abstract(unsigned int level,
const PancakeState14 &s) const
{
std::vector<Pancake> cakes = s.get_cakes();
boost::array<Pancake, 14> new_cakes;
for (unsigned int i = 0; i < cakes.size(); i += 1) {
if (cakes[i] == -1 || should_abstract(level, cakes[i]))
new_cakes[i] = -1;
else
new_cakes[i] = cakes[i];
}
return PancakeState14(new_cakes);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Emilian Cioca
#include "Jewel3D/Precompiled.h"
#include "FileSystem.h"
#include "Logging.h"
#include <Dirent/dirent.h>
#include <direct.h>
#include <sstream>
#include <stack>
#define SUCCESS 0
// Resolve name conflict with our functions.
#undef GetCurrentDirectory
#undef SetCurrentDirectory
namespace
{
std::stack<std::string> currentDirectoryStack;
}
namespace Jwl
{
bool ParseDirectory(DirectoryData& outData)
{
return ParseDirectory(outData, GetCurrentDirectory());
}
bool ParseDirectory(DirectoryData& outData, std::string_view directory)
{
outData.files.clear();
outData.folders.clear();
DIR* dir = opendir(directory.data());
if (dir == nullptr)
{
return false;
}
dirent* drnt;
while ((drnt = readdir(dir)) != nullptr)
{
switch (drnt->d_type)
{
// Regular file.
case DT_REG:
outData.files.emplace_back(drnt->d_name);
break;
// Directory.
case DT_DIR:
if (strcmp(drnt->d_name, ".") != 0 &&
strcmp(drnt->d_name, "..") != 0)
{
outData.folders.emplace_back(drnt->d_name);
}
break;
}
}
closedir(dir);
return true;
}
bool DirectoryExists(std::string_view directory)
{
if (auto dir = opendir(directory.data()))
{
closedir(dir);
return true;
}
else
{
return false;
}
}
bool IsPathRelative(std::string_view path)
{
return ExtractDriveLetter(path) == '\0';
}
bool IsPathAbsolute(std::string_view path)
{
return !IsPathRelative(path);
}
bool FileExists(std::string_view file)
{
FILE* f = nullptr;
fopen_s(&f, file.data(), "r");
if (f == nullptr)
{
return false;
}
fclose(f);
return true;
}
bool RemoveFile(std::string_view file)
{
return DeleteFile(file.data()) == TRUE;
}
bool MakeDirectory(std::string_view directory)
{
if (_mkdir(directory.data()) == ENOENT)
{
Error("FileSystem: Could not create directory due to an invalid directory path.");
return false;
}
else
{
return true;
}
}
std::string GetCurrentDirectory()
{
char result[MAX_PATH] = { '\0' };
GetCurrentDirectoryA(MAX_PATH, result);
return result;
}
void SetCurrentDirectory(std::string_view directory)
{
SetCurrentDirectoryA(directory.data());
}
void PushCurrentDirectory(std::string_view newDirectory)
{
currentDirectoryStack.push(GetCurrentDirectory());
SetCurrentDirectory(newDirectory);
}
void PopCurrentDirectory()
{
SetCurrentDirectory(currentDirectoryStack.top());
currentDirectoryStack.pop();
}
char ExtractDriveLetter(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return '\0';
}
char result[_MAX_DRIVE] = { '\0' };
if (_splitpath_s(path.data(), result, _MAX_DRIVE, nullptr, 0, nullptr, 0, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return '\0';
}
return result[0];
}
std::string ExtractPath(std::string_view path)
{
std::string result;
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return result;
}
char drive[_MAX_DRIVE] = { '\0' };
char dir[_MAX_DIR] = { '\0' };
if (_splitpath_s(path.data(), drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return result;
}
result.reserve(_MAX_DIR + _MAX_DRIVE - 1);
result = drive;
result += dir;
return result;
}
std::string ExtractFile(std::string_view path)
{
return ExtractFilename(path) + ExtractFileExtension(path);
}
std::string ExtractFilename(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return std::string();
}
char result[_MAX_FNAME] = { '\0' };
if (_splitpath_s(path.data(), nullptr, 0, nullptr, 0, result, _MAX_FNAME, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return std::string();
}
return result;
}
std::string ExtractFileExtension(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return std::string();
}
char result[_MAX_EXT] = { '\0' };
if (_splitpath_s(path.data(), nullptr, 0, nullptr, 0, nullptr, 0, result, _MAX_EXT) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return std::string();
}
return result;
}
bool LoadFileAsString(std::string_view file, std::string& output)
{
std::ifstream inStream(file.data());
if (!inStream.good())
{
return false;
}
std::ostringstream contents;
contents << inStream.rdbuf();
output = contents.str();
return true;
}
FileReader::~FileReader()
{
Close();
}
bool FileReader::operator!() const
{
return !file.is_open() && buffer.empty();
}
bool FileReader::OpenAsBuffer(std::string_view filePath)
{
ASSERT(!(*this), "FileReader: Already associated with a file.");
return LoadFileAsString(filePath, buffer);
}
bool FileReader::OpenAsStream(std::string_view filePath)
{
ASSERT(!(*this), "FileReader: Already associated with a file.");
file.open(filePath.data());
if (!file.good())
{
return false;
}
// Get length of file.
file.seekg(0, std::ifstream::end);
length = static_cast<unsigned>(file.tellg());
file.seekg(0, std::ifstream::beg);
return true;
}
void FileReader::Close()
{
buffer.clear();
currentPos = 0;
if (file.good())
{
file.close();
}
}
std::string FileReader::GetContents()
{
if (buffer.empty())
{
// Buffer mode
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
else
{
// Stream mode
if (currentPos >= buffer.size())
{
return std::string();
}
return buffer.substr(currentPos);
}
}
std::string FileReader::GetLine()
{
std::string result;
if (buffer.empty())
{
std::getline(file, result);
}
else
{
if (currentPos < buffer.size())
{
result = buffer.substr(currentPos, buffer.find('\n', currentPos) - currentPos);
currentPos += result.size() + 1; //+ 1 for '\n'
}
}
return result;
}
std::string FileReader::GetWord()
{
std::string result;
if (buffer.empty())
{
file >> result;
}
else
{
if (currentPos < buffer.size())
{
result = buffer.substr(currentPos, buffer.find_first_of(" \n", currentPos) - currentPos);
currentPos += result.size();
}
}
return result;
}
float FileReader::GetFloat()
{
if (buffer.empty())
{
float result;
file >> result;
return result;
}
else
{
if (currentPos >= buffer.size())
{
return 0.0f;
}
return std::stof(&buffer[currentPos], ¤tPos);
}
}
int FileReader::GetInt()
{
if (buffer.empty())
{
int result;
file >> result;
return result;
}
else
{
if (currentPos >= buffer.size())
{
return 0;
}
return std::stoi(&buffer[currentPos], ¤tPos);
}
}
char FileReader::GetChar()
{
if (buffer.empty())
{
return static_cast<char>(file.get());
}
else
{
if (currentPos >= buffer.size())
{
return 0;
}
return buffer[currentPos++];
}
}
bool FileReader::IsEOF() const
{
if (buffer.empty())
{
return file.eof();
}
else
{
return currentPos >= buffer.size();
}
}
int FileReader::GetSize() const
{
return length;
}
}
<commit_msg>MakeDirectory() can now make nested folders when needed<commit_after>// Copyright (c) 2017 Emilian Cioca
#include "Jewel3D/Precompiled.h"
#include "FileSystem.h"
#include "Logging.h"
#include <Dirent/dirent.h>
#include <direct.h>
#include <sstream>
#include <stack>
#define SUCCESS 0
// Resolve name conflict with our functions.
#undef GetCurrentDirectory
#undef SetCurrentDirectory
namespace
{
std::stack<std::string> currentDirectoryStack;
}
namespace Jwl
{
bool ParseDirectory(DirectoryData& outData)
{
return ParseDirectory(outData, GetCurrentDirectory());
}
bool ParseDirectory(DirectoryData& outData, std::string_view directory)
{
outData.files.clear();
outData.folders.clear();
DIR* dir = opendir(directory.data());
if (dir == nullptr)
{
return false;
}
dirent* drnt;
while ((drnt = readdir(dir)) != nullptr)
{
switch (drnt->d_type)
{
// Regular file.
case DT_REG:
outData.files.emplace_back(drnt->d_name);
break;
// Directory.
case DT_DIR:
if (strcmp(drnt->d_name, ".") != 0 &&
strcmp(drnt->d_name, "..") != 0)
{
outData.folders.emplace_back(drnt->d_name);
}
break;
}
}
closedir(dir);
return true;
}
bool DirectoryExists(std::string_view directory)
{
if (auto dir = opendir(directory.data()))
{
closedir(dir);
return true;
}
else
{
return false;
}
}
bool IsPathRelative(std::string_view path)
{
return ExtractDriveLetter(path) == '\0';
}
bool IsPathAbsolute(std::string_view path)
{
return !IsPathRelative(path);
}
bool FileExists(std::string_view file)
{
FILE* f = nullptr;
fopen_s(&f, file.data(), "r");
if (f == nullptr)
{
return false;
}
fclose(f);
return true;
}
bool RemoveFile(std::string_view file)
{
return DeleteFile(file.data()) == TRUE;
}
bool MakeDirectory(std::string_view directory)
{
if (directory.empty())
{
Error("FileSystem: Could not create directory: Empty path.");
return false;
}
if (directory.size() > MAX_PATH - 1)
{
Error("FileSystem: Could not create directory: Path is too long.");
return false;
}
char buffer[MAX_PATH];
memcpy(buffer, directory.data(), sizeof(char) * directory.size());
buffer[directory.size()] = '\0';
for (unsigned i = 1; i < directory.size() - 1; ++i)
{
if (buffer[i] == '\\' || buffer[i] == '/')
{
char saved = buffer[i + 1];
buffer[i + 1] = '\0';
if (_mkdir(buffer) == ENOENT)
{
Error("FileSystem: Could not create directory: Invalid path.");
return false;
}
buffer[i + 1] = saved;
}
}
if (_mkdir(buffer) == ENOENT)
{
Error("FileSystem: Could not create directory: Invalid path.");
return false;
}
return true;
}
std::string GetCurrentDirectory()
{
char result[MAX_PATH] = { '\0' };
GetCurrentDirectoryA(MAX_PATH, result);
return result;
}
void SetCurrentDirectory(std::string_view directory)
{
SetCurrentDirectoryA(directory.data());
}
void PushCurrentDirectory(std::string_view newDirectory)
{
currentDirectoryStack.push(GetCurrentDirectory());
SetCurrentDirectory(newDirectory);
}
void PopCurrentDirectory()
{
SetCurrentDirectory(currentDirectoryStack.top());
currentDirectoryStack.pop();
}
char ExtractDriveLetter(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return '\0';
}
char result[_MAX_DRIVE] = { '\0' };
if (_splitpath_s(path.data(), result, _MAX_DRIVE, nullptr, 0, nullptr, 0, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return '\0';
}
return result[0];
}
std::string ExtractPath(std::string_view path)
{
std::string result;
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return result;
}
char drive[_MAX_DRIVE] = { '\0' };
char dir[_MAX_DIR] = { '\0' };
if (_splitpath_s(path.data(), drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return result;
}
result.reserve(_MAX_DIR + _MAX_DRIVE - 1);
result = drive;
result += dir;
return result;
}
std::string ExtractFile(std::string_view path)
{
return ExtractFilename(path) + ExtractFileExtension(path);
}
std::string ExtractFilename(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return std::string();
}
char result[_MAX_FNAME] = { '\0' };
if (_splitpath_s(path.data(), nullptr, 0, nullptr, 0, result, _MAX_FNAME, nullptr, 0) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return std::string();
}
return result;
}
std::string ExtractFileExtension(std::string_view path)
{
if (path.empty())
{
Error("FileSystem: Cannot process an empty string.");
return std::string();
}
char result[_MAX_EXT] = { '\0' };
if (_splitpath_s(path.data(), nullptr, 0, nullptr, 0, nullptr, 0, result, _MAX_EXT) != SUCCESS)
{
Error("FileSystem: Invalid path.");
return std::string();
}
return result;
}
bool LoadFileAsString(std::string_view file, std::string& output)
{
std::ifstream inStream(file.data());
if (!inStream.good())
{
return false;
}
std::ostringstream contents;
contents << inStream.rdbuf();
output = contents.str();
return true;
}
FileReader::~FileReader()
{
Close();
}
bool FileReader::operator!() const
{
return !file.is_open() && buffer.empty();
}
bool FileReader::OpenAsBuffer(std::string_view filePath)
{
ASSERT(!(*this), "FileReader: Already associated with a file.");
return LoadFileAsString(filePath, buffer);
}
bool FileReader::OpenAsStream(std::string_view filePath)
{
ASSERT(!(*this), "FileReader: Already associated with a file.");
file.open(filePath.data());
if (!file.good())
{
return false;
}
// Get length of file.
file.seekg(0, std::ifstream::end);
length = static_cast<unsigned>(file.tellg());
file.seekg(0, std::ifstream::beg);
return true;
}
void FileReader::Close()
{
buffer.clear();
currentPos = 0;
if (file.good())
{
file.close();
}
}
std::string FileReader::GetContents()
{
if (buffer.empty())
{
// Buffer mode
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
else
{
// Stream mode
if (currentPos >= buffer.size())
{
return std::string();
}
return buffer.substr(currentPos);
}
}
std::string FileReader::GetLine()
{
std::string result;
if (buffer.empty())
{
std::getline(file, result);
}
else
{
if (currentPos < buffer.size())
{
result = buffer.substr(currentPos, buffer.find('\n', currentPos) - currentPos);
currentPos += result.size() + 1; //+ 1 for '\n'
}
}
return result;
}
std::string FileReader::GetWord()
{
std::string result;
if (buffer.empty())
{
file >> result;
}
else
{
if (currentPos < buffer.size())
{
result = buffer.substr(currentPos, buffer.find_first_of(" \n", currentPos) - currentPos);
currentPos += result.size();
}
}
return result;
}
float FileReader::GetFloat()
{
if (buffer.empty())
{
float result;
file >> result;
return result;
}
else
{
if (currentPos >= buffer.size())
{
return 0.0f;
}
return std::stof(&buffer[currentPos], ¤tPos);
}
}
int FileReader::GetInt()
{
if (buffer.empty())
{
int result;
file >> result;
return result;
}
else
{
if (currentPos >= buffer.size())
{
return 0;
}
return std::stoi(&buffer[currentPos], ¤tPos);
}
}
char FileReader::GetChar()
{
if (buffer.empty())
{
return static_cast<char>(file.get());
}
else
{
if (currentPos >= buffer.size())
{
return 0;
}
return buffer[currentPos++];
}
}
bool FileReader::IsEOF() const
{
if (buffer.empty())
{
return file.eof();
}
else
{
return currentPos >= buffer.size();
}
}
int FileReader::GetSize() const
{
return length;
}
}
<|endoftext|>
|
<commit_before><commit_msg>fix name<commit_after><|endoftext|>
|
<commit_before><commit_msg>Don't run attack count test if prior tests fail<commit_after><|endoftext|>
|
<commit_before><commit_msg>Fixed service referencing bug<commit_after><|endoftext|>
|
<commit_before>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using boost::filesystem::remove_all;
using boost::filesystem::exists;
void test_swarm()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48010, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49010, 50000), "0.0.0.0", 0);
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50010, 51000), "0.0.0.0", 0);
ses1.set_severity_level(alert::debug);
ses2.set_severity_level(alert::debug);
ses3.set_severity_level(alert::debug);
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
float rate_limit = 100000;
ses1.set_upload_rate_limit(int(rate_limit));
ses1.set_max_uploads(1);
ses2.set_download_rate_limit(int(rate_limit / 5));
ses3.set_download_rate_limit(int(rate_limit / 5));
ses2.set_upload_rate_limit(int(rate_limit / 10));
ses3.set_upload_rate_limit(int(rate_limit / 10));
session_settings settings;
settings.allow_multiple_connections_per_ip = true;
settings.ignore_limits_on_local_network = false;
settings.auto_upload_slots = true;
settings.auto_upload_slots_rate_based = false;
ses1.set_settings(settings);
ses2.set_settings(settings);
ses3.set_settings(settings);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_unchoke");
session_status st = ses1.status();
TEST_CHECK(st.allowed_upload_slots == 1);
for (int i = 0; i < 50; ++i)
{
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
print_alerts(ses3, "ses3");
st = ses1.status();
if (st.allowed_upload_slots >= 2) break;
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
torrent_status st3 = tor3.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << " " << st.allowed_upload_slots << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
test_sleep(1000);
}
TEST_CHECK(st.allowed_upload_slots == 2);
// make sure the files are deleted
ses1.remove_torrent(tor1, session::delete_files);
ses2.remove_torrent(tor2, session::delete_files);
ses3.remove_torrent(tor3, session::delete_files);
}
int test_main()
{
using namespace libtorrent;
using namespace boost::filesystem;
// in case the previous run was terminated
try { remove_all("./tmp1_unchoke"); } catch (std::exception&) {}
try { remove_all("./tmp2_unchoke"); } catch (std::exception&) {}
try { remove_all("./tmp3_unchoke"); } catch (std::exception&) {}
test_swarm();
test_sleep(2000);
TEST_CHECK(!exists("./tmp1_unchoke/temporary"));
TEST_CHECK(!exists("./tmp2_unchoke/temporary"));
TEST_CHECK(!exists("./tmp3_unchoke/temporary"));
remove_all("./tmp1_unchoke");
remove_all("./tmp2_unchoke");
remove_all("./tmp3_unchoke");
return 0;
}
<commit_msg>fixed auto unchoke test<commit_after>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/alert_types.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
using boost::filesystem::remove_all;
using boost::filesystem::exists;
void test_swarm()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48010, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49010, 50000), "0.0.0.0", 0);
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50010, 51000), "0.0.0.0", 0);
ses1.set_severity_level(alert::debug);
ses2.set_severity_level(alert::debug);
ses3.set_severity_level(alert::debug);
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
float rate_limit = 100000;
ses1.set_upload_rate_limit(int(rate_limit));
ses1.set_max_uploads(1);
ses2.set_download_rate_limit(int(rate_limit / 5));
ses3.set_download_rate_limit(int(rate_limit / 5));
ses2.set_upload_rate_limit(int(rate_limit / 10));
ses3.set_upload_rate_limit(int(rate_limit / 10));
session_settings settings;
settings.allow_multiple_connections_per_ip = true;
settings.ignore_limits_on_local_network = false;
settings.auto_upload_slots = true;
settings.auto_upload_slots_rate_based = false;
ses1.set_settings(settings);
ses2.set_settings(settings);
ses3.set_settings(settings);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_unchoke");
session_status st = ses1.status();
TEST_CHECK(st.allowed_upload_slots == 1);
for (int i = 0; i < 50; ++i)
{
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
print_alerts(ses3, "ses3");
st = ses1.status();
std::cerr << st.allowed_upload_slots << " ";
if (st.allowed_upload_slots >= 2) break;
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
torrent_status st3 = tor3.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << " " << st.allowed_upload_slots << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
test_sleep(1000);
}
TEST_CHECK(st.allowed_upload_slots >= 2);
// make sure the files are deleted
ses1.remove_torrent(tor1, session::delete_files);
ses2.remove_torrent(tor2, session::delete_files);
ses3.remove_torrent(tor3, session::delete_files);
}
int test_main()
{
using namespace libtorrent;
using namespace boost::filesystem;
// in case the previous run was terminated
try { remove_all("./tmp1_unchoke"); } catch (std::exception&) {}
try { remove_all("./tmp2_unchoke"); } catch (std::exception&) {}
try { remove_all("./tmp3_unchoke"); } catch (std::exception&) {}
test_swarm();
test_sleep(2000);
TEST_CHECK(!exists("./tmp1_unchoke/temporary"));
TEST_CHECK(!exists("./tmp2_unchoke/temporary"));
TEST_CHECK(!exists("./tmp3_unchoke/temporary"));
remove_all("./tmp1_unchoke");
remove_all("./tmp2_unchoke");
remove_all("./tmp3_unchoke");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/transformations/remove_comments.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <cstring>
#include "modsecurity/transaction.h"
#include "src/actions/transformations/transformation.h"
namespace modsecurity {
namespace actions {
namespace transformations {
std::string RemoveComments::evaluate(const std::string &value,
Transaction *transaction) {
std::string ret;
unsigned char *input;
input = reinterpret_cast<unsigned char *>
(malloc(sizeof(char) * value.length()+1));
if (input == NULL) {
return "";
}
memcpy(input, value.c_str(), value.length()+1);
uint64_t input_len = value.size();
uint64_t i, j, incomment;
i = j = incomment = 0;
while (i < input_len) {
if (incomment == 0) {
if ((input[i] == '/') && (i + 1 < input_len)
&& (input[i + 1] == '*')) {
incomment = 1;
i += 2;
} else if ((input[i] == '<') && (i + 1 < input_len)
&& (input[i + 1] == '!') && (i + 2 < input_len)
&& (input[i+2] == '-') && (i + 3 < input_len)
&& (input[i + 3] == '-') && (incomment == 0)) {
incomment = 1;
i += 4;
} else if ((input[i] == '-') && (i + 1 < input_len)
&& (input[i + 1] == '-') && (incomment == 0)) {
input[i] = ' ';
break;
} else if (input[i] == '#' && (incomment == 0)) {
input[i] = ' ';
break;
} else {
input[j] = input[i];
i++;
j++;
}
} else {
if ((input[i] == '*') && (i + 1 < input_len)
&& (input[i + 1] == '/')) {
incomment = 0;
i += 2;
input[j] = input[i];
i++;
j++;
} else if ((input[i] == '-') && (i + 1 < input_len)
&& (input[i + 1] == '-') && (i + 2 < input_len)
&& (input[i+2] == '>')) {
incomment = 0;
i += 3;
input[j] = input[i];
i++;
j++;
} else {
i++;
}
}
}
if (incomment) {
input[j++] = ' ';
}
ret.assign(reinterpret_cast<char *>(input), j);
free(input);
return ret;
}
} // namespace transformations
} // namespace actions
} // namespace modsecurity
<commit_msg>Cosmetics: Having cppcheck pleased<commit_after>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/transformations/remove_comments.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <cstring>
#include "modsecurity/transaction.h"
#include "src/actions/transformations/transformation.h"
namespace modsecurity {
namespace actions {
namespace transformations {
std::string RemoveComments::evaluate(const std::string &value,
Transaction *transaction) {
std::string ret;
unsigned char *input;
input = reinterpret_cast<unsigned char *>
(malloc(sizeof(char) * value.length()+1));
if (input == NULL) {
return "";
}
memcpy(input, value.c_str(), value.length()+1);
uint64_t input_len = value.size();
uint64_t i, j, incomment;
i = j = incomment = 0;
while (i < input_len) {
if (incomment == 0) {
if ((input[i] == '/') && (i + 1 < input_len)
&& (input[i + 1] == '*')) {
incomment = 1;
i += 2;
} else if ((input[i] == '<') && (i + 1 < input_len)
&& (input[i + 1] == '!') && (i + 2 < input_len)
&& (input[i+2] == '-') && (i + 3 < input_len)
&& (input[i + 3] == '-')) {
incomment = 1;
i += 4;
} else if ((input[i] == '-') && (i + 1 < input_len)
&& (input[i + 1] == '-')) {
input[i] = ' ';
break;
} else if (input[i] == '#') {
input[i] = ' ';
break;
} else {
input[j] = input[i];
i++;
j++;
}
} else {
if ((input[i] == '*') && (i + 1 < input_len)
&& (input[i + 1] == '/')) {
incomment = 0;
i += 2;
input[j] = input[i];
i++;
j++;
} else if ((input[i] == '-') && (i + 1 < input_len)
&& (input[i + 1] == '-') && (i + 2 < input_len)
&& (input[i+2] == '>')) {
incomment = 0;
i += 3;
input[j] = input[i];
i++;
j++;
} else {
i++;
}
}
}
if (incomment) {
input[j++] = ' ';
}
ret.assign(reinterpret_cast<char *>(input), j);
free(input);
return ret;
}
} // namespace transformations
} // namespace actions
} // namespace modsecurity
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "musicextractorsvm.h"
#include "algorithmfactory.h"
using namespace std;
namespace essentia {
namespace standard {
const char* MusicExtractorSVM::name = "MusicExtractorSVM";
const char* MusicExtractorSVM::category = "Extractors";
const char* MusicExtractorSVM::description = DOC("This algorithms computes SVM predictions given a pool with aggregated descriptor values computed by MusicExtractor.");
// TODO explain better (reuse music extractor svm documentation)
MusicExtractorSVM::MusicExtractorSVM() {
declareInput(_inputPool, "pool", "aggregated pool of extracted values");
declareOutput(_outputPool, "pool", "pool with classification results (resulting from the transformation of the gaia point)");
}
MusicExtractorSVM::~MusicExtractorSVM() {
for (int i = 0; i < (int)_svms.size(); i++) {
if (_svms[i]) {
delete _svms[i];
}
}
}
void MusicExtractorSVM::reset() {}
void MusicExtractorSVM::configure() {
if (!parameter("svms").isConfigured()) {
throw EssentiaException("MusicExtractorSVM: No model files were specified in \"svm\" parameter");
}
vector<string> svmModels = parameter("svms").toVectorString();
for (int i=0; i<(int) svmModels.size(); i++) {
E_INFO("MusicExtractorSVM: adding SVM model " << svmModels[i]);
Algorithm* svm = AlgorithmFactory::create("GaiaTransform", "history", svmModels[i]);
_svms.push_back(svm);
}
}
void MusicExtractorSVM::compute() {
const Pool& inputPool = _inputPool.get();
Pool& outputPool = _outputPool.get();
for (int i = 0; i < (int)_svms.size(); i++) {
_svms[i]->input("pool").set(inputPool);
_svms[i]->output("pool").set(outputPool);
_svms[i]->compute();
}
}
} // namespace standard
} // namespace essentia
<commit_msg>Code cleanup<commit_after>/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "musicextractorsvm.h"
#include "algorithmfactory.h"
using namespace std;
namespace essentia {
namespace standard {
const char* MusicExtractorSVM::name = "MusicExtractorSVM";
const char* MusicExtractorSVM::category = "Extractors";
const char* MusicExtractorSVM::description = DOC("This algorithms computes SVM predictions given a pool with aggregated descriptor values computed by MusicExtractor.");
// TODO explain better (reuse music extractor svm documentation)
MusicExtractorSVM::MusicExtractorSVM() {
declareInput(_inputPool, "pool", "aggregated pool of extracted values");
declareOutput(_outputPool, "pool", "pool with classification results (resulting from the transformation of the gaia point)");
}
MusicExtractorSVM::~MusicExtractorSVM() {
for (int i = 0; i < (int)_svms.size(); i++) {
if (_svms[i]) {
delete _svms[i];
}
}
}
void MusicExtractorSVM::reset() {}
void MusicExtractorSVM::configure() {
if (!parameter("svms").isConfigured()) {
throw EssentiaException("MusicExtractorSVM: No model files were specified in \"svm\" parameter");
}
vector<string> svmModels = parameter("svms").toVectorString();
for (int i=0; i<(int) svmModels.size(); i++) {
E_INFO("MusicExtractorSVM: adding SVM model " << svmModels[i]);
Algorithm* svm = AlgorithmFactory::create("GaiaTransform", "history", svmModels[i]);
_svms.push_back(svm);
}
}
void MusicExtractorSVM::compute() {
const Pool& inputPool = _inputPool.get();
Pool& outputPool = _outputPool.get();
for (int i = 0; i < (int)_svms.size(); i++) {
_svms[i]->input("pool").set(inputPool);
_svms[i]->output("pool").set(outputPool);
_svms[i]->compute();
}
}
} // namespace standard
} // namespace essentia
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <DTK_ConfigDefs.hpp>
#include <DTK_LinearBVH.hpp>
#include <cmath>
#include <functional>
#include <random>
namespace details = DataTransferKit::Details;
std::vector<std::array<double, 3>>
make_stuctured_cloud( double Lx, double Ly, double Lz, int nx, int ny, int nz )
{
std::vector<std::array<double, 3>> cloud( nx * ny * nz );
std::function<int( int, int, int )> ind = [nx, ny]( int i, int j, int k ) {
return i + j * nx + k * ( nx * ny );
};
double x, y, z;
for ( int i = 0; i < nx; ++i )
for ( int j = 0; j < ny; ++j )
for ( int k = 0; k < nz; ++k )
{
x = i * Lx / ( nx - 1 );
y = j * Ly / ( ny - 1 );
z = k * Lz / ( nz - 1 );
cloud[ind( i, j, k )] = {{x, y, z}};
}
return cloud;
}
std::vector<std::array<double, 3>> make_random_cloud( double Lx, double Ly,
double Lz, int n )
{
std::vector<std::array<double, 3>> cloud( n );
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution_x( 0.0, Lx );
std::uniform_real_distribution<double> distribution_y( 0.0, Ly );
std::uniform_real_distribution<double> distribution_z( 0.0, Lz );
for ( int i = 0; i < n; ++i )
{
double x = distribution_x( generator );
double y = distribution_y( generator );
double z = distribution_z( generator );
cloud[i] = {{x, y, z}};
}
return cloud;
}
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
double Lx = 100.0;
double Ly = 100.0;
double Lz = 100.0;
int nx = 11;
int ny = 11;
int nz = 11;
int n_points = 100;
std::string mode = "radius";
clp.setOption( "nx", &nx, "source mesh points in x-direction." );
clp.setOption( "ny", &ny, "source mesh points in y-direction." );
clp.setOption( "nz", &nz, "source mesh points in z-direction." );
clp.setOption( "N", &n_points,
"number of target mesh points (distributed randomly)." );
clp.setOption( "mode", &mode, "mode: (knn | radius)" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
// contruct a cloud of points (nodes of a structured grid)
auto cloud = make_stuctured_cloud( Lx, Ly, Lz, nx, ny, nz );
int n = cloud.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n );
auto bounding_boxes_host = Kokkos::create_mirror_view( bounding_boxes );
// build bounding volume hierarchy
for ( int i = 0; i < n; ++i )
{
auto const &point = cloud[i];
double x = std::get<0>( point );
double y = std::get<1>( point );
double z = std::get<2>( point );
bounding_boxes_host[i] = {{{x, y, z}}, {{x, y, z}}};
}
Kokkos::deep_copy( bounding_boxes, bounding_boxes_host );
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
// random points for radius search and kNN queries
auto queries = make_random_cloud( Lx, Ly, Lz, n_points );
Kokkos::View<double * [3], ExecutionSpace> point_coords( "point_coords",
n_points );
auto point_coords_host = Kokkos::create_mirror_view( point_coords );
for ( int i = 0; i < n_points; ++i )
{
auto const &point = queries[i];
point_coords_host( i, 0 ) = std::get<0>( point );
point_coords_host( i, 1 ) = std::get<1>( point );
point_coords_host( i, 2 ) = std::get<2>( point );
}
Kokkos::deep_copy( point_coords, point_coords_host );
std::default_random_engine generator;
if ( mode == "knn" )
{
Kokkos::View<int *, ExecutionSpace> k( "distribution_k", n_points );
auto k_host = Kokkos::create_mirror_view( k );
// use random number k of for the kNN search
int max_k = std::floor( sqrt( nx * nx + ny * ny + nz * nz ) );
std::uniform_int_distribution<int> distribution_k( 1, max_k );
for ( int i = 0; i < n_points; ++i )
{
k_host[i] = distribution_k( generator );
}
Kokkos::deep_copy( k, k_host );
Kokkos::View<details::Nearest<DataTransferKit::Point> *, DeviceType>
nearest_queries( "nearest_queries", n_points );
Kokkos::parallel_for(
DTK_MARK_REGION( "register_nearest_queries" ),
Kokkos::RangePolicy<ExecutionSpace>( 0, n_points ),
KOKKOS_LAMBDA( int i ) {
nearest_queries( i ) = details::nearest<DataTransferKit::Point>(
{{point_coords( i, 0 ), point_coords( i, 1 ),
point_coords( i, 2 )}},
k( i ) );
} );
Kokkos::fence();
// do the search
Kokkos::View<int *, DeviceType> offset_nearest( "offset_nearest" );
Kokkos::View<int *, DeviceType> indices_nearest( "indices_nearest" );
bvh.query( nearest_queries, indices_nearest, offset_nearest );
}
else if ( mode == "radius" )
{
Kokkos::View<double *, ExecutionSpace> radii( "radii", n_points );
auto radii_host = Kokkos::create_mirror_view( radii );
// use random radius for the search
// set the limit of approximately 100 points by
// solving n_points*pi*r^2/(Lx^2 + Ly^2 + Lz^2) <= 100
const int approx_points = 100;
double max_radius = sqrt(
approx_points * ( Lx * Lx + Ly * Ly + Lz * Lz ) / ( n * M_PI ) );
std::uniform_real_distribution<double> distribution_radius(
0.0, max_radius );
for ( int i = 0; i < n_points; ++i )
{
radii_host[i] = distribution_radius( generator );
}
Kokkos::deep_copy( radii, radii_host );
Kokkos::View<details::Within *, DeviceType> within_queries(
"within_queries", n_points );
Kokkos::parallel_for(
DTK_MARK_REGION( "register_within_queries" ),
Kokkos::RangePolicy<ExecutionSpace>( 0, n_points ),
KOKKOS_LAMBDA( int i ) {
within_queries( i ) = details::within(
{{point_coords( i, 0 ), point_coords( i, 1 ),
point_coords( i, 2 )}},
radii( i ) );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset_within( "offset_within" );
Kokkos::View<int *, DeviceType> indices_within( "indices_within" );
bvh.query( within_queries, indices_within, offset_within );
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = false;
bool verbose = true;
int rv = 0;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
rv = 1;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( rv )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
rv = main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_HAVE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
rv = main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_HAVE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
rv = main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_HAVE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
rv = main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
if ( rv )
success = false;
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<commit_msg>Fix return value in bvh example driver<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <DTK_ConfigDefs.hpp>
#include <DTK_LinearBVH.hpp>
#include <cmath>
#include <functional>
#include <random>
namespace details = DataTransferKit::Details;
std::vector<std::array<double, 3>>
make_stuctured_cloud( double Lx, double Ly, double Lz, int nx, int ny, int nz )
{
std::vector<std::array<double, 3>> cloud( nx * ny * nz );
std::function<int( int, int, int )> ind = [nx, ny]( int i, int j, int k ) {
return i + j * nx + k * ( nx * ny );
};
double x, y, z;
for ( int i = 0; i < nx; ++i )
for ( int j = 0; j < ny; ++j )
for ( int k = 0; k < nz; ++k )
{
x = i * Lx / ( nx - 1 );
y = j * Ly / ( ny - 1 );
z = k * Lz / ( nz - 1 );
cloud[ind( i, j, k )] = {{x, y, z}};
}
return cloud;
}
std::vector<std::array<double, 3>> make_random_cloud( double Lx, double Ly,
double Lz, int n )
{
std::vector<std::array<double, 3>> cloud( n );
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution_x( 0.0, Lx );
std::uniform_real_distribution<double> distribution_y( 0.0, Ly );
std::uniform_real_distribution<double> distribution_z( 0.0, Lz );
for ( int i = 0; i < n; ++i )
{
double x = distribution_x( generator );
double y = distribution_y( generator );
double z = distribution_z( generator );
cloud[i] = {{x, y, z}};
}
return cloud;
}
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
double Lx = 100.0;
double Ly = 100.0;
double Lz = 100.0;
int nx = 11;
int ny = 11;
int nz = 11;
int n_points = 100;
std::string mode = "radius";
clp.setOption( "nx", &nx, "source mesh points in x-direction." );
clp.setOption( "ny", &ny, "source mesh points in y-direction." );
clp.setOption( "nz", &nz, "source mesh points in z-direction." );
clp.setOption( "N", &n_points,
"number of target mesh points (distributed randomly)." );
clp.setOption( "mode", &mode, "mode: (knn | radius)" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
// contruct a cloud of points (nodes of a structured grid)
auto cloud = make_stuctured_cloud( Lx, Ly, Lz, nx, ny, nz );
int n = cloud.size();
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n );
auto bounding_boxes_host = Kokkos::create_mirror_view( bounding_boxes );
// build bounding volume hierarchy
for ( int i = 0; i < n; ++i )
{
auto const &point = cloud[i];
double x = std::get<0>( point );
double y = std::get<1>( point );
double z = std::get<2>( point );
bounding_boxes_host[i] = {{{x, y, z}}, {{x, y, z}}};
}
Kokkos::deep_copy( bounding_boxes, bounding_boxes_host );
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
// random points for radius search and kNN queries
auto queries = make_random_cloud( Lx, Ly, Lz, n_points );
Kokkos::View<double * [3], ExecutionSpace> point_coords( "point_coords",
n_points );
auto point_coords_host = Kokkos::create_mirror_view( point_coords );
for ( int i = 0; i < n_points; ++i )
{
auto const &point = queries[i];
point_coords_host( i, 0 ) = std::get<0>( point );
point_coords_host( i, 1 ) = std::get<1>( point );
point_coords_host( i, 2 ) = std::get<2>( point );
}
Kokkos::deep_copy( point_coords, point_coords_host );
std::default_random_engine generator;
if ( mode == "knn" )
{
Kokkos::View<int *, ExecutionSpace> k( "distribution_k", n_points );
auto k_host = Kokkos::create_mirror_view( k );
// use random number k of for the kNN search
int max_k = std::floor( sqrt( nx * nx + ny * ny + nz * nz ) );
std::uniform_int_distribution<int> distribution_k( 1, max_k );
for ( int i = 0; i < n_points; ++i )
{
k_host[i] = distribution_k( generator );
}
Kokkos::deep_copy( k, k_host );
Kokkos::View<details::Nearest<DataTransferKit::Point> *, DeviceType>
nearest_queries( "nearest_queries", n_points );
Kokkos::parallel_for(
DTK_MARK_REGION( "register_nearest_queries" ),
Kokkos::RangePolicy<ExecutionSpace>( 0, n_points ),
KOKKOS_LAMBDA( int i ) {
nearest_queries( i ) = details::nearest<DataTransferKit::Point>(
{{point_coords( i, 0 ), point_coords( i, 1 ),
point_coords( i, 2 )}},
k( i ) );
} );
Kokkos::fence();
// do the search
Kokkos::View<int *, DeviceType> offset_nearest( "offset_nearest" );
Kokkos::View<int *, DeviceType> indices_nearest( "indices_nearest" );
bvh.query( nearest_queries, indices_nearest, offset_nearest );
}
else if ( mode == "radius" )
{
Kokkos::View<double *, ExecutionSpace> radii( "radii", n_points );
auto radii_host = Kokkos::create_mirror_view( radii );
// use random radius for the search
// set the limit of approximately 100 points by
// solving n_points*pi*r^2/(Lx^2 + Ly^2 + Lz^2) <= 100
const int approx_points = 100;
double max_radius = sqrt(
approx_points * ( Lx * Lx + Ly * Ly + Lz * Lz ) / ( n * M_PI ) );
std::uniform_real_distribution<double> distribution_radius(
0.0, max_radius );
for ( int i = 0; i < n_points; ++i )
{
radii_host[i] = distribution_radius( generator );
}
Kokkos::deep_copy( radii, radii_host );
Kokkos::View<details::Within *, DeviceType> within_queries(
"within_queries", n_points );
Kokkos::parallel_for(
DTK_MARK_REGION( "register_within_queries" ),
Kokkos::RangePolicy<ExecutionSpace>( 0, n_points ),
KOKKOS_LAMBDA( int i ) {
within_queries( i ) = details::within(
{{point_coords( i, 0 ), point_coords( i, 1 ),
point_coords( i, 2 )}},
radii( i ) );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset_within( "offset_within" );
Kokkos::View<int *, DeviceType> indices_within( "indices_within" );
bvh.query( within_queries, indices_within, offset_within );
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_HAVE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_HAVE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_HAVE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<|endoftext|>
|
<commit_before>#ifndef MYVECTOR_HPP
#define MYVECTOR_HPP 1
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>
namespace sandsnip3r {
template<typename Type>
class MyVectorIterator {
private:
};
template<typename Type>
class MyVector {
public:
typedef Type value_type;
typedef std::allocator<value_type> allocator_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef Type& reference;
typedef const Type& const_reference;
typedef Type* pointer;
typedef const Type* const_pointer;
//iterator
//const_iterator
//reverse_iterator
//const_reverse_iterator
private:
std::allocator<value_type> vectorAllocator;
std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData;
size_t vectorSize{0};
size_t vectorCapacity{0};
void reallocate(size_type newCapacity) {
//Allocate memory for the new data
// store it in a unique_ptr
std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){
vectorAllocator.deallocate(ptr, newCapacity);
});
//Move the old data into out new storage chunk
const auto &dataBegin = vectorData.get();
std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get());
//Assign the new data to be the current
vectorData = std::move(newData);
//Update the capacity
vectorCapacity = newCapacity;
}
public:
//constructor
~MyVector() {
this->clear();
}
//operator=
//assign
allocator_type get_allocator() const {
return vectorAllocator;
}
reference at(size_type pos) {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->at(pos));
}
const_reference at(size_type pos) const {
if (!(pos < this->size())) {
throw std::out_of_range("MyVector::at() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")");
}
return vectorData[pos];
}
reference operator[](size_type pos) {
return vectorData[pos];
}
const_reference operator[](size_type pos) const {
return vectorData[pos];
}
reference front() {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->front());
}
const_reference front() const {
if (this->empty()) {
throw std::out_of_range("MyVector::front(), but it's empty");
}
return vectorData[0];
}
reference back() {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->back());
}
const_reference back() const {
if (this->empty()) {
throw std::out_of_range("MyVector::back(), but it's empty");
}
return vectorData[this->size()-1];
}
pointer data() {
return vectorData.get();
}
const_pointer data() const {
return vectorData.get();
}
//begin, cbegin
//end, cend
//rbegin, crbegin
//rend, crend
bool empty() const {
return (this->size() == 0);
}
size_type size() const {
return vectorSize;
}
//max_size
void reserve(size_type newCapacity) {
//TODO: Check that we're under max_size
if (this->capacity() < newCapacity) {
reallocate(newCapacity);
}
}
size_type capacity() const {
return vectorCapacity;
}
void shrink_to_fit() {
if (this->size() < this->capacity()) {
reallocate(vectorSize);
}
}
void clear() {
for (size_type i=0; i<this->size(); ++i) {
vectorData[i].~value_type();
--vectorSize;
}
}
//insert
//emplace
//erase
void push_back(const value_type &obj) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{obj};
++vectorSize;
}
void push_back(value_type &&obj) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{std::move(obj)};
++vectorSize;
}
template<class... Args>
void emplace_back(Args&&... args) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...};
++vectorSize;
}
void pop_back() {
if (!this->empty()) {
vectorData[this->size()-1].~value_type();
--vectorSize;
}
}
void resize(size_type count) {
if (this->size() < count) {
if (this->capacity() < count) {
//need to allocate more
reallocate(count);
}
while (vectorSize < count) {
//Fill with default constructed elements
new(vectorData.get()+vectorSize) value_type{};
++vectorSize;
}
} else if (this->size() > count) {
for (size_type i=this->size()-1; i>=count; --i) {
vectorData[i].~value_type();
--vectorSize;
}
}
}
void resize(size_type count, const value_type &value) {
if (this->size() < count) {
if (this->capacity() < count) {
//need to allocate more
reallocate(count);
}
while (vectorSize < count) {
//Fill with default constructed elements
new(vectorData.get()+vectorSize) value_type{value};
++vectorSize;
}
} else if (this->size() > count) {
for (size_type i=this->size()-1; i>=count; --i) {
vectorData[i].~value_type();
--vectorSize;
}
}
}
//swap
//operators:
// ==
// !=
// <
// <=
// >
// >=
//std::swap
};
}
#endif //MYVECTOR_HPP<commit_msg>implemented max_size()<commit_after>#ifndef MYVECTOR_HPP
#define MYVECTOR_HPP 1
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>
namespace sandsnip3r {
template<typename Type>
class MyVectorIterator {
private:
};
template<typename Type>
class MyVector {
public:
typedef Type value_type;
typedef std::allocator<value_type> allocator_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef Type& reference;
typedef const Type& const_reference;
typedef Type* pointer;
typedef const Type* const_pointer;
//iterator
//const_iterator
//reverse_iterator
//const_reverse_iterator
private:
std::allocator<value_type> vectorAllocator;
std::unique_ptr<value_type[], std::function<void(value_type*)>> vectorData;
size_t vectorSize{0};
size_t vectorCapacity{0};
void reallocate(size_type newCapacity) {
//Allocate memory for the new data
if (newCapacity > this->max_size()) {
throw std::length_error("MyVector::reallocate() newCapacity (which is "+std::to_string(newCapacity)+") > max_size (which is "+std::to_string(this->max_size())+")");
}
// store it in a unique_ptr
std::unique_ptr<value_type[], std::function<void(value_type*)>> newData(vectorAllocator.allocate(newCapacity), [this, newCapacity](value_type *ptr){
vectorAllocator.deallocate(ptr, newCapacity);
});
//Move the old data into out new storage chunk
const auto &dataBegin = vectorData.get();
std::move(dataBegin, std::next(dataBegin, vectorSize), newData.get());
//Assign the new data to be the current
vectorData = std::move(newData);
//Update the capacity
vectorCapacity = newCapacity;
}
public:
//constructor
~MyVector() {
this->clear();
}
//operator=
//assign
allocator_type get_allocator() const {
return vectorAllocator;
}
reference at(size_type pos) {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->at(pos));
}
const_reference at(size_type pos) const {
if (!(pos < this->size())) {
throw std::out_of_range("MyVector::at() pos (which is "+std::to_string(pos)+") >= size (which is "+std::to_string(this->size())+")");
}
return vectorData[pos];
}
reference operator[](size_type pos) {
return vectorData[pos];
}
const_reference operator[](size_type pos) const {
return vectorData[pos];
}
reference front() {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->front());
}
const_reference front() const {
if (this->empty()) {
throw std::out_of_range("MyVector::front(), but it's empty");
}
return vectorData[0];
}
reference back() {
return const_cast<reference>(static_cast<const MyVector<value_type>*>(this)->back());
}
const_reference back() const {
if (this->empty()) {
throw std::out_of_range("MyVector::back(), but it's empty");
}
return vectorData[this->size()-1];
}
pointer data() {
return vectorData.get();
}
const_pointer data() const {
return vectorData.get();
}
//begin, cbegin
//end, cend
//rbegin, crbegin
//rend, crend
bool empty() const {
return (this->size() == 0);
}
size_type size() const {
return vectorSize;
}
//max_size
size_type max_size() const {
return std::numeric_limits<decltype(vectorSize)>::max();
}
void reserve(size_type newCapacity) {
if (this->capacity() < newCapacity) {
reallocate(newCapacity);
}
}
size_type capacity() const {
return vectorCapacity;
}
void shrink_to_fit() {
if (this->size() < this->capacity()) {
reallocate(vectorSize);
}
}
void clear() {
for (size_type i=0; i<this->size(); ++i) {
vectorData[i].~value_type();
--vectorSize;
}
}
//insert
//emplace
//erase
void push_back(const value_type &obj) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{obj};
++vectorSize;
}
void push_back(value_type &&obj) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{std::move(obj)};
++vectorSize;
}
template<class... Args>
void emplace_back(Args&&... args) {
if (this->size() == this->capacity()) {
//Need to reallocate to make space
auto newCapacity = (vectorCapacity == 0 ? 1 : vectorCapacity * 2);
reserve(newCapacity);
}
new(vectorData.get()+vectorSize) value_type{std::forward<Args>(args)...};
++vectorSize;
}
void pop_back() {
if (!this->empty()) {
vectorData[this->size()-1].~value_type();
--vectorSize;
}
}
void resize(size_type count) {
if (this->size() < count) {
if (this->capacity() < count) {
//need to allocate more
reallocate(count);
}
while (vectorSize < count) {
//Fill with default constructed elements
new(vectorData.get()+vectorSize) value_type{};
++vectorSize;
}
} else if (this->size() > count) {
for (size_type i=this->size()-1; i>=count; --i) {
vectorData[i].~value_type();
--vectorSize;
}
}
}
void resize(size_type count, const value_type &value) {
if (this->size() < count) {
if (this->capacity() < count) {
//need to allocate more
reallocate(count);
}
while (vectorSize < count) {
//Fill with default constructed elements
new(vectorData.get()+vectorSize) value_type{value};
++vectorSize;
}
} else if (this->size() > count) {
for (size_type i=this->size()-1; i>=count; --i) {
vectorData[i].~value_type();
--vectorSize;
}
}
}
//swap
//operators:
// ==
// !=
// <
// <=
// >
// >=
//std::swap
};
}
#endif //MYVECTOR_HPP<|endoftext|>
|
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/signcommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "signcommand.h"
#include "kleo-assuan.h"
#include "keyselectiondialog.h"
#include "utils/stl_util.h"
#include <kleo/keylistjob.h>
#include <kleo/signjob.h>
#include <kleo/cryptobackendfactory.h>
#include <gpgme++/data.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>
#include <gpgme++/keylistresult.h>
#include <QIODevice>
#include <QString>
#include <QStringList>
#include <QObject>
#include <QDebug>
#include <boost/bind.hpp>
using namespace Kleo;
namespace {
template <template <typename T> class Op>
struct ByProtocol {
typedef bool result_type;
bool operator()( const GpgME::Key & lhs, const GpgME::Key & rhs ) const {
return Op<int>()( qstricmp( lhs.protocolAsString(), rhs.protocolAsString() ), 0 );
}
bool operator()( const GpgME::Key & lhs, const char * rhs ) const {
return Op<int>()( qstricmp( lhs.protocolAsString(), rhs ), 0 );
}
bool operator()( const char * lhs, const GpgME::Key & rhs ) const {
return Op<int>()( qstricmp( lhs, rhs.protocolAsString() ), 0 );
}
bool operator()( const char * lhs, const char * rhs ) const {
return Op<int>()( qstricmp( lhs, rhs ), 0 );
}
};
}
class SignCommand::Private
: public AssuanCommandPrivateBaseMixin<SignCommand::Private, SignCommand>
{
Q_OBJECT
public:
Private( SignCommand * qq )
:AssuanCommandPrivateBaseMixin<SignCommand::Private, SignCommand>()
, q( qq ), m_keySelector(0), m_keyListings(0)
{}
virtual ~Private() {}
void checkInputs();
void startKeyListings();
void startSignJobs( const std::vector<GpgME::Key>& keys );
void showKeySelectionDialog();
struct Input {
QIODevice* data;
QString dataFileName;
};
SignCommand *q;
KeySelectionDialog *m_keySelector;
private Q_SLOTS:
void slotKeyListingDone( const GpgME::KeyListResult& );
void slotNextKey( const GpgME::Key& );
void slotKeySelectionDialogClosed();
void slotSigningResult( const GpgME::SigningResult & result, const QByteArray & signature );
private:
std::vector<Input> m_inputs;
std::vector<GpgME::Key> m_keys;
int m_keyListings;
int m_signJobs;
};
void SignCommand::Private::checkInputs()
{
const int numInputs = q->numBulkInputDevices( "INPUT" );
const int numOutputs = q->numBulkInputDevices( "OUTPUT" );
const int numMessages = q->numBulkInputDevices( "MESSAGE" );
//TODO use better error code if possible
if ( numMessages != 0 )
throw assuan_exception(makeError( GPG_ERR_ASS_NO_INPUT ), "Only --input and --output can be provided to the sign command, no --message");
// either the output is discarded, or there ar as many as inputs
//TODO use better error code if possible
if ( numOutputs > 0 && numInputs != numOutputs )
throw assuan_exception( makeError( GPG_ERR_ASS_NO_INPUT ), "For each --input there needs to be an --output");
for ( int i = 0; i < numInputs; ++i ) {
Input input;
input.data = q->bulkInputDevice( "INPUT", i );
input.dataFileName = q->bulkInputDeviceFileName( "INPUT", i );
m_inputs.push_back( input );
}
}
void SignCommand::Private::startKeyListings()
{
// do a key listing of private keys for both backends
const QStringList patterns; // FIXME?
m_keyListings = 2; // openpgg and cms
KeyListJob *keylisting = CryptoBackendFactory::instance()->protocol( "openpgp" )->keyListJob();
connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ),
this, SLOT( slotKeyListingDone( GpgME::KeyListResult ) ) );
connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ),
this, SLOT( slotNextKey( GpgME::Key ) ) );
if ( const GpgME::Error err = keylisting->start( patterns, true /*secret only*/) )
throw assuan_exception( err, "Unable to start keylisting" );
keylisting = Kleo::CryptoBackendFactory::instance()->protocol( "smime" )->keyListJob();
connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ),
this, SLOT( slotKeyListingDone( GpgME::KeyListResult ) ) );
connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ),
this, SLOT( slotNextKey( GpgME::Key ) ) );
if ( const GpgME::Error err = keylisting->start( patterns, true /*secret only*/) )
throw assuan_exception( err, "Unable to start keylisting" );
}
void SignCommand::Private::startSignJobs( const std::vector<GpgME::Key>& keys )
{
// make sure the keys are all of the same type
// FIXME reasonable assumption?
if ( keys.empty() || !kdtools::all( keys.begin(), keys.end(), boost::bind( ByProtocol<std::equal_to>(), _1, keys.front() ) ) ) {
q->done();
}
const CryptoBackend::Protocol* backend = CryptoBackendFactory::instance()->protocol( keys.front().protocolAsString() );
assert( backend );
Q_FOREACH( const Input input, m_inputs ) {
SignJob *job = backend->signJob();
connect( job, SIGNAL( result( GpgME::SigningResult, QByteArray ) ),
this, SLOT( slotSigningResult( GpgME::SigningResult, QByteArray ) ) );
// FIXME port to iodevice
// FIXME mode?
if ( const GpgME::Error err = job->start( keys, input.data->readAll(), GpgME::NormalSignatureMode ) ) {
q->done( err );
}
m_signJobs++;
}
}
void SignCommand::Private::slotKeySelectionDialogClosed()
{
if ( m_keySelector->result() == QDialog::Rejected ) {
q->done( q->makeError(GPG_ERR_CANCELED ) );
return;
}
// fire off the sign jobs
startSignJobs( m_keySelector->selectedKeys() );
}
void SignCommand::Private::showKeySelectionDialog()
{
m_keySelector = new KeySelectionDialog();
connect( m_keySelector, SIGNAL( accepted() ), this, SLOT( slotKeySelectionDialogClosed() ) );
connect( m_keySelector, SIGNAL( rejected() ), this, SLOT( slotKeySelectionDialogClosed() ) );
m_keySelector->addKeys( m_keys );
m_keySelector->show();
}
void SignCommand::Private::slotKeyListingDone( const GpgME::KeyListResult& result )
{
if ( result.error() )
q->done( result.error(), "Error during listing of private keys");
if ( --m_keyListings == 0 ) {
showKeySelectionDialog();
}
}
void SignCommand::Private::slotNextKey( const GpgME::Key& key )
{
m_keys.push_back( key );
}
void SignCommand::Private::slotSigningResult( const GpgME::SigningResult & result, const QByteArray & signature )
{
if ( --m_signJobs == 0 )
q->done();
}
SignCommand::SignCommand()
:d( new Private( this ) )
{
}
SignCommand::~SignCommand()
{
}
int SignCommand::doStart()
{
try {
d->checkInputs();
d->startKeyListings();
} catch ( const assuan_exception& e ) {
done( e.error_code(), e.what());
return e.error_code();
}
return 0;
}
void SignCommand::doCanceled()
{
delete d->m_keySelector;
d->m_keySelector = 0;
}
#include "signcommand.moc"
<commit_msg>Collect signing job results, write out signatures.<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/signcommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "signcommand.h"
#include "kleo-assuan.h"
#include "keyselectiondialog.h"
#include "utils/stl_util.h"
#include <kleo/keylistjob.h>
#include <kleo/signjob.h>
#include <kleo/cryptobackendfactory.h>
#include <gpgme++/data.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>
#include <gpgme++/keylistresult.h>
#include <gpgme++/signingresult.h>
#include <KLocale>
#include <QIODevice>
#include <QString>
#include <QStringList>
#include <QObject>
#include <QDebug>
#include <boost/bind.hpp>
using namespace Kleo;
namespace {
template <template <typename T> class Op>
struct ByProtocol {
typedef bool result_type;
bool operator()( const GpgME::Key & lhs, const GpgME::Key & rhs ) const {
return Op<int>()( qstricmp( lhs.protocolAsString(), rhs.protocolAsString() ), 0 );
}
bool operator()( const GpgME::Key & lhs, const char * rhs ) const {
return Op<int>()( qstricmp( lhs.protocolAsString(), rhs ), 0 );
}
bool operator()( const char * lhs, const GpgME::Key & rhs ) const {
return Op<int>()( qstricmp( lhs, rhs.protocolAsString() ), 0 );
}
bool operator()( const char * lhs, const char * rhs ) const {
return Op<int>()( qstricmp( lhs, rhs ), 0 );
}
};
}
class SignCommand::Private
: public AssuanCommandPrivateBaseMixin<SignCommand::Private, SignCommand>
{
Q_OBJECT
public:
Private( SignCommand * qq )
:AssuanCommandPrivateBaseMixin<SignCommand::Private, SignCommand>()
, q( qq ), m_keySelector(0), m_keyListings(0), m_statusSent(0)
{}
virtual ~Private() {}
void checkInputs();
void startKeyListings();
void startSignJobs( const std::vector<GpgME::Key>& keys );
void showKeySelectionDialog();
struct Input {
QIODevice* data;
QString dataFileName;
unsigned int id;
};
struct Result {
GpgME::SigningResult result;
QByteArray data;
unsigned int id;
unsigned int error;
QString errorString;
};
SignCommand *q;
KeySelectionDialog *m_keySelector;
private Q_SLOTS:
void slotKeyListingDone( const GpgME::KeyListResult& );
void slotNextKey( const GpgME::Key& );
void slotKeySelectionDialogClosed();
void slotSigningResult( const GpgME::SigningResult & result, const QByteArray & signature );
private:
void trySendingStatus( const QString & str );
std::vector<Input> m_inputs;
std::vector<GpgME::Key> m_keys;
QMap<int, Result> m_results;
QMap<const SignJob*, unsigned int> m_jobs;
int m_keyListings;
int m_signJobs;
int m_statusSent;
};
void SignCommand::Private::checkInputs()
{
const int numInputs = q->numBulkInputDevices( "INPUT" );
const int numOutputs = q->numBulkInputDevices( "OUTPUT" );
const int numMessages = q->numBulkInputDevices( "MESSAGE" );
//TODO use better error code if possible
if ( numMessages != 0 )
throw assuan_exception(makeError( GPG_ERR_ASS_NO_INPUT ), "Only --input and --output can be provided to the sign command, no --message");
// either the output is discarded, or there ar as many as inputs
//TODO use better error code if possible
if ( numOutputs > 0 && numInputs != numOutputs )
throw assuan_exception( makeError( GPG_ERR_ASS_NO_INPUT ), "For each --input there needs to be an --output");
for ( int i = 0; i < numInputs; ++i ) {
Input input;
input.id = i;
input.data = q->bulkInputDevice( "INPUT", i );
input.dataFileName = q->bulkInputDeviceFileName( "INPUT", i );
m_inputs.push_back( input );
}
}
void SignCommand::Private::startKeyListings()
{
// do a key listing of private keys for both backends
const QStringList patterns; // FIXME?
m_keyListings = 2; // openpgg and cms
KeyListJob *keylisting = CryptoBackendFactory::instance()->protocol( "openpgp" )->keyListJob();
connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ),
this, SLOT( slotKeyListingDone( GpgME::KeyListResult ) ) );
connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ),
this, SLOT( slotNextKey( GpgME::Key ) ) );
if ( const GpgME::Error err = keylisting->start( patterns, true /*secret only*/) )
throw assuan_exception( err, "Unable to start keylisting" );
keylisting = Kleo::CryptoBackendFactory::instance()->protocol( "smime" )->keyListJob();
connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ),
this, SLOT( slotKeyListingDone( GpgME::KeyListResult ) ) );
connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ),
this, SLOT( slotNextKey( GpgME::Key ) ) );
if ( const GpgME::Error err = keylisting->start( patterns, true /*secret only*/) )
throw assuan_exception( err, "Unable to start keylisting" );
}
void SignCommand::Private::startSignJobs( const std::vector<GpgME::Key>& keys )
{
// make sure the keys are all of the same type
// FIXME reasonable assumption?
if ( keys.empty() || !kdtools::all( keys.begin(), keys.end(), boost::bind( ByProtocol<std::equal_to>(), _1, keys.front() ) ) ) {
q->done();
}
const CryptoBackend::Protocol* backend = CryptoBackendFactory::instance()->protocol( keys.front().protocolAsString() );
assert( backend );
Q_FOREACH( const Input input, m_inputs ) {
SignJob *job = backend->signJob();
connect( job, SIGNAL( result( GpgME::SigningResult, QByteArray ) ),
this, SLOT( slotSigningResult( GpgME::SigningResult, QByteArray ) ) );
// FIXME port to iodevice
// FIXME mode?
if ( const GpgME::Error err = job->start( keys, input.data->readAll(), GpgME::NormalSignatureMode ) ) {
q->done( err );
}
m_jobs.insert( job, input.id );
m_signJobs++;
}
}
void SignCommand::Private::slotKeySelectionDialogClosed()
{
if ( m_keySelector->result() == QDialog::Rejected ) {
q->done( q->makeError(GPG_ERR_CANCELED ) );
return;
}
// fire off the sign jobs
startSignJobs( m_keySelector->selectedKeys() );
}
void SignCommand::Private::showKeySelectionDialog()
{
m_keySelector = new KeySelectionDialog();
connect( m_keySelector, SIGNAL( accepted() ), this, SLOT( slotKeySelectionDialogClosed() ) );
connect( m_keySelector, SIGNAL( rejected() ), this, SLOT( slotKeySelectionDialogClosed() ) );
m_keySelector->addKeys( m_keys );
m_keySelector->show();
}
void SignCommand::Private::slotKeyListingDone( const GpgME::KeyListResult& result )
{
if ( result.error() )
q->done( result.error(), "Error during listing of private keys");
if ( --m_keyListings == 0 ) {
showKeySelectionDialog();
}
}
void SignCommand::Private::slotNextKey( const GpgME::Key& key )
{
m_keys.push_back( key );
}
void SignCommand::Private::trySendingStatus( const QString & str )
{
if ( const int err = q->sendStatus( "SIGN", str ) ) {
QString errorString = i18n("Problem writing out the signature.");
q->done( err, errorString ) ;
}
}
void SignCommand::Private::slotSigningResult( const GpgME::SigningResult & result, const QByteArray & signature )
{
const SignJob * const job = qobject_cast<SignJob*>( sender() );
assert( job );
assert( m_jobs.contains( job ) );
const unsigned int id = m_jobs[job];
{
Result res;
res.result = result;
res.data = signature;
res.id = id;
m_results.insert( id, res );
}
// send status for all results received so far, but in order of id
while ( m_results.contains( m_statusSent ) ) {
SignCommand::Private::Result result = m_results[m_statusSent];
QString resultString;
try {
const GpgME::SigningResult & signres = result.result;
assert( !signres.isNull() );
const GpgME::Error signError = signres.error();
if ( signError )
throw assuan_exception( signError, "Signing failed: " );
// FIXME adjust for smime?
const QString filename = q->bulkInputDeviceFileName( "INPUT", m_statusSent ) + ".sig";
writeToOutputDeviceOrAskForFileName( result.id, result.data, filename );
resultString = "OK - Super Duper Weenie\n";
} catch ( const assuan_exception& e ) {
result.error = e.error_code();
result.errorString = e.what();
m_results[result.id] = result;
resultString = "ERR " + result.errorString;
// FIXME ask to continue or cancel
}
trySendingStatus( resultString );
m_statusSent++;
}
if ( --m_signJobs == 0 )
q->done();
}
SignCommand::SignCommand()
:d( new Private( this ) )
{
}
SignCommand::~SignCommand()
{
}
int SignCommand::doStart()
{
try {
d->checkInputs();
d->startKeyListings();
} catch ( const assuan_exception& e ) {
done( e.error_code(), e.what());
return e.error_code();
}
return 0;
}
void SignCommand::doCanceled()
{
delete d->m_keySelector;
d->m_keySelector = 0;
}
#include "signcommand.moc"
<|endoftext|>
|
<commit_before><commit_msg>Get current endpoint from interleaved docid<commit_after><|endoftext|>
|
<commit_before><commit_msg>long option for output file<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (c) 2011 Yahoo! Inc. All rights reserved. The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
This creates a binary tree topology over a set of n nodes that connect.
*/
#ifdef _WIN32
#include <WinSock2.h>
#include <Windows.h>
#include <WS2tcpip.h>
#include <io.h>
#define SHUT_RDWR SD_BOTH
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef int socklen_t;
typedef SOCKET socket_t;
int daemon(int a, int b)
{
return 0;
}
int getpid()
{
return (int) ::GetCurrentProcessId();
}
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <strings.h>
typedef int socket_t;
#endif
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <map>
using namespace std;
struct client {
uint32_t client_ip;
socket_t socket;
};
struct partial {
client* nodes;
size_t filled;
};
static int socket_sort(const void* s1, const void* s2) {
client* socket1 = (client*)s1;
client* socket2 = (client*)s2;
return socket1->client_ip - socket2->client_ip;
}
int build_tree(int* parent, uint16_t* kid_count, size_t source_count, int offset) {
if(source_count == 1) {
kid_count[offset] = 0;
return offset;
}
int height = (int)floor(log((double)source_count)/log(2.0));
int root = (1 << height) - 1;
int left_count = root;
int left_offset = offset;
int left_child = build_tree(parent, kid_count, left_count, left_offset);
int oroot = root+offset;
parent[left_child] = oroot;
size_t right_count = source_count - left_count - 1;
if (right_count > 0)
{
int right_offset = oroot+1;
int right_child = build_tree(parent, kid_count, right_count, right_offset);
parent[right_child] = oroot;
kid_count[oroot] = 2;
}
else
kid_count[oroot] = 1;
return oroot;
}
void fail_send(const socket_t fd, const void* buf, const int count)
{
if (send(fd,(char*)buf,count,0)==-1)
{
cerr << "send failed!" << endl;
exit(1);
}
}
int main(int argc, char* argv[]) {
if (argc > 2)
{
cout << "usage: spanning_tree [pid_file]" << endl;
exit(0);
}
#ifdef _WIN32
WSAData wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
int lastError = WSAGetLastError();
#endif
socket_t sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
#ifdef _WIN32
lastError = WSAGetLastError();
cerr << "can't open socket! (" << lastError << ")" << endl;
#else
cerr << "can't open socket! " << errno << endl;
#endif
exit(1);
}
int on = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0)
perror("setsockopt SO_REUSEADDR");
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
short unsigned int port = 26543;
address.sin_port = htons(port);
if (bind(sock,(sockaddr*)&address, sizeof(address)) < 0)
{
cerr << "failure to bind!" << endl;
exit(1);
}
if (daemon(1,1))
{
cerr << "failure to background!" << endl;
exit(1);
}
if (argc == 2)
{
ofstream pid_file;
pid_file.open(argv[1]);
if (!pid_file.is_open())
{
cerr << "error writing pid file" << endl;
exit(1);
}
pid_file << getpid() << endl;
pid_file.close();
}
map<size_t, partial> partial_nodesets;
while(true) {
listen(sock, 1024);
sockaddr_in client_address;
socklen_t size = sizeof(client_address);
socket_t f = accept(sock,(sockaddr*)&client_address,&size);
{
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
getnameinfo((sockaddr *) &client_address, sizeof(sockaddr), hostname, NI_MAXHOST, servInfo, NI_MAXSERV, 0);
cerr << "inbound connection from " << hostname << endl;
}
if (f < 0)
{
cerr << "bad client socket!" << endl;
exit (1);
}
size_t nonce = 0;
if (recv(f, (char*)&nonce, sizeof(nonce), 0) != sizeof(nonce))
{
cerr << "nonce read failed, exiting" << endl;
exit(1);
}
size_t total = 0;
if (recv(f, (char*)&total, sizeof(total), 0) != sizeof(total))
{
cerr << "total node count read failed, exiting" << endl;
exit(1);
}
size_t id = 0;
if (recv(f, (char*)&id, sizeof(id), 0) != sizeof(id))
{
cerr << "node id read failed, exiting" << endl;
exit(1);
}
int ok = true;
if ( id >= total )
{
cout << "invalid id! " << endl;
ok = false;
}
partial partial_nodeset;
if (partial_nodesets.find(nonce) == partial_nodesets.end() )
{
partial_nodeset.nodes = (client*) calloc(total, sizeof(client));
for (size_t i = 0; i < total; i++)
partial_nodeset.nodes[i].client_ip = (uint32_t)-1;
partial_nodeset.filled = 0;
}
else {
partial_nodeset = partial_nodesets[nonce];
partial_nodesets.erase(nonce);
}
if (ok && partial_nodeset.nodes[id].client_ip != (uint32_t)-1)
ok = false;
fail_send(f,&ok, sizeof(ok));
if (ok)
{
partial_nodeset.nodes[id].client_ip = client_address.sin_addr.s_addr;
partial_nodeset.nodes[id].socket = f;
partial_nodeset.filled++;
}
if (partial_nodeset.filled != total) //Need to wait for more connections
{
partial_nodesets[nonce] = partial_nodeset;
}
else
{//Time to make the spanning tree
qsort(partial_nodeset.nodes, total, sizeof(client), socket_sort);
int* parent = (int*)calloc(total,sizeof(int));
uint16_t* kid_count = (uint16_t*)calloc(total,sizeof(uint16_t));
int root = build_tree(parent, kid_count, total, 0);
parent[root] = -1;
for (size_t i = 0; i < total; i++)
{
fail_send(partial_nodeset.nodes[i].socket, &kid_count[i], sizeof(kid_count[i]));
}
uint16_t* client_ports=(uint16_t*)calloc(total,sizeof(uint16_t));
for(size_t i = 0;i < total;i++) {
int done = 0;
if(recv(partial_nodeset.nodes[i].socket, (char*)&(client_ports[i]), sizeof(client_ports[i]), 0) < (int) sizeof(client_ports[i]))
cerr<<" Port read failed for node "<<i<<" read "<<done<<endl;
}// all clients have bound to their ports.
for (size_t i = 0; i < total; i++)
{
if (parent[i] >= 0)
{
fail_send(partial_nodeset.nodes[i].socket, &partial_nodeset.nodes[parent[i]].client_ip, sizeof(partial_nodeset.nodes[parent[i]].client_ip));
fail_send(partial_nodeset.nodes[i].socket, &client_ports[parent[i]], sizeof(client_ports[parent[i]]));
}
else
{
int bogus = -1;
uint32_t bogus2 = -1;
fail_send(partial_nodeset.nodes[i].socket, &bogus2, sizeof(bogus2));
fail_send(partial_nodeset.nodes[i].socket, &bogus, sizeof(bogus));
}
shutdown(partial_nodeset.nodes[i].socket, SHUT_RDWR);
}
free (partial_nodeset.nodes);
}
}
#ifdef _WIN32
WSACleanup();
#endif
}
<commit_msg>add --nondaemon option to spanning_tree.cc<commit_after>/*
Copyright (c) 2011 Yahoo! Inc. All rights reserved. The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
This creates a binary tree topology over a set of n nodes that connect.
*/
#ifdef _WIN32
#include <WinSock2.h>
#include <Windows.h>
#include <WS2tcpip.h>
#include <io.h>
#define SHUT_RDWR SD_BOTH
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef int socklen_t;
typedef SOCKET socket_t;
int daemon(int a, int b)
{
return 0;
}
int getpid()
{
return (int) ::GetCurrentProcessId();
}
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <strings.h>
typedef int socket_t;
#endif
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <map>
using namespace std;
struct client {
uint32_t client_ip;
socket_t socket;
};
struct partial {
client* nodes;
size_t filled;
};
static int socket_sort(const void* s1, const void* s2) {
client* socket1 = (client*)s1;
client* socket2 = (client*)s2;
return socket1->client_ip - socket2->client_ip;
}
int build_tree(int* parent, uint16_t* kid_count, size_t source_count, int offset) {
if(source_count == 1) {
kid_count[offset] = 0;
return offset;
}
int height = (int)floor(log((double)source_count)/log(2.0));
int root = (1 << height) - 1;
int left_count = root;
int left_offset = offset;
int left_child = build_tree(parent, kid_count, left_count, left_offset);
int oroot = root+offset;
parent[left_child] = oroot;
size_t right_count = source_count - left_count - 1;
if (right_count > 0)
{
int right_offset = oroot+1;
int right_child = build_tree(parent, kid_count, right_count, right_offset);
parent[right_child] = oroot;
kid_count[oroot] = 2;
}
else
kid_count[oroot] = 1;
return oroot;
}
void fail_send(const socket_t fd, const void* buf, const int count)
{
if (send(fd,(char*)buf,count,0)==-1)
{
cerr << "send failed!" << endl;
exit(1);
}
}
int main(int argc, char* argv[]) {
if (argc > 2)
{
cout << "usage: spanning_tree [--nondaemon | pid_file]" << endl;
exit(0);
}
#ifdef _WIN32
WSAData wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
int lastError = WSAGetLastError();
#endif
socket_t sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
#ifdef _WIN32
lastError = WSAGetLastError();
cerr << "can't open socket! (" << lastError << ")" << endl;
#else
cerr << "can't open socket! " << errno << endl;
#endif
exit(1);
}
int on = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0)
perror("setsockopt SO_REUSEADDR");
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
short unsigned int port = 26543;
address.sin_port = htons(port);
if (bind(sock,(sockaddr*)&address, sizeof(address)) < 0)
{
cerr << "failure to bind!" << endl;
exit(1);
}
if (argc == 2 && strcmp("--nondaemon",argv[1])==0)
;
else
if (daemon(1,1))
{
cerr << "failure to background!" << endl;
exit(1);
}
if (argc == 2)
{
ofstream pid_file;
pid_file.open(argv[1]);
if (!pid_file.is_open())
{
cerr << "error writing pid file" << endl;
exit(1);
}
pid_file << getpid() << endl;
pid_file.close();
}
map<size_t, partial> partial_nodesets;
while(true) {
listen(sock, 1024);
sockaddr_in client_address;
socklen_t size = sizeof(client_address);
socket_t f = accept(sock,(sockaddr*)&client_address,&size);
{
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
getnameinfo((sockaddr *) &client_address, sizeof(sockaddr), hostname, NI_MAXHOST, servInfo, NI_MAXSERV, 0);
cerr << "inbound connection from " << hostname << endl;
}
if (f < 0)
{
cerr << "bad client socket!" << endl;
exit (1);
}
size_t nonce = 0;
if (recv(f, (char*)&nonce, sizeof(nonce), 0) != sizeof(nonce))
{
cerr << "nonce read failed, exiting" << endl;
exit(1);
}
size_t total = 0;
if (recv(f, (char*)&total, sizeof(total), 0) != sizeof(total))
{
cerr << "total node count read failed, exiting" << endl;
exit(1);
}
size_t id = 0;
if (recv(f, (char*)&id, sizeof(id), 0) != sizeof(id))
{
cerr << "node id read failed, exiting" << endl;
exit(1);
}
int ok = true;
if ( id >= total )
{
cout << "invalid id! " << endl;
ok = false;
}
partial partial_nodeset;
if (partial_nodesets.find(nonce) == partial_nodesets.end() )
{
partial_nodeset.nodes = (client*) calloc(total, sizeof(client));
for (size_t i = 0; i < total; i++)
partial_nodeset.nodes[i].client_ip = (uint32_t)-1;
partial_nodeset.filled = 0;
}
else {
partial_nodeset = partial_nodesets[nonce];
partial_nodesets.erase(nonce);
}
if (ok && partial_nodeset.nodes[id].client_ip != (uint32_t)-1)
ok = false;
fail_send(f,&ok, sizeof(ok));
if (ok)
{
partial_nodeset.nodes[id].client_ip = client_address.sin_addr.s_addr;
partial_nodeset.nodes[id].socket = f;
partial_nodeset.filled++;
}
if (partial_nodeset.filled != total) //Need to wait for more connections
{
partial_nodesets[nonce] = partial_nodeset;
}
else
{//Time to make the spanning tree
qsort(partial_nodeset.nodes, total, sizeof(client), socket_sort);
int* parent = (int*)calloc(total,sizeof(int));
uint16_t* kid_count = (uint16_t*)calloc(total,sizeof(uint16_t));
int root = build_tree(parent, kid_count, total, 0);
parent[root] = -1;
for (size_t i = 0; i < total; i++)
{
fail_send(partial_nodeset.nodes[i].socket, &kid_count[i], sizeof(kid_count[i]));
}
uint16_t* client_ports=(uint16_t*)calloc(total,sizeof(uint16_t));
for(size_t i = 0;i < total;i++) {
int done = 0;
if(recv(partial_nodeset.nodes[i].socket, (char*)&(client_ports[i]), sizeof(client_ports[i]), 0) < (int) sizeof(client_ports[i]))
cerr<<" Port read failed for node "<<i<<" read "<<done<<endl;
}// all clients have bound to their ports.
for (size_t i = 0; i < total; i++)
{
if (parent[i] >= 0)
{
fail_send(partial_nodeset.nodes[i].socket, &partial_nodeset.nodes[parent[i]].client_ip, sizeof(partial_nodeset.nodes[parent[i]].client_ip));
fail_send(partial_nodeset.nodes[i].socket, &client_ports[parent[i]], sizeof(client_ports[parent[i]]));
}
else
{
int bogus = -1;
uint32_t bogus2 = -1;
fail_send(partial_nodeset.nodes[i].socket, &bogus2, sizeof(bogus2));
fail_send(partial_nodeset.nodes[i].socket, &bogus, sizeof(bogus));
}
shutdown(partial_nodeset.nodes[i].socket, SHUT_RDWR);
}
free (partial_nodeset.nodes);
}
}
#ifdef _WIN32
WSACleanup();
#endif
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediadescriptor.hxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_
//_______________________________________________
// includes
#include <comphelper/sequenceashashmap.hxx>
#include <rtl/ustring.hxx>
#include "comphelper/comphelperdllapi.h"
namespace com { namespace sun { namespace star { namespace io {
class XInputStream;
} } } }
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
struct.
@descr It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
represent the MediaDescriptor item.
Further this helper defines often used functions (as e.g. open of the required streams,
consistent checks etcpp.) and it defines all useable property names.
@attention This class isnt threadsafe and must be guarded from outside!
*/
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
//-------------------------------------------
// const
public:
//---------------------------------------
/** @short these methods can be used to get the different property names
as static const OUString values.
@descr Because definition and declaration of static const class members
does not work as expected under windows (under unix it works as well)
these way must be used :-(
*/
static const ::rtl::OUString& PROP_ASTEMPLATE();
static const ::rtl::OUString& PROP_CHARACTERSET();
static const ::rtl::OUString& PROP_DEEPDETECTION();
static const ::rtl::OUString& PROP_DETECTSERVICE();
static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
static const ::rtl::OUString& PROP_EXTENSION();
static const ::rtl::OUString& PROP_FILENAME();
static const ::rtl::OUString& PROP_FILTERNAME();
static const ::rtl::OUString& PROP_FILTEROPTIONS();
static const ::rtl::OUString& PROP_FORMAT();
static const ::rtl::OUString& PROP_FRAMENAME();
static const ::rtl::OUString& PROP_HIDDEN();
static const ::rtl::OUString& PROP_INPUTSTREAM();
static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
static const ::rtl::OUString& PROP_JUMPMARK();
static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
static const ::rtl::OUString& PROP_MEDIATYPE();
static const ::rtl::OUString& PROP_MINIMIZED();
static const ::rtl::OUString& PROP_NOAUTOSAVE();
static const ::rtl::OUString& PROP_OPENNEWVIEW();
static const ::rtl::OUString& PROP_OUTPUTSTREAM();
static const ::rtl::OUString& PROP_PASSWORD();
static const ::rtl::OUString& PROP_PATTERN();
static const ::rtl::OUString& PROP_POSSIZE();
static const ::rtl::OUString& PROP_POSTDATA();
static const ::rtl::OUString& PROP_POSTSTRING();
static const ::rtl::OUString& PROP_PREVIEW();
static const ::rtl::OUString& PROP_READONLY();
static const ::rtl::OUString& PROP_REFERRER();
static const ::rtl::OUString& PROP_SALVAGEDFILE();
static const ::rtl::OUString& PROP_SILENT();
static const ::rtl::OUString& PROP_STATUSINDICATOR();
static const ::rtl::OUString& PROP_STREAM();
static const ::rtl::OUString& PROP_TEMPLATENAME();
static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
static const ::rtl::OUString& PROP_TITLE();
static const ::rtl::OUString& PROP_TYPENAME();
static const ::rtl::OUString& PROP_UCBCONTENT();
static const ::rtl::OUString& PROP_UPDATEDOCMODE();
static const ::rtl::OUString& PROP_URL();
static const ::rtl::OUString& PROP_VERSION();
static const ::rtl::OUString& PROP_VIEWID();
static const ::rtl::OUString& PROP_REPAIRPACKAGE();
static const ::rtl::OUString& PROP_DOCUMENTTITLE();
static const ::rtl::OUString& PROP_MODEL();
static const ::rtl::OUString& PROP_VIEWONLY();
static const ::rtl::OUString& PROP_DOCUMENTBASEURL();
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short these ctors do nothing - excepting that they forward
the given parameters to the base class ctors.
@descr The ctros must be overwritten to resolve conflicts with
the default ctors of the compiler :-(.
*/
MediaDescriptor();
MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short it checks if the descriptor already has a valid
InputStream item and creates a new one, if not.
@descr This method uses the current items of this MediaDescriptor,
to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
It creates a seekable stream and put it into the descriptor.
A might existing InteractionHandler will be used automaticly,
to solve problems!
@param bLockFile
specifies whether the file should be locked
@return TRUE, if the stream was already part of the descriptor or could
be created as new item. FALSE otherwhise.
*/
// HACK: IT SHOULD BE ONLY ONE METHOD, THE TEMPORARY SOLUTION ALLOWS TO AVOID INCOMPATIBLE BUILD
sal_Bool addInputStream_Impl( sal_Bool bLockFile );
sal_Bool addInputStream();
sal_Bool addInputStreamNoLock();
//---------------------------------------
/** @short it checks if the descriptor describes a readonly stream.
@descr The descriptor itself isnt changed doing so.
It's only checked if the stream seems to be based
of a real readonly file.
@Attention
We dont check the property "ReadOnly" here. Because
this property can be set from outside and overwrites
the readonly state of the stream.
If e.g. the stream could be opened read/write ...
but "ReadOnly" property is set to TRUE, this means:
show a readonly UI on top of this read/write stream.
@return TRUE, if the stream must be interpreted as readonly ...
FALSE otherwhise.
*/
sal_Bool isStreamReadOnly() const;
//-------------------------------------------
// helper
private:
//---------------------------------------
/** @short tries to open a stream by using the given PostData stream.
@descr The stream is used directly ...
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param _rxPostData
the PostData stream.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
@throw [css::lang::IllegalArgumentException]
if the given PostData stream is <NULL/>.
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData(
const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& _rxPostData
) throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short tries to open a stream by using the given URL.
@descr First it tries to open the content in r/w mode (if its
allowed to do so). Only in case its not allowed or it failed
the stream will be tried to open in readonly mode.
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param sURL
the URL for open.
@param bLockFile
specifies whether the file should be locked
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(
const ::rtl::OUString& sURL,
sal_Bool bLockFile
) throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short some URL parts can make trouble for opening streams (e.g. jumpmarks.)
An URL should be "normalized" before its used.
@param sURL
the original URL (e.g. including a jumpmark)
@return [string]
the "normalized" URL (e.g. without jumpmark)
*/
COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};
} // namespace comphelper
#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<commit_msg>INTEGRATION: CWS dba30c (1.14.14); FILE MERGED 2008/05/13 06:50:40 fs 1.14.14.1: joining changes from CWS odbmacros3 to CWS dba30c 2008/05/07 08:15:29 fs 1.13.8.1: during #i49133#: +PROP_VIEWCONTROLLERNAME 2008/05/09 09:28:53 fs 1.13.8.2: RESYNC: (1.13-1.14); FILE MERGED<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediadescriptor.hxx,v $
* $Revision: 1.15 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _COMPHELPER_MEDIADESCRIPTOR_HXX_
#define _COMPHELPER_MEDIADESCRIPTOR_HXX_
//_______________________________________________
// includes
#include <comphelper/sequenceashashmap.hxx>
#include <rtl/ustring.hxx>
#include "comphelper/comphelperdllapi.h"
namespace com { namespace sun { namespace star { namespace io {
class XInputStream;
} } } }
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short can be used to work with a <type scope="::com::sun::star::document">MediaDescriptor</type>
struct.
@descr It wraps a ::std::hash_map around the Sequence< css::beans::PropertyValue >, which
represent the MediaDescriptor item.
Further this helper defines often used functions (as e.g. open of the required streams,
consistent checks etcpp.) and it defines all useable property names.
@attention This class isnt threadsafe and must be guarded from outside!
*/
class COMPHELPER_DLLPUBLIC MediaDescriptor : public SequenceAsHashMap
{
//-------------------------------------------
// const
public:
//---------------------------------------
/** @short these methods can be used to get the different property names
as static const OUString values.
@descr Because definition and declaration of static const class members
does not work as expected under windows (under unix it works as well)
these way must be used :-(
*/
static const ::rtl::OUString& PROP_ASTEMPLATE();
static const ::rtl::OUString& PROP_CHARACTERSET();
static const ::rtl::OUString& PROP_DEEPDETECTION();
static const ::rtl::OUString& PROP_DETECTSERVICE();
static const ::rtl::OUString& PROP_DOCUMENTSERVICE();
static const ::rtl::OUString& PROP_EXTENSION();
static const ::rtl::OUString& PROP_FILENAME();
static const ::rtl::OUString& PROP_FILTERNAME();
static const ::rtl::OUString& PROP_FILTEROPTIONS();
static const ::rtl::OUString& PROP_FORMAT();
static const ::rtl::OUString& PROP_FRAMENAME();
static const ::rtl::OUString& PROP_HIDDEN();
static const ::rtl::OUString& PROP_INPUTSTREAM();
static const ::rtl::OUString& PROP_INTERACTIONHANDLER();
static const ::rtl::OUString& PROP_JUMPMARK();
static const ::rtl::OUString& PROP_MACROEXECUTIONMODE();
static const ::rtl::OUString& PROP_MEDIATYPE();
static const ::rtl::OUString& PROP_MINIMIZED();
static const ::rtl::OUString& PROP_NOAUTOSAVE();
static const ::rtl::OUString& PROP_OPENNEWVIEW();
static const ::rtl::OUString& PROP_OUTPUTSTREAM();
static const ::rtl::OUString& PROP_PASSWORD();
static const ::rtl::OUString& PROP_PATTERN();
static const ::rtl::OUString& PROP_POSSIZE();
static const ::rtl::OUString& PROP_POSTDATA();
static const ::rtl::OUString& PROP_POSTSTRING();
static const ::rtl::OUString& PROP_PREVIEW();
static const ::rtl::OUString& PROP_READONLY();
static const ::rtl::OUString& PROP_REFERRER();
static const ::rtl::OUString& PROP_SALVAGEDFILE();
static const ::rtl::OUString& PROP_SILENT();
static const ::rtl::OUString& PROP_STATUSINDICATOR();
static const ::rtl::OUString& PROP_STREAM();
static const ::rtl::OUString& PROP_TEMPLATENAME();
static const ::rtl::OUString& PROP_TEMPLATEREGIONNAME();
static const ::rtl::OUString& PROP_TITLE();
static const ::rtl::OUString& PROP_TYPENAME();
static const ::rtl::OUString& PROP_UCBCONTENT();
static const ::rtl::OUString& PROP_UPDATEDOCMODE();
static const ::rtl::OUString& PROP_URL();
static const ::rtl::OUString& PROP_VERSION();
static const ::rtl::OUString& PROP_VIEWID();
static const ::rtl::OUString& PROP_REPAIRPACKAGE();
static const ::rtl::OUString& PROP_DOCUMENTTITLE();
static const ::rtl::OUString& PROP_MODEL();
static const ::rtl::OUString& PROP_VIEWONLY();
static const ::rtl::OUString& PROP_DOCUMENTBASEURL();
static const ::rtl::OUString& PROP_VIEWCONTROLLERNAME();
//-------------------------------------------
// interface
public:
//---------------------------------------
/** @short these ctors do nothing - excepting that they forward
the given parameters to the base class ctors.
@descr The ctros must be overwritten to resolve conflicts with
the default ctors of the compiler :-(.
*/
MediaDescriptor();
MediaDescriptor(const ::com::sun::star::uno::Any& aSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
MediaDescriptor(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short it checks if the descriptor already has a valid
InputStream item and creates a new one, if not.
@descr This method uses the current items of this MediaDescriptor,
to open the stream (as e.g. URL, ReadOnly, PostData etcpp.).
It creates a seekable stream and put it into the descriptor.
A might existing InteractionHandler will be used automaticly,
to solve problems!
@param bLockFile
specifies whether the file should be locked
@return TRUE, if the stream was already part of the descriptor or could
be created as new item. FALSE otherwhise.
*/
// HACK: IT SHOULD BE ONLY ONE METHOD, THE TEMPORARY SOLUTION ALLOWS TO AVOID INCOMPATIBLE BUILD
sal_Bool addInputStream_Impl( sal_Bool bLockFile );
sal_Bool addInputStream();
sal_Bool addInputStreamNoLock();
//---------------------------------------
/** @short it checks if the descriptor describes a readonly stream.
@descr The descriptor itself isnt changed doing so.
It's only checked if the stream seems to be based
of a real readonly file.
@Attention
We dont check the property "ReadOnly" here. Because
this property can be set from outside and overwrites
the readonly state of the stream.
If e.g. the stream could be opened read/write ...
but "ReadOnly" property is set to TRUE, this means:
show a readonly UI on top of this read/write stream.
@return TRUE, if the stream must be interpreted as readonly ...
FALSE otherwhise.
*/
sal_Bool isStreamReadOnly() const;
//-------------------------------------------
// helper
private:
//---------------------------------------
/** @short tries to open a stream by using the given PostData stream.
@descr The stream is used directly ...
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param _rxPostData
the PostData stream.
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
@throw [css::lang::IllegalArgumentException]
if the given PostData stream is <NULL/>.
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithPostData(
const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& _rxPostData
) throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short tries to open a stream by using the given URL.
@descr First it tries to open the content in r/w mode (if its
allowed to do so). Only in case its not allowed or it failed
the stream will be tried to open in readonly mode.
The MediaDescriptor itself is changed inside this method.
Means: the stream is added internal and not returned by a value.
@param sURL
the URL for open.
@param bLockFile
specifies whether the file should be locked
@return TRUE if the stream could be added successfully.
Note: If FALSE is returned, the error was already handled inside!
@throw [css::uno::RuntimeException]
if the MediaDescriptor seems to be invalid!
*/
COMPHELPER_DLLPRIVATE sal_Bool impl_openStreamWithURL(
const ::rtl::OUString& sURL,
sal_Bool bLockFile
) throw(::com::sun::star::uno::RuntimeException);
//---------------------------------------
/** @short some URL parts can make trouble for opening streams (e.g. jumpmarks.)
An URL should be "normalized" before its used.
@param sURL
the original URL (e.g. including a jumpmark)
@return [string]
the "normalized" URL (e.g. without jumpmark)
*/
COMPHELPER_DLLPRIVATE ::rtl::OUString impl_normalizeURL(const ::rtl::OUString& sURL);
};
} // namespace comphelper
#endif // _COMPHELPER_MEDIADESCRIPTOR_HXX_
<|endoftext|>
|
<commit_before>// Copyright 2018 Alexander Gallego
//
#include <cstring>
#include <memory>
#include <benchmark/benchmark.h>
#include <fmt/format.h>
#include "hashing/hashing_utils.h"
using namespace smf; // NOLINT
static uint64_t
fixed_hash(const std::string &topic, uint32_t partition) {
const std::size_t kBufSize = 50;
char buf[kBufSize];
std::memset(buf, 0, kBufSize);
std::memcpy(buf, (char *)&partition, 4);
std::memcpy(buf + 4, topic.c_str(), std::min(kBufSize - 4, topic.size()));
return xxhash_64(buf, kBufSize);
}
static uint64_t
stack_hash(const std::string &topic, uint32_t partition) {
const std::size_t kBufSize = topic.size() + 4;
char buf[kBufSize];
std::memset(buf, 0, kBufSize);
std::memcpy(buf, (char *)&partition, 4);
std::memcpy(buf + 4, topic.c_str(), topic.size());
return xxhash_64(buf, kBufSize);
}
static uint64_t
dynamic_hash(const std::string &topic, uint32_t partition) {
fmt::MemoryWriter w;
w.write("{}:{}", topic, partition);
return xxhash_64(w.data(), w.size());
}
static uint64_t
incremental_hash(const std::string &topic, uint32_t partition) {
incremental_xxhash64 inc;
inc.update((char *)&partition, sizeof(partition));
inc.update(topic.data(), topic.size());
return inc.digest();
}
static void
BM_fixed_hash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(fixed_hash(x, state.range(0)));
}
}
BENCHMARK(BM_fixed_hash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
static void
BM_stackhash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(stack_hash(x, state.range(0)));
}
}
BENCHMARK(BM_stackhash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
static void
BM_dynamichash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(dynamic_hash(x, state.range(0)));
}
}
BENCHMARK(BM_dynamichash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
static void
BM_incremental_hash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(incremental_hash(x, state.range(0)));
}
}
BENCHMARK(BM_incremental_hash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
BENCHMARK_MAIN();
<commit_msg>fixing benchmarks<commit_after>// Copyright 2018 Alexander Gallego
//
#include <cstring>
#include <memory>
#include <benchmark/benchmark.h>
#include <fmt/format.h>
#include "hashing/hashing_utils.h"
using namespace smf; // NOLINT
static uint64_t
fixed_hash(const std::string &topic, uint32_t partition) {
const std::size_t kBufSize = 50;
char buf[kBufSize];
std::memset(buf, 0, kBufSize);
std::memcpy(buf, (char *)&partition, 4);
std::memcpy(buf + 4, topic.c_str(), std::min(kBufSize - 4, topic.size()));
return xxhash_64(buf, kBufSize);
}
static uint64_t
stack_hash(const std::string &topic, uint32_t partition) {
const std::size_t kBufSize = topic.size() + 4;
char buf[kBufSize];
std::memset(buf, 0, kBufSize);
std::memcpy(buf, (char *)&partition, 4);
std::memcpy(buf + 4, topic.c_str(), topic.size());
return xxhash_64(buf, kBufSize);
}
static uint64_t
dynamic_hash(const std::string &topic, uint32_t partition) {
fmt::MemoryWriter w;
w.write("{}:{}", topic, partition);
return xxhash_64(w.data(), w.size());
}
static uint64_t
incremental_hash(const std::string &topic, uint32_t partition) {
incremental_xxhash64 inc;
inc.update((char *)&partition, sizeof(partition));
inc.update(topic.data(), topic.size());
return inc.digest();
}
static void
BM_fixed_hash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(fixed_hash(x, state.range(0)));
}
}
BENCHMARK(BM_fixed_hash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8});
static void
BM_stackhash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(stack_hash(x, state.range(0)));
}
}
BENCHMARK(BM_stackhash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
static void
BM_dynamichash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(dynamic_hash(x, state.range(0)));
}
}
BENCHMARK(BM_dynamichash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
static void
BM_incremental_hash(benchmark::State &state) {
for (auto _ : state) {
state.PauseTiming();
std::string x;
x.reserve(state.range(0));
for (auto i = 0u; i < state.range(0); ++i) { x.push_back('x'); }
state.ResumeTiming();
benchmark::DoNotOptimize(incremental_hash(x, state.range(0)));
}
}
BENCHMARK(BM_incremental_hash)
->Args({1 << 1, 1 << 1})
->Args({1 << 4, 1 << 4})
->Args({1 << 8, 1 << 8})
->Args({1 << 16, 1 << 16});
BENCHMARK_MAIN();
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/scoring/scoring_result.h>
#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>
#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/make_shared.hpp>
/**
* \file scoring_result.cxx
*
* \brief Python bindings for scoring_result.
*/
using namespace boost::python;
static vistk::scoring_result_t new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth);
static vistk::scoring_result::count_t result_get_hit(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_miss(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_truth(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self);
static vistk::scoring_result_t result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs);
BOOST_PYTHON_MODULE(scoring_result)
{
class_<vistk::scoring_result_t>("ScoringResult"
, "A result from a scoring algorithm."
, no_init)
.def("__init__", &new_result
, (arg("hit"), arg("miss"), arg("truth"))
, "Constructor.")
.def("hit_count", &result_get_hit)
.def("miss_count", &result_get_miss)
.def("truth_count", &result_get_truth)
.def("percent_detection", &result_get_percent_detection)
.def("precision", &result_get_precision)
.def("__add__", &result_add
, (arg("lhs"), arg("rhs")))
;
vistk::python::register_type<vistk::scoring_result_t>(20);
}
vistk::scoring_result_t
new_result(vistk::scoring_result::count_t hit, vistk::scoring_result::count_t miss, vistk::scoring_result::count_t truth)
{
return boost::make_shared<vistk::scoring_result>(hit, miss, truth);
}
vistk::scoring_result::count_t
result_get_hit(vistk::scoring_result_t const& self)
{
return self->hit_count;
}
vistk::scoring_result::count_t
result_get_miss(vistk::scoring_result_t const& self)
{
return self->miss_count;
}
vistk::scoring_result::count_t
result_get_truth(vistk::scoring_result_t const& self)
{
return self->truth_count;
}
vistk::scoring_result::result_t
result_get_percent_detection(vistk::scoring_result_t const& self)
{
return self->percent_detection();
}
vistk::scoring_result::result_t
result_get_precision(vistk::scoring_result_t const& self)
{
return self->precision();
}
vistk::scoring_result_t
result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs)
{
return (lhs + rhs);
}
<commit_msg>Update Python bindings for scoring_result<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <vistk/scoring/scoring_result.h>
#include <vistk/python/any_conversion/prototypes.h>
#include <vistk/python/any_conversion/registration.h>
#include <boost/python/class.hpp>
#include <boost/python/module.hpp>
#include <boost/make_shared.hpp>
/**
* \file scoring_result.cxx
*
* \brief Python bindings for scoring_result.
*/
using namespace boost::python;
static vistk::scoring_result_t new_result(vistk::scoring_result::count_t true_positive,
vistk::scoring_result::count_t false_positive,
vistk::scoring_result::count_t total_true,
vistk::scoring_result::count_t possible);
static vistk::scoring_result::count_t result_get_true_positives(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_false_positives(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_total_trues(vistk::scoring_result_t const& self);
static vistk::scoring_result::count_t result_get_total_possible(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_percent_detection(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_precision(vistk::scoring_result_t const& self);
static vistk::scoring_result::result_t result_get_specificity(vistk::scoring_result_t const& self);
static vistk::scoring_result_t result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs);
BOOST_PYTHON_MODULE(scoring_result)
{
class_<vistk::scoring_result_t>("ScoringResult"
, "A result from a scoring algorithm."
, no_init)
.def("__init__", &new_result
, (arg("true_positive"), arg("false_positive"), arg("total_true"), arg("possible") = 0)
, "Constructor.")
.def("true_positives", &result_get_true_positives)
.def("false_positives", &result_get_false_positives)
.def("total_trues", &result_get_total_trues)
.def("total_possible", &result_get_total_possible)
.def("percent_detection", &result_get_percent_detection)
.def("precision", &result_get_precision)
.def("specificity", &result_get_specificity)
.def("__add__", &result_add
, (arg("lhs"), arg("rhs")))
;
vistk::python::register_type<vistk::scoring_result_t>(20);
}
vistk::scoring_result_t
new_result(vistk::scoring_result::count_t true_positive,
vistk::scoring_result::count_t false_positive,
vistk::scoring_result::count_t total_true,
vistk::scoring_result::count_t possible)
{
return boost::make_shared<vistk::scoring_result>(true_positive, false_positive, total_true, possible);
}
vistk::scoring_result::count_t
result_get_true_positives(vistk::scoring_result_t const& self)
{
return self->true_positives;
}
vistk::scoring_result::count_t
result_get_false_positives(vistk::scoring_result_t const& self)
{
return self->false_positives;
}
vistk::scoring_result::count_t
result_get_total_trues(vistk::scoring_result_t const& self)
{
return self->total_trues;
}
vistk::scoring_result::count_t
result_get_total_possible(vistk::scoring_result_t const& self)
{
return self->total_possible;
}
vistk::scoring_result::result_t
result_get_percent_detection(vistk::scoring_result_t const& self)
{
return self->percent_detection();
}
vistk::scoring_result::result_t
result_get_precision(vistk::scoring_result_t const& self)
{
return self->precision();
}
vistk::scoring_result::result_t
result_get_specificity(vistk::scoring_result_t const& self)
{
return self->specificity();
}
vistk::scoring_result_t
result_add(vistk::scoring_result_t const& lhs, vistk::scoring_result_t const& rhs)
{
return (lhs + rhs);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <memory>
#include <mutex>
#include <tuple>
#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"
namespace elasticsearch {
class http_transport_t {
public:
typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;
typedef boost::asio::io_service loop_type;
typedef http_connection_t connection_type;
typedef pool_t<connection_type> pool_type;
typedef pool_type::endpoint_type endpoint_type;
private:
settings_t settings;
loop_type& loop;
logger_type& log;
pool_type pool;
std::unique_ptr<balancing::strategy<pool_type>> balancer;
public:
http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
settings(settings),
loop(loop),
log(log),
balancer(new balancing::round_robin<pool_type>())
{}
void add_nodes(const std::vector<endpoint_type>& endpoints) {
for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
add_node(*it);
}
}
void add_node(const endpoint_type& endpoint) {
boost::system::error_code ec;
auto address = endpoint.address().to_string(ec);
if (ec) {
LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
return;
}
LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
bool inserted;
std::tie(std::ignore, inserted) = pool.insert(
endpoint, std::make_shared<connection_type>(endpoint, loop, log)
);
if (!inserted) {
LOG(log, "adding endpoint to the pool is rejected - already exists");
return;
}
}
void sniff() {
LOG(log, "sniffing nodes info ...");
perform(actions::nodes_info_t(),
std::bind(&http_transport_t::on_sniff, this, std::placeholders::_1));
}
template<class Action>
void perform(Action&& action, typename callback<Action>::type callback) {
BOOST_ASSERT(balancer);
LOG(log, "performing request ...");
auto connection = balancer->next(pool);
if (!connection) {
//!@todo: Write error to the callback via post.
return;
}
LOG(log, "balancing at %s", connection->endpoint());
request_watcher_t<Action> watcher(*this, callback);
connection->perform(std::move(action), watcher);
}
private:
void on_sniff(result_t<response::nodes_info_t>&& result) {
if (auto* nodes_info = boost::get<response::nodes_info_t>(&result)) {
LOG(log, "successfully sniffed %d nodes", nodes_info->nodes.size());
const auto& nodes = nodes_info->nodes;
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
}
}
}
template<class Action>
struct request_watcher_t {
typedef Action action_type;
typedef typename Action::result_type result_type;
typedef typename callback<action_type>::type callback_type;
http_transport_t& transport;
callback_type callback;
request_watcher_t(http_transport_t& transport, callback_type callback) :
transport(transport),
callback(callback)
{}
void operator()(result_type&& result) const {
if (boost::get<boost::system::error_code>(&result)) {
if (transport.settings.sniffer.when.error) {
//!@todo: Need to transfer sniff try number with error.
//! If it > max -> stop sniffing.
LOG(transport.log, "sniff.when.error is true - resniffing ...");
transport.sniff();
}
}
callback(std::move(result));
}
};
};
} // namespace elasticsearch
<commit_msg>[Elasticsearch] Wording.<commit_after>#pragma once
#include <memory>
#include <mutex>
#include <tuple>
#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"
namespace elasticsearch {
class http_transport_t {
public:
typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;
typedef boost::asio::io_service loop_type;
typedef http_connection_t connection_type;
typedef pool_t<connection_type> pool_type;
typedef pool_type::endpoint_type endpoint_type;
private:
settings_t settings;
loop_type& loop;
logger_type& log;
pool_type pool;
std::unique_ptr<balancing::strategy<pool_type>> balancer;
public:
http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
settings(settings),
loop(loop),
log(log),
balancer(new balancing::round_robin<pool_type>())
{}
void add_nodes(const std::vector<endpoint_type>& endpoints) {
for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
add_node(*it);
}
}
void add_node(const endpoint_type& endpoint) {
boost::system::error_code ec;
auto address = endpoint.address().to_string(ec);
if (ec) {
LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
return;
}
LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
bool inserted;
std::tie(std::ignore, inserted) = pool.insert(
endpoint, std::make_shared<connection_type>(endpoint, loop, log)
);
if (!inserted) {
LOG(log, "adding endpoint to the pool is rejected - already exists");
return;
}
}
void sniff() {
LOG(log, "sniffing nodes info ...");
perform(actions::nodes_info_t(),
std::bind(&http_transport_t::on_sniff, this, std::placeholders::_1));
}
template<class Action>
void perform(Action&& action, typename callback<Action>::type callback) {
BOOST_ASSERT(balancer);
LOG(log, "performing request ...");
auto connection = balancer->next(pool);
if (!connection) {
//!@todo: Write error to the callback via post.
return;
}
LOG(log, "balancing at %s", connection->endpoint());
request_watcher_t<Action> watcher(*this, callback);
connection->perform(std::move(action), watcher);
}
private:
void on_sniff(result_t<response::nodes_info_t>&& result) {
if (auto* nodes_info = boost::get<response::nodes_info_t>(&result)) {
LOG(log, "successfully sniffed %d node(s)", nodes_info->nodes.size());
const auto& nodes = nodes_info->nodes;
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
}
}
}
template<class Action>
struct request_watcher_t {
typedef Action action_type;
typedef typename Action::result_type result_type;
typedef typename callback<action_type>::type callback_type;
http_transport_t& transport;
callback_type callback;
request_watcher_t(http_transport_t& transport, callback_type callback) :
transport(transport),
callback(callback)
{}
void operator()(result_type&& result) const {
if (boost::get<boost::system::error_code>(&result)) {
if (transport.settings.sniffer.when.error) {
//!@todo: Need to transfer sniff try number with error.
//! If it > max -> stop sniffing.
LOG(transport.log, "sniff.when.error is true - resniffing ...");
transport.sniff();
}
}
callback(std::move(result));
}
};
};
} // namespace elasticsearch
<|endoftext|>
|
<commit_before>#include <limits>
#include <vector>
#include <set>
#include <iostream>
#include <typeinfo>
#include <stdint.h>
#include <tightdb/util/type_list.hpp>
#include <tightdb/util/safe_int_ops.hpp>
#include "util/demangle.hpp"
#include "util/super_int.hpp"
#include "test.hpp"
using namespace std;
using namespace tightdb::util;
using namespace tightdb::test_util;
using unit_test::TestResults;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
// FIXME: Test T -> tightdb::test_util::super_int -> T using min/max
// values for each fundamental standard type, and also using 0 and -1
// for signed types.
// FIXME: Test tightdb::util::from_twos_compl(). For each type pair
// (S,U), and for each super_int `i` in special set, if i.get_as<S>(s)
// && two's compl of `s` can be stored in U without loss of
// information, then CHECK_EQUAL(s, from_twos_compl(U(s))). Two's
// compl of `s` can be stored in U without loss of information if, and
// only if make_unsigned<S>::type(s < 0 ? -1-s : s) <
// (U(1)<<(lim_u::digits-1)).
// FIXME: Test tightdb::util::int_shift_left_with_overflow_detect().
// FIXME: Test tightdb::util::int_cast_with_overflow_detect().
TEST(SafeIntOps_AddWithOverflowDetect)
{
int lval = 255;
CHECK(!int_add_with_overflow_detect(lval, char(10)));
}
namespace {
template<class T_1, class T_2>
void test_two_args(TestResults& test_results, const set<super_int>& values)
{
// if (!(SameType<T_1, bool>::value && SameType<T_2, char>::value))
// return;
// cerr << get_type_name<T_1>() << ", " << get_type_name<T_2>() << "\n";
vector<T_1> values_1;
vector<T_2> values_2;
{
typedef set<super_int>::const_iterator iter;
iter end = values.end();
for (iter i = values.begin(); i != end; ++i) {
T_1 v_1;
if (i->get_as<T_1>(v_1))
values_1.push_back(v_1);
T_2 v_2;
if (i->get_as<T_2>(v_2))
values_2.push_back(v_2);
}
}
typedef typename vector<T_1>::const_iterator iter_1;
typedef typename vector<T_2>::const_iterator iter_2;
iter_1 end_1 = values_1.end();
iter_2 end_2 = values_2.end();
for (iter_1 i_1 = values_1.begin(); i_1 != end_1; ++i_1) {
for (iter_2 i_2 = values_2.begin(); i_2 != end_2; ++i_2) {
// cout << "--> " << promote(*i_1) << " vs " << promote(*i_2) << "\n";
// Comparisons
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool eq_1 = s_1 == s_2;
bool eq_2 = int_equal_to(v_1, v_2);
CHECK_EQUAL(eq_1, eq_2);
bool ne_1 = s_1 != s_2;
bool ne_2 = int_not_equal_to(v_1, v_2);
CHECK_EQUAL(ne_1, ne_2);
bool lt_1 = s_1 < s_2;
bool lt_2 = int_less_than(v_1, v_2);
CHECK_EQUAL(lt_1, lt_2);
bool gt_1 = s_1 > s_2;
bool gt_2 = int_greater_than(v_1, v_2);
CHECK_EQUAL(gt_1, gt_2);
bool le_1 = s_1 <= s_2;
bool le_2 = int_less_than_or_equal(v_1, v_2);
CHECK_EQUAL(le_1, le_2);
bool ge_1 = s_1 >= s_2;
bool ge_2 = int_greater_than_or_equal(v_1, v_2);
CHECK_EQUAL(ge_1, ge_2);
}
// Addition
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool add_overflow_1 = s_1.add_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool add_overflow_2 = int_add_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(add_overflow_1, add_overflow_2);
if (!add_overflow_1 && !add_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
// Subtraction
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool sub_overflow_1 = s_1.subtract_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool sub_overflow_2 = int_subtract_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(sub_overflow_1, sub_overflow_2);
if (!sub_overflow_1 && !sub_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
/*
// Multiplication
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
if (v_1 >= 0 && v_2 > 0) {
super_int s_1(v_1), s_2(v_2);
bool mul_overflow_1 = s_1.multiply_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool mul_overflow_2 = int_multiply_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(mul_overflow_1, mul_overflow_2);
if (!mul_overflow_1 && !mul_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
}
*/
}
}
}
typedef void types_00;
typedef TypeAppend<types_00, bool>::type types_01;
typedef TypeAppend<types_01, char>::type types_02;
typedef TypeAppend<types_02, signed char>::type types_03;
typedef TypeAppend<types_03, unsigned char>::type types_04;
typedef TypeAppend<types_04, wchar_t>::type types_05;
typedef TypeAppend<types_05, short>::type types_06;
typedef TypeAppend<types_06, unsigned short>::type types_07;
typedef TypeAppend<types_07, int>::type types_08;
typedef TypeAppend<types_08, unsigned>::type types_09;
typedef TypeAppend<types_09, long>::type types_10;
typedef TypeAppend<types_10, unsigned long>::type types_11;
typedef TypeAppend<types_11, long long>::type types_12;
typedef TypeAppend<types_12, unsigned long long>::type types_13;
typedef types_13 types;
template<class T, int> struct add_min_max {
static void exec(set<super_int>* values)
{
typedef numeric_limits<T> lim;
values->insert(super_int(lim::min()));
values->insert(super_int(lim::max()));
}
};
template<class T_1, int> struct test_two_args_1 {
template<class T_2, int> struct test_two_args_2 {
static void exec(TestResults* test_results, const set<super_int>* values)
{
test_two_args<T_1, T_2>(*test_results, *values);
}
};
static void exec(TestResults* test_results, const set<super_int>* values)
{
ForEachType<types, test_two_args_2>::exec(test_results, values);
}
};
} // anonymous namespace
TEST(SafeIntOps_General)
{
// Generate a set of interesting values in these steps
set<super_int> values;
// Add 0 to the set (worst case 1)
values.insert(super_int(0));
// Add min and max for all integer types to set (worst case 27)
ForEachType<types, add_min_max>::exec(&values);
// Add x-1 and x+1 to the set for all x in set (worst case 81)
{
super_int min_val(numeric_limits<intmax_t>::min());
super_int max_val(numeric_limits<uintmax_t>::max());
set<super_int> values_2 = values;
typedef set<super_int>::const_iterator iter;
iter end = values_2.end();
for (iter i = values_2.begin(); i != end; ++i) {
if (*i > min_val)
values.insert(*i - super_int(1));
if (*i < max_val)
values.insert(*i + super_int(1));
}
}
// Add x+y and x-y to the set for all x and y in set (worst case
// 13203)
{
super_int min_val(numeric_limits<intmax_t>::min());
super_int max_val(numeric_limits<uintmax_t>::max());
set<super_int> values_2 = values;
typedef set<super_int>::const_iterator iter;
iter end = values_2.end();
for (iter i_1 = values_2.begin(); i_1 != end; ++i_1) {
for (iter i_2 = values_2.begin(); i_2 != end; ++i_2) {
super_int v_1 = *i_1;
if (!v_1.add_with_overflow_detect(*i_2)) {
if (v_1 >= min_val && v_1 <= max_val)
values.insert(v_1);
}
super_int v_2 = *i_1;
if (!v_2.subtract_with_overflow_detect(*i_2)) {
if (v_2 >= min_val && v_2 <= max_val)
values.insert(v_2);
}
}
}
}
/*
{
typedef set<super_int>::const_iterator iter;
iter end = values.end();
for (iter i = values.begin(); i != end; ++i)
cout << *i << "\n";
}
*/
ForEachType<types, test_two_args_1>::exec(&test_results, &values);
}
<commit_msg>Fixed typo<commit_after>#include <limits>
#include <vector>
#include <set>
#include <iostream>
#include <typeinfo>
#include <stdint.h>
#include <tightdb/util/type_list.hpp>
#include <tightdb/util/safe_int_ops.hpp>
#include "util/demangle.hpp"
#include "util/super_int.hpp"
#include "test.hpp"
using namespace std;
using namespace tightdb::util;
using namespace tightdb::test_util;
using unit_test::TestResults;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
// FIXME: Test T -> tightdb::test_util::super_int -> T using min/max
// values for each fundamental standard type, and also using 0 and -1
// for signed types.
// FIXME: Test tightdb::util::from_twos_compl(). For each type pair
// (S,U), and for each super_int `i` in special set, if i.get_as<S>(s)
// && two's compl of `s` can be stored in U without loss of
// information, then CHECK_EQUAL(s, from_twos_compl(U(s))). Two's
// compl of `s` can be stored in U without loss of information if, and
// only if make_unsigned<S>::type(s < 0 ? -1-s : s) <
// (U(1)<<(lim_u::digits-1)).
// FIXME: Test tightdb::util::int_shift_left_with_overflow_detect().
// FIXME: Test tightdb::util::int_cast_with_overflow_detect().
TEST(SafeIntOps_AddWithOverflowDetect)
{
int lval = 255;
CHECK(!int_add_with_overflow_detect(lval, char(10)));
}
namespace {
template<class T_1, class T_2>
void test_two_args(TestResults& test_results, const set<super_int>& values)
{
// if (!(SameType<T_1, bool>::value && SameType<T_2, char>::value))
// return;
// cerr << get_type_name<T_1>() << ", " << get_type_name<T_2>() << "\n";
vector<T_1> values_1;
vector<T_2> values_2;
{
typedef set<super_int>::const_iterator iter;
iter end = values.end();
for (iter i = values.begin(); i != end; ++i) {
T_1 v_1;
if (i->get_as<T_1>(v_1))
values_1.push_back(v_1);
T_2 v_2;
if (i->get_as<T_2>(v_2))
values_2.push_back(v_2);
}
}
typedef typename vector<T_1>::const_iterator iter_1;
typedef typename vector<T_2>::const_iterator iter_2;
iter_1 end_1 = values_1.end();
iter_2 end_2 = values_2.end();
for (iter_1 i_1 = values_1.begin(); i_1 != end_1; ++i_1) {
for (iter_2 i_2 = values_2.begin(); i_2 != end_2; ++i_2) {
// cout << "--> " << promote(*i_1) << " vs " << promote(*i_2) << "\n";
// Comparisons
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool eq_1 = s_1 == s_2;
bool eq_2 = int_equal_to(v_1, v_2);
CHECK_EQUAL(eq_1, eq_2);
bool ne_1 = s_1 != s_2;
bool ne_2 = int_not_equal_to(v_1, v_2);
CHECK_EQUAL(ne_1, ne_2);
bool lt_1 = s_1 < s_2;
bool lt_2 = int_less_than(v_1, v_2);
CHECK_EQUAL(lt_1, lt_2);
bool gt_1 = s_1 > s_2;
bool gt_2 = int_greater_than(v_1, v_2);
CHECK_EQUAL(gt_1, gt_2);
bool le_1 = s_1 <= s_2;
bool le_2 = int_less_than_or_equal(v_1, v_2);
CHECK_EQUAL(le_1, le_2);
bool ge_1 = s_1 >= s_2;
bool ge_2 = int_greater_than_or_equal(v_1, v_2);
CHECK_EQUAL(ge_1, ge_2);
}
// Addition
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool add_overflow_1 = s_1.add_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool add_overflow_2 = int_add_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(add_overflow_1, add_overflow_2);
if (!add_overflow_1 && !add_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
// Subtraction
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
super_int s_1(v_1), s_2(v_2);
bool sub_overflow_1 = s_1.subtract_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool sub_overflow_2 = int_subtract_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(sub_overflow_1, sub_overflow_2);
if (!sub_overflow_1 && !sub_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
/*
// Multiplication
{
T_1 v_1 = *i_1;
T_2 v_2 = *i_2;
if (v_1 >= 0 && v_2 > 0) {
super_int s_1(v_1), s_2(v_2);
bool mul_overflow_1 = s_1.multiply_with_overflow_detect(s_2) ||
s_1.cast_has_overflow<T_1>();
bool mul_overflow_2 = int_multiply_with_overflow_detect(v_1, v_2);
CHECK_EQUAL(mul_overflow_1, mul_overflow_2);
if (!mul_overflow_1 && !mul_overflow_2)
CHECK_EQUAL(s_1, super_int(v_1));
}
}
*/
}
}
}
typedef void types_00;
typedef TypeAppend<types_00, bool>::type types_01;
typedef TypeAppend<types_01, char>::type types_02;
typedef TypeAppend<types_02, signed char>::type types_03;
typedef TypeAppend<types_03, unsigned char>::type types_04;
typedef TypeAppend<types_04, wchar_t>::type types_05;
typedef TypeAppend<types_05, short>::type types_06;
typedef TypeAppend<types_06, unsigned short>::type types_07;
typedef TypeAppend<types_07, int>::type types_08;
typedef TypeAppend<types_08, unsigned>::type types_09;
typedef TypeAppend<types_09, long>::type types_10;
typedef TypeAppend<types_10, unsigned long>::type types_11;
typedef TypeAppend<types_11, long long>::type types_12;
typedef TypeAppend<types_12, unsigned long long>::type types_13;
typedef types_13 types;
template<class T, int> struct add_min_max {
static void exec(set<super_int>* values)
{
typedef numeric_limits<T> lim;
values->insert(super_int(lim::min()));
values->insert(super_int(lim::max()));
}
};
template<class T_1, int> struct test_two_args_1 {
template<class T_2, int> struct test_two_args_2 {
static void exec(TestResults* test_results, const set<super_int>* values)
{
test_two_args<T_1, T_2>(*test_results, *values);
}
};
static void exec(TestResults* test_results, const set<super_int>* values)
{
ForEachType<types, test_two_args_2>::exec(test_results, values);
}
};
} // anonymous namespace
TEST(SafeIntOps_General)
{
// Generate a set of interesting values in three steps
set<super_int> values;
// Add 0 to the set (worst case 1)
values.insert(super_int(0));
// Add min and max for all integer types to set (worst case 27)
ForEachType<types, add_min_max>::exec(&values);
// Add x-1 and x+1 to the set for all x in set (worst case 81)
{
super_int min_val(numeric_limits<intmax_t>::min());
super_int max_val(numeric_limits<uintmax_t>::max());
set<super_int> values_2 = values;
typedef set<super_int>::const_iterator iter;
iter end = values_2.end();
for (iter i = values_2.begin(); i != end; ++i) {
if (*i > min_val)
values.insert(*i - super_int(1));
if (*i < max_val)
values.insert(*i + super_int(1));
}
}
// Add x+y and x-y to the set for all x and y in set (worst case
// 13203)
{
super_int min_val(numeric_limits<intmax_t>::min());
super_int max_val(numeric_limits<uintmax_t>::max());
set<super_int> values_2 = values;
typedef set<super_int>::const_iterator iter;
iter end = values_2.end();
for (iter i_1 = values_2.begin(); i_1 != end; ++i_1) {
for (iter i_2 = values_2.begin(); i_2 != end; ++i_2) {
super_int v_1 = *i_1;
if (!v_1.add_with_overflow_detect(*i_2)) {
if (v_1 >= min_val && v_1 <= max_val)
values.insert(v_1);
}
super_int v_2 = *i_1;
if (!v_2.subtract_with_overflow_detect(*i_2)) {
if (v_2 >= min_val && v_2 <= max_val)
values.insert(v_2);
}
}
}
}
/*
{
typedef set<super_int>::const_iterator iter;
iter end = values.end();
for (iter i = values.begin(); i != end; ++i)
cout << *i << "\n";
}
*/
ForEachType<types, test_two_args_1>::exec(&test_results, &values);
}
<|endoftext|>
|
<commit_before>#include "physics/barycentric_rotating_dynamic_frame.hpp"
#include <memory>
#include "astronomy/frames.hpp"
#include "geometry/frame.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/rotation.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/constants.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/geometry.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::Bivector;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Time;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AbsoluteError;
using testing_utilities::AlmostEquals;
using ::testing::Lt;
namespace physics {
namespace {
constexpr char kBig[] = "Big";
constexpr char kSmall[] = "Small";
} // namespace
class BarycentricRotatingDynamicFrameTest : public ::testing::Test {
protected:
// The rotating frame centred on the barycentre of the two bodies.
using BigSmall = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, false /*inertial*/>;
BarycentricRotatingDynamicFrameTest()
: period_(10 * π * sqrt(5.0 / 7.0) * Second),
centre_of_mass_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
big_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
small_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()) {
solar_system_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model_two_bodies_test.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_two_bodies_test.proto.txt");
t0_ = solar_system_.epoch();
ephemeris_ = solar_system_.MakeEphemeris(
integrators::McLachlanAtela1992Order4Optimal<
Position<ICRFJ2000Equator>>(),
10 * Milli(Second),
1 * Milli(Metre));
ephemeris_->Prolong(t0_ + 2 * period_);
big_initial_state_ = solar_system_.initial_state(kBig);
big_gravitational_parameter_ = solar_system_.gravitational_parameter(kBig);
small_initial_state_ = solar_system_.initial_state(kSmall);
small_gravitational_parameter_ =
solar_system_.gravitational_parameter(kSmall);
centre_of_mass_initial_state_ =
Barycentre<ICRFJ2000Equator, GravitationalParameter>(
{big_initial_state_, small_initial_state_},
{big_gravitational_parameter_, small_gravitational_parameter_});
big_small_frame_ =
std::make_unique<
BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>(
ephemeris_.get(),
solar_system_.massive_body(*ephemeris_, kBig),
solar_system_.massive_body(*ephemeris_, kSmall));
}
Time const period_;
Instant t0_;
DegreesOfFreedom<ICRFJ2000Equator> centre_of_mass_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> big_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> small_initial_state_;
GravitationalParameter big_gravitational_parameter_;
GravitationalParameter small_gravitational_parameter_;
std::unique_ptr<BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>
big_small_frame_;
std::unique_ptr<Ephemeris<ICRFJ2000Equator>> ephemeris_;
SolarSystem<ICRFJ2000Equator> solar_system_;
};
TEST_F(BarycentricRotatingDynamicFrameTest, ToBigSmallFrameAtTime) {
int const kSteps = 100;
for (Instant t = t0_; t < t0_ + 1 * period_; t += period_ / kSteps) {
auto const to_big_small_frame_at_t = big_small_frame_->ToThisFrameAtTime(t);
DegreesOfFreedom<BigSmall> const centre_of_mass_in_big_small_at_t =
to_big_small_frame_at_t(centre_of_mass_initial_state_);
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>()),
Lt(1.0E-11 * Metre));
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-11 * Metre / Second));
}
}
} // namespace physics
} // namespace principia
<commit_msg>Improved test.<commit_after>#include "physics/barycentric_rotating_dynamic_frame.hpp"
#include <memory>
#include "astronomy/frames.hpp"
#include "geometry/frame.hpp"
#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/rotation.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "quantities/constants.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/geometry.pb.h"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
namespace principia {
using astronomy::ICRFJ2000Equator;
using geometry::Bivector;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Time;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AbsoluteError;
using testing_utilities::AlmostEquals;
using ::testing::Lt;
namespace physics {
namespace {
constexpr char kBig[] = "Big";
constexpr char kSmall[] = "Small";
} // namespace
class BarycentricRotatingDynamicFrameTest : public ::testing::Test {
protected:
// The rotating frame centred on the barycentre of the two bodies.
using BigSmall = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, false /*inertial*/>;
BarycentricRotatingDynamicFrameTest()
: period_(10 * π * sqrt(5.0 / 7.0) * Second),
centre_of_mass_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
big_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()),
small_initial_state_(Position<ICRFJ2000Equator>(),
Velocity<ICRFJ2000Equator>()) {
solar_system_.Initialize(
SOLUTION_DIR / "astronomy" / "gravity_model_two_bodies_test.proto.txt",
SOLUTION_DIR / "astronomy" / "initial_state_two_bodies_test.proto.txt");
t0_ = solar_system_.epoch();
ephemeris_ = solar_system_.MakeEphemeris(
integrators::McLachlanAtela1992Order4Optimal<
Position<ICRFJ2000Equator>>(),
10 * Milli(Second),
1 * Milli(Metre));
ephemeris_->Prolong(t0_ + 2 * period_);
big_initial_state_ = solar_system_.initial_state(kBig);
big_gravitational_parameter_ = solar_system_.gravitational_parameter(kBig);
small_initial_state_ = solar_system_.initial_state(kSmall);
small_gravitational_parameter_ =
solar_system_.gravitational_parameter(kSmall);
centre_of_mass_initial_state_ =
Barycentre<ICRFJ2000Equator, GravitationalParameter>(
{big_initial_state_, small_initial_state_},
{big_gravitational_parameter_, small_gravitational_parameter_});
big_small_frame_ =
std::make_unique<
BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>(
ephemeris_.get(),
solar_system_.massive_body(*ephemeris_, kBig),
solar_system_.massive_body(*ephemeris_, kSmall));
}
Time const period_;
Instant t0_;
DegreesOfFreedom<ICRFJ2000Equator> centre_of_mass_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> big_initial_state_;
DegreesOfFreedom<ICRFJ2000Equator> small_initial_state_;
GravitationalParameter big_gravitational_parameter_;
GravitationalParameter small_gravitational_parameter_;
std::unique_ptr<BarycentricRotatingDynamicFrame<ICRFJ2000Equator, BigSmall>>
big_small_frame_;
std::unique_ptr<Ephemeris<ICRFJ2000Equator>> ephemeris_;
SolarSystem<ICRFJ2000Equator> solar_system_;
};
TEST_F(BarycentricRotatingDynamicFrameTest, ToBigSmallFrameAtTime) {
int const kSteps = 100;
ContinuousTrajectory<ICRFJ2000Equator>::Hint big_hint;
ContinuousTrajectory<ICRFJ2000Equator>::Hint small_hint;
for (Instant t = t0_; t < t0_ + 1 * period_; t += period_ / kSteps) {
auto const to_big_small_frame_at_t = big_small_frame_->ToThisFrameAtTime(t);
// Check that the centre of mass is at the origin and doesn't move.
DegreesOfFreedom<BigSmall> const centre_of_mass_in_big_small_at_t =
to_big_small_frame_at_t(centre_of_mass_initial_state_);
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>()),
Lt(1.0E-11 * Metre));
EXPECT_THAT(AbsoluteError(centre_of_mass_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-11 * Metre / Second));
// Check that the bodies don't move and are at the right locations.
DegreesOfFreedom<ICRFJ2000Equator> const big_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kBig).
EvaluateDegreesOfFreedom(t, &big_hint);
DegreesOfFreedom<ICRFJ2000Equator> const small_in_inertial_frame_at_t =
solar_system_.trajectory(*ephemeris_, kSmall).
EvaluateDegreesOfFreedom(t, &small_hint);
DegreesOfFreedom<BigSmall> const big_in_big_small_at_t =
to_big_small_frame_at_t(big_in_inertial_frame_at_t);
DegreesOfFreedom<BigSmall> const small_in_big_small_at_t =
to_big_small_frame_at_t(small_in_inertial_frame_at_t);
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({15.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-6 * Metre));
EXPECT_THAT(AbsoluteError(big_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.position() -
BigSmall::origin,
Displacement<BigSmall>({-20.0 / 7.0 * Kilo(Metre),
0 * Kilo(Metre),
0 * Kilo(Metre)})),
Lt(1.0E-5 * Metre));
EXPECT_THAT(AbsoluteError(small_in_big_small_at_t.velocity(),
Velocity<BigSmall>()),
Lt(1.0E-4 * Metre / Second));
}
}
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>/* ports.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.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.
*/
/*
* This file contains tables for the electrical layout and setup of the
* electrical components. Keep the formatting in this file very easy to read
* such that it is easy to maintain and quickly check if it is in sync with
* the actual state of affairs on the electrical board!
*/
#include <RobotDrive.h>
#include <Jaguar.h>
#include <Joystick.h>
#include <Encoder.h>
#include <Ultrasonic.h>
#include <DigitalInput.h>
#include <Relay.h>
#include <Servo.h>
#include <AnalogChannel.h>
#include <Vision/AxisCamera.h>
#include "612.h"
#include "ports.h"
#include "joysmooth.h"
#include "roller.h"
#include "shifter.h"
//just define & initialize all of the consts in ports.h
//slots table - in order to make sync with electrical easier.
const module_t slot1 = 1; //1st analog
const module_t slot2 = 1; //1st digital
const module_t slot3 = 1; //1st solenoid
const module_t slot4 = 0; //EMPTY
const module_t slot5 = 2; //2nd analog
const module_t slot6 = 2; //2nd digital
const module_t slot7 = 2; //2nd solenoid
const module_t slot8 = 0; //EMPTY
//camera IP address:
const char * cameraIP = "10.6.12.11"; //static IP, camera configured for connection to bridge
//const char * cameraIP = "192.168.0.90"; //static IP, camera configured for connection to cRIO
//PORTS TABLE
//PWMs SLOT PORT
Jaguar left_launcher_jag ( slot2, 1 );
Jaguar right_launcher_jag ( slot2, 2 );
Jaguar right_front_jag ( slot2, 3 );
Jaguar right_rear_jag ( slot2, 4 );
Jaguar turret_rotation_jag ( slot2, 5 );
Servo right_servo_shift ( slot2, 6 );
Jaguar turret_winch_jag ( slot6, 1 );
Jaguar left_front_jag ( slot6, 2 );
Jaguar left_rear_jag ( slot6, 3 );
Servo left_servo_shift ( slot6, 4 );
PWM camera_led ( slot6, 5 );
//NOTE: Sica wants to use pots (potentiometers) for the angles, as those are
//absolute and don't need a zero switch. If we do that they're seen as
//AnalogChannel s. We'll want to write a quick wrapper class so we can get
//an angular offset, but we'll cross that bridge when we come to it.
//note: for two channel encoders, we need to specify a slot for both ports
//DIOs SLOT PORT
Encoder right_drive ( slot2, 1,
slot2, 2 );
Encoder left_drive ( slot6, 4,
slot6, 5 );
Counter launcher_wheel ( slot2, 3 );
Ultrasonic front_ultrasonic ( slot6, 2,
slot6, 3 );
DigitalInput launch_angle_switch ( slot6, 1 );
DigitalInput bridge_arm_switch ( slot6, 6 );
DigitalInput turret_middle_switch ( slot2, 5 );
DigitalInput turret_right_switch ( slot2, 6 );
DigitalInput turret_left_switch ( slot2, 7 );
//note: since we rely on the default value of kInches for the 5th arg
//we should use Ultrasonic::GetRangeInches().
//AIOs SLOT PORT
AnalogChannel launch_angle_pot ( slot1, 1 );
//Relays SLOT PORT
Relay roller_spike_1 ( slot6, 1 );
Relay roller_spike_2 ( slot6, 2 );
Relay bridge_arm_spike ( slot6, 3 );
//USBs (on driver station) PORT
Joystick left_joystick_raw ( 1 );
Joystick right_joystick_raw ( 2 );
Joystick gunner_joystick_raw ( 3 );
joysmooth left_joystick ( left_joystick_raw );
joysmooth right_joystick ( right_joystick_raw );
joysmooth gunner_joystick ( gunner_joystick_raw );
//initialization of virtual devices:
//RobotDrive
RobotDrive drive (
left_front_motor.jag, //KEEP THIS ORDER (HERE)! IT'S IMPORTANT!
left_rear_motor.jag, //LF, LR, RF, RR -- see documentation
right_front_motor.jag, //for more details
right_rear_motor.jag
);
//roller_t
roller_t rollers(roller_spike_1, roller_spike_2);
//shifter
shifter servo_shifter(left_servo_shift, right_servo_shift);
/*
//turret
turret shooter_turret(turret_rotation_jag, turret_winch_jag, left_launcher_jag, right_launcher_jag, launcher_wheel);
*/
//drive_jaguar JAGUAR& TYPE REVERSE
drive_jaguar left_front_motor = { left_front_jag, RobotDrive::kFrontLeftMotor, false };
drive_jaguar left_rear_motor = { left_rear_jag, RobotDrive::kRearLeftMotor, false };
drive_jaguar right_front_motor = { right_front_jag, RobotDrive::kFrontRightMotor, false };
drive_jaguar right_rear_motor = { right_rear_jag, RobotDrive::kRearRightMotor, false };
<commit_msg>bridge arm spike moved to port 8<commit_after>/* ports.cpp
*
* Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.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.
*/
/*
* This file contains tables for the electrical layout and setup of the
* electrical components. Keep the formatting in this file very easy to read
* such that it is easy to maintain and quickly check if it is in sync with
* the actual state of affairs on the electrical board!
*/
#include <RobotDrive.h>
#include <Jaguar.h>
#include <Joystick.h>
#include <Encoder.h>
#include <Ultrasonic.h>
#include <DigitalInput.h>
#include <Relay.h>
#include <Servo.h>
#include <AnalogChannel.h>
#include <Vision/AxisCamera.h>
#include "612.h"
#include "ports.h"
#include "joysmooth.h"
#include "roller.h"
#include "shifter.h"
//just define & initialize all of the consts in ports.h
//slots table - in order to make sync with electrical easier.
const module_t slot1 = 1; //1st analog
const module_t slot2 = 1; //1st digital
const module_t slot3 = 1; //1st solenoid
const module_t slot4 = 0; //EMPTY
const module_t slot5 = 2; //2nd analog
const module_t slot6 = 2; //2nd digital
const module_t slot7 = 2; //2nd solenoid
const module_t slot8 = 0; //EMPTY
//camera IP address:
const char * cameraIP = "10.6.12.11"; //static IP, camera configured for connection to bridge
//const char * cameraIP = "192.168.0.90"; //static IP, camera configured for connection to cRIO
//PORTS TABLE
//PWMs SLOT PORT
Jaguar left_launcher_jag ( slot2, 1 );
Jaguar right_launcher_jag ( slot2, 2 );
Jaguar right_front_jag ( slot2, 3 );
Jaguar right_rear_jag ( slot2, 4 );
Jaguar turret_rotation_jag ( slot2, 5 );
Servo right_servo_shift ( slot2, 6 );
Jaguar turret_winch_jag ( slot6, 1 );
Jaguar left_front_jag ( slot6, 2 );
Jaguar left_rear_jag ( slot6, 3 );
Servo left_servo_shift ( slot6, 4 );
PWM camera_led ( slot6, 5 );
//NOTE: Sica wants to use pots (potentiometers) for the angles, as those are
//absolute and don't need a zero switch. If we do that they're seen as
//AnalogChannel s. We'll want to write a quick wrapper class so we can get
//an angular offset, but we'll cross that bridge when we come to it.
//note: for two channel encoders, we need to specify a slot for both ports
//DIOs SLOT PORT
Encoder right_drive ( slot2, 1,
slot2, 2 );
Encoder left_drive ( slot6, 4,
slot6, 5 );
Counter launcher_wheel ( slot2, 3 );
Ultrasonic front_ultrasonic ( slot6, 2,
slot6, 3 );
DigitalInput launch_angle_switch ( slot6, 1 );
DigitalInput bridge_arm_switch ( slot6, 6 );
DigitalInput turret_middle_switch ( slot2, 5 );
DigitalInput turret_right_switch ( slot2, 6 );
DigitalInput turret_left_switch ( slot2, 7 );
//note: since we rely on the default value of kInches for the 5th arg
//we should use Ultrasonic::GetRangeInches().
//AIOs SLOT PORT
AnalogChannel launch_angle_pot ( slot1, 1 );
//Relays SLOT PORT
Relay roller_spike_1 ( slot6, 1 );
Relay roller_spike_2 ( slot6, 2 );
Relay bridge_arm_spike ( slot6, 8 );
//USBs (on driver station) PORT
Joystick left_joystick_raw ( 1 );
Joystick right_joystick_raw ( 2 );
Joystick gunner_joystick_raw ( 3 );
joysmooth left_joystick ( left_joystick_raw );
joysmooth right_joystick ( right_joystick_raw );
joysmooth gunner_joystick ( gunner_joystick_raw );
//initialization of virtual devices:
//RobotDrive
RobotDrive drive (
left_front_motor.jag, //KEEP THIS ORDER (HERE)! IT'S IMPORTANT!
left_rear_motor.jag, //LF, LR, RF, RR -- see documentation
right_front_motor.jag, //for more details
right_rear_motor.jag
);
//roller_t
roller_t rollers(roller_spike_1, roller_spike_2);
//shifter
shifter servo_shifter(left_servo_shift, right_servo_shift);
/*
//turret
turret shooter_turret(turret_rotation_jag, turret_winch_jag, left_launcher_jag, right_launcher_jag, launcher_wheel);
*/
//drive_jaguar JAGUAR& TYPE REVERSE
drive_jaguar left_front_motor = { left_front_jag, RobotDrive::kFrontLeftMotor, false };
drive_jaguar left_rear_motor = { left_rear_jag, RobotDrive::kRearLeftMotor, false };
drive_jaguar right_front_motor = { right_front_jag, RobotDrive::kFrontRightMotor, false };
drive_jaguar right_rear_motor = { right_rear_jag, RobotDrive::kRearRightMotor, false };
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkCanvas.h"
#include "SkInterpolator.h"
#include "SkTime.h"
// This slide tests out the match up between BW clipping and rendering. It can
// draw a large rect through some clip geometry and draw the same geometry
// normally. Which one is drawn first can be toggled. The pair of objects is translated
// fractionally (via an animator) to expose snapping bugs. The key bindings are:
// 1-9: the different geometries
// t: toggle which is drawn first the clip or the normal geometry
// The possible geometric combinations to test
enum Geometry {
kRect_Geometry,
kRRect_Geometry,
kCircle_Geometry,
kConvexPath_Geometry,
kConcavePath_Geometry,
kRectAndRect_Geometry,
kRectAndRRect_Geometry,
kRectAndConvex_Geometry,
kRectAndConcave_Geometry
};
// The basic rect used is [kMin,kMin]..[kMax,kMax]
static const float kMin = 100.5f;
static const float kMid = 200.0f;
static const float kMax = 299.5f;
SkRect create_rect(const SkPoint& offset) {
SkRect r = SkRect::MakeLTRB(kMin, kMin, kMax, kMax);
r.offset(offset);
return r;
}
SkRRect create_rrect(const SkPoint& offset) {
SkRRect rrect;
rrect.setRectXY(create_rect(offset), 10, 10);
return rrect;
}
SkRRect create_circle(const SkPoint& offset) {
SkRRect circle;
circle.setOval(create_rect(offset));
return circle;
}
SkPath create_convex_path(const SkPoint& offset) {
SkPath convexPath;
convexPath.moveTo(kMin, kMin);
convexPath.lineTo(kMax, kMax);
convexPath.lineTo(kMin, kMax);
convexPath.close();
convexPath.offset(offset.fX, offset.fY);
return convexPath;
}
SkPath create_concave_path(const SkPoint& offset) {
SkPath concavePath;
concavePath.moveTo(kMin, kMin);
concavePath.lineTo(kMid, 105.0f);
concavePath.lineTo(kMax, kMin);
concavePath.lineTo(295.0f, kMid);
concavePath.lineTo(kMax, kMax);
concavePath.lineTo(kMid, 295.0f);
concavePath.lineTo(kMin, kMax);
concavePath.lineTo(105.0f, kMid);
concavePath.close();
concavePath.offset(offset.fX, offset.fY);
return concavePath;
}
static void draw_clipped_geom(SkCanvas* canvas, const SkPoint& offset, int geom, bool useAA) {
int count = canvas->save();
switch (geom) {
case kRect_Geometry:
canvas->clipRect(create_rect(offset), SkRegion::kReplace_Op, useAA);
break;
case kRRect_Geometry:
canvas->clipRRect(create_rrect(offset), SkRegion::kReplace_Op, useAA);
break;
case kCircle_Geometry:
canvas->clipRRect(create_circle(offset), SkRegion::kReplace_Op, useAA);
break;
case kConvexPath_Geometry:
canvas->clipPath(create_convex_path(offset), SkRegion::kReplace_Op, useAA);
break;
case kConcavePath_Geometry:
canvas->clipPath(create_concave_path(offset), SkRegion::kReplace_Op, useAA);
break;
case kRectAndRect_Geometry: {
SkRect r = create_rect(offset);
r.offset(-100.0f, -100.0f);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipRect(create_rect(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndRRect_Geometry: {
SkRect r = create_rect(offset);
r.offset(-100.0f, -100.0f);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipRRect(create_rrect(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndConvex_Geometry: {
SkRect r = create_rect(offset);
r.offset(-100.0f, -100.0f);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipPath(create_convex_path(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndConcave_Geometry: {
SkRect r = create_rect(offset);
r.offset(-100.0f, -100.0f);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipPath(create_concave_path(offset), SkRegion::kIntersect_Op, useAA);
} break;
}
SkISize size = canvas->getDeviceSize();
SkRect bigR = SkRect::MakeWH(SkIntToScalar(size.width()), SkIntToScalar(size.height()));
SkPaint p;
p.setColor(SK_ColorRED);
canvas->drawRect(bigR, p);
canvas->restoreToCount(count);
}
static void draw_normal_geom(SkCanvas* canvas, const SkPoint& offset, int geom, bool useAA) {
SkPaint p;
p.setAntiAlias(useAA);
p.setColor(SK_ColorBLACK);
switch (geom) {
case kRect_Geometry: // fall thru
case kRectAndRect_Geometry:
canvas->drawRect(create_rect(offset), p);
break;
case kRRect_Geometry: // fall thru
case kRectAndRRect_Geometry:
canvas->drawRRect(create_rrect(offset), p);
break;
case kCircle_Geometry:
canvas->drawRRect(create_circle(offset), p);
break;
case kConvexPath_Geometry: // fall thru
case kRectAndConvex_Geometry:
canvas->drawPath(create_convex_path(offset), p);
break;
case kConcavePath_Geometry: // fall thru
case kRectAndConcave_Geometry:
canvas->drawPath(create_concave_path(offset), p);
break;
}
}
class ClipDrawMatchView : public SampleView {
public:
ClipDrawMatchView() : fTrans(2, 5), fGeom(kRect_Geometry), fClipFirst(true) {
SkScalar values[2];
fTrans.setRepeatCount(999);
values[0] = values[1] = 0;
fTrans.setKeyFrame(0, SkTime::GetMSecs() + 1000, values);
values[1] = 1;
fTrans.setKeyFrame(1, SkTime::GetMSecs() + 2000, values);
values[0] = values[1] = 1;
fTrans.setKeyFrame(2, SkTime::GetMSecs() + 3000, values);
values[1] = 0;
fTrans.setKeyFrame(3, SkTime::GetMSecs() + 4000, values);
values[0] = 0;
fTrans.setKeyFrame(4, SkTime::GetMSecs() + 5000, values);
}
protected:
bool onQuery(SkEvent* evt) SK_OVERRIDE {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "ClipDrawMatch");
return true;
}
SkUnichar uni;
if (SampleCode::CharQ(*evt, &uni)) {
switch (uni) {
case '1': fGeom = kRect_Geometry; this->inval(NULL); return true;
case '2': fGeom = kRRect_Geometry; this->inval(NULL); return true;
case '3': fGeom = kCircle_Geometry; this->inval(NULL); return true;
case '4': fGeom = kConvexPath_Geometry; this->inval(NULL); return true;
case '5': fGeom = kConcavePath_Geometry; this->inval(NULL); return true;
case '6': fGeom = kRectAndRect_Geometry; this->inval(NULL); return true;
case '7': fGeom = kRectAndRRect_Geometry; this->inval(NULL); return true;
case '8': fGeom = kRectAndConvex_Geometry; this->inval(NULL); return true;
case '9': fGeom = kRectAndConcave_Geometry; this->inval(NULL); return true;
case 't': fClipFirst = !fClipFirst; this->inval(NULL); return true;
default: break;
}
}
return this->INHERITED::onQuery(evt);
}
// Draw a big red rect through some clip geometry and also draw that same
// geometry in black. The order in which they are drawn can be swapped.
// This tests whether the clip and normally drawn geometry match up.
void drawGeometry(SkCanvas* canvas, const SkPoint& offset, bool useAA) {
if (fClipFirst) {
draw_clipped_geom(canvas, offset, fGeom, useAA);
}
draw_normal_geom(canvas, offset, fGeom, useAA);
if (!fClipFirst) {
draw_clipped_geom(canvas, offset, fGeom, useAA);
}
}
void onDrawContent(SkCanvas* canvas) SK_OVERRIDE {
SkScalar trans[2];
fTrans.timeToValues(SkTime::GetMSecs(), trans);
SkPoint offset;
offset.set(trans[0], trans[1]);
int saveCount = canvas->save();
this->drawGeometry(canvas, offset, false);
canvas->restoreToCount(saveCount);
this->inval(NULL);
}
private:
SkInterpolator fTrans;
Geometry fGeom;
bool fClipFirst;
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new ClipDrawMatchView; }
static SkViewRegister reg(MyFactory);
<commit_msg>Salvage the SampleApp portion of the ill-fated "nudge" CL<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkCanvas.h"
#include "SkInterpolator.h"
#include "SkTime.h"
// This slide tests out the match up between BW clipping and rendering. It can
// draw a large rect through some clip geometry and draw the same geometry
// normally. Which one is drawn first can be toggled. The pair of objects is translated
// fractionally (via an animator) to expose snapping bugs. The key bindings are:
// 1-9: the different geometries
// t: toggle which is drawn first the clip or the normal geometry
// f: flip-flops which corner the bottom AA clip rect occupies in the complex clip cases
// The possible geometric combinations to test
enum Geometry {
kRect_Geometry,
kRRect_Geometry,
kCircle_Geometry,
kConvexPath_Geometry,
kConcavePath_Geometry,
kRectAndRect_Geometry,
kRectAndRRect_Geometry,
kRectAndConvex_Geometry,
kRectAndConcave_Geometry
};
// The basic rect used is [kMin,kMin]..[kMax,kMax]
static const float kMin = 100.5f;
static const float kMid = 200.0f;
static const float kMax = 299.5f;
// The translation applied to the base AA rect in the combination cases
// (i.e., kRectAndRect through kRectAndConcave)
static const float kXlate = 100.0f;
SkRect create_rect(const SkPoint& offset) {
SkRect r = SkRect::MakeLTRB(kMin, kMin, kMax, kMax);
r.offset(offset);
return r;
}
SkRRect create_rrect(const SkPoint& offset) {
SkRRect rrect;
rrect.setRectXY(create_rect(offset), 10, 10);
return rrect;
}
SkRRect create_circle(const SkPoint& offset) {
SkRRect circle;
circle.setOval(create_rect(offset));
return circle;
}
SkPath create_convex_path(const SkPoint& offset) {
SkPath convexPath;
convexPath.moveTo(kMin, kMin);
convexPath.lineTo(kMax, kMax);
convexPath.lineTo(kMin, kMax);
convexPath.close();
convexPath.offset(offset.fX, offset.fY);
return convexPath;
}
SkPath create_concave_path(const SkPoint& offset) {
SkPath concavePath;
concavePath.moveTo(kMin, kMin);
concavePath.lineTo(kMid, 105.0f);
concavePath.lineTo(kMax, kMin);
concavePath.lineTo(295.0f, kMid);
concavePath.lineTo(kMax, kMax);
concavePath.lineTo(kMid, 295.0f);
concavePath.lineTo(kMin, kMax);
concavePath.lineTo(105.0f, kMid);
concavePath.close();
concavePath.offset(offset.fX, offset.fY);
return concavePath;
}
static void draw_normal_geom(SkCanvas* canvas, const SkPoint& offset, int geom, bool useAA) {
SkPaint p;
p.setAntiAlias(useAA);
p.setColor(SK_ColorBLACK);
switch (geom) {
case kRect_Geometry: // fall thru
case kRectAndRect_Geometry:
canvas->drawRect(create_rect(offset), p);
break;
case kRRect_Geometry: // fall thru
case kRectAndRRect_Geometry:
canvas->drawRRect(create_rrect(offset), p);
break;
case kCircle_Geometry:
canvas->drawRRect(create_circle(offset), p);
break;
case kConvexPath_Geometry: // fall thru
case kRectAndConvex_Geometry:
canvas->drawPath(create_convex_path(offset), p);
break;
case kConcavePath_Geometry: // fall thru
case kRectAndConcave_Geometry:
canvas->drawPath(create_concave_path(offset), p);
break;
}
}
class ClipDrawMatchView : public SampleView {
public:
ClipDrawMatchView() : fTrans(2, 5), fGeom(kRect_Geometry), fClipFirst(true), fSign(1) {
SkScalar values[2];
fTrans.setRepeatCount(999);
values[0] = values[1] = 0;
fTrans.setKeyFrame(0, SkTime::GetMSecs() + 1000, values);
values[1] = 1;
fTrans.setKeyFrame(1, SkTime::GetMSecs() + 2000, values);
values[0] = values[1] = 1;
fTrans.setKeyFrame(2, SkTime::GetMSecs() + 3000, values);
values[1] = 0;
fTrans.setKeyFrame(3, SkTime::GetMSecs() + 4000, values);
values[0] = 0;
fTrans.setKeyFrame(4, SkTime::GetMSecs() + 5000, values);
}
protected:
bool onQuery(SkEvent* evt) SK_OVERRIDE {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "ClipDrawMatch");
return true;
}
SkUnichar uni;
if (SampleCode::CharQ(*evt, &uni)) {
switch (uni) {
case '1': fGeom = kRect_Geometry; this->inval(NULL); return true;
case '2': fGeom = kRRect_Geometry; this->inval(NULL); return true;
case '3': fGeom = kCircle_Geometry; this->inval(NULL); return true;
case '4': fGeom = kConvexPath_Geometry; this->inval(NULL); return true;
case '5': fGeom = kConcavePath_Geometry; this->inval(NULL); return true;
case '6': fGeom = kRectAndRect_Geometry; this->inval(NULL); return true;
case '7': fGeom = kRectAndRRect_Geometry; this->inval(NULL); return true;
case '8': fGeom = kRectAndConvex_Geometry; this->inval(NULL); return true;
case '9': fGeom = kRectAndConcave_Geometry; this->inval(NULL); return true;
case 'f': fSign = -fSign; this->inval(NULL); return true;
case 't': fClipFirst = !fClipFirst; this->inval(NULL); return true;
default: break;
}
}
return this->INHERITED::onQuery(evt);
}
void drawClippedGeom(SkCanvas* canvas, const SkPoint& offset, bool useAA) {
int count = canvas->save();
switch (fGeom) {
case kRect_Geometry:
canvas->clipRect(create_rect(offset), SkRegion::kReplace_Op, useAA);
break;
case kRRect_Geometry:
canvas->clipRRect(create_rrect(offset), SkRegion::kReplace_Op, useAA);
break;
case kCircle_Geometry:
canvas->clipRRect(create_circle(offset), SkRegion::kReplace_Op, useAA);
break;
case kConvexPath_Geometry:
canvas->clipPath(create_convex_path(offset), SkRegion::kReplace_Op, useAA);
break;
case kConcavePath_Geometry:
canvas->clipPath(create_concave_path(offset), SkRegion::kReplace_Op, useAA);
break;
case kRectAndRect_Geometry: {
SkRect r = create_rect(offset);
r.offset(fSign * kXlate, fSign * kXlate);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipRect(create_rect(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndRRect_Geometry: {
SkRect r = create_rect(offset);
r.offset(fSign * kXlate, fSign * kXlate);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipRRect(create_rrect(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndConvex_Geometry: {
SkRect r = create_rect(offset);
r.offset(fSign * kXlate, fSign * kXlate);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipPath(create_convex_path(offset), SkRegion::kIntersect_Op, useAA);
} break;
case kRectAndConcave_Geometry: {
SkRect r = create_rect(offset);
r.offset(fSign * kXlate, fSign * kXlate);
canvas->clipRect(r, SkRegion::kReplace_Op, true); // AA here forces shader clips
canvas->clipPath(create_concave_path(offset), SkRegion::kIntersect_Op, useAA);
} break;
}
SkISize size = canvas->getDeviceSize();
SkRect bigR = SkRect::MakeWH(SkIntToScalar(size.width()), SkIntToScalar(size.height()));
SkPaint p;
p.setColor(SK_ColorRED);
canvas->drawRect(bigR, p);
canvas->restoreToCount(count);
}
// Draw a big red rect through some clip geometry and also draw that same
// geometry in black. The order in which they are drawn can be swapped.
// This tests whether the clip and normally drawn geometry match up.
void drawGeometry(SkCanvas* canvas, const SkPoint& offset, bool useAA) {
if (fClipFirst) {
this->drawClippedGeom(canvas, offset, useAA);
}
draw_normal_geom(canvas, offset, fGeom, useAA);
if (!fClipFirst) {
this->drawClippedGeom(canvas, offset, useAA);
}
}
void onDrawContent(SkCanvas* canvas) SK_OVERRIDE {
SkScalar trans[2];
fTrans.timeToValues(SkTime::GetMSecs(), trans);
SkPoint offset;
offset.set(trans[0], trans[1]);
int saveCount = canvas->save();
this->drawGeometry(canvas, offset, false);
canvas->restoreToCount(saveCount);
this->inval(NULL);
}
private:
SkInterpolator fTrans;
Geometry fGeom;
bool fClipFirst;
int fSign;
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new ClipDrawMatchView; }
static SkViewRegister reg(MyFactory);
<|endoftext|>
|
<commit_before>#include <fstream.h>
#include "ppm.h"
void PPM::load_from_file(char *filename)
{
ifstream in;
in.open(filename, (ios::in | ios::binary));
if (in.is_open())
{
load_from_stream(&in);
in.close();
} else
cout << "Error loading file: " << *filename << "\n";
}
void PPM::load_from_stream(istream *in)
{
//Dump the old image and set the dimensions to 0 in case the loading fails
set_image(0);
set_dimensions(0, 0);
//Skip "P6" header thing
(*in).seekg(3, ios::cur);
ushortint new_width=0, new_height=0;
(*in) >> new_width >> new_height;
set_dimensions(new_width, new_height);
//skip the last bit of header crap
(*in) >> new_width;
(*in).seekg(1, ios::cur);
//Now ready to read in the binary data
allocate();
(*in).read(get_image(), (width*height*3));
}
void PPM::save_to_file(char *filename)
{
ofstream out;
out.open(filename, (ios::out | ios::binary | ios::trunc));
if(out.is_open())
{
save_to_stream(&out);
out.close();
} else
cout << "Error creating file: " << *filename << "\n";
}
void PPM::save_to_stream(ostream *out)
{
//Dump the header
(*out) << "P6\n" << get_width() << "\n" << get_height() << "\n" << 255 << "\n";
//Write out the binary data
(*out).write(get_image(), (width*height*3));
}
<commit_msg>updated char* casting<commit_after>#include <fstream.h>
#include "ppm.h"
void PPM::load_from_file(char *filename)
{
ifstream in;
in.open(filename, (ios::in | ios::binary));
if (in.is_open())
{
load_from_stream(&in);
in.close();
} else
cout << "Error loading file: " << *filename << "\n";
}
void PPM::load_from_stream(istream *in)
{
//Dump the old image and set the dimensions to 0 in case the loading fails
set_image(0);
set_dimensions(0, 0);
//Skip "P6" header thing
(*in).seekg(3, ios::cur);
ushortint new_width=0, new_height=0;
(*in) >> new_width >> new_height;
set_dimensions(new_width, new_height);
//skip the last bit of header crap
(*in) >> new_width;
(*in).seekg(1, ios::cur);
//Now ready to read in the binary data
allocate();
in->read((char*)get_image(), (width*height*3));
}
void PPM::save_to_file(char *filename)
{
ofstream out;
out.open(filename, (ios::out | ios::binary | ios::trunc));
if(out.is_open())
{
save_to_stream(&out);
out.close();
} else
cout << "Error creating file: " << *filename << "\n";
}
void PPM::save_to_stream(ostream *out)
{
//Dump the header
(*out) << "P6\n" << get_width() << "\n" << get_height() << "\n" << 255 << "\n";
//Write out the binary data
(*out).write((char*)get_image(), (width*height*3));
}
<|endoftext|>
|
<commit_before>#include "crab_llvm/config.h"
#include "path_analyzer.hpp"
#include "boost/unordered_set.hpp"
// flat_killgen_domain
#include <crab/iterators/killgen_fixpoint_iterator.hpp>
namespace crab {
namespace analyzer {
template<typename CFG, typename AbsDom>
path_analyzer<CFG,AbsDom>::path_analyzer(CFG cfg, AbsDom init, bool ignore_assertions)
: m_cfg(cfg), m_fwd_abs_tr(&init, ignore_assertions) { }
template<typename CFG, typename AbsDom>
bool path_analyzer<CFG,AbsDom>::solve(const std::vector<basic_block_label_t>& path,
bool compute_preconditions) {
// Reset state
m_fwd_dom_map.clear();
m_bwd_dom_map.clear();
m_core.clear();
if (path.empty()) {
CRAB_WARN("Empty path: do nothing\n");
return true;
}
// Sanity checks
basic_block_label_t first = path.front();
basic_block_label_t last = path.back();
if (m_cfg.entry() != first)
CRAB_ERROR("First block of the path must be the entry block of the cfg");
if (m_cfg.has_exit() && (m_cfg.exit() != last))
CRAB_ERROR("Last block of the path must be the exit block of the cfg");
if (path.size() > 1) {
boost::unordered_set<basic_block_label_t> visited;
for (unsigned i=0;i < path.size(); ++i) {
if (!visited.insert(path[i]).second) {
CRAB_ERROR("The path is not acyclic");
}
if (i < path.size() - 1) {
if (!has_kid(path[i], path[i+1])) {
CRAB_ERROR("There is no an edge from ",
cfg_impl::get_label_str(path[i]), " to ",
cfg_impl::get_label_str(path[i+1]));
}
}
}
}
// contain all statements along the path until the end of the path
// or bottom is found.
std::vector<typename crab::cfg::statement_wrapper> path_statements;
bool bottom_found = false;
unsigned bottom_pos = path.size();
// Compute strongest post-condition over the path
abs_dom_t pre = m_fwd_abs_tr.inv();
stmt_to_dom_map_t stmt_dom_map;
for(unsigned i=0; i < path.size(); ++i) {
if (pre.is_bottom()) {
if (!bottom_found) {
bottom_pos = i; // update only the first time bottom is found
}
bottom_found = true;
break;
}
// store constraints that hold at the entry of the block
basic_block_label_t node = path[i];
auto it = m_fwd_dom_map.find (node);
if (it == m_fwd_dom_map.end()) {
m_fwd_dom_map.insert(std::make_pair (node, pre));
}
// compute strongest post-condition for one block
m_fwd_abs_tr.set (pre);
auto &b = m_cfg.get_node (node);
for (auto &s : b) {
if (!s.is_assert() && !s.is_ptr_assert() && !s.is_bool_assert()) {
path_statements.push_back(crab::cfg::statement_wrapper(&s, node));
}
// XXX: we can store forward constraints that might help the
// backward analysis. This step is optional. We don't use it
// for now.
// stmt_dom_map.insert(std::make_pair(&s, m_fwd_abs_tr.inv()));
s.accept (&m_fwd_abs_tr);
}
}
if (bottom_found) {
if (compute_preconditions) {
// -- Compute pre-conditions starting from the block for which we
// inferred bottom.
assert (bottom_pos < path.size());
abs_dom_t abs_val = abs_dom_t::top();
bwd_abs_tr_t bwd_abs_tr(&abs_val, stmt_dom_map, true);
for(int i=bottom_pos; i >= 0; --i) {
basic_block_label_t node = path[i];
auto &b = m_cfg.get_node (node);
for(auto &s: boost::make_iterator_range(b.rbegin(),b.rend())) {
s.accept (&bwd_abs_tr);
}
auto it = m_bwd_dom_map.find (node);
if (it == m_bwd_dom_map.end()) {
m_bwd_dom_map.insert(std::make_pair (node, abs_val));
}
if (abs_val.is_bottom())
break;
}
}
// -- Compute minimal subset of statements that still implies
// bottom.
minimize_path(path_statements);
}
return !bottom_found;
}
template<typename CFG, typename AbsDom>
bool path_analyzer<CFG,AbsDom>::has_kid(basic_block_label_t b1, basic_block_label_t b2) {
for (basic_block_label_t child: m_cfg.next_nodes (b1)) {
if (child == b2)
return true;
}
return false;
}
// Compute a minimal subset of statements based on syntactic
// dependencies.
template<typename CFG, typename AbsDom>
void path_analyzer<CFG,AbsDom>::
remove_irrelevant_statements(std::vector<crab::cfg::statement_wrapper>& core) {
typedef typename CFG::basic_block_t::assume_t assume_t;
typedef typename CFG::basic_block_t::bool_assume_t bool_assume_t;
unsigned size = core.size();
if (size <= 1) {
return;
}
stmt_t& last = *(core[size-1].m_s);
if (!(last.is_assume()) && !(last.is_bool_assume())) {
// we expect last statement to be an assume, otherwise we bail out.
return;
}
typedef domains::flat_killgen_domain<typename CFG::variable_t> var_dom_t;
var_dom_t d;
if (last.is_assume()) {
auto assume = static_cast<const assume_t*>(&last);
if (assume->constraint().is_contradiction()) {
return; // we do nothing
}
for (typename CFG::variable_t v: assume->constraint().variables()) {
d += v;
}
} else {
auto bool_assume = static_cast<const bool_assume_t*>(&last);
d += bool_assume->cond();
}
// Traverse the whole path backwards and remove irrelevant
// statements based on data dependencies.
std::vector<bool> enabled(size, false);
enabled[size-1] = true; // added the last assume
for(int i= size-2; i >= 0 ; --i) { // start from penultimate statement
stmt_t& s = *(core[i].m_s);
var_dom_t uses, defs;
const typename stmt_t::live_t& ls = s.get_live();
for (auto v: boost::make_iterator_range(ls.uses_begin(), ls.uses_end()))
{ uses += v; }
for (auto v: boost::make_iterator_range(ls.defs_begin(), ls.defs_end()))
{ defs += v; }
if (defs.is_bottom() && !uses.is_bottom() && !(uses & d).is_bottom ()) {
d += uses;
enabled[i] = true;
} else if (!(d & defs).is_bottom()) {
d -= defs;
d += uses;
enabled[i] = true;
} else {
// irrelevant statement
}
}
std::vector<crab::cfg::statement_wrapper> res;
res.reserve(size);
for(unsigned i=0; i < size; ++i) {
if (enabled[i]) res.push_back(core[i]);
}
core.assign(res.begin(), res.end());
}
/**
** Compute a minimal subset of statements needed to prove that the
** path is infeasible.
**
** Pre: the strongest post-condition of path is false.
** Pre: path is well-formed.
**/
template<typename CFG, typename AbsDom>
void path_analyzer<CFG,AbsDom>::minimize_path(const std::vector<crab::cfg::statement_wrapper>& path) {
std::vector<crab::cfg::statement_wrapper> core(path.begin(), path.end());
// Remove first syntactically irrelevant statements wrt to the last
// statement which should be an assume statement where bottom was
// first inferred.
remove_irrelevant_statements(core);
// We use the enabled vector because we need to preserve the order
// since abstract interpretation cares about that.
std::vector<bool> enabled(core.size(), true);
for (unsigned i = 0; i < core.size (); ++i) {
enabled[i] = false;
abs_dom_t pre = AbsDom::top(); // m_fwd_abs_tr.inv();
bool res = true;
for(unsigned j=0; j < core.size(); ++j) {
if (enabled[j]) {
m_fwd_abs_tr.set (pre);
core[j].m_s->accept (&m_fwd_abs_tr);
res = !pre.is_bottom();
if (!res) break;
}
}
if (res) {
enabled[i] = true;
}
}
m_core.reserve(core.size());
for (unsigned i=0; i < core.size();++i) {
if (enabled[i]) {
m_core.push_back(core[i]);
}
}
assert(!m_core.empty());
}
}
}
#include <crab_llvm/crab_domains.hh>
#include <crab_llvm/crab_cfg.hh>
namespace crab {
namespace analyzer {
// explicit instantiations
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::num_domain_t>;
#ifdef HAVE_ALL_DOMAINS
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::term_int_domain_t>;
#endif
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::interval_domain_t>;
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::wrapped_interval_domain_t>;
}
}
<commit_msg>Report warning instead of error<commit_after>#include "crab_llvm/config.h"
#include "path_analyzer.hpp"
#include "boost/unordered_set.hpp"
// flat_killgen_domain
#include <crab/iterators/killgen_fixpoint_iterator.hpp>
namespace crab {
namespace analyzer {
template<typename CFG, typename AbsDom>
path_analyzer<CFG,AbsDom>::path_analyzer(CFG cfg, AbsDom init, bool ignore_assertions)
: m_cfg(cfg), m_fwd_abs_tr(&init, ignore_assertions) { }
template<typename CFG, typename AbsDom>
bool path_analyzer<CFG,AbsDom>::solve(const std::vector<basic_block_label_t>& path,
bool compute_preconditions) {
// Reset state
m_fwd_dom_map.clear();
m_bwd_dom_map.clear();
m_core.clear();
if (path.empty()) {
CRAB_WARN("Empty path: do nothing\n");
return true;
}
// Sanity checks
basic_block_label_t first = path.front();
basic_block_label_t last = path.back();
if (m_cfg.entry() != first)
CRAB_ERROR("First block of the path must be the entry block of the cfg");
if (m_cfg.has_exit() && (m_cfg.exit() != last))
CRAB_ERROR("Last block of the path must be the exit block of the cfg");
if (path.size() > 1) {
boost::unordered_set<basic_block_label_t> visited;
for (unsigned i=0;i < path.size(); ++i) {
if (!visited.insert(path[i]).second) {
CRAB_ERROR("The path is not acyclic");
}
if (i < path.size() - 1) {
if (!has_kid(path[i], path[i+1])) {
CRAB_WARN("There is no an edge from ",
cfg_impl::get_label_str(path[i]), " to ",
cfg_impl::get_label_str(path[i+1]));
return true;
}
}
}
}
// contain all statements along the path until the end of the path
// or bottom is found.
std::vector<typename crab::cfg::statement_wrapper> path_statements;
bool bottom_found = false;
unsigned bottom_pos = path.size();
// Compute strongest post-condition over the path
abs_dom_t pre = m_fwd_abs_tr.inv();
stmt_to_dom_map_t stmt_dom_map;
for(unsigned i=0; i < path.size(); ++i) {
if (pre.is_bottom()) {
if (!bottom_found) {
bottom_pos = i; // update only the first time bottom is found
}
bottom_found = true;
break;
}
// store constraints that hold at the entry of the block
basic_block_label_t node = path[i];
auto it = m_fwd_dom_map.find (node);
if (it == m_fwd_dom_map.end()) {
m_fwd_dom_map.insert(std::make_pair (node, pre));
}
// compute strongest post-condition for one block
m_fwd_abs_tr.set (pre);
auto &b = m_cfg.get_node (node);
for (auto &s : b) {
if (!s.is_assert() && !s.is_ptr_assert() && !s.is_bool_assert()) {
path_statements.push_back(crab::cfg::statement_wrapper(&s, node));
}
// XXX: we can store forward constraints that might help the
// backward analysis. This step is optional. We don't use it
// for now.
// stmt_dom_map.insert(std::make_pair(&s, m_fwd_abs_tr.inv()));
s.accept (&m_fwd_abs_tr);
}
}
if (bottom_found) {
if (compute_preconditions) {
// -- Compute pre-conditions starting from the block for which we
// inferred bottom.
assert (bottom_pos < path.size());
abs_dom_t abs_val = abs_dom_t::top();
bwd_abs_tr_t bwd_abs_tr(&abs_val, stmt_dom_map, true);
for(int i=bottom_pos; i >= 0; --i) {
basic_block_label_t node = path[i];
auto &b = m_cfg.get_node (node);
for(auto &s: boost::make_iterator_range(b.rbegin(),b.rend())) {
s.accept (&bwd_abs_tr);
}
auto it = m_bwd_dom_map.find (node);
if (it == m_bwd_dom_map.end()) {
m_bwd_dom_map.insert(std::make_pair (node, abs_val));
}
if (abs_val.is_bottom())
break;
}
}
// -- Compute minimal subset of statements that still implies
// bottom.
minimize_path(path_statements);
}
return !bottom_found;
}
template<typename CFG, typename AbsDom>
bool path_analyzer<CFG,AbsDom>::has_kid(basic_block_label_t b1, basic_block_label_t b2) {
for (basic_block_label_t child: m_cfg.next_nodes (b1)) {
if (child == b2)
return true;
}
return false;
}
// Compute a minimal subset of statements based on syntactic
// dependencies.
template<typename CFG, typename AbsDom>
void path_analyzer<CFG,AbsDom>::
remove_irrelevant_statements(std::vector<crab::cfg::statement_wrapper>& core) {
typedef typename CFG::basic_block_t::assume_t assume_t;
typedef typename CFG::basic_block_t::bool_assume_t bool_assume_t;
unsigned size = core.size();
if (size <= 1) {
return;
}
stmt_t& last = *(core[size-1].m_s);
if (!(last.is_assume()) && !(last.is_bool_assume())) {
// we expect last statement to be an assume, otherwise we bail out.
return;
}
typedef domains::flat_killgen_domain<typename CFG::variable_t> var_dom_t;
var_dom_t d;
if (last.is_assume()) {
auto assume = static_cast<const assume_t*>(&last);
if (assume->constraint().is_contradiction()) {
return; // we do nothing
}
for (typename CFG::variable_t v: assume->constraint().variables()) {
d += v;
}
} else {
auto bool_assume = static_cast<const bool_assume_t*>(&last);
d += bool_assume->cond();
}
// Traverse the whole path backwards and remove irrelevant
// statements based on data dependencies.
std::vector<bool> enabled(size, false);
enabled[size-1] = true; // added the last assume
for(int i= size-2; i >= 0 ; --i) { // start from penultimate statement
stmt_t& s = *(core[i].m_s);
var_dom_t uses, defs;
const typename stmt_t::live_t& ls = s.get_live();
for (auto v: boost::make_iterator_range(ls.uses_begin(), ls.uses_end()))
{ uses += v; }
for (auto v: boost::make_iterator_range(ls.defs_begin(), ls.defs_end()))
{ defs += v; }
if (defs.is_bottom() && !uses.is_bottom() && !(uses & d).is_bottom ()) {
d += uses;
enabled[i] = true;
} else if (!(d & defs).is_bottom()) {
d -= defs;
d += uses;
enabled[i] = true;
} else {
// irrelevant statement
}
}
std::vector<crab::cfg::statement_wrapper> res;
res.reserve(size);
for(unsigned i=0; i < size; ++i) {
if (enabled[i]) res.push_back(core[i]);
}
core.assign(res.begin(), res.end());
}
/**
** Compute a minimal subset of statements needed to prove that the
** path is infeasible.
**
** Pre: the strongest post-condition of path is false.
** Pre: path is well-formed.
**/
template<typename CFG, typename AbsDom>
void path_analyzer<CFG,AbsDom>::minimize_path(const std::vector<crab::cfg::statement_wrapper>& path) {
std::vector<crab::cfg::statement_wrapper> core(path.begin(), path.end());
// Remove first syntactically irrelevant statements wrt to the last
// statement which should be an assume statement where bottom was
// first inferred.
remove_irrelevant_statements(core);
// We use the enabled vector because we need to preserve the order
// since abstract interpretation cares about that.
std::vector<bool> enabled(core.size(), true);
for (unsigned i = 0; i < core.size (); ++i) {
enabled[i] = false;
abs_dom_t pre = AbsDom::top(); // m_fwd_abs_tr.inv();
bool res = true;
for(unsigned j=0; j < core.size(); ++j) {
if (enabled[j]) {
m_fwd_abs_tr.set (pre);
core[j].m_s->accept (&m_fwd_abs_tr);
res = !pre.is_bottom();
if (!res) break;
}
}
if (res) {
enabled[i] = true;
}
}
m_core.reserve(core.size());
for (unsigned i=0; i < core.size();++i) {
if (enabled[i]) {
m_core.push_back(core[i]);
}
}
assert(!m_core.empty());
}
}
}
#include <crab_llvm/crab_domains.hh>
#include <crab_llvm/crab_cfg.hh>
namespace crab {
namespace analyzer {
// explicit instantiations
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::num_domain_t>;
#ifdef HAVE_ALL_DOMAINS
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::term_int_domain_t>;
#endif
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::interval_domain_t>;
template class path_analyzer<crab_llvm::cfg_ref_t, crab_llvm::wrapped_interval_domain_t>;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "math/mathematics.h"
using namespace std ;
int main() {
cout << "\t\t***svector Test section***" << endl ;
svector myvec( 5.0, 15.0, 3.0, true ) ;
svector otrvec( 3.0, 22.0, -20.0, true ) ;
cout << myvec << endl ;
cout << "The two vectors...."
<< "\nmyvec" << myvec
<< "\notrvec" << otrvec ;
( myvec != otrvec ) ? cout << " are not equal." << endl :
cout << " are equal." << endl ;
cout << "The inner product of these two vectors is: "
<< myvec.dot(otrvec) << endl ;
cout << "The cross product is: "
<< myvec.cross(otrvec) << endl ;
cout << "(myvec < otrvec) is " ;
(myvec < otrvec) ? cout << "true." << endl :
cout << "false." << endl ;
cout << "maginutde of myvec: " << myvec.magnitude() << endl ;
cout << "norm of myvec " << myvec.norm() << endl ;
cout << "\t\t***bvector Test section***" << endl ;
bvector i( 1.0, 0.0, 0.0 ) ;
bvector j( 0.0, 1.0, 0.0 ) ;
bvector k( 0.0, 0.0, 1.0 ) ;
cout << "The dot products are..." << endl ;
cout << "i dot i: " << i.dot(i) << endl ;
cout << "i dot j: " << i.dot(j) << endl ;
cout << "i dot k: " << i.dot(k) << endl ;
cout << "j dot j: " << j.dot(j) << endl ;
cout << "j dot k: " << j.dot(k) << endl ;
cout << "k dot k: " << k.dot(k) << endl ;
cout << "The cross products are..." << endl ;
cout << "i cross i: " << i.cross(i) << endl ;
cout << "i cross j: " << i.cross(j) << endl ;
cout << "i cross k: " << i.cross(k) << endl ;
cout << "j cross i: " << j.cross(i) << endl ;
cout << "j cross j: " << j.cross(j) << endl ;
cout << "j cross k: " << j.cross(k) << endl ;
cout << "k cross i: " << k.cross(i) << endl ;
cout << "k cross j: " << k.cross(j) << endl ;
cout << "k cross k: " << k.cross(k) << endl ;
return 0 ;
}
<commit_msg>When the template function takes no arguments, the compiler requires that the template arguments be deducible. This is because without an arguement, the compiler would not be able to figure out what the arguments are. Thus for norm() the calles requires norm<T>().<commit_after>#include <iostream>
#include "math/mathematics.h"
using namespace std ;
int main() {
cout << "\t\t***svector Test section***" << endl ;
svector myvec( 5.0, 15.0, 3.0, true ) ;
svector otrvec( 3.0, 22.0, -20.0, true ) ;
cout << myvec << endl ;
cout << "The two vectors...."
<< "\nmyvec" << myvec
<< "\notrvec" << otrvec ;
( myvec != otrvec ) ? cout << " are not equal." << endl :
cout << " are equal." << endl ;
cout << "The inner product of these two vectors is: "
<< myvec.dot(otrvec) << endl ;
cout << "The cross product is: "
<< myvec.cross(otrvec) << endl ;
cout << "(myvec < otrvec) is " ;
(myvec < otrvec) ? cout << "true." << endl :
cout << "false." << endl ;
cout << "maginutde of myvec: " << myvec.magnitude() << endl ;
svector n_vec = myvec.norm<svector>() ;
cout << "norm of myvec " << n_vec << endl ;
cout << "magnitude of the norm of myvec: " << (myvec.norm<svector>()).magnitude() << endl ;
cout << "\t\t***bvector Test section***" << endl ;
bvector i( 1.0, 0.0, 0.0 ) ;
bvector j( 0.0, 1.0, 0.0 ) ;
bvector k( 0.0, 0.0, 1.0 ) ;
cout << "The dot products are..." << endl ;
cout << "i dot i: " << i.dot(i) << endl ;
cout << "i dot j: " << i.dot(j) << endl ;
cout << "i dot k: " << i.dot(k) << endl ;
cout << "j dot j: " << j.dot(j) << endl ;
cout << "j dot k: " << j.dot(k) << endl ;
cout << "k dot k: " << k.dot(k) << endl ;
cout << "The cross products are..." << endl ;
cout << "i cross i: " << i.cross(i) << endl ;
cout << "i cross j: " << i.cross(j) << endl ;
cout << "i cross k: " << i.cross(k) << endl ;
cout << "j cross i: " << j.cross(i) << endl ;
cout << "j cross j: " << j.cross(j) << endl ;
cout << "j cross k: " << j.cross(k) << endl ;
cout << "k cross i: " << k.cross(i) << endl ;
cout << "k cross j: " << k.cross(j) << endl ;
cout << "k cross k: " << k.cross(k) << endl ;
return 0 ;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <GPIOClass.h>
using namespace std;
int main (void)
{
string inputstate;
GPIOClass* gpio4 = new GPIOClass("4"); //create new GPIO object to be attached to GPIO4
GPIOClass* gpio17 = new GPIOClass("17"); //create new GPIO object to be attached to GPIO17
gpio4->export_gpio(); //export GPIO4
gpio17->export_gpio(); //export GPIO17
cout << " GPIO pins exported" << endl;
gpio17->setdir_gpio("in"); //GPIO4 set to output
gpio4->setdir_gpio("out"); // GPIO17 set to input
cout << " Set GPIO pin directions" << endl;
while(1)
{
usleep(500000); // wait for 0.5 seconds
gpio17->getval_gpio(inputstate); //read state of GPIO17 input pin
cout << "Current input pin state is " << inputstate <<endl;
if(inputstate == "0") // if input pin is at state "0" i.e. button pressed
{
cout << "input pin state is "Pressed ".n Will check input pin state again in 20ms "<<endl;
usleep(20000);
cout << "Checking again ....." << endl;
gpio17->getval_gpio(inputstate); // checking again to ensure that state "0" is due to button press and not noise
if(inputstate == "0")
{
cout << "input pin state is definitely "Pressed". Turning LED ON" <<endl;
gpio4->setval_gpio("1"); // turn LED ON
cout << " Waiting until pin is unpressed....." << endl;
while (inputstate == "0"){
gpio17->getval_gpio(inputstate);
};
cout << "pin is unpressed" << endl;
}
else
cout << "input pin state is definitely "UnPressed". That was just noise." <<endl;
}
gpio4->setval_gpio("0");
}
cout << "Exiting....." << endl;
return 0;
<commit_msg>Update TestGPIO.cpp<commit_after>#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <GPIOClass.h>
using namespace std;
int main (void)
{
string inputstate;
GPIOClass* gpio4 = new GPIOClass("4"); //create new GPIO object to be attached to GPIO4
GPIOClass* gpio17 = new GPIOClass("17"); //create new GPIO object to be attached to GPIO17
gpio4->export_gpio(); //export GPIO4
gpio17->export_gpio(); //export GPIO17
cout << " GPIO pins exported" << endl;
gpio17->setdir_gpio("in"); //GPIO4 set to output
gpio4->setdir_gpio("out"); // GPIO17 set to input
cout << " Set GPIO pin directions" << endl;
while(1)
{
usleep(500000); // wait for 0.5 seconds
gpio17->getval_gpio(inputstate); //read state of GPIO17 input pin
cout << "Current input pin state is " << inputstate <<endl;
if(inputstate == "0") // if input pin is at state "0" i.e. button pressed
{
cout << "input pin state is "Pressed ".n Will check input pin state again in 20ms "<<endl;
usleep(20000);
cout << "Checking again ....." << endl;
gpio17->getval_gpio(inputstate); // checking again to ensure that state "0" is due to button press and not noise
if(inputstate == "0")
{
cout << "input pin state is definitely "Pressed". Turning LED ON" <<endl;
gpio4->setval_gpio("1"); // turn LED ON
cout << " Waiting until pin is unpressed....." << endl;
while (inputstate == "0"){
gpio17->getval_gpio(inputstate);
};
cout << "pin is unpressed" << endl;
}
else
cout << "input pin state is definitely "UnPressed". That was just noise." <<endl;
}
gpio4->setval_gpio("0");
}
cout << "Exiting....." << endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/hid/hid_service.h"
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "components/device_event_log/device_event_log.h"
#if defined(OS_LINUX) && defined(USE_UDEV)
#include "device/hid/hid_service_linux.h"
#elif defined(OS_MACOSX)
#include "device/hid/hid_service_mac.h"
#else
#include "device/hid/hid_service_win.h"
#endif
namespace device {
namespace {
HidService* g_service;
}
void HidService::Observer::OnDeviceAdded(
scoped_refptr<HidDeviceInfo> device_info) {
}
void HidService::Observer::OnDeviceRemoved(
scoped_refptr<HidDeviceInfo> device_info) {
}
HidService* HidService::GetInstance(
scoped_refptr<base::SingleThreadTaskRunner> file_task_runner) {
if (g_service == NULL) {
#if defined(OS_LINUX) && defined(USE_UDEV)
g_service = new HidServiceLinux(file_task_runner);
#elif defined(OS_MACOSX)
g_service = new HidServiceMac(file_task_runner);
#elif defined(OS_WIN)
g_service = new HidServiceWin(file_task_runner);
#endif
if (g_service != nullptr) {
base::AtExitManager::RegisterTask(base::Bind(
&base::DeletePointer<HidService>, base::Unretained(g_service)));
}
}
return g_service;
}
void HidService::SetInstanceForTest(HidService* instance) {
DCHECK(!g_service);
g_service = instance;
base::AtExitManager::RegisterTask(base::Bind(&base::DeletePointer<HidService>,
base::Unretained(g_service)));
}
void HidService::GetDevices(const GetDevicesCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
if (enumeration_ready_) {
std::vector<scoped_refptr<HidDeviceInfo>> devices;
for (const auto& map_entry : devices_) {
devices.push_back(map_entry.second);
}
base::MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, devices));
} else {
pending_enumerations_.push_back(callback);
}
}
void HidService::AddObserver(HidService::Observer* observer) {
observer_list_.AddObserver(observer);
}
void HidService::RemoveObserver(HidService::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
// Fills in the device info struct of the given device_id.
scoped_refptr<HidDeviceInfo> HidService::GetDeviceInfo(
const HidDeviceId& device_id) const {
DCHECK(thread_checker_.CalledOnValidThread());
DeviceMap::const_iterator it = devices_.find(device_id);
if (it == devices_.end()) {
return nullptr;
}
return it->second;
}
HidService::HidService() : enumeration_ready_(false) {
}
HidService::~HidService() {
DCHECK(thread_checker_.CalledOnValidThread());
}
void HidService::AddDevice(scoped_refptr<HidDeviceInfo> device_info) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!ContainsKey(devices_, device_info->device_id())) {
devices_[device_info->device_id()] = device_info;
HID_LOG(USER) << "HID device "
<< (enumeration_ready_ ? "added" : "detected")
<< ": vendorId = " << device_info->vendor_id()
<< ", productId = " << device_info->product_id()
<< ", deviceId = '" << device_info->device_id() << "'";
if (enumeration_ready_) {
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceAdded(device_info));
}
}
}
void HidService::RemoveDevice(const HidDeviceId& device_id) {
DCHECK(thread_checker_.CalledOnValidThread());
DeviceMap::iterator it = devices_.find(device_id);
if (it != devices_.end()) {
HID_LOG(USER) << "HID device removed: deviceId = '" << device_id << "'";
if (enumeration_ready_) {
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceRemoved(it->second));
}
devices_.erase(it);
}
}
void HidService::FirstEnumerationComplete() {
enumeration_ready_ = true;
if (!pending_enumerations_.empty()) {
std::vector<scoped_refptr<HidDeviceInfo>> devices;
for (const auto& map_entry : devices_) {
devices.push_back(map_entry.second);
}
for (const GetDevicesCallback& callback : pending_enumerations_) {
callback.Run(devices);
}
pending_enumerations_.clear();
}
}
} // namespace device
<commit_msg>Guard hid_service_win.h include with OS_WIN.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/hid/hid_service.h"
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "components/device_event_log/device_event_log.h"
#if defined(OS_LINUX) && defined(USE_UDEV)
#include "device/hid/hid_service_linux.h"
#elif defined(OS_MACOSX)
#include "device/hid/hid_service_mac.h"
#elif defined(OS_WIN)
#include "device/hid/hid_service_win.h"
#endif
namespace device {
namespace {
HidService* g_service;
}
void HidService::Observer::OnDeviceAdded(
scoped_refptr<HidDeviceInfo> device_info) {
}
void HidService::Observer::OnDeviceRemoved(
scoped_refptr<HidDeviceInfo> device_info) {
}
HidService* HidService::GetInstance(
scoped_refptr<base::SingleThreadTaskRunner> file_task_runner) {
if (g_service == NULL) {
#if defined(OS_LINUX) && defined(USE_UDEV)
g_service = new HidServiceLinux(file_task_runner);
#elif defined(OS_MACOSX)
g_service = new HidServiceMac(file_task_runner);
#elif defined(OS_WIN)
g_service = new HidServiceWin(file_task_runner);
#endif
if (g_service != nullptr) {
base::AtExitManager::RegisterTask(base::Bind(
&base::DeletePointer<HidService>, base::Unretained(g_service)));
}
}
return g_service;
}
void HidService::SetInstanceForTest(HidService* instance) {
DCHECK(!g_service);
g_service = instance;
base::AtExitManager::RegisterTask(base::Bind(&base::DeletePointer<HidService>,
base::Unretained(g_service)));
}
void HidService::GetDevices(const GetDevicesCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
if (enumeration_ready_) {
std::vector<scoped_refptr<HidDeviceInfo>> devices;
for (const auto& map_entry : devices_) {
devices.push_back(map_entry.second);
}
base::MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(callback, devices));
} else {
pending_enumerations_.push_back(callback);
}
}
void HidService::AddObserver(HidService::Observer* observer) {
observer_list_.AddObserver(observer);
}
void HidService::RemoveObserver(HidService::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
// Fills in the device info struct of the given device_id.
scoped_refptr<HidDeviceInfo> HidService::GetDeviceInfo(
const HidDeviceId& device_id) const {
DCHECK(thread_checker_.CalledOnValidThread());
DeviceMap::const_iterator it = devices_.find(device_id);
if (it == devices_.end()) {
return nullptr;
}
return it->second;
}
HidService::HidService() : enumeration_ready_(false) {
}
HidService::~HidService() {
DCHECK(thread_checker_.CalledOnValidThread());
}
void HidService::AddDevice(scoped_refptr<HidDeviceInfo> device_info) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!ContainsKey(devices_, device_info->device_id())) {
devices_[device_info->device_id()] = device_info;
HID_LOG(USER) << "HID device "
<< (enumeration_ready_ ? "added" : "detected")
<< ": vendorId = " << device_info->vendor_id()
<< ", productId = " << device_info->product_id()
<< ", deviceId = '" << device_info->device_id() << "'";
if (enumeration_ready_) {
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceAdded(device_info));
}
}
}
void HidService::RemoveDevice(const HidDeviceId& device_id) {
DCHECK(thread_checker_.CalledOnValidThread());
DeviceMap::iterator it = devices_.find(device_id);
if (it != devices_.end()) {
HID_LOG(USER) << "HID device removed: deviceId = '" << device_id << "'";
if (enumeration_ready_) {
FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceRemoved(it->second));
}
devices_.erase(it);
}
}
void HidService::FirstEnumerationComplete() {
enumeration_ready_ = true;
if (!pending_enumerations_.empty()) {
std::vector<scoped_refptr<HidDeviceInfo>> devices;
for (const auto& map_entry : devices_) {
devices.push_back(map_entry.second);
}
for (const GetDevicesCallback& callback : pending_enumerations_) {
callback.Run(devices);
}
pending_enumerations_.clear();
}
}
} // namespace device
<|endoftext|>
|
<commit_before>// Copyright 2018 Google LLC
//
// 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
//
// https://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 "tools/render/processed_trace.h"
#include "absl/algorithm/container.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "tools/render/layout_constants.h"
namespace quic_trace {
namespace render {
namespace {
std::string FormatBandwidth(size_t total_bytes, uint64_t time_delta_us) {
double rate = 8e6 * total_bytes / time_delta_us;
const char* unit = "";
for (const char* current_unit : {"k", "M", "G"}) {
if (rate < 1e3) {
break;
}
rate /= 1e3;
unit = current_unit;
}
char buffer[16];
snprintf(buffer, sizeof(buffer), "%.2f %sbps", rate, unit);
return buffer;
}
std::string FormatPercentage(size_t numerator, size_t denominator) {
double percentage = 100. * numerator / denominator;
char buffer[8];
snprintf(buffer, sizeof(buffer), "%.2f%%", percentage);
return buffer;
}
std::string FormatTime(uint64_t time_us) {
char buffer[16];
snprintf(buffer, sizeof(buffer), "%.3fs", time_us / 1e6);
return buffer;
}
std::string FormatRtt(uint64_t rtt_us) {
if (rtt_us < 10 * 1000) {
return absl::StrCat(rtt_us, "µs");
}
if (rtt_us < 1000 * 1000) {
return absl::StrCat(rtt_us / 1000, "ms");
}
return FormatTime(rtt_us);
}
} // namespace
void ProcessedTrace::AddPacket(TraceRenderer* renderer,
const Event& packet,
Interval interval,
PacketType type) {
renderer->AddPacket(packet.time_us(), interval.offset, interval.size, type);
rendered_packets_.push_back(
RenderedPacket{Box{vec2(packet.time_us(), interval.offset),
vec2(kSentPacketDurationMs, interval.size)},
&packet});
}
ProcessedTrace::ProcessedTrace(std::unique_ptr<Trace> trace,
TraceRenderer* renderer) {
renderer->PacketCountHint(trace->events_size());
quic_trace::NumberingWithoutRetransmissions numbering;
size_t largest_sent = 0;
uint64_t largest_time = 0;
for (const Event& event : trace->events()) {
if (!event.has_time_us() || event.time_us() < largest_time) {
LOG(FATAL)
<< "All events in the trace have to be sorted in chronological order";
}
largest_time = event.time_us();
if (event.event_type() == PACKET_SENT) {
Interval mapped = numbering.AssignTraceNumbering(event);
AddPacket(renderer, event, mapped, PacketType::SENT);
largest_sent =
std::max<size_t>(mapped.offset + mapped.size, largest_sent);
}
if (event.event_type() == PACKET_RECEIVED) {
for (const Frame& frame : event.frames()) {
for (const AckBlock& range : frame.ack_info().acked_packets()) {
for (size_t i = range.first_packet(); i <= range.last_packet(); i++) {
if (!packets_acked_.insert(i).second) {
continue;
}
Interval mapped = numbering.GetTraceNumbering(i);
AddPacket(renderer, event, mapped, PacketType::ACKED);
acks_.emplace(vec2(event.time_us(), mapped.offset), i);
// Don't count spurious retransmissions as losses.
packets_lost_.erase(i);
}
}
}
}
if (event.event_type() == PACKET_LOST) {
Interval mapped = numbering.GetTraceNumbering(event.packet_number());
AddPacket(renderer, event, mapped, PacketType::LOST);
packets_lost_.insert(event.packet_number());
}
if (event.event_type() == APPLICATION_LIMITED) {
// Normally, we would use the size of the packet as height, but
// app-limited events have no size, so we pick an arbitrary number (in
// bytes).
const size_t kAppLimitedHeigth = 800;
AddPacket(renderer, event, Interval{largest_sent, kAppLimitedHeigth},
PacketType::APP_LIMITED);
}
}
renderer->FinishPackets();
trace_ = std::move(trace);
}
bool ProcessedTrace::SummaryTable(Table* table,
float start_time,
float end_time) {
auto compare = [](Event a, Event b) { return a.time_us() < b.time_us(); };
Event key_event;
key_event.set_time_us(start_time);
auto start_it = absl::c_lower_bound(trace_->events(), key_event, compare);
key_event.set_time_us(end_time);
auto end_it = absl::c_upper_bound(trace_->events(), key_event, compare);
if (start_it > end_it) {
return false;
}
// TODO(vasilvv): add actually useful information.
size_t count_sent = 0;
size_t bytes_sent = 0;
size_t bytes_sent_acked = 0;
size_t bytes_sent_lost = 0;
for (auto it = start_it; it != end_it; it++) {
switch (it->event_type()) {
case PACKET_SENT:
count_sent++;
bytes_sent += it->packet_size();
if (packets_acked_.count(it->packet_number()) > 0) {
bytes_sent_acked += it->packet_size();
}
if (packets_lost_.count(it->packet_number()) > 0) {
bytes_sent_lost += it->packet_size();
}
break;
default:
break;
};
}
table->AddHeader("Selection summary");
table->AddRow("#sent", absl::StrCat(count_sent));
table->AddRow("Send rate",
FormatBandwidth(bytes_sent, end_time - start_time));
table->AddRow("Goodput",
FormatBandwidth(bytes_sent_acked, end_time - start_time));
table->AddRow("Loss rate", FormatPercentage(bytes_sent_lost, bytes_sent));
return true;
}
ProcessedTrace::PacketSearchResult ProcessedTrace::FindPacketContainingPoint(
vec2 point,
vec2 margin) {
RenderedPacket key{Box(), nullptr};
key.box.origin.x = point.x - kSentPacketDurationMs - margin.x;
auto start_it = absl::c_lower_bound(rendered_packets_, key);
key.box.origin.x = point.x + kSentPacketDurationMs + margin.x;
auto end_it = absl::c_upper_bound(rendered_packets_, key);
if (start_it > end_it) {
return PacketSearchResult();
}
auto closest_box = end_it;
float closest_distance;
for (auto it = start_it; it != end_it; it++) {
Box target_box{it->box.origin - margin, it->box.size + 2 * margin};
if (IsInside(point, target_box)) {
float distance = DistanceSquared(point, BoxCenter(target_box));
if (closest_box == end_it || distance < closest_distance) {
closest_box = it;
closest_distance = distance;
}
}
}
if (closest_box != end_it) {
PacketSearchResult result;
result.index = closest_box - rendered_packets_.cbegin();
result.as_rendered = &closest_box->box;
result.event = closest_box->packet;
return result;
}
return PacketSearchResult();
}
namespace {
const char* EncryptionLevelToString(EncryptionLevel level) {
switch (level) {
case ENCRYPTION_INITIAL:
return "Initial";
case ENCRYPTION_0RTT:
return "0-RTT";
case ENCRYPTION_1RTT:
return "1-RTT";
case ENCRYPTION_UNKNOWN:
default:
return "???";
}
}
constexpr int kMaxAckBlocksShown = 3;
std::string AckSummary(const AckInfo& ack) {
if (ack.acked_packets_size() == 0) {
return "";
}
bool overflow = false;
int blocks_to_show = ack.acked_packets_size();
if (blocks_to_show > kMaxAckBlocksShown) {
blocks_to_show = kMaxAckBlocksShown;
overflow = true;
}
std::vector<std::string> ack_ranges;
for (int i = 0; i < blocks_to_show; i++) {
const AckBlock& block = ack.acked_packets(i);
if (block.first_packet() == block.last_packet()) {
ack_ranges.push_back(absl::StrCat(block.first_packet()));
} else {
ack_ranges.push_back(
absl::StrCat(block.first_packet(), ":", block.last_packet()));
}
}
std::string result = absl::StrJoin(ack_ranges, ", ");
if (overflow) {
absl::StrAppend(&result, "...");
}
return result;
}
} // namespace
void ProcessedTrace::FillTableForPacket(Table* table,
const Box* as_rendered,
const Event* packet) {
switch (packet->event_type()) {
case PACKET_SENT:
table->AddHeader(absl::StrCat("Sent packet #", packet->packet_number()));
break;
case PACKET_RECEIVED: {
std::string packet_acked = "???";
auto it = acks_.find(as_rendered->origin);
if (it != acks_.end()) {
packet_acked = absl::StrCat(it->second);
}
table->AddHeader(absl::StrCat("Ack for packet #", packet_acked));
break;
}
case PACKET_LOST:
table->AddHeader(absl::StrCat("Lost packet #", packet->packet_number()));
break;
case APPLICATION_LIMITED:
table->AddHeader("Application limited");
break;
default:
return;
}
table->AddRow("Time", FormatTime(packet->time_us()));
if (packet->event_type() == PACKET_SENT) {
table->AddRow("Size", absl::StrCat(packet->packet_size(), "bytes"));
table->AddRow("Encryption",
EncryptionLevelToString(packet->encryption_level()));
table->AddHeader("Frame list");
for (const Frame& frame : packet->frames()) {
switch (frame.frame_type()) {
case STREAM:
table->AddRow(
"Stream",
absl::StrCat("#", frame.stream_frame_info().stream_id(), ": ",
frame.stream_frame_info().offset(), "-",
frame.stream_frame_info().offset() +
frame.stream_frame_info().length(),
" (", frame.stream_frame_info().length(), ")"));
break;
case RESET_STREAM:
table->AddRow(
"Reset stream",
absl::StrCat("#", frame.reset_stream_info().stream_id()));
break;
case CONNECTION_CLOSE:
table->AddRow(
"Connection close",
absl::StrCat(absl::Hex(frame.close_info().error_code())));
break;
case PING:
table->AddRow("Ping", "");
break;
case BLOCKED:
table->AddRow("Blocked", "");
break;
case STREAM_BLOCKED:
table->AddRow("Stream blocked",
absl::StrCat(frame.flow_control_info().stream_id()));
break;
case ACK:
table->AddRow("Ack", AckSummary(frame.ack_info()));
break;
default:
table->AddRow("Unknown", "");
break;
}
}
}
if (packet->has_transport_state()) {
const TransportState& state = packet->transport_state();
table->AddHeader("Transport state");
if (state.has_last_rtt_us()) {
table->AddRow("RTT", FormatRtt(state.last_rtt_us()));
}
if (state.has_smoothed_rtt_us()) {
table->AddRow("SRTT", FormatRtt(state.smoothed_rtt_us()));
}
if (state.has_min_rtt_us()) {
table->AddRow("Min RTT", FormatRtt(state.min_rtt_us()));
}
if (state.has_in_flight_bytes()) {
table->AddRow("In flight",
absl::StrCat(state.in_flight_bytes(), " bytes"));
}
if (state.has_cwnd_bytes()) {
table->AddRow("CWND", absl::StrCat(state.cwnd_bytes(), " bytes"));
}
if (state.has_pacing_rate_bps()) {
table->AddRow("Pacing rate",
FormatBandwidth(state.pacing_rate_bps(), 8000 * 1000));
}
if (state.has_congestion_control_state()) {
table->AddRow("CC State", state.congestion_control_state());
}
}
}
absl::optional<Box> ProcessedTrace::BoundContainedPackets(Box boundary) {
RenderedPacket key{Box(), nullptr};
key.box.origin.x = boundary.origin.x;
auto range_start = absl::c_lower_bound(rendered_packets_, key);
key.box.origin.x =
boundary.origin.x + boundary.size.x + kSentPacketDurationMs;
auto range_end = absl::c_upper_bound(rendered_packets_, key);
if (range_start == rendered_packets_.end() ||
range_end == rendered_packets_.end() || range_start > range_end) {
return absl::nullopt;
}
absl::optional<Box> result;
for (auto it = range_start; it <= range_end; it++) {
if (IsInside(it->box, boundary)) {
result = result.has_value() ? BoundingBox(*result, it->box) : it->box;
}
}
return result;
}
} // namespace render
} // namespace quic_trace
<commit_msg>truncate congestion control states longer than 80 characters<commit_after>// Copyright 2018 Google LLC
//
// 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
//
// https://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 "tools/render/processed_trace.h"
#include "absl/algorithm/container.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "tools/render/layout_constants.h"
namespace quic_trace {
namespace render {
namespace {
std::string FormatBandwidth(size_t total_bytes, uint64_t time_delta_us) {
double rate = 8e6 * total_bytes / time_delta_us;
const char* unit = "";
for (const char* current_unit : {"k", "M", "G"}) {
if (rate < 1e3) {
break;
}
rate /= 1e3;
unit = current_unit;
}
char buffer[16];
snprintf(buffer, sizeof(buffer), "%.2f %sbps", rate, unit);
return buffer;
}
std::string FormatPercentage(size_t numerator, size_t denominator) {
double percentage = 100. * numerator / denominator;
char buffer[8];
snprintf(buffer, sizeof(buffer), "%.2f%%", percentage);
return buffer;
}
std::string FormatTime(uint64_t time_us) {
char buffer[16];
snprintf(buffer, sizeof(buffer), "%.3fs", time_us / 1e6);
return buffer;
}
std::string FormatRtt(uint64_t rtt_us) {
if (rtt_us < 10 * 1000) {
return absl::StrCat(rtt_us, "µs");
}
if (rtt_us < 1000 * 1000) {
return absl::StrCat(rtt_us / 1000, "ms");
}
return FormatTime(rtt_us);
}
} // namespace
void ProcessedTrace::AddPacket(TraceRenderer* renderer,
const Event& packet,
Interval interval,
PacketType type) {
renderer->AddPacket(packet.time_us(), interval.offset, interval.size, type);
rendered_packets_.push_back(
RenderedPacket{Box{vec2(packet.time_us(), interval.offset),
vec2(kSentPacketDurationMs, interval.size)},
&packet});
}
ProcessedTrace::ProcessedTrace(std::unique_ptr<Trace> trace,
TraceRenderer* renderer) {
renderer->PacketCountHint(trace->events_size());
quic_trace::NumberingWithoutRetransmissions numbering;
size_t largest_sent = 0;
uint64_t largest_time = 0;
for (const Event& event : trace->events()) {
if (!event.has_time_us() || event.time_us() < largest_time) {
LOG(FATAL)
<< "All events in the trace have to be sorted in chronological order";
}
largest_time = event.time_us();
if (event.event_type() == PACKET_SENT) {
Interval mapped = numbering.AssignTraceNumbering(event);
AddPacket(renderer, event, mapped, PacketType::SENT);
largest_sent =
std::max<size_t>(mapped.offset + mapped.size, largest_sent);
}
if (event.event_type() == PACKET_RECEIVED) {
for (const Frame& frame : event.frames()) {
for (const AckBlock& range : frame.ack_info().acked_packets()) {
for (size_t i = range.first_packet(); i <= range.last_packet(); i++) {
if (!packets_acked_.insert(i).second) {
continue;
}
Interval mapped = numbering.GetTraceNumbering(i);
AddPacket(renderer, event, mapped, PacketType::ACKED);
acks_.emplace(vec2(event.time_us(), mapped.offset), i);
// Don't count spurious retransmissions as losses.
packets_lost_.erase(i);
}
}
}
}
if (event.event_type() == PACKET_LOST) {
Interval mapped = numbering.GetTraceNumbering(event.packet_number());
AddPacket(renderer, event, mapped, PacketType::LOST);
packets_lost_.insert(event.packet_number());
}
if (event.event_type() == APPLICATION_LIMITED) {
// Normally, we would use the size of the packet as height, but
// app-limited events have no size, so we pick an arbitrary number (in
// bytes).
const size_t kAppLimitedHeigth = 800;
AddPacket(renderer, event, Interval{largest_sent, kAppLimitedHeigth},
PacketType::APP_LIMITED);
}
}
renderer->FinishPackets();
trace_ = std::move(trace);
}
bool ProcessedTrace::SummaryTable(Table* table,
float start_time,
float end_time) {
auto compare = [](Event a, Event b) { return a.time_us() < b.time_us(); };
Event key_event;
key_event.set_time_us(start_time);
auto start_it = absl::c_lower_bound(trace_->events(), key_event, compare);
key_event.set_time_us(end_time);
auto end_it = absl::c_upper_bound(trace_->events(), key_event, compare);
if (start_it > end_it) {
return false;
}
// TODO(vasilvv): add actually useful information.
size_t count_sent = 0;
size_t bytes_sent = 0;
size_t bytes_sent_acked = 0;
size_t bytes_sent_lost = 0;
for (auto it = start_it; it != end_it; it++) {
switch (it->event_type()) {
case PACKET_SENT:
count_sent++;
bytes_sent += it->packet_size();
if (packets_acked_.count(it->packet_number()) > 0) {
bytes_sent_acked += it->packet_size();
}
if (packets_lost_.count(it->packet_number()) > 0) {
bytes_sent_lost += it->packet_size();
}
break;
default:
break;
};
}
table->AddHeader("Selection summary");
table->AddRow("#sent", absl::StrCat(count_sent));
table->AddRow("Send rate",
FormatBandwidth(bytes_sent, end_time - start_time));
table->AddRow("Goodput",
FormatBandwidth(bytes_sent_acked, end_time - start_time));
table->AddRow("Loss rate", FormatPercentage(bytes_sent_lost, bytes_sent));
return true;
}
ProcessedTrace::PacketSearchResult ProcessedTrace::FindPacketContainingPoint(
vec2 point,
vec2 margin) {
RenderedPacket key{Box(), nullptr};
key.box.origin.x = point.x - kSentPacketDurationMs - margin.x;
auto start_it = absl::c_lower_bound(rendered_packets_, key);
key.box.origin.x = point.x + kSentPacketDurationMs + margin.x;
auto end_it = absl::c_upper_bound(rendered_packets_, key);
if (start_it > end_it) {
return PacketSearchResult();
}
auto closest_box = end_it;
float closest_distance;
for (auto it = start_it; it != end_it; it++) {
Box target_box{it->box.origin - margin, it->box.size + 2 * margin};
if (IsInside(point, target_box)) {
float distance = DistanceSquared(point, BoxCenter(target_box));
if (closest_box == end_it || distance < closest_distance) {
closest_box = it;
closest_distance = distance;
}
}
}
if (closest_box != end_it) {
PacketSearchResult result;
result.index = closest_box - rendered_packets_.cbegin();
result.as_rendered = &closest_box->box;
result.event = closest_box->packet;
return result;
}
return PacketSearchResult();
}
namespace {
const char* EncryptionLevelToString(EncryptionLevel level) {
switch (level) {
case ENCRYPTION_INITIAL:
return "Initial";
case ENCRYPTION_0RTT:
return "0-RTT";
case ENCRYPTION_1RTT:
return "1-RTT";
case ENCRYPTION_UNKNOWN:
default:
return "???";
}
}
constexpr int kMaxAckBlocksShown = 3;
std::string AckSummary(const AckInfo& ack) {
if (ack.acked_packets_size() == 0) {
return "";
}
bool overflow = false;
int blocks_to_show = ack.acked_packets_size();
if (blocks_to_show > kMaxAckBlocksShown) {
blocks_to_show = kMaxAckBlocksShown;
overflow = true;
}
std::vector<std::string> ack_ranges;
for (int i = 0; i < blocks_to_show; i++) {
const AckBlock& block = ack.acked_packets(i);
if (block.first_packet() == block.last_packet()) {
ack_ranges.push_back(absl::StrCat(block.first_packet()));
} else {
ack_ranges.push_back(
absl::StrCat(block.first_packet(), ":", block.last_packet()));
}
}
std::string result = absl::StrJoin(ack_ranges, ", ");
if (overflow) {
absl::StrAppend(&result, "...");
}
return result;
}
} // namespace
void ProcessedTrace::FillTableForPacket(Table* table,
const Box* as_rendered,
const Event* packet) {
switch (packet->event_type()) {
case PACKET_SENT:
table->AddHeader(absl::StrCat("Sent packet #", packet->packet_number()));
break;
case PACKET_RECEIVED: {
std::string packet_acked = "???";
auto it = acks_.find(as_rendered->origin);
if (it != acks_.end()) {
packet_acked = absl::StrCat(it->second);
}
table->AddHeader(absl::StrCat("Ack for packet #", packet_acked));
break;
}
case PACKET_LOST:
table->AddHeader(absl::StrCat("Lost packet #", packet->packet_number()));
break;
case APPLICATION_LIMITED:
table->AddHeader("Application limited");
break;
default:
return;
}
table->AddRow("Time", FormatTime(packet->time_us()));
if (packet->event_type() == PACKET_SENT) {
table->AddRow("Size", absl::StrCat(packet->packet_size(), "bytes"));
table->AddRow("Encryption",
EncryptionLevelToString(packet->encryption_level()));
table->AddHeader("Frame list");
for (const Frame& frame : packet->frames()) {
switch (frame.frame_type()) {
case STREAM:
table->AddRow(
"Stream",
absl::StrCat("#", frame.stream_frame_info().stream_id(), ": ",
frame.stream_frame_info().offset(), "-",
frame.stream_frame_info().offset() +
frame.stream_frame_info().length(),
" (", frame.stream_frame_info().length(), ")"));
break;
case RESET_STREAM:
table->AddRow(
"Reset stream",
absl::StrCat("#", frame.reset_stream_info().stream_id()));
break;
case CONNECTION_CLOSE:
table->AddRow(
"Connection close",
absl::StrCat(absl::Hex(frame.close_info().error_code())));
break;
case PING:
table->AddRow("Ping", "");
break;
case BLOCKED:
table->AddRow("Blocked", "");
break;
case STREAM_BLOCKED:
table->AddRow("Stream blocked",
absl::StrCat(frame.flow_control_info().stream_id()));
break;
case ACK:
table->AddRow("Ack", AckSummary(frame.ack_info()));
break;
default:
table->AddRow("Unknown", "");
break;
}
}
}
if (packet->has_transport_state()) {
const TransportState& state = packet->transport_state();
table->AddHeader("Transport state");
if (state.has_last_rtt_us()) {
table->AddRow("RTT", FormatRtt(state.last_rtt_us()));
}
if (state.has_smoothed_rtt_us()) {
table->AddRow("SRTT", FormatRtt(state.smoothed_rtt_us()));
}
if (state.has_min_rtt_us()) {
table->AddRow("Min RTT", FormatRtt(state.min_rtt_us()));
}
if (state.has_in_flight_bytes()) {
table->AddRow("In flight",
absl::StrCat(state.in_flight_bytes(), " bytes"));
}
if (state.has_cwnd_bytes()) {
table->AddRow("CWND", absl::StrCat(state.cwnd_bytes(), " bytes"));
}
if (state.has_pacing_rate_bps()) {
table->AddRow("Pacing rate",
FormatBandwidth(state.pacing_rate_bps(), 8000 * 1000));
}
if (state.has_congestion_control_state()) {
// truncate cc state strings longer than 80 characters
const int max_len = 80;
auto ccstate = state.congestion_control_state();
if(ccstate.length() > max_len) {
ccstate = ccstate.substr(0, max_len) + "...";
}
table->AddRow("CC State", ccstate);
}
}
}
absl::optional<Box> ProcessedTrace::BoundContainedPackets(Box boundary) {
RenderedPacket key{Box(), nullptr};
key.box.origin.x = boundary.origin.x;
auto range_start = absl::c_lower_bound(rendered_packets_, key);
key.box.origin.x =
boundary.origin.x + boundary.size.x + kSentPacketDurationMs;
auto range_end = absl::c_upper_bound(rendered_packets_, key);
if (range_start == rendered_packets_.end() ||
range_end == rendered_packets_.end() || range_start > range_end) {
return absl::nullopt;
}
absl::optional<Box> result;
for (auto it = range_start; it <= range_end; it++) {
if (IsInside(it->box, boundary)) {
result = result.has_value() ? BoundingBox(*result, it->box) : it->box;
}
}
return result;
}
} // namespace render
} // namespace quic_trace
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Window_win.h"
#include <tchar.h>
#include <windows.h>
#include <windowsx.h>
#include "SkUtils.h"
#include "../WindowContext.h"
#include "WindowContextFactory_win.h"
#ifdef SK_VULKAN
#include "../VulkanWindowContext.h"
#endif
namespace sk_app {
static int gWindowX = CW_USEDEFAULT;
static int gWindowY = 0;
static int gWindowWidth = CW_USEDEFAULT;
static int gWindowHeight = 0;
Window* Window::CreateNativeWindow(void* platformData) {
HINSTANCE hInstance = (HINSTANCE)platformData;
Window_win* window = new Window_win();
if (!window->init(hInstance)) {
delete window;
return nullptr;
}
return window;
}
void Window_win::closeWindow() {
RECT r;
if (GetWindowRect(fHWnd, &r)) {
gWindowX = r.left;
gWindowY = r.top;
gWindowWidth = r.right - r.left;
gWindowHeight = r.bottom - r.top;
}
DestroyWindow(fHWnd);
}
Window_win::~Window_win() {
this->closeWindow();
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
bool Window_win::init(HINSTANCE hInstance) {
fHInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
// The main window class name
static const TCHAR gSZWindowClass[] = _T("SkiaApp");
static WNDCLASSEX wcex;
static bool wcexInit = false;
if (!wcexInit) {
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = fHInstance;
wcex.hIcon = LoadIcon(fHInstance, (LPCTSTR)IDI_WINLOGO);
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = gSZWindowClass;
wcex.hIconSm = LoadIcon(fHInstance, (LPCTSTR)IDI_WINLOGO);;
if (!RegisterClassEx(&wcex)) {
return false;
}
wcexInit = true;
}
/*
if (fullscreen)
{
DEVMODE dmScreenSettings;
// If full screen set the screen to maximum size of the users desktop and 32bit.
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)width;
dmScreenSettings.dmPelsHeight = (unsigned long)height;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Change the display settings to full screen.
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
// Set the position of the window to the top left corner.
posX = posY = 0;
}
*/
// gIsFullscreen = fullscreen;
fHWnd = CreateWindow(gSZWindowClass, nullptr, WS_OVERLAPPEDWINDOW,
gWindowX, gWindowY, gWindowWidth, gWindowHeight,
nullptr, nullptr, fHInstance, nullptr);
if (!fHWnd)
{
return false;
}
SetWindowLongPtr(fHWnd, GWLP_USERDATA, (LONG_PTR)this);
RegisterTouchWindow(fHWnd, 0);
return true;
}
static Window::Key get_key(WPARAM vk) {
static const struct {
WPARAM fVK;
Window::Key fKey;
} gPair[] = {
{ VK_BACK, Window::Key::kBack },
{ VK_CLEAR, Window::Key::kBack },
{ VK_RETURN, Window::Key::kOK },
{ VK_UP, Window::Key::kUp },
{ VK_DOWN, Window::Key::kDown },
{ VK_LEFT, Window::Key::kLeft },
{ VK_RIGHT, Window::Key::kRight },
{ VK_TAB, Window::Key::kTab },
{ VK_PRIOR, Window::Key::kPageUp },
{ VK_NEXT, Window::Key::kPageDown },
{ VK_HOME, Window::Key::kHome },
{ VK_END, Window::Key::kEnd },
{ VK_DELETE, Window::Key::kDelete },
{ VK_ESCAPE, Window::Key::kEscape },
{ VK_SHIFT, Window::Key::kShift },
{ VK_CONTROL, Window::Key::kCtrl },
{ VK_MENU, Window::Key::kOption },
{ 'A', Window::Key::kA },
{ 'C', Window::Key::kC },
{ 'V', Window::Key::kV },
{ 'X', Window::Key::kX },
{ 'Y', Window::Key::kY },
{ 'Z', Window::Key::kZ },
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gPair); i++) {
if (gPair[i].fVK == vk) {
return gPair[i].fKey;
}
}
return Window::Key::kNONE;
}
static uint32_t get_modifiers(UINT message, WPARAM wParam, LPARAM lParam) {
uint32_t modifiers = 0;
switch (message) {
case WM_UNICHAR:
case WM_CHAR:
if (0 == (lParam & (1 << 30))) {
modifiers |= Window::kFirstPress_ModifierKey;
}
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (0 == (lParam & (1 << 30))) {
modifiers |= Window::kFirstPress_ModifierKey;
}
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_KEYUP:
case WM_SYSKEYUP:
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MOUSEMOVE:
case WM_MOUSEWHEEL:
if (wParam & MK_CONTROL) {
modifiers |= Window::kControl_ModifierKey;
}
if (wParam & MK_SHIFT) {
modifiers |= Window::kShift_ModifierKey;
}
break;
}
return modifiers;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
Window_win* window = (Window_win*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
bool eventHandled = false;
switch (message) {
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
window->onPaint();
EndPaint(hWnd, &ps);
eventHandled = true;
break;
case WM_CLOSE:
PostQuitMessage(0);
eventHandled = true;
break;
case WM_ACTIVATE:
// disable/enable rendering here, depending on wParam != WA_INACTIVE
break;
case WM_SIZE:
window->onResize(LOWORD(lParam), HIWORD(lParam));
eventHandled = true;
break;
case WM_UNICHAR:
eventHandled = window->onChar((SkUnichar)wParam,
get_modifiers(message, wParam, lParam));
break;
case WM_CHAR: {
const uint16_t* c = reinterpret_cast<uint16_t*>(&wParam);
eventHandled = window->onChar(SkUTF16_NextUnichar(&c),
get_modifiers(message, wParam, lParam));
} break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
eventHandled = window->onKey(get_key(wParam), Window::kDown_InputState,
get_modifiers(message, wParam, lParam));
break;
case WM_KEYUP:
case WM_SYSKEYUP:
eventHandled = window->onKey(get_key(wParam), Window::kUp_InputState,
get_modifiers(message, wParam, lParam));
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP: {
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
//if (!gIsFullscreen)
//{
// RECT rc = { 0, 0, 640, 480 };
// AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
// xPos -= rc.left;
// yPos -= rc.top;
//}
Window::InputState istate = ((wParam & MK_LBUTTON) != 0) ? Window::kDown_InputState
: Window::kUp_InputState;
eventHandled = window->onMouse(xPos, yPos, istate,
get_modifiers(message, wParam, lParam));
} break;
case WM_MOUSEMOVE: {
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
//if (!gIsFullscreen)
//{
// RECT rc = { 0, 0, 640, 480 };
// AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
// xPos -= rc.left;
// yPos -= rc.top;
//}
eventHandled = window->onMouse(xPos, yPos, Window::kMove_InputState,
get_modifiers(message, wParam, lParam));
} break;
case WM_MOUSEWHEEL:
eventHandled = window->onMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f,
get_modifiers(message, wParam, lParam));
break;
case WM_TOUCH: {
uint16_t numInputs = LOWORD(wParam);
std::unique_ptr<TOUCHINPUT[]> inputs(new TOUCHINPUT[numInputs]);
if (GetTouchInputInfo((HTOUCHINPUT)lParam, numInputs, inputs.get(),
sizeof(TOUCHINPUT))) {
RECT rect;
GetClientRect(hWnd, &rect);
for (uint16_t i = 0; i < numInputs; ++i) {
TOUCHINPUT ti = inputs[i];
Window::InputState state;
if (ti.dwFlags & TOUCHEVENTF_DOWN) {
state = Window::kDown_InputState;
} else if (ti.dwFlags & TOUCHEVENTF_MOVE) {
state = Window::kMove_InputState;
} else if (ti.dwFlags & TOUCHEVENTF_UP) {
state = Window::kUp_InputState;
} else {
continue;
}
// TOUCHINPUT coordinates are in 100ths of pixels
// Adjust for that, and make them window relative
LONG tx = (ti.x / 100) - rect.left;
LONG ty = (ti.y / 100) - rect.top;
eventHandled = window->onTouch(ti.dwID, state, tx, ty) || eventHandled;
}
}
} break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return eventHandled ? 0 : 1;
}
void Window_win::setTitle(const char* title) {
SetWindowTextA(fHWnd, title);
}
void Window_win::show() {
ShowWindow(fHWnd, SW_SHOW);
}
bool Window_win::attach(BackendType attachType) {
fBackend = attachType;
switch (attachType) {
case kNativeGL_BackendType:
fWindowContext = window_context_factory::NewGLForWin(fHWnd, fRequestedDisplayParams);
break;
#if SK_ANGLE
case kANGLE_BackendType:
fWindowContext = window_context_factory::NewANGLEForWin(fHWnd, fRequestedDisplayParams);
break;
#endif
case kRaster_BackendType:
fWindowContext = window_context_factory::NewRasterForWin(fHWnd,
fRequestedDisplayParams);
break;
#ifdef SK_VULKAN
case kVulkan_BackendType:
fWindowContext = window_context_factory::NewVulkanForWin(fHWnd,
fRequestedDisplayParams);
break;
#endif
}
this->onBackendCreated();
return (SkToBool(fWindowContext));
}
void Window_win::onInval() {
InvalidateRect(fHWnd, nullptr, false);
}
void Window_win::setRequestedDisplayParams(const DisplayParams& params, bool allowReattach) {
// GL on Windows doesn't let us change MSAA after the window is created
if (params.fMSAASampleCount != this->getRequestedDisplayParams().fMSAASampleCount
&& allowReattach) {
// Need to change these early, so attach() creates the window context correctly
fRequestedDisplayParams = params;
delete fWindowContext;
this->closeWindow();
this->init(fHInstance);
this->attach(fBackend);
}
INHERITED::setRequestedDisplayParams(params, allowReattach);
}
} // namespace sk_app
<commit_msg>Fix touch coordinate mapping in Windows<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Window_win.h"
#include <tchar.h>
#include <windows.h>
#include <windowsx.h>
#include "SkUtils.h"
#include "../WindowContext.h"
#include "WindowContextFactory_win.h"
#ifdef SK_VULKAN
#include "../VulkanWindowContext.h"
#endif
namespace sk_app {
static int gWindowX = CW_USEDEFAULT;
static int gWindowY = 0;
static int gWindowWidth = CW_USEDEFAULT;
static int gWindowHeight = 0;
Window* Window::CreateNativeWindow(void* platformData) {
HINSTANCE hInstance = (HINSTANCE)platformData;
Window_win* window = new Window_win();
if (!window->init(hInstance)) {
delete window;
return nullptr;
}
return window;
}
void Window_win::closeWindow() {
RECT r;
if (GetWindowRect(fHWnd, &r)) {
gWindowX = r.left;
gWindowY = r.top;
gWindowWidth = r.right - r.left;
gWindowHeight = r.bottom - r.top;
}
DestroyWindow(fHWnd);
}
Window_win::~Window_win() {
this->closeWindow();
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
bool Window_win::init(HINSTANCE hInstance) {
fHInstance = hInstance ? hInstance : GetModuleHandle(nullptr);
// The main window class name
static const TCHAR gSZWindowClass[] = _T("SkiaApp");
static WNDCLASSEX wcex;
static bool wcexInit = false;
if (!wcexInit) {
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = fHInstance;
wcex.hIcon = LoadIcon(fHInstance, (LPCTSTR)IDI_WINLOGO);
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);;
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = gSZWindowClass;
wcex.hIconSm = LoadIcon(fHInstance, (LPCTSTR)IDI_WINLOGO);;
if (!RegisterClassEx(&wcex)) {
return false;
}
wcexInit = true;
}
/*
if (fullscreen)
{
DEVMODE dmScreenSettings;
// If full screen set the screen to maximum size of the users desktop and 32bit.
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (unsigned long)width;
dmScreenSettings.dmPelsHeight = (unsigned long)height;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Change the display settings to full screen.
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
// Set the position of the window to the top left corner.
posX = posY = 0;
}
*/
// gIsFullscreen = fullscreen;
fHWnd = CreateWindow(gSZWindowClass, nullptr, WS_OVERLAPPEDWINDOW,
gWindowX, gWindowY, gWindowWidth, gWindowHeight,
nullptr, nullptr, fHInstance, nullptr);
if (!fHWnd)
{
return false;
}
SetWindowLongPtr(fHWnd, GWLP_USERDATA, (LONG_PTR)this);
RegisterTouchWindow(fHWnd, 0);
return true;
}
static Window::Key get_key(WPARAM vk) {
static const struct {
WPARAM fVK;
Window::Key fKey;
} gPair[] = {
{ VK_BACK, Window::Key::kBack },
{ VK_CLEAR, Window::Key::kBack },
{ VK_RETURN, Window::Key::kOK },
{ VK_UP, Window::Key::kUp },
{ VK_DOWN, Window::Key::kDown },
{ VK_LEFT, Window::Key::kLeft },
{ VK_RIGHT, Window::Key::kRight },
{ VK_TAB, Window::Key::kTab },
{ VK_PRIOR, Window::Key::kPageUp },
{ VK_NEXT, Window::Key::kPageDown },
{ VK_HOME, Window::Key::kHome },
{ VK_END, Window::Key::kEnd },
{ VK_DELETE, Window::Key::kDelete },
{ VK_ESCAPE, Window::Key::kEscape },
{ VK_SHIFT, Window::Key::kShift },
{ VK_CONTROL, Window::Key::kCtrl },
{ VK_MENU, Window::Key::kOption },
{ 'A', Window::Key::kA },
{ 'C', Window::Key::kC },
{ 'V', Window::Key::kV },
{ 'X', Window::Key::kX },
{ 'Y', Window::Key::kY },
{ 'Z', Window::Key::kZ },
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gPair); i++) {
if (gPair[i].fVK == vk) {
return gPair[i].fKey;
}
}
return Window::Key::kNONE;
}
static uint32_t get_modifiers(UINT message, WPARAM wParam, LPARAM lParam) {
uint32_t modifiers = 0;
switch (message) {
case WM_UNICHAR:
case WM_CHAR:
if (0 == (lParam & (1 << 30))) {
modifiers |= Window::kFirstPress_ModifierKey;
}
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
if (0 == (lParam & (1 << 30))) {
modifiers |= Window::kFirstPress_ModifierKey;
}
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_KEYUP:
case WM_SYSKEYUP:
if (lParam & (1 << 29)) {
modifiers |= Window::kOption_ModifierKey;
}
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MOUSEMOVE:
case WM_MOUSEWHEEL:
if (wParam & MK_CONTROL) {
modifiers |= Window::kControl_ModifierKey;
}
if (wParam & MK_SHIFT) {
modifiers |= Window::kShift_ModifierKey;
}
break;
}
return modifiers;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
Window_win* window = (Window_win*) GetWindowLongPtr(hWnd, GWLP_USERDATA);
bool eventHandled = false;
switch (message) {
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
window->onPaint();
EndPaint(hWnd, &ps);
eventHandled = true;
break;
case WM_CLOSE:
PostQuitMessage(0);
eventHandled = true;
break;
case WM_ACTIVATE:
// disable/enable rendering here, depending on wParam != WA_INACTIVE
break;
case WM_SIZE:
window->onResize(LOWORD(lParam), HIWORD(lParam));
eventHandled = true;
break;
case WM_UNICHAR:
eventHandled = window->onChar((SkUnichar)wParam,
get_modifiers(message, wParam, lParam));
break;
case WM_CHAR: {
const uint16_t* c = reinterpret_cast<uint16_t*>(&wParam);
eventHandled = window->onChar(SkUTF16_NextUnichar(&c),
get_modifiers(message, wParam, lParam));
} break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
eventHandled = window->onKey(get_key(wParam), Window::kDown_InputState,
get_modifiers(message, wParam, lParam));
break;
case WM_KEYUP:
case WM_SYSKEYUP:
eventHandled = window->onKey(get_key(wParam), Window::kUp_InputState,
get_modifiers(message, wParam, lParam));
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP: {
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
//if (!gIsFullscreen)
//{
// RECT rc = { 0, 0, 640, 480 };
// AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
// xPos -= rc.left;
// yPos -= rc.top;
//}
Window::InputState istate = ((wParam & MK_LBUTTON) != 0) ? Window::kDown_InputState
: Window::kUp_InputState;
eventHandled = window->onMouse(xPos, yPos, istate,
get_modifiers(message, wParam, lParam));
} break;
case WM_MOUSEMOVE: {
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
//if (!gIsFullscreen)
//{
// RECT rc = { 0, 0, 640, 480 };
// AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
// xPos -= rc.left;
// yPos -= rc.top;
//}
eventHandled = window->onMouse(xPos, yPos, Window::kMove_InputState,
get_modifiers(message, wParam, lParam));
} break;
case WM_MOUSEWHEEL:
eventHandled = window->onMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f,
get_modifiers(message, wParam, lParam));
break;
case WM_TOUCH: {
uint16_t numInputs = LOWORD(wParam);
std::unique_ptr<TOUCHINPUT[]> inputs(new TOUCHINPUT[numInputs]);
if (GetTouchInputInfo((HTOUCHINPUT)lParam, numInputs, inputs.get(),
sizeof(TOUCHINPUT))) {
POINT topLeft = {0, 0};
ClientToScreen(hWnd, &topLeft);
for (uint16_t i = 0; i < numInputs; ++i) {
TOUCHINPUT ti = inputs[i];
Window::InputState state;
if (ti.dwFlags & TOUCHEVENTF_DOWN) {
state = Window::kDown_InputState;
} else if (ti.dwFlags & TOUCHEVENTF_MOVE) {
state = Window::kMove_InputState;
} else if (ti.dwFlags & TOUCHEVENTF_UP) {
state = Window::kUp_InputState;
} else {
continue;
}
// TOUCHINPUT coordinates are in 100ths of pixels
// Adjust for that, and make them window relative
LONG tx = (ti.x / 100) - topLeft.x;
LONG ty = (ti.y / 100) - topLeft.y;
eventHandled = window->onTouch(ti.dwID, state, tx, ty) || eventHandled;
}
}
} break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return eventHandled ? 0 : 1;
}
void Window_win::setTitle(const char* title) {
SetWindowTextA(fHWnd, title);
}
void Window_win::show() {
ShowWindow(fHWnd, SW_SHOW);
}
bool Window_win::attach(BackendType attachType) {
fBackend = attachType;
switch (attachType) {
case kNativeGL_BackendType:
fWindowContext = window_context_factory::NewGLForWin(fHWnd, fRequestedDisplayParams);
break;
#if SK_ANGLE
case kANGLE_BackendType:
fWindowContext = window_context_factory::NewANGLEForWin(fHWnd, fRequestedDisplayParams);
break;
#endif
case kRaster_BackendType:
fWindowContext = window_context_factory::NewRasterForWin(fHWnd,
fRequestedDisplayParams);
break;
#ifdef SK_VULKAN
case kVulkan_BackendType:
fWindowContext = window_context_factory::NewVulkanForWin(fHWnd,
fRequestedDisplayParams);
break;
#endif
}
this->onBackendCreated();
return (SkToBool(fWindowContext));
}
void Window_win::onInval() {
InvalidateRect(fHWnd, nullptr, false);
}
void Window_win::setRequestedDisplayParams(const DisplayParams& params, bool allowReattach) {
// GL on Windows doesn't let us change MSAA after the window is created
if (params.fMSAASampleCount != this->getRequestedDisplayParams().fMSAASampleCount
&& allowReattach) {
// Need to change these early, so attach() creates the window context correctly
fRequestedDisplayParams = params;
delete fWindowContext;
this->closeWindow();
this->init(fHInstance);
this->attach(fBackend);
}
INHERITED::setRequestedDisplayParams(params, allowReattach);
}
} // namespace sk_app
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tdate.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:09:17 $
*
* 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_tools.hxx"
#if defined WNT
#pragma warning (push,1)
#include <tools/svwin.h>
#pragma warning (pop)
#else
#include <time.h>
#endif
#include <tools/debug.hxx>
#include <tools/date.hxx>
#ifdef MACOSX
extern "C" {
struct tm *localtime_r(const time_t *timep, struct tm *buffer);
}
#endif
// =======================================================================
static USHORT aDaysInMonth[12] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
#define MAX_DAYS 3636532
// =======================================================================
inline BOOL ImpIsLeapYear( USHORT nYear )
{
return (((nYear % 4) == 0) && ((nYear % 100) != 0) || ((nYear % 400) == 0));
}
// -----------------------------------------------------------------------
inline USHORT DaysInMonth( USHORT nMonth, USHORT nYear )
{
if ( nMonth != 2 )
return aDaysInMonth[nMonth-1];
else
{
if ( ((nYear % 4) == 0) && ((nYear % 100) != 0) ||
((nYear % 400) == 0) )
return aDaysInMonth[nMonth-1] + 1;
else
return aDaysInMonth[nMonth-1];
}
}
// -----------------------------------------------------------------------
static long DateToDays( USHORT nDay, USHORT nMonth, USHORT nYear )
{
long nDays;
nDays = ((ULONG)nYear-1) * 365;
nDays += ((nYear-1) / 4) - ((nYear-1) / 100) + ((nYear-1) / 400);
for( USHORT i = 1; i < nMonth; i++ )
nDays += DaysInMonth(i,nYear);
nDays += nDay;
return nDays;
}
// -----------------------------------------------------------------------
static void DaysToDate( long nDays,
USHORT& rDay, USHORT& rMonth, USHORT& rYear )
{
long nTempDays;
long i = 0;
BOOL bCalc;
do
{
nTempDays = (long)nDays;
rYear = (USHORT)((nTempDays / 365) - i);
nTempDays -= ((ULONG)rYear-1) * 365;
nTempDays -= ((rYear-1) / 4) - ((rYear-1) / 100) + ((rYear-1) / 400);
bCalc = FALSE;
if ( nTempDays < 1 )
{
i++;
bCalc = TRUE;
}
else
{
if ( nTempDays > 365 )
{
if ( (nTempDays != 366) || !ImpIsLeapYear( rYear ) )
{
i--;
bCalc = TRUE;
}
}
}
}
while ( bCalc );
rMonth = 1;
while ( (ULONG)nTempDays > DaysInMonth( rMonth, rYear ) )
{
nTempDays -= DaysInMonth( rMonth, rYear );
rMonth++;
}
rDay = (USHORT)nTempDays;
}
// =======================================================================
Date::Date()
{
#if defined WNT
SYSTEMTIME aDateTime;
GetLocalTime( &aDateTime );
// Datum zusammenbauen
nDate = ((ULONG)aDateTime.wDay) +
(((ULONG)aDateTime.wMonth)*100) +
(((ULONG)aDateTime.wYear)*10000);
#else
time_t nTmpTime;
struct tm aTime;
// Zeit ermitteln
nTmpTime = time( 0 );
// Datum zusammenbauen
if ( localtime_r( &nTmpTime, &aTime ) )
{
nDate = ((ULONG)aTime.tm_mday) +
(((ULONG)(aTime.tm_mon+1))*100) +
(((ULONG)(aTime.tm_year+1900))*10000);
}
else
nDate = 1 + 100 + (((ULONG)1900)*10000);
#endif
}
// -----------------------------------------------------------------------
void Date::SetDay( USHORT nNewDay )
{
ULONG nMonth = GetMonth();
ULONG nYear = GetYear();
nDate = ((ULONG)(nNewDay%100)) + (nMonth*100) + (nYear*10000);
}
// -----------------------------------------------------------------------
void Date::SetMonth( USHORT nNewMonth )
{
ULONG nDay = GetDay();
ULONG nYear = GetYear();
nDate = nDay + (((ULONG)(nNewMonth%100))*100) + (nYear*10000);
}
// -----------------------------------------------------------------------
void Date::SetYear( USHORT nNewYear )
{
ULONG nDay = GetDay();
ULONG nMonth = GetMonth();
nDate = nDay + (nMonth*100) + (((ULONG)(nNewYear%10000))*10000);
}
// -----------------------------------------------------------------------
DayOfWeek Date::GetDayOfWeek() const
{
return (DayOfWeek)((ULONG)(DateToDays( GetDay(), GetMonth(), GetYear() )-1) % 7);
}
// -----------------------------------------------------------------------
USHORT Date::GetDayOfYear() const
{
USHORT nDay = GetDay();
for( USHORT i = 1; i < GetMonth(); i++ )
nDay = nDay + ::DaysInMonth( i, GetYear() ); // += yields a warning on MSVC, so don't use it
return nDay;
}
// -----------------------------------------------------------------------
USHORT Date::GetWeekOfYear( DayOfWeek eStartDay,
sal_Int16 nMinimumNumberOfDaysInWeek ) const
{
short nWeek;
short n1WDay = (short)Date( 1, 1, GetYear() ).GetDayOfWeek();
short nDayOfYear = (short)GetDayOfYear();
// Wochentage beginnen bei 0, deshalb einen abziehen
nDayOfYear--;
// StartDay beruecksichtigen
n1WDay = (n1WDay+(7-(short)eStartDay)) % 7;
if (nMinimumNumberOfDaysInWeek < 1 || 7 < nMinimumNumberOfDaysInWeek)
{
DBG_ERRORFILE("Date::GetWeekOfYear: invalid nMinimumNumberOfDaysInWeek");
nMinimumNumberOfDaysInWeek = 4;
}
if ( nMinimumNumberOfDaysInWeek == 1 )
{
nWeek = ((n1WDay+nDayOfYear)/7) + 1;
// 53te-Woche nur dann, wenn wir nicht schon in der ersten
// Woche des neuen Jahres liegen
if ( nWeek == 54 )
nWeek = 1;
else if ( nWeek == 53 )
{
short nDaysInYear = (short)GetDaysInYear();
short nDaysNextYear = (short)Date( 1, 1, GetYear()+1 ).GetDayOfWeek();
nDaysNextYear = (nDaysNextYear+(7-(short)eStartDay)) % 7;
if ( nDayOfYear > (nDaysInYear-nDaysNextYear-1) )
nWeek = 1;
}
}
else if ( nMinimumNumberOfDaysInWeek == 7 )
{
nWeek = ((n1WDay+nDayOfYear)/7);
// Erste Woche eines Jahres entspricht der letzen Woche des
// vorherigen Jahres
if ( nWeek == 0 )
{
Date aLastDatePrevYear( 31, 12, GetYear()-1 );
nWeek = aLastDatePrevYear.GetWeekOfYear( eStartDay, nMinimumNumberOfDaysInWeek );
}
}
else // ( nMinimumNumberOfDaysInWeek == somehing_else, commentary examples for 4 )
{
// x_monday - thursday
if ( n1WDay < nMinimumNumberOfDaysInWeek )
nWeek = 1;
// friday
else if ( n1WDay == nMinimumNumberOfDaysInWeek )
nWeek = 53;
// saturday
else if ( n1WDay == nMinimumNumberOfDaysInWeek + 1 )
{
// Jahr nach Schaltjahr
if ( Date( 1, 1, GetYear()-1 ).IsLeapYear() )
nWeek = 53;
else
nWeek = 52;
}
// sunday
else
nWeek = 52;
if ( (nWeek == 1) || (nDayOfYear + n1WDay > 6) )
{
if ( nWeek == 1 )
nWeek += (nDayOfYear + n1WDay) / 7;
else
nWeek = (nDayOfYear + n1WDay) / 7;
if ( nWeek == 53 )
{
// naechster x_Sonntag == erster x_Sonntag im neuen Jahr
// == noch gleiche Woche
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays += 6 - (GetDayOfWeek()+(7-(short)eStartDay)) % 7;
USHORT nDay;
USHORT nMonth;
USHORT nYear;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nWeek = Date( nDay, nMonth, nYear ).GetWeekOfYear( eStartDay, nMinimumNumberOfDaysInWeek );
}
}
}
return (USHORT)nWeek;
}
// -----------------------------------------------------------------------
USHORT Date::GetDaysInMonth() const
{
return DaysInMonth( GetMonth(), GetYear() );
}
// -----------------------------------------------------------------------
BOOL Date::IsLeapYear() const
{
USHORT nYear = GetYear();
return ImpIsLeapYear( nYear );
}
// -----------------------------------------------------------------------
BOOL Date::IsValid() const
{
USHORT nDay = GetDay();
USHORT nMonth = GetMonth();
USHORT nYear = GetYear();
if ( !nMonth || (nMonth > 12) )
return FALSE;
if ( !nDay || (nDay > DaysInMonth( nMonth, nYear )) )
return FALSE;
else if ( nYear <= 1582 )
{
if ( nYear < 1582 )
return FALSE;
else if ( nMonth < 10 )
return FALSE;
else if ( (nMonth == 10) && (nDay < 15) )
return FALSE;
}
return TRUE;
}
// -----------------------------------------------------------------------
Date& Date::operator +=( long nDays )
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays += nDays;
if ( nTempDays > MAX_DAYS )
nDate = 31 + (12*100) + (((ULONG)9999)*10000);
else if ( nTempDays <= 0 )
nDate = 1 + 100;
else
{
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator -=( long nDays )
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays -= nDays;
if ( nTempDays > MAX_DAYS )
nDate = 31 + (12*100) + (((ULONG)9999)*10000);
else if ( nTempDays <= 0 )
nDate = 1 + 100;
else
{
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator ++()
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
if ( nTempDays < MAX_DAYS )
{
nTempDays++;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator --()
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
if ( nTempDays > 1 )
{
nTempDays--;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
#ifndef MPW33
// -----------------------------------------------------------------------
Date Date::operator ++( int )
{
Date aOldDate = *this;
Date::operator++();
return aOldDate;
}
// -----------------------------------------------------------------------
Date Date::operator --( int )
{
Date aOldDate = *this;
Date::operator--();
return aOldDate;
}
#endif
// -----------------------------------------------------------------------
Date operator +( const Date& rDate, long nDays )
{
Date aDate( rDate );
aDate += nDays;
return aDate;
}
// -----------------------------------------------------------------------
Date operator -( const Date& rDate, long nDays )
{
Date aDate( rDate );
aDate -= nDays;
return aDate;
}
// -----------------------------------------------------------------------
long operator -( const Date& rDate1, const Date& rDate2 )
{
ULONG nTempDays1 = DateToDays( rDate1.GetDay(), rDate1.GetMonth(),
rDate1.GetYear() );
ULONG nTempDays2 = DateToDays( rDate2.GetDay(), rDate2.GetMonth(),
rDate2.GetYear() );
return nTempDays1 - nTempDays2;
}
<commit_msg>INTEGRATION: CWS mingwport06 (1.6.24); FILE MERGED 2007/08/27 14:34:48 vg 1.6.24.1: #i75499# pragma for MSVC<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tdate.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2007-09-06 14:14:17 $
*
* 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_tools.hxx"
#if defined WNT
#ifdef _MSC_VER
#pragma warning (push,1)
#endif
#include <tools/svwin.h>
#ifdef _MSC_VER
#pragma warning (pop)
#endif
#else
#include <time.h>
#endif
#include <tools/debug.hxx>
#include <tools/date.hxx>
#ifdef MACOSX
extern "C" {
struct tm *localtime_r(const time_t *timep, struct tm *buffer);
}
#endif
// =======================================================================
static USHORT aDaysInMonth[12] = { 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
#define MAX_DAYS 3636532
// =======================================================================
inline BOOL ImpIsLeapYear( USHORT nYear )
{
return (((nYear % 4) == 0) && ((nYear % 100) != 0) || ((nYear % 400) == 0));
}
// -----------------------------------------------------------------------
inline USHORT DaysInMonth( USHORT nMonth, USHORT nYear )
{
if ( nMonth != 2 )
return aDaysInMonth[nMonth-1];
else
{
if ( ((nYear % 4) == 0) && ((nYear % 100) != 0) ||
((nYear % 400) == 0) )
return aDaysInMonth[nMonth-1] + 1;
else
return aDaysInMonth[nMonth-1];
}
}
// -----------------------------------------------------------------------
static long DateToDays( USHORT nDay, USHORT nMonth, USHORT nYear )
{
long nDays;
nDays = ((ULONG)nYear-1) * 365;
nDays += ((nYear-1) / 4) - ((nYear-1) / 100) + ((nYear-1) / 400);
for( USHORT i = 1; i < nMonth; i++ )
nDays += DaysInMonth(i,nYear);
nDays += nDay;
return nDays;
}
// -----------------------------------------------------------------------
static void DaysToDate( long nDays,
USHORT& rDay, USHORT& rMonth, USHORT& rYear )
{
long nTempDays;
long i = 0;
BOOL bCalc;
do
{
nTempDays = (long)nDays;
rYear = (USHORT)((nTempDays / 365) - i);
nTempDays -= ((ULONG)rYear-1) * 365;
nTempDays -= ((rYear-1) / 4) - ((rYear-1) / 100) + ((rYear-1) / 400);
bCalc = FALSE;
if ( nTempDays < 1 )
{
i++;
bCalc = TRUE;
}
else
{
if ( nTempDays > 365 )
{
if ( (nTempDays != 366) || !ImpIsLeapYear( rYear ) )
{
i--;
bCalc = TRUE;
}
}
}
}
while ( bCalc );
rMonth = 1;
while ( (ULONG)nTempDays > DaysInMonth( rMonth, rYear ) )
{
nTempDays -= DaysInMonth( rMonth, rYear );
rMonth++;
}
rDay = (USHORT)nTempDays;
}
// =======================================================================
Date::Date()
{
#if defined WNT
SYSTEMTIME aDateTime;
GetLocalTime( &aDateTime );
// Datum zusammenbauen
nDate = ((ULONG)aDateTime.wDay) +
(((ULONG)aDateTime.wMonth)*100) +
(((ULONG)aDateTime.wYear)*10000);
#else
time_t nTmpTime;
struct tm aTime;
// Zeit ermitteln
nTmpTime = time( 0 );
// Datum zusammenbauen
if ( localtime_r( &nTmpTime, &aTime ) )
{
nDate = ((ULONG)aTime.tm_mday) +
(((ULONG)(aTime.tm_mon+1))*100) +
(((ULONG)(aTime.tm_year+1900))*10000);
}
else
nDate = 1 + 100 + (((ULONG)1900)*10000);
#endif
}
// -----------------------------------------------------------------------
void Date::SetDay( USHORT nNewDay )
{
ULONG nMonth = GetMonth();
ULONG nYear = GetYear();
nDate = ((ULONG)(nNewDay%100)) + (nMonth*100) + (nYear*10000);
}
// -----------------------------------------------------------------------
void Date::SetMonth( USHORT nNewMonth )
{
ULONG nDay = GetDay();
ULONG nYear = GetYear();
nDate = nDay + (((ULONG)(nNewMonth%100))*100) + (nYear*10000);
}
// -----------------------------------------------------------------------
void Date::SetYear( USHORT nNewYear )
{
ULONG nDay = GetDay();
ULONG nMonth = GetMonth();
nDate = nDay + (nMonth*100) + (((ULONG)(nNewYear%10000))*10000);
}
// -----------------------------------------------------------------------
DayOfWeek Date::GetDayOfWeek() const
{
return (DayOfWeek)((ULONG)(DateToDays( GetDay(), GetMonth(), GetYear() )-1) % 7);
}
// -----------------------------------------------------------------------
USHORT Date::GetDayOfYear() const
{
USHORT nDay = GetDay();
for( USHORT i = 1; i < GetMonth(); i++ )
nDay = nDay + ::DaysInMonth( i, GetYear() ); // += yields a warning on MSVC, so don't use it
return nDay;
}
// -----------------------------------------------------------------------
USHORT Date::GetWeekOfYear( DayOfWeek eStartDay,
sal_Int16 nMinimumNumberOfDaysInWeek ) const
{
short nWeek;
short n1WDay = (short)Date( 1, 1, GetYear() ).GetDayOfWeek();
short nDayOfYear = (short)GetDayOfYear();
// Wochentage beginnen bei 0, deshalb einen abziehen
nDayOfYear--;
// StartDay beruecksichtigen
n1WDay = (n1WDay+(7-(short)eStartDay)) % 7;
if (nMinimumNumberOfDaysInWeek < 1 || 7 < nMinimumNumberOfDaysInWeek)
{
DBG_ERRORFILE("Date::GetWeekOfYear: invalid nMinimumNumberOfDaysInWeek");
nMinimumNumberOfDaysInWeek = 4;
}
if ( nMinimumNumberOfDaysInWeek == 1 )
{
nWeek = ((n1WDay+nDayOfYear)/7) + 1;
// 53te-Woche nur dann, wenn wir nicht schon in der ersten
// Woche des neuen Jahres liegen
if ( nWeek == 54 )
nWeek = 1;
else if ( nWeek == 53 )
{
short nDaysInYear = (short)GetDaysInYear();
short nDaysNextYear = (short)Date( 1, 1, GetYear()+1 ).GetDayOfWeek();
nDaysNextYear = (nDaysNextYear+(7-(short)eStartDay)) % 7;
if ( nDayOfYear > (nDaysInYear-nDaysNextYear-1) )
nWeek = 1;
}
}
else if ( nMinimumNumberOfDaysInWeek == 7 )
{
nWeek = ((n1WDay+nDayOfYear)/7);
// Erste Woche eines Jahres entspricht der letzen Woche des
// vorherigen Jahres
if ( nWeek == 0 )
{
Date aLastDatePrevYear( 31, 12, GetYear()-1 );
nWeek = aLastDatePrevYear.GetWeekOfYear( eStartDay, nMinimumNumberOfDaysInWeek );
}
}
else // ( nMinimumNumberOfDaysInWeek == somehing_else, commentary examples for 4 )
{
// x_monday - thursday
if ( n1WDay < nMinimumNumberOfDaysInWeek )
nWeek = 1;
// friday
else if ( n1WDay == nMinimumNumberOfDaysInWeek )
nWeek = 53;
// saturday
else if ( n1WDay == nMinimumNumberOfDaysInWeek + 1 )
{
// Jahr nach Schaltjahr
if ( Date( 1, 1, GetYear()-1 ).IsLeapYear() )
nWeek = 53;
else
nWeek = 52;
}
// sunday
else
nWeek = 52;
if ( (nWeek == 1) || (nDayOfYear + n1WDay > 6) )
{
if ( nWeek == 1 )
nWeek += (nDayOfYear + n1WDay) / 7;
else
nWeek = (nDayOfYear + n1WDay) / 7;
if ( nWeek == 53 )
{
// naechster x_Sonntag == erster x_Sonntag im neuen Jahr
// == noch gleiche Woche
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays += 6 - (GetDayOfWeek()+(7-(short)eStartDay)) % 7;
USHORT nDay;
USHORT nMonth;
USHORT nYear;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nWeek = Date( nDay, nMonth, nYear ).GetWeekOfYear( eStartDay, nMinimumNumberOfDaysInWeek );
}
}
}
return (USHORT)nWeek;
}
// -----------------------------------------------------------------------
USHORT Date::GetDaysInMonth() const
{
return DaysInMonth( GetMonth(), GetYear() );
}
// -----------------------------------------------------------------------
BOOL Date::IsLeapYear() const
{
USHORT nYear = GetYear();
return ImpIsLeapYear( nYear );
}
// -----------------------------------------------------------------------
BOOL Date::IsValid() const
{
USHORT nDay = GetDay();
USHORT nMonth = GetMonth();
USHORT nYear = GetYear();
if ( !nMonth || (nMonth > 12) )
return FALSE;
if ( !nDay || (nDay > DaysInMonth( nMonth, nYear )) )
return FALSE;
else if ( nYear <= 1582 )
{
if ( nYear < 1582 )
return FALSE;
else if ( nMonth < 10 )
return FALSE;
else if ( (nMonth == 10) && (nDay < 15) )
return FALSE;
}
return TRUE;
}
// -----------------------------------------------------------------------
Date& Date::operator +=( long nDays )
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays += nDays;
if ( nTempDays > MAX_DAYS )
nDate = 31 + (12*100) + (((ULONG)9999)*10000);
else if ( nTempDays <= 0 )
nDate = 1 + 100;
else
{
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator -=( long nDays )
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
nTempDays -= nDays;
if ( nTempDays > MAX_DAYS )
nDate = 31 + (12*100) + (((ULONG)9999)*10000);
else if ( nTempDays <= 0 )
nDate = 1 + 100;
else
{
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator ++()
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
if ( nTempDays < MAX_DAYS )
{
nTempDays++;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
// -----------------------------------------------------------------------
Date& Date::operator --()
{
USHORT nDay;
USHORT nMonth;
USHORT nYear;
long nTempDays = DateToDays( GetDay(), GetMonth(), GetYear() );
if ( nTempDays > 1 )
{
nTempDays--;
DaysToDate( nTempDays, nDay, nMonth, nYear );
nDate = ((ULONG)nDay) + (((ULONG)nMonth)*100) + (((ULONG)nYear)*10000);
}
return *this;
}
#ifndef MPW33
// -----------------------------------------------------------------------
Date Date::operator ++( int )
{
Date aOldDate = *this;
Date::operator++();
return aOldDate;
}
// -----------------------------------------------------------------------
Date Date::operator --( int )
{
Date aOldDate = *this;
Date::operator--();
return aOldDate;
}
#endif
// -----------------------------------------------------------------------
Date operator +( const Date& rDate, long nDays )
{
Date aDate( rDate );
aDate += nDays;
return aDate;
}
// -----------------------------------------------------------------------
Date operator -( const Date& rDate, long nDays )
{
Date aDate( rDate );
aDate -= nDays;
return aDate;
}
// -----------------------------------------------------------------------
long operator -( const Date& rDate1, const Date& rDate2 )
{
ULONG nTempDays1 = DateToDays( rDate1.GetDay(), rDate1.GetMonth(),
rDate1.GetYear() );
ULONG nTempDays2 = DateToDays( rDate2.GetDay(), rDate2.GetMonth(),
rDate2.GetYear() );
return nTempDays1 - nTempDays2;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id: transform_point_cloud.cpp 1032 2011-05-18 22:43:27Z mdixon $
*
*/
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/registration/transforms.h>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat w,x,y,z = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" seconds : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT>
void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <>
void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <>
void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT>
void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromROSMsg (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toROSMsg (cloud, output);
}
void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name == "rgb")
has_rgb = true;
if (input.fields[i].name == "normals")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
double dx, dy, dz;
std::vector<double> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const double & x = values[0];
const double & y = values[1];
const double & z = values[2];
const double & w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const double & ax = values[0];
const double & ay = values[1];
const double & az = values[2];
const double & theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = sqrt (values.size ());
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
sensor_msgs::PointCloud2 output;
compute (cloud, output, tform);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<commit_msg>There is no integer sqrt, hard coding possible values.<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
* $Id: transform_point_cloud.cpp 1032 2011-05-18 22:43:27Z mdixon $
*
*/
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/ros/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#include <pcl/registration/transforms.h>
#include <cmath>
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
void
printHelp (int argc, char **argv)
{
print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -trans dx,dy,dz = the translation (default: ");
print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n");
print_info (" -quat w,x,y,z = rotation as quaternion\n");
print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n");
print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n");
print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n");
print_info (" Note: If a rotation is not specified, it will default to no rotation.\n");
print_info (" If redundant or conflicting transforms are specified, then:\n");
print_info (" -axisangle will override -quat\n");
print_info (" -matrix (3x3) will take override -axisangle and -quat\n");
print_info (" -matrix (4x4) will take override all other arguments\n");
}
void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1)
{
print_info ("[done, "); print_value ("%g", t); print_info (" seconds : ");
print_value ("%d", w*h); print_info (" points]\n");
}
bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
TicToc tt;
print_highlight ("Loading "); print_value ("%s ", filename.c_str ());
tt.tic ();
if (loadPCDFile (filename, cloud) < 0)
return (false);
printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height);
print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
return (true);
}
template <typename PointT>
void
transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output,
Eigen::Matrix4f &tform)
{
transformPointCloud (input, output, tform);
}
template <>
void
transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <>
void
transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input,
PointCloud<PointXYZRGBNormal> & output,
Eigen::Matrix4f &tform)
{
transformPointCloudWithNormals (input, output, tform);
}
template <typename PointT>
void
transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
PointCloud<PointT> cloud;
fromROSMsg (input, cloud);
transformPointCloudHelper (cloud, cloud, tform);
toROSMsg (cloud, output);
}
void
transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
// Check for 'rgb' and 'normals' fields
bool has_rgb = false;
bool has_normals = false;
for (size_t i = 0; i < input.fields.size (); ++i)
{
if (input.fields[i].name == "rgb")
has_rgb = true;
if (input.fields[i].name == "normals")
has_normals = true;
}
// Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal
if (!has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZ> (input, output, tform);
else if (has_rgb && !has_normals)
transformPointCloud2AsType<PointXYZRGB> (input, output, tform);
else if (!has_rgb && has_normals)
transformPointCloud2AsType<PointNormal> (input, output, tform);
else // (has_rgb && has_normals)
transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform);
}
void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
Eigen::Matrix4f &tform)
{
TicToc tt;
tt.tic ();
print_highlight ("Transforming ");
transformPointCloud2 (*input, output, tform);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
TicToc tt;
tt.tic ();
print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
pcl::io::savePCDFile (filename, output);
printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height);
}
/* ---[ */
int
main (int argc, char** argv)
{
print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]);
if (argc < 3)
{
printHelp (argc, argv);
return (-1);
}
// Parse the command line arguments for .pcd files
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () != 2)
{
print_error ("Need one input PCD file and one output PCD file to continue.\n");
return (-1);
}
// Initialize the transformation matrix
Eigen::Matrix4f tform;
tform.setIdentity ();
// Command line parsing
double dx, dy, dz;
std::vector<double> values;
if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1)
{
tform (0, 3) = dx;
tform (1, 3) = dy;
tform (2, 3) = dz;
}
if (parse_x_arguments (argc, argv, "-quat", values) > -1)
{
if (values.size () == 4)
{
const double & x = values[0];
const double & y = values[1];
const double & z = values[2];
const double & w = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n");
}
}
if (parse_x_arguments (argc, argv, "-axisangle", values) > -1)
{
if (values.size () == 4)
{
const double & ax = values[0];
const double & ay = values[1];
const double & az = values[2];
const double & theta = values[3];
tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az)));
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n");
}
}
if (parse_x_arguments (argc, argv, "-matrix", values) > -1)
{
if (values.size () == 9 || values.size () == 16)
{
int n = values.size () == 9 ? 3 : 4;
for (int r = 0; r < n; ++r)
for (int c = 0; c < n; ++c)
tform (r, c) = values[n*r+c];
}
else
{
print_error ("Wrong number of values given (%zu): ", values.size ());
print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n");
}
}
// Load the first file
sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
if (!loadCloud (argv[p_file_indices[0]], *cloud))
return (-1);
// Apply the transform
sensor_msgs::PointCloud2 output;
compute (cloud, output, tform);
// Save into the second file
saveCloud (argv[p_file_indices[1]], output);
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <mapnik/text/icu_shaper.hpp>
#include <mapnik/text/harfbuzz_shaper.hpp>
#include <mapnik/text/font_library.hpp>
#include <mapnik/unicode.hpp>
namespace {
void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm,
std::vector<std::tuple<unsigned, unsigned>> expected,
char const* str, bool debug = false)
{
mapnik::transcoder tr("utf8");
std::map<unsigned,double> width_map;
mapnik::text_itemizer itemizer;
auto props = std::make_unique<mapnik::detail::evaluated_format_properties>();
props->fontset = fontset;
props->text_size = 32;
double scale_factor = 1;
auto ustr = tr.transcode(str);
auto length = ustr.length();
itemizer.add_text(ustr, props);
mapnik::text_line line(0, length);
mapnik::harfbuzz_shaper::shape_text(line, itemizer,
width_map,
fm,
scale_factor);
std::size_t index = 0;
for (auto const& g : line)
{
if (debug)
{
if (index++ > 0) std::cerr << ",";
std::cerr << "{" << g.glyph_index << ", " << g.char_index
//<< ", " << g.face->family_name() << ":" << g.face->style_name()
<< "}";
}
else
{
unsigned glyph_index, char_index;
CHECK(index < expected.size());
std::tie(glyph_index, char_index) = expected[index++];
REQUIRE(glyph_index == g.glyph_index);
REQUIRE(char_index == g.char_index);
}
}
}
}
TEST_CASE("shaping")
{
mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc");
mapnik::freetype_engine::register_fonts("test/data/fonts/Noto");
mapnik::font_set fontset("fontset");
for (auto const& name : mapnik::freetype_engine::face_names())
{
fontset.add_face_name(name);
}
mapnik::font_library fl;
mapnik::freetype_engine::font_file_mapping_type font_file_mapping;
mapnik::freetype_engine::font_memory_cache_type font_memory_cache;
mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache);
{
auto expected =
{std::tuple<unsigned, unsigned>(0, 0), {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}};
// with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^
//std::vector<std::pair<unsigned, unsigned>> expected =
// {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}};
// expected results if "NotoSansTibetan-Regular.ttf is registered^^
test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (abc)");
}
{
auto expected =
{std::tuple<unsigned, unsigned>(0, 0), {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}};
test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (普兰镇)");
}
{
auto expected =
{std::tuple<unsigned, unsigned>(68, 0), {69, 1}, {70, 2}, {3, 3}, {11, 4}, {0, 5}, {0, 6}, {0, 7}, {12, 8}};
test_shaping(fontset, fm, expected, u8"abc (普兰镇)");
}
{
auto expected =
{std::tuple<unsigned, unsigned>(68, 0), {69, 1}, {70, 2}, {3, 3}, {11, 4}, {68, 5}, {69, 6}, {70, 7}, {12, 8}};
test_shaping(fontset, fm, expected, "abc (abc)");
}
{
// "ⵃⴰⵢ ⵚⵉⵏⴰⵄⵉ الحي الصناعي"
auto expected =
{std::tuple<unsigned, unsigned>(0, 0), {0, 1}, {0, 2}, {3, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7},
{0, 8}, {0, 9}, {3, 10}, {509, 22}, {481, 21}, {438, 20}, {503, 19},
{470, 18}, {496, 17}, {43, 16}, {3, 15}, {509, 14}, {454, 13}, {496, 12}, {43, 11}};
test_shaping(fontset, fm, expected, u8"ⵃⴰⵢ ⵚⵉⵏⴰⵄⵉ الحي الصناعي");
}
}
<commit_msg>Revert "one more time."<commit_after>#include "catch.hpp"
#include <mapnik/text/icu_shaper.hpp>
#include <mapnik/text/harfbuzz_shaper.hpp>
#include <mapnik/text/font_library.hpp>
#include <mapnik/unicode.hpp>
namespace {
void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm,
std::vector<std::pair<unsigned, unsigned>> const& expected, char const* str, bool debug = false)
{
mapnik::transcoder tr("utf8");
std::map<unsigned,double> width_map;
mapnik::text_itemizer itemizer;
auto props = std::make_unique<mapnik::detail::evaluated_format_properties>();
props->fontset = fontset;
props->text_size = 32;
double scale_factor = 1;
auto ustr = tr.transcode(str);
auto length = ustr.length();
itemizer.add_text(ustr, props);
mapnik::text_line line(0, length);
mapnik::harfbuzz_shaper::shape_text(line, itemizer,
width_map,
fm,
scale_factor);
std::size_t index = 0;
for (auto const& g : line)
{
if (debug)
{
if (index++ > 0) std::cerr << ",";
std::cerr << "{" << g.glyph_index << ", " << g.char_index
//<< ", " << g.face->family_name() << ":" << g.face->style_name()
<< "}";
}
else
{
unsigned glyph_index, char_index;
CHECK(index < expected.size());
std::tie(glyph_index, char_index) = expected[index++];
REQUIRE(glyph_index == g.glyph_index);
REQUIRE(char_index == g.char_index);
}
}
}
}
TEST_CASE("shaping")
{
mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc");
mapnik::freetype_engine::register_fonts("test/data/fonts/Noto");
mapnik::font_set fontset("fontset");
for (auto const& name : mapnik::freetype_engine::face_names())
{
fontset.add_face_name(name);
}
mapnik::font_library fl;
mapnik::freetype_engine::font_file_mapping_type font_file_mapping;
mapnik::freetype_engine::font_memory_cache_type font_memory_cache;
mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache);
{
std::vector<std::pair<unsigned, unsigned>> expected =
{{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}};
// with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^
//std::vector<std::pair<unsigned, unsigned>> expected =
// {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}};
// expected results if "NotoSansTibetan-Regular.ttf is registered^^
test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (abc)");
}
{
std::vector<std::pair<unsigned, unsigned>> expected =
{{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}};
test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (普兰镇)");
}
{
std::vector<std::pair<unsigned, unsigned>> expected =
{{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {0, 5}, {0, 6}, {0, 7}, {12, 8}};
test_shaping(fontset, fm, expected, u8"abc (普兰镇)");
}
{
std::vector<std::pair<unsigned, unsigned>> expected =
{{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {68, 5}, {69, 6}, {70, 7}, {12, 8}};
test_shaping(fontset, fm, expected, "abc (abc)");
}
{
// "ⵃⴰⵢ ⵚⵉⵏⴰⵄⵉ الحي الصناعي"
std::vector<std::pair<unsigned, unsigned>> expected =
{{0, 0}, {0, 1}, {0, 2}, {3, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7},
{0, 8}, {0, 9}, {3, 10}, {509, 22}, {481, 21}, {438, 20}, {503, 19},
{470, 18}, {496, 17}, {43, 16}, {3, 15}, {509, 14}, {454, 13}, {496, 12}, {43, 11}};
test_shaping(fontset, fm, expected, u8"ⵃⴰⵢ ⵚⵉⵏⴰⵄⵉ الحي الصناعي");
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "v_array.h"
struct interact
{ unsigned char n1, n2; //namespaces to interact
features feat_store;
vw *all;
float n1_feat_sq;
float total_sum_feat_sq;
size_t num_features;
};
bool contains_valid_namespaces(features& f_src1, features& f_src2, interact& in)
{ // first feature must be 1 so we're sure that the anchor feature is present
if (f_src1.size() == 0 || f_src2.size() == 0)
return false;
if (f_src1.values[0] != 1)
{ cerr << "Namespace '" << (char)in.n1 << "' misses anchor feature with value 1";
return false;
}
if (f_src2.values[0] != 1)
{ cerr << "Namespace '" << (char)in.n2 << "' misses anchor feature with value 1";
return false;
}
return true;
}
void multiply(features& f_dest, features& f_src2, interact& in)
{ f_dest.erase();
features& f_src1 = in.feat_store;
vw* all = in.all;
uint64_t weight_mask = all->reg.weight_mask;
uint64_t base_id1 = f_src1.indicies[0] & weight_mask;
uint64_t base_id2 = f_src2.indicies[0] & weight_mask;
f_dest.push_back(f_src1.values[0]*f_src2.values[0], f_src1.indicies[0]);
uint64_t prev_id1 = 0;
uint64_t prev_id2 = 0;
for(size_t i1 = 1, i2 = 1; i1 < f_src1.size() && i2 < f_src2.size();)
{ // calculating the relative offset from the namespace offset used to match features
uint64_t cur_id1 = (uint64_t)(((f_src1.indicies[i1] & weight_mask) - base_id1) & weight_mask);
uint64_t cur_id2 = (uint64_t)(((f_src2.indicies[i2] & weight_mask) - base_id2) & weight_mask);
// checking for sorting requirement
if (cur_id1 < prev_id1)
{ cout << "interact features are out of order: " << cur_id1 << " > " << prev_id1 << ". Skipping features." << endl;
return;
}
if (cur_id2 < prev_id2)
{ cout << "interact features are out of order: " << cur_id2 << " > " << prev_id2 << ". Skipping features." << endl;
return;
}
if(cur_id1 == cur_id2)
{ f_dest.push_back(f_src1.values[i1]*f_src2.values[i2], f_src1.indicies[i1]);
i1++;
i2++;
}
else if (cur_id1 < cur_id2)
i1++;
else
i2++;
}
}
template <bool is_learn, bool print_all>
void predict_or_learn(interact& in, LEARNER::base_learner& base, example& ec)
{ features& f1 = ec.feature_space[in.n1];
features& f2 = ec.feature_space[in.n2];
if (!contains_valid_namespaces(f1, f2, in))
{ if (is_learn)
base.learn(ec);
else
base.predict(ec);
return;
}
in.num_features = ec.num_features;
in.total_sum_feat_sq = ec.total_sum_feat_sq;
ec.total_sum_feat_sq -= f1.sum_feat_sq;
ec.total_sum_feat_sq -= f2.sum_feat_sq;
ec.num_features -= f1.size();
ec.num_features -= f2.size();
copy(in.feat_store, f1);
multiply(f1, f2, in);
ec.total_sum_feat_sq += f1.sum_feat_sq;
ec.num_features += f1.size();
/*for(uint64_t i = 0;i < f1.size();i++)
cout<<f1[i].weight_index<<":"<<f1[i].x<<" ";
cout<<endl;*/
// remove 2nd namespace
int n2_i = -1;
for (size_t i = 0; i < ec.indices.size(); i++)
{ if (ec.indices[i] == in.n2)
{ n2_i = (int)i;
memmove(&ec.indices[n2_i], &ec.indices[n2_i + 1], sizeof(unsigned char) * (ec.indices.size() - n2_i - 1));
ec.indices.decr();
break;
}
}
base.predict(ec);
if (is_learn)
base.learn(ec);
// re-insert namespace into the right position
ec.indices.incr();
memmove(&ec.indices[n2_i + 1], &ec.indices[n2_i], sizeof(unsigned char) * (ec.indices.size() - n2_i - 1));
ec.indices[n2_i] = in.n2;
copy(f1,in.feat_store);
ec.total_sum_feat_sq = in.total_sum_feat_sq;
ec.num_features = in.num_features;
}
void finish(interact& in) { in.feat_store.delete_v(); }
LEARNER::base_learner* interact_setup(vw& all)
{ if(missing_option<string, true>(all, "interact", "Put weights on feature products from namespaces <n1> and <n2>"))
return nullptr;
string s = all.vm["interact"].as<string>();
if(s.length() != 2)
{ cerr<<"Need two namespace arguments to interact!! EXITING\n";
return nullptr;
}
interact& data = calloc_or_throw<interact>();
data.n1 = (unsigned char) s[0];
data.n2 = (unsigned char) s[1];
if (!all.quiet)
cerr <<"Interacting namespaces "<<data.n1<<" and "<<data.n2<<endl;
data.all = &all;
LEARNER::learner<interact>* l;
l = &LEARNER::init_learner(&data, setup_base(all), predict_or_learn<true, true>, predict_or_learn<false, true>, 1);
l->set_finish(finish);
return make_base(*l);
}
<commit_msg>better error report in interact.cc<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "v_array.h"
struct interact
{ unsigned char n1, n2; //namespaces to interact
features feat_store;
vw *all;
float n1_feat_sq;
float total_sum_feat_sq;
size_t num_features;
};
bool contains_valid_namespaces(features& f_src1, features& f_src2, interact& in)
{ // first feature must be 1 so we're sure that the anchor feature is present
if (f_src1.size() == 0 || f_src2.size() == 0)
return false;
if (f_src1.values[0] != 1)
{ cerr << "Namespace '" << (char)in.n1 << "' misses anchor feature with value 1";
return false;
}
if (f_src2.values[0] != 1)
{ cerr << "Namespace '" << (char)in.n2 << "' misses anchor feature with value 1";
return false;
}
return true;
}
void multiply(features& f_dest, features& f_src2, interact& in)
{ f_dest.erase();
features& f_src1 = in.feat_store;
vw* all = in.all;
uint64_t weight_mask = all->reg.weight_mask;
uint64_t base_id1 = f_src1.indicies[0] & weight_mask;
uint64_t base_id2 = f_src2.indicies[0] & weight_mask;
f_dest.push_back(f_src1.values[0]*f_src2.values[0], f_src1.indicies[0]);
uint64_t prev_id1 = 0;
uint64_t prev_id2 = 0;
for(size_t i1 = 1, i2 = 1; i1 < f_src1.size() && i2 < f_src2.size();)
{ // calculating the relative offset from the namespace offset used to match features
uint64_t cur_id1 = (uint64_t)(((f_src1.indicies[i1] & weight_mask) - base_id1) & weight_mask);
uint64_t cur_id2 = (uint64_t)(((f_src2.indicies[i2] & weight_mask) - base_id2) & weight_mask);
// checking for sorting requirement
if (cur_id1 < prev_id1)
{ cout << "interact features are out of order: " << cur_id1 << " > " << prev_id1 << ". Skipping features." << endl;
return;
}
if (cur_id2 < prev_id2)
{ cout << "interact features are out of order: " << cur_id2 << " > " << prev_id2 << ". Skipping features." << endl;
return;
}
if(cur_id1 == cur_id2)
{ f_dest.push_back(f_src1.values[i1]*f_src2.values[i2], f_src1.indicies[i1]);
i1++;
i2++;
}
else if (cur_id1 < cur_id2)
i1++;
else
i2++;
}
}
template <bool is_learn, bool print_all>
void predict_or_learn(interact& in, LEARNER::base_learner& base, example& ec)
{ features& f1 = ec.feature_space[in.n1];
features& f2 = ec.feature_space[in.n2];
if (!contains_valid_namespaces(f1, f2, in))
{ if (is_learn)
base.learn(ec);
else
base.predict(ec);
return;
}
in.num_features = ec.num_features;
in.total_sum_feat_sq = ec.total_sum_feat_sq;
ec.total_sum_feat_sq -= f1.sum_feat_sq;
ec.total_sum_feat_sq -= f2.sum_feat_sq;
ec.num_features -= f1.size();
ec.num_features -= f2.size();
copy(in.feat_store, f1);
multiply(f1, f2, in);
ec.total_sum_feat_sq += f1.sum_feat_sq;
ec.num_features += f1.size();
/*for(uint64_t i = 0;i < f1.size();i++)
cout<<f1[i].weight_index<<":"<<f1[i].x<<" ";
cout<<endl;*/
// remove 2nd namespace
int n2_i = -1;
for (size_t i = 0; i < ec.indices.size(); i++)
{ if (ec.indices[i] == in.n2)
{ n2_i = (int)i;
memmove(&ec.indices[n2_i], &ec.indices[n2_i + 1], sizeof(unsigned char) * (ec.indices.size() - n2_i - 1));
ec.indices.decr();
break;
}
}
base.predict(ec);
if (is_learn)
base.learn(ec);
// re-insert namespace into the right position
ec.indices.incr();
memmove(&ec.indices[n2_i + 1], &ec.indices[n2_i], sizeof(unsigned char) * (ec.indices.size() - n2_i - 1));
ec.indices[n2_i] = in.n2;
copy(f1,in.feat_store);
ec.total_sum_feat_sq = in.total_sum_feat_sq;
ec.num_features = in.num_features;
}
void finish(interact& in) { in.feat_store.delete_v(); }
LEARNER::base_learner* interact_setup(vw& all)
{ if(missing_option<string, true>(all, "interact", "Put weights on feature products from namespaces <n1> and <n2>"))
return nullptr;
string s = all.vm["interact"].as<string>();
if(s.length() != 2)
{ cerr<<"Need two namespace arguments to interact: " << s << " won't do EXITING\n";
return nullptr;
}
interact& data = calloc_or_throw<interact>();
data.n1 = (unsigned char) s[0];
data.n2 = (unsigned char) s[1];
if (!all.quiet)
cerr <<"Interacting namespaces "<<data.n1<<" and "<<data.n2<<endl;
data.all = &all;
LEARNER::learner<interact>* l;
l = &LEARNER::init_learner(&data, setup_base(all), predict_or_learn<true, true>, predict_or_learn<false, true>, 1);
l->set_finish(finish);
return make_base(*l);
}
<|endoftext|>
|
<commit_before>/******************************************
Author: Tiago Britto Lobão
tiago.blobao@gmail.com
Year: 2017
Version: 0.1
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
This is a FREE SOFTWARE. You can change
it or distribute. If you notice any issues
or suggestions, contact me
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
#ifdef ARDUINO_NodeMCU_32S //For Esp32
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
#ifndef ARDUINO_NodeMCU_32S //For Arduino & ESP8622
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
cSerial->flush();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
cSerial->flush();
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Expoent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::CC(){
this->instruct(21);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100);
cSerial->end();
cSerial->begin(value);
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return 0;
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
<commit_msg>Add comments setBaudRate Method<commit_after>/******************************************
Author: Tiago Britto Lobão
tiago.blobao@gmail.com
Year: 2017
Version: 0.1
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
This is a FREE SOFTWARE. You can change
it or distribute. If you notice any issues
or suggestions, contact me
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
#ifdef ARDUINO_NodeMCU_32S //For Esp32
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
#ifndef ARDUINO_NodeMCU_32S //For Arduino & ESP8622
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
cSerial->flush();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
cSerial->flush();
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Expoent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::CC(){
this->instruct(21);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
//Calculate the correct binary value
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100); //To avoid bugs from ESP32
//Reset Serial communication from controller
cSerial->end();
cSerial->begin(value);
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return 0;
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
<|endoftext|>
|
<commit_before>#include "compiler/build_tables/build_parse_table.h"
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include "compiler/parse_table.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/remove_duplicate_states.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/lexical_grammar.h"
#include "compiler/syntax_grammar.h"
#include "compiler/rules/symbol.h"
#include "compiler/rules/built_in_symbols.h"
#include "compiler/build_tables/recovery_tokens.h"
namespace tree_sitter {
namespace build_tables {
using std::find;
using std::pair;
using std::vector;
using std::set;
using std::map;
using std::string;
using std::to_string;
using std::unordered_map;
using std::make_shared;
using rules::Symbol;
class ParseTableBuilder {
const SyntaxGrammar grammar;
const LexicalGrammar lexical_grammar;
ParseConflictManager conflict_manager;
unordered_map<Symbol, ParseItemSet> recovery_states;
unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;
vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;
ParseTable parse_table;
std::set<string> conflicts;
ParseItemSet null_item_set;
std::set<const Production *> fragile_productions;
bool allow_any_conflict;
public:
ParseTableBuilder(const SyntaxGrammar &grammar,
const LexicalGrammar &lex_grammar)
: grammar(grammar),
lexical_grammar(lex_grammar),
allow_any_conflict(false) {}
pair<ParseTable, CompileError> build() {
Symbol start_symbol = Symbol(0, grammar.variables.empty());
Production start_production({
ProductionStep(start_symbol, 0, rules::AssociativityNone),
});
add_parse_state(ParseItemSet({
{
ParseItem(rules::START(), start_production, 0),
LookaheadSet({ rules::END_OF_INPUT() }),
},
}));
CompileError error = process_part_state_queue();
if (error.type != TSCompileErrorTypeNone) {
return { parse_table, error };
}
add_out_of_context_parse_states();
allow_any_conflict = true;
process_part_state_queue();
allow_any_conflict = false;
for (ParseStateId state = 0; state < parse_table.states.size(); state++) {
add_shift_extra_actions(state);
add_reduce_extra_actions(state);
}
mark_fragile_actions();
remove_duplicate_parse_states();
return { parse_table, CompileError::none() };
}
private:
CompileError process_part_state_queue() {
while (!item_sets_to_process.empty()) {
auto pair = item_sets_to_process.back();
ParseItemSet item_set = item_set_closure(pair.first, grammar);
ParseStateId state_id = pair.second;
item_sets_to_process.pop_back();
add_reduce_actions(item_set, state_id);
add_shift_actions(item_set, state_id);
if (!conflicts.empty()) {
return CompileError(TSCompileErrorTypeParseConflict,
"Unresolved conflict.\n\n" + *conflicts.begin());
}
}
return CompileError::none();
}
void add_out_of_context_parse_states() {
for (const Symbol &symbol : recovery_tokens(lexical_grammar)) {
add_out_of_context_parse_state(symbol);
}
for (size_t i = 0; i < grammar.variables.size(); i++) {
Symbol symbol(i, false);
add_out_of_context_parse_state(symbol);
}
parse_table.error_state.actions[rules::END_OF_INPUT()].push_back(
ParseAction::Shift(0, PrecedenceRange()));
}
void add_out_of_context_parse_state(const rules::Symbol &symbol) {
const ParseItemSet &item_set = recovery_states[symbol];
if (!item_set.entries.empty()) {
ParseStateId state = add_parse_state(item_set);
parse_table.error_state.actions[symbol].push_back(
ParseAction::Shift(state, PrecedenceRange()));
}
}
ParseStateId add_parse_state(const ParseItemSet &item_set) {
auto pair = parse_state_ids.find(item_set);
if (pair == parse_state_ids.end()) {
ParseStateId state_id = parse_table.add_state();
parse_state_ids[item_set] = state_id;
item_sets_to_process.push_back({ item_set, state_id });
return state_id;
} else {
return pair->second;
}
}
void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &transition : item_set.transitions()) {
const Symbol &symbol = transition.first;
const ParseItemSet &next_item_set = transition.second.first;
const PrecedenceRange &precedence = transition.second.second;
ParseAction *new_action = add_action(
state_id, symbol, ParseAction::Shift(0, precedence), item_set);
if (!allow_any_conflict)
recovery_states[symbol].add(next_item_set);
if (new_action)
new_action->state_index = add_parse_state(next_item_set);
}
}
void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const auto &lookahead_symbols = pair.second;
ParseItem::CompletionStatus status = item.completion_status();
if (status.is_done) {
ParseAction action =
(item.lhs() == rules::START())
? ParseAction::Accept()
: ParseAction::Reduce(Symbol(item.variable_index), item.step_index,
status.precedence, status.associativity,
*item.production);
for (const auto &lookahead_sym : *lookahead_symbols.entries)
add_action(state_id, lookahead_sym, action, item_set);
}
}
}
void add_shift_extra_actions(ParseStateId state_id) {
ParseAction action = ParseAction::ShiftExtra();
for (const Symbol &extra_symbol : grammar.extra_tokens)
add_action(state_id, extra_symbol, action, null_item_set);
}
void add_reduce_extra_actions(ParseStateId state_id) {
const ParseState &state = parse_table.states[state_id];
for (const Symbol &extra_symbol : grammar.extra_tokens) {
const auto &actions_for_symbol = state.actions.find(extra_symbol);
if (actions_for_symbol == state.actions.end())
continue;
for (const ParseAction &action : actions_for_symbol->second)
if (action.type == ParseActionTypeShift && !action.extra) {
size_t dest_state_id = action.state_index;
ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);
for (const auto &pair : state.actions)
add_action(dest_state_id, pair.first, reduce_extra, null_item_set);
}
}
}
void mark_fragile_actions() {
for (ParseState &state : parse_table.states) {
set<Symbol> symbols_with_multiple_actions;
for (auto &entry : state.actions) {
if (entry.second.size() > 1)
symbols_with_multiple_actions.insert(entry.first);
for (ParseAction &action : entry.second) {
if (action.type == ParseActionTypeReduce && !action.extra) {
if (has_fragile_production(action.production))
action.fragile = true;
action.production = NULL;
action.precedence_range = PrecedenceRange();
action.associativity = rules::AssociativityNone;
}
}
for (auto i = entry.second.begin(); i != entry.second.end();) {
bool erased = false;
for (auto j = entry.second.begin(); j != i; j++) {
if (*j == *i) {
entry.second.erase(i);
erased = true;
break;
}
}
if (!erased)
++i;
}
}
if (!symbols_with_multiple_actions.empty()) {
for (auto &entry : state.actions) {
if (!entry.first.is_token) {
set<Symbol> first_set = get_first_set(entry.first);
for (const Symbol &symbol : symbols_with_multiple_actions) {
if (first_set.count(symbol)) {
entry.second[0].can_hide_split = true;
break;
}
}
}
}
}
}
}
void remove_duplicate_parse_states() {
auto replacements =
remove_duplicate_states<ParseState, ParseAction>(&parse_table.states);
parse_table.error_state.each_advance_action(
[&replacements](ParseAction *action) {
auto replacement = replacements.find(action->state_index);
if (replacement != replacements.end())
action->state_index = replacement->second;
});
}
ParseAction *add_action(ParseStateId state_id, Symbol lookahead,
const ParseAction &new_action,
const ParseItemSet &item_set) {
const auto ¤t_actions = parse_table.states[state_id].actions;
const auto ¤t_entry = current_actions.find(lookahead);
if (current_entry == current_actions.end())
return &parse_table.set_action(state_id, lookahead, new_action);
if (allow_any_conflict)
return &parse_table.add_action(state_id, lookahead, new_action);
const ParseAction old_action = current_entry->second[0];
auto resolution = conflict_manager.resolve(new_action, old_action);
switch (resolution.second) {
case ConflictTypeNone:
if (resolution.first)
return &parse_table.set_action(state_id, lookahead, new_action);
break;
case ConflictTypeResolved: {
if (resolution.first) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
return &parse_table.set_action(state_id, lookahead, new_action);
} else {
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
break;
}
}
case ConflictTypeUnresolved: {
if (handle_unresolved_conflict(item_set, lookahead)) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
return &parse_table.add_action(state_id, lookahead, new_action);
}
break;
}
}
return nullptr;
}
bool handle_unresolved_conflict(const ParseItemSet &item_set,
const Symbol &lookahead) {
set<Symbol> involved_symbols;
set<ParseItem> reduce_items;
set<ParseItem> core_shift_items;
set<ParseItem> other_shift_items;
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
Symbol next_symbol = item.next_symbol();
if (next_symbol == rules::NONE()) {
if (lookahead_set.contains(lookahead)) {
involved_symbols.insert(item.lhs());
reduce_items.insert(item);
}
} else {
if (item.step_index > 0) {
set<Symbol> first_set = get_first_set(next_symbol);
if (first_set.count(lookahead)) {
involved_symbols.insert(item.lhs());
core_shift_items.insert(item);
}
} else if (next_symbol == lookahead) {
other_shift_items.insert(item);
}
}
}
for (const auto &conflict_set : grammar.expected_conflicts)
if (involved_symbols == conflict_set)
return true;
string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n";
if (!reduce_items.empty()) {
description += "Reduce items:\n";
for (const ParseItem &item : reduce_items)
description += " " + item_string(item) + "\n";
}
if (!core_shift_items.empty()) {
description += "Core shift items:\n";
for (const ParseItem &item : core_shift_items)
description += " " + item_string(item) + "\n";
}
if (!other_shift_items.empty()) {
description += "Other shift items:\n";
for (const ParseItem &item : other_shift_items)
description += " " + item_string(item) + "\n";
}
conflicts.insert(description);
return false;
}
string item_string(const ParseItem &item) const {
string result = symbol_name(item.lhs()) + " ->";
size_t i = 0;
for (const ProductionStep &step : *item.production) {
if (i == item.step_index)
result += " \u2022";
result += " " + symbol_name(step.symbol);
i++;
}
if (i == item.step_index)
result += " \u2022";
result += " (prec " + to_string(item.precedence());
switch (item.associativity()) {
case rules::AssociativityNone:
result += ")";
break;
case rules::AssociativityLeft:
result += ", assoc left)";
break;
case rules::AssociativityRight:
result += ", assoc right)";
break;
}
return result;
}
set<Symbol> get_first_set(const Symbol &start_symbol) {
set<Symbol> result;
vector<Symbol> symbols_to_process({ start_symbol });
while (!symbols_to_process.empty()) {
Symbol symbol = symbols_to_process.back();
symbols_to_process.pop_back();
if (result.insert(symbol).second)
for (const Production &production : grammar.productions(symbol))
if (!production.empty())
symbols_to_process.push_back(production[0].symbol);
}
return result;
}
string symbol_name(const rules::Symbol &symbol) const {
if (symbol.is_built_in()) {
if (symbol == rules::END_OF_INPUT())
return "END_OF_INPUT";
else
return "";
} else if (symbol.is_token) {
const Variable &variable = lexical_grammar.variables[symbol.index];
if (variable.type == VariableTypeNamed)
return variable.name;
else
return "'" + variable.name + "'";
} else {
return grammar.variables[symbol.index].name;
}
}
bool has_fragile_production(const Production *production) {
auto end = fragile_productions.end();
return std::find(fragile_productions.begin(), end, production) != end;
}
};
pair<ParseTable, CompileError> build_parse_table(
const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {
return ParseTableBuilder(grammar, lex_grammar).build();
}
} // namespace build_tables
} // namespace tree_sitter
<commit_msg>Don't include accept actions in recovery states<commit_after>#include "compiler/build_tables/build_parse_table.h"
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include "compiler/parse_table.h"
#include "compiler/build_tables/parse_conflict_manager.h"
#include "compiler/build_tables/remove_duplicate_states.h"
#include "compiler/build_tables/parse_item.h"
#include "compiler/build_tables/item_set_closure.h"
#include "compiler/lexical_grammar.h"
#include "compiler/syntax_grammar.h"
#include "compiler/rules/symbol.h"
#include "compiler/rules/built_in_symbols.h"
#include "compiler/build_tables/recovery_tokens.h"
namespace tree_sitter {
namespace build_tables {
using std::find;
using std::pair;
using std::vector;
using std::set;
using std::map;
using std::string;
using std::to_string;
using std::unordered_map;
using std::make_shared;
using rules::Symbol;
class ParseTableBuilder {
const SyntaxGrammar grammar;
const LexicalGrammar lexical_grammar;
ParseConflictManager conflict_manager;
unordered_map<Symbol, ParseItemSet> recovery_states;
unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids;
vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process;
ParseTable parse_table;
std::set<string> conflicts;
ParseItemSet null_item_set;
std::set<const Production *> fragile_productions;
bool allow_any_conflict;
public:
ParseTableBuilder(const SyntaxGrammar &grammar,
const LexicalGrammar &lex_grammar)
: grammar(grammar),
lexical_grammar(lex_grammar),
allow_any_conflict(false) {}
pair<ParseTable, CompileError> build() {
Symbol start_symbol = Symbol(0, grammar.variables.empty());
Production start_production({
ProductionStep(start_symbol, 0, rules::AssociativityNone),
});
add_parse_state(ParseItemSet({
{
ParseItem(rules::START(), start_production, 0),
LookaheadSet({ rules::END_OF_INPUT() }),
},
}));
CompileError error = process_part_state_queue();
if (error.type != TSCompileErrorTypeNone) {
return { parse_table, error };
}
add_out_of_context_parse_states();
allow_any_conflict = true;
process_part_state_queue();
allow_any_conflict = false;
for (ParseStateId state = 0; state < parse_table.states.size(); state++) {
add_shift_extra_actions(state);
add_reduce_extra_actions(state);
}
mark_fragile_actions();
remove_duplicate_parse_states();
return { parse_table, CompileError::none() };
}
private:
CompileError process_part_state_queue() {
while (!item_sets_to_process.empty()) {
auto pair = item_sets_to_process.back();
ParseItemSet item_set = item_set_closure(pair.first, grammar);
ParseStateId state_id = pair.second;
item_sets_to_process.pop_back();
add_reduce_actions(item_set, state_id);
add_shift_actions(item_set, state_id);
if (!conflicts.empty()) {
return CompileError(TSCompileErrorTypeParseConflict,
"Unresolved conflict.\n\n" + *conflicts.begin());
}
}
return CompileError::none();
}
void add_out_of_context_parse_states() {
for (const Symbol &symbol : recovery_tokens(lexical_grammar)) {
add_out_of_context_parse_state(symbol);
}
for (size_t i = 0; i < grammar.variables.size(); i++) {
Symbol symbol(i, false);
add_out_of_context_parse_state(symbol);
}
parse_table.error_state.actions[rules::END_OF_INPUT()].push_back(
ParseAction::Shift(0, PrecedenceRange()));
}
void add_out_of_context_parse_state(const rules::Symbol &symbol) {
const ParseItemSet &item_set = recovery_states[symbol];
if (!item_set.entries.empty()) {
ParseStateId state = add_parse_state(item_set);
parse_table.error_state.actions[symbol].push_back(
ParseAction::Shift(state, PrecedenceRange()));
}
}
ParseStateId add_parse_state(const ParseItemSet &item_set) {
auto pair = parse_state_ids.find(item_set);
if (pair == parse_state_ids.end()) {
ParseStateId state_id = parse_table.add_state();
parse_state_ids[item_set] = state_id;
item_sets_to_process.push_back({ item_set, state_id });
return state_id;
} else {
return pair->second;
}
}
void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &transition : item_set.transitions()) {
const Symbol &symbol = transition.first;
const ParseItemSet &next_item_set = transition.second.first;
const PrecedenceRange &precedence = transition.second.second;
ParseAction *new_action = add_action(
state_id, symbol, ParseAction::Shift(0, precedence), item_set);
if (!allow_any_conflict)
recovery_states[symbol].add(next_item_set);
if (new_action)
new_action->state_index = add_parse_state(next_item_set);
}
}
void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const auto &lookahead_symbols = pair.second;
ParseItem::CompletionStatus status = item.completion_status();
if (status.is_done) {
ParseAction action;
if (item.lhs() == rules::START()) {
if (state_id == 1) {
action = ParseAction::Accept();
} else {
continue;
}
} else {
action = ParseAction::Reduce(Symbol(item.variable_index),
item.step_index, status.precedence,
status.associativity, *item.production);
}
for (const auto &lookahead_sym : *lookahead_symbols.entries)
add_action(state_id, lookahead_sym, action, item_set);
}
}
}
void add_shift_extra_actions(ParseStateId state_id) {
ParseAction action = ParseAction::ShiftExtra();
for (const Symbol &extra_symbol : grammar.extra_tokens)
add_action(state_id, extra_symbol, action, null_item_set);
}
void add_reduce_extra_actions(ParseStateId state_id) {
const ParseState &state = parse_table.states[state_id];
for (const Symbol &extra_symbol : grammar.extra_tokens) {
const auto &actions_for_symbol = state.actions.find(extra_symbol);
if (actions_for_symbol == state.actions.end())
continue;
for (const ParseAction &action : actions_for_symbol->second)
if (action.type == ParseActionTypeShift && !action.extra) {
size_t dest_state_id = action.state_index;
ParseAction reduce_extra = ParseAction::ReduceExtra(extra_symbol);
for (const auto &pair : state.actions)
add_action(dest_state_id, pair.first, reduce_extra, null_item_set);
}
}
}
void mark_fragile_actions() {
for (ParseState &state : parse_table.states) {
set<Symbol> symbols_with_multiple_actions;
for (auto &entry : state.actions) {
if (entry.second.size() > 1)
symbols_with_multiple_actions.insert(entry.first);
for (ParseAction &action : entry.second) {
if (action.type == ParseActionTypeReduce && !action.extra) {
if (has_fragile_production(action.production))
action.fragile = true;
action.production = NULL;
action.precedence_range = PrecedenceRange();
action.associativity = rules::AssociativityNone;
}
}
for (auto i = entry.second.begin(); i != entry.second.end();) {
bool erased = false;
for (auto j = entry.second.begin(); j != i; j++) {
if (*j == *i) {
entry.second.erase(i);
erased = true;
break;
}
}
if (!erased)
++i;
}
}
if (!symbols_with_multiple_actions.empty()) {
for (auto &entry : state.actions) {
if (!entry.first.is_token) {
set<Symbol> first_set = get_first_set(entry.first);
for (const Symbol &symbol : symbols_with_multiple_actions) {
if (first_set.count(symbol)) {
entry.second[0].can_hide_split = true;
break;
}
}
}
}
}
}
}
void remove_duplicate_parse_states() {
auto replacements =
remove_duplicate_states<ParseState, ParseAction>(&parse_table.states);
parse_table.error_state.each_advance_action(
[&replacements](ParseAction *action) {
auto replacement = replacements.find(action->state_index);
if (replacement != replacements.end())
action->state_index = replacement->second;
});
}
ParseAction *add_action(ParseStateId state_id, Symbol lookahead,
const ParseAction &new_action,
const ParseItemSet &item_set) {
const auto ¤t_actions = parse_table.states[state_id].actions;
const auto ¤t_entry = current_actions.find(lookahead);
if (current_entry == current_actions.end())
return &parse_table.set_action(state_id, lookahead, new_action);
if (allow_any_conflict)
return &parse_table.add_action(state_id, lookahead, new_action);
const ParseAction old_action = current_entry->second[0];
auto resolution = conflict_manager.resolve(new_action, old_action);
switch (resolution.second) {
case ConflictTypeNone:
if (resolution.first)
return &parse_table.set_action(state_id, lookahead, new_action);
break;
case ConflictTypeResolved: {
if (resolution.first) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
return &parse_table.set_action(state_id, lookahead, new_action);
} else {
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
break;
}
}
case ConflictTypeUnresolved: {
if (handle_unresolved_conflict(item_set, lookahead)) {
if (old_action.type == ParseActionTypeReduce)
fragile_productions.insert(old_action.production);
if (new_action.type == ParseActionTypeReduce)
fragile_productions.insert(new_action.production);
return &parse_table.add_action(state_id, lookahead, new_action);
}
break;
}
}
return nullptr;
}
bool handle_unresolved_conflict(const ParseItemSet &item_set,
const Symbol &lookahead) {
set<Symbol> involved_symbols;
set<ParseItem> reduce_items;
set<ParseItem> core_shift_items;
set<ParseItem> other_shift_items;
for (const auto &pair : item_set.entries) {
const ParseItem &item = pair.first;
const LookaheadSet &lookahead_set = pair.second;
Symbol next_symbol = item.next_symbol();
if (next_symbol == rules::NONE()) {
if (lookahead_set.contains(lookahead)) {
involved_symbols.insert(item.lhs());
reduce_items.insert(item);
}
} else {
if (item.step_index > 0) {
set<Symbol> first_set = get_first_set(next_symbol);
if (first_set.count(lookahead)) {
involved_symbols.insert(item.lhs());
core_shift_items.insert(item);
}
} else if (next_symbol == lookahead) {
other_shift_items.insert(item);
}
}
}
for (const auto &conflict_set : grammar.expected_conflicts)
if (involved_symbols == conflict_set)
return true;
string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n";
if (!reduce_items.empty()) {
description += "Reduce items:\n";
for (const ParseItem &item : reduce_items)
description += " " + item_string(item) + "\n";
}
if (!core_shift_items.empty()) {
description += "Core shift items:\n";
for (const ParseItem &item : core_shift_items)
description += " " + item_string(item) + "\n";
}
if (!other_shift_items.empty()) {
description += "Other shift items:\n";
for (const ParseItem &item : other_shift_items)
description += " " + item_string(item) + "\n";
}
conflicts.insert(description);
return false;
}
string item_string(const ParseItem &item) const {
string result = symbol_name(item.lhs()) + " ->";
size_t i = 0;
for (const ProductionStep &step : *item.production) {
if (i == item.step_index)
result += " \u2022";
result += " " + symbol_name(step.symbol);
i++;
}
if (i == item.step_index)
result += " \u2022";
result += " (prec " + to_string(item.precedence());
switch (item.associativity()) {
case rules::AssociativityNone:
result += ")";
break;
case rules::AssociativityLeft:
result += ", assoc left)";
break;
case rules::AssociativityRight:
result += ", assoc right)";
break;
}
return result;
}
set<Symbol> get_first_set(const Symbol &start_symbol) {
set<Symbol> result;
vector<Symbol> symbols_to_process({ start_symbol });
while (!symbols_to_process.empty()) {
Symbol symbol = symbols_to_process.back();
symbols_to_process.pop_back();
if (result.insert(symbol).second)
for (const Production &production : grammar.productions(symbol))
if (!production.empty())
symbols_to_process.push_back(production[0].symbol);
}
return result;
}
string symbol_name(const rules::Symbol &symbol) const {
if (symbol.is_built_in()) {
if (symbol == rules::END_OF_INPUT())
return "END_OF_INPUT";
else
return "";
} else if (symbol.is_token) {
const Variable &variable = lexical_grammar.variables[symbol.index];
if (variable.type == VariableTypeNamed)
return variable.name;
else
return "'" + variable.name + "'";
} else {
return grammar.variables[symbol.index].name;
}
}
bool has_fragile_production(const Production *production) {
auto end = fragile_productions.end();
return std::find(fragile_productions.begin(), end, production) != end;
}
};
pair<ParseTable, CompileError> build_parse_table(
const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) {
return ParseTableBuilder(grammar, lex_grammar).build();
}
} // namespace build_tables
} // namespace tree_sitter
<|endoftext|>
|
<commit_before>#ifndef ETCDV3_CLIENT
#define ETCDV3_CLIENT
#include "rpc.grpc.pb.h"
#include <grpc++/grpc++.h>
#include <map>
using grpc::Channel;
using grpc::ClientContext;
using etcdserverpb::KV;
using etcdserverpb::Watch;
using etcdserverpb::Lease;
using etcdserverpb::PutRequest;
using etcdserverpb::PutResponse;
using etcdserverpb::RangeRequest;
using etcdserverpb::RangeResponse;
using etcdserverpb::WatchRequest;
using etcdserverpb::WatchCreateRequest;
using etcdserverpb::WatchResponse;
using etcdserverpb::TxnRequest;
using etcdserverpb::TxnResponse;
using grpc::Status;
using grpc::CompletionQueue;
using grpc::ClientAsyncReaderWriter;
//--------------------------------------------------
class Client {
//--------------------------------------------------
public:
explicit Client(std::shared_ptr<Channel> channel)
: m_kvStub(KV::NewStub(channel)),
m_watchStub(Watch::NewStub(channel)),
m_leaseStub(Lease::NewStub(channel))
{
}
explicit Client(std::string address)
: Client(grpc::CreateChannel(address, grpc::InsecureChannelCredentials()))
{
}
Status put(const std::string &key, const std::string &value){
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(false);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
return putStatus;
}
Status put(const std::string &key, const std::string &value, std::pair<std::string, std::string> &prevKV) {
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(true);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
prevKV.first = put_response.prev_kv().key();
prevKV.first = put_response.prev_kv().value();
return putStatus;
}
Status put(const std::string &key, const std::string &value, int64_t lease){
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(false);
put_request->set_lease(lease);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
return putStatus;
}
const std::string get(const std::string key){
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
return getResponse.kvs(0).value();
}
Status getFromKey(const std::string key, std::map<std::string, std::string> & pairs) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
getRequest.set_range_end("\0", 1);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
pairs[kv_item.key()] = kv_item.value();
}
return getStatus;
}
Status get(const std::string key, std::map<std::string, std::string> & pairs) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
std::string range_end (key);
range_end.back()++;
getRequest.set_range_end(range_end);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
pairs[kv_item.key()] = kv_item.value();
}
return getStatus;
}
Status getKeys(const std::string key, std::vector<std::string> & keys) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
std::string range_end (key);
range_end.back()++;
getRequest.set_range_end(range_end);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
keys.push_back(kv_item.key());
}
return getStatus;
}
template <typename T>
void watch(const std::string key, T callback) {
ClientContext context;
WatchRequest watchRequest;
CompletionQueue cq_;
WatchResponse watchResponse;
watchRequest.mutable_create_request()->set_key(key);
auto stream = m_watchStub->Watch(&context);
stream->Write(watchRequest);
stream->Read(&watchResponse);
while(true){
bool op = stream->Read(&watchResponse);
// event is of type: mvccpb::Event
for(auto event: watchResponse.events()){
std::cerr << "Reveived watch_response event.type() = "<< event.type() << std::endl;
callback(event);
}
if(!op){
std::cerr << "Lost connection with stream..."<< std::endl;
break;
}
}
}
Status txn(const std::string key, const std::string value) {
ClientContext context;
TxnRequest txnRequest;
TxnResponse txnResponse;
// RangeRequest getRequest;
std::unique_ptr<RangeRequest> getRequest(new RangeRequest());
// add compare object to Txn
auto compare = txnRequest.add_compare();
compare->set_result(etcdserverpb::Compare_CompareResult_EQUAL);
compare->set_target(etcdserverpb::Compare_CompareTarget_VALUE);
compare->set_key(key);
compare->set_value(value);
//add success object to Txn
auto success = txnRequest.add_success();
getRequest->set_key(key);
success->set_allocated_request_range(getRequest.release());
Status getStatus = m_kvStub->Txn(&context, txnRequest , &txnResponse);
for(auto resp: txnResponse.responses()){
for(auto kvs_items: resp.response_range().kvs()){
std::cerr << kvs_items.key() <<
":" << kvs_items.value() << std::endl;
}
}
return getStatus;
}
private:
std::unique_ptr<KV::Stub> m_kvStub;
std::unique_ptr<Watch::Stub> m_watchStub;
std::unique_ptr<Lease::Stub> m_leaseStub;
};
#endif
<commit_msg>added update and create lease funcs. removed uneeded whitespace<commit_after>#ifndef ETCDV3_CLIENT
#define ETCDV3_CLIENT
#include "rpc.grpc.pb.h"
#include <grpc++/grpc++.h>
#include <map>
using grpc::Channel;
using grpc::ClientContext;
using etcdserverpb::KV;
using etcdserverpb::Watch;
using etcdserverpb::Lease;
using etcdserverpb::PutRequest;
using etcdserverpb::PutResponse;
using etcdserverpb::RangeRequest;
using etcdserverpb::RangeResponse;
using etcdserverpb::WatchRequest;
using etcdserverpb::WatchCreateRequest;
using etcdserverpb::WatchResponse;
using etcdserverpb::TxnRequest;
using etcdserverpb::TxnResponse;
using grpc::Status;
using grpc::CompletionQueue;
using grpc::ClientAsyncReaderWriter;
//--------------------------------------------------
class Client {
//--------------------------------------------------
public:
explicit Client(std::shared_ptr<Channel> channel)
: m_kvStub(KV::NewStub(channel)),
m_watchStub(Watch::NewStub(channel)),
m_leaseStub(Lease::NewStub(channel))
{
}
explicit Client(std::string address)
: Client(grpc::CreateChannel(address, grpc::InsecureChannelCredentials()))
{
}
Status put(const std::string &key, const std::string &value){
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(false);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
return putStatus;
}
Status put(const std::string &key, const std::string &value, std::pair<std::string, std::string> &prevKV) {
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(true);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
prevKV.first = put_response.prev_kv().key();
prevKV.first = put_response.prev_kv().value();
return putStatus;
}
Status put(const std::string &key, const std::string &value, int64_t lease){
ClientContext context;
PutResponse put_response;
std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key);
put_request->set_value(value);
put_request->set_prev_kv(false);
put_request->set_lease(lease);
Status putStatus = m_kvStub->Put(&context, *(put_request.get()), &put_response);
return putStatus;
}
const std::string get(const std::string key){
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
return getResponse.kvs(0).value();
}
Status getFromKey(const std::string key, std::map<std::string, std::string> & pairs) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
getRequest.set_range_end("\0", 1);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
pairs[kv_item.key()] = kv_item.value();
}
return getStatus;
}
Status get(const std::string key, std::map<std::string, std::string> & pairs) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
std::string range_end (key);
range_end.back()++;
getRequest.set_range_end(range_end);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
pairs[kv_item.key()] = kv_item.value();
}
return getStatus;
}
Status getKeys(const std::string key, std::vector<std::string> & keys) {
ClientContext context;
RangeRequest getRequest;
RangeResponse getResponse;
getRequest.set_key(key);
std::string range_end (key);
range_end.back()++;
getRequest.set_range_end(range_end);
Status getStatus = m_kvStub->Range(&context, getRequest , &getResponse);
for(auto kv_item: getResponse.kvs()){
keys.push_back(kv_item.key());
}
return getStatus;
}
void updateLease(uint64_t leaseId) {
ClientContext context;
etcdserverpb::LeaseKeepAliveRequest leaseKeepAliveRequest;
etcdserverpb::LeaseKeepAliveResponse leaseKeepAliveResponse;
auto stream = m_leaseStub->LeaseKeepAlive(&context);
leaseKeepAliveRequest.set_id(leaseId);
stream->Write(leaseKeepAliveRequest);
stream->Read(&leaseKeepAliveResponse);
}
Status createLease(uint64_t leaseId, uint64_t ttl) {
ClientContext context;
etcdserverpb::LeaseGrantRequest createLeaseRequest;
etcdserverpb::LeaseGrantResponse createLeaseResponse;
createLeaseRequest.set_id(leaseId);
createLeaseRequest.set_ttl(ttl);
Status createLeaseStatus = m_leaseStub->LeaseGrant(&context, createLeaseRequest, &createLeaseResponse);
return createLeaseStatus;
}
template <typename T>
void watch(const std::string key, T callback) {
ClientContext context;
WatchRequest watchRequest;
CompletionQueue cq_;
WatchResponse watchResponse;
watchRequest.mutable_create_request()->set_key(key);
auto stream = m_watchStub->Watch(&context);
stream->Write(watchRequest);
stream->Read(&watchResponse);
while(true){
bool op = stream->Read(&watchResponse);
// event is of type: mvccpb::Event
for(auto event: watchResponse.events()){
std::cerr << "Reveived watch_response event.type() = "<< event.type() << std::endl;
callback(event);
}
if(!op){
std::cerr << "Lost connection with stream..."<< std::endl;
break;
}
}
}
Status txn(const std::string key, const std::string value) {
ClientContext context;
TxnRequest txnRequest;
TxnResponse txnResponse;
// RangeRequest getRequest;
std::unique_ptr<RangeRequest> getRequest(new RangeRequest());
// add compare object to Txn
auto compare = txnRequest.add_compare();
compare->set_result(etcdserverpb::Compare_CompareResult_EQUAL);
compare->set_target(etcdserverpb::Compare_CompareTarget_VALUE);
compare->set_key(key);
compare->set_value(value);
//add success object to Txn
auto success = txnRequest.add_success();
getRequest->set_key(key);
success->set_allocated_request_range(getRequest.release());
Status getStatus = m_kvStub->Txn(&context, txnRequest , &txnResponse);
for(auto resp: txnResponse.responses()){
for(auto kvs_items: resp.response_range().kvs()){
std::cerr << kvs_items.key() <<
":" << kvs_items.value() << std::endl;
}
}
return getStatus;
}
private:
std::unique_ptr<KV::Stub> m_kvStub;
std::unique_ptr<Watch::Stub> m_watchStub;
std::unique_ptr<Lease::Stub> m_leaseStub;
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 "SkData.h"
#include "SkFlate.h"
#include "SkStream.h"
#ifndef SK_ZLIB_INCLUDE
bool SkFlate::HaveFlate() { return false; }
bool SkFlate::Deflate(SkStream*, SkWStream*) { return false; }
bool SkFlate::Inflate(SkStream*, SkWStream*) { return false; }
#else
// static
bool SkFlate::HaveFlate() {
return true;
}
namespace {
#include SK_ZLIB_INCLUDE
// static
const size_t kBufferSize = 1024;
bool doFlate(bool compress, SkStream* src, SkWStream* dst) {
uint8_t inputBuffer[kBufferSize];
uint8_t outputBuffer[kBufferSize];
z_stream flateData;
flateData.zalloc = NULL;
flateData.zfree = NULL;
flateData.next_in = NULL;
flateData.avail_in = 0;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
int rc;
if (compress)
rc = deflateInit(&flateData, Z_DEFAULT_COMPRESSION);
else
rc = inflateInit(&flateData);
if (rc != Z_OK)
return false;
uint8_t* input = (uint8_t*)src->getMemoryBase();
size_t inputLength = src->getLength();
if (input == NULL || inputLength == 0) {
input = NULL;
flateData.next_in = inputBuffer;
flateData.avail_in = 0;
} else {
flateData.next_in = input;
flateData.avail_in = inputLength;
}
rc = Z_OK;
while (true) {
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out)) {
rc = Z_BUF_ERROR;
break;
}
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
if (rc != Z_OK)
break;
if (flateData.avail_in == 0) {
if (input != NULL)
break;
size_t read = src->read(&inputBuffer, kBufferSize);
if (read == 0)
break;
flateData.next_in = inputBuffer;
flateData.avail_in = read;
}
if (compress)
rc = deflate(&flateData, Z_NO_FLUSH);
else
rc = inflate(&flateData, Z_NO_FLUSH);
}
while (rc == Z_OK) {
if (compress)
rc = deflate(&flateData, Z_FINISH);
else
rc = inflate(&flateData, Z_FINISH);
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out))
return false;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
}
if (compress)
deflateEnd(&flateData);
else
inflateEnd(&flateData);
if (rc == Z_STREAM_END)
return true;
return false;
}
}
// static
bool SkFlate::Deflate(SkStream* src, SkWStream* dst) {
return doFlate(true, src, dst);
}
bool SkFlate::Deflate(const void* ptr, size_t len, SkWStream* dst) {
SkMemoryStream stream(ptr, len);
return doFlate(true, &stream, dst);
}
bool SkFlate::Deflate(const SkData* data, SkWStream* dst) {
if (data) {
SkMemoryStream stream(data->data(), data->size());
return doFlate(true, &stream, dst);
}
return false;
}
// static
bool SkFlate::Inflate(SkStream* src, SkWStream* dst) {
return doFlate(false, src, dst);
}
#endif
<commit_msg>Fix SkFlate.cpp when SK_ZLIB_INCLUDE is not #defined.<commit_after>/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 "SkData.h"
#include "SkFlate.h"
#include "SkStream.h"
#ifndef SK_ZLIB_INCLUDE
bool SkFlate::HaveFlate() { return false; }
bool SkFlate::Deflate(SkStream*, SkWStream*) { return false; }
bool SkFlate::Deflate(const void*, size_t, SkWStream*) { return false; }
bool SkFlate::Deflate(const SkData*, SkWStream*) { return false; }
bool SkFlate::Inflate(SkStream*, SkWStream*) { return false; }
#else
// static
bool SkFlate::HaveFlate() {
return true;
}
namespace {
#include SK_ZLIB_INCLUDE
// static
const size_t kBufferSize = 1024;
bool doFlate(bool compress, SkStream* src, SkWStream* dst) {
uint8_t inputBuffer[kBufferSize];
uint8_t outputBuffer[kBufferSize];
z_stream flateData;
flateData.zalloc = NULL;
flateData.zfree = NULL;
flateData.next_in = NULL;
flateData.avail_in = 0;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
int rc;
if (compress)
rc = deflateInit(&flateData, Z_DEFAULT_COMPRESSION);
else
rc = inflateInit(&flateData);
if (rc != Z_OK)
return false;
uint8_t* input = (uint8_t*)src->getMemoryBase();
size_t inputLength = src->getLength();
if (input == NULL || inputLength == 0) {
input = NULL;
flateData.next_in = inputBuffer;
flateData.avail_in = 0;
} else {
flateData.next_in = input;
flateData.avail_in = inputLength;
}
rc = Z_OK;
while (true) {
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out)) {
rc = Z_BUF_ERROR;
break;
}
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
if (rc != Z_OK)
break;
if (flateData.avail_in == 0) {
if (input != NULL)
break;
size_t read = src->read(&inputBuffer, kBufferSize);
if (read == 0)
break;
flateData.next_in = inputBuffer;
flateData.avail_in = read;
}
if (compress)
rc = deflate(&flateData, Z_NO_FLUSH);
else
rc = inflate(&flateData, Z_NO_FLUSH);
}
while (rc == Z_OK) {
if (compress)
rc = deflate(&flateData, Z_FINISH);
else
rc = inflate(&flateData, Z_FINISH);
if (flateData.avail_out < kBufferSize) {
if (!dst->write(outputBuffer, kBufferSize - flateData.avail_out))
return false;
flateData.next_out = outputBuffer;
flateData.avail_out = kBufferSize;
}
}
if (compress)
deflateEnd(&flateData);
else
inflateEnd(&flateData);
if (rc == Z_STREAM_END)
return true;
return false;
}
}
// static
bool SkFlate::Deflate(SkStream* src, SkWStream* dst) {
return doFlate(true, src, dst);
}
bool SkFlate::Deflate(const void* ptr, size_t len, SkWStream* dst) {
SkMemoryStream stream(ptr, len);
return doFlate(true, &stream, dst);
}
bool SkFlate::Deflate(const SkData* data, SkWStream* dst) {
if (data) {
SkMemoryStream stream(data->data(), data->size());
return doFlate(true, &stream, dst);
}
return false;
}
// static
bool SkFlate::Inflate(SkStream* src, SkWStream* dst) {
return doFlate(false, src, dst);
}
#endif
<|endoftext|>
|
<commit_before>#include "googletest/googletest/include/gtest/gtest.h"
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <unordered_map>
#include <unordered_set>
const std::string TempNTP1File("ntp1txout.bin");
std::string RandomString(const int len)
{
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string s;
s.resize(len);
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}
#define CUSTOM_LMDB_DB_SIZE (1 << 14)
#include "../txdb-lmdb.h"
TEST(lmdb_tests, basic)
{
std::cout << "LMDB DB size: " << DB_DEFAULT_MAPSIZE << std::endl;
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::string k1 = "key1";
std::string v1 = "val1";
EXPECT_TRUE(db.test1_WriteStrKeyVal(k1, v1));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k1, out));
EXPECT_EQ(out, v1);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test1_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, basic_in_1_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
db.TxnBegin();
std::string k1 = "key1";
std::string v1 = "val1";
EXPECT_TRUE(db.test1_WriteStrKeyVal(k1, v1));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k1, out));
EXPECT_EQ(out, v1);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k1));
db.TxnAbort();
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, many_inputs)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::unordered_map<std::string, std::string> entries;
const uint64_t entriesCount = 100;
for (uint64_t i = 0; i < entriesCount; i++) {
std::string k = RandomString(100);
std::string v = RandomString(1000000);
if (entries.find(k) != entries.end()) {
continue;
}
entries[k] = v;
EXPECT_TRUE(db.test1_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k, out));
EXPECT_EQ(out, v);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k));
}
for (const auto& pair : entries) {
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(pair.first, out));
EXPECT_EQ(out, pair.second);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(pair.first));
}
db.Close();
}
TEST(lmdb_tests, many_inputs_one_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::unordered_map<std::string, std::string> entries;
const uint64_t entriesCount = 100;
std::size_t keySize = 100;
std::size_t valSize = 1000000;
db.TxnBegin(keySize * valSize * 11 / 10);
for (uint64_t i = 0; i < entriesCount; i++) {
std::string k = RandomString(keySize);
std::string v = RandomString(valSize);
if (entries.find(k) != entries.end()) {
continue;
}
entries[k] = v;
EXPECT_TRUE(db.test1_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k, out));
EXPECT_EQ(out, v);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k));
}
db.TxnCommit();
for (const auto& pair : entries) {
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(pair.first, out));
EXPECT_EQ(out, pair.second);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(pair.first));
}
db.Close();
}
TEST(lmdb_tests, basic_multiple_read)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::string k1 = "key1";
std::string v1 = "val1";
std::string v2 = "val2";
std::string v3 = "val3";
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v1));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v2));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v3));
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k1, outs));
EXPECT_EQ(outs, std::vector<std::string>({v1, v2, v3}));
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k1));
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, basic_multiple_read_in_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
db.TxnBegin(100);
std::string k1 = "key1";
std::string v1 = "val1";
std::string v2 = "val2";
std::string v3 = "val3";
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v1));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v2));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v3));
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k1, outs));
EXPECT_EQ(outs, std::vector<std::string>({v1, v2, v3}));
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k1));
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.TxnCommit();
db.Close();
}
TEST(lmdb_tests, basic_multiple_many_inputs)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::vector<std::string> entries;
std::string k = "TheKey";
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k));
const uint64_t entriesCount = 1;
for (uint64_t i = 0; i < entriesCount; i++) {
std::string v = RandomString(508); // bigger size seems to create error: MDB_BAD_VALSIZE
entries.push_back(v);
EXPECT_TRUE(db.test2_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k));
}
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k, outs));
EXPECT_EQ(outs, entries);
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k));
db.Close();
}
TEST(quicksync_tests, download_index_file)
{
std::string s = cURLTools::GetFileFromHTTPS(QuickSyncDataLink, 30, false);
json_spirit::Value parsedData;
json_spirit::read_or_throw(s, parsedData);
json_spirit::Array rootArray = parsedData.get_array();
ASSERT_GE(rootArray.size(), 1u);
for (const json_spirit::Value& val : rootArray) {
json_spirit::Array files = NTP1Tools::GetArrayField(val.get_obj(), "files");
bool lockFileFound = false;
for (const json_spirit::Value& fileVal : files) {
std::string url = NTP1Tools::GetStrField(fileVal.get_obj(), "url");
std::string sum = NTP1Tools::GetStrField(fileVal.get_obj(), "sha256sum");
int64_t fileSize = NTP1Tools::GetInt64Field(fileVal.get_obj(), "size");
std::string sumBin = boost::algorithm::unhex(sum);
EXPECT_GT(fileSize, 0);
// test the lock file, if this iteration is for the lock file
if (boost::algorithm::ends_with(url, "lock.mdb")) {
lockFileFound = true;
{
// test by loading to memory and calculating the hash
std::string lockFile = cURLTools::GetFileFromHTTPS(url, 30, false);
std::string sha256_result;
sha256_result.resize(32);
SHA256(reinterpret_cast<unsigned char*>(&lockFile.front()), lockFile.size(),
reinterpret_cast<unsigned char*>(&sha256_result.front()));
EXPECT_EQ(sumBin, sha256_result);
}
{
// test by downloading to a file and calculating the hash
std::atomic<float> progress;
boost::filesystem::path testFilePath = "test_lock.mdb";
cURLTools::GetLargeFileFromHTTPS(url, 30, testFilePath, progress);
std::string sha256_result = CalculateHashOfFile<Sha256Calculator>(testFilePath);
EXPECT_EQ(sumBin, sha256_result);
boost::filesystem::remove(testFilePath);
}
}
// test the data file, if this iteration is for the data file
// if (boost::algorithm::ends_with(url, "data.mdb")) {
// std::string url = NTP1Tools::GetStrField(fileVal.get_obj(), "url");
// std::string sum = NTP1Tools::GetStrField(fileVal.get_obj(),
// "sha256sum"); std::string sumBin = boost::algorithm::unhex(sum);
// {
// // test by downloading to a file and calculating the hash
// std::atomic<float> progress;
// boost::filesystem::path testFilePath = "test_data.mdb";
// std::atomic_bool finishedDownload;
// finishedDownload.store(false);
// boost::thread downloadThread([&]() {
// cURLTools::GetLargeFileFromHTTPS(url, 30, testFilePath, progress);
// finishedDownload.store(true);
// });
// std::cout << "Downloading file: " << url << std::endl;
// while (!finishedDownload) {
// std::cout << "File download progress: " << progress.load() << "%"
// << std::endl;
// boost::this_thread::sleep_for(boost::chrono::seconds(2));
// }
// std::cout << "File download progress: "
// << "100"
// << "%" << std::endl;
// downloadThread.join();
// std::string sha256_result =
// CalculateHashOfFile<Sha256Calculator>(testFilePath); EXPECT_EQ(sumBin,
// sha256_result); boost::filesystem::remove(testFilePath);
// }
// }
}
EXPECT_TRUE(lockFileFound) << "For one entry, lock file not found: " << QuickSyncDataLink;
std::string os = NTP1Tools::GetStrField(val.get_obj(), "os");
}
}
<commit_msg>Fix the tests to comply with the new backup-urls json scheme.<commit_after>#include "googletest/googletest/include/gtest/gtest.h"
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <unordered_map>
#include <unordered_set>
const std::string TempNTP1File("ntp1txout.bin");
std::string RandomString(const int len)
{
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string s;
s.resize(len);
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}
#define CUSTOM_LMDB_DB_SIZE (1 << 14)
#include "../txdb-lmdb.h"
TEST(lmdb_tests, basic)
{
std::cout << "LMDB DB size: " << DB_DEFAULT_MAPSIZE << std::endl;
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::string k1 = "key1";
std::string v1 = "val1";
EXPECT_TRUE(db.test1_WriteStrKeyVal(k1, v1));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k1, out));
EXPECT_EQ(out, v1);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test1_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, basic_in_1_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
db.TxnBegin();
std::string k1 = "key1";
std::string v1 = "val1";
EXPECT_TRUE(db.test1_WriteStrKeyVal(k1, v1));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k1, out));
EXPECT_EQ(out, v1);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k1));
db.TxnAbort();
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, many_inputs)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::unordered_map<std::string, std::string> entries;
const uint64_t entriesCount = 100;
for (uint64_t i = 0; i < entriesCount; i++) {
std::string k = RandomString(100);
std::string v = RandomString(1000000);
if (entries.find(k) != entries.end()) {
continue;
}
entries[k] = v;
EXPECT_TRUE(db.test1_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k, out));
EXPECT_EQ(out, v);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k));
}
for (const auto& pair : entries) {
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(pair.first, out));
EXPECT_EQ(out, pair.second);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(pair.first));
}
db.Close();
}
TEST(lmdb_tests, many_inputs_one_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::unordered_map<std::string, std::string> entries;
const uint64_t entriesCount = 100;
std::size_t keySize = 100;
std::size_t valSize = 1000000;
db.TxnBegin(keySize * valSize * 11 / 10);
for (uint64_t i = 0; i < entriesCount; i++) {
std::string k = RandomString(keySize);
std::string v = RandomString(valSize);
if (entries.find(k) != entries.end()) {
continue;
}
entries[k] = v;
EXPECT_TRUE(db.test1_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(k, out));
EXPECT_EQ(out, v);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(k));
}
db.TxnCommit();
for (const auto& pair : entries) {
std::string out;
EXPECT_TRUE(db.test1_ReadStrKeyVal(pair.first, out));
EXPECT_EQ(out, pair.second);
EXPECT_TRUE(db.test1_ExistsStrKeyVal(pair.first));
}
db.Close();
}
TEST(lmdb_tests, basic_multiple_read)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::string k1 = "key1";
std::string v1 = "val1";
std::string v2 = "val2";
std::string v3 = "val3";
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v1));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v2));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v3));
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k1, outs));
EXPECT_EQ(outs, std::vector<std::string>({v1, v2, v3}));
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k1));
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.Close();
}
TEST(lmdb_tests, basic_multiple_read_in_tx)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
db.TxnBegin(100);
std::string k1 = "key1";
std::string v1 = "val1";
std::string v2 = "val2";
std::string v3 = "val3";
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v1));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v2));
EXPECT_TRUE(db.test2_WriteStrKeyVal(k1, v3));
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k1, outs));
EXPECT_EQ(outs, std::vector<std::string>({v1, v2, v3}));
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k1));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k1));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k1));
// uncommitted data shouldn't exist
EXPECT_FALSE(db.test1_ExistsStrKeyVal(k1));
db.TxnCommit();
db.Close();
}
TEST(lmdb_tests, basic_multiple_many_inputs)
{
CTxDB::DB_DIR = "test-txdb"; // avoid writing to the main database
CTxDB::__deleteDb(); // clean up
CTxDB::QuickSyncHigherControl_Enabled = false;
CTxDB db;
std::vector<std::string> entries;
std::string k = "TheKey";
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k));
const uint64_t entriesCount = 1;
for (uint64_t i = 0; i < entriesCount; i++) {
std::string v = RandomString(508); // bigger size seems to create error: MDB_BAD_VALSIZE
entries.push_back(v);
EXPECT_TRUE(db.test2_WriteStrKeyVal(k, v));
std::string out;
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k));
}
std::vector<std::string> outs;
EXPECT_TRUE(db.test2_ReadMultipleStr1KeyVal(k, outs));
EXPECT_EQ(outs, entries);
EXPECT_TRUE(db.test2_ExistsStrKeyVal(k));
EXPECT_TRUE(db.test2_EraseStrKeyVal(k));
EXPECT_FALSE(db.test2_ExistsStrKeyVal(k));
db.Close();
}
TEST(quicksync_tests, download_index_file)
{
std::string s = cURLTools::GetFileFromHTTPS(QuickSyncDataLink, 30, false);
json_spirit::Value parsedData;
json_spirit::read_or_throw(s, parsedData);
json_spirit::Array rootArray = parsedData.get_array();
ASSERT_GE(rootArray.size(), 1u);
for (const json_spirit::Value& val : rootArray) {
json_spirit::Array files = NTP1Tools::GetArrayField(val.get_obj(), "files");
bool lockFileFound = false;
for (const json_spirit::Value& fileVal : files) {
json_spirit::Array urlsObj = NTP1Tools::GetArrayField(fileVal.get_obj(), "url");
std::string sum = NTP1Tools::GetStrField(fileVal.get_obj(), "sha256sum");
int64_t fileSize = NTP1Tools::GetInt64Field(fileVal.get_obj(), "size");
std::string sumBin = boost::algorithm::unhex(sum);
EXPECT_GT(fileSize, 0);
ASSERT_GE(urlsObj.size(), 0u);
for (const auto& urlObj : urlsObj) {
std::string url = urlObj.get_str();
// test the lock file, if this iteration is for the lock file
if (boost::algorithm::ends_with(url, "lock.mdb")) {
lockFileFound = true;
{
// test by loading to memory and calculating the hash
std::string lockFile = cURLTools::GetFileFromHTTPS(url, 30, false);
std::string sha256_result;
sha256_result.resize(32);
SHA256(reinterpret_cast<unsigned char*>(&lockFile.front()), lockFile.size(),
reinterpret_cast<unsigned char*>(&sha256_result.front()));
EXPECT_EQ(sumBin, sha256_result);
}
{
// test by downloading to a file and calculating the hash
std::atomic<float> progress;
boost::filesystem::path testFilePath = "test_lock.mdb";
cURLTools::GetLargeFileFromHTTPS(url, 30, testFilePath, progress);
std::string sha256_result = CalculateHashOfFile<Sha256Calculator>(testFilePath);
EXPECT_EQ(sumBin, sha256_result);
boost::filesystem::remove(testFilePath);
}
}
// test the data file, if this iteration is for the data file
// if (boost::algorithm::ends_with(url, "data.mdb")) {
// std::string url = NTP1Tools::GetStrField(fileVal.get_obj(), "url");
// std::string sum = NTP1Tools::GetStrField(fileVal.get_obj(),
// "sha256sum"); std::string sumBin = boost::algorithm::unhex(sum);
// {
// // test by downloading to a file and calculating the hash
// std::atomic<float> progress;
// boost::filesystem::path testFilePath = "test_data.mdb";
// std::atomic_bool finishedDownload;
// finishedDownload.store(false);
// boost::thread downloadThread([&]() {
// cURLTools::GetLargeFileFromHTTPS(url, 30, testFilePath,
// progress); finishedDownload.store(true);
// });
// std::cout << "Downloading file: " << url << std::endl;
// while (!finishedDownload) {
// std::cout << "File download progress: " << progress.load() <<
// "%"
// << std::endl;
// boost::this_thread::sleep_for(boost::chrono::seconds(2));
// }
// std::cout << "File download progress: "
// << "100"
// << "%" << std::endl;
// downloadThread.join();
// std::string sha256_result =
// CalculateHashOfFile<Sha256Calculator>(testFilePath);
// EXPECT_EQ(sumBin, sha256_result);
// boost::filesystem::remove(testFilePath);
// }
// }
}
}
EXPECT_TRUE(lockFileFound) << "For one entry, lock file not found: " << QuickSyncDataLink;
std::string os = NTP1Tools::GetStrField(val.get_obj(), "os");
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
Coords.h
Coordinate values (x, y, z, width, height ) wrapper
Copyright (c) 2013 Jeffrey Carpenter
All rights reserved.
******************************************************************************/
#ifndef NOMLIB_COORDS_HEADERS
#define NOMLIB_COORDS_HEADERS
#include <iostream>
#include <string>
#include <map>
#include "SDL.h"
#include "gamelib.h"
namespace nom
{
class Coords
{
public:
Coords ( void );
Coords ( signed int x_, signed int y_,
signed int width_ = 0, signed height_ = 0);
~Coords ( void );
// phase out
void setCoords ( signed int x_, signed int y_,
signed int width_ = 0, signed int height_ = 0 );
SDL_Rect getSDL_Rect ( void ) const;
signed int getX ( void ) const;
signed int getY ( void ) const;
void setX ( signed int x_ );
void setY ( signed int y_ );
void setXY ( signed int x_, signed int y_ );
signed int getWidth ( void ) const;
signed int getHeight ( void ) const;
void setWidth ( signed int width_ );
void setHeight ( signed int height_ );
// phase out
void setDimensions ( signed int width_, signed int height_ );
void updateX ( signed int x_ );
void updateY ( signed int y_ );
void updateXY ( signed int x_ = 0, signed int y_ = 0 );
void updateWidth ( signed int width_ );
void updateHeight ( signed int height_ );
void updateCoords ( signed int x_ = 0, signed int y_ = 0, signed int width_ = 0, signed int height_ = 0 );
//signed int x;
//signed int y;
//signed int z;
//signed int width;
//signed int height;
private:
signed int x;
signed int y;
signed int z; // reserved
signed int width;
signed int height;
};
}
#endif // NOMLIB_COORDS_HEADERS defined
<commit_msg>Added comparison operators for nom::Coords objects<commit_after>/******************************************************************************
Coords.h
Coordinate values (x, y, z, width, height ) wrapper
Copyright (c) 2013 Jeffrey Carpenter
All rights reserved.
******************************************************************************/
#ifndef NOMLIB_COORDS_HEADERS
#define NOMLIB_COORDS_HEADERS
#include <iostream>
#include <string>
#include <map>
#include "SDL.h"
#include "gamelib.h"
namespace nom
{
class Coords
{
public:
Coords ( void );
Coords ( signed int x_, signed int y_,
signed int width_ = 0, signed height_ = 0);
~Coords ( void );
// phase out
void setCoords ( signed int x_, signed int y_,
signed int width_ = 0, signed int height_ = 0 );
SDL_Rect getSDL_Rect ( void ) const;
signed int getX ( void ) const;
signed int getY ( void ) const;
void setX ( signed int x_ );
void setY ( signed int y_ );
void setXY ( signed int x_, signed int y_ );
signed int getWidth ( void ) const;
signed int getHeight ( void ) const;
void setWidth ( signed int width_ );
void setHeight ( signed int height_ );
// phase out
void setDimensions ( signed int width_, signed int height_ );
void updateX ( signed int x_ );
void updateY ( signed int y_ );
void updateXY ( signed int x_ = 0, signed int y_ = 0 );
void updateWidth ( signed int width_ );
void updateHeight ( signed int height_ );
void updateCoords ( signed int x_ = 0, signed int y_ = 0, signed int width_ = 0, signed int height_ = 0 );
signed int x;
signed int y;
signed int z; // reserved
signed int width;
signed int height;
private:
// ...
};
// FIXME: not sure why these cannot be put into the class file without
// linking errs?
inline bool operator == ( const nom::Coords& left, const nom::Coords& right )
{
return (left.x == right.x ) &&
(left.y == right.y ) &&
(left.width == right.width ) &&
(left.height == right.height );
}
inline bool operator != ( const nom::Coords& left, const nom::Coords& right )
{
return ! ( left == right );
}
inline nom::Coords operator + ( const nom::Coords& left, const nom::Coords& right )
{
return nom::Coords ( static_cast<int32_t> ( left.x + right.x ),
static_cast<int32_t> ( left.y + right.y ),
static_cast<int32_t> ( left.width + right.width ),
static_cast<int32_t> ( left.height + right.height )
);
}
inline nom::Coords operator ++ ( nom::Coords& left )
{
return nom::Coords ( static_cast<int32_t> ( left.x ++ ),
static_cast<int32_t> ( left.y ++ ),
static_cast<int32_t> ( left.width ++ ),
static_cast<int32_t> ( left.height ++ )
);
}
inline nom::Coords operator - ( const nom::Coords& left, const nom::Coords& right )
{
return nom::Coords ( static_cast<int32_t> ( left.x - right.x ),
static_cast<int32_t> ( left.y - right.y ),
static_cast<int32_t> ( left.width - right.width ),
static_cast<int32_t> ( left.height - right.height )
);
}
inline nom::Coords operator -- ( nom::Coords& left )
{
return nom::Coords ( static_cast<int32_t> ( left.x -- ),
static_cast<int32_t> ( left.y -- ),
static_cast<int32_t> ( left.width -- ),
static_cast<int32_t> ( left.height -- )
);
}
inline nom::Coords operator * ( const nom::Coords& left, const nom::Coords& right)
{
return nom::Coords ( static_cast<int32_t> ( left.x * right.x ),
static_cast<int32_t> ( left.y * right.y ),
static_cast<int32_t> ( left.width * right.width ),
static_cast<int32_t> ( left.height * right.height )
);
}
inline nom::Coords& operator += ( nom::Coords& left, const nom::Coords& right)
{
return left = left + right;
}
inline nom::Coords& operator -= ( nom::Coords& left, const nom::Coords& right )
{
return left = left - right;
}
inline nom::Coords& operator *= ( nom::Coords& left, const nom::Coords& right)
{
return left = left * right;
}
}
#endif // NOMLIB_COORDS_HEADERS defined
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: YTables.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: oj $ $Date: 2002-11-28 10:27:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_MYSQL_TABLES_HXX
#include "mysql/YTables.hxx"
#endif
#ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_
#include "mysql/YViews.hxx"
#endif
#ifndef CONNECTIVITY_MYSQL_TABLE_HXX
#include "mysql/YTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_MYSQL_CATALOG_HXX
#include "mysql/YCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace ::cppu;
using namespace connectivity::mysql;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
Reference< XNamed > OTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));
Sequence< ::rtl::OUString > sTableTypes(3);
sTableTypes[0] = s_sTableTypeView;
sTableTypes[1] = s_sTableTypeTable;
sTableTypes[2] = s_sAll; // just to be sure to include anything else ....
Any aCatalog;
if ( sCatalog.getLength() )
aCatalog <<= sCatalog;
Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);
Reference< XNamed > xRet = NULL;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() ) // there can be only one table with this name
{
// Reference<XStatement> xStmt = m_xConnection->createStatement();
// if ( xStmt.is() )
// {
// Reference< XResultSet > xPrivRes = xStmt->executeQuery();
// Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY);
// while ( xPrivRes.is() && xPrivRes->next() )
// {
// if ( xPrivRow->getString(1) )
// {
// }
// }
// }
sal_Int32 nPrivileges = Privilege::DROP |
Privilege::REFERENCE |
Privilege::ALTER |
Privilege::CREATE |
Privilege::READ |
Privilege::DELETE |
Privilege::UPDATE |
Privilege::INSERT |
Privilege::SELECT;
OMySQLTable* pRet = new OMySQLTable( this
,static_cast<OMySQLCatalog&>(m_rParent).getConnection()
,sTable
,xRow->getString(4)
,xRow->getString(5)
,sSchema
,sCatalog
,nPrivileges);
xRet = pRet;
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh( ) throw(RuntimeException)
{
static_cast<OMySQLCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
m_xMetaData = NULL;
OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection());
}
// -----------------------------------------------------------------------------
Reference< XNamed > OTables::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
if(!aName.getLength())
::dbtools::throwFunctionSequenceException(*this);
createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
ObjectIter aIter = m_aElements[_nPos];
if(!aIter->second.is()) // we want to drop a object which isn't loaded yet so we must load it
aIter->second = createObject(_sElementName);
Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(aIter->second.get(),UNO_QUERY);
sal_Bool bIsNew = sal_False;
if(xTunnel.is())
{
connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
if(pTable)
bIsNew = pTable->isNew();
}
if (!bIsNew)
{
Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");
Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
sal_Bool bIsView;
if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
aSql += ::rtl::OUString::createFromAscii("VIEW ");
else
aSql += ::rtl::OUString::createFromAscii("TABLE ");
::rtl::OUString sComposedName;
::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
aSql += sComposedName;
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
// if no exception was thrown we must delete it from the views
if ( bIsView )
{
OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews());
if ( pViews && pViews->hasByName(_sElementName) )
pViews->dropByNameImpl(_sElementName);
}
}
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
insertElement(_rsNewTable,NULL);
// notify our container listeners
ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
while (aListenerLoop.hasMoreElements())
static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS insight01 (1.3.92); FILE MERGED 2004/02/12 16:06:33 oj 1.3.92.1: #111075# fix refcount problem<commit_after>/*************************************************************************
*
* $RCSfile: YTables.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-08-02 17:08:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef CONNECTIVITY_MYSQL_TABLES_HXX
#include "mysql/YTables.hxx"
#endif
#ifndef _CONNECTIVITY_MYSQL_VIEWS_HXX_
#include "mysql/YViews.hxx"
#endif
#ifndef CONNECTIVITY_MYSQL_TABLE_HXX
#include "mysql/YTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef CONNECTIVITY_MYSQL_CATALOG_HXX
#include "mysql/YCatalog.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace ::cppu;
using namespace connectivity::mysql;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace dbtools;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
Reference< XNamed > OTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_rName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
static const ::rtl::OUString s_sTableTypeView(RTL_CONSTASCII_USTRINGPARAM("VIEW"));
static const ::rtl::OUString s_sTableTypeTable(RTL_CONSTASCII_USTRINGPARAM("TABLE"));
static const ::rtl::OUString s_sAll(RTL_CONSTASCII_USTRINGPARAM("%"));
Sequence< ::rtl::OUString > sTableTypes(3);
sTableTypes[0] = s_sTableTypeView;
sTableTypes[1] = s_sTableTypeTable;
sTableTypes[2] = s_sAll; // just to be sure to include anything else ....
Any aCatalog;
if ( sCatalog.getLength() )
aCatalog <<= sCatalog;
Reference< XResultSet > xResult = m_xMetaData->getTables(aCatalog,sSchema,sTable,sTableTypes);
Reference< XNamed > xRet = NULL;
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xResult->next() ) // there can be only one table with this name
{
// Reference<XStatement> xStmt = m_xConnection->createStatement();
// if ( xStmt.is() )
// {
// Reference< XResultSet > xPrivRes = xStmt->executeQuery();
// Reference< XRow > xPrivRow(xPrivRes,UNO_QUERY);
// while ( xPrivRes.is() && xPrivRes->next() )
// {
// if ( xPrivRow->getString(1) )
// {
// }
// }
// }
sal_Int32 nPrivileges = Privilege::DROP |
Privilege::REFERENCE |
Privilege::ALTER |
Privilege::CREATE |
Privilege::READ |
Privilege::DELETE |
Privilege::UPDATE |
Privilege::INSERT |
Privilege::SELECT;
OMySQLTable* pRet = new OMySQLTable( this
,static_cast<OMySQLCatalog&>(m_rParent).getConnection()
,sTable
,xRow->getString(4)
,xRow->getString(5)
,sSchema
,sCatalog
,nPrivileges);
xRet = pRet;
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OTables::impl_refresh( ) throw(RuntimeException)
{
static_cast<OMySQLCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
void OTables::disposing(void)
{
m_xMetaData = NULL;
OCollection::disposing();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OTables::createEmptyObject()
{
return new OMySQLTable(this,static_cast<OMySQLCatalog&>(m_rParent).getConnection());
}
// -----------------------------------------------------------------------------
Reference< XNamed > OTables::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference< XNamed > xName(_xDescriptor,UNO_QUERY);
OSL_ENSURE(xName.is(),"Must be a XName interface here !");
return xName.is() ? createObject(xName->getName()) : Reference< XNamed >();
}
// -------------------------------------------------------------------------
// XAppend
void OTables::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
if(!aName.getLength())
::dbtools::throwFunctionSequenceException(*this);
createTable(descriptor);
}
// -------------------------------------------------------------------------
// XDrop
void OTables::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
Reference< ::com::sun::star::lang::XUnoTunnel> xTunnel(getObject(_nPos),UNO_QUERY);
sal_Bool bIsNew = sal_False;
if(xTunnel.is())
{
connectivity::sdbcx::ODescriptor* pTable = (connectivity::sdbcx::ODescriptor*)xTunnel->getSomething(connectivity::sdbcx::ODescriptor::getUnoTunnelImplementationId());
if(pTable)
bIsNew = pTable->isNew();
}
if (!bIsNew)
{
Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(m_xMetaData,_sElementName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP ");
Reference<XPropertySet> xProp(xTunnel,UNO_QUERY);
sal_Bool bIsView;
if(bIsView = (xProp.is() && ::comphelper::getString(xProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))) == ::rtl::OUString::createFromAscii("VIEW"))) // here we have a view
aSql += ::rtl::OUString::createFromAscii("VIEW ");
else
aSql += ::rtl::OUString::createFromAscii("TABLE ");
::rtl::OUString sComposedName;
::dbtools::composeTableName(m_xMetaData,sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
aSql += sComposedName;
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
// if no exception was thrown we must delete it from the views
if ( bIsView )
{
OViews* pViews = static_cast<OViews*>(static_cast<OMySQLCatalog&>(m_rParent).getPrivateViews());
if ( pViews && pViews->hasByName(_sElementName) )
pViews->dropByNameImpl(_sElementName);
}
}
}
// -------------------------------------------------------------------------
void OTables::createTable( const Reference< XPropertySet >& descriptor )
{
Reference< XConnection > xConnection = static_cast<OMySQLCatalog&>(m_rParent).getConnection();
::rtl::OUString aSql = ::dbtools::createSqlCreateTableStatement(descriptor,xConnection);
Reference< XStatement > xStmt = xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -----------------------------------------------------------------------------
void OTables::appendNew(const ::rtl::OUString& _rsNewTable)
{
insertElement(_rsNewTable,NULL);
// notify our container listeners
ContainerEvent aEvent(static_cast<XContainer*>(this), makeAny(_rsNewTable), Any(), Any());
OInterfaceIteratorHelper aListenerLoop(m_aContainerListeners);
while (aListenerLoop.hasMoreElements())
static_cast<XContainerListener*>(aListenerLoop.next())->elementInserted(aEvent);
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************
** Tsunagari Tile Engine **
** measure.cpp **
** Copyright 2016-2019 Paul Merrill **
*************************************/
// **********
// 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 "core/measure.h"
#include "core/log.h"
#include "os/chrono.h"
#ifdef __APPLE__
# include <sys/kdebug_signpost.h>
# include "util/hashtable.h"
static uint32_t nextSignpost = 0;
static Hashmap<String, uint32_t> signposts;
uint32_t
getSignpost(String description) {
if (signposts.find(description) != signposts.end()) {
return signposts[description];
}
else {
Log::info("Measure",
String() << description << " is signpost " << nextSignpost);
signposts[move_(description)] = nextSignpost;
return nextSignpost++;
}
}
#endif // __APPLE__
struct TimeMeasureImpl {
String description;
TimePoint start;
#ifdef __APPLE__
uint32_t signpost;
#endif
};
TimeMeasure::TimeMeasure(String description) {
impl = new TimeMeasureImpl;
impl->description = move_(description);
impl->start = SteadyClock::now();
#ifdef __APPLE__
impl->signpost = getSignpost(impl->description);
kdebug_signpost_start(impl->signpost, 0, 0, 0, 0);
#endif
}
TimeMeasure::~TimeMeasure() {
#ifdef __APPLE__
kdebug_signpost_end(impl->signpost, 0, 0, 0, 0);
#endif
TimePoint end = SteadyClock::now();
Duration elapsed = end - impl->start;
Log::info("Measure",
String() << impl->description << " took "
<< ns_to_s_d(elapsed)
<< " seconds");
delete impl;
}
<commit_msg>measure: Inline function declarations<commit_after>/*************************************
** Tsunagari Tile Engine **
** measure.cpp **
** Copyright 2016-2019 Paul Merrill **
*************************************/
// **********
// 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 "core/measure.h"
#include "core/log.h"
#include "os/chrono.h"
#ifdef __APPLE__
# include "util/hashtable.h"
// sys/kdebug_signpost.h
extern "C" {
int kdebug_signpost_start(uint32_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t);
int kdebug_signpost_end(uint32_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t);
}
static uint32_t nextSignpost = 0;
static Hashmap<String, uint32_t> signposts;
uint32_t
getSignpost(String description) {
if (signposts.find(description) != signposts.end()) {
return signposts[description];
}
else {
Log::info("Measure",
String() << description << " is signpost " << nextSignpost);
signposts[move_(description)] = nextSignpost;
return nextSignpost++;
}
}
#endif // __APPLE__
struct TimeMeasureImpl {
String description;
TimePoint start;
#ifdef __APPLE__
uint32_t signpost;
#endif
};
TimeMeasure::TimeMeasure(String description) {
impl = new TimeMeasureImpl;
impl->description = move_(description);
impl->start = SteadyClock::now();
#ifdef __APPLE__
impl->signpost = getSignpost(impl->description);
kdebug_signpost_start(impl->signpost, 0, 0, 0, 0);
#endif
}
TimeMeasure::~TimeMeasure() {
#ifdef __APPLE__
kdebug_signpost_end(impl->signpost, 0, 0, 0, 0);
#endif
TimePoint end = SteadyClock::now();
Duration elapsed = end - impl->start;
Log::info("Measure",
String() << impl->description << " took "
<< ns_to_s_d(elapsed)
<< " seconds");
delete impl;
}
<|endoftext|>
|
<commit_before>//---------------------------------*-C++-*-----------------------------------//
/*!
* \file MC/mc/Fission_Tally.t.hh
* \author Thomas M. Evans
* \date Fri Aug 21 15:29:14 2015
* \brief Fission_Tally class definitions.
* \note Copyright (c) 2015 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#ifndef MC_mc_Fission_Tally_t_hh
#define MC_mc_Fission_Tally_t_hh
#include <cmath>
#include <algorithm>
#include "Utils/comm/global.hh"
#include "Fission_Tally.hh"
namespace profugus
{
//---------------------------------------------------------------------------//
// CONSTRUCTOR
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
*/
template <class Geometry>
Fission_Tally<Geometry>::Fission_Tally(SP_Physics physics)
: Base(physics, false)
, d_geometry(b_physics->get_geometry())
{
REQUIRE(d_geometry);
// set the tally name
set_name("fission");
// reset tally
reset();
}
//---------------------------------------------------------------------------//
// PUBLIC INTERFACE
//---------------------------------------------------------------------------//
/*!
* \brief Add a list of cells to tally.
*/
template <class Geometry>
void Fission_Tally<Geometry>::set_mesh(SP_Mesh mesh)
{
REQUIRE( mesh );
d_mesh = mesh;
// Resize result vector
d_tally.resize(mesh->num_cells(),{0.0,0.0});
d_hist.resize( mesh->num_cells(),0.0);
}
//---------------------------------------------------------------------------//
// DERIVED INTERFACE
//---------------------------------------------------------------------------//
/*
* \brief Accumulate first and second moments.
*/
template <class Geometry>
void Fission_Tally<Geometry>::end_history()
{
REQUIRE( d_tally.size() == d_mesh->num_cells() );
REQUIRE( d_hist.size() == d_mesh->num_cells() );
// Iterate through local tally results and add them to the permanent
// results
for (int cell = 0; cell < d_mesh->num_cells(); ++cell )
{
d_tally[cell].first += d_hist[cell];
d_tally[cell].second += d_hist[cell]*d_hist[cell];
}
// Clear the local tally
clear_local();
}
//---------------------------------------------------------------------------//
/*
* \brief Do post-processing on first and second moments.
*/
template <class Geometry>
void Fission_Tally<Geometry>::finalize(double num_particles)
{
REQUIRE(num_particles > 1);
// Do a global reduction on moments
std::vector<double> first( d_tally.size(), 0.0);
std::vector<double> second(d_tally.size(), 0.0);
// Write tally results into separate arrays for reduction
for( int cell = 0; cell < d_tally.size(); ++cell )
{
first[cell] = d_tally[cell].first;
second[cell] = d_tally[cell].second;
}
// Do global reductions on the moments
profugus::global_sum(&first[0], d_tally.size());
profugus::global_sum(&second[0], d_tally.size());
// Store 1/N
double inv_N = 1.0 / static_cast<double>(num_particles);
for( int cell = 0; cell < d_tally.size(); ++cell )
{
double inv_V = 1.0 / d_mesh->volume(cell);
CHECK( inv_V > 0.0 );
// Calculate means for this cell
double avg_l = first[cell] * inv_N;
double avg_l2 = second[cell] * inv_N;
// Get a reference to the moments
auto &moments = d_tally[cell];
// Store the sample mean
moments.first = avg_l * inv_V;
// Calculate the variance
double var = (avg_l2 - avg_l * avg_l) / (num_particles - 1);
// Store the error of the sample mean
moments.second = std::sqrt(var) * inv_V;
}
}
//---------------------------------------------------------------------------//
/*
* \brief Clear/re-initialize all tally values between solves.
*/
template <class Geometry>
void Fission_Tally<Geometry>::reset()
{
// Clear the local tally
clear_local();
}
//---------------------------------------------------------------------------//
/*
* \brief Track particle and tally..
*/
template <class Geometry>
void Fission_Tally<Geometry>::accumulate(double step,
const Particle_t &p)
{
// Get the cell index
Mesh::Dim_Vector ijk;
const Mesh::Space_Vector &xyz = p.geo_state().d_r;
d_mesh->find(xyz,ijk);
int cell = d_mesh->index( ijk[def::I], ijk[def::J], ijk[def::K] );
// Tally for the history
d_hist[cell] += p.wt() * step * b_physics->total(physics::NU_FISSION,p);
}
//---------------------------------------------------------------------------//
// PRIVATE FUNCTIONS
//---------------------------------------------------------------------------//
/*
* \brief Clear local values.
*/
template <class Geometry>
void Fission_Tally<Geometry>::clear_local()
{
// Clear the local tally
std::fill(d_hist.begin(), d_hist.end(), 0.0);
}
} // end namespace profugus
#endif // MC_mc_Fission_Tally_t_hh
//---------------------------------------------------------------------------//
// end of MC/mc/Fission_Tally.t.hh
//---------------------------------------------------------------------------//
<commit_msg>Fixup for edge cells in fission tally.<commit_after>//---------------------------------*-C++-*-----------------------------------//
/*!
* \file MC/mc/Fission_Tally.t.hh
* \author Thomas M. Evans
* \date Fri Aug 21 15:29:14 2015
* \brief Fission_Tally class definitions.
* \note Copyright (c) 2015 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#ifndef MC_mc_Fission_Tally_t_hh
#define MC_mc_Fission_Tally_t_hh
#include <cmath>
#include <algorithm>
#include "Utils/comm/global.hh"
#include "Fission_Tally.hh"
namespace profugus
{
//---------------------------------------------------------------------------//
// CONSTRUCTOR
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
*/
template <class Geometry>
Fission_Tally<Geometry>::Fission_Tally(SP_Physics physics)
: Base(physics, false)
, d_geometry(b_physics->get_geometry())
{
REQUIRE(d_geometry);
// set the tally name
set_name("fission");
// reset tally
reset();
}
//---------------------------------------------------------------------------//
// PUBLIC INTERFACE
//---------------------------------------------------------------------------//
/*!
* \brief Add a list of cells to tally.
*/
template <class Geometry>
void Fission_Tally<Geometry>::set_mesh(SP_Mesh mesh)
{
REQUIRE( mesh );
d_mesh = mesh;
// Resize result vector
d_tally.resize(mesh->num_cells(),{0.0,0.0});
d_hist.resize( mesh->num_cells(),0.0);
}
//---------------------------------------------------------------------------//
// DERIVED INTERFACE
//---------------------------------------------------------------------------//
/*
* \brief Accumulate first and second moments.
*/
template <class Geometry>
void Fission_Tally<Geometry>::end_history()
{
REQUIRE( d_tally.size() == d_mesh->num_cells() );
REQUIRE( d_hist.size() == d_mesh->num_cells() );
// Iterate through local tally results and add them to the permanent
// results
for (int cell = 0; cell < d_mesh->num_cells(); ++cell )
{
d_tally[cell].first += d_hist[cell];
d_tally[cell].second += d_hist[cell]*d_hist[cell];
}
// Clear the local tally
clear_local();
}
//---------------------------------------------------------------------------//
/*
* \brief Do post-processing on first and second moments.
*/
template <class Geometry>
void Fission_Tally<Geometry>::finalize(double num_particles)
{
REQUIRE(num_particles > 1);
// Do a global reduction on moments
std::vector<double> first( d_tally.size(), 0.0);
std::vector<double> second(d_tally.size(), 0.0);
// Write tally results into separate arrays for reduction
for( int cell = 0; cell < d_tally.size(); ++cell )
{
first[cell] = d_tally[cell].first;
second[cell] = d_tally[cell].second;
}
// Do global reductions on the moments
profugus::global_sum(&first[0], d_tally.size());
profugus::global_sum(&second[0], d_tally.size());
// Store 1/N
double inv_N = 1.0 / static_cast<double>(num_particles);
for( int cell = 0; cell < d_tally.size(); ++cell )
{
double inv_V = 1.0 / d_mesh->volume(cell);
CHECK( inv_V > 0.0 );
// Calculate means for this cell
double avg_l = first[cell] * inv_N;
double avg_l2 = second[cell] * inv_N;
// Get a reference to the moments
auto &moments = d_tally[cell];
// Store the sample mean
moments.first = avg_l * inv_V;
// Calculate the variance
double var = (avg_l2 - avg_l * avg_l) / (num_particles - 1);
// Store the error of the sample mean
moments.second = std::sqrt(var) * inv_V;
}
}
//---------------------------------------------------------------------------//
/*
* \brief Clear/re-initialize all tally values between solves.
*/
template <class Geometry>
void Fission_Tally<Geometry>::reset()
{
// Clear the local tally
clear_local();
}
//---------------------------------------------------------------------------//
/*
* \brief Track particle and tally..
*/
template <class Geometry>
void Fission_Tally<Geometry>::accumulate(double step,
const Particle_t &p)
{
// Get the cell index
Mesh::Dim_Vector ijk;
const Mesh::Space_Vector &xyz = p.geo_state().d_r;
d_mesh->find_upper(xyz,ijk);
Mesh::size_type cell;
bool found = d_mesh->index( ijk[def::I], ijk[def::J], ijk[def::K], cell );
if( found )
{
REQUIRE( cell >= 0 && cell < d_mesh->num_cells() );
// Tally for the history
d_hist[cell] += p.wt() * step * b_physics->total(physics::NU_FISSION,p);
}
}
//---------------------------------------------------------------------------//
// PRIVATE FUNCTIONS
//---------------------------------------------------------------------------//
/*
* \brief Clear local values.
*/
template <class Geometry>
void Fission_Tally<Geometry>::clear_local()
{
// Clear the local tally
std::fill(d_hist.begin(), d_hist.end(), 0.0);
}
} // end namespace profugus
#endif // MC_mc_Fission_Tally_t_hh
//---------------------------------------------------------------------------//
// end of MC/mc/Fission_Tally.t.hh
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* 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.
*/
/**
* net_interface_imp.cpp
*
* Network interface implementation class
*/
#include <winsock2.h>
#include <iphlpapi.h>
#include "util.h"
#include "enumeration.h"
#include "log_imp.h"
#include "jdksavdecc_pdu.h"
#include "net_interface_imp.h"
namespace avdecc_lib
{
net_interface * STDCALL create_net_interface()
{
return (new net_interface_imp());
}
net_interface_imp::net_interface_imp()
{
if(pcap_findalldevs(&all_devs, err_buf) == -1) // Retrieve the device list on the local machine.
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_findalldevs error %s", err_buf);
exit(EXIT_FAILURE);
}
for(dev = all_devs, total_devs = 0; dev; dev = dev->next)
{
total_devs++;
}
if(total_devs == 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "No interfaces found! Make sure WinPcap is installed.");
exit(EXIT_FAILURE);
}
}
net_interface_imp::~net_interface_imp()
{
pcap_freealldevs(all_devs); // Free the device list
pcap_close(pcap_interface);
}
void STDCALL net_interface_imp::destroy()
{
delete this;
}
uint32_t STDCALL net_interface_imp::devs_count()
{
return total_devs;
}
uint64_t net_interface_imp::mac_addr()
{
return mac;
}
char * STDCALL net_interface_imp::get_dev_desc_by_index(size_t dev_index)
{
uint32_t i;
for(dev = all_devs, i = 0; (i < dev_index) && (dev_index < total_devs); dev = dev->next, i++); // Get the selected interface
if(!dev->description)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface description is blank.");
}
return dev->description;
}
char * STDCALL net_interface_imp::get_dev_name_by_index(size_t dev_index)
{
uint32_t i;
for (dev = all_devs, i = 0; (i < dev_index) && (dev_index < total_devs); dev = dev->next, i++); // Get the selected interface
if (!dev->name)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface name is blank.");
}
return dev->name;
}
int STDCALL net_interface_imp::select_interface_by_num(uint32_t interface_num)
{
uint32_t index;
IP_ADAPTER_INFO *AdapterInfo;
IP_ADAPTER_INFO *Current;
ULONG AIS;
DWORD status;
int timeout_ms = NETIF_READ_TIMEOUT_MS;
if(interface_num < 1 || interface_num > total_devs)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface number out of range.");
pcap_freealldevs(all_devs); // Free the device list
exit(EXIT_FAILURE);
}
for(dev = all_devs, index = 0; index < interface_num - 1; dev = dev->next, index++); // Jump to the selected adapter
/************************************************************** Open the device ****************************************************************/
if((pcap_interface = pcap_open_live(dev->name, // Name of the device
65536, // Portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // In promiscuous mode, all packets including packets of other hosts are captured
timeout_ms, // Read timeout in ms
err_buf // Error buffer
)) == NULL)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to open the adapter. %s is not supported by WinPcap.", dev->name);
pcap_freealldevs(all_devs); // Free the device list
exit(EXIT_FAILURE);
}
/****************************** Lookup IP address ***************************/
AdapterInfo = (IP_ADAPTER_INFO *)calloc(total_devs, sizeof(IP_ADAPTER_INFO));
AIS = sizeof(IP_ADAPTER_INFO) * total_devs;
if(GetAdaptersInfo(AdapterInfo, &AIS) == ERROR_BUFFER_OVERFLOW)
{
free(AdapterInfo);
AdapterInfo = (IP_ADAPTER_INFO *)calloc(1, AIS);
if(AdapterInfo == NULL)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Allocating memory needed to call GetAdaptersinfo.", dev->name);
exit(EXIT_FAILURE);
}
status = GetAdaptersInfo(AdapterInfo, &AIS);
if(status != ERROR_SUCCESS)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "GetAdaptersInfo call in netif_win32_pcap.c failed.", dev->name);
free(AdapterInfo);
exit(EXIT_FAILURE);
}
}
for(Current = AdapterInfo; Current != NULL; Current = Current->Next)
{
if(strstr(dev->name, Current->AdapterName) != 0)
{
uint32_t my_ip;
ULONG len;
uint8_t tmp[16];
my_ip = inet_addr(Current->IpAddressList.IpAddress.String);
len = sizeof(tmp);
SendARP(my_ip ,INADDR_ANY, tmp, &len);
utility::convert_eui48_to_uint64(&tmp[0], mac);
}
}
uint16_t ether_type[1];
ether_type[0] = JDKSAVDECC_AVTP_ETHERTYPE;
set_capture_ether_type(ether_type, 0); // Set the filter
free(AdapterInfo);
return 0;
}
int net_interface_imp::set_capture_ether_type(uint16_t *ether_type, uint32_t count)
{
struct bpf_program fcode;
char ether_type_string[512];
char ether_type_single[64];
const unsigned char *ether_packet = NULL;
struct pcap_pkthdr pcap_header;
ether_type_string[0] = 0;
for(uint32_t i = 0; i < count; i++)
{
sprintf(ether_type_single, "ether proto 0x%04x", ether_type[i]);
strcat(ether_type_string, ether_type_single);
if((i + 1) < count)
{
strcat(ether_type_string, " or ");
}
}
/************************************** Compile a filter **************************************/
if(pcap_compile(pcap_interface, &fcode, ether_type_string, 1, 0) < 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to compile the packet filter.");
pcap_freealldevs(all_devs); // Free the device list
return -1;
}
/********************************** Set the filter *********************************/
if(pcap_setfilter(pcap_interface, &fcode) < 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Error setting the filter.");
pcap_freealldevs(all_devs); // Free the device list
return -1;
}
/*********** Flush any packets that might be present **********/
for(uint32_t index_j = 0; index_j < 1; index_j++)
{
ether_packet = pcap_next(pcap_interface, &pcap_header);
}
return 0;
}
int STDCALL net_interface_imp::capture_frame(const uint8_t **frame, uint16_t *frame_len)
{
struct pcap_pkthdr *header;
int error = 0;
*frame_len = 0;
error = pcap_next_ex(pcap_interface, &header, frame);
if(error > 0 )
{
cmd_frame = *frame;
*frame_len = (uint16_t)header->len;
return 1;
}
return -2; // Timeout
}
int net_interface_imp::send_frame(uint8_t *frame, size_t frame_len)
{
if(pcap_sendpacket(pcap_interface, frame, (int)frame_len) != 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_sendpacket error %s", pcap_geterr(pcap_interface));
return -1;
}
return 0;
}
}
<commit_msg>controller: lib: src: MSVC: net if, init pcap_interface pointer to nullptr<commit_after>/*
* Licensed under the MIT License (MIT)
*
* Copyright (c) 2013 AudioScience Inc.
*
* 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.
*/
/**
* net_interface_imp.cpp
*
* Network interface implementation class
*/
#include <winsock2.h>
#include <iphlpapi.h>
#include "util.h"
#include "enumeration.h"
#include "log_imp.h"
#include "jdksavdecc_pdu.h"
#include "net_interface_imp.h"
namespace avdecc_lib
{
net_interface * STDCALL create_net_interface()
{
return (new net_interface_imp());
}
net_interface_imp::net_interface_imp()
{
if(pcap_findalldevs(&all_devs, err_buf) == -1) // Retrieve the device list on the local machine.
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_findalldevs error %s", err_buf);
exit(EXIT_FAILURE);
}
for(dev = all_devs, total_devs = 0; dev; dev = dev->next)
{
total_devs++;
}
if(total_devs == 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "No interfaces found! Make sure WinPcap is installed.");
exit(EXIT_FAILURE);
}
pcap_interface = nullptr;
}
net_interface_imp::~net_interface_imp()
{
pcap_freealldevs(all_devs); // Free the device list
if (pcap_interface != nullptr)
pcap_close(pcap_interface);
}
void STDCALL net_interface_imp::destroy()
{
delete this;
}
uint32_t STDCALL net_interface_imp::devs_count()
{
return total_devs;
}
uint64_t net_interface_imp::mac_addr()
{
return mac;
}
char * STDCALL net_interface_imp::get_dev_desc_by_index(size_t dev_index)
{
uint32_t i;
for(dev = all_devs, i = 0; (i < dev_index) && (dev_index < total_devs); dev = dev->next, i++); // Get the selected interface
if(!dev->description)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface description is blank.");
}
return dev->description;
}
char * STDCALL net_interface_imp::get_dev_name_by_index(size_t dev_index)
{
uint32_t i;
for (dev = all_devs, i = 0; (i < dev_index) && (dev_index < total_devs); dev = dev->next, i++); // Get the selected interface
if (!dev->name)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface name is blank.");
}
return dev->name;
}
int STDCALL net_interface_imp::select_interface_by_num(uint32_t interface_num)
{
uint32_t index;
IP_ADAPTER_INFO *AdapterInfo;
IP_ADAPTER_INFO *Current;
ULONG AIS;
DWORD status;
int timeout_ms = NETIF_READ_TIMEOUT_MS;
if(interface_num < 1 || interface_num > total_devs)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Interface number out of range.");
pcap_freealldevs(all_devs); // Free the device list
exit(EXIT_FAILURE);
}
for(dev = all_devs, index = 0; index < interface_num - 1; dev = dev->next, index++); // Jump to the selected adapter
/************************************************************** Open the device ****************************************************************/
if((pcap_interface = pcap_open_live(dev->name, // Name of the device
65536, // Portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // In promiscuous mode, all packets including packets of other hosts are captured
timeout_ms, // Read timeout in ms
err_buf // Error buffer
)) == NULL)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to open the adapter. %s is not supported by WinPcap.", dev->name);
pcap_freealldevs(all_devs); // Free the device list
exit(EXIT_FAILURE);
}
/****************************** Lookup IP address ***************************/
AdapterInfo = (IP_ADAPTER_INFO *)calloc(total_devs, sizeof(IP_ADAPTER_INFO));
AIS = sizeof(IP_ADAPTER_INFO) * total_devs;
if(GetAdaptersInfo(AdapterInfo, &AIS) == ERROR_BUFFER_OVERFLOW)
{
free(AdapterInfo);
AdapterInfo = (IP_ADAPTER_INFO *)calloc(1, AIS);
if(AdapterInfo == NULL)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Allocating memory needed to call GetAdaptersinfo.", dev->name);
exit(EXIT_FAILURE);
}
status = GetAdaptersInfo(AdapterInfo, &AIS);
if(status != ERROR_SUCCESS)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "GetAdaptersInfo call in netif_win32_pcap.c failed.", dev->name);
free(AdapterInfo);
exit(EXIT_FAILURE);
}
}
for(Current = AdapterInfo; Current != NULL; Current = Current->Next)
{
if(strstr(dev->name, Current->AdapterName) != 0)
{
uint32_t my_ip;
ULONG len;
uint8_t tmp[16];
my_ip = inet_addr(Current->IpAddressList.IpAddress.String);
len = sizeof(tmp);
SendARP(my_ip ,INADDR_ANY, tmp, &len);
utility::convert_eui48_to_uint64(&tmp[0], mac);
}
}
uint16_t ether_type[1];
ether_type[0] = JDKSAVDECC_AVTP_ETHERTYPE;
set_capture_ether_type(ether_type, 0); // Set the filter
free(AdapterInfo);
return 0;
}
int net_interface_imp::set_capture_ether_type(uint16_t *ether_type, uint32_t count)
{
struct bpf_program fcode;
char ether_type_string[512];
char ether_type_single[64];
const unsigned char *ether_packet = NULL;
struct pcap_pkthdr pcap_header;
ether_type_string[0] = 0;
for(uint32_t i = 0; i < count; i++)
{
sprintf(ether_type_single, "ether proto 0x%04x", ether_type[i]);
strcat(ether_type_string, ether_type_single);
if((i + 1) < count)
{
strcat(ether_type_string, " or ");
}
}
/************************************** Compile a filter **************************************/
if(pcap_compile(pcap_interface, &fcode, ether_type_string, 1, 0) < 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Unable to compile the packet filter.");
pcap_freealldevs(all_devs); // Free the device list
return -1;
}
/********************************** Set the filter *********************************/
if(pcap_setfilter(pcap_interface, &fcode) < 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "Error setting the filter.");
pcap_freealldevs(all_devs); // Free the device list
return -1;
}
/*********** Flush any packets that might be present **********/
for(uint32_t index_j = 0; index_j < 1; index_j++)
{
ether_packet = pcap_next(pcap_interface, &pcap_header);
}
return 0;
}
int STDCALL net_interface_imp::capture_frame(const uint8_t **frame, uint16_t *frame_len)
{
struct pcap_pkthdr *header;
int error = 0;
*frame_len = 0;
error = pcap_next_ex(pcap_interface, &header, frame);
if(error > 0 )
{
cmd_frame = *frame;
*frame_len = (uint16_t)header->len;
return 1;
}
return -2; // Timeout
}
int net_interface_imp::send_frame(uint8_t *frame, size_t frame_len)
{
if(pcap_sendpacket(pcap_interface, frame, (int)frame_len) != 0)
{
log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "pcap_sendpacket error %s", pcap_geterr(pcap_interface));
return -1;
}
return 0;
}
}
<|endoftext|>
|
<commit_before>/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 <ts/ts.h>
#include <ts/remap.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <time.h>
#include <openssl/sha.h>
#include <string>
#include <list>
// TODO: We should eliminate this when we have unordered_map on all supported platforms
#if HAVE_UNORDERED_MAP
#include <unordered_map>
#else
#include <map>
#endif
static const char *PLUGIN_NAME = "cache_promote";
//////////////////////////////////////////////////////////////////////////////////////////////
// Note that all options for all policies has to go here. Not particularly pretty...
//
static const struct option longopt[] = {{const_cast<char *>("policy"), required_argument, NULL, 'p'},
// This is for both Chance and LRU (optional) policy
{const_cast<char *>("sample"), required_argument, NULL, 's'},
// For the LRU policy
{const_cast<char *>("buckets"), required_argument, NULL, 'b'},
{const_cast<char *>("hits"), required_argument, NULL, 'h'},
// EOF
{NULL, no_argument, NULL, '\0'}};
//////////////////////////////////////////////////////////////////////////////////////////////
// Abstract base class for all policies.
//
class PromotionPolicy
{
public:
PromotionPolicy() : _sample(0.0)
{
// This doesn't have to be perfect, since this is just chance sampling.
// coverity[dont_call]
srand48((long)time(NULL));
}
void
setSample(char *s)
{
_sample = strtof(s, NULL) / 100.0;
}
float
getSample() const
{
return _sample;
}
bool
doSample() const
{
if (_sample > 0) {
// coverity[dont_call]
double r = drand48();
if (_sample > r) {
TSDebug(PLUGIN_NAME, "checking sampling, is %f > %f? Yes!", _sample, r);
} else {
TSDebug(PLUGIN_NAME, "checking sampling, is %f > %f? No!", _sample, r);
return false;
}
}
return true;
}
virtual ~PromotionPolicy(){};
virtual bool
parseOption(int opt, char *optarg)
{
return false;
}
// These are pure virtual
virtual bool doPromote(TSHttpTxn txnp) = 0;
virtual const char *policyName() const = 0;
virtual void usage() const = 0;
private:
float _sample;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// This is the simplest of all policies, just give each request a (small)
// percentage chance to be promoted to cache.
//
class ChancePolicy : public PromotionPolicy
{
public:
bool doPromote(TSHttpTxn /* txnp ATS_UNUSED */)
{
TSDebug(PLUGIN_NAME, "ChancePolicy::doPromote(%f)", getSample());
return true;
}
void
usage() const
{
TSError(PLUGIN_NAME, "Usage: @plugin=%s.so @pparam=--policy=chance @pparam=--sample=<x>%", PLUGIN_NAME);
}
const char *
policyName() const
{
return "chance";
}
};
//////////////////////////////////////////////////////////////////////////////////////////////
// The LRU based policy keeps track of <bucket> number of URLs, with a counter for each slot.
// Objects are not promoted unless the counter reaches <hits> before it gets evicted. An
// optional <chance> parameter can be used to sample hits, this can reduce contention and
// churning in the LRU as well.
//
class LRUHash
{
friend struct LRUHashHasher;
public:
LRUHash() { TSDebug(PLUGIN_NAME, "In LRUHash()"); }
~LRUHash() { TSDebug(PLUGIN_NAME, "In ~LRUHash()"); }
LRUHash &operator=(const LRUHash &h)
{
TSDebug(PLUGIN_NAME, "copying an LRUHash object");
memcpy(_hash, h._hash, sizeof(_hash));
return *this;
}
void
init(char *data, int len)
{
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, data, len);
SHA1_Final(_hash, &sha);
}
private:
u_char _hash[SHA_DIGEST_LENGTH];
};
struct LRUHashHasher {
bool operator()(const LRUHash *s1, const LRUHash *s2) const { return 0 == memcmp(s1->_hash, s2->_hash, sizeof(s2->_hash)); }
size_t operator()(const LRUHash *s) const { return *((size_t *)s->_hash) ^ *((size_t *)(s->_hash + 9)); }
};
typedef std::pair<LRUHash, unsigned> LRUEntry;
typedef std::list<LRUEntry> LRUList;
static LRUEntry NULL_LRU_ENTRY; // Used to create an "empty" new LRUEntry
// TODO: We should eliminate this when we have unordered_map on all supported platforms.
#if HAVE_UNORDERED_MAP
#include <unordered_map>
typedef std::unordered_map<const LRUHash *, LRUList::iterator, LRUHashHasher, LRUHashHasher> LRUMap;
#else
#include <map>
typedef std::map<LRUHash *, LRUList::iterator> LRUMap;
#endif
class LRUPolicy : public PromotionPolicy
{
public:
LRUPolicy() : PromotionPolicy(), _buckets(1000), _hits(10), _lock(TSMutexCreate()) {}
~LRUPolicy()
{
TSDebug(PLUGIN_NAME, "deleting LRUPolicy object");
TSMutexLock(_lock);
_map.clear();
_list.clear();
_freelist.clear();
TSMutexUnlock(_lock);
// ToDo: Destroy mutex ? TS-1432
}
bool
parseOption(int opt, char *optarg)
{
switch (opt) {
case 'b':
_buckets = static_cast<unsigned>(strtol(optarg, NULL, 10));
break;
case 'h':
_hits = static_cast<unsigned>(strtol(optarg, NULL, 10));
break;
default:
// All other options are unsupported for this policy
return false;
}
// This doesn't have to be perfect, since this is just chance sampling.
// coverity[dont_call]
srand48((long)time(NULL) ^ (long)getpid() ^ (long)getppid());
#if HAVE_UNORDERED_MAP
_map.reserve(_buckets);
#endif
return true;
}
bool
doPromote(TSHttpTxn txnp)
{
LRUHash hash;
LRUMap::iterator map_it;
int url_len = 0;
char *url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_len);
bool ret = false;
TSDebug(PLUGIN_NAME, "LRUPolicy::doPromote(%.*s ...)", url_len > 30 ? 30 : url_len, url);
hash.init(url, url_len);
// We have to hold the lock across all list and hash access / updates
TSMutexLock(_lock);
map_it = _map.find(&hash);
if (_map.end() != map_it) {
// We have an entry in the LRU
if (++(map_it->second->second) >= _hits) {
// Promoted! Cleanup the LRU, and signal success. Save the promoted entry on the freelist.
TSDebug(PLUGIN_NAME, "saving the LRUEntry to the freelist");
_freelist.splice(_freelist.begin(), _list, map_it->second);
_map.erase(map_it->first);
ret = true;
} else {
// It's still not promoted, make sure it's moved to the front of the list
_list.splice(_list.begin(), _list, map_it->second);
}
} else {
// New LRU entry for the URL, try to repurpose the list entry as much as possible
if (_list.size() >= _buckets) {
TSDebug(PLUGIN_NAME, "repurposing last LRUHash entry");
_list.splice(_list.begin(), _list, --_list.end());
_map.erase(&(_list.begin()->first));
} else if (_freelist.size() > 0) {
TSDebug(PLUGIN_NAME, "reusing LRUEntry from freelist");
_list.splice(_list.begin(), _freelist, _freelist.begin());
} else {
TSDebug(PLUGIN_NAME, "creating new LRUEntry");
_list.push_front(NULL_LRU_ENTRY);
}
// Update the "new" LRUEntry and add it to the hash
_list.begin()->first = hash;
_list.begin()->second = 1;
_map[&(_list.begin()->first)] = _list.begin();
}
TSMutexUnlock(_lock);
return ret;
}
void
usage() const
{
TSError(PLUGIN_NAME, "Usage: @plugin=%s.so @pparam=--policy=lru @pparam=--buckets=<n> --hits=<m> --sample=<x>", PLUGIN_NAME);
}
const char *
policyName() const
{
return "LRU";
}
private:
unsigned _buckets;
unsigned _hits;
// For the LRU
TSMutex _lock;
LRUMap _map;
LRUList _list, _freelist;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// This holds the configuration for a remap rule, as well as parses the configurations.
//
class PromotionConfig
{
public:
PromotionConfig() : _policy(NULL) {}
~PromotionConfig() { delete _policy; }
PromotionPolicy *
getPolicy() const
{
return _policy;
}
// Parse the command line arguments to the plugin, and instantiate the appropriate policy
bool
factory(int argc, char *argv[])
{
optind = 0;
while (true) {
int opt = getopt_long(argc, (char *const *)argv, "psbh", longopt, NULL);
if (opt == -1) {
break;
} else if (opt == 'p') {
if (0 == strncasecmp(optarg, "chance", 6)) {
_policy = new ChancePolicy();
} else if (0 == strncasecmp(optarg, "lru", 3)) {
_policy = new LRUPolicy();
} else {
TSError("Unknown policy --policy=%s", optarg);
return false;
}
if (_policy) {
TSDebug(PLUGIN_NAME, "created remap with cache promotion policy = %s", _policy->policyName());
}
} else {
if (_policy) {
// The --sample (-s) option is allowed for all configs, but only after --policy is specified.
if (opt == 's') {
_policy->setSample(optarg);
} else {
if (!_policy->parseOption(opt, optarg)) {
TSError("The specified policy (%s) does not support the -%c option", _policy->policyName(), opt);
delete _policy;
_policy = NULL;
return false;
}
}
} else {
TSError("The --policy=<n> parameter must come first on the remap configuration");
return false;
}
}
}
return true;
}
private:
PromotionPolicy *_policy;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// Main "plugin", a TXN hook in the TS_HTTP_READ_CACHE_HDR_HOOK. Unless the policy allows
// caching, we will turn off the cache from here on for the TXN.
//
// NOTE: This is not optimal, the goal was to handle this before we lock the URL in the
// cache. However, that does not work. Hence, for now, we also schedule the continuation
// for READ_RESPONSE_HDR such that we can turn off the actual cache write.
//
static int
cont_handle_policy(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
PromotionConfig *config = static_cast<PromotionConfig *>(TSContDataGet(contp));
int obj_status;
switch (event) {
// Main HOOK
case TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE:
if (TS_ERROR != TSHttpTxnCacheLookupStatusGet(txnp, &obj_status)) {
switch (obj_status) {
case TS_CACHE_LOOKUP_MISS:
case TS_CACHE_LOOKUP_SKIPPED:
if (config->getPolicy()->doSample() && config->getPolicy()->doPromote(txnp)) {
TSDebug(PLUGIN_NAME, "cache-status is %d, and leaving cache on (promoted)", obj_status);
} else {
TSDebug(PLUGIN_NAME, "cache-status is %d, and turning off the cache (not promoted)", obj_status);
TSHttpTxnHookAdd(txnp, TS_HTTP_READ_RESPONSE_HDR_HOOK, contp);
}
break;
default:
// Do nothing, just let it handle the lookup.
TSDebug(PLUGIN_NAME, "cache-status is %d (hit), nothing to do", obj_status);
break;
}
}
break;
// Temporaray hack, to deal with the fact that we can turn off the cache earlier
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
TSHttpTxnServerRespNoStoreSet(txnp, 1);
break;
// Should not happen
default:
TSDebug(PLUGIN_NAME, "Unhandled event %d", (int)event);
break;
}
// Reenable and continue with the state machine.
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialize the plugin as a remap plugin.
//
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
{
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] - Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16,
(api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS; /* success */
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
PromotionConfig *config = new PromotionConfig;
--argc;
++argv;
if (config->factory(argc, argv)) {
TSCont contp = TSContCreate(cont_handle_policy, TSMutexCreate());
TSContDataSet(contp, static_cast<void *>(config));
*ih = static_cast<void *>(contp);
return TS_SUCCESS;
} else {
delete config;
return TS_ERROR;
}
}
void
TSRemapDeleteInstance(void *ih)
{
TSCont contp = static_cast<TSCont>(ih);
PromotionConfig *config = static_cast<PromotionConfig *>(TSContDataGet(contp));
delete config;
TSContDestroy(contp);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Schedule the cache-read continuation for this remap rule.
//
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * /* ATS_UNUSED rri */)
{
if (NULL == ih) {
TSDebug(PLUGIN_NAME, "No ACLs configured, this is probably a plugin bug");
} else {
TSCont contp = static_cast<TSCont>(ih);
TSHttpTxnHookAdd(rh, TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK, contp);
}
return TSREMAP_NO_REMAP;
}
<commit_msg>TS-3561 Destroy the mutex on cleanup<commit_after>/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 <ts/ts.h>
#include <ts/remap.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <time.h>
#include <openssl/sha.h>
#include <string>
#include <list>
// TODO: We should eliminate this when we have unordered_map on all supported platforms
#if HAVE_UNORDERED_MAP
#include <unordered_map>
#else
#include <map>
#endif
static const char *PLUGIN_NAME = "cache_promote";
//////////////////////////////////////////////////////////////////////////////////////////////
// Note that all options for all policies has to go here. Not particularly pretty...
//
static const struct option longopt[] = {{const_cast<char *>("policy"), required_argument, NULL, 'p'},
// This is for both Chance and LRU (optional) policy
{const_cast<char *>("sample"), required_argument, NULL, 's'},
// For the LRU policy
{const_cast<char *>("buckets"), required_argument, NULL, 'b'},
{const_cast<char *>("hits"), required_argument, NULL, 'h'},
// EOF
{NULL, no_argument, NULL, '\0'}};
//////////////////////////////////////////////////////////////////////////////////////////////
// Abstract base class for all policies.
//
class PromotionPolicy
{
public:
PromotionPolicy() : _sample(0.0)
{
// This doesn't have to be perfect, since this is just chance sampling.
// coverity[dont_call]
srand48((long)time(NULL));
}
void
setSample(char *s)
{
_sample = strtof(s, NULL) / 100.0;
}
float
getSample() const
{
return _sample;
}
bool
doSample() const
{
if (_sample > 0) {
// coverity[dont_call]
double r = drand48();
if (_sample > r) {
TSDebug(PLUGIN_NAME, "checking sampling, is %f > %f? Yes!", _sample, r);
} else {
TSDebug(PLUGIN_NAME, "checking sampling, is %f > %f? No!", _sample, r);
return false;
}
}
return true;
}
virtual ~PromotionPolicy(){};
virtual bool
parseOption(int opt, char *optarg)
{
return false;
}
// These are pure virtual
virtual bool doPromote(TSHttpTxn txnp) = 0;
virtual const char *policyName() const = 0;
virtual void usage() const = 0;
private:
float _sample;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// This is the simplest of all policies, just give each request a (small)
// percentage chance to be promoted to cache.
//
class ChancePolicy : public PromotionPolicy
{
public:
bool doPromote(TSHttpTxn /* txnp ATS_UNUSED */)
{
TSDebug(PLUGIN_NAME, "ChancePolicy::doPromote(%f)", getSample());
return true;
}
void
usage() const
{
TSError(PLUGIN_NAME, "Usage: @plugin=%s.so @pparam=--policy=chance @pparam=--sample=<x>%", PLUGIN_NAME);
}
const char *
policyName() const
{
return "chance";
}
};
//////////////////////////////////////////////////////////////////////////////////////////////
// The LRU based policy keeps track of <bucket> number of URLs, with a counter for each slot.
// Objects are not promoted unless the counter reaches <hits> before it gets evicted. An
// optional <chance> parameter can be used to sample hits, this can reduce contention and
// churning in the LRU as well.
//
class LRUHash
{
friend struct LRUHashHasher;
public:
LRUHash() { TSDebug(PLUGIN_NAME, "In LRUHash()"); }
~LRUHash() { TSDebug(PLUGIN_NAME, "In ~LRUHash()"); }
LRUHash &operator=(const LRUHash &h)
{
TSDebug(PLUGIN_NAME, "copying an LRUHash object");
memcpy(_hash, h._hash, sizeof(_hash));
return *this;
}
void
init(char *data, int len)
{
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, data, len);
SHA1_Final(_hash, &sha);
}
private:
u_char _hash[SHA_DIGEST_LENGTH];
};
struct LRUHashHasher {
bool operator()(const LRUHash *s1, const LRUHash *s2) const { return 0 == memcmp(s1->_hash, s2->_hash, sizeof(s2->_hash)); }
size_t operator()(const LRUHash *s) const { return *((size_t *)s->_hash) ^ *((size_t *)(s->_hash + 9)); }
};
typedef std::pair<LRUHash, unsigned> LRUEntry;
typedef std::list<LRUEntry> LRUList;
static LRUEntry NULL_LRU_ENTRY; // Used to create an "empty" new LRUEntry
// TODO: We should eliminate this when we have unordered_map on all supported platforms.
#if HAVE_UNORDERED_MAP
#include <unordered_map>
typedef std::unordered_map<const LRUHash *, LRUList::iterator, LRUHashHasher, LRUHashHasher> LRUMap;
#else
#include <map>
typedef std::map<LRUHash *, LRUList::iterator> LRUMap;
#endif
class LRUPolicy : public PromotionPolicy
{
public:
LRUPolicy() : PromotionPolicy(), _buckets(1000), _hits(10), _lock(TSMutexCreate()) {}
~LRUPolicy()
{
TSDebug(PLUGIN_NAME, "deleting LRUPolicy object");
TSMutexLock(_lock);
_map.clear();
_list.clear();
_freelist.clear();
TSMutexUnlock(_lock);
TSMutexDestroy(_lock);
}
bool
parseOption(int opt, char *optarg)
{
switch (opt) {
case 'b':
_buckets = static_cast<unsigned>(strtol(optarg, NULL, 10));
break;
case 'h':
_hits = static_cast<unsigned>(strtol(optarg, NULL, 10));
break;
default:
// All other options are unsupported for this policy
return false;
}
// This doesn't have to be perfect, since this is just chance sampling.
// coverity[dont_call]
srand48((long)time(NULL) ^ (long)getpid() ^ (long)getppid());
#if HAVE_UNORDERED_MAP
_map.reserve(_buckets);
#endif
return true;
}
bool
doPromote(TSHttpTxn txnp)
{
LRUHash hash;
LRUMap::iterator map_it;
int url_len = 0;
char *url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_len);
bool ret = false;
TSDebug(PLUGIN_NAME, "LRUPolicy::doPromote(%.*s ...)", url_len > 30 ? 30 : url_len, url);
hash.init(url, url_len);
// We have to hold the lock across all list and hash access / updates
TSMutexLock(_lock);
map_it = _map.find(&hash);
if (_map.end() != map_it) {
// We have an entry in the LRU
if (++(map_it->second->second) >= _hits) {
// Promoted! Cleanup the LRU, and signal success. Save the promoted entry on the freelist.
TSDebug(PLUGIN_NAME, "saving the LRUEntry to the freelist");
_freelist.splice(_freelist.begin(), _list, map_it->second);
_map.erase(map_it->first);
ret = true;
} else {
// It's still not promoted, make sure it's moved to the front of the list
_list.splice(_list.begin(), _list, map_it->second);
}
} else {
// New LRU entry for the URL, try to repurpose the list entry as much as possible
if (_list.size() >= _buckets) {
TSDebug(PLUGIN_NAME, "repurposing last LRUHash entry");
_list.splice(_list.begin(), _list, --_list.end());
_map.erase(&(_list.begin()->first));
} else if (_freelist.size() > 0) {
TSDebug(PLUGIN_NAME, "reusing LRUEntry from freelist");
_list.splice(_list.begin(), _freelist, _freelist.begin());
} else {
TSDebug(PLUGIN_NAME, "creating new LRUEntry");
_list.push_front(NULL_LRU_ENTRY);
}
// Update the "new" LRUEntry and add it to the hash
_list.begin()->first = hash;
_list.begin()->second = 1;
_map[&(_list.begin()->first)] = _list.begin();
}
TSMutexUnlock(_lock);
return ret;
}
void
usage() const
{
TSError(PLUGIN_NAME, "Usage: @plugin=%s.so @pparam=--policy=lru @pparam=--buckets=<n> --hits=<m> --sample=<x>", PLUGIN_NAME);
}
const char *
policyName() const
{
return "LRU";
}
private:
unsigned _buckets;
unsigned _hits;
// For the LRU
TSMutex _lock;
LRUMap _map;
LRUList _list, _freelist;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// This holds the configuration for a remap rule, as well as parses the configurations.
//
class PromotionConfig
{
public:
PromotionConfig() : _policy(NULL) {}
~PromotionConfig() { delete _policy; }
PromotionPolicy *
getPolicy() const
{
return _policy;
}
// Parse the command line arguments to the plugin, and instantiate the appropriate policy
bool
factory(int argc, char *argv[])
{
optind = 0;
while (true) {
int opt = getopt_long(argc, (char *const *)argv, "psbh", longopt, NULL);
if (opt == -1) {
break;
} else if (opt == 'p') {
if (0 == strncasecmp(optarg, "chance", 6)) {
_policy = new ChancePolicy();
} else if (0 == strncasecmp(optarg, "lru", 3)) {
_policy = new LRUPolicy();
} else {
TSError("Unknown policy --policy=%s", optarg);
return false;
}
if (_policy) {
TSDebug(PLUGIN_NAME, "created remap with cache promotion policy = %s", _policy->policyName());
}
} else {
if (_policy) {
// The --sample (-s) option is allowed for all configs, but only after --policy is specified.
if (opt == 's') {
_policy->setSample(optarg);
} else {
if (!_policy->parseOption(opt, optarg)) {
TSError("The specified policy (%s) does not support the -%c option", _policy->policyName(), opt);
delete _policy;
_policy = NULL;
return false;
}
}
} else {
TSError("The --policy=<n> parameter must come first on the remap configuration");
return false;
}
}
}
return true;
}
private:
PromotionPolicy *_policy;
};
//////////////////////////////////////////////////////////////////////////////////////////////
// Main "plugin", a TXN hook in the TS_HTTP_READ_CACHE_HDR_HOOK. Unless the policy allows
// caching, we will turn off the cache from here on for the TXN.
//
// NOTE: This is not optimal, the goal was to handle this before we lock the URL in the
// cache. However, that does not work. Hence, for now, we also schedule the continuation
// for READ_RESPONSE_HDR such that we can turn off the actual cache write.
//
static int
cont_handle_policy(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = static_cast<TSHttpTxn>(edata);
PromotionConfig *config = static_cast<PromotionConfig *>(TSContDataGet(contp));
int obj_status;
switch (event) {
// Main HOOK
case TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE:
if (TS_ERROR != TSHttpTxnCacheLookupStatusGet(txnp, &obj_status)) {
switch (obj_status) {
case TS_CACHE_LOOKUP_MISS:
case TS_CACHE_LOOKUP_SKIPPED:
if (config->getPolicy()->doSample() && config->getPolicy()->doPromote(txnp)) {
TSDebug(PLUGIN_NAME, "cache-status is %d, and leaving cache on (promoted)", obj_status);
} else {
TSDebug(PLUGIN_NAME, "cache-status is %d, and turning off the cache (not promoted)", obj_status);
TSHttpTxnHookAdd(txnp, TS_HTTP_READ_RESPONSE_HDR_HOOK, contp);
}
break;
default:
// Do nothing, just let it handle the lookup.
TSDebug(PLUGIN_NAME, "cache-status is %d (hit), nothing to do", obj_status);
break;
}
}
break;
// Temporaray hack, to deal with the fact that we can turn off the cache earlier
case TS_EVENT_HTTP_READ_RESPONSE_HDR:
TSHttpTxnServerRespNoStoreSet(txnp, 1);
break;
// Should not happen
default:
TSDebug(PLUGIN_NAME, "Unhandled event %d", (int)event);
break;
}
// Reenable and continue with the state machine.
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialize the plugin as a remap plugin.
//
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
{
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] - Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16,
(api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS; /* success */
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
PromotionConfig *config = new PromotionConfig;
--argc;
++argv;
if (config->factory(argc, argv)) {
TSCont contp = TSContCreate(cont_handle_policy, TSMutexCreate());
TSContDataSet(contp, static_cast<void *>(config));
*ih = static_cast<void *>(contp);
return TS_SUCCESS;
} else {
delete config;
return TS_ERROR;
}
}
void
TSRemapDeleteInstance(void *ih)
{
TSCont contp = static_cast<TSCont>(ih);
PromotionConfig *config = static_cast<PromotionConfig *>(TSContDataGet(contp));
delete config;
TSContDestroy(contp);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Schedule the cache-read continuation for this remap rule.
//
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo * /* ATS_UNUSED rri */)
{
if (NULL == ih) {
TSDebug(PLUGIN_NAME, "No ACLs configured, this is probably a plugin bug");
} else {
TSCont contp = static_cast<TSCont>(ih);
TSHttpTxnHookAdd(rh, TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK, contp);
}
return TSREMAP_NO_REMAP;
}
<|endoftext|>
|
<commit_before>#include "Arduino.h"
#include "Denbit.h"
#include "config.h"
Denbit::Denbit()
{
// Single LEDs
pinMode(DENBIT_GREEN, OUTPUT);
pinMode(DENBIT_RED, OUTPUT);
// RGB led
pinMode(DENBIT_RGB_RED, OUTPUT);
pinMode(DENBIT_RGB_GREEN, OUTPUT);
pinMode(DENBIT_RGB_BLUE, OUTPUT);
// Switches
pinMode(DENBIT_SW1, INPUT_PULLUP);
pinMode(DENBIT_SW2, INPUT); // No pullup on pin 16
digitalWrite(DENBIT_GREEN, LOW);
digitalWrite(DENBIT_RED, LOW);
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
}
/**
* Turn off the RGB led.
*/
void Denbit::RGBoff() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
}
/**
* Let this library control All the OTA setup.
*/
void Denbit::OTAsetup() {
// First connect to the WiFi network.
WiFi.mode(WIFI_STA);
WiFi.begin(denbit_wifi_ssid, denbit_wifi_password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
// Show the connection failure with a red led.
digitalWrite(DENBIT_RGB_RED, HIGH);
delay(1000);
// Try again...
ESP.restart();
}
// denbit_name comes from config.h
ArduinoOTA.setHostname(denbit_name);
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
// Flash the RGB led.
byte val = (progress / (total / 100)) * 2;
analogWrite(DENBIT_RGB_RED, val);
analogWrite(DENBIT_RGB_GREEN, val);
analogWrite(DENBIT_RGB_BLUE, val);
});
ArduinoOTA.onError([](ota_error_t error) {
// Restart on failure.
ESP.restart();
});
// When programming starts.
ArduinoOTA.onStart([]() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
// Turn on the red led.
digitalWrite(12, HIGH);
// Turn off the green led.
digitalWrite(13, LOW);
});
// When programming ends..
ArduinoOTA.onEnd([]() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
// Turn off the red led.
digitalWrite(12, LOW);
// Turn on the green led.
digitalWrite(13, HIGH);
});
// Start the Over The Air service.
ArduinoOTA.begin();
}
/**
* Setup and initialise OTA.
*/
void Denbit::OTAinit() {
ArduinoOTA.setHostname(denbit_name);
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
// Flash the RGB led.
byte val = (progress / (total / 100)) * 2;
analogWrite(DENBIT_RGB_RED, val);
analogWrite(DENBIT_RGB_GREEN, val);
analogWrite(DENBIT_RGB_BLUE, val);
});
ArduinoOTA.onError([](ota_error_t error) {
// Restart on failure.
ESP.restart();
});
}
/**
* Alias for ArduinoOTA.handle();
*/
void Denbit::OTAhandle() {
ArduinoOTA.handle();
}
<commit_msg>Use the default name if the config did not get changed<commit_after>#include "Arduino.h"
#include "Denbit.h"
#include "config.h"
Denbit::Denbit()
{
// Single LEDs
pinMode(DENBIT_GREEN, OUTPUT);
pinMode(DENBIT_RED, OUTPUT);
// RGB led
pinMode(DENBIT_RGB_RED, OUTPUT);
pinMode(DENBIT_RGB_GREEN, OUTPUT);
pinMode(DENBIT_RGB_BLUE, OUTPUT);
// Switches
pinMode(DENBIT_SW1, INPUT_PULLUP);
pinMode(DENBIT_SW2, INPUT); // No pullup on pin 16
digitalWrite(DENBIT_GREEN, LOW);
digitalWrite(DENBIT_RED, LOW);
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
}
/**
* Turn off the RGB led.
*/
void Denbit::RGBoff() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
}
/**
* Let this library control All the OTA setup.
*/
void Denbit::OTAsetup() {
// First connect to the WiFi network.
WiFi.mode(WIFI_STA);
WiFi.begin(denbit_wifi_ssid, denbit_wifi_password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
// Show the connection failure with a red led.
digitalWrite(DENBIT_RGB_RED, HIGH);
delay(1000);
// Try again...
ESP.restart();
}
// denbit_name comes from config.h
if (strcmp(denbit_name, "xxx") == 0) {
// Use the autogenerated name as the name didn't get changed.
} else {
ArduinoOTA.setHostname(denbit_name);
}
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
// Flash the RGB led.
byte val = (progress / (total / 100)) * 2;
analogWrite(DENBIT_RGB_RED, val);
analogWrite(DENBIT_RGB_GREEN, val);
analogWrite(DENBIT_RGB_BLUE, val);
});
ArduinoOTA.onError([](ota_error_t error) {
// Restart on failure.
ESP.restart();
});
// When programming starts.
ArduinoOTA.onStart([]() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
// Turn on the red led.
digitalWrite(12, HIGH);
// Turn off the green led.
digitalWrite(13, LOW);
});
// When programming ends..
ArduinoOTA.onEnd([]() {
digitalWrite(DENBIT_RGB_RED, LOW);
digitalWrite(DENBIT_RGB_GREEN, LOW);
digitalWrite(DENBIT_RGB_BLUE, LOW);
// Turn off the red led.
digitalWrite(12, LOW);
// Turn on the green led.
digitalWrite(13, HIGH);
});
// Start the Over The Air service.
ArduinoOTA.begin();
}
/**
* Setup and initialise OTA.
*/
void Denbit::OTAinit() {
ArduinoOTA.setHostname(denbit_name);
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
// Flash the RGB led.
byte val = (progress / (total / 100)) * 2;
analogWrite(DENBIT_RGB_RED, val);
analogWrite(DENBIT_RGB_GREEN, val);
analogWrite(DENBIT_RGB_BLUE, val);
});
ArduinoOTA.onError([](ota_error_t error) {
// Restart on failure.
ESP.restart();
});
}
/**
* Alias for ArduinoOTA.handle();
*/
void Denbit::OTAhandle() {
ArduinoOTA.handle();
}
<|endoftext|>
|
<commit_before>#include <string>
#include <sstream>
#include <iostream>
#include <utility>
#include <glad/glad.h>
#include "vfs.hpp"
#include "texture.hpp"
#if USE_LIB_PNGCPP
#include "png.hpp"
#endif
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_STDIO
//exclude image formats
#define STBI_NO_PIC
#define STBI_NO_PNM
#define STBI_NO_PSD
#define STBI_NO_GIF
// This leaves us with the following supported image formats:
// jpg png bmp tga hdr
#include "stb_image.h"
namespace ORCore
{
static int _texCount = 0;
static GLuint _currentBoundtexture = 0;
#if USE_LIB_PNGCPP
Image loadPNG(std::string filename)
{
std::istringstream file(ORCore::read_file( filename, FileMode::Binary ));
png::image<png::rgba_pixel> image(file);
auto pixelBuffer = image.get_pixbuf();
Image imgData;
imgData.width = image.get_width();
imgData.height = image.get_height();
imgData.length = imgData.width * imgData.height * 4;
imgData.pixelData = std::make_unique<unsigned char[]>(imgData.length);
int i = 0;
for (int x = 0;x < imgData.width; x++) {
for (int y = 0; y < imgData.height; y++) {
auto pixel = pixelBuffer.get_pixel(x, y);
i = 4 * (y * imgData.width + x);
imgData.pixelData[i+0] = pixel.red;
imgData.pixelData[i+1] = pixel.green;
imgData.pixelData[i+2] = pixel.blue;
imgData.pixelData[i+3] = pixel.alpha;
}
}
return imgData;
}
#endif
Image loadSTB(std::string filename)
{
std::string mem_buf = ORCore::read_file( filename, FileMode::Binary );
Image imgData;
auto conv_mem = std::make_unique<unsigned char[]>( mem_buf.size() );
// to prevent potential issues convert each value seperately
// one could cast the int* to unsigned int* however this could have large issues there can be
// platform differances on how this is imeplemented.
for (size_t i = 0; i < mem_buf.size(); i++) {
conv_mem[i] = static_cast<unsigned char>(mem_buf[i]);
}
unsigned char *img_buf;
int comp;
img_buf = stbi_load_from_memory( &conv_mem[0], mem_buf.size(), &imgData.width, &imgData.height, &comp, 0 );
if ( img_buf == nullptr )
std::cout << "Failed to get image data" << std::endl;
imgData.length = imgData.width * imgData.height * 4;
imgData.pixelData = std::make_unique<unsigned char[]>(imgData.length);
// We have to copy the data out of the returned data from stb.
// This was an issue with the previous implementation where the data was destroyed before
// opengl could copy the data to the gpu. OpenGL may even require the image data to be persistant
// cpu side if not it may be a good idea to do so anyways.
int i, j;
// currently the main reason the loop is setup like this, is that it makes it a bit easier to convert RGB to RGBA.
for (int x = 0;x < imgData.width; x++) {
for (int y = 0; y < imgData.height; y++) {
i = 4 * (y * imgData.width + x);
j = comp * (y * imgData.width + x);
imgData.pixelData[i+0] = img_buf[j+0];
imgData.pixelData[i+1] = img_buf[j+1];
imgData.pixelData[i+2] = img_buf[j+2];
if (comp == 4) {
imgData.pixelData[i+3] = img_buf[j+3];
} else {
imgData.pixelData[i+3] = 255U;
}
}
}
stbi_image_free( img_buf );
return std::move(imgData);
}
Texture::Texture(std::string path, ShaderProgram *program)
: m_path(path), m_program(program)
{
_texCount++;
m_texUnitID = _texCount;
#if USE_LIB_PNGCPP
m_image = ORCore::loadPNG(m_path);
#else
m_image = ORCore::loadSTB(m_path);
#endif
m_texSampID = m_program->uniform_attribute("textureSampler");
GLuint texid;
glGenTextures(1, &texid);
m_texID = texid;
glBindTexture(GL_TEXTURE_2D, m_texID);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_image.width, m_image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(m_image.pixelData.get())[0]);
}
void Texture::bind()
{
if (_currentBoundtexture != m_texUnitID) {
_currentBoundtexture = m_texUnitID;
glActiveTexture(GL_TEXTURE0+m_texUnitID);
glBindTexture(GL_TEXTURE_2D, m_texID);
m_program->set_uniform(m_texSampID, m_texUnitID);
std::cout << "Texture bound" << std::endl;
}
}
}
<commit_msg>Switch some includes to using brackets.<commit_after>#include <string>
#include <sstream>
#include <iostream>
#include <utility>
#include <glad/glad.h>
#include "vfs.hpp"
#include "texture.hpp"
#if USE_LIB_PNGCPP
#include <png.hpp>
#endif
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_STDIO
//exclude image formats
#define STBI_NO_PIC
#define STBI_NO_PNM
#define STBI_NO_PSD
#define STBI_NO_GIF
// This leaves us with the following supported image formats:
// jpg png bmp tga hdr
#include <stb_image.h>
namespace ORCore
{
static int _texCount = 0;
static GLuint _currentBoundtexture = 0;
#if USE_LIB_PNGCPP
Image loadPNG(std::string filename)
{
std::istringstream file(ORCore::read_file( filename, FileMode::Binary ));
png::image<png::rgba_pixel> image(file);
auto pixelBuffer = image.get_pixbuf();
Image imgData;
imgData.width = image.get_width();
imgData.height = image.get_height();
imgData.length = imgData.width * imgData.height * 4;
imgData.pixelData = std::make_unique<unsigned char[]>(imgData.length);
int i = 0;
for (int x = 0;x < imgData.width; x++) {
for (int y = 0; y < imgData.height; y++) {
auto pixel = pixelBuffer.get_pixel(x, y);
i = 4 * (y * imgData.width + x);
imgData.pixelData[i+0] = pixel.red;
imgData.pixelData[i+1] = pixel.green;
imgData.pixelData[i+2] = pixel.blue;
imgData.pixelData[i+3] = pixel.alpha;
}
}
return imgData;
}
#endif
Image loadSTB(std::string filename)
{
std::string mem_buf = ORCore::read_file( filename, FileMode::Binary );
Image imgData;
auto conv_mem = std::make_unique<unsigned char[]>( mem_buf.size() );
// to prevent potential issues convert each value seperately
// one could cast the int* to unsigned int* however this could have large issues there can be
// platform differances on how this is imeplemented.
for (size_t i = 0; i < mem_buf.size(); i++) {
conv_mem[i] = static_cast<unsigned char>(mem_buf[i]);
}
unsigned char *img_buf;
int comp;
img_buf = stbi_load_from_memory( &conv_mem[0], mem_buf.size(), &imgData.width, &imgData.height, &comp, 0 );
if ( img_buf == nullptr )
std::cout << "Failed to get image data" << std::endl;
imgData.length = imgData.width * imgData.height * 4;
imgData.pixelData = std::make_unique<unsigned char[]>(imgData.length);
// We have to copy the data out of the returned data from stb.
// This was an issue with the previous implementation where the data was destroyed before
// opengl could copy the data to the gpu. OpenGL may even require the image data to be persistant
// cpu side if not it may be a good idea to do so anyways.
int i, j;
// currently the main reason the loop is setup like this, is that it makes it a bit easier to convert RGB to RGBA.
for (int x = 0;x < imgData.width; x++) {
for (int y = 0; y < imgData.height; y++) {
i = 4 * (y * imgData.width + x);
j = comp * (y * imgData.width + x);
imgData.pixelData[i+0] = img_buf[j+0];
imgData.pixelData[i+1] = img_buf[j+1];
imgData.pixelData[i+2] = img_buf[j+2];
if (comp == 4) {
imgData.pixelData[i+3] = img_buf[j+3];
} else {
imgData.pixelData[i+3] = 255U;
}
}
}
stbi_image_free( img_buf );
return std::move(imgData);
}
Texture::Texture(std::string path, ShaderProgram *program)
: m_path(path), m_program(program)
{
_texCount++;
m_texUnitID = _texCount;
#if USE_LIB_PNGCPP
m_image = ORCore::loadPNG(m_path);
#else
m_image = ORCore::loadSTB(m_path);
#endif
m_texSampID = m_program->uniform_attribute("textureSampler");
GLuint texid;
glGenTextures(1, &texid);
m_texID = texid;
glBindTexture(GL_TEXTURE_2D, m_texID);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_image.width, m_image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(m_image.pixelData.get())[0]);
}
void Texture::bind()
{
if (_currentBoundtexture != m_texUnitID) {
_currentBoundtexture = m_texUnitID;
glActiveTexture(GL_TEXTURE0+m_texUnitID);
glBindTexture(GL_TEXTURE_2D, m_texID);
m_program->set_uniform(m_texSampID, m_texUnitID);
std::cout << "Texture bound" << std::endl;
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "../stack/stack.h"
using namespace std;
int calculatePostfix(const string& expression);
bool isDigit(char symbol);
int calculateBinary(int leftOperand, int rightOperand, char operation);
void inputExpression(string& expression);
int main()
{
cout << "Enter an expression: \n";
string expression = "";
inputExpression(expression);
int result = calculatePostfix(expression);
cout << "Result is " << result << endl;
return 0;
}
void inputExpression(string& expression)
{
getline(cin, expression);
}
int calculatePostfix(const string& expression)
{
Stack* stack = createStack();
for (auto symbol : expression) {
if (isDigit(symbol)) {
int digit = symbol - '0';
push(digit, stack);
} else if (symbol != ' '){
int right = pop(stack);
int left = pop(stack);
int value = calculateBinary(left, right, symbol);
push(value, stack);
}
}
int result = top(stack);
deleteStack(stack);
return result;
}
bool isDigit(char symbol)
{
return (int(symbol) >= 48 && int(symbol) <= 57); // 0 - 9
}
int calculateBinary(int leftOperand, int rightOperand, char operation)
{
int result = 0;
switch (operation) {
case '+':
result = leftOperand + rightOperand;
break;
case '-':
result = leftOperand - rightOperand;
break;
case '*':
result = leftOperand * rightOperand;
break;
case '/':
result = leftOperand / rightOperand;
break;
default:
break;
}
return result;
}
<commit_msg>updated in view of changing stack<commit_after>#include <iostream>
#include <string>
#include "../stack/stack.h"
using namespace std;
int calculatePostfix(const string& expression);
bool isDigit(char symbol);
int calculateBinary(int leftOperand, int rightOperand, char operation);
void inputExpression(string& expression);
int main()
{
cout << "Enter an expression: \n";
string expression = "";
inputExpression(expression);
int result = calculatePostfix(expression);
cout << "Result is " << result << endl;
return 0;
}
void inputExpression(string& expression)
{
getline(cin, expression);
}
int calculatePostfix(const string& expression)
{
Stack* stack = createStack();
for (auto symbol : expression) {
if (isDigit(symbol)) {
int digit = symbol - '0';
push(digit, stack);
} else if (symbol != ' '){
int right = 0;
pop(stack, right);
int left = 0;
pop(stack, left);
int value = calculateBinary(left, right, symbol);
push(value, stack);
}
}
int result = 0;
top(stack, result);
deleteStack(stack);
return result;
}
bool isDigit(char symbol)
{
return (int(symbol) >= 48 && int(symbol) <= 57); // 0 - 9
}
int calculateBinary(int leftOperand, int rightOperand, char operation)
{
int result = 0;
switch (operation) {
case '+':
result = leftOperand + rightOperand;
break;
case '-':
result = leftOperand - rightOperand;
break;
case '*':
result = leftOperand * rightOperand;
break;
case '/':
result = leftOperand / rightOperand;
break;
default:
break;
}
return result;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680)
#define REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680
#include <algorithm>
#include <vector>
#include "ReusableArenaBlock.hpp"
#include "ArenaAllocator.hpp"
template<class ObjectType>
class ReusableArenaAllocator : public ArenaAllocator<ObjectType,
ReusableArenaBlock<ObjectType> >
{
public:
typedef ReusableArenaBlock<ObjectType> ReusableArenaBlockType;
typedef typename ReusableArenaBlockType::size_type size_type;
typedef ArenaAllocator<ObjectType,
ReusableArenaBlockType> BaseClassType;
// $$$ ToDo: This typedef is here because of a bug in gcc.
#if defined (XALAN_NO_NAMESPACES)
typedef vector<ReusableArenaBlockType*> ArenaBlockListType;
#else
typedef std::vector<ReusableArenaBlockType*> ArenaBlockListType;
#endif
/*
* Construct an instance that will allocate blocks of the specified size.
*
* @param theBlockSize The block size.
*/
ReusableArenaAllocator(size_type theBlockSize) :
BaseClassType(theBlockSize),
m_lastBlockReferenced(0)
{
}
virtual
~ReusableArenaAllocator()
{
}
/*
* Destroy the object, and free the block for re-use.
*
* @param theObject the address of the object.
* @return true if the object was deleted, false if not.
*/
bool
destroyObject(ObjectType* theObject)
{
bool fSucess = false;
// Check this, just in case...
if (m_lastBlockReferenced != 0 && m_lastBlockReferenced->ownsObject(theObject) == true)
{
m_lastBlockReferenced->destroyObject(theObject);
fSucess = true;
}
else
{
// Note that this-> is required by template lookup rules.
const typename ArenaBlockListType::reverse_iterator theEnd = this->m_blocks.rend();
typename ArenaBlockListType::reverse_iterator i = this->m_blocks.rbegin();
while(i != theEnd)
{
if ((*i)->ownsObject(theObject) == true)
{
m_lastBlockReferenced = *i;
m_lastBlockReferenced->destroyObject(theObject);
fSucess = true;
break;
}
else
{
++i;
}
}
}
return fSucess;
}
/*
* Allocate a block of the appropriate size for an
* object. Call commitAllocation() when after
* the object is successfully constructed. You _must_
* commit an allocation before performing any other
* operation on the allocator.
*
* @return A pointer to a block of memory
*/
virtual ObjectType*
allocateBlock()
{
if (m_lastBlockReferenced == 0 ||
m_lastBlockReferenced->blockAvailable() == false)
{
// Search back for a block with some space available...
const typename ArenaBlockListType::reverse_iterator theEnd = this->m_blocks.rend();
// Note that this-> is required by template lookup rules.
typename ArenaBlockListType::reverse_iterator i = this->m_blocks.rbegin();
while(i != theEnd)
{
assert(*i != 0);
if (*i != m_lastBlockReferenced && (*i)->blockAvailable() == true)
{
// Ahh, found one with free space.
m_lastBlockReferenced = *i;
break;
}
else
{
++i;
}
}
if (i == theEnd)
{
// No blocks have free space available, so create a new block, and
// push it on the list.
// Note that this-> is required by template lookup rules.
m_lastBlockReferenced = new ReusableArenaBlockType(this->m_blockSize);
this->m_blocks.push_back(m_lastBlockReferenced);
}
}
assert(m_lastBlockReferenced != 0 && m_lastBlockReferenced->blockAvailable() == true);
return m_lastBlockReferenced->allocateBlock();
}
/*
* Commits the allocation of the previous
* allocateBlock() call.
*
* @param theObject A pointer to a block of memory
*/
virtual void
commitAllocation(ObjectType* theObject)
{
// Note that this-> is required by template lookup rules.
assert(this->m_blocks.size() != 0 && m_lastBlockReferenced != 0 && m_lastBlockReferenced->ownsBlock(theObject) == true);
m_lastBlockReferenced->commitAllocation(theObject);
assert(m_lastBlockReferenced->ownsObject(theObject) == true);
}
virtual void
reset()
{
m_lastBlockReferenced = 0;
BaseClassType::reset();
}
virtual bool
ownsObject(const ObjectType* theObject) const
{
bool fResult = false;
// If no block has ever been referenced, then we haven't allocated
// any objects.
if (m_lastBlockReferenced != 0)
{
// Check the last referenced block first.
fResult = m_lastBlockReferenced->ownsObject(theObject);
if (fResult == false)
{
fResult = BaseClassType::ownsObject(theObject);
}
}
return fResult;
}
private:
// Not defined...
ReusableArenaAllocator(const ReusableArenaAllocator<ObjectType>&);
ReusableArenaAllocator<ObjectType>&
operator=(const ReusableArenaAllocator<ObjectType>&);
// Data members...
ReusableArenaBlockType* m_lastBlockReferenced;
};
#endif // !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680)
<commit_msg>Fixed typo.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680)
#define REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680
#include <algorithm>
#include <vector>
#include "ReusableArenaBlock.hpp"
#include "ArenaAllocator.hpp"
template<class ObjectType>
class ReusableArenaAllocator : public ArenaAllocator<ObjectType,
ReusableArenaBlock<ObjectType> >
{
public:
typedef ReusableArenaBlock<ObjectType> ReusableArenaBlockType;
typedef typename ReusableArenaBlockType::size_type size_type;
typedef ArenaAllocator<ObjectType,
ReusableArenaBlockType> BaseClassType;
// $$$ ToDo: This typedef is here because of a bug in gcc.
#if defined (XALAN_NO_NAMESPACES)
typedef vector<ReusableArenaBlockType*> ArenaBlockListType;
#else
typedef std::vector<ReusableArenaBlockType*> ArenaBlockListType;
#endif
/*
* Construct an instance that will allocate blocks of the specified size.
*
* @param theBlockSize The block size.
*/
ReusableArenaAllocator(size_type theBlockSize) :
BaseClassType(theBlockSize),
m_lastBlockReferenced(0)
{
}
virtual
~ReusableArenaAllocator()
{
}
/*
* Destroy the object, and free the block for re-use.
*
* @param theObject the address of the object.
* @return true if the object was deleted, false if not.
*/
bool
destroyObject(ObjectType* theObject)
{
bool fSuccess = false;
// Check this, just in case...
if (m_lastBlockReferenced != 0 && m_lastBlockReferenced->ownsObject(theObject) == true)
{
m_lastBlockReferenced->destroyObject(theObject);
fSuccess = true;
}
else
{
// Note that this-> is required by template lookup rules.
const typename ArenaBlockListType::reverse_iterator theEnd = this->m_blocks.rend();
typename ArenaBlockListType::reverse_iterator i = this->m_blocks.rbegin();
while(i != theEnd)
{
if ((*i)->ownsObject(theObject) == true)
{
m_lastBlockReferenced = *i;
m_lastBlockReferenced->destroyObject(theObject);
fSuccess = true;
break;
}
else
{
++i;
}
}
}
return fSuccess;
}
/*
* Allocate a block of the appropriate size for an
* object. Call commitAllocation() when after
* the object is successfully constructed. You _must_
* commit an allocation before performing any other
* operation on the allocator.
*
* @return A pointer to a block of memory
*/
virtual ObjectType*
allocateBlock()
{
if (m_lastBlockReferenced == 0 ||
m_lastBlockReferenced->blockAvailable() == false)
{
// Search back for a block with some space available...
const typename ArenaBlockListType::reverse_iterator theEnd = this->m_blocks.rend();
// Note that this-> is required by template lookup rules.
typename ArenaBlockListType::reverse_iterator i = this->m_blocks.rbegin();
while(i != theEnd)
{
assert(*i != 0);
if (*i != m_lastBlockReferenced && (*i)->blockAvailable() == true)
{
// Ahh, found one with free space.
m_lastBlockReferenced = *i;
break;
}
else
{
++i;
}
}
if (i == theEnd)
{
// No blocks have free space available, so create a new block, and
// push it on the list.
// Note that this-> is required by template lookup rules.
m_lastBlockReferenced = new ReusableArenaBlockType(this->m_blockSize);
this->m_blocks.push_back(m_lastBlockReferenced);
}
}
assert(m_lastBlockReferenced != 0 && m_lastBlockReferenced->blockAvailable() == true);
return m_lastBlockReferenced->allocateBlock();
}
/*
* Commits the allocation of the previous
* allocateBlock() call.
*
* @param theObject A pointer to a block of memory
*/
virtual void
commitAllocation(ObjectType* theObject)
{
// Note that this-> is required by template lookup rules.
assert(this->m_blocks.size() != 0 && m_lastBlockReferenced != 0 && m_lastBlockReferenced->ownsBlock(theObject) == true);
m_lastBlockReferenced->commitAllocation(theObject);
assert(m_lastBlockReferenced->ownsObject(theObject) == true);
}
virtual void
reset()
{
m_lastBlockReferenced = 0;
BaseClassType::reset();
}
virtual bool
ownsObject(const ObjectType* theObject) const
{
bool fResult = false;
// If no block has ever been referenced, then we haven't allocated
// any objects.
if (m_lastBlockReferenced != 0)
{
// Check the last referenced block first.
fResult = m_lastBlockReferenced->ownsObject(theObject);
if (fResult == false)
{
fResult = BaseClassType::ownsObject(theObject);
}
}
return fResult;
}
private:
// Not defined...
ReusableArenaAllocator(const ReusableArenaAllocator<ObjectType>&);
ReusableArenaAllocator<ObjectType>&
operator=(const ReusableArenaAllocator<ObjectType>&);
// Data members...
ReusableArenaBlockType* m_lastBlockReferenced;
};
#endif // !defined(REUSABLEARENAALLOCATOR_INCLUDE_GUARD_1357924680)
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015 Anon authors, see AUTHORS file.
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 "tls_pipe.h"
///////////////////////////////////////////////////////////////
// an implementation of an openssl "BIO" based on anon's fiberpipe
// unlike some other non-blocking openssl implementations, this solution
// does fiber-friendly reads/writes within the read/write callback,
// making the read/write appear blocking from the perspective of openssl.
#define BIO_TYPE_FIBER_PIPE (53 | 0x0400 | 0x0100) /* '53' is our custom type, 4, and 1 are BIO_TYPE_SOURCE_SINK and BIO_TYPE_DESCRIPTOR */
static int fp_write(BIO *h, const char *buf, int num);
static int fp_read(BIO *h, char *buf, int size);
static int fp_puts(BIO *h, const char *str);
static int fp_gets(BIO *h, char *buf, int size);
static long fp_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int fp_new(BIO *h);
static int fp_free(BIO *data);
static BIO_METHOD methods_fdp =
{
BIO_TYPE_FIBER_PIPE,
"fiber_pipe",
fp_write,
fp_read,
fp_puts,
fp_gets,
fp_ctrl,
fp_new,
fp_free,
NULL,
};
namespace
{
class fp_pipe
{
public:
fp_pipe(std::unique_ptr<fiber_pipe> &&pipe)
: pipe_(std::move(pipe)),
hit_fiber_io_error_(false),
hit_fiber_io_timeout_error_(false)
{
}
std::unique_ptr<fiber_pipe> pipe_;
bool hit_fiber_io_error_;
bool hit_fiber_io_timeout_error_;
};
} // namespace
static BIO *BIO_new_fp(std::unique_ptr<fiber_pipe> &&pipe)
{
BIO *b = BIO_new(&methods_fdp);
if (b == 0)
return 0;
b->ptr = new fp_pipe(std::move(pipe));
return b;
}
static int fp_new(BIO *b)
{
b->init = 1;
b->ptr = NULL;
return 1;
}
static int fp_free(BIO *b)
{
if (b == NULL)
return 0;
auto p = reinterpret_cast<fp_pipe *>(b->ptr);
if (p)
delete p;
b->ptr = 0;
return 1;
}
static int fp_read(BIO *b, char *out, int outl)
{
auto p = reinterpret_cast<fp_pipe *>(b->ptr);
if (p)
{
try
{
int ret = p->pipe_->read(out, outl);
return ret;
}
catch (const fiber_io_error &)
{
p->hit_fiber_io_error_ = true;
}
catch(const fiber_io_timeout_error &)
{
p->hit_fiber_io_timeout_error_ = true;
}
catch (...)
{
}
}
return -1;
}
static int fp_write(BIO *b, const char *in, int inl)
{
auto p = reinterpret_cast<fp_pipe *>(b->ptr);
if (p)
{
try
{
p->pipe_->write(in, inl);
return inl;
}
catch (const fiber_io_error &)
{
p->hit_fiber_io_error_ = true;
}
catch (const fiber_io_timeout_error &)
{
p->hit_fiber_io_timeout_error_ = true;
}
catch (...)
{
}
}
return -1;
}
static long fp_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret = 1;
switch (cmd)
{
case BIO_CTRL_RESET:
anon_log("fp_ctrl BIO_CTRL_RESET");
break;
case BIO_CTRL_EOF:
anon_log("fp_ctrl BIO_CTRL_EOF");
break;
case BIO_CTRL_INFO:
anon_log("fp_ctrl BIO_CTRL_INFO");
break;
case BIO_CTRL_SET:
anon_log("fp_ctrl BIO_CTRL_SET");
break;
case BIO_CTRL_GET:
anon_log("fp_ctrl BIO_CTRL_GET");
break;
case BIO_CTRL_PUSH:
//anon_log("fp_ctrl BIO_CTRL_PUSH");
break;
case BIO_CTRL_POP:
//anon_log("fp_ctrl BIO_CTRL_POP");
break;
case BIO_CTRL_GET_CLOSE:
anon_log("fp_ctrl BIO_CTRL_GET_CLOSE");
break;
case BIO_CTRL_SET_CLOSE:
anon_log("fp_ctrl BIO_CTRL_SET_CLOSE");
break;
case BIO_CTRL_PENDING:
anon_log("fp_ctrl BIO_CTRL_PENDING");
ret = 0;
break;
case BIO_CTRL_FLUSH:
//anon_log("fp_ctrl BIO_CTRL_FLUSH");
break;
case BIO_CTRL_DUP:
anon_log("fp_ctrl BIO_CTRL_DUP");
break;
case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
// anon_log("fp_ctrl BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT");
break;
case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
ret = 28;
break;
case BIO_CTRL_DGRAM_QUERY_MTU:
ret = 1400;
break;
case BIO_CTRL_DGRAM_SET_MTU:
ret = num;
break;
case BIO_CTRL_WPENDING:
// anon_log("fp_ctl BIO_CTRL_WPENDING");
break;
default:
anon_log("fp_ctrl unknown: " << cmd);
ret = 0;
break;
}
return ret;
}
static int fp_puts(BIO *b, const char *str)
{
return fp_write(b, str, strlen(str));
}
static int fp_gets(BIO *b, char *buf, int size)
{
int ret = 0;
char *ptr = buf;
char *end = buf + size - 1;
while ((ptr < end) && (fp_read(b, ptr, 1) > 0) && (ptr[0] != '\n'))
ptr++;
ptr[0] = 0;
return strlen(buf);
}
/////////////////////////////////////////////////////////////////////////////////
namespace
{
struct auto_bio
{
auto_bio(BIO *bio)
: bio_(bio)
{
if (!bio_)
throw_ssl_error();
}
~auto_bio()
{
if (bio_)
BIO_free(bio_);
}
operator BIO *() { return bio_; }
BIO *release()
{
auto bio = bio_;
bio_ = 0;
return bio;
}
BIO *bio_;
};
void throw_ssl_error_(BIO *fpb)
{
auto p = reinterpret_cast<fp_pipe *>(fpb->ptr);
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 1");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 1");
else
throw_ssl_error();
}
static void throw_ssl_error_(BIO *fpb, unsigned long err)
{
auto p = reinterpret_cast<fp_pipe *>(fpb->ptr);
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 2");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 2");
else
throw_ssl_error(err);
}
void throw_ssl_io_error_(BIO *fpb, unsigned long err)
{
auto p = reinterpret_cast<fp_pipe *>(fpb->ptr);
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 3");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 3");
else
throw_ssl_io_error(err);
}
} // namespace
//////////////////////////////////////////////////////////////////////////////////
tls_pipe::tls_pipe(std::unique_ptr<fiber_pipe> &&pipe, bool client, bool verify_peer,
bool doSNI, const char *host_name, const tls_context &context)
: fp_(pipe.get())
{
auto_bio fp_bio(BIO_new_fp(std::move(pipe)));
auto_bio ssl_bio(BIO_new_ssl(context, client));
BIO_push(ssl_bio, fp_bio);
BIO_get_ssl(ssl_bio, &ssl_);
if (!ssl_)
throw_ssl_error_(fp_bio);
if (doSNI && host_name)
SSL_set_tlsext_host_name(ssl_, host_name);
if (BIO_do_handshake(ssl_bio) != 1)
throw_ssl_error_(fp_bio);
if (verify_peer)
{
if (host_name)
{
X509 *cert = SSL_get_peer_certificate(ssl_);
if (cert && verify_host_name(cert, host_name))
{
X509_free(cert);
}
else
{
if (cert)
X509_free(cert);
throw_ssl_error_(fp_bio, X509_V_ERR_APPLICATION_VERIFICATION);
}
}
auto res = SSL_get_verify_result(ssl_);
if (res != X509_V_OK)
throw_ssl_error_(fp_bio, (unsigned long)res);
}
ssl_bio_ = ssl_bio.release();
fp_bio_ = fp_bio.release();
}
tls_pipe::~tls_pipe()
{
// if we get here, and no one has done an SSL shutdown yet,
// we _dont_ want to have the BIO_free try to send more data
// (that can fail, and throw, etc...)
SSL_set_quiet_shutdown(ssl_, 1);
BIO_free(ssl_bio_);
BIO_free(fp_bio_);
}
size_t tls_pipe::read(void *buff, size_t len) const
{
auto ret = SSL_read(ssl_, buff, len);
if (ret <= 0)
throw_ssl_io_error_(fp_bio_, SSL_get_error(ssl_, ret));
return ret;
}
void tls_pipe::shutdown()
{
SSL_shutdown(ssl_);
}
//#define ANON_SLOW_TLS_WRITES 50
void tls_pipe::write(const void *buff, size_t len) const
{
size_t tot_bytes = 0;
const char *buf = (const char *)buff;
while (tot_bytes < len)
{
#ifdef ANON_SLOW_TLS_WRITES
fiber::msleep(ANON_SLOW_TLS_WRITES);
auto written = SSL_write(ssl_, &buf[tot_bytes], 1);
#else
auto written = SSL_write(ssl_, &buf[tot_bytes], len - tot_bytes);
#endif
if (written < 0)
throw_ssl_io_error_(fp_bio_, SSL_get_error(ssl_, written));
tot_bytes += written;
}
}
void tls_pipe::limit_io_block_time(int seconds)
{
fp_->limit_io_block_time(seconds);
}
<commit_msg>openssl 1.1 compatibility update<commit_after>/*
Copyright (c) 2015 Anon authors, see AUTHORS file.
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 "tls_pipe.h"
///////////////////////////////////////////////////////////////
// an implementation of an openssl "BIO" based on anon's fiberpipe
// unlike some other non-blocking openssl implementations, this solution
// does fiber-friendly reads/writes within the read/write callback,
// making the read/write appear blocking from the perspective of openssl.
#define BIO_TYPE_FIBER_PIPE (53 | 0x0400 | 0x0100) /* '53' is our custom type, 4, and 1 are BIO_TYPE_SOURCE_SINK and BIO_TYPE_DESCRIPTOR */
static int fp_write(BIO *h, const char *buf, int num);
static int fp_read(BIO *h, char *buf, int size);
static int fp_puts(BIO *h, const char *str);
static int fp_gets(BIO *h, char *buf, int size);
static long fp_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int fp_new(BIO *h);
static int fp_free(BIO *data);
namespace
{
std::mutex mtx;
BIO_METHOD* biom = 0;
BIO_METHOD* create_biom()
{
std::unique_lock<std::mutex> l(mtx);
if (biom)
return biom;
auto index = BIO_get_new_index();
biom = BIO_meth_new(index, "fiber_pipe");
BIO_meth_set_write(biom, fp_write);
BIO_meth_set_read(biom, fp_read);
BIO_meth_set_puts(biom, fp_puts);
BIO_meth_set_gets(biom, fp_gets);
BIO_meth_set_ctrl(biom, fp_ctrl);
BIO_meth_set_create(biom, fp_new);
BIO_meth_set_destroy(biom, fp_free);
return biom;
}
class fp_pipe
{
public:
fp_pipe(std::unique_ptr<fiber_pipe> &&pipe)
: pipe_(std::move(pipe)),
hit_fiber_io_error_(false),
hit_fiber_io_timeout_error_(false)
{
}
std::unique_ptr<fiber_pipe> pipe_;
bool hit_fiber_io_error_;
bool hit_fiber_io_timeout_error_;
};
} // namespace
static BIO *BIO_new_fp(std::unique_ptr<fiber_pipe> &&pipe)
{
BIO *b = BIO_new(create_biom());
if (b == 0)
return 0;
BIO_set_data(b, new fp_pipe(std::move(pipe)));
return b;
}
static int fp_new(BIO *b)
{
//b->init = 1;
BIO_set_data(b, 0);
return 1;
}
static int fp_free(BIO *b)
{
if (b == NULL)
return 0;
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(b));
if (p)
delete p;
BIO_set_data(b, 0);
return 1;
}
static int fp_read(BIO *b, char *out, int outl)
{
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(b));
if (p)
{
try
{
int ret = p->pipe_->read(out, outl);
return ret;
}
catch (const fiber_io_error &)
{
p->hit_fiber_io_error_ = true;
}
catch(const fiber_io_timeout_error &)
{
p->hit_fiber_io_timeout_error_ = true;
}
catch (...)
{
}
}
return -1;
}
static int fp_write(BIO *b, const char *in, int inl)
{
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(b));
if (p)
{
try
{
p->pipe_->write(in, inl);
return inl;
}
catch (const fiber_io_error &)
{
p->hit_fiber_io_error_ = true;
}
catch (const fiber_io_timeout_error &)
{
p->hit_fiber_io_timeout_error_ = true;
}
catch (...)
{
}
}
return -1;
}
static long fp_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret = 1;
switch (cmd)
{
case BIO_CTRL_RESET:
anon_log("fp_ctrl BIO_CTRL_RESET");
break;
case BIO_CTRL_EOF:
anon_log("fp_ctrl BIO_CTRL_EOF");
break;
case BIO_CTRL_INFO:
anon_log("fp_ctrl BIO_CTRL_INFO");
break;
case BIO_CTRL_SET:
anon_log("fp_ctrl BIO_CTRL_SET");
break;
case BIO_CTRL_GET:
anon_log("fp_ctrl BIO_CTRL_GET");
break;
case BIO_CTRL_PUSH:
//anon_log("fp_ctrl BIO_CTRL_PUSH");
break;
case BIO_CTRL_POP:
//anon_log("fp_ctrl BIO_CTRL_POP");
break;
case BIO_CTRL_GET_CLOSE:
anon_log("fp_ctrl BIO_CTRL_GET_CLOSE");
break;
case BIO_CTRL_SET_CLOSE:
anon_log("fp_ctrl BIO_CTRL_SET_CLOSE");
break;
case BIO_CTRL_PENDING:
anon_log("fp_ctrl BIO_CTRL_PENDING");
ret = 0;
break;
case BIO_CTRL_FLUSH:
//anon_log("fp_ctrl BIO_CTRL_FLUSH");
break;
case BIO_CTRL_DUP:
anon_log("fp_ctrl BIO_CTRL_DUP");
break;
case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
// anon_log("fp_ctrl BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT");
break;
case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
ret = 28;
break;
case BIO_CTRL_DGRAM_QUERY_MTU:
ret = 1400;
break;
case BIO_CTRL_DGRAM_SET_MTU:
ret = num;
break;
case BIO_CTRL_WPENDING:
// anon_log("fp_ctl BIO_CTRL_WPENDING");
break;
default:
anon_log("fp_ctrl unknown: " << cmd);
ret = 0;
break;
}
return ret;
}
static int fp_puts(BIO *b, const char *str)
{
return fp_write(b, str, strlen(str));
}
static int fp_gets(BIO *b, char *buf, int size)
{
int ret = 0;
char *ptr = buf;
char *end = buf + size - 1;
while ((ptr < end) && (fp_read(b, ptr, 1) > 0) && (ptr[0] != '\n'))
ptr++;
ptr[0] = 0;
return strlen(buf);
}
/////////////////////////////////////////////////////////////////////////////////
namespace
{
struct auto_bio
{
auto_bio(BIO *bio)
: bio_(bio)
{
if (!bio_)
throw_ssl_error();
}
~auto_bio()
{
if (bio_)
BIO_free(bio_);
}
operator BIO *() { return bio_; }
BIO *release()
{
auto bio = bio_;
bio_ = 0;
return bio;
}
BIO *bio_;
};
void throw_ssl_error_(BIO *fpb)
{
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(fpb));
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 1");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 1");
else
throw_ssl_error();
}
static void throw_ssl_error_(BIO *fpb, unsigned long err)
{
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(fpb));
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 2");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 2");
else
throw_ssl_error(err);
}
void throw_ssl_io_error_(BIO *fpb, unsigned long err)
{
auto p = reinterpret_cast<fp_pipe *>(BIO_get_data(fpb));
if (p->hit_fiber_io_error_)
throw fiber_io_error("fiber io error during tls 3");
else if (p->hit_fiber_io_timeout_error_)
throw fiber_io_timeout_error("fiber io timeout error during tls 3");
else
throw_ssl_io_error(err);
}
} // namespace
//////////////////////////////////////////////////////////////////////////////////
tls_pipe::tls_pipe(std::unique_ptr<fiber_pipe> &&pipe, bool client, bool verify_peer,
bool doSNI, const char *host_name, const tls_context &context)
: fp_(pipe.get())
{
auto_bio fp_bio(BIO_new_fp(std::move(pipe)));
auto_bio ssl_bio(BIO_new_ssl(context, client));
BIO_push(ssl_bio, fp_bio);
BIO_get_ssl(ssl_bio, &ssl_);
if (!ssl_)
throw_ssl_error_(fp_bio);
if (doSNI && host_name)
SSL_set_tlsext_host_name(ssl_, host_name);
if (BIO_do_handshake(ssl_bio) != 1)
throw_ssl_error_(fp_bio);
if (verify_peer)
{
if (host_name)
{
X509 *cert = SSL_get_peer_certificate(ssl_);
if (cert && verify_host_name(cert, host_name))
{
X509_free(cert);
}
else
{
if (cert)
X509_free(cert);
throw_ssl_error_(fp_bio, X509_V_ERR_APPLICATION_VERIFICATION);
}
}
auto res = SSL_get_verify_result(ssl_);
if (res != X509_V_OK)
throw_ssl_error_(fp_bio, (unsigned long)res);
}
ssl_bio_ = ssl_bio.release();
fp_bio_ = fp_bio.release();
}
tls_pipe::~tls_pipe()
{
// if we get here, and no one has done an SSL shutdown yet,
// we _dont_ want to have the BIO_free try to send more data
// (that can fail, and throw, etc...)
SSL_set_quiet_shutdown(ssl_, 1);
BIO_free(ssl_bio_);
BIO_free(fp_bio_);
}
size_t tls_pipe::read(void *buff, size_t len) const
{
auto ret = SSL_read(ssl_, buff, len);
if (ret <= 0)
throw_ssl_io_error_(fp_bio_, SSL_get_error(ssl_, ret));
return ret;
}
void tls_pipe::shutdown()
{
SSL_shutdown(ssl_);
}
//#define ANON_SLOW_TLS_WRITES 50
void tls_pipe::write(const void *buff, size_t len) const
{
size_t tot_bytes = 0;
const char *buf = (const char *)buff;
while (tot_bytes < len)
{
#ifdef ANON_SLOW_TLS_WRITES
fiber::msleep(ANON_SLOW_TLS_WRITES);
auto written = SSL_write(ssl_, &buf[tot_bytes], 1);
#else
auto written = SSL_write(ssl_, &buf[tot_bytes], len - tot_bytes);
#endif
if (written < 0)
throw_ssl_io_error_(fp_bio_, SSL_get_error(ssl_, written));
tot_bytes += written;
}
}
void tls_pipe::limit_io_block_time(int seconds)
{
fp_->limit_io_block_time(seconds);
}
<|endoftext|>
|
<commit_before>//===-RTLs/generic-64bit/src/rtl.cpp - Target RTLs Implementation - C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// RTL for generic 64-bit machine
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <dlfcn.h>
#include <ffi.h>
#include <gelf.h>
#include <link.h>
#include <list>
#include <string>
#include <vector>
#include "omptargetplugin.h"
#ifndef TARGET_NAME
#define TARGET_NAME Generic ELF - 64bit
#endif
#ifndef TARGET_ELF_ID
#define TARGET_ELF_ID 0
#endif
#ifdef OMPTARGET_DEBUG
static int DebugLevel = 0;
#define GETNAME2(name) #name
#define GETNAME(name) GETNAME2(name)
#define DP(...) \
do { \
if (DebugLevel > 0) { \
DEBUGP("Target " GETNAME(TARGET_NAME) " RTL", __VA_ARGS__); \
} \
} while (false)
#else // OMPTARGET_DEBUG
#define DP(...) {}
#endif // OMPTARGET_DEBUG
#include "../../common/elf_common.c"
#define NUMBER_OF_DEVICES 4
#define OFFLOADSECTIONNAME ".omp_offloading.entries"
/// Array of Dynamic libraries loaded for this target.
struct DynLibTy {
char *FileName;
void *Handle;
};
/// Keep entries table per device.
struct FuncOrGblEntryTy {
__tgt_target_table Table;
};
/// Class containing all the device information.
class RTLDeviceInfoTy {
std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries;
public:
std::list<DynLibTy> DynLibs;
// Record entry point associated with device.
void createOffloadTable(int32_t device_id, __tgt_offload_entry *begin,
__tgt_offload_entry *end) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncGblEntries[device_id].emplace_back();
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
E.Table.EntriesBegin = begin;
E.Table.EntriesEnd = end;
}
// Return true if the entry is associated with device.
bool findOffloadEntry(int32_t device_id, void *addr) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
for (__tgt_offload_entry *i = E.Table.EntriesBegin, *e = E.Table.EntriesEnd;
i < e; ++i) {
if (i->addr == addr)
return true;
}
return false;
}
// Return the pointer to the target entries table.
__tgt_target_table *getOffloadEntriesTable(int32_t device_id) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
return &E.Table;
}
RTLDeviceInfoTy(int32_t num_devices) {
#ifdef OMPTARGET_DEBUG
if (char *envStr = getenv("LIBOMPTARGET_DEBUG")) {
DebugLevel = std::stoi(envStr);
}
#endif // OMPTARGET_DEBUG
FuncGblEntries.resize(num_devices);
}
~RTLDeviceInfoTy() {
// Close dynamic libraries
for (auto &lib : DynLibs) {
if (lib.Handle) {
dlclose(lib.Handle);
remove(lib.FileName);
}
}
}
};
static RTLDeviceInfoTy DeviceInfo(NUMBER_OF_DEVICES);
#ifdef __cplusplus
extern "C" {
#endif
int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
// If we don't have a valid ELF ID we can just fail.
#if TARGET_ELF_ID < 1
return 0;
#else
return elf_check_machine(image, TARGET_ELF_ID);
#endif
}
int32_t __tgt_rtl_number_of_devices() { return NUMBER_OF_DEVICES; }
int32_t __tgt_rtl_init_device(int32_t device_id) { return OFFLOAD_SUCCESS; }
__tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
__tgt_device_image *image) {
DP("Dev %d: load binary from " DPxMOD " image\n", device_id,
DPxPTR(image->ImageStart));
assert(device_id >= 0 && device_id < NUMBER_OF_DEVICES && "bad dev id");
size_t ImageSize = (size_t)image->ImageEnd - (size_t)image->ImageStart;
size_t NumEntries = (size_t)(image->EntriesEnd - image->EntriesBegin);
DP("Expecting to have %zd entries defined.\n", NumEntries);
// Is the library version incompatible with the header file?
if (elf_version(EV_CURRENT) == EV_NONE) {
DP("Incompatible ELF library!\n");
return NULL;
}
// Obtain elf handler
Elf *e = elf_memory((char *)image->ImageStart, ImageSize);
if (!e) {
DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1));
return NULL;
}
if (elf_kind(e) != ELF_K_ELF) {
DP("Invalid Elf kind!\n");
elf_end(e);
return NULL;
}
// Find the entries section offset
Elf_Scn *section = 0;
Elf64_Off entries_offset = 0;
size_t shstrndx;
if (elf_getshdrstrndx(e, &shstrndx)) {
DP("Unable to get ELF strings index!\n");
elf_end(e);
return NULL;
}
while ((section = elf_nextscn(e, section))) {
GElf_Shdr hdr;
gelf_getshdr(section, &hdr);
if (!strcmp(elf_strptr(e, shstrndx, hdr.sh_name), OFFLOADSECTIONNAME)) {
entries_offset = hdr.sh_addr;
break;
}
}
if (!entries_offset) {
DP("Entries Section Offset Not Found\n");
elf_end(e);
return NULL;
}
DP("Offset of entries section is (" DPxMOD ").\n", DPxPTR(entries_offset));
// load dynamic library and get the entry points. We use the dl library
// to do the loading of the library, but we could do it directly to avoid the
// dump to the temporary file.
//
// 1) Create tmp file with the library contents.
// 2) Use dlopen to load the file and dlsym to retrieve the symbols.
char tmp_name[] = "/tmp/tmpfile_XXXXXX";
int tmp_fd = mkstemp(tmp_name);
if (tmp_fd == -1) {
elf_end(e);
return NULL;
}
FILE *ftmp = fdopen(tmp_fd, "wb");
if (!ftmp) {
elf_end(e);
return NULL;
}
fwrite(image->ImageStart, ImageSize, 1, ftmp);
fclose(ftmp);
DynLibTy Lib = {tmp_name, dlopen(tmp_name, RTLD_LAZY)};
if (!Lib.Handle) {
DP("Target library loading error: %s\n", dlerror());
elf_end(e);
return NULL;
}
DeviceInfo.DynLibs.push_back(Lib);
struct link_map *libInfo = (struct link_map *)Lib.Handle;
// The place where the entries info is loaded is the library base address
// plus the offset determined from the ELF file.
Elf64_Addr entries_addr = libInfo->l_addr + entries_offset;
DP("Pointer to first entry to be loaded is (" DPxMOD ").\n",
DPxPTR(entries_addr));
// Table of pointers to all the entries in the target.
__tgt_offload_entry *entries_table = (__tgt_offload_entry *)entries_addr;
__tgt_offload_entry *entries_begin = &entries_table[0];
__tgt_offload_entry *entries_end = entries_begin + NumEntries;
if (!entries_begin) {
DP("Can't obtain entries begin\n");
elf_end(e);
return NULL;
}
DP("Entries table range is (" DPxMOD ")->(" DPxMOD ")\n",
DPxPTR(entries_begin), DPxPTR(entries_end));
DeviceInfo.createOffloadTable(device_id, entries_begin, entries_end);
elf_end(e);
return DeviceInfo.getOffloadEntriesTable(device_id);
}
void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *hst_ptr) {
void *ptr = malloc(size);
return ptr;
}
int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
int64_t size) {
memcpy(tgt_ptr, hst_ptr, size);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
int64_t size) {
memcpy(hst_ptr, tgt_ptr, size);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
free(tgt_ptr);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
int32_t thread_limit, uint64_t loop_tripcount /*not used*/) {
// ignore team num and thread limit.
// Use libffi to launch execution.
ffi_cif cif;
// All args are references.
std::vector<ffi_type *> args_types(arg_num, &ffi_type_pointer);
std::vector<void *> args(arg_num);
std::vector<void *> ptrs(arg_num);
for (int32_t i = 0; i < arg_num; ++i) {
ptrs[i] = (void *)((intptr_t)tgt_args[i] + tgt_offsets[i]);
args[i] = &ptrs[i];
}
ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, arg_num,
&ffi_type_void, &args_types[0]);
assert(status == FFI_OK && "Unable to prepare target launch!");
if (status != FFI_OK)
return OFFLOAD_FAIL;
DP("Running entry point at " DPxMOD "...\n", DPxPTR(tgt_entry_ptr));
void (*entry)(void);
*((void**) &entry) = tgt_entry_ptr;
ffi_call(&cif, entry, NULL, &args[0]);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num) {
// use one team and one thread.
return __tgt_rtl_run_target_team_region(device_id, tgt_entry_ptr, tgt_args,
tgt_offsets, arg_num, 1, 1, 0);
}
#ifdef __cplusplus
}
#endif
<commit_msg>[Clang][OpenMP Offload] Create start/end symbols for the offloading entry table with a help of a linker<commit_after>//===-RTLs/generic-64bit/src/rtl.cpp - Target RTLs Implementation - C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// RTL for generic 64-bit machine
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <dlfcn.h>
#include <ffi.h>
#include <gelf.h>
#include <link.h>
#include <list>
#include <string>
#include <vector>
#include "omptargetplugin.h"
#ifndef TARGET_NAME
#define TARGET_NAME Generic ELF - 64bit
#endif
#ifndef TARGET_ELF_ID
#define TARGET_ELF_ID 0
#endif
#ifdef OMPTARGET_DEBUG
static int DebugLevel = 0;
#define GETNAME2(name) #name
#define GETNAME(name) GETNAME2(name)
#define DP(...) \
do { \
if (DebugLevel > 0) { \
DEBUGP("Target " GETNAME(TARGET_NAME) " RTL", __VA_ARGS__); \
} \
} while (false)
#else // OMPTARGET_DEBUG
#define DP(...) {}
#endif // OMPTARGET_DEBUG
#include "../../common/elf_common.c"
#define NUMBER_OF_DEVICES 4
#define OFFLOADSECTIONNAME "omp_offloading_entries"
/// Array of Dynamic libraries loaded for this target.
struct DynLibTy {
char *FileName;
void *Handle;
};
/// Keep entries table per device.
struct FuncOrGblEntryTy {
__tgt_target_table Table;
};
/// Class containing all the device information.
class RTLDeviceInfoTy {
std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries;
public:
std::list<DynLibTy> DynLibs;
// Record entry point associated with device.
void createOffloadTable(int32_t device_id, __tgt_offload_entry *begin,
__tgt_offload_entry *end) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncGblEntries[device_id].emplace_back();
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
E.Table.EntriesBegin = begin;
E.Table.EntriesEnd = end;
}
// Return true if the entry is associated with device.
bool findOffloadEntry(int32_t device_id, void *addr) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
for (__tgt_offload_entry *i = E.Table.EntriesBegin, *e = E.Table.EntriesEnd;
i < e; ++i) {
if (i->addr == addr)
return true;
}
return false;
}
// Return the pointer to the target entries table.
__tgt_target_table *getOffloadEntriesTable(int32_t device_id) {
assert(device_id < (int32_t)FuncGblEntries.size() &&
"Unexpected device id!");
FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
return &E.Table;
}
RTLDeviceInfoTy(int32_t num_devices) {
#ifdef OMPTARGET_DEBUG
if (char *envStr = getenv("LIBOMPTARGET_DEBUG")) {
DebugLevel = std::stoi(envStr);
}
#endif // OMPTARGET_DEBUG
FuncGblEntries.resize(num_devices);
}
~RTLDeviceInfoTy() {
// Close dynamic libraries
for (auto &lib : DynLibs) {
if (lib.Handle) {
dlclose(lib.Handle);
remove(lib.FileName);
}
}
}
};
static RTLDeviceInfoTy DeviceInfo(NUMBER_OF_DEVICES);
#ifdef __cplusplus
extern "C" {
#endif
int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
// If we don't have a valid ELF ID we can just fail.
#if TARGET_ELF_ID < 1
return 0;
#else
return elf_check_machine(image, TARGET_ELF_ID);
#endif
}
int32_t __tgt_rtl_number_of_devices() { return NUMBER_OF_DEVICES; }
int32_t __tgt_rtl_init_device(int32_t device_id) { return OFFLOAD_SUCCESS; }
__tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
__tgt_device_image *image) {
DP("Dev %d: load binary from " DPxMOD " image\n", device_id,
DPxPTR(image->ImageStart));
assert(device_id >= 0 && device_id < NUMBER_OF_DEVICES && "bad dev id");
size_t ImageSize = (size_t)image->ImageEnd - (size_t)image->ImageStart;
size_t NumEntries = (size_t)(image->EntriesEnd - image->EntriesBegin);
DP("Expecting to have %zd entries defined.\n", NumEntries);
// Is the library version incompatible with the header file?
if (elf_version(EV_CURRENT) == EV_NONE) {
DP("Incompatible ELF library!\n");
return NULL;
}
// Obtain elf handler
Elf *e = elf_memory((char *)image->ImageStart, ImageSize);
if (!e) {
DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1));
return NULL;
}
if (elf_kind(e) != ELF_K_ELF) {
DP("Invalid Elf kind!\n");
elf_end(e);
return NULL;
}
// Find the entries section offset
Elf_Scn *section = 0;
Elf64_Off entries_offset = 0;
size_t shstrndx;
if (elf_getshdrstrndx(e, &shstrndx)) {
DP("Unable to get ELF strings index!\n");
elf_end(e);
return NULL;
}
while ((section = elf_nextscn(e, section))) {
GElf_Shdr hdr;
gelf_getshdr(section, &hdr);
if (!strcmp(elf_strptr(e, shstrndx, hdr.sh_name), OFFLOADSECTIONNAME)) {
entries_offset = hdr.sh_addr;
break;
}
}
if (!entries_offset) {
DP("Entries Section Offset Not Found\n");
elf_end(e);
return NULL;
}
DP("Offset of entries section is (" DPxMOD ").\n", DPxPTR(entries_offset));
// load dynamic library and get the entry points. We use the dl library
// to do the loading of the library, but we could do it directly to avoid the
// dump to the temporary file.
//
// 1) Create tmp file with the library contents.
// 2) Use dlopen to load the file and dlsym to retrieve the symbols.
char tmp_name[] = "/tmp/tmpfile_XXXXXX";
int tmp_fd = mkstemp(tmp_name);
if (tmp_fd == -1) {
elf_end(e);
return NULL;
}
FILE *ftmp = fdopen(tmp_fd, "wb");
if (!ftmp) {
elf_end(e);
return NULL;
}
fwrite(image->ImageStart, ImageSize, 1, ftmp);
fclose(ftmp);
DynLibTy Lib = {tmp_name, dlopen(tmp_name, RTLD_LAZY)};
if (!Lib.Handle) {
DP("Target library loading error: %s\n", dlerror());
elf_end(e);
return NULL;
}
DeviceInfo.DynLibs.push_back(Lib);
struct link_map *libInfo = (struct link_map *)Lib.Handle;
// The place where the entries info is loaded is the library base address
// plus the offset determined from the ELF file.
Elf64_Addr entries_addr = libInfo->l_addr + entries_offset;
DP("Pointer to first entry to be loaded is (" DPxMOD ").\n",
DPxPTR(entries_addr));
// Table of pointers to all the entries in the target.
__tgt_offload_entry *entries_table = (__tgt_offload_entry *)entries_addr;
__tgt_offload_entry *entries_begin = &entries_table[0];
__tgt_offload_entry *entries_end = entries_begin + NumEntries;
if (!entries_begin) {
DP("Can't obtain entries begin\n");
elf_end(e);
return NULL;
}
DP("Entries table range is (" DPxMOD ")->(" DPxMOD ")\n",
DPxPTR(entries_begin), DPxPTR(entries_end));
DeviceInfo.createOffloadTable(device_id, entries_begin, entries_end);
elf_end(e);
return DeviceInfo.getOffloadEntriesTable(device_id);
}
void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *hst_ptr) {
void *ptr = malloc(size);
return ptr;
}
int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
int64_t size) {
memcpy(tgt_ptr, hst_ptr, size);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
int64_t size) {
memcpy(hst_ptr, tgt_ptr, size);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
free(tgt_ptr);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
int32_t thread_limit, uint64_t loop_tripcount /*not used*/) {
// ignore team num and thread limit.
// Use libffi to launch execution.
ffi_cif cif;
// All args are references.
std::vector<ffi_type *> args_types(arg_num, &ffi_type_pointer);
std::vector<void *> args(arg_num);
std::vector<void *> ptrs(arg_num);
for (int32_t i = 0; i < arg_num; ++i) {
ptrs[i] = (void *)((intptr_t)tgt_args[i] + tgt_offsets[i]);
args[i] = &ptrs[i];
}
ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, arg_num,
&ffi_type_void, &args_types[0]);
assert(status == FFI_OK && "Unable to prepare target launch!");
if (status != FFI_OK)
return OFFLOAD_FAIL;
DP("Running entry point at " DPxMOD "...\n", DPxPTR(tgt_entry_ptr));
void (*entry)(void);
*((void**) &entry) = tgt_entry_ptr;
ffi_call(&cif, entry, NULL, &args[0]);
return OFFLOAD_SUCCESS;
}
int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
void **tgt_args, ptrdiff_t *tgt_offsets, int32_t arg_num) {
// use one team and one thread.
return __tgt_rtl_run_target_team_region(device_id, tgt_entry_ptr, tgt_args,
tgt_offsets, arg_num, 1, 1, 0);
}
#ifdef __cplusplus
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Bardsley
*/
#include "arch/utility.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/dyn_inst.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/pipeline.hh"
#include "debug/Drain.hh"
#include "debug/MinorCPU.hh"
#include "debug/Quiesce.hh"
MinorCPU::MinorCPU(MinorCPUParams *params) :
BaseCPU(params)
{
/* This is only written for one thread at the moment */
Minor::MinorThread *thread;
if (FullSystem) {
thread = new Minor::MinorThread(this, 0, params->system, params->itb,
params->dtb, params->isa[0]);
} else {
/* thread_id 0 */
thread = new Minor::MinorThread(this, 0, params->system,
params->workload[0], params->itb, params->dtb, params->isa[0]);
}
threads.push_back(thread);
thread->setStatus(ThreadContext::Halted);
ThreadContext *tc = thread->getTC();
if (params->checker) {
fatal("The Minor model doesn't support checking (yet)\n");
}
threadContexts.push_back(tc);
Minor::MinorDynInst::init();
pipeline = new Minor::Pipeline(*this, *params);
activityRecorder = pipeline->getActivityRecorder();
}
MinorCPU::~MinorCPU()
{
delete pipeline;
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
delete threads[thread_id];
}
}
void
MinorCPU::init()
{
BaseCPU::init();
if (!params()->switched_out &&
system->getMemoryMode() != Enums::timing)
{
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
/* Initialise the ThreadContext's memory proxies */
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
ThreadContext *tc = getContext(thread_id);
tc->initMemProxies(tc);
}
/* Initialise CPUs (== threads in the ISA) */
if (FullSystem && !params()->switched_out) {
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++)
{
ThreadContext *tc = getContext(thread_id);
/* Initialize CPU, including PC */
TheISA::initCPU(tc, cpuId());
}
}
}
/** Stats interface from SimObject (by way of BaseCPU) */
void
MinorCPU::regStats()
{
BaseCPU::regStats();
stats.regStats(name(), *this);
pipeline->regStats();
}
void
MinorCPU::serializeThread(CheckpointOut &cp, ThreadID thread_id) const
{
threads[thread_id]->serialize(cp);
}
void
MinorCPU::unserializeThread(CheckpointIn &cp, ThreadID thread_id)
{
if (thread_id != 0)
fatal("Trying to load more than one thread into a MinorCPU\n");
threads[thread_id]->unserialize(cp);
}
void
MinorCPU::serialize(CheckpointOut &cp) const
{
pipeline->serialize(cp);
BaseCPU::serialize(cp);
}
void
MinorCPU::unserialize(CheckpointIn &cp)
{
pipeline->unserialize(cp);
BaseCPU::unserialize(cp);
}
Addr
MinorCPU::dbg_vtophys(Addr addr)
{
/* Note that this gives you the translation for thread 0 */
panic("No implementation for vtophy\n");
return 0;
}
void
MinorCPU::wakeup()
{
DPRINTF(Drain, "MinorCPU wakeup\n");
for (auto i = threads.begin(); i != threads.end(); i ++) {
if ((*i)->status() == ThreadContext::Suspended)
(*i)->activate();
}
DPRINTF(Drain,"Suspended Processor awoke\n");
}
void
MinorCPU::startup()
{
DPRINTF(MinorCPU, "MinorCPU startup\n");
BaseCPU::startup();
for (auto i = threads.begin(); i != threads.end(); i ++)
(*i)->startup();
/* CPU state setup, activate initial context */
activateContext(0);
}
DrainState
MinorCPU::drain()
{
DPRINTF(Drain, "MinorCPU drain\n");
/* Need to suspend all threads and wait for Execute to idle.
* Tell Fetch1 not to fetch */
if (pipeline->drain()) {
DPRINTF(Drain, "MinorCPU drained\n");
return DrainState::Drained;
} else {
DPRINTF(Drain, "MinorCPU not finished draining\n");
return DrainState::Draining;
}
}
void
MinorCPU::signalDrainDone()
{
DPRINTF(Drain, "MinorCPU drain done\n");
Drainable::signalDrainDone();
}
void
MinorCPU::drainResume()
{
if (switchedOut()) {
DPRINTF(Drain, "drainResume while switched out. Ignoring\n");
return;
}
DPRINTF(Drain, "MinorCPU drainResume\n");
if (!system->isTimingMode()) {
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
wakeup();
pipeline->drainResume();
}
void
MinorCPU::memWriteback()
{
DPRINTF(Drain, "MinorCPU memWriteback\n");
}
void
MinorCPU::switchOut()
{
DPRINTF(MinorCPU, "MinorCPU switchOut\n");
assert(!switchedOut());
BaseCPU::switchOut();
/* Check that the CPU is drained? */
activityRecorder->reset();
}
void
MinorCPU::takeOverFrom(BaseCPU *old_cpu)
{
DPRINTF(MinorCPU, "MinorCPU takeOverFrom\n");
BaseCPU::takeOverFrom(old_cpu);
/* Don't think I need to do anything here */
}
void
MinorCPU::activateContext(ThreadID thread_id)
{
DPRINTF(MinorCPU, "ActivateContext thread: %d", thread_id);
/* Do some cycle accounting. lastStopped is reset to stop the
* wakeup call on the pipeline from adding the quiesce period
* to BaseCPU::numCycles */
stats.quiesceCycles += pipeline->cyclesSinceLastStopped();
pipeline->resetLastStopped();
/* Wake up the thread, wakeup the pipeline tick */
threads[thread_id]->activate();
wakeupOnEvent(Minor::Pipeline::CPUStageId);
pipeline->wakeupFetch();
}
void
MinorCPU::suspendContext(ThreadID thread_id)
{
DPRINTF(MinorCPU, "SuspendContext %d\n", thread_id);
threads[thread_id]->suspend();
}
void
MinorCPU::wakeupOnEvent(unsigned int stage_id)
{
DPRINTF(Quiesce, "Event wakeup from stage %d\n", stage_id);
/* Mark that some activity has taken place and start the pipeline */
activityRecorder->activateStage(stage_id);
pipeline->start();
}
MinorCPU *
MinorCPUParams::create()
{
numThreads = 1;
if (!FullSystem && workload.size() != 1)
panic("only one workload allowed");
return new MinorCPU(this);
}
MasterPort &MinorCPU::getInstPort()
{
return pipeline->getInstPort();
}
MasterPort &MinorCPU::getDataPort()
{
return pipeline->getDataPort();
}
Counter
MinorCPU::totalInsts() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numInst;
return ret;
}
Counter
MinorCPU::totalOps() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numOp;
return ret;
}
<commit_msg>cpu: Only activate thread 0 in Minor if the CPU is active<commit_after>/*
* Copyright (c) 2012-2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andrew Bardsley
*/
#include "arch/utility.hh"
#include "cpu/minor/cpu.hh"
#include "cpu/minor/dyn_inst.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/pipeline.hh"
#include "debug/Drain.hh"
#include "debug/MinorCPU.hh"
#include "debug/Quiesce.hh"
MinorCPU::MinorCPU(MinorCPUParams *params) :
BaseCPU(params)
{
/* This is only written for one thread at the moment */
Minor::MinorThread *thread;
if (FullSystem) {
thread = new Minor::MinorThread(this, 0, params->system, params->itb,
params->dtb, params->isa[0]);
} else {
/* thread_id 0 */
thread = new Minor::MinorThread(this, 0, params->system,
params->workload[0], params->itb, params->dtb, params->isa[0]);
}
threads.push_back(thread);
thread->setStatus(ThreadContext::Halted);
ThreadContext *tc = thread->getTC();
if (params->checker) {
fatal("The Minor model doesn't support checking (yet)\n");
}
threadContexts.push_back(tc);
Minor::MinorDynInst::init();
pipeline = new Minor::Pipeline(*this, *params);
activityRecorder = pipeline->getActivityRecorder();
}
MinorCPU::~MinorCPU()
{
delete pipeline;
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
delete threads[thread_id];
}
}
void
MinorCPU::init()
{
BaseCPU::init();
if (!params()->switched_out &&
system->getMemoryMode() != Enums::timing)
{
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
/* Initialise the ThreadContext's memory proxies */
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {
ThreadContext *tc = getContext(thread_id);
tc->initMemProxies(tc);
}
/* Initialise CPUs (== threads in the ISA) */
if (FullSystem && !params()->switched_out) {
for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++)
{
ThreadContext *tc = getContext(thread_id);
/* Initialize CPU, including PC */
TheISA::initCPU(tc, cpuId());
}
}
}
/** Stats interface from SimObject (by way of BaseCPU) */
void
MinorCPU::regStats()
{
BaseCPU::regStats();
stats.regStats(name(), *this);
pipeline->regStats();
}
void
MinorCPU::serializeThread(CheckpointOut &cp, ThreadID thread_id) const
{
threads[thread_id]->serialize(cp);
}
void
MinorCPU::unserializeThread(CheckpointIn &cp, ThreadID thread_id)
{
if (thread_id != 0)
fatal("Trying to load more than one thread into a MinorCPU\n");
threads[thread_id]->unserialize(cp);
}
void
MinorCPU::serialize(CheckpointOut &cp) const
{
pipeline->serialize(cp);
BaseCPU::serialize(cp);
}
void
MinorCPU::unserialize(CheckpointIn &cp)
{
pipeline->unserialize(cp);
BaseCPU::unserialize(cp);
}
Addr
MinorCPU::dbg_vtophys(Addr addr)
{
/* Note that this gives you the translation for thread 0 */
panic("No implementation for vtophy\n");
return 0;
}
void
MinorCPU::wakeup()
{
DPRINTF(Drain, "MinorCPU wakeup\n");
for (auto i = threads.begin(); i != threads.end(); i ++) {
if ((*i)->status() == ThreadContext::Suspended)
(*i)->activate();
}
DPRINTF(Drain,"Suspended Processor awoke\n");
}
void
MinorCPU::startup()
{
DPRINTF(MinorCPU, "MinorCPU startup\n");
BaseCPU::startup();
for (auto i = threads.begin(); i != threads.end(); i ++)
(*i)->startup();
/* Workaround cases in SE mode where a thread is activated with an
* incorrect PC that is updated after the call to activate. This
* causes problems for Minor since it instantiates a virtual
* branch instruction when activateContext() is called which ends
* up pointing to an illegal address. */
if (threads[0]->status() == ThreadContext::Active)
activateContext(0);
}
DrainState
MinorCPU::drain()
{
DPRINTF(Drain, "MinorCPU drain\n");
/* Need to suspend all threads and wait for Execute to idle.
* Tell Fetch1 not to fetch */
if (pipeline->drain()) {
DPRINTF(Drain, "MinorCPU drained\n");
return DrainState::Drained;
} else {
DPRINTF(Drain, "MinorCPU not finished draining\n");
return DrainState::Draining;
}
}
void
MinorCPU::signalDrainDone()
{
DPRINTF(Drain, "MinorCPU drain done\n");
Drainable::signalDrainDone();
}
void
MinorCPU::drainResume()
{
if (switchedOut()) {
DPRINTF(Drain, "drainResume while switched out. Ignoring\n");
return;
}
DPRINTF(Drain, "MinorCPU drainResume\n");
if (!system->isTimingMode()) {
fatal("The Minor CPU requires the memory system to be in "
"'timing' mode.\n");
}
wakeup();
pipeline->drainResume();
}
void
MinorCPU::memWriteback()
{
DPRINTF(Drain, "MinorCPU memWriteback\n");
}
void
MinorCPU::switchOut()
{
DPRINTF(MinorCPU, "MinorCPU switchOut\n");
assert(!switchedOut());
BaseCPU::switchOut();
/* Check that the CPU is drained? */
activityRecorder->reset();
}
void
MinorCPU::takeOverFrom(BaseCPU *old_cpu)
{
DPRINTF(MinorCPU, "MinorCPU takeOverFrom\n");
BaseCPU::takeOverFrom(old_cpu);
/* Don't think I need to do anything here */
}
void
MinorCPU::activateContext(ThreadID thread_id)
{
DPRINTF(MinorCPU, "ActivateContext thread: %d", thread_id);
/* Do some cycle accounting. lastStopped is reset to stop the
* wakeup call on the pipeline from adding the quiesce period
* to BaseCPU::numCycles */
stats.quiesceCycles += pipeline->cyclesSinceLastStopped();
pipeline->resetLastStopped();
/* Wake up the thread, wakeup the pipeline tick */
threads[thread_id]->activate();
wakeupOnEvent(Minor::Pipeline::CPUStageId);
pipeline->wakeupFetch();
}
void
MinorCPU::suspendContext(ThreadID thread_id)
{
DPRINTF(MinorCPU, "SuspendContext %d\n", thread_id);
threads[thread_id]->suspend();
}
void
MinorCPU::wakeupOnEvent(unsigned int stage_id)
{
DPRINTF(Quiesce, "Event wakeup from stage %d\n", stage_id);
/* Mark that some activity has taken place and start the pipeline */
activityRecorder->activateStage(stage_id);
pipeline->start();
}
MinorCPU *
MinorCPUParams::create()
{
numThreads = 1;
if (!FullSystem && workload.size() != 1)
panic("only one workload allowed");
return new MinorCPU(this);
}
MasterPort &MinorCPU::getInstPort()
{
return pipeline->getInstPort();
}
MasterPort &MinorCPU::getDataPort()
{
return pipeline->getDataPort();
}
Counter
MinorCPU::totalInsts() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numInst;
return ret;
}
Counter
MinorCPU::totalOps() const
{
Counter ret = 0;
for (auto i = threads.begin(); i != threads.end(); i ++)
ret += (*i)->numOp;
return ret;
}
<|endoftext|>
|
<commit_before>/*
* IdentConn.cpp
*
* Created on: Nov 17, 2010
* Author: pschultz
*/
#include "IdentConn.hpp"
namespace PV {
PVConnParams defaultConnParamsIdent =
{
/*delay*/ 0, /*fixDelay*/ 0, /*varDelayMin*/ 0, /*varDelayMax*/ 0, /*numDelay*/ 1,
/*isGraded*/ 0, /*vel*/ 45.248, /*rmin*/ 0.0, /*rmax*/ 4.0
};
IdentConn::IdentConn(const char * name, HyPerCol *hc,
HyPerLayer * pre, HyPerLayer * post, int channel) {
initialize_base();
initialize(name, hc, pre, post, channel);
} // end of IdentConn::IdentConn(const char *, HyPerCol *, int, GenLatConn *)
int IdentConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel) {
PVLayer * preclayer = pre->getCLayer();
PVLayer * postclayer = post->getCLayer();
if( memcmp(&preclayer->loc,&postclayer->loc,sizeof(PVLayerLoc)) ) {
fprintf( stderr,
"IdentConn: %s and %s do not have the same dimensions\n",
pre->getName(),post->getName() );
return EXIT_FAILURE;
}
// lines below swiped from HyPerConn::initialize
this->parent = hc;
this->pre = pre;
this->post = post;
this->channel = channel;
free(this->name); // name will already have been set in initialize_base()
this->name = strdup(name);
assert(this->name != NULL);
// lines above swiped from HyPerConn::initialize
// HyPerConn::initialize(filename);
const int arbor = 0;
numAxonalArborLists = 1;
assert(this->channel < postclayer->numPhis);
this->connId = parent->numberOfConnections();
PVParams * inputParams = parent->parameters();
setParams(inputParams, &defaultConnParamsIdent);
setPatchSize(NULL); // overridden
// wPatches[arbor] = createWeights(wPatches[arbor]);
wPatches[arbor] = createWeights(wPatches[arbor],
numWeightPatches(arbor),nxp,nyp,nfp); // don't need to override
// initializeSTDP();
// Create list of axonal arbors containing pointers to {phi,w,P,M} patches.
// weight patches may shrink
// readWeights() should expect shrunken patches
// initializeWeights() must be aware that patches may not be uniform
createAxonalArbors();
initializeWeights(wPatches[arbor], numWeightPatches(arbor), NULL); // need to override
assert(wPatches[arbor] != NULL);
writeTime = parent->simulationTime();
writeStep = inputParams->value(name, "writeStep", parent->getDeltaTime());
parent->addConnection(this);
// HyPerConn::initialize(filename);
return EXIT_SUCCESS;
} // end of IdentConn::initialize(const char *, HyPerCol *, HyPerLayer *, HyPerLayer *, int, const char * filename, GenLatConn *)
int IdentConn::setPatchSize(const char * filename) {
int status = EXIT_SUCCESS;
nxp = 1;
nyp = 1;
nfp = pre->getCLayer()->numFeatures;
return status;
} // end of IdentConn::setPatchSize(const char *)
PVPatch ** IdentConn::initializeWeights(PVPatch ** patches, int numPatches,
const char * filename) {
int numKernels = numDataPatches(0);
for( int k=0; k < numKernels; k++ ) {
PVPatch * kp = getKernelPatch(k);
for( int l=0; l < kp->nf; l++ ) {
kp->data[l] = l==k;
}
}
return patches;
}
} // end of namespace PV block
<commit_msg>Corrected two end-of-block comments<commit_after>/*
* IdentConn.cpp
*
* Created on: Nov 17, 2010
* Author: pschultz
*/
#include "IdentConn.hpp"
namespace PV {
PVConnParams defaultConnParamsIdent =
{
/*delay*/ 0, /*fixDelay*/ 0, /*varDelayMin*/ 0, /*varDelayMax*/ 0, /*numDelay*/ 1,
/*isGraded*/ 0, /*vel*/ 45.248, /*rmin*/ 0.0, /*rmax*/ 4.0
};
IdentConn::IdentConn(const char * name, HyPerCol *hc,
HyPerLayer * pre, HyPerLayer * post, int channel) {
initialize_base();
initialize(name, hc, pre, post, channel);
} // end of IdentConn::IdentConn(const char *, HyPerCol *, HyPerLayer *, HyPerLayer *, int)
int IdentConn::initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel) {
PVLayer * preclayer = pre->getCLayer();
PVLayer * postclayer = post->getCLayer();
if( memcmp(&preclayer->loc,&postclayer->loc,sizeof(PVLayerLoc)) ) {
fprintf( stderr,
"IdentConn: %s and %s do not have the same dimensions\n",
pre->getName(),post->getName() );
return EXIT_FAILURE;
}
// lines below swiped from HyPerConn::initialize
this->parent = hc;
this->pre = pre;
this->post = post;
this->channel = channel;
free(this->name); // name will already have been set in initialize_base()
this->name = strdup(name);
assert(this->name != NULL);
// lines above swiped from HyPerConn::initialize
// HyPerConn::initialize(filename);
const int arbor = 0;
numAxonalArborLists = 1;
assert(this->channel < postclayer->numPhis);
this->connId = parent->numberOfConnections();
PVParams * inputParams = parent->parameters();
setParams(inputParams, &defaultConnParamsIdent);
setPatchSize(NULL); // overridden
// wPatches[arbor] = createWeights(wPatches[arbor]);
wPatches[arbor] = createWeights(wPatches[arbor],
numWeightPatches(arbor),nxp,nyp,nfp); // don't need to override
// initializeSTDP();
// Create list of axonal arbors containing pointers to {phi,w,P,M} patches.
// weight patches may shrink
// readWeights() should expect shrunken patches
// initializeWeights() must be aware that patches may not be uniform
createAxonalArbors();
initializeWeights(wPatches[arbor], numWeightPatches(arbor), NULL); // need to override
assert(wPatches[arbor] != NULL);
writeTime = parent->simulationTime();
writeStep = inputParams->value(name, "writeStep", parent->getDeltaTime());
parent->addConnection(this);
// HyPerConn::initialize(filename);
return EXIT_SUCCESS;
} // end of IdentConn::initialize(const char *, HyPerCol *, HyPerLayer *, HyPerLayer *)
int IdentConn::setPatchSize(const char * filename) {
int status = EXIT_SUCCESS;
nxp = 1;
nyp = 1;
nfp = pre->getCLayer()->numFeatures;
return status;
} // end of IdentConn::setPatchSize(const char *)
PVPatch ** IdentConn::initializeWeights(PVPatch ** patches, int numPatches,
const char * filename) {
int numKernels = numDataPatches(0);
for( int k=0; k < numKernels; k++ ) {
PVPatch * kp = getKernelPatch(k);
for( int l=0; l < kp->nf; l++ ) {
kp->data[l] = l==k;
}
}
return patches;
}
} // end of namespace PV block
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "pluginstore.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/plugin.h"
// appleseed.foundation headers.
#include "foundation/platform/path.h"
#include "foundation/platform/sharedlibrary.h"
#include "foundation/utility/searchpaths.h"
// Boost headers.
#include "boost/filesystem.hpp"
#include "boost/thread/locks.hpp"
#include "boost/thread/mutex.hpp"
// Standard headers.
#include <cassert>
#include <cstddef>
#include <map>
#include <memory>
#include <string>
using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;
namespace renderer
{
struct PluginStore::Impl
{
typedef PluginStore::PluginHandlerType PluginHandlerType;
typedef map<string, PluginHandlerType> PluginHandlerMap;
struct PluginDeleter;
typedef unique_ptr<Plugin, PluginDeleter> PluginUniquePtr;
typedef map<string, PluginUniquePtr> PluginMap;
typedef map<Plugin*, PluginMap::const_iterator> PluginInverseMap;
struct PluginDeleter
{
void operator()(Plugin* plugin)
{
RENDERER_LOG_INFO("unloading plugin %s...", plugin->get_filepath());
// Try to call the plugin's uninitialization function if defined.
const auto uninit_fn = reinterpret_cast<Plugin::UnInitPluginFnType>(plugin->get_symbol("uninitialize_plugin"));
if (uninit_fn != nullptr)
uninit_fn();
// Delete the plugin.
delete plugin;
}
};
boost::mutex m_store_mutex;
PluginHandlerMap m_plugin_handlers;
PluginMap m_plugin_map;
PluginInverseMap m_plugin_inverse_map;
Plugin* load_plugin_no_lock(const char* filepath)
{
auto plugin_map_it = m_plugin_map.find(filepath);
if (plugin_map_it == m_plugin_map.end())
{
RENDERER_LOG_INFO("loading plugin %s...", filepath);
// Load the plugin.
PluginUniquePtr plugin(new Plugin(filepath));
// Try to call the plugin's initialization function if defined.
const auto init_fn = reinterpret_cast<Plugin::InitPluginFnType>(plugin->get_symbol("initialize_plugin"));
if (init_fn != nullptr)
{
if (!init_fn())
{
RENDERER_LOG_WARNING("plugin %s failed to initialize itself.", filepath);
return nullptr;
}
}
// Insert the plugin into the map.
const auto insert_result =
m_plugin_map.insert(PluginMap::value_type(filepath, std::move(plugin)));
assert(insert_result.second);
plugin_map_it = insert_result.first;
// Insert the corresponding entry into the inverse map.
#ifndef NDEBUG
const auto inverse_insert_result =
#endif
m_plugin_inverse_map.insert(PluginInverseMap::value_type(plugin_map_it->second.get(), plugin_map_it));
assert(inverse_insert_result.second);
RENDERER_LOG_DEBUG("plugin %s successfully loaded and initialized.", filepath);
}
else
{
RENDERER_LOG_DEBUG("plugin %s already loaded.", filepath);
}
return plugin_map_it->second.get();
}
void load_all_plugins_from_path_no_lock(bf::path path)
{
path = safe_canonical(path);
// Only consider directories.
if (!bf::exists(path) || !bf::is_directory(path))
{
RENDERER_LOG_WARNING("not scanning %s for plugins since it doesn't exist or it isn't a directory.",
path.string().c_str());
return;
}
RENDERER_LOG_INFO("scanning %s for plugins...", path.string().c_str());
// Iterate over all files in this directory.
for (bf::directory_iterator i(path), e; i != e; ++i)
{
const bf::path& filepath = i->path();
// Only consider files.
if (!bf::is_regular_file(filepath))
continue;
// Only consider shared libraries.
if (lower_case(filepath.extension().string()) != SharedLibrary::get_default_file_extension())
continue;
vector<PluginHandlerMap::value_type> relevant_plugin_handlers;
try
{
// Open the shared library.
SharedLibrary library(filepath.string().c_str());
// Collect known entry points defined by the shared library.
for (const auto& plugin_handler_item : m_plugin_handlers)
{
const string& entry_point_name = plugin_handler_item.first;
// If the plugin defines the expected entry point then keep this plugin handler to invoke it later.
if (library.get_symbol(entry_point_name.c_str()) != nullptr)
relevant_plugin_handlers.push_back(plugin_handler_item);
}
}
catch (const ExceptionCannotLoadSharedLib& e)
{
RENDERER_LOG_DEBUG("could not open shared library %s: %s.", filepath.string().c_str(), e.what());
continue;
}
if (!relevant_plugin_handlers.empty())
{
// Load the plugin.
Plugin* plugin = load_plugin_no_lock(filepath.string().c_str());
// Invoke plugin handlers.
for (const auto& plugin_handler_item : relevant_plugin_handlers)
{
const string& entry_point_name = plugin_handler_item.first;
const PluginHandlerType& plugin_handler = plugin_handler_item.second;
// Retrieve again the plugin's entry point corresponding to this plugin handler.
void* plugin_entry_point = plugin->get_symbol(entry_point_name.c_str());
// Invoke the plugin handler.
plugin_handler(plugin, plugin_entry_point);
}
}
}
}
};
PluginStore::PluginStore()
: impl(new Impl())
{
}
PluginStore::~PluginStore()
{
unload_all_plugins();
delete impl;
}
void PluginStore::register_plugin_handler(
const char* entry_point_name,
const PluginHandlerType& plugin_handler)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
impl->m_plugin_handlers.insert(
Impl::PluginHandlerMap::value_type(entry_point_name, plugin_handler));
}
void PluginStore::unload_all_plugins()
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
RENDERER_LOG_INFO("unloading all plugins...");
impl->m_plugin_inverse_map.clear();
impl->m_plugin_map.clear();
}
Plugin* PluginStore::load_plugin(const char* filepath)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
return impl->load_plugin_no_lock(filepath);
}
void PluginStore::unload_plugin(Plugin* plugin)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
const auto plugin_map_inverse_it = impl->m_plugin_inverse_map.find(plugin);
assert(plugin_map_inverse_it != impl->m_plugin_inverse_map.end());
impl->m_plugin_map.erase(plugin_map_inverse_it->second);
impl->m_plugin_inverse_map.erase(plugin_map_inverse_it);
}
void PluginStore::load_all_plugins_from_paths(const SearchPaths& search_paths)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
for (size_t i = 0, e = search_paths.get_path_count(); i < e; ++i)
{
bf::path search_path(search_paths.get_path(i));
// Make the search path absolute if it isn't already.
if (!search_path.is_absolute() && search_paths.has_root_path())
search_path = search_paths.get_root_path().c_str() / search_path;
// Load all plugins from this search path.
impl->load_all_plugins_from_path_no_lock(search_path);
}
}
void PluginStore::load_all_plugins_from_path(const char* path)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
impl->load_all_plugins_from_path_no_lock(path);
}
} // namespace renderer
<commit_msg>Invoke plugin handlers when loading single plugin<commit_after>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2018 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "pluginstore.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/utility/plugin.h"
// appleseed.foundation headers.
#include "foundation/platform/path.h"
#include "foundation/platform/sharedlibrary.h"
#include "foundation/utility/searchpaths.h"
// Boost headers.
#include "boost/filesystem.hpp"
#include "boost/thread/locks.hpp"
#include "boost/thread/mutex.hpp"
// Standard headers.
#include <cassert>
#include <cstddef>
#include <map>
#include <memory>
#include <string>
using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;
namespace renderer
{
struct PluginStore::Impl
{
typedef PluginStore::PluginHandlerType PluginHandlerType;
typedef map<string, PluginHandlerType> PluginHandlerMap;
struct PluginDeleter;
typedef unique_ptr<Plugin, PluginDeleter> PluginUniquePtr;
typedef map<string, PluginUniquePtr> PluginMap;
typedef map<Plugin*, PluginMap::const_iterator> PluginInverseMap;
struct PluginDeleter
{
void operator()(Plugin* plugin)
{
RENDERER_LOG_INFO("unloading plugin %s...", plugin->get_filepath());
// Try to call the plugin's uninitialization function if defined.
const auto uninit_fn = reinterpret_cast<Plugin::UnInitPluginFnType>(plugin->get_symbol("uninitialize_plugin"));
if (uninit_fn != nullptr)
uninit_fn();
// Delete the plugin.
delete plugin;
}
};
boost::mutex m_store_mutex;
PluginHandlerMap m_plugin_handlers;
PluginMap m_plugin_map;
PluginInverseMap m_plugin_inverse_map;
Plugin* load_plugin_no_lock(const char* filepath)
{
auto plugin_map_it = m_plugin_map.find(filepath);
if (plugin_map_it == m_plugin_map.end())
{
RENDERER_LOG_INFO("loading plugin %s...", filepath);
// Load the plugin.
PluginUniquePtr plugin(new Plugin(filepath));
// Try to call the plugin's initialization function if defined.
const auto init_fn = reinterpret_cast<Plugin::InitPluginFnType>(plugin->get_symbol("initialize_plugin"));
if (init_fn != nullptr)
{
if (!init_fn())
{
RENDERER_LOG_WARNING("plugin %s failed to initialize itself.", filepath);
return nullptr;
}
}
// Insert the plugin into the map.
const auto insert_result =
m_plugin_map.insert(PluginMap::value_type(filepath, std::move(plugin)));
assert(insert_result.second);
plugin_map_it = insert_result.first;
// Insert the corresponding entry into the inverse map.
#ifndef NDEBUG
const auto inverse_insert_result =
#endif
m_plugin_inverse_map.insert(PluginInverseMap::value_type(plugin_map_it->second.get(), plugin_map_it));
assert(inverse_insert_result.second);
RENDERER_LOG_DEBUG("plugin %s successfully loaded and initialized.", filepath);
}
else
{
RENDERER_LOG_DEBUG("plugin %s already loaded.", filepath);
}
return plugin_map_it->second.get();
}
Plugin* load_plugin_and_invoke_handlers_no_lock(const char* filepath)
{
// Load the plugin.
Plugin* plugin = load_plugin_no_lock(filepath);
if (plugin != nullptr)
{
// Invoke plugin handlers.
for (const auto& plugin_handler_item : m_plugin_handlers)
{
const string& entry_point_name = plugin_handler_item.first;
const PluginHandlerType& plugin_handler = plugin_handler_item.second;
// If the plugin exposes the expected entry point then pass it to the plugin handler.
void* plugin_entry_point = plugin->get_symbol(entry_point_name.c_str());
if (plugin_entry_point != nullptr)
plugin_handler(plugin, plugin_entry_point);
}
}
return plugin;
}
void load_all_plugins_from_path_no_lock(bf::path path)
{
path = safe_canonical(path);
// Only consider directories.
if (!bf::exists(path) || !bf::is_directory(path))
{
RENDERER_LOG_WARNING("not scanning %s for plugins since it doesn't exist or it isn't a directory.",
path.string().c_str());
return;
}
RENDERER_LOG_INFO("scanning %s for plugins...", path.string().c_str());
// Iterate over all files in this directory.
for (bf::directory_iterator i(path), e; i != e; ++i)
{
const bf::path& filepath = i->path();
// Only consider files.
if (!bf::is_regular_file(filepath))
continue;
// Only consider shared libraries.
if (lower_case(filepath.extension().string()) != SharedLibrary::get_default_file_extension())
continue;
// Load the plugin and invoke plugin handlers.
load_plugin_and_invoke_handlers_no_lock(filepath.string().c_str());
}
}
};
PluginStore::PluginStore()
: impl(new Impl())
{
}
PluginStore::~PluginStore()
{
unload_all_plugins();
delete impl;
}
void PluginStore::register_plugin_handler(
const char* entry_point_name,
const PluginHandlerType& plugin_handler)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
impl->m_plugin_handlers.insert(
Impl::PluginHandlerMap::value_type(entry_point_name, plugin_handler));
}
void PluginStore::unload_all_plugins()
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
RENDERER_LOG_INFO("unloading all plugins...");
impl->m_plugin_inverse_map.clear();
impl->m_plugin_map.clear();
}
Plugin* PluginStore::load_plugin(const char* filepath)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
return impl->load_plugin_and_invoke_handlers_no_lock(filepath);
}
void PluginStore::unload_plugin(Plugin* plugin)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
const auto plugin_map_inverse_it = impl->m_plugin_inverse_map.find(plugin);
assert(plugin_map_inverse_it != impl->m_plugin_inverse_map.end());
impl->m_plugin_map.erase(plugin_map_inverse_it->second);
impl->m_plugin_inverse_map.erase(plugin_map_inverse_it);
}
void PluginStore::load_all_plugins_from_paths(const SearchPaths& search_paths)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
for (size_t i = 0, e = search_paths.get_path_count(); i < e; ++i)
{
bf::path search_path(search_paths.get_path(i));
// Make the search path absolute if it isn't already.
if (!search_path.is_absolute() && search_paths.has_root_path())
search_path = search_paths.get_root_path().c_str() / search_path;
// Load all plugins from this search path.
impl->load_all_plugins_from_path_no_lock(search_path);
}
}
void PluginStore::load_all_plugins_from_path(const char* path)
{
boost::lock_guard<boost::mutex> lock(impl->m_store_mutex);
impl->load_all_plugins_from_path_no_lock(path);
}
} // namespace renderer
<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <algorithm>
#include "gsl/span.hpp"
#include "gsl/assert.hpp"
#include "cryptic/base64.hpp"
namespace cryptic {
using namespace std;
using namespace gsl;
class sha1
{
public:
sha1() :
message_digest{0x67452301u,
0xEFCDAB89u,
0x98BADCFEu,
0x10325476u,
0xC3D2E1F0u},
buffer{},
message_length{0ull}
{}
sha1(span<const byte> message) : sha1()
{
update(message);
}
void update(span<const byte> message)
{
message_length += 8 * message.size();
while(message.size() >= 64)
{
const auto chunk = message.subspan(0, 64);
transform(chunk);
message = message.subspan<64>();
}
auto chunk = array<byte,64>{};
auto itr = copy(message.cbegin(), message.cend(), chunk.begin());
*itr++ = byte{0b10000000};
fill(itr, chunk.end(), byte{0b00000000});
if(distance(chunk.begin(), itr) < 56)
{
auto length = make_span(chunk).subspan<56>();
encode(length, message_length);
}
transform(chunk);
if(distance(chunk.begin(), itr) > 56)
{
fill(chunk.begin(), chunk.end(), byte{0b00000000});
auto length = make_span(chunk).subspan<56>();
encode(length, message_length);
transform(chunk);
}
}
const byte* data() noexcept
{
encode(buffer, message_digest);
return buffer.data();
}
constexpr size_t size() const noexcept
{
return buffer.size();
}
string base64()
{
return base64::encode(make_span(data(), size()));
}
static string base64(span<const byte> message)
{
auto hash = sha1{message};
return hash.base64();
}
private:
array<uint32_t,5> message_digest;
array<byte,20> buffer;
uint64_t message_length;
template<size_t Rotation, typename Unsigned>
static Unsigned leftrotate(Unsigned number)
{
static_assert(is_unsigned_v<Unsigned>);
constexpr auto bits = numeric_limits<Unsigned>::digits;
static_assert(Rotation <= bits);
return (number << Rotation) bitor (number >> (bits-Rotation));
}
void transform(span<const byte> chunk)
{
Expects(chunk.size() == 64);
auto words = array<uint32_t,80>{};
for(auto i = 0u, j = 0u; i < 16u; ++i, j += 4u)
words[i] = to_integer<uint32_t>(chunk[j+0]) << 24 xor
to_integer<uint32_t>(chunk[j+1]) << 16 xor
to_integer<uint32_t>(chunk[j+2]) << 8 xor
to_integer<uint32_t>(chunk[j+3]);
for(auto i = 16u; i < 32u; ++i)
words[i] = leftrotate<1>(words[i-3] xor words[i-8] xor words[i-14] xor words[i-16]);
for(auto i = 32u; i < 80u; ++i)
words[i] = leftrotate<2>(words[i-6] xor words[i-16] xor words[i-28] xor words[i-32]);
auto a = message_digest[0],
b = message_digest[1],
c = message_digest[2],
d = message_digest[3],
e = message_digest[4],
f = 0u,
k = 0u;
for(auto i = 0u; i < 80u; ++i)
{
if (i < 20)
{
f = (b bitand c) bitor ((compl b) bitand d);
k = 0x5A827999u;
}
else if (i < 40)
{
f = b xor c xor d;
k = 0x6ED9EBA1u;
}
else if (i < 60)
{
f = (b bitand c) bitor (b bitand d) bitor (c bitand d);
k = 0x8F1BBCDCu;
}
else if (i < 80)
{
f = b xor c xor d;
k = 0xCA62C1D6u;
}
auto temp = leftrotate<5>(a) + f + e + k + words[i];
e = d;
d = c;
c = leftrotate<30>(b);
b = a;
a = temp;
}
message_digest[0] += a;
message_digest[1] += b;
message_digest[2] += c;
message_digest[3] += d;
message_digest[4] += e;
}
template<typename Type, typename Integer>
static byte narrow(Integer number)
{
static_assert(is_integral_v<Integer>);
static_assert(numeric_limits<Type>::digits<numeric_limits<Integer>::digits);
return static_cast<Type>(number bitand 0b11111111);
}
static void encode(span<byte> output, const uint64_t input)
{
output[7] = narrow<byte>(input >> 0);
output[6] = narrow<byte>(input >> 8);
output[5] = narrow<byte>(input >> 16);
output[4] = narrow<byte>(input >> 24);
output[3] = narrow<byte>(input >> 32);
output[2] = narrow<byte>(input >> 40);
output[1] = narrow<byte>(input >> 48);
output[0] = narrow<byte>(input >> 56);
}
static void encode(span<byte> output, const span<uint32_t> input)
{
for (auto i = 0ull, j = 0ull; j < output.size(); ++i, j += 4ull)
{
output[j+3] = narrow<byte>(input[i]);
output[j+2] = narrow<byte>(input[i] >> 8);
output[j+1] = narrow<byte>(input[i] >> 16);
output[j+0] = narrow<byte>(input[i] >> 24);
}
}
};
} // namespace sha1
<commit_msg>optimization<commit_after>#pragma once
#include <array>
#include <algorithm>
#include "gsl/span.hpp"
#include "gsl/assert.hpp"
#include "cryptic/base64.hpp"
namespace cryptic {
using namespace std;
using namespace gsl;
class sha1
{
public:
sha1() :
message_digest{0x67452301u,
0xEFCDAB89u,
0x98BADCFEu,
0x10325476u,
0xC3D2E1F0u},
buffer{},
message_length{0ull}
{}
sha1(span<const byte> message) : sha1()
{
update(message);
}
void update(span<const byte> message)
{
message_length += 8 * message.size();
while(message.size() >= 64)
{
const auto chunk = message.subspan(0, 64);
transform(chunk);
message = message.subspan<64>();
}
auto chunk = array<byte,64>{};
auto itr = copy(message.cbegin(), message.cend(), chunk.begin());
*itr++ = byte{0b10000000};
fill(itr, chunk.end(), byte{0b00000000});
if(distance(chunk.begin(), itr) < 56)
{
auto length = make_span(chunk).subspan<56>();
encode(length, message_length);
}
transform(chunk);
if(distance(chunk.begin(), itr) > 56)
{
fill(chunk.begin(), chunk.end(), byte{0b00000000});
auto length = make_span(chunk).subspan<56>();
encode(length, message_length);
transform(chunk);
}
}
const byte* data() noexcept
{
encode(buffer, message_digest);
return buffer.data();
}
constexpr size_t size() const noexcept
{
return buffer.size();
}
string base64()
{
return base64::encode(make_span(data(), size()));
}
static string base64(span<const byte> message)
{
auto hash = sha1{message};
return hash.base64();
}
private:
array<uint32_t,5> message_digest;
array<byte,20> buffer;
uint64_t message_length;
template<size_t Rotation, typename Unsigned>
static Unsigned leftrotate(Unsigned number)
{
static_assert(is_unsigned_v<Unsigned>);
constexpr auto bits = numeric_limits<Unsigned>::digits;
static_assert(Rotation <= bits);
return (number << Rotation) bitor (number >> (bits-Rotation));
}
void transform(span<const byte> chunk)
{
Expects(chunk.size() == 64);
auto words = array<uint32_t,80>{};
for(auto i = 0u, j = 0u; i < 16u; ++i, j += 4u)
words[i] = to_integer<uint32_t>(chunk[j+0]) << 24 xor
to_integer<uint32_t>(chunk[j+1]) << 16 xor
to_integer<uint32_t>(chunk[j+2]) << 8 xor
to_integer<uint32_t>(chunk[j+3]);
for(auto i = 16u; i < 32u; ++i)
words[i] = leftrotate<1>(words[i-3] xor words[i-8] xor words[i-14] xor words[i-16]);
for(auto i = 32u; i < 80u; ++i)
words[i] = leftrotate<2>(words[i-6] xor words[i-16] xor words[i-28] xor words[i-32]);
auto a = message_digest[0],
b = message_digest[1],
c = message_digest[2],
d = message_digest[3],
e = message_digest[4],
f = 0u,
k = 0u;
for(auto i = 0u; i < 20u; ++i)
{
f = (b bitand c) bitor ((compl b) bitand d);
k = 0x5A827999u;
auto temp = leftrotate<5>(a) + f + e + k + words[i];
e = d;
d = c;
c = leftrotate<30>(b);
b = a;
a = temp;
}
for(auto i = 20u; i < 40u; ++i)
{
f = b xor c xor d;
k = 0x6ED9EBA1u;
auto temp = leftrotate<5>(a) + f + e + k + words[i];
e = d;
d = c;
c = leftrotate<30>(b);
b = a;
a = temp;
}
for(auto i = 40u; i < 60u; ++i)
{
f = (b bitand c) bitor (b bitand d) bitor (c bitand d);
k = 0x8F1BBCDCu;
auto temp = leftrotate<5>(a) + f + e + k + words[i];
e = d;
d = c;
c = leftrotate<30>(b);
b = a;
a = temp;
}
for(auto i = 60u; i < 80u; ++i)
{
f = b xor c xor d;
k = 0xCA62C1D6u;
auto temp = leftrotate<5>(a) + f + e + k + words[i];
e = d;
d = c;
c = leftrotate<30>(b);
b = a;
a = temp;
}
message_digest[0] += a;
message_digest[1] += b;
message_digest[2] += c;
message_digest[3] += d;
message_digest[4] += e;
}
template<typename Type, typename Integer>
static byte narrow(Integer number)
{
static_assert(is_integral_v<Integer>);
static_assert(numeric_limits<Type>::digits<numeric_limits<Integer>::digits);
return static_cast<Type>(number bitand 0b11111111);
}
static void encode(span<byte> output, const uint64_t input)
{
output[7] = narrow<byte>(input >> 0);
output[6] = narrow<byte>(input >> 8);
output[5] = narrow<byte>(input >> 16);
output[4] = narrow<byte>(input >> 24);
output[3] = narrow<byte>(input >> 32);
output[2] = narrow<byte>(input >> 40);
output[1] = narrow<byte>(input >> 48);
output[0] = narrow<byte>(input >> 56);
}
static void encode(span<byte> output, const span<uint32_t> input)
{
for (auto i = 0ull, j = 0ull; j < output.size(); ++i, j += 4ull)
{
output[j+3] = narrow<byte>(input[i]);
output[j+2] = narrow<byte>(input[i] >> 8);
output[j+1] = narrow<byte>(input[i] >> 16);
output[j+0] = narrow<byte>(input[i] >> 24);
}
}
};
} // namespace sha1
<|endoftext|>
|
<commit_before>// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include "derivator_dictionary_encoder.h"
#include "morpho/morpho.h"
#include "morpho/morpho_ids.h"
#include "utils/binary_encoder.h"
#include "utils/compressor.h"
#include "utils/split.h"
namespace ufal {
namespace morphodita {
void derivator_dictionary_encoder::encode(istream& is, istream& dictionary, bool verbose, ostream& os) {
// Load the morphology
cerr << "Loading morphology: ";
auto dictionary_start = dictionary.tellg();
unique_ptr<morpho> morpho(morpho::load(dictionary));
if (!morpho) runtime_failure("Cannot load morpho model from given file!");
if (morpho->get_derivator()) runtime_failure("The given morpho model already has a derivator!");
auto dictionary_end = dictionary.tellg();
cerr << "done" << endl;
// Load the derivator
cerr << "Loading derivator data: ";
struct lemma_info {
string sense;
string comment;
string parent;
set<string> parents;
unsigned children;
unsigned mark;
lemma_info(const string& sense = string(), const string& comment = string())
: sense(sense), comment(comment), children(0), mark(0) {}
};
map<string, lemma_info> derinet;
string line;
string part_lid, lemma_lid, lemma_comment;
vector<string> tokens;
vector<string> parts;
unordered_map<string, lemma_info> matched[2];
vector<tagged_lemma_forms> matched_lemmas_forms;
while (getline(is, line)) {
split(line, '\t', tokens);
if (tokens.size() != 2) runtime_failure("Expected two tab separated columns on derivator line '" << line << "'!");
// Generate all possible lemmas and parents
for (int i = 0; i < 2; i++) {
split(tokens[i], ' ', parts);
if (parts.size() > 2) runtime_failure("The derivator lemma desctiption '" << tokens[i] << "' contains two or more spaces!");
bool is_lemma_id = parts.size() == 1;
part_lid.assign(parts[0], 0, morpho->lemma_id_len(parts[0]));
morpho->generate(parts[0], is_lemma_id ? nullptr : parts[1].c_str(), morpho::NO_GUESSER, matched_lemmas_forms);
matched[i].clear();
for (auto&& lemma_forms : matched_lemmas_forms) {
lemma_lid.assign(lemma_forms.lemma, 0, morpho->lemma_id_len(lemma_forms.lemma));
if (!is_lemma_id || part_lid == lemma_lid) {
// Choose only the shortest lemma comment for the lemma id of lemma_form.lemma
lemma_comment.assign(lemma_forms.lemma, lemma_lid.size(), string::npos);
auto it = matched[i].emplace(lemma_lid, lemma_info(lemma_lid.substr(morpho->raw_lemma_len(lemma_lid)), lemma_comment));
if (!it.second &&
(lemma_comment.size() < it.first->second.comment.size() ||
(lemma_comment.size() == it.first->second.comment.size() && lemma_comment < it.first->second.comment)))
it.first->second.comment.assign(lemma_comment);
}
}
}
if (matched[0].empty() || matched[1].empty()) {
if (verbose)
cerr << "Could not match a lemma from line '" << line << "', skipping." << endl;
continue;
}
// Store the possible parents
derinet.insert(matched[0].begin(), matched[0].end());
derinet.insert(matched[1].begin(), matched[1].end());
for (auto&& lemma : matched[0])
for (auto&& parent : matched[1])
derinet[lemma.first].parents.insert(parent.first);
}
cerr << "done" << endl;
// Choose unique parent for every lemma
for (auto&& lemma : derinet)
if (!lemma.second.parents.empty()) {
// Try locating lexicographically smallest parent with the same sense
for (auto&& parent : lemma.second.parents)
if (derinet[parent].sense == lemma.second.sense) {
lemma.second.parent.assign(parent);
break;
}
// Otherwise, choose the lexicographically smallest parent
if (lemma.second.parent.empty())
lemma.second.parent.assign(*lemma.second.parents.begin());
// Add this edge also to the parent
derinet[lemma.second.parent].children++;
if (verbose)
cerr << lemma.first << lemma.second.comment << " -> " << lemma.second.parent << derinet[lemma.second.parent].comment << endl;
}
// Make sure the derinet contains no cycles
unsigned mark = 0;
for (auto&& lemma : derinet) {
lemma.second.mark = ++mark;
for (auto node = derinet.find(lemma.first); !node->second.parent.empty(); ) {
node = derinet.find(node->second.parent);
if (node->second.mark) {
if (node->second.mark == mark)
runtime_failure("The derivator data contains a cycle with lemma '" << lemma.first << "'!");
break;
}
node->second.mark = mark;
}
}
// Encode the derivator
cerr << "Encoding derivator: ";
os.put(morpho_ids::DERIVATOR_DICTIONARY);
binary_encoder enc;
vector<int> lengths;
for (auto&& lemma : derinet) {
if (lemma.first.size() >= lengths.size())
lengths.resize(lemma.first.size() + 1);
lengths[lemma.first.size()]++;
}
enc.add_1B(lengths.size());
for (auto&& length : lengths)
enc.add_4B(length);
enc.add_4B(derinet.size());
string prev = "";
for (auto&& lemma : derinet) {
int cpl = 0;
while (prev[cpl] && prev[cpl] == lemma.first[cpl]) cpl++;
enc.add_1B(prev.size() - cpl);
enc.add_1B(lemma.first.size() - cpl);
enc.add_data(lemma.first.c_str() + cpl);
enc.add_1B(lemma.second.comment.size());
enc.add_data(lemma.second.comment);
enc.add_2B(lemma.second.children);
if (lemma.second.parent.empty()) {
enc.add_1B(0);
} else {
unsigned best_lemma_from = 0, best_parent_from = 0, best_len = 0;
for (unsigned lemma_from = 0; lemma_from < lemma.first.size(); lemma_from++)
for (unsigned parent_from = 0; parent_from < lemma.second.parent.size(); parent_from++) {
unsigned len = 0;
while (lemma_from + len < lemma.first.size() &&
parent_from + len < lemma.second.parent.size() &&
lemma.first[lemma_from+len] == lemma.second.parent[parent_from+len])
len++;
if (len > best_len) best_lemma_from = lemma_from, best_parent_from = parent_from, best_len = len;
}
enum { REMOVE_START = 1, REMOVE_END = 2, ADD_START = 4, ADD_END = 8 };
enc.add_1B(REMOVE_START * (best_lemma_from>0) + REMOVE_END * (best_lemma_from+best_len<lemma.first.size()) +
ADD_START * (best_parent_from>0) + ADD_END * (best_parent_from+best_len<lemma.second.parent.size()));
if (best_lemma_from > 0) enc.add_1B(best_lemma_from);
if (best_lemma_from + best_len < lemma.first.size()) enc.add_1B(lemma.first.size() - best_lemma_from - best_len);
if (best_parent_from > 0) {
enc.add_1B(best_parent_from);
enc.add_data(string_piece(lemma.second.parent.c_str(), best_parent_from));
}
if (best_parent_from + best_len < lemma.second.parent.size()) {
enc.add_1B(lemma.second.parent.size() - best_parent_from - best_len);
enc.add_data(lemma.second.parent.c_str() + best_parent_from + best_len);
}
}
prev.assign(lemma.first);
}
compressor::save(os, enc);
// Append the morphology after the derivator dictionary model
if (!dictionary.seekg(dictionary_start, dictionary.beg)) runtime_failure("Cannot seek in the morpho model!");
for (auto length = dictionary_end - dictionary_start; length; length--)
os.put(dictionary.get());
cerr << "done" << endl;
}
} // namespace morphodita
} // namespace ufal
<commit_msg>Fix wrong indentation.<commit_after>// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include "derivator_dictionary_encoder.h"
#include "morpho/morpho.h"
#include "morpho/morpho_ids.h"
#include "utils/binary_encoder.h"
#include "utils/compressor.h"
#include "utils/split.h"
namespace ufal {
namespace morphodita {
void derivator_dictionary_encoder::encode(istream& is, istream& dictionary, bool verbose, ostream& os) {
// Load the morphology
cerr << "Loading morphology: ";
auto dictionary_start = dictionary.tellg();
unique_ptr<morpho> morpho(morpho::load(dictionary));
if (!morpho) runtime_failure("Cannot load morpho model from given file!");
if (morpho->get_derivator()) runtime_failure("The given morpho model already has a derivator!");
auto dictionary_end = dictionary.tellg();
cerr << "done" << endl;
// Load the derivator
cerr << "Loading derivator data: ";
struct lemma_info {
string sense;
string comment;
string parent;
set<string> parents;
unsigned children;
unsigned mark;
lemma_info(const string& sense = string(), const string& comment = string())
: sense(sense), comment(comment), children(0), mark(0) {}
};
map<string, lemma_info> derinet;
string line;
string part_lid, lemma_lid, lemma_comment;
vector<string> tokens;
vector<string> parts;
unordered_map<string, lemma_info> matched[2];
vector<tagged_lemma_forms> matched_lemmas_forms;
while (getline(is, line)) {
split(line, '\t', tokens);
if (tokens.size() != 2) runtime_failure("Expected two tab separated columns on derivator line '" << line << "'!");
// Generate all possible lemmas and parents
for (int i = 0; i < 2; i++) {
split(tokens[i], ' ', parts);
if (parts.size() > 2) runtime_failure("The derivator lemma desctiption '" << tokens[i] << "' contains two or more spaces!");
bool is_lemma_id = parts.size() == 1;
part_lid.assign(parts[0], 0, morpho->lemma_id_len(parts[0]));
morpho->generate(parts[0], is_lemma_id ? nullptr : parts[1].c_str(), morpho::NO_GUESSER, matched_lemmas_forms);
matched[i].clear();
for (auto&& lemma_forms : matched_lemmas_forms) {
lemma_lid.assign(lemma_forms.lemma, 0, morpho->lemma_id_len(lemma_forms.lemma));
if (!is_lemma_id || part_lid == lemma_lid) {
// Choose only the shortest lemma comment for the lemma id of lemma_form.lemma
lemma_comment.assign(lemma_forms.lemma, lemma_lid.size(), string::npos);
auto it = matched[i].emplace(lemma_lid, lemma_info(lemma_lid.substr(morpho->raw_lemma_len(lemma_lid)), lemma_comment));
if (!it.second &&
(lemma_comment.size() < it.first->second.comment.size() ||
(lemma_comment.size() == it.first->second.comment.size() && lemma_comment < it.first->second.comment)))
it.first->second.comment.assign(lemma_comment);
}
}
}
if (matched[0].empty() || matched[1].empty()) {
if (verbose)
cerr << "Could not match a lemma from line '" << line << "', skipping." << endl;
continue;
}
// Store the possible parents
derinet.insert(matched[0].begin(), matched[0].end());
derinet.insert(matched[1].begin(), matched[1].end());
for (auto&& lemma : matched[0])
for (auto&& parent : matched[1])
derinet[lemma.first].parents.insert(parent.first);
}
cerr << "done" << endl;
// Choose unique parent for every lemma
for (auto&& lemma : derinet)
if (!lemma.second.parents.empty()) {
// Try locating lexicographically smallest parent with the same sense
for (auto&& parent : lemma.second.parents)
if (derinet[parent].sense == lemma.second.sense) {
lemma.second.parent.assign(parent);
break;
}
// Otherwise, choose the lexicographically smallest parent
if (lemma.second.parent.empty())
lemma.second.parent.assign(*lemma.second.parents.begin());
// Add this edge also to the parent
derinet[lemma.second.parent].children++;
if (verbose)
cerr << lemma.first << lemma.second.comment << " -> " << lemma.second.parent << derinet[lemma.second.parent].comment << endl;
}
// Make sure the derinet contains no cycles
unsigned mark = 0;
for (auto&& lemma : derinet) {
lemma.second.mark = ++mark;
for (auto node = derinet.find(lemma.first); !node->second.parent.empty(); ) {
node = derinet.find(node->second.parent);
if (node->second.mark) {
if (node->second.mark == mark)
runtime_failure("The derivator data contains a cycle with lemma '" << lemma.first << "'!");
break;
}
node->second.mark = mark;
}
}
// Encode the derivator
cerr << "Encoding derivator: ";
os.put(morpho_ids::DERIVATOR_DICTIONARY);
binary_encoder enc;
vector<int> lengths;
for (auto&& lemma : derinet) {
if (lemma.first.size() >= lengths.size())
lengths.resize(lemma.first.size() + 1);
lengths[lemma.first.size()]++;
}
enc.add_1B(lengths.size());
for (auto&& length : lengths)
enc.add_4B(length);
enc.add_4B(derinet.size());
string prev = "";
for (auto&& lemma : derinet) {
int cpl = 0;
while (prev[cpl] && prev[cpl] == lemma.first[cpl]) cpl++;
enc.add_1B(prev.size() - cpl);
enc.add_1B(lemma.first.size() - cpl);
enc.add_data(lemma.first.c_str() + cpl);
enc.add_1B(lemma.second.comment.size());
enc.add_data(lemma.second.comment);
enc.add_2B(lemma.second.children);
if (lemma.second.parent.empty()) {
enc.add_1B(0);
} else {
unsigned best_lemma_from = 0, best_parent_from = 0, best_len = 0;
for (unsigned lemma_from = 0; lemma_from < lemma.first.size(); lemma_from++)
for (unsigned parent_from = 0; parent_from < lemma.second.parent.size(); parent_from++) {
unsigned len = 0;
while (lemma_from + len < lemma.first.size() &&
parent_from + len < lemma.second.parent.size() &&
lemma.first[lemma_from+len] == lemma.second.parent[parent_from+len])
len++;
if (len > best_len) best_lemma_from = lemma_from, best_parent_from = parent_from, best_len = len;
}
enum { REMOVE_START = 1, REMOVE_END = 2, ADD_START = 4, ADD_END = 8 };
enc.add_1B(REMOVE_START * (best_lemma_from>0) + REMOVE_END * (best_lemma_from+best_len<lemma.first.size()) +
ADD_START * (best_parent_from>0) + ADD_END * (best_parent_from+best_len<lemma.second.parent.size()));
if (best_lemma_from > 0) enc.add_1B(best_lemma_from);
if (best_lemma_from + best_len < lemma.first.size()) enc.add_1B(lemma.first.size() - best_lemma_from - best_len);
if (best_parent_from > 0) {
enc.add_1B(best_parent_from);
enc.add_data(string_piece(lemma.second.parent.c_str(), best_parent_from));
}
if (best_parent_from + best_len < lemma.second.parent.size()) {
enc.add_1B(lemma.second.parent.size() - best_parent_from - best_len);
enc.add_data(lemma.second.parent.c_str() + best_parent_from + best_len);
}
}
prev.assign(lemma.first);
}
compressor::save(os, enc);
// Append the morphology after the derivator dictionary model
if (!dictionary.seekg(dictionary_start, dictionary.beg)) runtime_failure("Cannot seek in the morpho model!");
for (auto length = dictionary_end - dictionary_start; length; length--)
os.put(dictionary.get());
cerr << "done" << endl;
}
} // namespace morphodita
} // namespace ufal
<|endoftext|>
|
<commit_before>#include <cmath>
#include <cstdio>
#include "json.hpp"
#include <cstring>
#include <climits>
using namespace std;
using json::JSON;
class Node
{
public:
int split_feature;
float split_value;
float leaf_value;
int is_leaf;
int child_left, child_right;
Node(){};
void set_node(int is_leaf_ = -1, float leaf_value_ = -1, int split_feature_ = -1, float split_value_ = -1, int child_left_ = -1, int child_right_ = -1)
{
is_leaf = is_leaf_;
leaf_value = leaf_value_;
split_feature = split_feature_;
split_value = split_value_;
child_left = child_left_;
child_right = child_right_;
}
void print_node(int id)
{
printf("%d %d %f %d %f %d %d\n", id, is_leaf, leaf_value, split_feature, split_value, child_left, child_right);
}
};
class Tree
{
public:
int depth;
Node *nodes;
Tree(){};
void init(int depth_ = 0)
{
depth = depth_;
nodes = new Node[1 << (depth + 1)];
}
void print_tree_util(int root, int level)
{
for (int i = 0; i < level; ++i)
printf("\t");
nodes[root].print_node(root);
int child_left = nodes[root].child_left;
int child_right = nodes[root].child_right;
if (child_left >= 0)
print_tree_util(child_left, level + 1);
if (child_right >= 0)
print_tree_util(child_right, level + 1);
}
void print_tree()
{
print_tree_util(0, 0);
}
float predict_util(float *features, int root)
{
Node node = nodes[root];
int child;
//printf ("leaf: %f", node.leaf_value);
if (node.is_leaf)
return node.leaf_value;
if (features[node.split_feature] < node.split_value)
child = node.child_left;
else
child = node.child_right;
//printf("%d %d %f %d\n", node.is_leaf, node.split_feature, node.split_value, features[node.split_feature] < node.split_value);
return predict_util(features, child);
}
float predict(float *features)
{
return predict_util(features, 0);
}
};
class CXgboost
{
public:
int n_trees;
Tree *trees;
float base_score;
int objective;
CXgboost(){};
CXgboost(int depth, int n_features, int n_trees_ , int objective_, float base_score_)
{
base_score = base_score_;
objective = objective_;
if (objective == 1)
base_score = -log(1.0 / base_score - 1.0);
n_trees = n_trees_;
char string[1000000];
trees = new Tree[n_trees];
for(int i = 0; i < n_trees; ++i)
trees[i].init(depth);
char filename[1000];
for(int i = 0; i < n_trees; ++i)
{
sprintf(filename, "trees/tree_%d.json", i);
FILE *f = fopen(filename, "r");
size_t fsize = fread(string, sizeof(char), 1000000, f);
string[fsize] = 0;
fclose(f);
json::JSON obj = JSON::Load(string);
save_tree(i, obj);
}
}
void save_tree(int tree_num, json::JSON &tree_data)
{
int node_id, split_feature, child_left_id, child_right_id;
float split_condition, leaf;
json::JSON child_left, child_right;
node_id = tree_data["nodeid"].ToInt();
if (tree_data.hasKey("split_condition"))
{
bool has_floating_point = tree_data["split_condition"].ToFloat(has_floating_point);
if (!has_floating_point)
split_condition = (float)tree_data["split_condition"].ToInt();
else
split_condition = tree_data["split_condition"].ToFloat();
}
if (tree_data.hasKey("split"))
{
string split_feature_str = tree_data["split"].ToString();
split_feature_str = split_feature_str.substr(1);
split_feature = stoi(split_feature_str);
}
if (tree_data.hasKey("leaf"))
{
bool has_floating_point = tree_data["leaf"].ToFloat(has_floating_point);
if (!has_floating_point)
leaf = (float)tree_data["leaf"].ToInt();
else
leaf = tree_data["leaf"].ToFloat();
}
if (tree_data.hasKey("children"))
{
child_left = tree_data["children"][0];
child_right = tree_data["children"][1];
}
if (!tree_data.hasKey("leaf"))
{
child_left_id = child_left["nodeid"].ToInt();
child_right_id = child_right["nodeid"].ToInt();
trees[tree_num].nodes[node_id].set_node(0, -1, split_feature, split_condition, child_left_id, child_right_id);
save_tree(tree_num, child_left);
save_tree(tree_num, child_right);
}
else
trees[tree_num].nodes[node_id].set_node(1, leaf);
}
float logistic(float x)
{
return 1 / (1 + exp(-x));
}
float predict_tree(int tree_num, float *features)
{
float tree_prediction = trees[tree_num].predict(features);
//printf ("%d %f\n", tree_num, tree_prediction);
return tree_prediction;
}
float predict(float *features, int ntree_limit)
{
float total_prediction = base_score;
for (int i = 0; i < ntree_limit; i++)
{ total_prediction += predict_tree(i, features);
//printf("%d -- %.3f, ", i+1, total_prediction);
}
if (objective == 1)
total_prediction = logistic(total_prediction);
return total_prediction;
}
};
<commit_msg>filestream added<commit_after>#include <cmath>
#include <cstdio>
#include "json.hpp"
#include <cstring>
#include <fstream>
#include <string>
#include <climits>
using namespace std;
using json::JSON;
class Node
{
public:
int split_feature;
float split_value;
float leaf_value;
int is_leaf;
int child_left, child_right;
Node(){};
void set_node(int is_leaf_ = -1, float leaf_value_ = -1, int split_feature_ = -1, float split_value_ = -1, int child_left_ = -1, int child_right_ = -1)
{
is_leaf = is_leaf_;
leaf_value = leaf_value_;
split_feature = split_feature_;
split_value = split_value_;
child_left = child_left_;
child_right = child_right_;
}
void print_node(int id)
{
printf("%d %d %f %d %f %d %d\n", id, is_leaf, leaf_value, split_feature, split_value, child_left, child_right);
}
};
class Tree
{
public:
int depth;
Node *nodes;
Tree(){};
void init(int depth_ = 0)
{
depth = depth_;
nodes = new Node[1 << (depth + 1)];
}
void print_tree_util(int root, int level)
{
for (int i = 0; i < level; ++i)
printf("\t");
nodes[root].print_node(root);
int child_left = nodes[root].child_left;
int child_right = nodes[root].child_right;
if (child_left >= 0)
print_tree_util(child_left, level + 1);
if (child_right >= 0)
print_tree_util(child_right, level + 1);
}
void print_tree()
{
print_tree_util(0, 0);
}
float predict_util(float *features, int root)
{
Node node = nodes[root];
int child;
if (node.is_leaf)
return node.leaf_value;
if (features[node.split_feature] < node.split_value)
child = node.child_left;
else
child = node.child_right;
return predict_util(features, child);
}
float predict(float *features)
{
return predict_util(features, 0);
}
};
class CXgboost
{
public:
int n_trees;
Tree *trees;
float base_score;
int objective;
CXgboost(){};
CXgboost(int depth, int n_features, int n_trees_ , int objective_, float base_score_)
{
base_score = base_score_;
objective = objective_;
if (objective == 1)
base_score = -log(1.0 / base_score - 1.0);
n_trees = n_trees_;
trees = new Tree[n_trees];
for(int i = 0; i < n_trees; ++i)
trees[i].init(depth);
string filename, string_data;
for(int i = 0; i < n_trees; ++i)
{
filename = "trees/tree_" + to_str(i) + ".json";
ifstream in;
in.open(filename);
in<<string_data;
in.close();
json::JSON obj = JSON::Load(string_data);
save_tree(i, obj);
}
}
void save_tree(int tree_num, json::JSON &tree_data)
{
int node_id, split_feature, child_left_id, child_right_id;
float split_condition, leaf;
json::JSON child_left, child_right;
node_id = tree_data["nodeid"].ToInt();
if (tree_data.hasKey("split_condition"))
{
bool has_floating_point = tree_data["split_condition"].ToFloat(has_floating_point);
if (!has_floating_point)
split_condition = (float)tree_data["split_condition"].ToInt();
else
split_condition = tree_data["split_condition"].ToFloat();
}
if (tree_data.hasKey("split"))
{
string split_feature_str = tree_data["split"].ToString();
split_feature_str = split_feature_str.substr(1);
split_feature = stoi(split_feature_str);
}
if (tree_data.hasKey("leaf"))
{
bool has_floating_point = tree_data["leaf"].ToFloat(has_floating_point);
if (!has_floating_point)
leaf = (float)tree_data["leaf"].ToInt();
else
leaf = tree_data["leaf"].ToFloat();
}
if (tree_data.hasKey("children"))
{
child_left = tree_data["children"][0];
child_right = tree_data["children"][1];
}
if (!tree_data.hasKey("leaf"))
{
child_left_id = child_left["nodeid"].ToInt();
child_right_id = child_right["nodeid"].ToInt();
trees[tree_num].nodes[node_id].set_node(0, -1, split_feature, split_condition, child_left_id, child_right_id);
save_tree(tree_num, child_left);
save_tree(tree_num, child_right);
}
else
trees[tree_num].nodes[node_id].set_node(1, leaf);
}
float logistic(float x)
{
return 1 / (1 + exp(-x));
}
float predict_tree(int tree_num, float *features)
{
float tree_prediction = trees[tree_num].predict(features);
return tree_prediction;
}
float predict(float *features, int ntree_limit)
{
float total_prediction = base_score;
for (int i = 0; i < ntree_limit; i++)
{
total_prediction += predict_tree(i, features);
}
if (objective == 1)
total_prediction = logistic(total_prediction);
return total_prediction;
}
};
<|endoftext|>
|
<commit_before>// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
// Xor all the elements to get x ^ y.
int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor<int>());
// Get the last bit where 1 occurs.
x_xor_y &= -x_xor_y;
// Get the subset of A where the number has the bit.
// The subset only contains one of the two integers, call it x.
// Xor all the elemets in the subset to get x.
vector<int> result(2, 0);
for (const auto& i : nums) {
result[!(i & x_xor_y)] ^= i;
}
return result;
}
};
class Solution2 {
public:
vector<int> singleNumber(vector<int>& nums) {
// Xor all the elements to get x ^ y.
int x_xor_y = 0;
for (const auto& i : nums) {
x_xor_y ^= i;
}
// Get the last bit where 1 occurs.
const auto bit = x_xor_y & ~(x_xor_y - 1);
// Get the subset of A where the number has the bit.
// The subset only contains one of the two integers, call it x.
// Xor all the elemets in the subset to get x.
int x = 0;
for (const auto& i : nums) {
if (i & bit) {
x ^= i;
}
}
return {x, x_xor_y ^ x};
}
};
<commit_msg>Update single-number-iii.cpp<commit_after>// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
// Xor all the elements to get x ^ y.
int x_xor_y = accumulate(nums.cbegin(), nums.cend(), 0, bit_xor<int>());
// Get the last bit where 1 occurs.
x_xor_y &= -x_xor_y;
// Get the subset of A where the number has the bit.
// The subset only contains one of the two integers, call it x.
// Xor all the elemets in the subset to get x.
vector<int> result(2, 0);
for (const auto& i : nums) {
result[static_cast<bool>(i & x_xor_y)] ^= i;
}
return result;
}
};
class Solution2 {
public:
vector<int> singleNumber(vector<int>& nums) {
// Xor all the elements to get x ^ y.
int x_xor_y = 0;
for (const auto& i : nums) {
x_xor_y ^= i;
}
// Get the last bit where 1 occurs.
const auto bit = x_xor_y & ~(x_xor_y - 1);
// Get the subset of A where the number has the bit.
// The subset only contains one of the two integers, call it x.
// Xor all the elemets in the subset to get x.
int x = 0;
for (const auto& i : nums) {
if (i & bit) {
x ^= i;
}
}
return {x, x_xor_y ^ x};
}
};
<|endoftext|>
|
<commit_before>#include "Nil.h"
#include "Runtime.h"
namespace snow {
static Handle<Object> NilPrototype = NULL;
Handle<Object>& nil_prototype() {
if (NilPrototype)
return NilPrototype;
NilPrototype = new Object;
NilPrototype->set("to_string", create_string("nil"));
NilPrototype->set("name", create_string("nil"));
return NilPrototype;
}
}<commit_msg>nil.to_string is now an empty string<commit_after>#include "Nil.h"
#include "Runtime.h"
namespace snow {
static Handle<Object> NilPrototype = NULL;
Handle<Object>& nil_prototype() {
if (NilPrototype)
return NilPrototype;
NilPrototype = new Object;
NilPrototype->set("to_string", create_string(""));
NilPrototype->set("name", create_string("nil"));
return NilPrototype;
}
}<|endoftext|>
|
<commit_before>
#include <cstdio>
#include <cstdlib>
using namespace std;
/*
* LL(1) Grammar
* expr : sub expr_rest
*
* expr_rest : | sub expr_rest
* | ε
*
* sub : term sub_rest
*
* sub_rest : & term sub_rest
* | ε
*
* term : ! term
* | atom
*
* atom : (expr)
* | V
* | F
*
* Pitfall:
* bool val = left_operand && term(); // or
* bool val = left_operand || sub();
*/
char lookahead = '$';
void match(char c) {
if (lookahead != c) {
// ERROR
}
if (lookahead == '\n') {
return;
}
lookahead = getchar();
while (lookahead == ' ') {
lookahead = getchar();
}
}
bool expr();
bool expr_rest(bool left_operand);
bool sub();
bool sub_rest(bool left_operand);
bool term();
bool atom();
void line() {
if (expr()) {
printf("V\n");
}
else {
printf("F\n");
}
match('\n');
}
bool expr() {
bool left_operand = sub();
return expr_rest(left_operand);
}
bool expr_rest(bool left_operand) {
if (lookahead == '|') {
match('|');
bool right_operand = sub();
return expr_rest(left_operand || right_operand);
}
else {
return left_operand;
}
}
bool sub() {
bool left_operand = term();
return sub_rest(left_operand);
}
bool sub_rest(bool left_operand) {
if (lookahead == '&') {
match('&');
bool right_operand = term();
return sub_rest(left_operand && right_operand);
}
else {
return left_operand;
}
}
bool term() {
if (lookahead == '!') {
match('!');
return !term();
}
else {
return atom();
}
}
bool atom() {
if (lookahead == '(') {
match('(');
bool val = expr();
match(')');
return val;
}
else if (lookahead == 'V') {
match('V');
return true;
}
else if (lookahead == 'F') {
match('F');
return false;
}
else {
printf("Symbol Error\n");
exit(1);
}
}
int main() {
int t = 0;
// while (lookahead != EOF) {
// lookahead = getchar();
// printf("Expression %d: ", ++t);
// line();
// printf("\n");
// }
lookahead = getchar();
line();
}
<commit_msg>fix error<commit_after>
#include <cstdio>
#include <cstdlib>
using namespace std;
/*
* LL(1) Grammar
* expr : sub expr_rest
*
* expr_rest : | sub expr_rest
* | ε
*
* sub : term sub_rest
*
* sub_rest : & term sub_rest
* | ε
*
* term : ! term
* | atom
*
* atom : (expr)
* | V
* | F
*
* Pitfall:
* bool val = left_operand && term(); // lazy evaluation, or
* bool val = left_operand || sub();
*/
char lookahead = '$';
void match(char c) {
if (lookahead != c) {
// ERROR
}
if (c == '\n') {
lookahead = '$';
return;
}
lookahead = getchar();
while (lookahead == ' ') {
lookahead = getchar();
}
}
bool expr();
bool expr_rest(bool left_operand);
bool sub();
bool sub_rest(bool left_operand);
bool term();
bool atom();
void line() {
if (expr()) {
printf("V\n");
}
else {
printf("F\n");
}
match('\n');
}
bool expr() {
bool left_operand = sub();
return expr_rest(left_operand);
}
bool expr_rest(bool left_operand) {
if (lookahead == '|') {
match('|');
bool right_operand = sub();
return expr_rest(left_operand || right_operand);
}
else {
return left_operand;
}
}
bool sub() {
bool left_operand = term();
return sub_rest(left_operand);
}
bool sub_rest(bool left_operand) {
if (lookahead == '&') {
match('&');
bool right_operand = term();
return sub_rest(left_operand && right_operand);
}
else {
return left_operand;
}
}
bool term() {
if (lookahead == '!') {
match('!');
return !term();
}
else {
return atom();
}
}
bool atom() {
if (lookahead == '(') {
match('(');
bool val = expr();
match(')');
return val;
}
else if (lookahead == 'V') {
match('V');
return true;
}
else if (lookahead == 'F') {
match('F');
return false;
}
else {
printf("Symbol Error\n");
exit(1);
}
}
int main() {
int t = 0;
while (1) {
lookahead = getchar();
if (lookahead == EOF) {
break;
}
printf("Expression %d: ", ++t);
line();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"
using namespace std;
int menu();
int main() {
vector<Usuario*> usuarios;
bool seguir = true;
cout << "Bienvenido al Restaurante: - Como vos Querras! -." << endl;
while (seguir == true) {
int resp1 = menu();
if (resp1 == 1)
{
bool user = false, pass = false, enter = false, enter2 = false;
int userM;
while (enter == false) {
cout << "Ingrese el nombre de usuario: " << endl;
string nombre1;
cin >> nombre1;
cout << "Ingrese la contraseña: " << endl;
string contra1;
cin >> contra1;
for (int i = 0; i < usuarios.size(); ++i)
{
if (usuarios.at(i) -> getUsername() == nombre1)
{
user = true;
}
if (usuarios.at(i) -> getPassword() == contra1)
{
pass = true;
}
if (user == true && pass == true)
{
i = usuarios.size();
userM = i;
enter = true;
enter2 = true;
} else {
user = false;
pass = false;
}
}
if (enter == false)
{
cout << "Desea salir?" << endl;
cout << "1) Salir" << endl;
cout << "2) Seguir tratando" << endl;
int resp0;
cin >> resp0;
if (resp0 == 1)
{
enter = true;
} else {
enter = false;
}
}
}
if (enter2 == true)
{
bool seguir2 = true;
while(seguir2 == true) {
if (dynamic_cast<Cliente*>(usuarios.at(userM)))
{
Cliente* temp1 = dynamic_cast<Cliente*>(usuarios.at(userM));
cout << "Que desea hacer?" << endl;
cout << "1) Dar rating" << endl;
cout << "2) Salir" << endl;
int resp2;
cin >> resp2;
if (resp2 == 1)
{
cout << "Ingrese el rating del 1 - 5 que desea darle al restaurante: " << endl;
int rating;
cin >> rating;
while (rating < 0 || rating > 5) {
cout << "Rating invalido, ingrese su rating de nuevo." << endl;
cin >> rating;
}
} else {
seguir2 = false;
}
} else if (dynamic_cast<Personal*>(usuarios.at(userM)))
{
if (dynamic_cast<Administrador*>(usuarios.at(userM)))
{
Administrador* temp2 = dynamic_cast<Administrador*>(usuarios.at(userM));
} else if (dynamic_cast<Chef*>(usuarios.at(userM)))
{
Chef* temp3 = dynamic_cast<Chef*>(usuarios.at(userM));
} else if (dynamic_cast<Lavaplatos*>(usuarios.at(userM)))
{
Lavaplatos* temp4 = dynamic_cast<Lavaplatos*>(usuarios.at(userM));
} else if (dynamic_cast<Mesero*>(usuarios.at(userM)))
{
Mesero* temp5 = dynamic_cast<Mesero*>(usuarios.at(userM));
}
}
}
}
} else {
cout << "Nos vemos luego!" << endl;
seguir = false;
}
}
return 0;
}
int menu() {
cout << "-------Menu-------\n";
cout << "1) Ingresar al sistema\n";
cout << "2) Salir\n";
int resp;
cin >> resp;
return resp;
}<commit_msg>Main modificado<commit_after>#include <iostream>
#include <string>
#include <vector>
#include "Usuario.h"
#include "Cliente.h"
#include "Personal.h"
#include "Administrador.h"
#include "Chef.h"
#include "Lavaplatos.h"
#include "Mesero.h"
using namespace std;
int menu();
void promedioClientes(vector<Usuario*>);
int main() {
vector<Usuario*> usuarios;
usuarios.push_back(new Administrador("admin123", "pass123", 20, "0801182519855", ));
bool seguir = true;
cout << "Bienvenido al Restaurante: - Como vos Querras! -." << endl;
while (seguir == true) {
int resp1 = menu();
if (resp1 == 1)
{
bool user = false, pass = false, enter = false, enter2 = false;
int userM;
while (enter == false) {
cout << "Ingrese el nombre de usuario: " << endl;
string nombre1;
cin >> nombre1;
cout << "Ingrese la contraseña: " << endl;
string contra1;
cin >> contra1;
for (int i = 0; i < usuarios.size(); ++i)
{
if (usuarios.at(i) -> getUsername() == nombre1)
{
user = true;
}
if (usuarios.at(i) -> getPassword() == contra1)
{
pass = true;
}
if (user == true && pass == true)
{
i = usuarios.size();
userM = i;
enter = true;
enter2 = true;
} else {
user = false;
pass = false;
}
}
if (enter == false)
{
cout << "Desea salir?" << endl;
cout << "1) Salir" << endl;
cout << "2) Seguir tratando" << endl;
int resp0;
cin >> resp0;
if (resp0 == 1)
{
enter = true;
} else {
enter = false;
}
}
}
if (enter2 == true)
{
bool seguir2 = true;
while(seguir2 == true) {
if (dynamic_cast<Cliente*>(usuarios.at(userM)))
{
Cliente* temp1 = dynamic_cast<Cliente*>(usuarios.at(userM));
cout << "Que desea hacer?" << endl;
cout << "1) Dar rating" << endl;
cout << "2) Salir" << endl;
int resp2;
cin >> resp2;
while (resp2 < 1 || resp2 > 2) {
cout << "Opcion invalida, ingrese su opcion de nuevo." << endl;
cin >> resp2;
}
if (resp2 == 1)
{
cout << "Ingrese el rating del 1 - 5 que desea darle al restaurante: " << endl;
int rating;
cin >> rating;
while (rating < 0 || rating > 5) {
cout << "Rating invalido, ingrese su rating de nuevo." << endl;
cin >> rating;
}
temp1 -> setEstrellas(rating);
usuarios.at(userM) = temp;
cout << "Rating guardado exitosamente!" << endl;
promedioClientes(usuarios);
} else {
seguir2 = false;
}
} else if (dynamic_cast<Personal*>(usuarios.at(userM)))
{
if (dynamic_cast<Administrador*>(usuarios.at(userM)))
{
Administrador* temp2 = dynamic_cast<Administrador*>(usuarios.at(userM));
} else if (dynamic_cast<Chef*>(usuarios.at(userM)))
{
Chef* temp3 = dynamic_cast<Chef*>(usuarios.at(userM));
cout << "Que desea hacer?" << endl;
cout << "1) Gritarle a un lavaplatos" << endl;
cout << "2) Agradar a un lavaplatos" << endl;
cout << "3) Salir" << endl;
int resp4;
cin >> resp4;
while (resp4 < 1 || resp4 > 3) {
cout << "Opcion invalida, ingrese su opcion de nuevo." << endl;
cin >> resp4;
}
if (resp4 == 1)
{
cout << "Cuanta motivacion desea quitarle al lavaplatos?" << endl;
int motivacionQ;
cin >> motivacionQ;
cout << "A cual empleado le desea gritar?" << endl;
for (int i = 0; i < usuarios.size(); ++i)
{
if (i != userM)
{
cout << i << ") " << usuarios.at(i) -> getNombre();
}
}
int respB;
cin >> respB;
while (respB < 0 || respB > usuarios.size() || respB == userM) {
cout << "Opcion invalida, ingrese su opcion de nuevo!" << endl;
cin >> respB;
}
usuarios.at(respB) -> setMotivacion(usuarios.at(respB) -> getMotivacion() - motivacionQ);
cout << "Gritada ejecutada exitosamente!" << endl;
} else if (resp4 == 2)
{
cout << "Cuanta motivacion desea darle al lavaplatos?" << endl;
int motivacionA;
cin >> motivacionA;
cout << "A cual empleado le desea agradar?" << endl;
for (int i = 0; i < usuarios.size(); ++i)
{
if (i != userM)
{
cout << i << ") " << usuarios.at(i) -> getNombre();
}
}
int respB;
cin >> respB;
while (respB < 0 || respB > usuarios.size() || respB == userM) {
cout << "Opcion invalida, ingrese su opcion de nuevo!" << endl;
cin >> respB;
}
usuarios.at(respB) -> setMotivacion(usuarios.at(respB) -> getMotivacion() + motivacionA);
cout << "Agradada ejecutada exitosamente!" << endl;
} else {
seguir2 == false;
}
} else if (dynamic_cast<Lavaplatos*>(usuarios.at(userM)))
{
Lavaplatos* temp4 = dynamic_cast<Lavaplatos*>(usuarios.at(userM));
cout << "Que desea hacer?" << endl;
cout << "1) Renunciar" << endl;
cout << "2) Pedir aumento" << endl;
cout << "3) Salir" << endl;
int resp5;
cin >> resp5;
while (resp5 < 1 || resp5 > 3) {
cout << "Opcion invalida, ingrese su opcion de nuevo." << endl;
cin >> resp5;
}
if (resp5 == 1)
{
if (usuarios.at(userM) -> getMotivacion() <= 25)
{
usuarios.erase(usuarios.begin() + userM);
cout << "Lavaplatos se fue del establecimiento." << endl;
seguir2 == false;
} else {
cout << "La motivacion del lavaplatos no es suficientemente baja para renunciar." << endl;
}
} else if (resp5 == 2)
{
if (usuarios.at(userM) -> getMotivacion() >= 100)
{
cout << "De cuanto sera el aumento del lavaplatos?" << endl;
int aumento;
cin >> aumento;
while (aumento > usuarios.at(userM) -> getSueldo()) {
cout << "El aumento no puede ser mayor al saldo actual del lavaplatos, ingrese aumento de nuevo."
cin >> aumento;
}
usuarios.at(userM) -> setSueldo(usuarios.at(userM) -> getSueldo() + aumento);
cout << "Aumento aplicado!" << endl;
}
} else {
seguir2 == false;
}
} else if (dynamic_cast<Mesero*>(usuarios.at(userM)))
{
Mesero* temp5 = dynamic_cast<Mesero*>(usuarios.at(userM));
}
}
}
}
} else {
cout << "Nos vemos luego!" << endl;
seguir = false;
}
}
return 0;
}
int menu() {
cout << "-------Menu-------\n";
cout << "1) Ingresar al sistema\n";
cout << "2) Salir\n";
int resp;
cin >> resp;
return resp;
}
void promedioClientes(vector<Usuario*> usuarios) {
double total;
int cont;
for (int i = 0; i < usuarios.size(); ++i)
{
if (dynamic_cast<Cliente*>(usuarios.at(i)))
{
total = total + usuarios.at(i) -> getEstrellas();
cont++;
}
}
total = total / cont;
cout << "El numero de estrellas del restaurante es de: " << total << endl;
}<|endoftext|>
|
<commit_before>#if USE_PARQUET
#include <iostream>
#include <stdio.h>
#include "parquet/parquet.h"
#include "rdd.h"
#include "hdfs.h"
using namespace parquet;
using namespace parquet_cpp;
using namespace std;
// 4 byte constant + 4 byte metadata len
const uint32_t FOOTER_SIZE = 8;
const uint8_t PARQUET_MAGIC[4] = {'P', 'A', 'R', '1'};
class ParquetFile {
public:
ParquetFile(char const* url) {
if (strncmp(url, "hdfs://", 7) == 0) {
path = (char*)strchr(url+7, '/');
if (fs == NULL) {
*path = '\0';
fs = hdfsConnect(url, 0);
assert(fs);
*path = '/';
}
if (hdfsExists(fs, path) == 0) {
hf = hdfsOpenFile(fs, path, O_RDONLY, 0, 0, 0);
assert(hf);
} else {
hf = NULL;
}
f = NULL;
} else {
hf = NULL;
f = fopen(url, "rb");
//assert(f);
}
}
static bool isLocal(char const* url, bool& eof) {
char* path = (char*)strchr(url+7, '/');
if (fs == NULL) {
*path = '\0';
fs = hdfsConnect(url, 0);
assert(fs);
*path = '/';
}
char*** hosts = hdfsGetHosts(fs, path, 0, FOOTER_SIZE);
if (hosts == NULL) {
eof = true;
return false;
}
eof = false;
bool my = Cluster::instance->isLocalNode(hosts[0][0]);
hdfsFreeHosts(hosts);
return my;
}
bool exists() {
return hf != NULL || f != NULL;
}
size_t size() {
if (hf) {
hdfsFileInfo* info = hdfsGetPathInfo(fs, path);
size_t sz = info->mSize;
hdfsFreeFileInfo(info, 1);
return sz;
//return hdfsAvailable(fs, hf);
} else {
int rc = fseek(f, 0, SEEK_END);
assert(rc == 0);
return ftell(f);
}
}
void seek(size_t pos) {
if (hf) {
int rc = hdfsSeek(fs, hf, pos);
assert(rc == 0);
} else {
int rc = fseek(f, pos, SEEK_SET);
assert(rc == 0);
}
}
void read(void* buf, size_t size) {
if (hf) {
size_t offs = 0;
while (offs < size) {
int n = hdfsRead(fs, hf, (char*)buf + offs, size - offs);
assert(n > 0);
offs += n;
}
} else {
int rc = fread(buf, size, 1, f);
assert(rc == 1);
}
}
~ParquetFile() {
if (f != NULL) {
fclose(f);
} else if (hf != NULL) {
hdfsCloseFile(fs, hf);
}
}
private:
static hdfsFS fs;
hdfsFile hf;
char* path;
FILE* f;
};
hdfsFS ParquetFile::fs;
bool GetFileMetadata(ParquetFile& file, FileMetaData* metadata)
{
size_t file_len = file.size();
if (file_len < FOOTER_SIZE) {
cerr << "Invalid parquet file. Corrupt footer." << endl;
return false;
}
uint8_t footer_buffer[FOOTER_SIZE];
file.seek(file_len - FOOTER_SIZE);
file.read(footer_buffer, FOOTER_SIZE);
if (memcmp(footer_buffer + 4, PARQUET_MAGIC, 4) != 0) {
cerr << "Invalid parquet file. Corrupt footer." << endl;
return false;
}
uint32_t metadata_len = *reinterpret_cast<uint32_t*>(footer_buffer);
size_t metadata_start = file_len - FOOTER_SIZE - metadata_len;
if (metadata_start < 0) {
cerr << "Invalid parquet file. File is less than file metadata size." << endl;
return false;
}
file.seek(metadata_start);
uint8_t metadata_buffer[metadata_len];
file.read(metadata_buffer, metadata_len);
DeserializeThriftMsg(metadata_buffer, &metadata_len, metadata);
return true;
}
bool ParquetReader::loadFile(char const* dir, size_t partNo)
{
char path[MAX_PATH_LEN];
sprintf(path, "%s/part-r-%05d.parquet", dir, (int)partNo + 1);
ParquetFile file(path);
if (!file.exists()) {
return false;
}
if (!GetFileMetadata(file, &metadata)) {
return false;
}
size_t nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
nColumns += row_group.columns.size();
}
columns.resize(0); // do cleanup
columns.resize(nColumns);
nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
for (size_t c = 0; c < row_group.columns.size(); ++c) {
const ColumnChunk& col = row_group.columns[c];
size_t col_start = col.meta_data.data_page_offset;
if (col.meta_data.__isset.dictionary_page_offset) {
if (col_start > col.meta_data.dictionary_page_offset) {
col_start = col.meta_data.dictionary_page_offset;
}
}
file.seek(col_start);
ParquetColumnReader& cr = columns[nColumns++];
cr.column_buffer.resize(col.meta_data.total_compressed_size);
file.read(&cr.column_buffer[0], cr.column_buffer.size());
cr.stream = new InMemoryInputStream(&cr.column_buffer[0], cr.column_buffer.size());
cr.reader = new ColumnReader(&col.meta_data, &metadata.schema[c + 1], cr.stream);
}
}
return true;
}
bool ParquetReader::loadLocalFile(char const* dir, size_t partNo, bool& eof)
{
char url[MAX_PATH_LEN];
sprintf(url, "%s/part-r-%05d.parquet", dir, (int)partNo + 1);
if (ParquetFile::isLocal(url, eof)) {
ParquetFile file(url);
if (!GetFileMetadata(file, &metadata)) {
return false;
}
size_t nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
nColumns += row_group.columns.size();
}
columns.resize(0); // do cleanup
columns.resize(nColumns);
nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
for (size_t c = 0; c < row_group.columns.size(); ++c) {
const ColumnChunk& col = row_group.columns[c];
size_t col_start = col.meta_data.data_page_offset;
if (col.meta_data.__isset.dictionary_page_offset) {
if (col_start > col.meta_data.dictionary_page_offset) {
col_start = col.meta_data.dictionary_page_offset;
}
}
file.seek(col_start);
ParquetColumnReader& cr = columns[nColumns++];
cr.column_buffer.resize(col.meta_data.total_compressed_size);
file.read(&cr.column_buffer[0], cr.column_buffer.size());
cr.stream = new InMemoryInputStream(&cr.column_buffer[0], cr.column_buffer.size());
cr.reader = new ColumnReader(&col.meta_data, &metadata.schema[c + 1], cr.stream);
}
}
return true;
}
return false;
}
#endif
<commit_msg>Correctly handle in Kraps@HDFS case of multiple executors per host<commit_after>#if USE_PARQUET
#include <iostream>
#include <stdio.h>
#include "parquet/parquet.h"
#include "rdd.h"
#include "hdfs.h"
using namespace parquet;
using namespace parquet_cpp;
using namespace std;
// 4 byte constant + 4 byte metadata len
const uint32_t FOOTER_SIZE = 8;
const uint8_t PARQUET_MAGIC[4] = {'P', 'A', 'R', '1'};
class ParquetFile {
public:
ParquetFile(char const* url) {
if (strncmp(url, "hdfs://", 7) == 0) {
path = (char*)strchr(url+7, '/');
if (fs == NULL) {
*path = '\0';
fs = hdfsConnect(url, 0);
assert(fs);
*path = '/';
}
if (hdfsExists(fs, path) == 0) {
hf = hdfsOpenFile(fs, path, O_RDONLY, 0, 0, 0);
assert(hf);
} else {
hf = NULL;
}
f = NULL;
} else {
hf = NULL;
f = fopen(url, "rb");
//assert(f);
}
}
static bool isLocal(char const* url, bool& eof) {
char* path = (char*)strchr(url+7, '/');
if (fs == NULL) {
*path = '\0';
fs = hdfsConnect(url, 0);
assert(fs);
*path = '/';
}
char*** hosts = hdfsGetHosts(fs, path, 0, FOOTER_SIZE);
if (hosts == NULL) {
eof = true;
return false;
}
eof = false;
bool my = Cluster::instance->isLocalNode(hosts[0][0]);
hdfsFreeHosts(hosts);
return my;
}
bool exists() {
return hf != NULL || f != NULL;
}
size_t size() {
if (hf) {
hdfsFileInfo* info = hdfsGetPathInfo(fs, path);
size_t sz = info->mSize;
hdfsFreeFileInfo(info, 1);
return sz;
//return hdfsAvailable(fs, hf);
} else {
int rc = fseek(f, 0, SEEK_END);
assert(rc == 0);
return ftell(f);
}
}
void seek(size_t pos) {
if (hf) {
int rc = hdfsSeek(fs, hf, pos);
assert(rc == 0);
} else {
int rc = fseek(f, pos, SEEK_SET);
assert(rc == 0);
}
}
void read(void* buf, size_t size) {
if (hf) {
size_t offs = 0;
while (offs < size) {
int n = hdfsRead(fs, hf, (char*)buf + offs, size - offs);
assert(n > 0);
offs += n;
}
} else {
int rc = fread(buf, size, 1, f);
assert(rc == 1);
}
}
~ParquetFile() {
if (f != NULL) {
fclose(f);
} else if (hf != NULL) {
hdfsCloseFile(fs, hf);
}
}
private:
static hdfsFS fs;
hdfsFile hf;
char* path;
FILE* f;
};
hdfsFS ParquetFile::fs;
bool GetFileMetadata(ParquetFile& file, FileMetaData* metadata)
{
size_t file_len = file.size();
if (file_len < FOOTER_SIZE) {
cerr << "Invalid parquet file. Corrupt footer." << endl;
return false;
}
uint8_t footer_buffer[FOOTER_SIZE];
file.seek(file_len - FOOTER_SIZE);
file.read(footer_buffer, FOOTER_SIZE);
if (memcmp(footer_buffer + 4, PARQUET_MAGIC, 4) != 0) {
cerr << "Invalid parquet file. Corrupt footer." << endl;
return false;
}
uint32_t metadata_len = *reinterpret_cast<uint32_t*>(footer_buffer);
size_t metadata_start = file_len - FOOTER_SIZE - metadata_len;
if (metadata_start < 0) {
cerr << "Invalid parquet file. File is less than file metadata size." << endl;
return false;
}
file.seek(metadata_start);
uint8_t metadata_buffer[metadata_len];
file.read(metadata_buffer, metadata_len);
DeserializeThriftMsg(metadata_buffer, &metadata_len, metadata);
return true;
}
bool ParquetReader::loadFile(char const* dir, size_t partNo)
{
char path[MAX_PATH_LEN];
sprintf(path, "%s/part-r-%05d.parquet", dir, (int)partNo + 1);
ParquetFile file(path);
if (!file.exists()) {
return false;
}
if (!GetFileMetadata(file, &metadata)) {
return false;
}
size_t nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
nColumns += row_group.columns.size();
}
columns.resize(0); // do cleanup
columns.resize(nColumns);
nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
for (size_t c = 0; c < row_group.columns.size(); ++c) {
const ColumnChunk& col = row_group.columns[c];
size_t col_start = col.meta_data.data_page_offset;
if (col.meta_data.__isset.dictionary_page_offset) {
if (col_start > col.meta_data.dictionary_page_offset) {
col_start = col.meta_data.dictionary_page_offset;
}
}
file.seek(col_start);
ParquetColumnReader& cr = columns[nColumns++];
cr.column_buffer.resize(col.meta_data.total_compressed_size);
file.read(&cr.column_buffer[0], cr.column_buffer.size());
cr.stream = new InMemoryInputStream(&cr.column_buffer[0], cr.column_buffer.size());
cr.reader = new ColumnReader(&col.meta_data, &metadata.schema[c + 1], cr.stream);
}
}
return true;
}
bool ParquetReader::loadLocalFile(char const* dir, size_t partNo, bool& eof)
{
char url[MAX_PATH_LEN];
sprintf(url, "%s/part-r-%05d.parquet", dir, (int)partNo + 1);
Cluster* cluster = Cluster::instance;
size_t nExecutors = cluster->nExecutorsPerHost;
if (ParquetFile::isLocal(url, eof) && cluster->nodeId % nExecutors == partNo % nExecutors) {
ParquetFile file(url);
if (!GetFileMetadata(file, &metadata)) {
return false;
}
size_t nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
nColumns += row_group.columns.size();
}
columns.resize(0); // do cleanup
columns.resize(nColumns);
nColumns = 0;
for (size_t i = 0; i < metadata.row_groups.size(); ++i) {
const RowGroup& row_group = metadata.row_groups[i];
for (size_t c = 0; c < row_group.columns.size(); ++c) {
const ColumnChunk& col = row_group.columns[c];
size_t col_start = col.meta_data.data_page_offset;
if (col.meta_data.__isset.dictionary_page_offset) {
if (col_start > col.meta_data.dictionary_page_offset) {
col_start = col.meta_data.dictionary_page_offset;
}
}
file.seek(col_start);
ParquetColumnReader& cr = columns[nColumns++];
cr.column_buffer.resize(col.meta_data.total_compressed_size);
file.read(&cr.column_buffer[0], cr.column_buffer.size());
cr.stream = new InMemoryInputStream(&cr.column_buffer[0], cr.column_buffer.size());
cr.reader = new ColumnReader(&col.meta_data, &metadata.schema[c + 1], cr.stream);
}
}
return true;
}
return false;
}
#endif
<|endoftext|>
|
<commit_before>// Here's a wirish include:
#include <wirish/wirish.h>
#include "fpga-comm/FPGAComm.h"
FPGAComm* comm;
void setup(void) {
// init the FPGA comm
comm = FPGAComm::getInstance();
FPGAPinInLayout inLayout;
inLayout.leftWall = D0;
inLayout.frontWall = D1;
inLayout.rightWall = D2;
inLayout.interrupt = D13;
FPGAPinOutLayout outLayout;
outLayout.drive = D6;
outLayout.turn = D7;
outLayout.dataStart = D8;
outLayout.interrupt = D12;
comm->init(inLayout, outLayout);
pinMode(BOARD_LED_PIN, OUTPUT);
}
void loop(void) {
if (comm->isNewData()) {
SerialUSB.println("Found new data!");
FPGAInPacket packet = comm->getLastPacket();
SerialUSB.print("LeftWall: ");
SerialUSB.println(packet.leftWall);
SerialUSB.print("FrontWall: ");
SerialUSB.println(packet.frontWall);
SerialUSB.print("RightWall: ");
SerialUSB.println(packet.rightWall);
}
else {
SerialUSB.println("No new data");
}
//toggleLED();
digitalWrite(BOARD_LED_PIN, LOW);
delay(250);
}
// Standard libmaple init() and main.
//
// The init() part makes sure your board gets set up correctly. It's
// best to leave that alone unless you know what you're doing. main()
// is the usual "call setup(), then loop() forever", but of course can
// be whatever you want.
__attribute__((constructor)) void premain() {
init();
}
int main(void) {
setup();
while (true) {
loop();
}
return 0;
}
<commit_msg>fixed stupid problem btsync kinda sucks sometimes..<commit_after>// Here's a wirish include:
#include <wirish/wirish.h>
#include "fpga-comm/FPGAComm.h"
FPGAComm* comm;
void setup(void) {
// init the FPGA comm
comm = FPGAComm::getInstance();
FPGAPinInLayout inLayout;
inLayout.leftWall = D0;
inLayout.frontWall = D1;
inLayout.rightWall = D2;
inLayout.interrupt = D13;
FPGAPinOutLayout outLayout;
outLayout.drive = D6;
outLayout.turn = D7;
outLayout.dataStart = D8;
outLayout.interrupt = D12;
comm->init(inLayout, outLayout);
pinMode(BOARD_LED_PIN, OUTPUT);
}
void loop(void) {
if (comm->isNewData()) {
SerialUSB.println("Found new data!");
FPGAInPacket packet = comm->getLastPacket();
SerialUSB.print("LeftWall: ");
SerialUSB.println(packet.leftWall);
SerialUSB.print("FrontWall: ");
SerialUSB.println(packet.frontWall);
SerialUSB.print("RightWall: ");
SerialUSB.println(packet.rightWall);
}
else {
SerialUSB.println("No new data");
}
//toggleLED();
digitalWrite(BOARD_LED_PIN, LOW);
delay(250);
}
// Standard libmaple init() and main.
//
// The init() part makes sure your board gets set up correctly. It's
// best to leave that alone unless you know what you're doing. main()
// is the usual "call setup(), then loop() forever", but of course can
// be whatever you want.
__attribute__((constructor)) void premain() {
init();
}
int main(void) {
setup();
while (true) {
loop();
}
return 0;
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* mapper_utils.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/dml/mapper/mapper_utils.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/bridge/ddl/schema_transformer.h"
#include "backend/planner/projection_node.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Utils
//===--------------------------------------------------------------------===//
const ValueArray PlanTransformer::BuildParams(const ParamListInfo param_list) {
ValueArray params;
if (param_list != nullptr) {
params.Reset(param_list->numParams);
ParamExternData *postgres_param = param_list->params;
for (int i = 0; i < params.GetSize(); ++i, ++postgres_param) {
params[i] = TupleTransformer::GetValue(postgres_param->value,
postgres_param->ptype);
}
}
LOG_INFO("Built %d params: \n%s", params.GetSize(), params.Debug().c_str());
return params;
}
/**
* @brief Extract the common things shared by all Scan types:
* generic predicates and projections.
*
* @param[out] parent Set to a created projection plan node if one is needed,
* or NULL otherwise.
*
* @param[out] predicate Set to the transformed Expression based on qual. Or NULL if so is qual.
*
* @param[out] out_col_list Set to the output column list if ps_ProjInfo contains only
* direct mapping of attributes. \b Empty if no direct map is presented.
*
* @param[in] sstate The ScanState from which generic things are extracted.
*
* @param[in] use_projInfo Parse projInfo or not. Sometimes the projInfo of a Scan may have been
* stolen by its parent.
*
* @return Nothing.
*/
void PlanTransformer::GetGenericInfoFromScanState(
planner::AbstractPlanNode*& parent,
expression::AbstractExpression*& predicate,
std::vector<oid_t>& out_col_list,
const ScanState* sstate,
bool use_projInfo) {
List* qual = sstate->ps.qual;
const ProjectionInfo *pg_proj_info = sstate->ps.ps_ProjInfo;
oid_t out_column_count = static_cast<oid_t>(sstate->ps.ps_ResultTupleSlot->tts_tupleDescriptor->natts);
parent = nullptr;
predicate = nullptr;
out_col_list.clear();
/* Transform predicate */
predicate = BuildPredicateFromQual(qual);
/* Transform project info */
std::unique_ptr<const planner::ProjectInfo> project_info(nullptr);
if(use_projInfo){
project_info.reset(BuildProjectInfo(pg_proj_info, out_column_count));
}
/*
* Based on project_info, see whether we should create a functional projection node
* on top, or simply pushed in an output column list.
*/
if(nullptr == project_info.get()){ // empty predicate, or ignore projInfo, pass thru
LOG_INFO("No projections (all pass through)");
assert(out_col_list.size() == 0);
}
else if(project_info->GetTargetList().size() > 0){ // Have non-trivial projection, add a plan node
LOG_INFO("Non-trivial projections are found. Projection node will be created. \n");
auto project_schema =
SchemaTransformer::GetSchemaFromTupleDesc(sstate->ps.ps_ResultTupleSlot->tts_tupleDescriptor);
parent = new planner::ProjectionNode(project_info.release(), project_schema);
}
else { // Pure direct map
assert(project_info->GetTargetList().size() == 0);
assert(project_info->GetDirectMapList().size() > 0);
LOG_INFO("Pure direct map projection.\n");
std::vector<oid_t> column_ids;
column_ids = BuildColumnListFromDirectMap(project_info->GetDirectMapList());
out_col_list = std::move(column_ids);
assert(out_col_list.size() == out_column_count);
}
}
/**
* @brief Transform a PG ProjectionInfo structure to a Peloton ProjectInfo
*object.
*
* @param pg_proj_info The PG ProjectionInfo struct to be transformed
* @param column_count The valid column count of output. This is used to
* skip junk attributes in PG.
* @return An ProjectInfo object built from the PG ProjectionInfo.
* NULL if no valid project info is found.
*
* @warning Some projections in PG may be ignored.
* For example, the "row" projection
*/
const planner::ProjectInfo *PlanTransformer::BuildProjectInfo(
const ProjectionInfo *pg_pi,
oid_t column_count) {
if (pg_pi == nullptr) {
LOG_INFO("pg proj info is null, no projection");
return nullptr;
}
/*
* (A) Transform non-trivial target list
*/
planner::ProjectInfo::TargetList target_list;
ListCell *tl;
foreach (tl, pg_pi->pi_targetlist) {
GenericExprState *gstate = (GenericExprState *)lfirst(tl);
TargetEntry *tle = (TargetEntry *)gstate->xprstate.expr;
AttrNumber resind = tle->resno - 1;
if (!(resind < column_count
&& AttributeNumberIsValid(tle->resno)
&& AttrNumberIsForUserDefinedAttr(tle->resno)
&& !tle->resjunk)){
LOG_INFO("Invalid / Junk attribute. Skipped. \n");
continue; // skip junk attributes
}
oid_t col_id = static_cast<oid_t>(resind);
auto peloton_expr = ExprTransformer::TransformExpr(gstate->arg);
if(peloton_expr == nullptr){
LOG_INFO("Seems to be a row value expression. Skipped.\n");
continue;
}
LOG_INFO("Target : column id %u, Expression : \n%s\n", col_id, peloton_expr->DebugInfo().c_str());
target_list.emplace_back(col_id, peloton_expr);
}
/*
* (B) Transform direct map list
* Special case:
* a null constant may be specified in SimpleVars by PG,
* in case of that, we add a Target to target_list we created above.
*/
planner::ProjectInfo::DirectMapList direct_map_list;
if (pg_pi->pi_numSimpleVars > 0) {
int numSimpleVars = pg_pi->pi_numSimpleVars;
//bool *isnull = pg_pi->pi_slot->tts_isnull;
int *varSlotOffsets = pg_pi->pi_varSlotOffsets;
int *varNumbers = pg_pi->pi_varNumbers;
if (pg_pi->pi_directMap) // Sequential direct map
{
/* especially simple case where vars go to output in order */
for (int i = 0; i < numSimpleVars && i < column_count; i++) {
oid_t tuple_idx =
(varSlotOffsets[i] == offsetof(ExprContext, ecxt_innertuple) ? 1
: 0);
int varNumber = varNumbers[i] - 1;
oid_t in_col_id = static_cast<oid_t>(varNumber);
oid_t out_col_id = static_cast<oid_t>(i);
if (true) { // Non null, direct map
direct_map_list.emplace_back(
out_col_id, planner::ProjectInfo::DirectMap::second_type(
tuple_idx, in_col_id));
} else { // NUll, constant, added to target_list
Value null = ValueFactory::GetNullValue();
target_list.emplace_back(out_col_id,
expression::ConstantValueFactory(null));
}
LOG_INFO("Input column : %u , Output column : %u \n", in_col_id,
out_col_id);
}
} else // Non-sequential direct map
{
/* we have to pay attention to varOutputCols[] */
int *varOutputCols = pg_pi->pi_varOutputCols;
for (int i = 0; i < numSimpleVars; i++) {
oid_t tuple_idx =
(varSlotOffsets[i] == offsetof(ExprContext, ecxt_innertuple) ? 1
: 0);
int varNumber = varNumbers[i] - 1;
int varOutputCol = varOutputCols[i] - 1;
oid_t in_col_id = static_cast<oid_t>(varNumber);
oid_t out_col_id = static_cast<oid_t>(varOutputCol);
if (true) { // Non null, direct map
direct_map_list.emplace_back(
out_col_id, planner::ProjectInfo::DirectMap::second_type(
tuple_idx, in_col_id));
} else { // NUll, constant
Value null = ValueFactory::GetNullValue();
target_list.emplace_back(out_col_id,
expression::ConstantValueFactory(null));
}
LOG_INFO("Input column : %u , Output column : %u \n", in_col_id,
out_col_id);
}
}
}
if(target_list.empty() && direct_map_list.empty())
return nullptr;
return new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list));
}
/**
* @brief Transform a PG qual list to an expression tree.
*
* @return Expression tree, null if empty.
*/
expression::AbstractExpression*
PlanTransformer::BuildPredicateFromQual(List* qual){
expression::AbstractExpression* predicate =
ExprTransformer::TransformExpr(
reinterpret_cast<ExprState*>(qual) );
LOG_INFO("Predicate:\n%s \n", (nullptr==predicate)? "NULL" : predicate->DebugInfo().c_str());
return predicate;
}
/**
* @brief Transform a DirectMapList to a one-dimensional column list.
* This is intended to incorporate a pure-direct-map projection into a scan.
* The caller should make sure the direct map list has output columns positions.
* from 0 ~ N-1
*/
const std::vector<oid_t>
PlanTransformer::BuildColumnListFromDirectMap(planner::ProjectInfo::DirectMapList dmlist){
std::sort(dmlist.begin(), dmlist.end(),
[](const planner::ProjectInfo::DirectMap &a,
const planner::ProjectInfo::DirectMap &b){
return a.first < b.first; }
);
assert(dmlist.front().first == 0);
assert(dmlist.back().first == dmlist.size()-1 );
std::vector<oid_t> rv;
for(auto map : dmlist) {
assert(map.second.first == 0);
rv.emplace_back(map.second.second);
}
return rv;
}
/**
* Convet a Postgres JoinType into a Peloton JoinType
*
* We may want to have a uniform JoinType enum, instead of a transformation
*/
PelotonJoinType PlanTransformer::TransformJoinType(const JoinType type) {
switch (type) {
case JOIN_INNER:
return JOIN_TYPE_INNER;
case JOIN_FULL:
return JOIN_TYPE_OUTER;
case JOIN_LEFT:
return JOIN_TYPE_LEFT;
case JOIN_RIGHT:
return JOIN_TYPE_RIGHT;
default:
return JOIN_TYPE_INVALID;
}
}
} // namespace bridge
} // namespace peloton
<commit_msg>Clean up buggy code.<commit_after>/*-------------------------------------------------------------------------
*
* mapper_utils.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/dml/mapper/mapper_utils.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/bridge/ddl/schema_transformer.h"
#include "backend/planner/projection_node.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Utils
//===--------------------------------------------------------------------===//
const ValueArray PlanTransformer::BuildParams(const ParamListInfo param_list) {
ValueArray params;
if (param_list != nullptr) {
params.Reset(param_list->numParams);
ParamExternData *postgres_param = param_list->params;
for (int i = 0; i < params.GetSize(); ++i, ++postgres_param) {
params[i] = TupleTransformer::GetValue(postgres_param->value,
postgres_param->ptype);
}
}
LOG_INFO("Built %d params: \n%s", params.GetSize(), params.Debug().c_str());
return params;
}
/**
* @brief Extract the common things shared by all Scan types:
* generic predicates and projections.
*
* @param[out] parent Set to a created projection plan node if one is needed,
* or NULL otherwise.
*
* @param[out] predicate Set to the transformed Expression based on qual. Or NULL if so is qual.
*
* @param[out] out_col_list Set to the output column list if ps_ProjInfo contains only
* direct mapping of attributes. \b Empty if no direct map is presented.
*
* @param[in] sstate The ScanState from which generic things are extracted.
*
* @param[in] use_projInfo Parse projInfo or not. Sometimes the projInfo of a Scan may have been
* stolen by its parent.
*
* @return Nothing.
*/
void PlanTransformer::GetGenericInfoFromScanState(
planner::AbstractPlanNode*& parent,
expression::AbstractExpression*& predicate,
std::vector<oid_t>& out_col_list,
const ScanState* sstate,
bool use_projInfo) {
List* qual = sstate->ps.qual;
const ProjectionInfo *pg_proj_info = sstate->ps.ps_ProjInfo;
oid_t out_column_count = static_cast<oid_t>(sstate->ps.ps_ResultTupleSlot->tts_tupleDescriptor->natts);
parent = nullptr;
predicate = nullptr;
out_col_list.clear();
/* Transform predicate */
predicate = BuildPredicateFromQual(qual);
/* Transform project info */
std::unique_ptr<const planner::ProjectInfo> project_info(nullptr);
if(use_projInfo){
project_info.reset(BuildProjectInfo(pg_proj_info, out_column_count));
}
/*
* Based on project_info, see whether we should create a functional projection node
* on top, or simply pushed in an output column list.
*/
if(nullptr == project_info.get()){ // empty predicate, or ignore projInfo, pass thru
LOG_INFO("No projections (all pass through)");
assert(out_col_list.size() == 0);
}
else if(project_info->GetTargetList().size() > 0){ // Have non-trivial projection, add a plan node
LOG_INFO("Non-trivial projections are found. Projection node will be created. \n");
auto project_schema =
SchemaTransformer::GetSchemaFromTupleDesc(sstate->ps.ps_ResultTupleSlot->tts_tupleDescriptor);
parent = new planner::ProjectionNode(project_info.release(), project_schema);
}
else { // Pure direct map
assert(project_info->GetTargetList().size() == 0);
assert(project_info->GetDirectMapList().size() > 0);
LOG_INFO("Pure direct map projection.\n");
std::vector<oid_t> column_ids;
column_ids = BuildColumnListFromDirectMap(project_info->GetDirectMapList());
out_col_list = std::move(column_ids);
assert(out_col_list.size() == out_column_count);
}
}
/**
* @brief Transform a PG ProjectionInfo structure to a Peloton ProjectInfo
*object.
*
* @param pg_proj_info The PG ProjectionInfo struct to be transformed
* @param column_count The valid column count of output. This is used to
* skip junk attributes in PG.
* @return An ProjectInfo object built from the PG ProjectionInfo.
* NULL if no valid project info is found.
*
* @warning Some projections in PG may be ignored.
* For example, the "row" projection
*/
const planner::ProjectInfo *PlanTransformer::BuildProjectInfo(
const ProjectionInfo *pg_pi,
oid_t column_count) {
if (pg_pi == nullptr) {
LOG_INFO("pg proj info is null, no projection");
return nullptr;
}
/*
* (A) Transform non-trivial target list
*/
planner::ProjectInfo::TargetList target_list;
ListCell *tl;
foreach (tl, pg_pi->pi_targetlist) {
GenericExprState *gstate = (GenericExprState *)lfirst(tl);
TargetEntry *tle = (TargetEntry *)gstate->xprstate.expr;
AttrNumber resind = tle->resno - 1;
if (!(resind < column_count
&& AttributeNumberIsValid(tle->resno)
&& AttrNumberIsForUserDefinedAttr(tle->resno)
&& !tle->resjunk)){
LOG_INFO("Invalid / Junk attribute. Skipped. \n");
continue; // skip junk attributes
}
oid_t col_id = static_cast<oid_t>(resind);
auto peloton_expr = ExprTransformer::TransformExpr(gstate->arg);
if(peloton_expr == nullptr){
LOG_INFO("Seems to be a row value expression. Skipped.\n");
continue;
}
LOG_INFO("Target : column id %u, Expression : \n%s\n", col_id, peloton_expr->DebugInfo().c_str());
target_list.emplace_back(col_id, peloton_expr);
}
/*
* (B) Transform direct map list
* Special case:
* a null constant may be specified in SimpleVars by PG,
* in case of that, we add a Target to target_list we created above.
*/
planner::ProjectInfo::DirectMapList direct_map_list;
if (pg_pi->pi_numSimpleVars > 0) {
int numSimpleVars = pg_pi->pi_numSimpleVars;
int *varSlotOffsets = pg_pi->pi_varSlotOffsets;
int *varNumbers = pg_pi->pi_varNumbers;
if (pg_pi->pi_directMap) // Sequential direct map
{
/* especially simple case where vars go to output in order */
for (int i = 0; i < numSimpleVars && i < column_count; i++) {
oid_t tuple_idx =
(varSlotOffsets[i] == offsetof(ExprContext, ecxt_innertuple) ? 1
: 0);
int varNumber = varNumbers[i] - 1;
oid_t in_col_id = static_cast<oid_t>(varNumber);
oid_t out_col_id = static_cast<oid_t>(i);
direct_map_list.emplace_back(out_col_id, std::make_pair(tuple_idx, in_col_id));
LOG_INFO("Input column : %u , Output column : %u \n", in_col_id,
out_col_id);
}
} else // Non-sequential direct map
{
/* we have to pay attention to varOutputCols[] */
int *varOutputCols = pg_pi->pi_varOutputCols;
for (int i = 0; i < numSimpleVars; i++) {
oid_t tuple_idx =
(varSlotOffsets[i] == offsetof(ExprContext, ecxt_innertuple) ? 1
: 0);
int varNumber = varNumbers[i] - 1;
int varOutputCol = varOutputCols[i] - 1;
oid_t in_col_id = static_cast<oid_t>(varNumber);
oid_t out_col_id = static_cast<oid_t>(varOutputCol);
direct_map_list.emplace_back(out_col_id, std::make_pair(tuple_idx, in_col_id));
LOG_INFO("Input column : %u , Output column : %u \n", in_col_id,
out_col_id);
}
}
}
if(target_list.empty() && direct_map_list.empty())
return nullptr;
return new planner::ProjectInfo(std::move(target_list),
std::move(direct_map_list));
}
/**
* @brief Transform a PG qual list to an expression tree.
*
* @return Expression tree, null if empty.
*/
expression::AbstractExpression*
PlanTransformer::BuildPredicateFromQual(List* qual){
expression::AbstractExpression* predicate =
ExprTransformer::TransformExpr(
reinterpret_cast<ExprState*>(qual) );
LOG_INFO("Predicate:\n%s \n", (nullptr==predicate)? "NULL" : predicate->DebugInfo().c_str());
return predicate;
}
/**
* @brief Transform a DirectMapList to a one-dimensional column list.
* This is intended to incorporate a pure-direct-map projection into a scan.
* The caller should make sure the direct map list has output columns positions.
* from 0 ~ N-1
*/
const std::vector<oid_t>
PlanTransformer::BuildColumnListFromDirectMap(planner::ProjectInfo::DirectMapList dmlist){
std::sort(dmlist.begin(), dmlist.end(),
[](const planner::ProjectInfo::DirectMap &a,
const planner::ProjectInfo::DirectMap &b){
return a.first < b.first; }
);
assert(dmlist.front().first == 0);
assert(dmlist.back().first == dmlist.size()-1 );
std::vector<oid_t> rv;
for(auto map : dmlist) {
assert(map.second.first == 0);
rv.emplace_back(map.second.second);
}
return rv;
}
/**
* Convet a Postgres JoinType into a Peloton JoinType
*
* We may want to have a uniform JoinType enum, instead of a transformation
*/
PelotonJoinType PlanTransformer::TransformJoinType(const JoinType type) {
switch (type) {
case JOIN_INNER:
return JOIN_TYPE_INNER;
case JOIN_FULL:
return JOIN_TYPE_OUTER;
case JOIN_LEFT:
return JOIN_TYPE_LEFT;
case JOIN_RIGHT:
return JOIN_TYPE_RIGHT;
default:
return JOIN_TYPE_INVALID;
}
}
} // namespace bridge
} // namespace peloton
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <JSON.h>
#include <test.h>
#include <Context.h>
Context context;
const char *positive_tests[] =
{
"{}",
" { } ",
"[]",
"{\"one\":1}",
"{\n\"one\"\n:\n1\n}\n",
"{\"name\":123, \"array\":[1,2,3.4], \"object\":{\"m1\":\"v1\", \"m2\":\"v2\"}}",
"{\"name\":\"value\",\"array\":[\"one\",\"two\"],\"object\":{\"name2\":123,\"literal\":false}}",
"{\n"
"\"ticket\": { \"type\":\"add\", \"client\":\"taskwarrior 2.x\"},\n"
"\"auth\": { \"user\":\"paul\", \"org\":\"gbf\", \"key\":\".........\",\n"
" \"locale\":\"en-US\" },\n"
"\n"
"\"add\": { \"description\":\"Wash the dog\",\n"
" \"project\":\"home\",\n"
" \"due\":\"20101101T000000Z\" }\n"
"}",
"{"
"\"ticket\":{"
"\"type\":\"synch\","
"\"client\":\"taskd-test-suite 1.0\""
"},"
"\"synch\":{"
"\"user\":{"
"\"data\":["
"{"
"\"uuid\":\"11111111-1111-1111-1111-111111111111\","
"\"status\":\"pending\","
"\"description\":\"This is a test\","
"\"entry\":\"20110111T124000Z\""
"}"
"],"
"\"synch\":\"key\""
"}"
"},"
"\"auth\":{"
"\"org\":\"gbf\","
"\"user\":\"Paul Beckingham\","
"\"key\":\"K\","
"\"locale\":\"en-US\""
"}"
"}"
};
#define NUM_POSITIVE_TESTS (sizeof (positive_tests) / sizeof (positive_tests[0]))
const char *negative_tests[] =
{
"",
"{",
"}",
"[",
"]",
"foo",
"[?]"
};
#define NUM_NEGATIVE_TESTS (sizeof (negative_tests) / sizeof (negative_tests[0]))
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
UnitTest t (NUM_POSITIVE_TESTS + NUM_NEGATIVE_TESTS + 22);
// Ensure environment has no influence.
unsetenv ("TASKDATA");
unsetenv ("TASKRC");
// Positive tests.
for (int i = 0; i < NUM_POSITIVE_TESTS; ++i)
{
try
{
json::value* root = json::parse (positive_tests[i]);
t.ok (root, std::string ("positive: ") + positive_tests[i]);
if (root)
{
t.diag (root->dump ());
delete root;
}
}
catch (const std::string& e) { t.diag (e); }
catch (...) { t.diag ("Unknown error"); }
}
// Negative tests.
for (int i = 0; i < NUM_NEGATIVE_TESTS; ++i)
{
try
{
json::value* root = json::parse (negative_tests[i]);
t.is ((const char*) root, (const char*) NULL,
std::string ("negative: ") + negative_tests[i]);
}
catch (const std::string& e) { t.pass (e); }
catch (...) { t.fail ("Unknown error"); }
}
// Other tests.
try
{
// Regular unit tests.
t.is (json::encode ("1\b2"), "1\\b2", "json::encode slashslashb -> slashslashslashslashb");
t.is (json::decode ("1\\b2"), "1\b2", "json::decode slashslashslashslashb -> slashslashb");
t.is (json::encode ("1\n2"), "1\\n2", "json::encode slashslashn -> slashslashslashslashn");
t.is (json::decode ("1\\n2"), "1\n2", "json::decode slashslashslashslashn -> slashslashn");
t.is (json::encode ("1\r2"), "1\\r2", "json::encode slashslashr -> slashslashslashslashr");
t.is (json::decode ("1\\r2"), "1\r2", "json::decode slashslashslashslashr -> slashslashr");
t.is (json::encode ("1\t2"), "1\\t2", "json::encode slashslasht -> slashslashslashslasht");
t.is (json::decode ("1\\t2"), "1\t2", "json::decode slashslashslashslasht -> slashslasht");
t.is (json::encode ("1\\2"), "1\\\\2", "json::encode slashslash -> slashslashslashslash");
t.is (json::decode ("1\\\\2"), "1\\2", "json::decode slashslashslashslash -> slashslash");
t.is (json::encode ("1\x2"), "1\x2", "json::encode slashslashx -> slashslashx(NOP)");
t.is (json::decode ("1\x2"), "1\x2", "json::decode slashslashx -> slashslashx(NOP)");
t.is (json::encode ("1€2"), "1€2", "json::encode € -> €");
t.is (json::decode ("1\\u20ac2"), "1€2", "json::decode slashslashu20ac -> €");
std::string encoded = json::encode ("one\\");
t.is (encoded, "one\\\\", "json::encode oneslashslashslashslash -> oneslashslashslashslashslashslashslashslash");
t.is ((int)encoded.length (), 5, "json::encode oneslashslashslashslash -> length 5");
t.is (encoded[0], 'o', "json::encode oneslashslashslashslash[0] -> o");
t.is (encoded[1], 'n', "json::encode oneslashslashslashslash[1] -> n");
t.is (encoded[2], 'e', "json::encode oneslashslashslashslash[2] -> e");
t.is (encoded[3], '\\', "json::encode oneslashslashslashslash[3] -> slashslash");
t.is (encoded[4], '\\', "json::encode oneslashslashslashslash[4] -> slashslash");
t.is (json::decode (encoded), "one\\", "json::decode oneslashslashslashslashslashslashslashslash -> oneslashslashslashslash");
}
catch (const std::string& e) {t.diag (e);}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Unit Tests<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <JSON.h>
#include <test.h>
#include <Context.h>
Context context;
const char *positive_tests[] =
{
"{}",
" { } ",
"[]",
"{\"one\":1}",
"{\n\"one\"\n:\n1\n}\n",
" { \"one\" : 1 } ",
"{\"name\":123, \"array\":[1,2,3.4], \"object\":{\"m1\":\"v1\", \"m2\":\"v2\"}}",
"{\"name\":\"value\",\"array\":[\"one\",\"two\"],\"object\":{\"name2\":123,\"literal\":false}}",
"{\n"
"\"ticket\": { \"type\":\"add\", \"client\":\"taskwarrior 2.x\"},\n"
"\"auth\": { \"user\":\"paul\", \"org\":\"gbf\", \"key\":\".........\",\n"
" \"locale\":\"en-US\" },\n"
"\n"
"\"add\": { \"description\":\"Wash the dog\",\n"
" \"project\":\"home\",\n"
" \"due\":\"20101101T000000Z\" }\n"
"}",
"{"
"\"ticket\":{"
"\"type\":\"synch\","
"\"client\":\"taskd-test-suite 1.0\""
"},"
"\"synch\":{"
"\"user\":{"
"\"data\":["
"{"
"\"uuid\":\"11111111-1111-1111-1111-111111111111\","
"\"status\":\"pending\","
"\"description\":\"This is a test\","
"\"entry\":\"20110111T124000Z\""
"}"
"],"
"\"synch\":\"key\""
"}"
"},"
"\"auth\":{"
"\"org\":\"gbf\","
"\"user\":\"Paul Beckingham\","
"\"key\":\"K\","
"\"locale\":\"en-US\""
"}"
"}"
};
#define NUM_POSITIVE_TESTS (sizeof (positive_tests) / sizeof (positive_tests[0]))
const char *negative_tests[] =
{
"",
"{",
"}",
"[",
"]",
"foo",
"[?]"
};
#define NUM_NEGATIVE_TESTS (sizeof (negative_tests) / sizeof (negative_tests[0]))
////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
UnitTest t (NUM_POSITIVE_TESTS + NUM_NEGATIVE_TESTS + 22);
// Ensure environment has no influence.
unsetenv ("TASKDATA");
unsetenv ("TASKRC");
// Positive tests.
for (int i = 0; i < NUM_POSITIVE_TESTS; ++i)
{
try
{
json::value* root = json::parse (positive_tests[i]);
t.ok (root, std::string ("positive: ") + positive_tests[i]);
if (root)
{
t.diag (root->dump ());
delete root;
}
}
catch (const std::string& e) { t.diag (e); }
catch (...) { t.diag ("Unknown error"); }
}
// Negative tests.
for (int i = 0; i < NUM_NEGATIVE_TESTS; ++i)
{
try
{
json::value* root = json::parse (negative_tests[i]);
t.is ((const char*) root, (const char*) NULL,
std::string ("negative: ") + negative_tests[i]);
}
catch (const std::string& e) { t.pass (e); }
catch (...) { t.fail ("Unknown error"); }
}
// Other tests.
try
{
// Regular unit tests.
t.is (json::encode ("1\b2"), "1\\b2", "json::encode slashslashb -> slashslashslashslashb");
t.is (json::decode ("1\\b2"), "1\b2", "json::decode slashslashslashslashb -> slashslashb");
t.is (json::encode ("1\n2"), "1\\n2", "json::encode slashslashn -> slashslashslashslashn");
t.is (json::decode ("1\\n2"), "1\n2", "json::decode slashslashslashslashn -> slashslashn");
t.is (json::encode ("1\r2"), "1\\r2", "json::encode slashslashr -> slashslashslashslashr");
t.is (json::decode ("1\\r2"), "1\r2", "json::decode slashslashslashslashr -> slashslashr");
t.is (json::encode ("1\t2"), "1\\t2", "json::encode slashslasht -> slashslashslashslasht");
t.is (json::decode ("1\\t2"), "1\t2", "json::decode slashslashslashslasht -> slashslasht");
t.is (json::encode ("1\\2"), "1\\\\2", "json::encode slashslash -> slashslashslashslash");
t.is (json::decode ("1\\\\2"), "1\\2", "json::decode slashslashslashslash -> slashslash");
t.is (json::encode ("1\x2"), "1\x2", "json::encode slashslashx -> slashslashx(NOP)");
t.is (json::decode ("1\x2"), "1\x2", "json::decode slashslashx -> slashslashx(NOP)");
t.is (json::encode ("1€2"), "1€2", "json::encode € -> €");
t.is (json::decode ("1\\u20ac2"), "1€2", "json::decode slashslashu20ac -> €");
std::string encoded = json::encode ("one\\");
t.is (encoded, "one\\\\", "json::encode oneslashslashslashslash -> oneslashslashslashslashslashslashslashslash");
t.is ((int)encoded.length (), 5, "json::encode oneslashslashslashslash -> length 5");
t.is (encoded[0], 'o', "json::encode oneslashslashslashslash[0] -> o");
t.is (encoded[1], 'n', "json::encode oneslashslashslashslash[1] -> n");
t.is (encoded[2], 'e', "json::encode oneslashslashslashslash[2] -> e");
t.is (encoded[3], '\\', "json::encode oneslashslashslashslash[3] -> slashslash");
t.is (encoded[4], '\\', "json::encode oneslashslashslashslash[4] -> slashslash");
t.is (json::decode (encoded), "one\\", "json::decode oneslashslashslashslashslashslashslashslash -> oneslashslashslashslash");
}
catch (const std::string& e) {t.diag (e);}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#pragma once
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
/** @file qi/log.hpp
* @brief Convenient log macro
*/
#ifndef _QI_LOG_HPP_
#define _QI_LOG_HPP_
# include <string>
# include <iostream>
# include <sstream>
# include <cstdarg>
# include <cstdio>
#include <boost/format.hpp>
#include <boost/function/function_fwd.hpp>
#include <qi/os.hpp>
# define qiLogCategory(Cat) \
static ::qi::log::CategoryType _QI_LOG_CATEGORY_GET() = \
::qi::log::addCategory(Cat)
#if defined(NO_QI_DEBUG) || defined(NDEBUG)
# define qiLogDebug(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogDebugF(Msg, ...)
#else
# define qiLogDebug(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Debug, Debug , __VA_ARGS__)
# define qiLogDebugF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Debug, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_VERBOSE)
# define qiLogVerbose(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogVerboseF(Msg, ...)
#else
# define qiLogVerbose(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Verbose, Verbose, __VA_ARGS__)
# define qiLogVerboseF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Verbose, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_INFO)
# define qiLogInfo(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogInfoF(Msg, ...)
#else
# define qiLogInfo(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Info, Info, __VA_ARGS__)
# define qiLogInfoF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Info, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_WARNING)
# define qiLogWarning(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogWarningF(Msg, ...)
#else
# define qiLogWarning(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Warning, Warning, __VA_ARGS__)
# define qiLogWarningF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Warning, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_ERROR)
# define qiLogError(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogErrorF(Msg, ...)
#else
# define qiLogError(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Error, Error, __VA_ARGS__)
# define qiLogErrorF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Error, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_FATAL)
# define qiLogFatal(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogFatalF(Msg, ...)
#else
# define qiLogFatal(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Fatal, Fatal, __VA_ARGS__)
# define qiLogFatalF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Fatal, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
namespace qi {
enum LogLevel {
LogLevel_Silent = 0,
LogLevel_Fatal,
LogLevel_Error,
LogLevel_Warning,
LogLevel_Info,
LogLevel_Verbose,
LogLevel_Debug
};
enum LogColor {
LogColor_Never,
LogColor_Auto,
LogColor_Always,
};
enum LogContextAttr {
LogContextAttr_None = 0,
LogContextAttr_Verbosity = 1 << 0,
LogContextAttr_ShortVerbosity = 1 << 1,
LogContextAttr_Date = 1 << 2,
LogContextAttr_Tid = 1 << 3,
LogContextAttr_Category = 1 << 4,
LogContextAttr_File = 1 << 5,
LogContextAttr_Function = 1 << 6,
LogContextAttr_Return = 1 << 7
};
typedef int LogContext;
namespace log {
//deprecated 1.22
QI_API_DEPRECATED static const qi::LogLevel silent = LogLevel_Silent;
QI_API_DEPRECATED static const qi::LogLevel fatal = LogLevel_Fatal;
QI_API_DEPRECATED static const qi::LogLevel error = LogLevel_Error;
QI_API_DEPRECATED static const qi::LogLevel warning = LogLevel_Warning;
QI_API_DEPRECATED static const qi::LogLevel info = LogLevel_Info;
QI_API_DEPRECATED static const qi::LogLevel verbose = LogLevel_Verbose;
QI_API_DEPRECATED static const qi::LogLevel debug = LogLevel_Debug;
//deprecated 1.22
QI_API_DEPRECATED typedef qi::LogLevel LogLevel;
}
}
namespace qi {
namespace log {
namespace detail {
struct Category;
}
typedef unsigned int SubscriberId;
typedef detail::Category* CategoryType;
//Deprecated 1.22
QI_API_DEPRECATED typedef unsigned int Subscriber;
typedef boost::function7<void,
const qi::LogLevel,
const qi::os::timeval,
const char*,
const char*,
const char*,
const char*,
int> logFuncHandler;
QI_API void init(qi::LogLevel verb = qi::LogLevel_Info,
qi::LogContext context = qi::LogContextAttr_ShortVerbosity | qi::LogContextAttr_Tid | qi::LogContextAttr_Category,
bool synchronous = true);
QI_API void destroy();
QI_API void log(const qi::LogLevel verb,
const char* category,
const char* msg,
const char* file = "",
const char* fct = "",
const int line = 0);
QI_API void log(const qi::LogLevel verb,
CategoryType category,
const std::string& msg,
const char* file = "",
const char* fct = "",
const int line = 0);
QI_API const char* logLevelToString(const qi::LogLevel verb, bool verbose = true);
QI_API qi::LogLevel stringToLogLevel(const char* verb);
QI_API qi::LogLevel verbosity(SubscriberId sub = 0);
/// @return the list of existing categories
QI_API std::vector<std::string> categories();
/** Parse and execute a set of verbosity rules
* Colon separated of rules.
* Each rule can be:
* - (+)?CAT : enable category CAT
* - -CAT : disable category CAT
* - CAT=level : set category CAT to level
*
* Each category can include a '*' for globbing.
*/
QI_API void setVerbosity(const std::string& rules, SubscriberId sub = 0);
QI_API void setVerbosity(const qi::LogLevel lv, SubscriberId sub = 0);
//deprecated 1.22
QI_API_DEPRECATED inline void setVerbosity(SubscriberId sub, const qi::log::LogLevel lv) { setVerbosity((qi::LogLevel)lv, sub); }
/// Add/get a category
QI_API CategoryType addCategory(const std::string& name);
/// Set \param cat to current verbosity level. Globbing is supported.
QI_API void enableCategory(const std::string& cat, SubscriberId sub = 0);
/// Set \param cat to silent log level. Globbing is supported.
QI_API void disableCategory(const std::string& cat, SubscriberId sub = 0);
/// Set per-subscriber \param cat to level \param level. Globbing is supported.
QI_API void setCategory(const std::string& cat, qi::LogLevel level, SubscriberId sub = 0);
// Deprecated 1.22
QI_API_DEPRECATED inline void setCategory(SubscriberId sub, const std::string& cat, qi::log::LogLevel level) { setCategory(cat, (qi::LogLevel)level, sub); }
/// \return true if given combination of category and level is enabled.
QI_API bool isVisible(CategoryType category, qi::LogLevel level);
/// \return true if given combination of category and level is enabled.
QI_API bool isVisible(const std::string& category, qi::LogLevel level);
QI_API void setContext(int ctx);
QI_API int context();
QI_API void setColor(LogColor color);
QI_API LogColor color();
QI_API void setSynchronousLog(bool sync);
QI_API SubscriberId addLogHandler(const std::string& name,
qi::log::logFuncHandler fct);
QI_API void removeLogHandler(const std::string& name);
QI_API void flush();
}
}
#include <qi/details/log.hxx>
#endif // _QI_LOG_HPP_
<commit_msg>log: remove deprecated from function using deprecated struct.<commit_after>#pragma once
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
/** @file qi/log.hpp
* @brief Convenient log macro
*/
#ifndef _QI_LOG_HPP_
#define _QI_LOG_HPP_
# include <string>
# include <iostream>
# include <sstream>
# include <cstdarg>
# include <cstdio>
#include <boost/format.hpp>
#include <boost/function/function_fwd.hpp>
#include <qi/os.hpp>
# define qiLogCategory(Cat) \
static ::qi::log::CategoryType _QI_LOG_CATEGORY_GET() = \
::qi::log::addCategory(Cat)
#if defined(NO_QI_DEBUG) || defined(NDEBUG)
# define qiLogDebug(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogDebugF(Msg, ...)
#else
# define qiLogDebug(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Debug, Debug , __VA_ARGS__)
# define qiLogDebugF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Debug, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_VERBOSE)
# define qiLogVerbose(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogVerboseF(Msg, ...)
#else
# define qiLogVerbose(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Verbose, Verbose, __VA_ARGS__)
# define qiLogVerboseF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Verbose, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_INFO)
# define qiLogInfo(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogInfoF(Msg, ...)
#else
# define qiLogInfo(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Info, Info, __VA_ARGS__)
# define qiLogInfoF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Info, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_WARNING)
# define qiLogWarning(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogWarningF(Msg, ...)
#else
# define qiLogWarning(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Warning, Warning, __VA_ARGS__)
# define qiLogWarningF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Warning, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_ERROR)
# define qiLogError(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogErrorF(Msg, ...)
#else
# define qiLogError(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Error, Error, __VA_ARGS__)
# define qiLogErrorF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Error, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
#if defined(NO_QI_FATAL)
# define qiLogFatal(...) ::qi::log::detail::qiFalse() && false < qi::log::detail::NullStream().self()
# define qiLogFatalF(Msg, ...)
#else
# define qiLogFatal(...) _QI_LOG_MESSAGE_STREAM(LogLevel_Fatal, Fatal, __VA_ARGS__)
# define qiLogFatalF(Msg, ...) _QI_LOG_MESSAGE(LogLevel_Fatal, _QI_LOG_FORMAT(Msg, __VA_ARGS__))
#endif
namespace qi {
enum LogLevel {
LogLevel_Silent = 0,
LogLevel_Fatal,
LogLevel_Error,
LogLevel_Warning,
LogLevel_Info,
LogLevel_Verbose,
LogLevel_Debug
};
enum LogColor {
LogColor_Never,
LogColor_Auto,
LogColor_Always,
};
enum LogContextAttr {
LogContextAttr_None = 0,
LogContextAttr_Verbosity = 1 << 0,
LogContextAttr_ShortVerbosity = 1 << 1,
LogContextAttr_Date = 1 << 2,
LogContextAttr_Tid = 1 << 3,
LogContextAttr_Category = 1 << 4,
LogContextAttr_File = 1 << 5,
LogContextAttr_Function = 1 << 6,
LogContextAttr_Return = 1 << 7
};
typedef int LogContext;
namespace log {
//deprecated 1.22
QI_API_DEPRECATED static const qi::LogLevel silent = LogLevel_Silent;
QI_API_DEPRECATED static const qi::LogLevel fatal = LogLevel_Fatal;
QI_API_DEPRECATED static const qi::LogLevel error = LogLevel_Error;
QI_API_DEPRECATED static const qi::LogLevel warning = LogLevel_Warning;
QI_API_DEPRECATED static const qi::LogLevel info = LogLevel_Info;
QI_API_DEPRECATED static const qi::LogLevel verbose = LogLevel_Verbose;
QI_API_DEPRECATED static const qi::LogLevel debug = LogLevel_Debug;
//deprecated 1.22
QI_API_DEPRECATED typedef qi::LogLevel LogLevel;
}
}
namespace qi {
namespace log {
namespace detail {
struct Category;
}
typedef unsigned int SubscriberId;
typedef detail::Category* CategoryType;
//Deprecated 1.22
QI_API_DEPRECATED typedef unsigned int Subscriber;
typedef boost::function7<void,
const qi::LogLevel,
const qi::os::timeval,
const char*,
const char*,
const char*,
const char*,
int> logFuncHandler;
QI_API void init(qi::LogLevel verb = qi::LogLevel_Info,
qi::LogContext context = qi::LogContextAttr_ShortVerbosity | qi::LogContextAttr_Tid | qi::LogContextAttr_Category,
bool synchronous = true);
QI_API void destroy();
QI_API void log(const qi::LogLevel verb,
const char* category,
const char* msg,
const char* file = "",
const char* fct = "",
const int line = 0);
QI_API void log(const qi::LogLevel verb,
CategoryType category,
const std::string& msg,
const char* file = "",
const char* fct = "",
const int line = 0);
QI_API const char* logLevelToString(const qi::LogLevel verb, bool verbose = true);
QI_API qi::LogLevel stringToLogLevel(const char* verb);
QI_API qi::LogLevel verbosity(SubscriberId sub = 0);
/// @return the list of existing categories
QI_API std::vector<std::string> categories();
/** Parse and execute a set of verbosity rules
* Colon separated of rules.
* Each rule can be:
* - (+)?CAT : enable category CAT
* - -CAT : disable category CAT
* - CAT=level : set category CAT to level
*
* Each category can include a '*' for globbing.
*/
QI_API void setVerbosity(const std::string& rules, SubscriberId sub = 0);
QI_API void setVerbosity(const qi::LogLevel lv, SubscriberId sub = 0);
//deprecated 1.22
/*QI_API_DEPRECATED*/ inline void setVerbosity(SubscriberId sub, const qi::log::LogLevel lv) { setVerbosity((qi::LogLevel)lv, sub); }
/// Add/get a category
QI_API CategoryType addCategory(const std::string& name);
/// Set \param cat to current verbosity level. Globbing is supported.
QI_API void enableCategory(const std::string& cat, SubscriberId sub = 0);
/// Set \param cat to silent log level. Globbing is supported.
QI_API void disableCategory(const std::string& cat, SubscriberId sub = 0);
/// Set per-subscriber \param cat to level \param level. Globbing is supported.
QI_API void setCategory(const std::string& cat, qi::LogLevel level, SubscriberId sub = 0);
// Deprecated 1.22
/*QI_API_DEPRECATED*/ inline void setCategory(SubscriberId sub, const std::string& cat, qi::log::LogLevel level) { setCategory(cat, (qi::LogLevel)level, sub); }
/// \return true if given combination of category and level is enabled.
QI_API bool isVisible(CategoryType category, qi::LogLevel level);
/// \return true if given combination of category and level is enabled.
QI_API bool isVisible(const std::string& category, qi::LogLevel level);
QI_API void setContext(int ctx);
QI_API int context();
QI_API void setColor(LogColor color);
QI_API LogColor color();
QI_API void setSynchronousLog(bool sync);
QI_API SubscriberId addLogHandler(const std::string& name,
qi::log::logFuncHandler fct);
QI_API void removeLogHandler(const std::string& name);
QI_API void flush();
}
}
#include <qi/details/log.hxx>
#endif // _QI_LOG_HPP_
<|endoftext|>
|
<commit_before>#include "proxyparser.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Winhttp.h>
#include <Ws2tcpip.h>
#include <Winsock2.h>
#include <iostream>
#include <sstream>
ProxyParser::ProxyParser(string url)
{
}
ProxyParser::~ProxyParser(void)
{
}
void ProxyParser::getProxySettingForUrl(string url, ProxySetting & proxy)
{
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig;
WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
WINHTTP_PROXY_INFO autoProxyInfo;
BOOL autoProxy = FALSE;
memset(&ieProxyConfig,0,sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG));
memset(&autoProxyOptions,0,sizeof(WINHTTP_AUTOPROXY_OPTIONS));
memset(&autoProxyInfo,0,sizeof(WINHTTP_PROXY_INFO));
if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) ){
if( ieProxyConfig.fAutoDetect ){
// WPAD
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
autoProxyOptions.fAutoLogonIfChallenged = TRUE;
autoProxy = TRUE;
cout << "proxy configured with WPAD" << endl;
}
else if( ieProxyConfig.lpszAutoConfigUrl != NULL ){
// Normal PAC file
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;
autoProxy = TRUE;
wcout << L"download PAC file from: " << ieProxyConfig.lpszAutoConfigUrl << endl;
}
else if ( ieProxyConfig.lpszProxy != NULL ){
autoProxy = FALSE;
wcout << L"hardcoded proxy address: " << ieProxyConfig.lpszProxy << endl;
if(ieProxyConfig.lpszProxyBypass != NULL)
wcout << L"proxy bypass list: " << ieProxyConfig.lpszProxyBypass << endl;
else
wcout << L"proxy bypass list: NONE" << endl;
}
}
if(autoProxy)
{
cout << "testing proxy autoconfiguration for this URL: " << url << endl;
std::wstring wUrl(url.begin() , url.end());
HINTERNET session = WinHttpOpen(0, // no agent string
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
WINHTTP_FLAG_ASYNC);
autoProxy = WinHttpGetProxyForUrl( session, wUrl.c_str(), &autoProxyOptions, &autoProxyInfo );
if (!autoProxy)
cout << "WinHttpGetProxyForUrl failed with error: " << GetLastError() << endl;
else
{
if (NULL != autoProxyInfo.lpszProxy)
{
wcout << L"got proxy list: " << autoProxyInfo.lpszProxy << endl;
//proxy.domain = autoProxyInfo.lpszProxy;
GlobalFree( autoProxyInfo.lpszProxy );
if(NULL != autoProxyInfo.lpszProxyBypass)
{
wcout << L"and proxy bypass list: " << autoProxyInfo.lpszProxyBypass << endl;
GlobalFree( autoProxyInfo.lpszProxyBypass );
}
}
}
}
else
{
getStaticProxySettingForUrl(url, ieProxyConfig.lpszProxy, ieProxyConfig.lpszProxyBypass, proxy);
}
}
void ProxyParser::getProxySettingForProtocolFromProxyList(string protocol, string proxyList, ProxySetting & proxy)
{
size_t token, precedent_token = 0;
token = proxyList.find(";");
do
{
string proxyItem = proxyList.substr(precedent_token, token-precedent_token);
//proxy item strings: ([<scheme>=][<scheme>"://"]<server>[":"<port>])
size_t proxyToken = proxyItem.find("=");
string proto = proxyItem.substr(0, proxyToken);
if(protocol == proto)
{
cout << "found matching proxy item for protocol: " << protocol << endl;
proxy.protocol = protocol;
proxyItem = proxyItem.erase(0, proxyToken+1);
cout << "remaining proxy item: " <<proxyItem << endl;
proxyToken = proxyItem.find("/");
if(proxyToken != string::npos)
proxyItem = proxyItem.erase(0, proxyToken+2);
proxyToken = proxyItem.find(":");
proxy.domain = proxyItem.substr(0, proxyToken);
stringstream s(proxyItem.substr(proxyToken+1, string::npos));
s >> proxy.port;
break;
}
precedent_token = token+1;
token = proxyList.find(";", precedent_token);//can be separated by whitespace too?
}while(token != string::npos);
}
void ProxyParser::getStaticProxySettingForUrl(string url, wstring wproxylist, wstring proxybypass, ProxySetting & proxy)
{
URL_COMPONENTS components = {0};
components.dwStructSize = sizeof(URL_COMPONENTS);
wchar_t scheme[20] = {0};
wchar_t domain[MAX_PATH] = {0};
components.lpszScheme = scheme;
components.dwSchemeLength = 20;
components.lpszHostName = domain;
components.dwHostNameLength = MAX_PATH;
wstring wurl(url.begin(), url.end());
WinHttpCrackUrl( wurl.c_str(), (DWORD)wurl.length(), 0, &components);
wstring whost(domain);
string host(whost.begin(), whost.end());
//FIXME
if(!testHostForBypassList(host, proxybypass))
{
string proxylist(wproxylist.begin(), wproxylist.end());
wstring wscheme(scheme);
string protocol(wscheme.begin(), wscheme.end());
getProxySettingForProtocolFromProxyList(protocol, proxylist, proxy);
//proxy.domain = proxylist;
}
}
bool ProxyParser::testHostForBypassList(string host, wstring wproxybypass)
{
string proxybypass(wproxybypass.begin(), wproxybypass.end());
size_t token, precedent_token = 0;
token = proxybypass.find(";");
while(token != string::npos)
{
string bypass = proxybypass.substr(precedent_token, token-precedent_token);
if(testHostForBypass(host, bypass))
return true;
precedent_token = token+1;
token = proxybypass.find(";", precedent_token);
}
string bypass = proxybypass.substr(precedent_token, token);
return testHostForBypass(host, bypass);
}
bool ProxyParser::testHostForBypass(string host, string bypass)
{
cout << "testing domain \"" << host << "\" for bypass: " << bypass << " ";
if(isDomain(host))
{
bool result = testDomainForBypass(host, bypass);
if(result)
{
cout << " => MATCH" << endl;
return true;
}
else
{
cout << " => NO MATCH" << endl;
return false;
}
}
return false;
}
bool ProxyParser::testDomainForBypass(string domain, string bypass)
{
if(isDomain(bypass))
{
if(domain == bypass)
return true;
if(bypass.at(0) == '*')
{
string suffix = bypass.substr(1, string::npos);
size_t found = domain.rfind(suffix);
return(found+suffix.length() == domain.length());//the suffix is the end of the domain
}
if(bypass == "<local>" && domain.find('.') == string::npos)
return true;
}
else
{
vector<string> ips = getIPForHost(domain);
vector<string>::iterator ipIt;
for(ipIt = ips.begin(); ipIt != ips.end(); ipIt++)
{
string ip = *ipIt;
if(testIpForBypass(ip, bypass))
return true;
}
}
return false;
}
bool ProxyParser::testIpForBypass(string ip, string bypass)
{
if(!isDomain(bypass))
{
if(ip == bypass)
return true;
//special case for IP like 172.16*
if(bypass.at(bypass.size()-1) == '*')
{
if(ip.substr(0, bypass.size()-1) == bypass.substr(0, bypass.size()-1))
return true;
}
size_t token, iptoken, precedent_token = 0, precedent_iptoken = 0;
token = bypass.find(".");
iptoken = ip.find(".");
while(token != string::npos)
{
string bypassnum = bypass.substr(precedent_token, token-precedent_token);
string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken);
if(!(bypassnum == ipnum || bypassnum == "*"))
return false;
precedent_token = token+1;
precedent_iptoken = iptoken+1;
token = bypass.find(".", precedent_token);
iptoken = ip.find(".", precedent_iptoken);
}
string bypassnum = bypass.substr(precedent_token, token-precedent_token);
string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken);
if(bypassnum == ipnum || bypassnum == "*")
return true;
}
return false;
}
vector<string> ProxyParser::getIPForHost(string host)
{
vector<string> ips;
WSADATA wsaData;
int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(res != 0)
return ips;
struct addrinfo * result;
res = getaddrinfo(host.c_str(), NULL, NULL, &result);
if(res == 0)
{
struct addrinfo * current = result;
do{
struct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) current->ai_addr;
string ip = inet_ntoa(sockaddr_ipv4->sin_addr);
ips.push_back(ip);
current = current->ai_next;
}while(current != NULL);
freeaddrinfo(result);
}
WSACleanup();
return ips;
}
bool ProxyParser::isDomain(string host)
{
return (isalpha(host.at(0))
|| (host.at(0) == '*' && host.at(1) == '.' && isalpha(host.at(2)))
|| host == "<local>");
}
<commit_msg>Implement proxy list parsing for items like proxy.com:3128 Use proxy list parsing for autoconfig too<commit_after>#include "proxyparser.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Winhttp.h>
#include <Ws2tcpip.h>
#include <Winsock2.h>
#include <iostream>
#include <sstream>
ProxyParser::ProxyParser(string url)
{
}
ProxyParser::~ProxyParser(void)
{
}
void ProxyParser::getProxySettingForUrl(string url, ProxySetting & proxy)
{
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig;
WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
WINHTTP_PROXY_INFO autoProxyInfo;
BOOL autoProxy = FALSE;
memset(&ieProxyConfig,0,sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG));
memset(&autoProxyOptions,0,sizeof(WINHTTP_AUTOPROXY_OPTIONS));
memset(&autoProxyInfo,0,sizeof(WINHTTP_PROXY_INFO));
if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) ){
if( ieProxyConfig.fAutoDetect ){
// WPAD
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
autoProxyOptions.fAutoLogonIfChallenged = TRUE;
autoProxy = TRUE;
cout << "proxy configured with WPAD" << endl;
}
else if( ieProxyConfig.lpszAutoConfigUrl != NULL ){
// Normal PAC file
autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl;
autoProxy = TRUE;
wcout << L"download PAC file from: " << ieProxyConfig.lpszAutoConfigUrl << endl;
}
else if ( ieProxyConfig.lpszProxy != NULL ){
autoProxy = FALSE;
wcout << L"hardcoded proxy address: " << ieProxyConfig.lpszProxy << endl;
if(ieProxyConfig.lpszProxyBypass != NULL)
wcout << L"proxy bypass list: " << ieProxyConfig.lpszProxyBypass << endl;
else
wcout << L"proxy bypass list: NONE" << endl;
}
}
if(autoProxy)
{
cout << "testing proxy autoconfiguration for this URL: " << url << endl;
std::wstring wUrl(url.begin() , url.end());
HINTERNET session = WinHttpOpen(0, // no agent string
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
WINHTTP_FLAG_ASYNC);
autoProxy = WinHttpGetProxyForUrl( session, wUrl.c_str(), &autoProxyOptions, &autoProxyInfo );
if (!autoProxy)
cout << "WinHttpGetProxyForUrl failed with error: " << GetLastError() << endl;
else
{
if (NULL != autoProxyInfo.lpszProxy)
{
wcout << L"got proxy list: " << autoProxyInfo.lpszProxy << endl;
wstring wproxyList(autoProxyInfo.lpszProxy);
string proxyList(wproxyList.begin(), wproxyList.end());
getProxySettingForProtocolFromProxyList("http", proxyList, proxy);
GlobalFree( autoProxyInfo.lpszProxy );
if(NULL != autoProxyInfo.lpszProxyBypass)
{
wcout << L"and proxy bypass list: " << autoProxyInfo.lpszProxyBypass << endl;
GlobalFree( autoProxyInfo.lpszProxyBypass );
}
}
}
}
else
{
getStaticProxySettingForUrl(url, ieProxyConfig.lpszProxy, ieProxyConfig.lpszProxyBypass, proxy);
}
}
void ProxyParser::getProxySettingForProtocolFromProxyList(string protocol, string proxyList, ProxySetting & proxy)
{
size_t token, precedent_token = 0;
token = proxyList.find(";");
do
{
string proxyItem = proxyList.substr(precedent_token, token-precedent_token);
//proxy item strings: ([<scheme>=][<scheme>"://"]<server>[":"<port>])
size_t proxyToken = proxyItem.find("=");
if(proxyToken == string::npos)
{
cout << "found matching proxy item for protocol: " << protocol << endl;
proxy.protocol = protocol;
proxyItem = proxyItem.erase(0, proxyToken+1);
cout << "remaining proxy item: " <<proxyItem << endl;
proxyToken = proxyItem.find("/");
if(proxyToken != string::npos)
proxyItem = proxyItem.erase(0, proxyToken+2);
proxyToken = proxyItem.find(":");
proxy.domain = proxyItem.substr(0, proxyToken);
stringstream s(proxyItem.substr(proxyToken+1, string::npos));
s >> proxy.port;
break;
}
else
{
string proto = proxyItem.substr(0, proxyToken);
if(protocol == proto)
{
cout << "found matching proxy item for protocol: " << protocol << endl;
proxy.protocol = protocol;
proxyItem = proxyItem.erase(0, proxyToken+1);
cout << "remaining proxy item: " <<proxyItem << endl;
proxyToken = proxyItem.find("/");
if(proxyToken != string::npos)
proxyItem = proxyItem.erase(0, proxyToken+2);
proxyToken = proxyItem.find(":");
proxy.domain = proxyItem.substr(0, proxyToken);
stringstream s(proxyItem.substr(proxyToken+1, string::npos));
s >> proxy.port;
break;
}
}
precedent_token = token+1;
token = proxyList.find(";", precedent_token);//can be separated by whitespace too?
}while(token != string::npos);
}
void ProxyParser::getStaticProxySettingForUrl(string url, wstring wproxylist, wstring proxybypass, ProxySetting & proxy)
{
URL_COMPONENTS components = {0};
components.dwStructSize = sizeof(URL_COMPONENTS);
wchar_t scheme[20] = {0};
wchar_t domain[MAX_PATH] = {0};
components.lpszScheme = scheme;
components.dwSchemeLength = 20;
components.lpszHostName = domain;
components.dwHostNameLength = MAX_PATH;
wstring wurl(url.begin(), url.end());
WinHttpCrackUrl( wurl.c_str(), (DWORD)wurl.length(), 0, &components);
wstring whost(domain);
string host(whost.begin(), whost.end());
//FIXME
if(!testHostForBypassList(host, proxybypass))
{
string proxylist(wproxylist.begin(), wproxylist.end());
wstring wscheme(scheme);
string protocol(wscheme.begin(), wscheme.end());
getProxySettingForProtocolFromProxyList(protocol, proxylist, proxy);
//proxy.domain = proxylist;
}
}
bool ProxyParser::testHostForBypassList(string host, wstring wproxybypass)
{
string proxybypass(wproxybypass.begin(), wproxybypass.end());
size_t token, precedent_token = 0;
token = proxybypass.find(";");
while(token != string::npos)
{
string bypass = proxybypass.substr(precedent_token, token-precedent_token);
if(testHostForBypass(host, bypass))
return true;
precedent_token = token+1;
token = proxybypass.find(";", precedent_token);
}
string bypass = proxybypass.substr(precedent_token, token);
return testHostForBypass(host, bypass);
}
bool ProxyParser::testHostForBypass(string host, string bypass)
{
cout << "testing domain \"" << host << "\" for bypass: " << bypass << " ";
if(isDomain(host))
{
bool result = testDomainForBypass(host, bypass);
if(result)
{
cout << " => MATCH" << endl;
return true;
}
else
{
cout << " => NO MATCH" << endl;
return false;
}
}
return false;
}
bool ProxyParser::testDomainForBypass(string domain, string bypass)
{
if(isDomain(bypass))
{
if(domain == bypass)
return true;
if(bypass.at(0) == '*')
{
string suffix = bypass.substr(1, string::npos);
size_t found = domain.rfind(suffix);
return(found+suffix.length() == domain.length());//the suffix is the end of the domain
}
if(bypass == "<local>" && domain.find('.') == string::npos)
return true;
}
else
{
vector<string> ips = getIPForHost(domain);
vector<string>::iterator ipIt;
for(ipIt = ips.begin(); ipIt != ips.end(); ipIt++)
{
string ip = *ipIt;
if(testIpForBypass(ip, bypass))
return true;
}
}
return false;
}
bool ProxyParser::testIpForBypass(string ip, string bypass)
{
if(!isDomain(bypass))
{
if(ip == bypass)
return true;
//special case for IP like 172.16*
if(bypass.at(bypass.size()-1) == '*')
{
if(ip.substr(0, bypass.size()-1) == bypass.substr(0, bypass.size()-1))
return true;
}
size_t token, iptoken, precedent_token = 0, precedent_iptoken = 0;
token = bypass.find(".");
iptoken = ip.find(".");
while(token != string::npos)
{
string bypassnum = bypass.substr(precedent_token, token-precedent_token);
string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken);
if(!(bypassnum == ipnum || bypassnum == "*"))
return false;
precedent_token = token+1;
precedent_iptoken = iptoken+1;
token = bypass.find(".", precedent_token);
iptoken = ip.find(".", precedent_iptoken);
}
string bypassnum = bypass.substr(precedent_token, token-precedent_token);
string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken);
if(bypassnum == ipnum || bypassnum == "*")
return true;
}
return false;
}
vector<string> ProxyParser::getIPForHost(string host)
{
vector<string> ips;
WSADATA wsaData;
int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
if(res != 0)
return ips;
struct addrinfo * result;
res = getaddrinfo(host.c_str(), NULL, NULL, &result);
if(res == 0)
{
struct addrinfo * current = result;
do{
struct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) current->ai_addr;
string ip = inet_ntoa(sockaddr_ipv4->sin_addr);
ips.push_back(ip);
current = current->ai_next;
}while(current != NULL);
freeaddrinfo(result);
}
WSACleanup();
return ips;
}
bool ProxyParser::isDomain(string host)
{
return (isalpha(host.at(0))
|| (host.at(0) == '*' && host.at(1) == '.' && isalpha(host.at(2)))
|| host == "<local>");
}
<|endoftext|>
|
<commit_before>#include "condor_common.h"
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "condor_classad.h"
#include "proc_obj.h"
#include "dgram_io_handle.h"
#include "condor_attributes.h"
#include "condor_expressions.h"
#include "condor_collector.h"
int send_classad_to_machine(DGRAM_IO_HANDLE *UdpHandle, int cmd, const ClassAd* ad);
extern "C" {
int
send_classad_to_negotiator(DGRAM_IO_HANDLE *handle, CONTEXT *cp)
{
int ret;
ClassAd *ad;
ad = new ClassAd(cp);
ret = send_classad_to_machine(handle, UPDATE_STARTD_AD, ad);
delete ad;
return ret;
}
}
<commit_msg>Added code to fix the types of the startd's classad<commit_after>#include "condor_common.h"
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "condor_classad.h"
#include "proc_obj.h"
#include "dgram_io_handle.h"
#include "condor_attributes.h"
#include "condor_expressions.h"
#include "condor_collector.h"
int send_classad_to_machine(DGRAM_IO_HANDLE *UdpHandle, int cmd, const ClassAd* ad);
extern "C" {
int
send_classad_to_negotiator(DGRAM_IO_HANDLE *handle, CONTEXT *cp)
{
int ret;
ClassAd *ad;
ad = new ClassAd(cp);
ad->SetMyTypeName ("Machine");
ad->SetTargetTypeName ("Job");
ret = send_classad_to_machine(handle, UPDATE_STARTD_AD, ad);
delete ad;
return ret;
}
}
<|endoftext|>
|
<commit_before>
#include <vector>
#include <iostream>
// euclidean distance
double distance(std::pair<double, double>, std::pair<double, double>);
double distance(std::pair<int, int>, std::pair<int, int>);
int shortest_path_dist(vector< vector<int> >);
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit! << std::endl;
return 1;
}
std::fstream f(argv[1]);
// well what now?
// something about an algorithm...
// i think i need to build the distance array
}
<commit_msg>Copied psuedocode from paper.<commit_after>#include <vector>
#include <iostream>
// euclidean distance
double distance(std::pair<double, double>, std::pair<double, double>);
double distance(std::pair<int, int>, std::pair<int, int>);
int shortest_path_dist(vector< vector<int> >);
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit! << std::endl;
return 1;
}
std::fstream f(argv[1]);
// well what now?
// something about an algorithm...
// oh yes! i think i need to build the distance array
// call shortest path with it
// then print out the answer
std::cout << answer << std::endl;
}
int shortest_path_dist(std::vector< std::vector<int> > dist)
{
// for each iteration
// for each ant : IN PARALLEL
// start a new thread,initialize the ant
// share distance and pheromone graph for the thread
// while a tour is not finished
// choose the next city (eq 1,2)
// lock pheremone path
// local pheromone update (eq 3)
// unlock pheromone path
// end while // end of ant's travel
// lock the path
// global pheromone update (eq 4)
// unlock the path
// terminate the thread, release resources
// end for
// end for // end of iteration
}
<|endoftext|>
|
<commit_before>#include "dwi/tractography/tracking/tractography.h"
#define MAX_TRIALS 1000
namespace MR
{
namespace DWI
{
namespace Tractography
{
namespace Tracking
{
using namespace App;
const OptionGroup TrackOption = OptionGroup ("Streamlines tractography options")
+ Option ("step",
"set the step size of the algorithm in mm (default is 0.1 x voxelsize; for iFOD2: 0.5 x voxelsize).")
+ Argument ("size").type_float (0.0, 0.0, INFINITY)
+ Option ("angle",
"set the maximum angle between successive steps (default is 90deg x stepsize / voxelsize).")
+ Argument ("theta").type_float (0.0, 90.0, 90.0)
+ Option ("number",
"set the desired number of tracks. The program will continue to "
"generate tracks until this number of tracks have been selected "
"and written to the output file.")
+ Argument ("tracks").type_integer (0, 0, std::numeric_limits<int>::max())
+ Option ("maxnum",
"set the maximum number of tracks to generate. The program will "
"not generate more tracks than this number, even if the desired "
"number of tracks hasn't yet been reached (default is 100 x number).")
+ Argument ("tracks").type_integer (1, 1, INT_MAX)
+ Option ("maxlength",
"set the maximum length of any track in mm (default is 100 x voxelsize).")
+ Argument ("value").type_float (0.0, 0.0, INFINITY)
+ Option ("minlength",
"set the minimum length of any track in mm (default is 5 x voxelsize).")
+ Argument ("value").type_float (0.0, 0.0, INFINITY)
+ Option ("cutoff",
"set the FA or FOD amplitude cutoff for terminating tracks "
"(default is 0.1).")
+ Argument ("value").type_float (0.0, 0.1, INFINITY)
+ Option ("initcutoff",
"set the minimum FA or FOD amplitude for initiating tracks (default "
"is the same as the normal cutoff).")
+ Argument ("value").type_float (0.0, 0.1, INFINITY)
+ Option ("trials",
"set the maximum number of sampling trials at each point (only "
"used for probabilistic tracking).")
+ Argument ("number").type_integer (1, MAX_TRIALS, std::numeric_limits<int>::max())
+ Option ("unidirectional",
"track from the seed point in one direction only (default is to "
"track in both directions).")
+ Option ("initdirection",
"specify an initial direction for the tracking (this should be "
"supplied as a vector of 3 comma-separated values.")
+ Argument ("dir").type_sequence_float()
+ Option ("noprecomputed",
"do NOT pre-compute legendre polynomial values. Warning: "
"this will slow down the algorithm by a factor of approximately 4.")
+ Option ("power",
"raise the FOD to the power specified (default is 1/nsamples).")
+ Argument ("value").type_float (1e-6, 1.0, 1e6)
+ Option ("samples",
"set the number of FOD samples to take per step for the 2nd order "
"(iFOD2) method (Default: 4).")
+ Argument ("number").type_integer (2, 4, 100)
+ Option ("rk4", "use 4th-order Runge-Kutta integration "
"(slower, but eliminates curvature overshoot in 1st-order deterministic methods)")
+ Option ("stop", "stop propagating a streamline once it has traversed all include regions")
+ Option ("downsample", "downsample the generated streamlines to reduce output file size")
+ Argument ("factor").type_integer (1, 1, 100);
void load_streamline_properties (Properties& properties)
{
using namespace MR::App;
Options opt = get_options ("include");
for (size_t i = 0; i < opt.size(); ++i)
properties.include.add (ROI (opt[i][0]));
opt = get_options ("exclude");
for (size_t i = 0; i < opt.size(); ++i)
properties.exclude.add (ROI (opt[i][0]));
opt = get_options ("mask");
for (size_t i = 0; i < opt.size(); ++i)
properties.mask.add (ROI (opt[i][0]));
opt = get_options ("grad");
if (opt.size()) properties["DW_scheme"] = std::string (opt[0][0]);
opt = get_options ("step");
if (opt.size()) properties["step_size"] = std::string (opt[0][0]);
opt = get_options ("angle");
if (opt.size()) properties["max_angle"] = std::string (opt[0][0]);
opt = get_options ("number");
if (opt.size()) properties["max_num_tracks"] = std::string (opt[0][0]);
opt = get_options ("maxnum");
if (opt.size()) properties["max_num_attempts"] = std::string (opt[0][0]);
opt = get_options ("maxlength");
if (opt.size()) properties["max_dist"] = std::string (opt[0][0]);
opt = get_options ("minlength");
if (opt.size()) properties["min_dist"] = std::string (opt[0][0]);
opt = get_options ("cutoff");
if (opt.size()) properties["threshold"] = std::string (opt[0][0]);
opt = get_options ("initcutoff");
if (opt.size()) properties["init_threshold"] = std::string (opt[0][0]);
opt = get_options ("trials");
if (opt.size()) properties["max_trials"] = std::string (opt[0][0]);
opt = get_options ("unidirectional");
if (opt.size()) properties["unidirectional"] = "1";
opt = get_options ("initdirection");
if (opt.size()) properties["init_direction"] = std::string (opt[0][0]);
opt = get_options ("noprecomputed");
if (opt.size()) properties["sh_precomputed"] = "0";
opt = get_options ("power");
if (opt.size()) properties["fod_power"] = std::string (opt[0][0]);
opt = get_options ("samples");
if (opt.size()) properties["samples_per_step"] = std::string (opt[0][0]);
opt = get_options ("rk4");
if (opt.size()) properties["rk4"] = "1";
opt = get_options ("stop");
if (opt.size()) {
if (properties.include.size())
properties["stop_on_all_include"] = "1";
else
WARN ("-stop option ignored - no -include regions specified");
}
opt = get_options ("downsample");
if (opt.size()) properties["downsample_factor"] = std::string (opt[0][0]);
}
}
}
}
}
<commit_msg>tckgen: Add default downsampling values to help page<commit_after>#include "dwi/tractography/tracking/tractography.h"
#define MAX_TRIALS 1000
namespace MR
{
namespace DWI
{
namespace Tractography
{
namespace Tracking
{
using namespace App;
const OptionGroup TrackOption = OptionGroup ("Streamlines tractography options")
+ Option ("step",
"set the step size of the algorithm in mm (default is 0.1 x voxelsize; for iFOD2: 0.5 x voxelsize).")
+ Argument ("size").type_float (0.0, 0.0, INFINITY)
+ Option ("angle",
"set the maximum angle between successive steps (default is 90deg x stepsize / voxelsize).")
+ Argument ("theta").type_float (0.0, 90.0, 90.0)
+ Option ("number",
"set the desired number of tracks. The program will continue to "
"generate tracks until this number of tracks have been selected "
"and written to the output file.")
+ Argument ("tracks").type_integer (0, 0, std::numeric_limits<int>::max())
+ Option ("maxnum",
"set the maximum number of tracks to generate. The program will "
"not generate more tracks than this number, even if the desired "
"number of tracks hasn't yet been reached (default is 100 x number).")
+ Argument ("tracks").type_integer (1, 1, INT_MAX)
+ Option ("maxlength",
"set the maximum length of any track in mm (default is 100 x voxelsize).")
+ Argument ("value").type_float (0.0, 0.0, INFINITY)
+ Option ("minlength",
"set the minimum length of any track in mm (default is 5 x voxelsize).")
+ Argument ("value").type_float (0.0, 0.0, INFINITY)
+ Option ("cutoff",
"set the FA or FOD amplitude cutoff for terminating tracks "
"(default is 0.1).")
+ Argument ("value").type_float (0.0, 0.1, INFINITY)
+ Option ("initcutoff",
"set the minimum FA or FOD amplitude for initiating tracks (default "
"is the same as the normal cutoff).")
+ Argument ("value").type_float (0.0, 0.1, INFINITY)
+ Option ("trials",
"set the maximum number of sampling trials at each point (only "
"used for probabilistic tracking).")
+ Argument ("number").type_integer (1, MAX_TRIALS, std::numeric_limits<int>::max())
+ Option ("unidirectional",
"track from the seed point in one direction only (default is to "
"track in both directions).")
+ Option ("initdirection",
"specify an initial direction for the tracking (this should be "
"supplied as a vector of 3 comma-separated values.")
+ Argument ("dir").type_sequence_float()
+ Option ("noprecomputed",
"do NOT pre-compute legendre polynomial values. Warning: "
"this will slow down the algorithm by a factor of approximately 4.")
+ Option ("power",
"raise the FOD to the power specified (default is 1/nsamples).")
+ Argument ("value").type_float (1e-6, 1.0, 1e6)
+ Option ("samples",
"set the number of FOD samples to take per step for the 2nd order "
"(iFOD2) method (Default: 4).")
+ Argument ("number").type_integer (2, 4, 100)
+ Option ("rk4", "use 4th-order Runge-Kutta integration "
"(slower, but eliminates curvature overshoot in 1st-order deterministic methods)")
+ Option ("stop", "stop propagating a streamline once it has traversed all include regions")
+ Option ("downsample", "downsample the generated streamlines to reduce output file size "
"(default is (samples-1) for iFOD2, 1 for all other algorithms)")
+ Argument ("factor").type_integer (1, 1, 100);
void load_streamline_properties (Properties& properties)
{
using namespace MR::App;
Options opt = get_options ("include");
for (size_t i = 0; i < opt.size(); ++i)
properties.include.add (ROI (opt[i][0]));
opt = get_options ("exclude");
for (size_t i = 0; i < opt.size(); ++i)
properties.exclude.add (ROI (opt[i][0]));
opt = get_options ("mask");
for (size_t i = 0; i < opt.size(); ++i)
properties.mask.add (ROI (opt[i][0]));
opt = get_options ("grad");
if (opt.size()) properties["DW_scheme"] = std::string (opt[0][0]);
opt = get_options ("step");
if (opt.size()) properties["step_size"] = std::string (opt[0][0]);
opt = get_options ("angle");
if (opt.size()) properties["max_angle"] = std::string (opt[0][0]);
opt = get_options ("number");
if (opt.size()) properties["max_num_tracks"] = std::string (opt[0][0]);
opt = get_options ("maxnum");
if (opt.size()) properties["max_num_attempts"] = std::string (opt[0][0]);
opt = get_options ("maxlength");
if (opt.size()) properties["max_dist"] = std::string (opt[0][0]);
opt = get_options ("minlength");
if (opt.size()) properties["min_dist"] = std::string (opt[0][0]);
opt = get_options ("cutoff");
if (opt.size()) properties["threshold"] = std::string (opt[0][0]);
opt = get_options ("initcutoff");
if (opt.size()) properties["init_threshold"] = std::string (opt[0][0]);
opt = get_options ("trials");
if (opt.size()) properties["max_trials"] = std::string (opt[0][0]);
opt = get_options ("unidirectional");
if (opt.size()) properties["unidirectional"] = "1";
opt = get_options ("initdirection");
if (opt.size()) properties["init_direction"] = std::string (opt[0][0]);
opt = get_options ("noprecomputed");
if (opt.size()) properties["sh_precomputed"] = "0";
opt = get_options ("power");
if (opt.size()) properties["fod_power"] = std::string (opt[0][0]);
opt = get_options ("samples");
if (opt.size()) properties["samples_per_step"] = std::string (opt[0][0]);
opt = get_options ("rk4");
if (opt.size()) properties["rk4"] = "1";
opt = get_options ("stop");
if (opt.size()) {
if (properties.include.size())
properties["stop_on_all_include"] = "1";
else
WARN ("-stop option ignored - no -include regions specified");
}
opt = get_options ("downsample");
if (opt.size()) properties["downsample_factor"] = std::string (opt[0][0]);
}
}
}
}
}
<|endoftext|>
|
<commit_before>#include "DateTime.h"
#include "ArraySort.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
using namespace NP_DATETIME;
using namespace NP_ARRAYSORT;
// .h
int main();
void showSortFunction();
// .cpp
void showSortFunction() {
cout << "For our first act, we're going to sort some times in our very own DateTime class!" << endl;
cout << "How many DateTimes would you like to sort? ";
short items;
cin >> items;
if (items <= 1) {
cout << "Well it wouldn't be much of a show if I didn't sort at least 2 things, right? We'll sort 2 things for now." << endl;
items = 2;
}
else {
cout << items << " DateTimes it is!" << endl;
}
cout << "Now if you could type these times in yourself..." << endl;
Comparable ** timesToSort = nullptr;
timesToSort = new Comparable * [items];
for (short index = 0; index < items; index++)
timesToSort[index] = nullptr;
for (short tIndex = 0; tIndex < items; tIndex++) {
cout << "DateTime " << tIndex + 1 << " [dd/mm/yyyy hh:mm:ss]: ";
DateTime thisTime;
Comparable * thisTimeComparable = &thisTime;
safeRead(cin, &thisTime, "");
cout << "You entered: " << thisTime << endl;
timesToSort[tIndex] = new DateTime(dynamic_cast<DateTime&>(*thisTimeComparable));
}
cout << "Awesome! Now that we have " << items << " different DateTimes, let me present them in the order you entered..." << endl << endl;
printArray(cout, timesToSort, items);
cout << endl << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl << endl;
strangeSort(timesToSort, 0, items - 1);
printArray(cout, timesToSort, items);
cout << endl << endl;
cout << "Now, using the same array, we will place Dates!" << endl;
for (short tIndex = 0; tIndex < items; tIndex++) {
cout << "Date " << tIndex + 1 << " [dd/mm/yyyy]: ";
Date thisDate;
Comparable * thisTimeComparable = &thisDate;
safeRead(cin, &thisDate, "");
cout << "You entered: " << thisDate << endl;
timesToSort[tIndex] = new Date(dynamic_cast<Date&>(*thisTimeComparable));
}
cout << "Awesome! Now that we have " << items << " different DAtes, let me present them in the order you entered..." << endl << endl;
printArray(cout, timesToSort, items);
cout << endl << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl << endl;
strangeSort(timesToSort, 0, items - 1);
printArray(cout, timesToSort, items);
cout << endl << endl;
cout << " ... For our last trick, we will dynamically clean your memory! " << endl << endl;
// clean up memory
delete[] timesToSort;
timesToSort = nullptr;
}
int main()
{
string name;
cout << "Hello! Welcome the magic sorting show! Please enter your name: ";
cin >> name;
if (name.length() <= 1) {
cout << "no name, huh? I'll just call you Bill!" << endl;
name = "Bill";
}
else {
cout << "Hello, " << name << "!" << endl;
}
cout << "We have quite a treat for you today! We're going to sort things for you in C++!" << endl;
showSortFunction();
cout << "Thank you Seattle, you have been an amazing audience!" << endl;
cout << "I have been your host, Norton Pengra and I will see you later!" << endl;
char tmp;
cin >> tmp;
}<commit_msg>add full memory deallocation code<commit_after>#include "DateTime.h"
#include "ArraySort.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
using namespace NP_DATETIME;
using namespace NP_ARRAYSORT;
// .h
int main();
void showSortFunction();
// .cpp
void showSortFunction() {
cout << "For our first act, we're going to sort some times in our very own DateTime class!" << endl;
cout << "How many DateTimes would you like to sort? ";
short items;
cin >> items;
if (items <= 1) {
cout << "Well it wouldn't be much of a show if I didn't sort at least 2 things, right? We'll sort 2 things for now." << endl;
items = 2;
}
else {
cout << items << " DateTimes it is!" << endl;
}
cout << "Now if you could type these times in yourself..." << endl;
Comparable ** timesToSort = nullptr;
try {
timesToSort = new Comparable *[items];
}
catch (bad_alloc e) {
cout << "Oh no! something went wrong :(" << endl;
cout << "Couldn't allocate the memory" << endl;
return;
}
for (short index = 0; index < items; index++)
timesToSort[index] = nullptr;
for (short tIndex = 0; tIndex < items; tIndex++) {
cout << "DateTime " << tIndex + 1 << " [dd/mm/yyyy hh:mm:ss]: ";
DateTime thisTime;
Comparable * thisTimeComparable = &thisTime;
safeRead(cin, &thisTime, "");
cout << "You entered: " << thisTime << endl;
timesToSort[tIndex] = new DateTime(dynamic_cast<DateTime&>(*thisTimeComparable));
}
cout << "Awesome! Now that we have " << items << " different DateTimes, let me present them in the order you entered..." << endl << endl;
printArray(cout, timesToSort, items);
cout << endl << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl << endl;
strangeSort(timesToSort, 0, items - 1);
printArray(cout, timesToSort, items);
cout << endl << endl;
cout << "Now, using the same array, we will place Dates!" << endl;
for (short tIndex = 0; tIndex < items; tIndex++) {
cout << "Date " << tIndex + 1 << " [dd/mm/yyyy]: ";
Date thisDate;
Comparable * thisTimeComparable = &thisDate;
safeRead(cin, &thisDate, "");
cout << "You entered: " << thisDate << endl;
timesToSort[tIndex] = new Date(dynamic_cast<Date&>(*thisTimeComparable));
}
cout << "Awesome! Now that we have " << items << " different DAtes, let me present them in the order you entered..." << endl << endl;
printArray(cout, timesToSort, items);
cout << endl << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl << endl;
strangeSort(timesToSort, 0, items - 1);
printArray(cout, timesToSort, items);
cout << endl << endl;
cout << " ... For our last trick, we will dynamically clean your memory! " << endl << endl;
// clean up memory
for (int index = 0; index < items; index++) {
delete timesToSort[index];
}
delete[] timesToSort;
timesToSort = nullptr;
}
int main()
{
string name;
cout << "Hello! Welcome the magic sorting show! Please enter your name: ";
cin >> name;
if (name.length() <= 1) {
cout << "no name, huh? I'll just call you Bill!" << endl;
name = "Bill";
}
else {
cout << "Hello, " << name << "!" << endl;
}
cout << "We have quite a treat for you today! We're going to sort things for you in C++!" << endl;
showSortFunction();
cout << "Thank you Seattle, you have been an amazing audience!" << endl;
cout << "I have been your host, Norton Pengra and I will see you later!" << endl;
char tmp;
cin >> tmp;
}<|endoftext|>
|
<commit_before><commit_msg>optimizations<commit_after><|endoftext|>
|
<commit_before>#include "editor_native/property_frame/script_ui.h"
#include <cstdio>
#include <Windows.h>
#include "core/crc32.h"
#include "editor/editor_client.h"
#include "editor/server_message_types.h"
#include "editor_native/main_frame.h"
#include "editor_native/property_frame/property_frame.h"
#include "gui/controls/button.h"
#include "gui/controls/text_box.h"
#include "gui/gui.h"
ScriptUI::ScriptUI(PropertyFrame& property_frame, Lux::UI::Block* parent, Lux::EditorClient& client)
: Block(parent->getGui(), parent, NULL)
, m_property_frame(property_frame)
{
m_client = &client;
setArea(0, 0, 0, 0, 1, 0, 0, 40);
Lux::UI::Block* label = LUX_NEW(Lux::UI::Block)(getGui(), this, "_text_centered");
label->setBlockText("Script");
label->setArea(0, 0, 0, 0, 1, 0, 0, 20);
label = LUX_NEW(Lux::UI::Block)(getGui(), this, "_text");
label->setBlockText("Source");
label->setArea(0, 0, 0, 20, 0, 50, 0, 40);
m_source_box = LUX_NEW(Lux::UI::TextBox)("empty", getGui(), this);
m_source_box->setArea(0, 50, 0, 20, 1, -21, 0, 40);
m_source_box->onEvent("text_accepted").bind<ScriptUI, &ScriptUI::sourceChanged>(this);
Lux::UI::Button* browse_button = LUX_NEW(Lux::UI::Button)("...", getGui(), this);
browse_button->setArea(1, -20, 0, 20, 1, -1, 0, 40);
browse_button->onEvent("click").bind<ScriptUI, &ScriptUI::browseSource>(this);
Lux::UI::Button* edit_button = LUX_NEW(Lux::UI::Button)("Edit script", getGui(), this);
edit_button->setArea(0.5f, -40, 0, 42, 0.5f, 40, 0, 62);
edit_button->onEvent("click").bind<ScriptUI, &ScriptUI::editScript>(this);
}
void ScriptUI::sourceChanged(Lux::UI::Block& block, void*)
{
const Lux::string& s = m_source_box->getChild(0)->getBlockText();
m_client->setComponentProperty("script", "source", s.c_str(), s.length()+1);
}
void ScriptUI::editScript(Lux::UI::Block& block, void*)
{
ShellExecute(NULL, "open", m_source_box->getText().c_str(), NULL, NULL, SW_SHOW);
}
void ScriptUI::browseSource(Lux::UI::Block& block, void*)
{
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "models\0*.scene.xml\0";
char buf[MAX_PATH];
buf[0] = 0;
ofn.lpstrFile = buf;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
if(GetOpenFileName(&ofn) != FALSE)
{
Lux::string& s = m_property_frame.getMainFrame()->getStartupDirectory();
if(strncmp(s.c_str(), buf, s.length()) == 0)
{
if(buf[s.length()] == '\\')
{
strcpy_s(buf, buf + s.length()+1);
}
else
{
strcpy_s(buf, buf + s.length());
}
}
m_source_box->getChild(0)->setBlockText(buf);
m_source_box->getChild(0)->emitEvent("text_accepted");
}
const Lux::string& s = m_source_box->getText();
m_client->setComponentProperty("script", "source", s.c_str(), s.length()+1);
}
void ScriptUI::onEntityProperties(Lux::PropertyListEvent& evt)
{
if(evt.type_hash == crc32("script"))
{
for(int i = 0; i < evt.properties.size(); ++i)
{
if(evt.properties[i].name_hash == crc32("source"))
{
if(evt.properties[i].data_size > 0)
{
m_source_box->setText((char*)evt.properties[i].data);
}
}
}
}
}
<commit_msg>fixed script ui in property grid - closes #92<commit_after>#include "editor_native/property_frame/script_ui.h"
#include <cstdio>
#include <Windows.h>
#include "core/crc32.h"
#include "editor/editor_client.h"
#include "editor/server_message_types.h"
#include "editor_native/main_frame.h"
#include "editor_native/property_frame/property_frame.h"
#include "gui/controls/button.h"
#include "gui/controls/text_box.h"
#include "gui/gui.h"
ScriptUI::ScriptUI(PropertyFrame& property_frame, Lux::UI::Block* parent, Lux::EditorClient& client)
: Block(parent->getGui(), parent, NULL)
, m_property_frame(property_frame)
{
m_client = &client;
setArea(0, 0, 0, 0, 1, 0, 0, 60);
Lux::UI::Block* label = LUX_NEW(Lux::UI::Block)(getGui(), this, "_text_centered");
label->setBlockText("Script");
label->setArea(0, 0, 0, 0, 1, 0, 0, 20);
label = LUX_NEW(Lux::UI::Block)(getGui(), this, "_text");
label->setBlockText("Source");
label->setArea(0, 0, 0, 20, 0, 50, 0, 40);
m_source_box = LUX_NEW(Lux::UI::TextBox)("empty", getGui(), this);
m_source_box->setArea(0, 50, 0, 20, 1, -21, 0, 40);
m_source_box->onEvent("text_accepted").bind<ScriptUI, &ScriptUI::sourceChanged>(this);
Lux::UI::Button* browse_button = LUX_NEW(Lux::UI::Button)("...", getGui(), this);
browse_button->setArea(1, -20, 0, 20, 1, -1, 0, 40);
browse_button->onEvent("click").bind<ScriptUI, &ScriptUI::browseSource>(this);
Lux::UI::Button* edit_button = LUX_NEW(Lux::UI::Button)("Edit script", getGui(), this);
edit_button->setArea(0.5f, -40, 0, 42, 0.5f, 40, 0, 62);
edit_button->onEvent("click").bind<ScriptUI, &ScriptUI::editScript>(this);
}
void ScriptUI::sourceChanged(Lux::UI::Block& block, void*)
{
const Lux::string& s = m_source_box->getChild(0)->getBlockText();
m_client->setComponentProperty("script", "source", s.c_str(), s.length()+1);
}
void ScriptUI::editScript(Lux::UI::Block& block, void*)
{
ShellExecute(NULL, "open", m_source_box->getText().c_str(), NULL, NULL, SW_SHOW);
}
void ScriptUI::browseSource(Lux::UI::Block& block, void*)
{
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "models\0*.scene.xml\0";
char buf[MAX_PATH];
buf[0] = 0;
ofn.lpstrFile = buf;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
if(GetOpenFileName(&ofn) != FALSE)
{
Lux::string& s = m_property_frame.getMainFrame()->getStartupDirectory();
if(strncmp(s.c_str(), buf, s.length()) == 0)
{
if(buf[s.length()] == '\\')
{
strcpy_s(buf, buf + s.length()+1);
}
else
{
strcpy_s(buf, buf + s.length());
}
}
m_source_box->getChild(0)->setBlockText(buf);
m_source_box->getChild(0)->emitEvent("text_accepted");
}
const Lux::string& s = m_source_box->getText();
m_client->setComponentProperty("script", "source", s.c_str(), s.length()+1);
}
void ScriptUI::onEntityProperties(Lux::PropertyListEvent& evt)
{
if(evt.type_hash == crc32("script"))
{
for(int i = 0; i < evt.properties.size(); ++i)
{
if(evt.properties[i].name_hash == crc32("source"))
{
if(evt.properties[i].data_size > 0)
{
m_source_box->setText((char*)evt.properties[i].data);
}
}
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
http://github.com/chukong/EarthWarrior3D
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 "GameOverLayer.h"
#include "MainMenuScene.h"
#include "HelloWorldScene.h"
#include "GameLayer.h"
#include "GameControllers.h"
#include "AirCraft.h"
#include "Bullets.h"
GameOverLayer* GameOverLayer::create(int score)
{
GameOverLayer *pRet = new GameOverLayer();
pRet->m_score=score;
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
return pRet;
}
bool GameOverLayer::init()
{
if (!LayerColor::initWithColor(Color4B(255, 255, 255, 50))) {
return false;
}
auto visibleSize=Director::getInstance()->getVisibleSize();
auto score_bk=Sprite::createWithSpriteFrameName("gameover_score_bk.png");
score_bk->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2));
addChild(score_bk,1);
score_bk->setScale(0.2f);
score_bk->runAction(Sequence::create(ScaleTo::create(0.2f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::ShowScore,this)),
NULL));
auto backtomenu_normal=Sprite::createWithSpriteFrameName("gameover_backtomenu.png");
auto backtomenu_pressed=Sprite::createWithSpriteFrameName("gameover_backtomenu.png");
backtomenu_Item = MenuItemSprite::create(backtomenu_normal,
backtomenu_pressed,
CC_CALLBACK_1(GameOverLayer::menu_backtomenu_Callback,this));
// auto playagain_normal=Sprite::createWithSpriteFrameName("gameover_playagain.png");
// auto playagain_pressed=Sprite::createWithSpriteFrameName("gameover_playagain.png");
// playagain_Item = MenuItemSprite::create(playagain_normal,
// playagain_pressed,
// CC_CALLBACK_1(GameOverLayer::menu_playagain_Callback,this));
auto menu = Menu::create(backtomenu_Item,NULL);
menu->alignItemsHorizontallyWithPadding(20);
menu->setPosition(visibleSize.width/2, 100);
this->addChild(menu, 2);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(GameOverLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(GameOverLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(GameOverLayer::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void GameOverLayer::ShowScore()
{
auto visibleSize=Director::getInstance()->getVisibleSize();
auto score_text=Sprite::createWithSpriteFrameName("gameover_score.png");
score_text->setPosition(Vec2(-200, visibleSize.height/2+30));
score_text->runAction(MoveTo::create(0.5f, Vec2(visibleSize.width/2,visibleSize.height/2+30)));
addChild(score_text,2);
char pScore[10];
sprintf(pScore, "%d",m_score);
auto score_label=LabelBMFont::create(pScore, "gameover_score_num.fnt");
score_label->setAnchorPoint(Vec2(0.5f,0.5f));
score_label->setPosition(Vec2(1000,visibleSize.height/2-40));
score_label->runAction(Sequence::create(
MoveTo::create(0.5f, Vec2(visibleSize.width/2,visibleSize.height/2-30)),
ScaleTo::create(0.1f, 1.3f),
ScaleTo::create(0.1f, 0.98f),
ScaleTo::create(0.1f, 1.2f),NULL));
addChild(score_label,2);
}
void GameOverLayer::menu_backtomenu_Callback(Ref* sender)
{
backtomenu_Item->runAction(Sequence::create(ScaleTo::create(0.1f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::menu_backtomenu, this)),NULL));
}
void GameOverLayer::menu_backtomenu()
{
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
Director::getInstance()->replaceScene(MainMenuScene::createScene());
for(int i=EnemyController::enemies.size()-1;i>=0;i--)
{
EnemyController::enemies.at(i)->removeFromParentAndCleanup(true);
}
EnemyController::enemies.clear();
for(int i=EnemyController::showCaseEnemies.size()-1;i>=0;i--)
{
EnemyController::showCaseEnemies.at(i)->removeFromParentAndCleanup(true);
//EnemyController::showCaseEnemies.erase(i);
}
EnemyController::showCaseEnemies.clear();
for(int i=BulletController::bullets.size()-1;i>=0;i--)
{
BulletController::bullets.erase(i);
}
BulletController::bullets.clear();
}
void GameOverLayer::menu_playagain_Callback(Ref* sender)
{
playagain_Item->runAction(Sequence::create(ScaleTo::create(0.1f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::menu_playagain, this)),NULL));
}
void GameOverLayer::menu_playagain()
{
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
GameLayer::isDie = false;
for(int i=EnemyController::enemies.size()-1;i>=0;i--)
{
EnemyController::erase(i);
}
for(int i=EnemyController::showCaseEnemies.size()-1;i>=0;i--)
{
//EnemyController::erase(i);
EnemyController::showCaseEnemies.at(i)->removeFromParentAndCleanup(false);
}
for(int i=BulletController::bullets.size()-1;i>=0;i--)
{
BulletController::erase(i);
}
Director::getInstance()->replaceScene(HelloWorld::createScene());
}
bool GameOverLayer::onTouchBegan(Touch *touch, Event *event)
{
return true;
}
void GameOverLayer::onTouchMoved(Touch *touch, Event *event)
{
}
void GameOverLayer::onTouchEnded(Touch *touch, Event *event)
{
}<commit_msg>using stringStream instead of sprintf<commit_after>/****************************************************************************
Copyright (c) 2014 Chukong Technologies Inc.
http://github.com/chukong/EarthWarrior3D
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 "GameOverLayer.h"
#include "MainMenuScene.h"
#include "HelloWorldScene.h"
#include "GameLayer.h"
#include "GameControllers.h"
#include "AirCraft.h"
#include "Bullets.h"
#include <sstream>
GameOverLayer* GameOverLayer::create(int score)
{
GameOverLayer *pRet = new GameOverLayer();
pRet->m_score=score;
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
delete pRet;
pRet = NULL;
}
return pRet;
}
bool GameOverLayer::init()
{
if (!LayerColor::initWithColor(Color4B(255, 255, 255, 50))) {
return false;
}
auto visibleSize=Director::getInstance()->getVisibleSize();
auto score_bk=Sprite::createWithSpriteFrameName("gameover_score_bk.png");
score_bk->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2));
addChild(score_bk,1);
score_bk->setScale(0.2f);
score_bk->runAction(Sequence::create(ScaleTo::create(0.2f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::ShowScore,this)),
NULL));
auto backtomenu_normal=Sprite::createWithSpriteFrameName("gameover_backtomenu.png");
auto backtomenu_pressed=Sprite::createWithSpriteFrameName("gameover_backtomenu.png");
backtomenu_Item = MenuItemSprite::create(backtomenu_normal,
backtomenu_pressed,
CC_CALLBACK_1(GameOverLayer::menu_backtomenu_Callback,this));
// auto playagain_normal=Sprite::createWithSpriteFrameName("gameover_playagain.png");
// auto playagain_pressed=Sprite::createWithSpriteFrameName("gameover_playagain.png");
// playagain_Item = MenuItemSprite::create(playagain_normal,
// playagain_pressed,
// CC_CALLBACK_1(GameOverLayer::menu_playagain_Callback,this));
auto menu = Menu::create(backtomenu_Item,NULL);
menu->alignItemsHorizontallyWithPadding(20);
menu->setPosition(visibleSize.width/2, 100);
this->addChild(menu, 2);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(GameOverLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(GameOverLayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(GameOverLayer::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
void GameOverLayer::ShowScore()
{
auto visibleSize=Director::getInstance()->getVisibleSize();
auto score_text=Sprite::createWithSpriteFrameName("gameover_score.png");
score_text->setPosition(Vec2(-200, visibleSize.height/2+30));
score_text->runAction(MoveTo::create(0.5f, Vec2(visibleSize.width/2,visibleSize.height/2+30)));
addChild(score_text,2);
std::ostringstream pScore;
pScore<<m_score;
auto score_label=LabelBMFont::create(pScore.str(), "gameover_score_num.fnt");
score_label->setAnchorPoint(Vec2(0.5f,0.5f));
score_label->setPosition(Vec2(1000,visibleSize.height/2-40));
score_label->runAction(Sequence::create(
MoveTo::create(0.5f, Vec2(visibleSize.width/2,visibleSize.height/2-30)),
ScaleTo::create(0.1f, 1.3f),
ScaleTo::create(0.1f, 0.98f),
ScaleTo::create(0.1f, 1.2f),NULL));
addChild(score_label,2);
}
void GameOverLayer::menu_backtomenu_Callback(Ref* sender)
{
backtomenu_Item->runAction(Sequence::create(ScaleTo::create(0.1f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::menu_backtomenu, this)),NULL));
}
void GameOverLayer::menu_backtomenu()
{
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
Director::getInstance()->replaceScene(MainMenuScene::createScene());
for(int i=EnemyController::enemies.size()-1;i>=0;i--)
{
EnemyController::enemies.at(i)->removeFromParentAndCleanup(true);
}
EnemyController::enemies.clear();
for(int i=EnemyController::showCaseEnemies.size()-1;i>=0;i--)
{
EnemyController::showCaseEnemies.at(i)->removeFromParentAndCleanup(true);
//EnemyController::showCaseEnemies.erase(i);
}
EnemyController::showCaseEnemies.clear();
for(int i=BulletController::bullets.size()-1;i>=0;i--)
{
BulletController::bullets.erase(i);
}
BulletController::bullets.clear();
}
void GameOverLayer::menu_playagain_Callback(Ref* sender)
{
playagain_Item->runAction(Sequence::create(ScaleTo::create(0.1f, 1.1f),
ScaleTo::create(0.1f, 0.9f),
ScaleTo::create(0.1f, 1.0f),
CallFunc::create(CC_CALLBACK_0(GameOverLayer::menu_playagain, this)),NULL));
}
void GameOverLayer::menu_playagain()
{
CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();
GameLayer::isDie = false;
for(int i=EnemyController::enemies.size()-1;i>=0;i--)
{
EnemyController::erase(i);
}
for(int i=EnemyController::showCaseEnemies.size()-1;i>=0;i--)
{
//EnemyController::erase(i);
EnemyController::showCaseEnemies.at(i)->removeFromParentAndCleanup(false);
}
for(int i=BulletController::bullets.size()-1;i>=0;i--)
{
BulletController::erase(i);
}
Director::getInstance()->replaceScene(HelloWorld::createScene());
}
bool GameOverLayer::onTouchBegan(Touch *touch, Event *event)
{
return true;
}
void GameOverLayer::onTouchMoved(Touch *touch, Event *event)
{
}
void GameOverLayer::onTouchEnded(Touch *touch, Event *event)
{
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkObject.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkCommand.h"
namespace itk
{
class Observer
{
public:
Observer(Command* c,
unsigned long event,
unsigned long tag) :m_Command(c),
m_Event(event),
m_Tag(tag)
{ }
Command::Pointer m_Command;
unsigned long m_Event;
unsigned long m_Tag;
};
class SubjectImplementation
{
public:
SubjectImplementation() {m_Count = 0;}
~SubjectImplementation();
unsigned long AddObserver(unsigned long event, Command* cmd);
void RemoveObserver(unsigned long tag);
void InvokeEvent(unsigned long event, Object* self);
void InvokeEvent(unsigned long event, const Object* self);
Command *GetCommand(unsigned long tag);
bool HasObserver(unsigned long event) const;
private:
std::list<Observer* > m_Observers;
unsigned long m_Count;
};
SubjectImplementation::
~SubjectImplementation()
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
delete (*i);
}
}
unsigned long
SubjectImplementation::
AddObserver(unsigned long event,
Command* cmd)
{
Observer* ptr = new Observer(cmd, event, m_Count);
m_Observers.push_back(ptr);
m_Count++;
return ptr->m_Tag;
}
void
SubjectImplementation::
RemoveObserver(unsigned long tag)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
if((*i)->m_Tag == tag)
{
delete (*i);
m_Observers.erase(i);
return;
}
}
}
void
SubjectImplementation::
InvokeEvent(unsigned long event,
Object* self)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
(*i)->m_Command->Execute(self, event);
}
}
}
void
SubjectImplementation::
InvokeEvent(unsigned long event,
const Object* self)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
(*i)->m_Command->Execute(self, event);
}
}
}
Command*
SubjectImplementation::
GetCommand(unsigned long tag)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
if ( (*i)->m_Tag == tag)
{
return (*i)->m_Command;
}
}
return 0;
}
bool
SubjectImplementation::
HasObserver(unsigned long event) const
{
for(std::list<Observer* >::const_iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
return true;
}
}
return false;
}
/**
* Instance creation.
*/
Object::Pointer
Object
::New()
{
Self *ret = ObjectFactory<Self>::Create();
if(ret)
{
return ret;
}
return new Self;
}
/**
* Turn debugging output on.
*/
void
Object
::DebugOn() const
{
m_Debug = true;
}
/**
* Turn debugging output off.
*/
void
Object
::DebugOff() const
{
m_Debug = false;
}
/**
* Get the value of the debug flag.
*/
bool
Object
::GetDebug() const
{
return m_Debug;
}
/**
* Set the value of the debug flag. A non-zero value turns debugging on.
*/
void
Object
::SetDebug(bool debugFlag) const
{
m_Debug = debugFlag;
}
/**
* Return the modification for this object.
*/
unsigned long
Object
::GetMTime() const
{
return m_MTime.GetMTime();
}
/**
* Make sure this object's modified time is greater than all others.
*/
void
Object
::Modified() const
{
m_MTime.Modified();
InvokeEvent( Command::ModifiedEvent );
}
/**
* Increase the reference count (mark as used by another object).
*/
void
Object
::Register() const
{
itkDebugMacro(<< "Registered, "
<< "ReferenceCount = " << (m_ReferenceCount+1));
// call the parent
Superclass::Register();
}
/**
* Decrease the reference count (release by another object).
*/
void
Object
::UnRegister() const
{
// call the parent
itkDebugMacro(<< this << "UnRegistered, "
<< "ReferenceCount = " << (m_ReferenceCount-1));
if ( (m_ReferenceCount-1) <= 0)
{
/**
* If there is a delete method, invoke it.
*/
this->InvokeEvent(Command::DeleteEvent);
}
Superclass::UnRegister();
}
/**
* Sets the reference count (use with care)
*/
void
Object
::SetReferenceCount(int ref)
{
itkDebugMacro(<< "Reference Count set to " << ref);
// ReferenceCount in now unlocked. We may have a race condition to
// to delete the object.
if( ref <= 0 )
{
/**
* If there is a delete method, invoke it.
*/
this->InvokeEvent(Command::DeleteEvent);
}
Superclass::SetReferenceCount(ref);
}
/**
* Set the value of the global debug output control flag.
*/
void
Object
::SetGlobalWarningDisplay(bool val)
{
m_GlobalWarningDisplay = val;
}
/**
* Get the value of the global debug output control flag.
*/
bool
Object
::GetGlobalWarningDisplay()
{
return m_GlobalWarningDisplay;
}
unsigned long
Object
::AddObserver(unsigned long event, Command *cmd)
{
if (!this->m_SubjectImplementation)
{
this->m_SubjectImplementation = new SubjectImplementation;
}
return this->m_SubjectImplementation->AddObserver(event,cmd);
}
unsigned long
Object
::AddObserver(const char *event,Command *cmd)
{
return this->AddObserver(Command::GetEventIdFromString(event), cmd);
}
Command*
Object
::GetCommand(unsigned long tag)
{
if (this->m_SubjectImplementation)
{
return this->m_SubjectImplementation->GetCommand(tag);
}
return NULL;
}
void
Object
::RemoveObserver(unsigned long tag)
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->RemoveObserver(tag);
}
}
void
Object
::InvokeEvent(unsigned long event)
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->InvokeEvent(event,this);
}
}
void
Object
::InvokeEvent(unsigned long event) const
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->InvokeEvent(event,this);
}
}
void
Object
::InvokeEvent(const char *event)
{
this->InvokeEvent(Command::GetEventIdFromString(event));
}
void
Object
::InvokeEvent(const char *event) const
{
this->InvokeEvent(Command::GetEventIdFromString(event));
}
bool
Object
::HasObserver(unsigned long event) const
{
if (this->m_SubjectImplementation)
{
return this->m_SubjectImplementation->HasObserver(event);
}
return false;
}
bool
Object
::HasObserver(const char *event) const
{
return this->HasObserver(Command::GetEventIdFromString(event));
}
/**
* Create an object with Debug turned off and modified time initialized
* to the most recently modified object.
*/
Object
::Object():
LightObject(),
m_Debug(false),
m_SubjectImplementation(0)
{
this->Modified();
}
Object
::~Object()
{
itkDebugMacro(<< "Destructing!");
delete m_SubjectImplementation;
}
/**
* Chaining method to print an object's instance variables, as well as
* its superclasses.
*/
void
Object
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Modified Time: " << this->GetMTime() << std::endl;
os << indent << "Debug: " << (m_Debug ? "On\n" : "Off\n");
os << indent << "Instance has ";
if ( this->HasObserver(Command::AnyEvent) )
{
os << "one or more observers\n";
}
else
{
os << "no observers\n";
}
}
/**
* Initialize static member that controls warning display.
*/
bool Object::m_GlobalWarningDisplay = true;
} // end namespace itk
<commit_msg>FIX: debug macro in UnRegister()<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkObject.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2001 Insight Consortium
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.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkCommand.h"
namespace itk
{
class Observer
{
public:
Observer(Command* c,
unsigned long event,
unsigned long tag) :m_Command(c),
m_Event(event),
m_Tag(tag)
{ }
Command::Pointer m_Command;
unsigned long m_Event;
unsigned long m_Tag;
};
class SubjectImplementation
{
public:
SubjectImplementation() {m_Count = 0;}
~SubjectImplementation();
unsigned long AddObserver(unsigned long event, Command* cmd);
void RemoveObserver(unsigned long tag);
void InvokeEvent(unsigned long event, Object* self);
void InvokeEvent(unsigned long event, const Object* self);
Command *GetCommand(unsigned long tag);
bool HasObserver(unsigned long event) const;
private:
std::list<Observer* > m_Observers;
unsigned long m_Count;
};
SubjectImplementation::
~SubjectImplementation()
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
delete (*i);
}
}
unsigned long
SubjectImplementation::
AddObserver(unsigned long event,
Command* cmd)
{
Observer* ptr = new Observer(cmd, event, m_Count);
m_Observers.push_back(ptr);
m_Count++;
return ptr->m_Tag;
}
void
SubjectImplementation::
RemoveObserver(unsigned long tag)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
if((*i)->m_Tag == tag)
{
delete (*i);
m_Observers.erase(i);
return;
}
}
}
void
SubjectImplementation::
InvokeEvent(unsigned long event,
Object* self)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
(*i)->m_Command->Execute(self, event);
}
}
}
void
SubjectImplementation::
InvokeEvent(unsigned long event,
const Object* self)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
(*i)->m_Command->Execute(self, event);
}
}
}
Command*
SubjectImplementation::
GetCommand(unsigned long tag)
{
for(std::list<Observer* >::iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
if ( (*i)->m_Tag == tag)
{
return (*i)->m_Command;
}
}
return 0;
}
bool
SubjectImplementation::
HasObserver(unsigned long event) const
{
for(std::list<Observer* >::const_iterator i = m_Observers.begin();
i != m_Observers.end(); ++i)
{
unsigned long e = (*i)->m_Event;
if( e == Command::AnyEvent || e == event)
{
return true;
}
}
return false;
}
/**
* Instance creation.
*/
Object::Pointer
Object
::New()
{
Self *ret = ObjectFactory<Self>::Create();
if(ret)
{
return ret;
}
return new Self;
}
/**
* Turn debugging output on.
*/
void
Object
::DebugOn() const
{
m_Debug = true;
}
/**
* Turn debugging output off.
*/
void
Object
::DebugOff() const
{
m_Debug = false;
}
/**
* Get the value of the debug flag.
*/
bool
Object
::GetDebug() const
{
return m_Debug;
}
/**
* Set the value of the debug flag. A non-zero value turns debugging on.
*/
void
Object
::SetDebug(bool debugFlag) const
{
m_Debug = debugFlag;
}
/**
* Return the modification for this object.
*/
unsigned long
Object
::GetMTime() const
{
return m_MTime.GetMTime();
}
/**
* Make sure this object's modified time is greater than all others.
*/
void
Object
::Modified() const
{
m_MTime.Modified();
InvokeEvent( Command::ModifiedEvent );
}
/**
* Increase the reference count (mark as used by another object).
*/
void
Object
::Register() const
{
itkDebugMacro(<< "Registered, "
<< "ReferenceCount = " << (m_ReferenceCount+1));
// call the parent
Superclass::Register();
}
/**
* Decrease the reference count (release by another object).
*/
void
Object
::UnRegister() const
{
// call the parent
itkDebugMacro(<< "UnRegistered, "
<< "ReferenceCount = " << (m_ReferenceCount-1));
if ( (m_ReferenceCount-1) <= 0)
{
/**
* If there is a delete method, invoke it.
*/
this->InvokeEvent(Command::DeleteEvent);
}
Superclass::UnRegister();
}
/**
* Sets the reference count (use with care)
*/
void
Object
::SetReferenceCount(int ref)
{
itkDebugMacro(<< "Reference Count set to " << ref);
// ReferenceCount in now unlocked. We may have a race condition to
// to delete the object.
if( ref <= 0 )
{
/**
* If there is a delete method, invoke it.
*/
this->InvokeEvent(Command::DeleteEvent);
}
Superclass::SetReferenceCount(ref);
}
/**
* Set the value of the global debug output control flag.
*/
void
Object
::SetGlobalWarningDisplay(bool val)
{
m_GlobalWarningDisplay = val;
}
/**
* Get the value of the global debug output control flag.
*/
bool
Object
::GetGlobalWarningDisplay()
{
return m_GlobalWarningDisplay;
}
unsigned long
Object
::AddObserver(unsigned long event, Command *cmd)
{
if (!this->m_SubjectImplementation)
{
this->m_SubjectImplementation = new SubjectImplementation;
}
return this->m_SubjectImplementation->AddObserver(event,cmd);
}
unsigned long
Object
::AddObserver(const char *event,Command *cmd)
{
return this->AddObserver(Command::GetEventIdFromString(event), cmd);
}
Command*
Object
::GetCommand(unsigned long tag)
{
if (this->m_SubjectImplementation)
{
return this->m_SubjectImplementation->GetCommand(tag);
}
return NULL;
}
void
Object
::RemoveObserver(unsigned long tag)
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->RemoveObserver(tag);
}
}
void
Object
::InvokeEvent(unsigned long event)
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->InvokeEvent(event,this);
}
}
void
Object
::InvokeEvent(unsigned long event) const
{
if (this->m_SubjectImplementation)
{
this->m_SubjectImplementation->InvokeEvent(event,this);
}
}
void
Object
::InvokeEvent(const char *event)
{
this->InvokeEvent(Command::GetEventIdFromString(event));
}
void
Object
::InvokeEvent(const char *event) const
{
this->InvokeEvent(Command::GetEventIdFromString(event));
}
bool
Object
::HasObserver(unsigned long event) const
{
if (this->m_SubjectImplementation)
{
return this->m_SubjectImplementation->HasObserver(event);
}
return false;
}
bool
Object
::HasObserver(const char *event) const
{
return this->HasObserver(Command::GetEventIdFromString(event));
}
/**
* Create an object with Debug turned off and modified time initialized
* to the most recently modified object.
*/
Object
::Object():
LightObject(),
m_Debug(false),
m_SubjectImplementation(0)
{
this->Modified();
}
Object
::~Object()
{
itkDebugMacro(<< "Destructing!");
delete m_SubjectImplementation;
}
/**
* Chaining method to print an object's instance variables, as well as
* its superclasses.
*/
void
Object
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Modified Time: " << this->GetMTime() << std::endl;
os << indent << "Debug: " << (m_Debug ? "On\n" : "Off\n");
os << indent << "Instance has ";
if ( this->HasObserver(Command::AnyEvent) )
{
os << "one or more observers\n";
}
else
{
os << "no observers\n";
}
}
/**
* Initialize static member that controls warning display.
*/
bool Object::m_GlobalWarningDisplay = true;
} // end namespace itk
<|endoftext|>
|
<commit_before><commit_msg>Fix time calculation error....<commit_after><|endoftext|>
|
<commit_before>/*--------------------------------------------------------------------------
File : device_intrf.cpp
Author : Hoang Nguyen Hoan Dec. 25, 2011
Desc : Generic device interface class
This class is used to implement serial communication interfaces
such as I2C, UART, etc... Not limited to wired interface
Copyright (c) 2011, I-SYST inc., all rights reserved
Permission to use, copy, modify, and 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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
Hoan Mar. 3, 2017 Rename to DevIntrf
----------------------------------------------------------------------------*/
#include <string.h>
#include "device_intrf.h"
// NOTE : For thread safe use
//
// DeviceIntrfStartRx
// DeviceIntrfStopRx
// DeviceIntrfStartTx
// DeviceIntrfStopTx
//
int DeviceIntrfRx(DEVINTRF *pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartRx(pDev, DevAddr)) {
count = pDev->RxData(pDev, pBuff, BuffLen);
DeviceIntrfStopRx(pDev);
}
} while(count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfTx(DEVINTRF *pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartTx(pDev, DevAddr)) {
count = pDev->TxData(pDev, pBuff, BuffLen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfRead(DEVINTRF *pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pRxBuff, int RxLen)
{
int count = 0;
int nrtry = pDev->MaxRetry;
if (pRxBuff == NULL || RxLen <= 0)
return 0;
do {
if (DeviceIntrfStartRx(pDev, DevAddr))
{
if (pAdCmd)
{
count = pDev->TxData(pDev, pAdCmd, AdCmdLen);
}
count = pDev->RxData(pDev, pRxBuff, RxLen);
DeviceIntrfStopRx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfWrite(DEVINTRF *pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pTxData, int TxLen)
{
int count = 0;
int nrtry = pDev->MaxRetry;
uint8_t d[AdCmdLen + TxLen];
if (pTxData == NULL || pAdCmd == NULL)
return 0;
memcpy(d, pAdCmd, AdCmdLen);
memcpy(&d[AdCmdLen], pTxData, TxLen);
do {
if (DeviceIntrfStartTx(pDev, DevAddr))
{
count = pDev->TxData(pDev, d, AdCmdLen + TxLen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
if (count >= AdCmdLen)
count -= AdCmdLen;
else
count = 0;
return count;
}
<commit_msg>Add restart condition for compatibility with LPC MCU<commit_after>/*--------------------------------------------------------------------------
File : device_intrf.cpp
Author : Hoang Nguyen Hoan Dec. 25, 2011
Desc : Generic device interface class
This class is used to implement serial communication interfaces
such as I2C, UART, etc... Not limited to wired interface
Copyright (c) 2011, I-SYST inc., all rights reserved
Permission to use, copy, modify, and 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, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
----------------------------------------------------------------------------
Modified by Date Description
Hoan Mar. 3, 2017 Rename to DevIntrf
----------------------------------------------------------------------------*/
#include <string.h>
#include "device_intrf.h"
// NOTE : For thread safe use
//
// DeviceIntrfStartRx
// DeviceIntrfStopRx
// DeviceIntrfStartTx
// DeviceIntrfStopTx
//
int DeviceIntrfRx(DEVINTRF *pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartRx(pDev, DevAddr)) {
count = pDev->RxData(pDev, pBuff, BuffLen);
DeviceIntrfStopRx(pDev);
}
} while(count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfTx(DEVINTRF *pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartTx(pDev, DevAddr)) {
count = pDev->TxData(pDev, pBuff, BuffLen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfRead(DEVINTRF *pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pRxBuff, int RxLen)
{
int count = 0;
int nrtry = pDev->MaxRetry;
if (pRxBuff == NULL || RxLen <= 0)
return 0;
do {
if (DeviceIntrfStartTx(pDev, DevAddr))
{
if (pAdCmd)
{
count = pDev->TxData(pDev, pAdCmd, AdCmdLen);
}
// Note : this is restart condition in read mode,
// must not generate any stop condition here
pDev->StartRx(pDev, DevAddr);
count = pDev->RxData(pDev, pRxBuff, RxLen);
DeviceIntrfStopRx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfWrite(DEVINTRF *pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pTxData, int TxLen)
{
int count = 0;
int nrtry = pDev->MaxRetry;
uint8_t d[AdCmdLen + TxLen];
if (pTxData == NULL || pAdCmd == NULL)
return 0;
memcpy(d, pAdCmd, AdCmdLen);
memcpy(&d[AdCmdLen], pTxData, TxLen);
do {
if (DeviceIntrfStartTx(pDev, DevAddr))
{
count = pDev->TxData(pDev, d, AdCmdLen + TxLen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
if (count >= AdCmdLen)
count -= AdCmdLen;
else
count = 0;
return count;
}
<|endoftext|>
|
<commit_before><commit_msg>Use the re-entrant variants of the time functions.<commit_after><|endoftext|>
|
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_EXTRACTION_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_EXTRACTION_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include <algorithm>
#include <vector>
#include <cmath>
namespace aleph
{
/**
Stores all (signed) persistence values in an output iterator. This is
a convenience function to simplify common operations. If desired, the
absolute value of the persistence is being reported.
*/
template <class DataType, class OutputIterator>
void persistence( const PersistenceDiagram<DataType>& D,
OutputIterator result,
bool useAbsoluteValue = false )
{
for( auto&& point : D )
*result++ = useAbsoluteValue ? std::abs( point.persistence() ) : point.persistence();
}
/**
Similar to aleph::persistence(), but takes the multiplicity of points
into account. Hence, this function does not offer the option to apply
the absolute value to the persistence.
*/
template <class DataType, class OutputIterator>
void weightedPersistence( const PersistenceDiagram<DataType>& D,
OutputIterator result )
{
using Point = typename PersistenceDiagram<DataType>::Point;
std::vector<Point> points;
points.reserve( D.size() );
for( auto&& point : D )
points.push_back( point );
std::sort( points.begin(), points.end(), [] ( const Point& p, const Point& q )
{
if( p.x() == q.x() )
return p.y() < q.y();
else
return p.x() < q.x();
} );
// Get all unique points
std::vector<Point> uniquePoints;
std::unique_copy( points.begin(), points.end(),
std::back_inserter( uniquePoints ) );
for( auto&& point : uniquePoints )
{
auto count = std::count( points.begin(), points.end(), point );
auto weight = static_cast<double>( count ) / static_cast<double>( points.size() );
*result++ = point.persistence() / weight;
}
}
} // namespace aleph
#endif
<commit_msg>Fixed weighting scheme for persistence extraction<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_EXTRACTION_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_EXTRACTION_HH__
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include <algorithm>
#include <vector>
#include <cmath>
namespace aleph
{
/**
Stores all (signed) persistence values in an output iterator. This is
a convenience function to simplify common operations. If desired, the
absolute value of the persistence is being reported.
*/
template <class DataType, class OutputIterator>
void persistence( const PersistenceDiagram<DataType>& D,
OutputIterator result,
bool useAbsoluteValue = false )
{
for( auto&& point : D )
*result++ = useAbsoluteValue ? std::abs( point.persistence() ) : point.persistence();
}
/**
Similar to aleph::persistence(), but takes the multiplicity of points
into account. Hence, this function does not offer the option to apply
the absolute value to the persistence.
*/
template <class DataType, class OutputIterator>
void weightedPersistence( const PersistenceDiagram<DataType>& D,
OutputIterator result )
{
using Point = typename PersistenceDiagram<DataType>::Point;
std::vector<Point> points;
points.reserve( D.size() );
for( auto&& point : D )
points.push_back( point );
std::sort( points.begin(), points.end(), [] ( const Point& p, const Point& q )
{
if( p.x() == q.x() )
return p.y() < q.y();
else
return p.x() < q.x();
} );
// Get all unique points
std::vector<Point> uniquePoints;
std::unique_copy( points.begin(), points.end(),
std::back_inserter( uniquePoints ) );
for( auto&& point : uniquePoints )
{
auto count = std::count( points.begin(), points.end(), point );
auto weight = static_cast<double>( count ) / static_cast<double>( points.size() );
*result++ = weight * point.persistence();
}
}
} // namespace aleph
#endif
<|endoftext|>
|
<commit_before>#include <pybind11/embed.h>
#include "plugin.h"
#include "plugin_manager.h"
#include "term_gl_ui.h"
#include "term_window.h"
#include "task.h"
#include "term_context.h"
#include "term_network.h"
#include "term_buffer.h"
#include "term_data_handler.h"
#include "app_config_impl.h"
#include "plugin_base.h"
#include <iostream>
#include "freetype-gl.h"
#include "vertex-buffer.h"
#include "text-buffer.h"
#include <GLFW/glfw3.h>
#include "default_term_window.h"
#include "freetype_gl.h"
// --------------------------------------------------------- error-callback ---
void error_callback( int error, const char* description )
{
std::cerr << "error:" << error << ", description:" << description << std::endl;
}
class __GLTermUIInitializer {
public:
bool init;
__GLTermUIInitializer() : init(false) {
}
void Initialize() {
if (init) return;
glfwSetErrorCallback( error_callback );
init = glfwInit();
}
~__GLTermUIInitializer() {
if (init)
glfwTerminate();
}
};
class DefaultTermUI : public virtual PluginBase, public virtual TermUI {
static __GLTermUIInitializer _initializer;
public:
DefaultTermUI() :
PluginBase("term_gl_ui", "opengl terminal ui plugin", 1)
{
}
virtual ~DefaultTermUI() {
}
struct TaskEntry {
TaskPtr task;
double end_time;
bool repeated;
bool done;
int interval;
};
std::vector<TaskEntry> m_Tasks;
std::vector<TermWindowPtr> m_Windows;
TermWindowPtr CreateWindow() {
DefaultTermUI::_initializer.Initialize();
auto window = TermWindowPtr { new DefaultTermWindow() };
window->InitPlugin(GetPluginContext(),
GetPluginConfig());
m_Windows.push_back(window);
return window;
}
double ProcessTasks() {
auto cur_time = glfwGetTime();
double next_end_time = 0.0;
for(auto & entry : m_Tasks) {
if (entry.done) continue;
if (cur_time * 1000 >= entry.end_time) {
if (entry.task && !entry.task->IsCancelled()) {
entry.task->Run();
}
if (entry.repeated) {
entry.end_time = cur_time * 1000 + entry.interval;
} else {
entry.done = true;
}
} else if (next_end_time == 0.0
|| entry.end_time < next_end_time) {
next_end_time = entry.end_time;
}
}
return next_end_time == 0.0 ? 0.0 : (next_end_time - cur_time);
}
bool AllWindowClosed() {
for(auto & window : m_Windows) {
DefaultTermWindow * pWindow =
dynamic_cast<DefaultTermWindow*>(window.get());
if (!pWindow->ShouldClose())
return false;
}
return true;
}
void UpdateAllWindows() {
for(auto & window : m_Windows) {
DefaultTermWindow * pWindow =
dynamic_cast<DefaultTermWindow*>(window.get());
pWindow->UpdateWindow();
}
}
int32_t StartMainUILoop() {
glfwWindowHint( GLFW_VISIBLE, GL_FALSE );
glfwWindowHint( GLFW_RESIZABLE, GL_TRUE );
pybind11::gil_scoped_release release;
double delta = ProcessTasks();
while (!AllWindowClosed())
{
if (delta) {
glfwWaitEventsTimeout(delta / 1000);
} else {
glfwWaitEvents();
}
delta = ProcessTasks();
UpdateAllWindows();
}
return 0;
}
bool ScheduleTask(TaskPtr task, int miliseconds, bool repeated) {
TaskEntry entry {
.task = task,
.end_time = glfwGetTime() * 1000 + miliseconds,
.repeated = repeated,
.done = false,
.interval = miliseconds
};
m_Tasks.push_back(entry);
glfwPostEmptyEvent();
return true;
}
};
__GLTermUIInitializer DefaultTermUI::_initializer;
TermUIPtr CreateOpenGLTermUI() {
return TermUIPtr{ new DefaultTermUI()};
}
<commit_msg>trying to avoid deadlock when error<commit_after>#include <pybind11/embed.h>
#include "plugin.h"
#include "plugin_manager.h"
#include "term_gl_ui.h"
#include "term_window.h"
#include "task.h"
#include "term_context.h"
#include "term_network.h"
#include "term_buffer.h"
#include "term_data_handler.h"
#include "app_config_impl.h"
#include "plugin_base.h"
#include <iostream>
#include "freetype-gl.h"
#include "vertex-buffer.h"
#include "text-buffer.h"
#include <GLFW/glfw3.h>
#include "default_term_window.h"
#include "freetype_gl.h"
// --------------------------------------------------------- error-callback ---
void error_callback( int error, const char* description )
{
std::cerr << "error:" << error << ", description:" << description << std::endl;
}
class __GLTermUIInitializer {
public:
bool init;
__GLTermUIInitializer() : init(false) {
}
void Initialize() {
if (init) return;
glfwSetErrorCallback( error_callback );
init = glfwInit();
}
void Cleanup() {
if (init)
glfwTerminate();
init = false;
}
~__GLTermUIInitializer() {
}
};
class DefaultTermUI : public virtual PluginBase, public virtual TermUI {
static __GLTermUIInitializer _initializer;
public:
DefaultTermUI() :
PluginBase("term_gl_ui", "opengl terminal ui plugin", 1)
{
}
virtual ~DefaultTermUI() {
}
struct TaskEntry {
TaskPtr task;
double end_time;
bool repeated;
bool done;
int interval;
};
std::vector<TaskEntry> m_Tasks;
std::vector<TermWindowPtr> m_Windows;
TermWindowPtr CreateWindow() {
DefaultTermUI::_initializer.Initialize();
auto window = TermWindowPtr { new DefaultTermWindow() };
window->InitPlugin(GetPluginContext(),
GetPluginConfig());
m_Windows.push_back(window);
return window;
}
double ProcessTasks() {
auto cur_time = glfwGetTime();
double next_end_time = 0.0;
for(auto & entry : m_Tasks) {
if (entry.done) continue;
if (cur_time * 1000 >= entry.end_time) {
if (entry.task && !entry.task->IsCancelled()) {
entry.task->Run();
}
if (entry.repeated) {
entry.end_time = cur_time * 1000 + entry.interval;
} else {
entry.done = true;
}
} else if (next_end_time == 0.0
|| entry.end_time < next_end_time) {
next_end_time = entry.end_time;
}
}
return next_end_time == 0.0 ? 0.0 : (next_end_time - cur_time);
}
bool AllWindowClosed() {
for(auto & window : m_Windows) {
DefaultTermWindow * pWindow =
dynamic_cast<DefaultTermWindow*>(window.get());
if (!pWindow->ShouldClose())
return false;
}
return true;
}
void UpdateAllWindows() {
for(auto & window : m_Windows) {
DefaultTermWindow * pWindow =
dynamic_cast<DefaultTermWindow*>(window.get());
pWindow->UpdateWindow();
}
}
int32_t StartMainUILoop() {
glfwWindowHint( GLFW_VISIBLE, GL_FALSE );
glfwWindowHint( GLFW_RESIZABLE, GL_TRUE );
pybind11::gil_scoped_release release;
double delta = ProcessTasks();
while (!AllWindowClosed())
{
if (delta) {
glfwWaitEventsTimeout(delta / 1000);
} else {
glfwWaitEvents();
}
delta = ProcessTasks();
UpdateAllWindows();
}
DefaultTermUI::_initializer.Cleanup();
return 0;
}
bool ScheduleTask(TaskPtr task, int miliseconds, bool repeated) {
TaskEntry entry {
.task = task,
.end_time = glfwGetTime() * 1000 + miliseconds,
.repeated = repeated,
.done = false,
.interval = miliseconds
};
m_Tasks.push_back(entry);
glfwPostEmptyEvent();
return true;
}
};
__GLTermUIInitializer DefaultTermUI::_initializer;
TermUIPtr CreateOpenGLTermUI() {
return TermUIPtr{ new DefaultTermUI()};
}
<|endoftext|>
|
<commit_before><commit_msg>[core] Removed logging in cleanup<commit_after><|endoftext|>
|
<commit_before>#include "similarity_opencl_worker.h"
#include "similarity_resultblock.h"
#include "similarity_workblock.h"
#include <ace/core/elog.h>
using namespace std;
/*!
* Construct a new OpenCL worker with the given parent analytic, OpenCL object,
* OpenCL context, and OpenCL program.
*
* @param base
* @param baseOpenCL
* @param context
* @param program
*/
Similarity::OpenCL::Worker::Worker(Similarity* base, Similarity::OpenCL* baseOpenCL, ::OpenCL::Context* context, ::OpenCL::Program* program):
_base(base),
_baseOpenCL(baseOpenCL),
_queue(new ::OpenCL::CommandQueue(context, context->devices().first(), this)),
_kernels({
.fetchPair = new OpenCL::FetchPair(program, this),
.gmm = new OpenCL::GMM(program, this),
.outlier = new OpenCL::Outlier(program, this),
.pearson = new OpenCL::Pearson(program, this),
.spearman = new OpenCL::Spearman(program, this)
})
{
EDEBUG_FUNC(this,base,baseOpenCL,context,program);
// initialize buffers
int W {_base->_globalWorkSize};
int N {_base->_input->sampleSize()};
int N_pow2 {nextPower2(N)};
int K {_base->_maxClusters};
_buffers.in_index = ::OpenCL::Buffer<cl_int2>(context, 1 * W);
_buffers.work_N = ::OpenCL::Buffer<cl_int>(context, 1 * W);
_buffers.work_X = ::OpenCL::Buffer<cl_float2>(context, N * W);
_buffers.work_labels = ::OpenCL::Buffer<cl_char>(context, N * W);
_buffers.work_components = ::OpenCL::Buffer<cl_component>(context, K * W);
_buffers.work_MP = ::OpenCL::Buffer<cl_float2>(context, K * W);
_buffers.work_counts = ::OpenCL::Buffer<cl_int>(context, K * W);
_buffers.work_logpi = ::OpenCL::Buffer<cl_float>(context, K * W);
_buffers.work_gamma = ::OpenCL::Buffer<cl_float>(context, N * K * W);
_buffers.work_x = ::OpenCL::Buffer<cl_float>(context, N_pow2 * W);
_buffers.work_y = ::OpenCL::Buffer<cl_float>(context, N_pow2 * W);
_buffers.out_K = ::OpenCL::Buffer<cl_char>(context, 1 * W);
_buffers.out_labels = ::OpenCL::Buffer<cl_char>(context, N * W);
_buffers.out_correlations = ::OpenCL::Buffer<cl_float>(context, K * W);
}
/*!
* Read in the given work block, execute the algorithms necessary to produce
* results using OpenCL acceleration, and save those results in a new result
* block whose pointer is returned.
*
* @param block
*/
std::unique_ptr<EAbstractAnalyticBlock> Similarity::OpenCL::Worker::execute(const EAbstractAnalyticBlock* block)
{
EDEBUG_FUNC(this,block);
if ( ELog::isActive() )
{
ELog() << tr("Executing(OpenCL) work index %1.\n").arg(block->index());
}
// cast block to work block
const WorkBlock* workBlock {block->cast<const WorkBlock>()};
// initialize result block
ResultBlock* resultBlock {new ResultBlock(workBlock->index(), workBlock->start())};
// iterate through all pairs
Pairwise::Index index {workBlock->start()};
for ( int i = 0; i < workBlock->size(); i += _base->_globalWorkSize )
{
// write input buffers to device
int numPairs {static_cast<int>(min(static_cast<qint64>(_base->_globalWorkSize), workBlock->size() - i))};
_buffers.in_index.mapWrite(_queue).wait();
for ( int j = 0; j < numPairs; ++j )
{
_buffers.in_index[j] = { index.getX(), index.getY() };
++index;
}
_buffers.in_index.unmap(_queue).wait();
// execute fetch-pair kernel
_kernels.fetchPair->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_minExpression,
&_buffers.work_N,
&_buffers.out_labels
).wait();
// execute outlier kernel (pre-clustering)
if ( _base->_removePreOutliers )
{
_kernels.outlier->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
&_buffers.work_N,
&_buffers.out_labels,
&_buffers.out_K,
-7,
&_buffers.work_x,
&_buffers.work_y
).wait();
}
// execute clustering kernel
if ( _base->_clusMethod == ClusteringMethod::GMM )
{
_kernels.gmm->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_minSamples,
_base->_minClusters,
_base->_maxClusters,
(cl_int) _base->_criterion,
&_buffers.work_X,
&_buffers.work_N,
&_buffers.work_labels,
&_buffers.work_components,
&_buffers.work_MP,
&_buffers.work_counts,
&_buffers.work_logpi,
&_buffers.work_gamma,
&_buffers.out_K,
&_buffers.out_labels
).wait();
}
else
{
// set cluster size to 1 if clustering is disabled
_buffers.out_K.mapWrite(_queue).wait();
for ( int i = 0; i < numPairs; ++i )
{
_buffers.out_K[i] = 1;
}
_buffers.out_K.unmap(_queue).wait();
}
// execute outlier kernel (post-clustering)
if ( _base->_removePostOutliers )
{
_kernels.outlier->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
&_buffers.work_N,
&_buffers.out_labels,
&_buffers.out_K,
-8,
&_buffers.work_x,
&_buffers.work_y
).wait();
}
// execute correlation kernel
if ( _base->_corrMethod == CorrelationMethod::Pearson )
{
_kernels.pearson->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_maxClusters,
&_buffers.out_labels,
_base->_minSamples,
&_buffers.out_correlations
).wait();
}
else if ( _base->_corrMethod == CorrelationMethod::Spearman )
{
_kernels.spearman->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_maxClusters,
&_buffers.out_labels,
_base->_minSamples,
&_buffers.work_x,
&_buffers.work_y,
&_buffers.out_correlations
).wait();
}
// read results from device
auto e1 {_buffers.out_K.mapRead(_queue)};
auto e2 {_buffers.out_labels.mapRead(_queue)};
auto e3 {_buffers.out_correlations.mapRead(_queue)};
e1.wait();
e2.wait();
e3.wait();
// save results
for ( int j = 0; j < numPairs; ++j )
{
// get pointers to the cluster labels and correlations for this pair
const qint8 *labels = &_buffers.out_labels.at(j * _base->_input->sampleSize());
const float *correlations = &_buffers.out_correlations.at(j * _base->_maxClusters);
Pair pair;
// save the number of clusters
pair.K = _buffers.out_K.at(j);
// save the cluster labels and correlations (if the pair was able to be processed)
if ( pair.K > 0 )
{
pair.labels = ResultBlock::makeVector(labels, _base->_input->sampleSize());
pair.correlations = ResultBlock::makeVector(correlations, _base->_maxClusters);
}
resultBlock->append(pair);
}
auto e4 {_buffers.out_K.unmap(_queue)};
auto e5 {_buffers.out_labels.unmap(_queue)};
auto e6 {_buffers.out_correlations.unmap(_queue)};
e4.wait();
e5.wait();
e6.wait();
}
// return result block
return unique_ptr<EAbstractAnalyticBlock>(resultBlock);
}
<commit_msg>Updated similarity opencl worker to use queue wait()<commit_after>#include "similarity_opencl_worker.h"
#include "similarity_resultblock.h"
#include "similarity_workblock.h"
#include <ace/core/elog.h>
using namespace std;
/*!
* Construct a new OpenCL worker with the given parent analytic, OpenCL object,
* OpenCL context, and OpenCL program.
*
* @param base
* @param baseOpenCL
* @param context
* @param program
*/
Similarity::OpenCL::Worker::Worker(Similarity* base, Similarity::OpenCL* baseOpenCL, ::OpenCL::Context* context, ::OpenCL::Program* program):
_base(base),
_baseOpenCL(baseOpenCL),
_queue(new ::OpenCL::CommandQueue(context, context->devices().first(), this)),
_kernels({
.fetchPair = new OpenCL::FetchPair(program, this),
.gmm = new OpenCL::GMM(program, this),
.outlier = new OpenCL::Outlier(program, this),
.pearson = new OpenCL::Pearson(program, this),
.spearman = new OpenCL::Spearman(program, this)
})
{
EDEBUG_FUNC(this,base,baseOpenCL,context,program);
// initialize buffers
int W {_base->_globalWorkSize};
int N {_base->_input->sampleSize()};
int N_pow2 {nextPower2(N)};
int K {_base->_maxClusters};
_buffers.in_index = ::OpenCL::Buffer<cl_int2>(context, 1 * W);
_buffers.work_N = ::OpenCL::Buffer<cl_int>(context, 1 * W);
_buffers.work_X = ::OpenCL::Buffer<cl_float2>(context, N * W);
_buffers.work_labels = ::OpenCL::Buffer<cl_char>(context, N * W);
_buffers.work_components = ::OpenCL::Buffer<cl_component>(context, K * W);
_buffers.work_MP = ::OpenCL::Buffer<cl_float2>(context, K * W);
_buffers.work_counts = ::OpenCL::Buffer<cl_int>(context, K * W);
_buffers.work_logpi = ::OpenCL::Buffer<cl_float>(context, K * W);
_buffers.work_gamma = ::OpenCL::Buffer<cl_float>(context, N * K * W);
_buffers.work_x = ::OpenCL::Buffer<cl_float>(context, N_pow2 * W);
_buffers.work_y = ::OpenCL::Buffer<cl_float>(context, N_pow2 * W);
_buffers.out_K = ::OpenCL::Buffer<cl_char>(context, 1 * W);
_buffers.out_labels = ::OpenCL::Buffer<cl_char>(context, N * W);
_buffers.out_correlations = ::OpenCL::Buffer<cl_float>(context, K * W);
}
/*!
* Read in the given work block, execute the algorithms necessary to produce
* results using OpenCL acceleration, and save those results in a new result
* block whose pointer is returned.
*
* @param block
*/
std::unique_ptr<EAbstractAnalyticBlock> Similarity::OpenCL::Worker::execute(const EAbstractAnalyticBlock* block)
{
EDEBUG_FUNC(this,block);
if ( ELog::isActive() )
{
ELog() << tr("Executing(OpenCL) work index %1.\n").arg(block->index());
}
// cast block to work block
const WorkBlock* workBlock {block->cast<const WorkBlock>()};
// initialize result block
ResultBlock* resultBlock {new ResultBlock(workBlock->index(), workBlock->start())};
// iterate through all pairs
Pairwise::Index index {workBlock->start()};
for ( int i = 0; i < workBlock->size(); i += _base->_globalWorkSize )
{
// write input buffers to device
int numPairs {static_cast<int>(min(static_cast<qint64>(_base->_globalWorkSize), workBlock->size() - i))};
_buffers.in_index.mapWrite(_queue).wait();
for ( int j = 0; j < numPairs; ++j )
{
_buffers.in_index[j] = { index.getX(), index.getY() };
++index;
}
_buffers.in_index.unmap(_queue);
// execute fetch-pair kernel
_kernels.fetchPair->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_minExpression,
&_buffers.work_N,
&_buffers.out_labels
);
// execute outlier kernel (pre-clustering)
if ( _base->_removePreOutliers )
{
_kernels.outlier->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
&_buffers.work_N,
&_buffers.out_labels,
&_buffers.out_K,
-7,
&_buffers.work_x,
&_buffers.work_y
);
}
// execute clustering kernel
if ( _base->_clusMethod == ClusteringMethod::GMM )
{
_kernels.gmm->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_minSamples,
_base->_minClusters,
_base->_maxClusters,
(cl_int) _base->_criterion,
&_buffers.work_X,
&_buffers.work_N,
&_buffers.work_labels,
&_buffers.work_components,
&_buffers.work_MP,
&_buffers.work_counts,
&_buffers.work_logpi,
&_buffers.work_gamma,
&_buffers.out_K,
&_buffers.out_labels
);
}
else
{
// set cluster size to 1 if clustering is disabled
_buffers.out_K.mapWrite(_queue).wait();
for ( int i = 0; i < numPairs; ++i )
{
_buffers.out_K[i] = 1;
}
_buffers.out_K.unmap(_queue);
}
// execute outlier kernel (post-clustering)
if ( _base->_removePostOutliers )
{
_kernels.outlier->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
&_buffers.work_N,
&_buffers.out_labels,
&_buffers.out_K,
-8,
&_buffers.work_x,
&_buffers.work_y
);
}
// execute correlation kernel
if ( _base->_corrMethod == CorrelationMethod::Pearson )
{
_kernels.pearson->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_maxClusters,
&_buffers.out_labels,
_base->_minSamples,
&_buffers.out_correlations
);
}
else if ( _base->_corrMethod == CorrelationMethod::Spearman )
{
_kernels.spearman->execute(
_queue,
_base->_globalWorkSize,
_base->_localWorkSize,
numPairs,
&_baseOpenCL->_expressions,
_base->_input->sampleSize(),
&_buffers.in_index,
_base->_maxClusters,
&_buffers.out_labels,
_base->_minSamples,
&_buffers.work_x,
&_buffers.work_y,
&_buffers.out_correlations
);
}
// read results from device
_buffers.out_K.mapRead(_queue);
_buffers.out_labels.mapRead(_queue);
_buffers.out_correlations.mapRead(_queue);
// wait for everything to finish
_queue->wait();
// save results
for ( int j = 0; j < numPairs; ++j )
{
// get pointers to the cluster labels and correlations for this pair
const qint8 *labels = &_buffers.out_labels.at(j * _base->_input->sampleSize());
const float *correlations = &_buffers.out_correlations.at(j * _base->_maxClusters);
Pair pair;
// save the number of clusters
pair.K = _buffers.out_K.at(j);
// save the cluster labels and correlations (if the pair was able to be processed)
if ( pair.K > 0 )
{
pair.labels = ResultBlock::makeVector(labels, _base->_input->sampleSize());
pair.correlations = ResultBlock::makeVector(correlations, _base->_maxClusters);
}
resultBlock->append(pair);
}
_buffers.out_K.unmap(_queue);
_buffers.out_labels.unmap(_queue);
_buffers.out_correlations.unmap(_queue);
}
// return result block
return unique_ptr<EAbstractAnalyticBlock>(resultBlock);
}
<|endoftext|>
|
<commit_before>#include "core/EnvironmentOperations.h"
extern "C" {
#include "clips.h"
#include <stdio.h>
}
#define werror (char*)"werror"
#define wdisplay (char*)"wdisplay"
#define wwarning (char*)"wwarning"
#define PrintError(e, msg) EnvPrintRouter(e, werror, (char*) msg)
#define CharBuffer(sz) (char*)calloc(sz, sizeof(char))
extern "C" void EnvironmentDestroy(void* theEnv);
extern "C" void* GetCurrentlyExecutingEnvironment(void* theEnv);
extern "C" void* IsCurrentlyExecutingEnvironment(void* theEnv);
extern "C" void* ToPointer(void* theEnv);
extern "C" void RunEnvironment(void* theEnv);
extern "C" void EnvironmentEval(void* theEnv, DATA_OBJECT_PTR ret);
extern "C" void EnvironmentBuild(void* theEnv);
extern "C" void EnvironmentFacts(void* theEnv);
extern "C" void EnvironmentInstances(void* theEnv);
extern "C" void EnvironmentRules(void* theEnv);
extern "C" void EnvironmentAssertString(void* theEnv);
extern "C" void* EnvironmentCreate(void* theEnv);
void EnvironmentOperationsDefinitions(void* theEnv) {
EnvDefineFunction(theEnv, "env-destroy", 'v',
PTIEF EnvironmentDestroy,
"EnvironmentDestroy");
EnvDefineFunction(theEnv, "get-currently-executing-environment", 'a',
PTIEF GetCurrentlyExecutingEnvironment,
"GetCurrentlyExecutingEnvironment");
EnvDefineFunction(theEnv, "is-currently-executing-environment", 'w',
PTIEF IsCurrentlyExecutingEnvironment,
"IsCurrentlyExecutingEnvironment");
EnvDefineFunction(theEnv, "to-pointer", 'a', PTIEF ToPointer, "ToPointer");
EnvDefineFunction(theEnv, "env-run", 'v', PTIEF RunEnvironment, "RunEnvironment");
EnvDefineFunction(theEnv, "env-eval", 'u', PTIEF EnvironmentEval,
"EnvironmentEval");
EnvDefineFunction(theEnv, "env-build", 'v', PTIEF EnvironmentBuild,
"EnvironmentBuild");
EnvDefineFunction(theEnv, "env-facts", 'v', PTIEF EnvironmentFacts,
"EnvironmentFacts");
EnvDefineFunction(theEnv, "env-instances", 'v', PTIEF EnvironmentInstances,
"EnvironmentInstances");
EnvDefineFunction(theEnv, "env-rules", 'v', PTIEF EnvironmentRules,
"EnvironmentRules");
EnvDefineFunction(theEnv, "env-assert-string", 'v', PTIEF EnvironmentAssertString,
"EnvironmentAssertString");
EnvDefineFunction(theEnv, "env-create", 'a', PTIEF EnvironmentCreate,
"EnvironmentCreate");
}
void EnvironmentDestroy(void* theEnv) {
DATA_OBJECT arg0;
if((EnvArgCountCheck(theEnv, "env-destroy", EXACTLY, 1) == -1)) {
return;
}
if(EnvArgTypeCheck(theEnv, "env-destroy", 1, EXTERNAL_ADDRESS, &arg0)) {
void* targetEnv = (void*)GetValue(arg0);
DestroyEnvironment(targetEnv);
return;
} else if(EnvArgTypeCheck(theEnv, "env-destroy", 1, INTEGER, &arg0)) {
void* targetEnv = (void*)(long long)DOToLong(arg0);
DestroyEnvironment(targetEnv);
return;
} else {
return;
}
}
void* GetCurrentlyExecutingEnvironment(void* theEnv) {
if(EnvArgCountCheck(theEnv, "get-currently-executing-environment", EXACTLY, 0) == -1) {
PrintError(theEnv,
"get-currently-executing-environment does not accept arguments\n");
return (void*)0;
}
return GetCurrentEnvironment();
}
void* IsCurrentlyExecutingEnvironment(void* theEnv) {
DATA_OBJECT arg0;
if((EnvArgCountCheck(theEnv, "is-currently-executing-environment", EXACTLY, 1) == -1)) {
PrintError(theEnv, "Either too many or too few arguments provided\n");
return FalseSymbol();
}
if(EnvArgTypeCheck(theEnv, "is-currently-executing-environment", 1, EXTERNAL_ADDRESS, &arg0)) {
void* otherEnv = (void*)GetValue(arg0);
if(otherEnv == theEnv) {
return TrueSymbol();
} else {
return FalseSymbol();
}
} else if (EnvArgTypeCheck(theEnv, "is-currently-executing-environment", 1, INTEGER, &arg0)) {
void* otherEnv = (void*)(long long)DOToLong(arg0);
if(otherEnv == theEnv) {
return TrueSymbol();
} else {
return FalseSymbol();
}
} else {
PrintError(theEnv, "Target argument isn't an integer or external-address.\n");
return FalseSymbol();
}
}
extern void* ToPointer(void* theEnv) {
DATA_OBJECT arg0;
void* nil = (void*)0;
if(EnvArgCountCheck(theEnv, "to-pointer", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too few or too many arguments provided\n");
return nil;
}
if(EnvArgTypeCheck(theEnv, "to-pointer", 1, INTEGER, &arg0)) {
return (void*)(long long)DOToLong(arg0);
} else if(EnvArgTypeCheck(theEnv, "to-pointer", 1, EXTERNAL_ADDRESS, &arg0)) {
return (void*)GetValue(arg0);
} else {
return nil;
}
}
extern void RunEnvironment(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
if(EnvArgCountCheck(theEnv, "env-run", EXACTLY, 2) == -1) {
PrintError(theEnv,"Too few or too many arguments provided!\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-run", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "Provided pointer address isn't an external address!\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-run", 2, INTEGER, &arg1) == FALSE) {
PrintError(theEnv, "Provided duration is not an integer!\n");
return;
}
long value = (long)DOToLong(arg1);
address = (void*)GetValue(arg0);
if(value > 0L || value == -1) {
SetCurrentEnvironment(address);
EnvRun(address, value);
SetCurrentEnvironment(theEnv);
return;
} else {
PrintError(theEnv, "Provided duration must be greater than zero or -1\n");
return;
}
}
void EnvironmentEval(void* theEnv, DATA_OBJECT_PTR ret) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-eval", EXACTLY, 2) == -1) {
PrintError(theEnv, "env-eval accepts exactly two arguments\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-eval", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-eval", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvEval(address, result, ret);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentBuild(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-build", EXACTLY, 2) == -1) {
PrintError(theEnv, "env-build accepts exactly two arguments\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-build", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-build", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvBuild(address, result);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentAssertString(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-assert-string", EXACTLY, 2) == -1) {
PrintError(theEnv, "Only two arguments are allowed\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-assert-string", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-assert-string", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvAssertString(address, result);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentFacts(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-facts", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-facts\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-facts", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvFacts(address, wdisplay, NULL, -1, -1, -1);
SetCurrentEnvironment(theEnv);
}
void EnvironmentInstances(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-instances", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-instances\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-instances", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvInstances(address, wdisplay, NULL, NULL, 1);
SetCurrentEnvironment(theEnv);
}
void EnvironmentRules(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-rules", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-rules\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-rules", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvListDefrules(address, wdisplay, NULL);
SetCurrentEnvironment(theEnv);
}
void* EnvironmentCreate(void* theEnv) {
/*
* This is really unsafe to call on it's own unless you REALLY know what
* you're doing
*/
void* address;
if(EnvArgCountCheck(theEnv, "env-create", EXACTLY, 0) == -1) {
PrintError(theEnv, "ERROR: env-create takes in no arguments\n");
return (void*)0;
}
address = CreateEnvironment();
SetCurrentEnvironment(theEnv);
return address;
}
#undef werror
#undef wdisplay
#undef wwarning
#undef PrintError
#undef CharBuffer
<commit_msg>Removed the (long long) cast in to-pointer<commit_after>#include "core/EnvironmentOperations.h"
extern "C" {
#include "clips.h"
#include <stdio.h>
}
#define werror (char*)"werror"
#define wdisplay (char*)"wdisplay"
#define wwarning (char*)"wwarning"
#define PrintError(e, msg) EnvPrintRouter(e, werror, (char*) msg)
#define CharBuffer(sz) (char*)calloc(sz, sizeof(char))
extern "C" void EnvironmentDestroy(void* theEnv);
extern "C" void* GetCurrentlyExecutingEnvironment(void* theEnv);
extern "C" void* IsCurrentlyExecutingEnvironment(void* theEnv);
extern "C" void* ToPointer(void* theEnv);
extern "C" void RunEnvironment(void* theEnv);
extern "C" void EnvironmentEval(void* theEnv, DATA_OBJECT_PTR ret);
extern "C" void EnvironmentBuild(void* theEnv);
extern "C" void EnvironmentFacts(void* theEnv);
extern "C" void EnvironmentInstances(void* theEnv);
extern "C" void EnvironmentRules(void* theEnv);
extern "C" void EnvironmentAssertString(void* theEnv);
extern "C" void* EnvironmentCreate(void* theEnv);
void EnvironmentOperationsDefinitions(void* theEnv) {
EnvDefineFunction(theEnv, "env-destroy", 'v',
PTIEF EnvironmentDestroy,
"EnvironmentDestroy");
EnvDefineFunction(theEnv, "get-currently-executing-environment", 'a',
PTIEF GetCurrentlyExecutingEnvironment,
"GetCurrentlyExecutingEnvironment");
EnvDefineFunction(theEnv, "is-currently-executing-environment", 'w',
PTIEF IsCurrentlyExecutingEnvironment,
"IsCurrentlyExecutingEnvironment");
EnvDefineFunction(theEnv, "to-pointer", 'a', PTIEF ToPointer, "ToPointer");
EnvDefineFunction(theEnv, "env-run", 'v', PTIEF RunEnvironment, "RunEnvironment");
EnvDefineFunction(theEnv, "env-eval", 'u', PTIEF EnvironmentEval,
"EnvironmentEval");
EnvDefineFunction(theEnv, "env-build", 'v', PTIEF EnvironmentBuild,
"EnvironmentBuild");
EnvDefineFunction(theEnv, "env-facts", 'v', PTIEF EnvironmentFacts,
"EnvironmentFacts");
EnvDefineFunction(theEnv, "env-instances", 'v', PTIEF EnvironmentInstances,
"EnvironmentInstances");
EnvDefineFunction(theEnv, "env-rules", 'v', PTIEF EnvironmentRules,
"EnvironmentRules");
EnvDefineFunction(theEnv, "env-assert-string", 'v', PTIEF EnvironmentAssertString,
"EnvironmentAssertString");
EnvDefineFunction(theEnv, "env-create", 'a', PTIEF EnvironmentCreate,
"EnvironmentCreate");
}
void EnvironmentDestroy(void* theEnv) {
DATA_OBJECT arg0;
if((EnvArgCountCheck(theEnv, "env-destroy", EXACTLY, 1) == -1)) {
return;
}
if(EnvArgTypeCheck(theEnv, "env-destroy", 1, EXTERNAL_ADDRESS, &arg0)) {
void* targetEnv = (void*)GetValue(arg0);
DestroyEnvironment(targetEnv);
return;
} else if(EnvArgTypeCheck(theEnv, "env-destroy", 1, INTEGER, &arg0)) {
void* targetEnv = (void*)(long long)DOToLong(arg0);
DestroyEnvironment(targetEnv);
return;
} else {
return;
}
}
void* GetCurrentlyExecutingEnvironment(void* theEnv) {
if(EnvArgCountCheck(theEnv, "get-currently-executing-environment", EXACTLY, 0) == -1) {
PrintError(theEnv,
"get-currently-executing-environment does not accept arguments\n");
return (void*)0;
}
return GetCurrentEnvironment();
}
void* IsCurrentlyExecutingEnvironment(void* theEnv) {
DATA_OBJECT arg0;
if((EnvArgCountCheck(theEnv, "is-currently-executing-environment", EXACTLY, 1) == -1)) {
PrintError(theEnv, "Either too many or too few arguments provided\n");
return FalseSymbol();
}
if(EnvArgTypeCheck(theEnv, "is-currently-executing-environment", 1, EXTERNAL_ADDRESS, &arg0)) {
void* otherEnv = (void*)GetValue(arg0);
if(otherEnv == theEnv) {
return TrueSymbol();
} else {
return FalseSymbol();
}
} else if (EnvArgTypeCheck(theEnv, "is-currently-executing-environment", 1, INTEGER, &arg0)) {
void* otherEnv = (void*)(long long)DOToLong(arg0);
if(otherEnv == theEnv) {
return TrueSymbol();
} else {
return FalseSymbol();
}
} else {
PrintError(theEnv, "Target argument isn't an integer or external-address.\n");
return FalseSymbol();
}
}
extern void* ToPointer(void* theEnv) {
DATA_OBJECT arg0;
void* nil = (void*)0;
if(EnvArgCountCheck(theEnv, "to-pointer", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too few or too many arguments provided\n");
return nil;
}
if(EnvArgTypeCheck(theEnv, "to-pointer", 1, INTEGER, &arg0)) {
return (void*)DOToLong(arg0);
} else if(EnvArgTypeCheck(theEnv, "to-pointer", 1, EXTERNAL_ADDRESS, &arg0)) {
return (void*)GetValue(arg0);
} else {
return nil;
}
}
extern void RunEnvironment(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
if(EnvArgCountCheck(theEnv, "env-run", EXACTLY, 2) == -1) {
PrintError(theEnv,"Too few or too many arguments provided!\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-run", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "Provided pointer address isn't an external address!\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-run", 2, INTEGER, &arg1) == FALSE) {
PrintError(theEnv, "Provided duration is not an integer!\n");
return;
}
long value = (long)DOToLong(arg1);
address = (void*)GetValue(arg0);
if(value > 0L || value == -1) {
SetCurrentEnvironment(address);
EnvRun(address, value);
SetCurrentEnvironment(theEnv);
return;
} else {
PrintError(theEnv, "Provided duration must be greater than zero or -1\n");
return;
}
}
void EnvironmentEval(void* theEnv, DATA_OBJECT_PTR ret) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-eval", EXACTLY, 2) == -1) {
PrintError(theEnv, "env-eval accepts exactly two arguments\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-eval", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-eval", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvEval(address, result, ret);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentBuild(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-build", EXACTLY, 2) == -1) {
PrintError(theEnv, "env-build accepts exactly two arguments\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-build", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-build", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvBuild(address, result);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentAssertString(void* theEnv) {
DATA_OBJECT arg0, arg1;
void* address;
char* result;
char* tmp;
if(EnvArgCountCheck(theEnv, "env-assert-string", EXACTLY, 2) == -1) {
PrintError(theEnv, "Only two arguments are allowed\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-assert-string", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "First argument must be an external address\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-assert-string", 2, STRING, &arg1) == FALSE) {
PrintError(theEnv, "Second argument must be a string\n");
return;
}
address = (void*)GetValue(arg0);
tmp = DOToString(arg1);
result = CharBuffer(strlen(tmp) + 1);
sprintf(result, "%s", tmp);
SetCurrentEnvironment(address);
EnvAssertString(address, result);
SetCurrentEnvironment(theEnv);
free(result);
}
void EnvironmentFacts(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-facts", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-facts\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-facts", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvFacts(address, wdisplay, NULL, -1, -1, -1);
SetCurrentEnvironment(theEnv);
}
void EnvironmentInstances(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-instances", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-instances\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-instances", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvInstances(address, wdisplay, NULL, NULL, 1);
SetCurrentEnvironment(theEnv);
}
void EnvironmentRules(void* theEnv) {
DATA_OBJECT arg0;
void* address;
if(EnvArgCountCheck(theEnv, "env-rules", EXACTLY, 1) == -1) {
PrintError(theEnv, "Too many or too few arguments provided to env-rules\n");
return;
}
if(EnvArgTypeCheck(theEnv, "env-rules", 1, EXTERNAL_ADDRESS, &arg0) == FALSE) {
PrintError(theEnv, "The provided argument must be an external address\n");
return;
}
address = (void*)GetValue(arg0);
SetCurrentEnvironment(address);
EnvListDefrules(address, wdisplay, NULL);
SetCurrentEnvironment(theEnv);
}
void* EnvironmentCreate(void* theEnv) {
/*
* This is really unsafe to call on it's own unless you REALLY know what
* you're doing
*/
void* address;
if(EnvArgCountCheck(theEnv, "env-create", EXACTLY, 0) == -1) {
PrintError(theEnv, "ERROR: env-create takes in no arguments\n");
return (void*)0;
}
address = CreateEnvironment();
SetCurrentEnvironment(theEnv);
return address;
}
#undef werror
#undef wdisplay
#undef wwarning
#undef PrintError
#undef CharBuffer
<|endoftext|>
|
<commit_before>#include "MooseInit.h"
#include "MooseTestApp.h"
#include "Moose.h"
#include "AppFactory.h"
// Create a performance log
PerfLog Moose::perf_log("Moose Test");
int main(int argc, char *argv[])
{
// Initialize MPI, solvers and MOOSE
MooseInit init(argc, argv);
std::cout << "Thanks for running moose_test, have a nice day!\n";
// Register this application's MooseApp and any it depends on
MooseTestApp::registerApps();
// This creates dynamic memory that we're responsible for deleting
MooseApp * app = AppFactory::createApp("MooseTestApp", argc, argv);
// Execute the application
app->run();
// Free up the memory we created earlier
delete app;
return 0;
}
<commit_msg>Testing new compile hook #2<commit_after>#include "MooseInit.h"
#include "MooseTestApp.h"
#include "Moose.h"
#include "AppFactory.h"
// Create a performance log
PerfLog Moose::perf_log("Moose Test");
int main(int argc, char *argv[])
{
// Initialize MPI, solvers and MOOSE
MooseInit init(argc, argv);
// Register this application's MooseApp and any it depends on
MooseTestApp::registerApps();
// This creates dynamic memory that we're responsible for deleting
MooseApp * app = AppFactory::createApp("MooseTestApp", argc, argv);
// Execute the application
app->run();
// Free up the memory we created earlier
delete app;
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>fixed lambda arguments<commit_after><|endoftext|>
|
<commit_before><commit_msg>Update BestO.cpp<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <utility>
#include "Bool.hh"
#include "Number.hh"
#include "String.hh"
#include "Table.hh"
using namespace py;
using std::unique_ptr;
//------------------------------------------------------------------------------
namespace {
int tp_init(Table* self, Tuple* args, Dict* kw_args)
{
// No arguments.
static char const* arg_names[] = {nullptr};
Arg::ParseTupleAndKeywords(args, kw_args, "", (char**) arg_names);
self->table_ = unique_ptr<fixfmt::Table>(new fixfmt::Table());
return 0;
}
ref<Object> tp_call(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"index", nullptr};
long index;
Arg::ParseTupleAndKeywords(args, kw_args, "l", arg_names, &index);
long const width = self->table_->get_width();
char buf[width];
self->table_->format(index, buf);
return Unicode::FromStringAndSize(buf, width);
}
ref<Object> add_string(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"str", nullptr};
char* str;
Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str);
self->table_->add_string(std::string(str));
return none_ref();
}
/**
* Template method for adding a column to the table.
*
* 'buf' is a 'bytes' object containing contiguous values of type 'TYPE', e.g.
* 'int' or 'double'. 'PYFMT" is a Python object that wraps a formatter for
* 'TYPE' values.
*/
template<typename TYPE, typename PYFMT>
ref<Object> add_column(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"buf", "format", nullptr};
const TYPE* buf;
int buf_len;
PYFMT* format;
Arg::ParseTupleAndKeywords(
args, kw_args, "y#O!", arg_names,
&buf, &buf_len, &PYFMT::type_, &format);
using Column = fixfmt::ColumnImpl<TYPE, typename PYFMT::Formatter>;
unique_ptr<fixfmt::Column> col(new Column(buf, *format->fmt_));
self->table_->add_column(std::move(col));
return none_ref();
}
/**
* Column of Python object pointers, with an object first converted with 'str()'
* and then formatted as a string.
*/
class StrObjectColumn
: public fixfmt::Column
{
public:
StrObjectColumn(Object** values, fixfmt::String format)
: values_(values),
format_(std::move(format))
{
}
virtual ~StrObjectColumn() override {}
virtual size_t get_width() const override { return format_.get_width(); }
virtual void format(size_t const index, char* const buf) const override
{
// Convert (or cast) to string.
auto str = values_[index]->Str();
// Format the string.
format_.format(str->as_utf8_string(), buf);
}
private:
Object** const values_;
fixfmt::String const format_;
};
ref<Object> add_str_object_column(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"buf", "format", nullptr};
Object** buf;
int buf_len;
String* format;
Arg::ParseTupleAndKeywords(
args, kw_args, "y#O!", arg_names,
&buf, &buf_len, &String::type_, &format);
unique_ptr<fixfmt::Column> col(new StrObjectColumn(buf, *format->fmt_));
self->table_->add_column(std::move(col));
return none_ref();
}
PyMethodDef const tp_methods[] = {
{"add_string",
(PyCFunction) wrap_method<Table, add_string>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_bool",
(PyCFunction) wrap_method<Table, add_column<bool, Bool>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int8",
(PyCFunction) wrap_method<Table, add_column<char, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int16",
(PyCFunction) wrap_method<Table, add_column<short, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int32",
(PyCFunction) wrap_method<Table, add_column<int, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int64",
(PyCFunction) wrap_method<Table, add_column<long, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_float32",
(PyCFunction) wrap_method<Table, add_column<float, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_float64",
(PyCFunction) wrap_method<Table, add_column<double, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_str_object",
(PyCFunction) wrap_method<Table, add_str_object_column>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
METHODDEF_END
};
} // anonymous namespace
Type Table::type_ = PyTypeObject{
PyVarObject_HEAD_INIT(nullptr, 0)
"fixfmt.Table", // tp_name
sizeof(Table), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
nullptr, // tp_print
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_reserved
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
(ternaryfunc) wrap_method<Table, tp_call>,
// tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE, // tp_flags
nullptr, // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
(PyMethodDef*) tp_methods, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
(initproc) tp_init, // tp_init
nullptr, // tp_alloc
PyType_GenericNew, // tp_new
};
<commit_msg>Simplify.<commit_after>#include <iostream>
#include <string>
#include <utility>
#include "Bool.hh"
#include "Number.hh"
#include "String.hh"
#include "Table.hh"
using namespace py;
using std::unique_ptr;
//------------------------------------------------------------------------------
namespace {
int tp_init(Table* self, Tuple* args, Dict* kw_args)
{
// No arguments.
static char const* arg_names[] = {nullptr};
Arg::ParseTupleAndKeywords(args, kw_args, "", (char**) arg_names);
self->table_ = unique_ptr<fixfmt::Table>(new fixfmt::Table());
return 0;
}
ref<Object> tp_call(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"index", nullptr};
long index;
Arg::ParseTupleAndKeywords(args, kw_args, "l", arg_names, &index);
long const width = self->table_->get_width();
char buf[width];
self->table_->format(index, buf);
return Unicode::FromStringAndSize(buf, width);
}
ref<Object> add_string(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"str", nullptr};
char* str;
Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str);
self->table_->add_string(std::string(str));
return none_ref();
}
/**
* Template method for adding a column to the table.
*
* 'buf' is a 'bytes' object containing contiguous values of type 'TYPE', e.g.
* 'int' or 'double'. 'PYFMT" is a Python object that wraps a formatter for
* 'TYPE' values.
*/
template<typename TYPE, typename PYFMT>
ref<Object> add_column(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"buf", "format", nullptr};
const TYPE* buf;
int buf_len;
PYFMT* format;
Arg::ParseTupleAndKeywords(
args, kw_args, "y#O!", arg_names,
&buf, &buf_len, &PYFMT::type_, &format);
using ColumnUptr = unique_ptr<fixfmt::Column>;
using Column = fixfmt::ColumnImpl<TYPE, typename PYFMT::Formatter>;
self->table_->add_column(ColumnUptr(new Column(buf, *format->fmt_)));
return none_ref();
}
/**
* Column of Python object pointers, with an object first converted with 'str()'
* and then formatted as a string.
*/
class StrObjectColumn
: public fixfmt::Column
{
public:
StrObjectColumn(Object** values, fixfmt::String format)
: values_(values),
format_(std::move(format))
{
}
virtual ~StrObjectColumn() override {}
virtual size_t get_width() const override { return format_.get_width(); }
virtual void format(size_t const index, char* const buf) const override
{
// Convert (or cast) to string.
auto str = values_[index]->Str();
// Format the string.
format_.format(str->as_utf8_string(), buf);
}
private:
Object** const values_;
fixfmt::String const format_;
};
ref<Object> add_str_object_column(Table* self, Tuple* args, Dict* kw_args)
{
static char const* arg_names[] = {"buf", "format", nullptr};
Object** buf;
int buf_len;
String* format;
Arg::ParseTupleAndKeywords(
args, kw_args, "y#O!", arg_names,
&buf, &buf_len, &String::type_, &format);
using ColumnUptr = unique_ptr<fixfmt::Column>;
self->table_->add_column(ColumnUptr(new StrObjectColumn(buf, *format->fmt_)));
return none_ref();
}
PyMethodDef const tp_methods[] = {
{"add_string",
(PyCFunction) wrap_method<Table, add_string>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_bool",
(PyCFunction) wrap_method<Table, add_column<bool, Bool>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int8",
(PyCFunction) wrap_method<Table, add_column<char, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int16",
(PyCFunction) wrap_method<Table, add_column<short, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int32",
(PyCFunction) wrap_method<Table, add_column<int, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_int64",
(PyCFunction) wrap_method<Table, add_column<long, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_float32",
(PyCFunction) wrap_method<Table, add_column<float, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_float64",
(PyCFunction) wrap_method<Table, add_column<double, Number>>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
{"add_str_object",
(PyCFunction) wrap_method<Table, add_str_object_column>,
METH_VARARGS | METH_KEYWORDS,
nullptr},
METHODDEF_END
};
} // anonymous namespace
Type Table::type_ = PyTypeObject{
PyVarObject_HEAD_INIT(nullptr, 0)
"fixfmt.Table", // tp_name
sizeof(Table), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
nullptr, // tp_print
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_reserved
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
(ternaryfunc) wrap_method<Table, tp_call>,
// tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE, // tp_flags
nullptr, // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
(PyMethodDef*) tp_methods, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
(initproc) tp_init, // tp_init
nullptr, // tp_alloc
PyType_GenericNew, // tp_new
};
<|endoftext|>
|
<commit_before>#include "EventOutputQueue.hpp"
#include "ConsumerToConsumer.hpp"
#include "KeyboardRepeat.hpp"
#include "ListHookedKeyboard.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
void
ConsumerToConsumer::initialize(void)
{
toKeys_ = new Vector_PairConsumerKeyFlags();
}
void
ConsumerToConsumer::terminate(void)
{
if (toKeys_) {
delete toKeys_;
toKeys_ = NULL;
}
}
void
ConsumerToConsumer::add(ConsumerKeyCode newval)
{
if (! toKeys_) return;
switch (index_) {
case 0:
fromKey_.key = newval;
break;
default:
toKeys_->push_back(PairConsumerKeyFlags(newval));
break;
}
++index_;
}
void
ConsumerToConsumer::add(Flags newval)
{
if (! toKeys_) return;
switch (index_) {
case 0:
IOLOG_ERROR("Invalid ConsumerToConsumer::add\n");
break;
case 1:
fromKey_.flags = newval;
break;
default:
toKeys_->back().flags = newval;
break;
}
}
bool
ConsumerToConsumer::remap(RemapConsumerParams& remapParams)
{
if (! toKeys_) return false;
// ------------------------------------------------------------
// NumLock Hack
// If we change NumLock key, we need to call IOHIKeyboard::setNumLock(false).
// Unless call setNumLock, internal NumLock status of IOHIKeyboard is still active.
// And NumLock retains working status.
if (fromKey_.key == ConsumerKeyCode::NUMLOCK) {
bool tonumlock = false;
for (size_t i = 0; i < toKeys_->size(); ++i) {
if ((*toKeys_)[i].key == ConsumerKeyCode::NUMLOCK) {
tonumlock = true;
}
}
if (! tonumlock) {
HookedKeyboard* hk = ListHookedKeyboard::instance().get();
if (hk) {
IOHIKeyboard* kbd = hk->get();
if (kbd) {
if (kbd->numLock()) {
kbd->setNumLock(false);
}
}
}
}
}
// ------------------------------------------------------------
if (remapParams.isremapped) return false;
if (! fromkeychecker_.isFromKey(remapParams.params.eventType, remapParams.params.key, FlagStatus::makeFlags(), fromKey_.key, fromKey_.flags)) return false;
remapParams.isremapped = true;
// ----------------------------------------
FlagStatus::temporary_decrease(fromKey_.flags);
KeyboardRepeat::cancel();
switch (toKeys_->size()) {
case 0:
break;
case 1:
{
FlagStatus::temporary_increase((*toKeys_)[0].flags);
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(remapParams.params.eventType,
FlagStatus::makeFlags(),
(*toKeys_)[0].key,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
KeyboardRepeat::set(params);
EventOutputQueue::FireConsumer::fire(params);
break;
}
default:
if (remapParams.params.eventType == EventType::DOWN) {
for (size_t i = 0; i < toKeys_->size(); ++i) {
FlagStatus::temporary_increase((*toKeys_)[i].flags);
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(EventType::DOWN,
FlagStatus::makeFlags(),
(*toKeys_)[i].key,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
EventOutputQueue::FireConsumer::fire(params);
params.eventType = EventType::UP;
EventOutputQueue::FireConsumer::fire(params);
KeyboardRepeat::primitive_add(EventType::DOWN, params.flags, params.key);
KeyboardRepeat::primitive_add(EventType::UP, params.flags, params.key);
FlagStatus::temporary_decrease((*toKeys_)[i].flags);
}
KeyboardRepeat::primitive_start();
}
break;
}
return true;
}
bool
ConsumerToConsumer::call_remap_with_VK_PSEUDO_KEY(EventType eventType)
{
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(eventType,
FlagStatus::makeFlags(),
ConsumerKeyCode::VK_PSEUDO_KEY,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
RemapConsumerParams rp(params);
return remap(rp);
}
}
}
<commit_msg>update ConsumerToConsumer around ListHooked*<commit_after>#include "EventOutputQueue.hpp"
#include "ConsumerToConsumer.hpp"
#include "KeyboardRepeat.hpp"
#include "ListHookedKeyboard.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
void
ConsumerToConsumer::initialize(void)
{
toKeys_ = new Vector_PairConsumerKeyFlags();
}
void
ConsumerToConsumer::terminate(void)
{
if (toKeys_) {
delete toKeys_;
toKeys_ = NULL;
}
}
void
ConsumerToConsumer::add(ConsumerKeyCode newval)
{
if (! toKeys_) return;
switch (index_) {
case 0:
fromKey_.key = newval;
break;
default:
toKeys_->push_back(PairConsumerKeyFlags(newval));
break;
}
++index_;
}
void
ConsumerToConsumer::add(Flags newval)
{
if (! toKeys_) return;
switch (index_) {
case 0:
IOLOG_ERROR("Invalid ConsumerToConsumer::add\n");
break;
case 1:
fromKey_.flags = newval;
break;
default:
toKeys_->back().flags = newval;
break;
}
}
bool
ConsumerToConsumer::remap(RemapConsumerParams& remapParams)
{
if (! toKeys_) return false;
// ------------------------------------------------------------
// NumLock Hack
// If we change NumLock key, we need to call IOHIKeyboard::setNumLock(false).
// Unless call setNumLock, internal NumLock status of IOHIKeyboard is still active.
// And NumLock retains working status.
if (fromKey_.key == ConsumerKeyCode::NUMLOCK) {
bool tonumlock = false;
for (size_t i = 0; i < toKeys_->size(); ++i) {
if ((*toKeys_)[i].key == ConsumerKeyCode::NUMLOCK) {
tonumlock = true;
}
}
if (! tonumlock) {
ListHookedKeyboard::Item* hk = ListHookedKeyboard::instance().get();
if (hk) {
IOHIKeyboard* kbd = hk->get();
if (kbd) {
if (kbd->numLock()) {
kbd->setNumLock(false);
}
}
}
}
}
// ------------------------------------------------------------
if (remapParams.isremapped) return false;
if (! fromkeychecker_.isFromKey(remapParams.params.eventType, remapParams.params.key, FlagStatus::makeFlags(), fromKey_.key, fromKey_.flags)) return false;
remapParams.isremapped = true;
// ----------------------------------------
FlagStatus::temporary_decrease(fromKey_.flags);
KeyboardRepeat::cancel();
switch (toKeys_->size()) {
case 0:
break;
case 1:
{
FlagStatus::temporary_increase((*toKeys_)[0].flags);
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(remapParams.params.eventType,
FlagStatus::makeFlags(),
(*toKeys_)[0].key,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
KeyboardRepeat::set(params);
EventOutputQueue::FireConsumer::fire(params);
break;
}
default:
if (remapParams.params.eventType == EventType::DOWN) {
for (size_t i = 0; i < toKeys_->size(); ++i) {
FlagStatus::temporary_increase((*toKeys_)[i].flags);
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(EventType::DOWN,
FlagStatus::makeFlags(),
(*toKeys_)[i].key,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
EventOutputQueue::FireConsumer::fire(params);
params.eventType = EventType::UP;
EventOutputQueue::FireConsumer::fire(params);
KeyboardRepeat::primitive_add(EventType::DOWN, params.flags, params.key);
KeyboardRepeat::primitive_add(EventType::UP, params.flags, params.key);
FlagStatus::temporary_decrease((*toKeys_)[i].flags);
}
KeyboardRepeat::primitive_start();
}
break;
}
return true;
}
bool
ConsumerToConsumer::call_remap_with_VK_PSEUDO_KEY(EventType eventType)
{
Params_KeyboardSpecialEventCallback::auto_ptr ptr(Params_KeyboardSpecialEventCallback::alloc(eventType,
FlagStatus::makeFlags(),
ConsumerKeyCode::VK_PSEUDO_KEY,
false));
if (! ptr) return false;
Params_KeyboardSpecialEventCallback& params = *ptr;
RemapConsumerParams rp(params);
return remap(rp);
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Add a comment.<commit_after><|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (foldComment && (style == SCE_C_COMMENTLINE)) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelCurrent++;
} else if (chNext2 == '}') {
levelCurrent--;
}
}
}
if (style == SCE_C_PREPROCESSOR) {
if (ch == '#') {
unsigned int j=i+1;
while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (styler.Match(j, "region")) {
levelCurrent++;
} else if (styler.Match(j, "endregion")) {
levelCurrent--;
}
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<commit_msg>Fold #if as well as #region but require fold.preprocessor property to be set to allow folding preprocessor directives.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (foldComment && (style == SCE_C_COMMENTLINE)) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelCurrent++;
} else if (chNext2 == '}') {
levelCurrent--;
}
}
}
if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
if (ch == '#') {
unsigned int j=i+1;
while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (styler.Match(j, "region") || styler.Match(j, "if")) {
levelCurrent++;
} else if (styler.Match(j, "end")) {
levelCurrent--;
}
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<|endoftext|>
|
<commit_before>/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Ensure that Python.h is included before any other header.
#include "common.h"
#include "immutability_tracer.h"
#include "python_util.h"
DEFINE_int32(
max_expression_lines,
10000,
"maximum number of Python lines to allow in a single expression");
namespace devtools {
namespace cdbg {
PyTypeObject ImmutabilityTracer::python_type_ =
DefaultTypeDefinition(CDBG_SCOPED_NAME("__ImmutabilityTracer"));
// Whitelisted C functions that we consider immutable. Some of these functions
// call Python code (like "repr"), but we can enforce immutability of these
// recursive calls.
static const char* kWhitelistedCFunctions[] = {
"abs",
"divmod",
"all",
"enumerate",
"int",
"ord",
"str",
"any",
"isinstance",
"pow",
"sum",
"issubclass",
"super",
"bin",
"iter",
"tuple",
"bool",
"filter",
"len",
"range",
"type",
"bytearray",
"float",
"list",
"unichr",
"format",
"locals"
"reduce",
"unicode",
"chr",
"frozenset",
"long",
"vars",
"getattr",
"map",
"repr",
"xrange",
"cmp",
"globals",
"max",
"reversed",
"zip",
"hasattr",
"round",
"complex",
"hash",
"min",
"set",
"apply",
"next",
"dict",
"hex",
"object",
"slice",
"coerce",
"dir",
"id",
"oct",
"sorted"
};
static const char* kBlacklistedCodeObjectNames[] = {
"__setattr__",
"__delattr__",
"__del__",
"__new__",
"__set__",
"__delete__",
"__call__",
"__setitem__",
"__delitem__",
"__setslice__",
"__delslice__",
};
ImmutabilityTracer::ImmutabilityTracer()
: self_(nullptr),
thread_state_(nullptr),
original_thread_state_tracing_(0),
line_count_(0),
mutable_code_detected_(false) {
}
ImmutabilityTracer::~ImmutabilityTracer() {
DCHECK(thread_state_ == nullptr);
}
void ImmutabilityTracer::Start(PyObject* self) {
self_ = self;
DCHECK(self_);
thread_state_ = PyThreadState_GET();
DCHECK(thread_state_);
original_thread_state_tracing_ = thread_state_->tracing;
// See "original_thread_state_tracing_" comment for explanation.
thread_state_->tracing = 0;
// We need to enable both "PyEval_SetTrace" and "PyEval_SetProfile". Enabling
// just the former will skip over "PyTrace_C_CALL" notification.
PyEval_SetTrace(OnTraceCallback, self_);
PyEval_SetProfile(OnTraceCallback, self_);
}
void ImmutabilityTracer::Stop() {
if (thread_state_ != nullptr) {
DCHECK_EQ(thread_state_, PyThreadState_GET());
PyEval_SetTrace(nullptr, nullptr);
PyEval_SetProfile(nullptr, nullptr);
// See "original_thread_state_tracing_" comment for explanation.
thread_state_->tracing = original_thread_state_tracing_;
thread_state_ = nullptr;
}
}
int ImmutabilityTracer::OnTraceCallbackInternal(
PyFrameObject* frame,
int what,
PyObject* arg) {
switch (what) {
case PyTrace_CALL:
VerifyCodeObject(ScopedPyCodeObject::NewReference(frame->f_code));
break;
case PyTrace_EXCEPTION:
break;
case PyTrace_LINE:
++line_count_;
ProcessCodeLine(frame->f_code, frame->f_lineno);
break;
case PyTrace_RETURN:
break;
case PyTrace_C_CALL:
++line_count_;
ProcessCCall(arg);
break;
case PyTrace_C_EXCEPTION:
break;
case PyTrace_C_RETURN:
break;
}
if (line_count_ > FLAGS_max_expression_lines) {
LOG(INFO) << "Expression evaluation exceeded quota";
mutable_code_detected_ = true;
}
if (mutable_code_detected_) {
SetMutableCodeException();
return -1;
}
return 0;
}
void ImmutabilityTracer::VerifyCodeObject(ScopedPyCodeObject code_object) {
if (code_object == nullptr) {
return;
}
if (verified_code_objects_.count(code_object) != 0) {
return;
}
// Try to block expressions like "x.__setattr__('a', 1)". Python interpreter
// doesn't generate any trace callback for calls to built-in primitives like
// "__setattr__". Our best effort is to enumerate over all names in the code
// object and block ones with names like "__setprop__". The user can still
// bypass it, so this is just best effort.
PyObject* names = code_object.get()->co_names;
if ((names == nullptr) || !PyTuple_CheckExact(names)) {
LOG(WARNING) << "Corrupted code object: co_names is not a valid tuple";
mutable_code_detected_ = true;
return;
}
int count = PyTuple_GET_SIZE(names);
for (int i = 0; i != count; ++i) {
const char* name = PyString_AsString(PyTuple_GET_ITEM(names, i));
if (name == nullptr) {
LOG(WARNING) << "Corrupted code object: name " << i << " is not a string";
mutable_code_detected_ = true;
return;
}
for (int j = 0; j != arraysize(kBlacklistedCodeObjectNames); ++j) {
if (!strcmp(kBlacklistedCodeObjectNames[j], name)) {
mutable_code_detected_ = true;
return;
}
}
}
verified_code_objects_.insert(code_object);
}
void ImmutabilityTracer::ProcessCodeLine(
PyCodeObject* code_object,
int line_number) {
int size = PyString_Size(code_object->co_code);
const uint8* opcodes =
reinterpret_cast<uint8*>(PyString_AsString(code_object->co_code));
DCHECK(opcodes != nullptr);
// Find all the code ranges mapping to the current line.
int start_offset = -1;
CodeObjectLinesEnumerator enumerator(code_object);
do {
if (start_offset != -1) {
ProcessCodeRange(
opcodes + start_offset,
enumerator.offset() - start_offset);
start_offset = -1;
}
if (line_number == enumerator.line_number()) {
start_offset = enumerator.offset();
}
} while (enumerator.Next());
if (start_offset != -1) {
ProcessCodeRange(opcodes + start_offset, size - start_offset);
}
}
void ImmutabilityTracer::ProcessCodeRange(const uint8* opcodes, int size) {
const uint8* end = opcodes + size;
while (opcodes < end) {
// Read opcode.
const uint8 opcode = *opcodes;
++opcodes;
if (HAS_ARG(opcode)) {
DCHECK_LE(opcodes + 2, end);
opcodes += 2;
// Opcode argument is:
// (static_cast<uint16>(opcodes[1]) << 8) | opcodes[0];
// and can extend to 32 bit if EXTENDED_ARG is used.
}
// Notes:
// * We allow changing local variables (i.e. STORE_FAST). Expression
// evaluation doesn't let changing local variables of the top frame
// because we use "Py_eval_input" when compiling the expression. Methods
// invoked by an expression can freely change local variables as it
// doesn't change the state of the program once the method exits.
// * We let opcodes calling methods like "PyObject_Repr". These will either
// be completely executed inside Python interpreter (with no side
// effects), or call object method (e.g. "__repr__"). In this case the
// tracer will kick in and will verify that the method has no side
// effects.
switch (opcode) {
case NOP:
case LOAD_FAST:
case LOAD_CONST:
case STORE_FAST:
case POP_TOP:
case ROT_TWO:
case ROT_THREE:
case ROT_FOUR:
case DUP_TOP:
case DUP_TOPX:
case UNARY_POSITIVE:
case UNARY_NEGATIVE:
case UNARY_NOT:
case UNARY_CONVERT:
case UNARY_INVERT:
case BINARY_POWER:
case BINARY_MULTIPLY:
case BINARY_DIVIDE:
case BINARY_TRUE_DIVIDE:
case BINARY_FLOOR_DIVIDE:
case BINARY_MODULO:
case BINARY_ADD:
case BINARY_SUBTRACT:
case BINARY_SUBSCR:
case BINARY_LSHIFT:
case BINARY_RSHIFT:
case BINARY_AND:
case BINARY_XOR:
case BINARY_OR:
case INPLACE_POWER:
case INPLACE_MULTIPLY:
case INPLACE_DIVIDE:
case INPLACE_TRUE_DIVIDE:
case INPLACE_FLOOR_DIVIDE:
case INPLACE_MODULO:
case INPLACE_ADD:
case INPLACE_SUBTRACT:
case INPLACE_LSHIFT:
case INPLACE_RSHIFT:
case INPLACE_AND:
case INPLACE_XOR:
case INPLACE_OR:
case SLICE+0:
case SLICE+1:
case SLICE+2:
case SLICE+3:
case LOAD_LOCALS:
case RETURN_VALUE:
case YIELD_VALUE:
case EXEC_STMT:
case UNPACK_SEQUENCE:
case LOAD_NAME:
case LOAD_GLOBAL:
case DELETE_FAST:
case LOAD_DEREF:
case BUILD_TUPLE:
case BUILD_LIST:
case BUILD_SET:
case BUILD_MAP:
case LOAD_ATTR:
case COMPARE_OP:
case JUMP_FORWARD:
case POP_JUMP_IF_FALSE:
case POP_JUMP_IF_TRUE:
case JUMP_IF_FALSE_OR_POP:
case JUMP_IF_TRUE_OR_POP:
case JUMP_ABSOLUTE:
case GET_ITER:
case FOR_ITER:
case BREAK_LOOP:
case CONTINUE_LOOP:
case SETUP_LOOP:
case CALL_FUNCTION:
case CALL_FUNCTION_VAR:
case CALL_FUNCTION_KW:
case CALL_FUNCTION_VAR_KW:
case MAKE_FUNCTION:
case MAKE_CLOSURE:
case BUILD_SLICE:
case POP_BLOCK:
break;
case EXTENDED_ARG:
// Go to the next opcode. The argument is going to be incorrect,
// but we don't really care.
break;
// TODO(vlif): allow changing fields of locally created objects/lists.
case LIST_APPEND:
case SET_ADD:
case STORE_SLICE+0:
case STORE_SLICE+1:
case STORE_SLICE+2:
case STORE_SLICE+3:
case DELETE_SLICE+0:
case DELETE_SLICE+1:
case DELETE_SLICE+2:
case DELETE_SLICE+3:
case STORE_SUBSCR:
case DELETE_SUBSCR:
case STORE_NAME:
case DELETE_NAME:
case STORE_ATTR:
case DELETE_ATTR:
case STORE_DEREF:
case STORE_MAP:
case MAP_ADD:
mutable_code_detected_ = true;
return;
case STORE_GLOBAL:
case DELETE_GLOBAL:
mutable_code_detected_ = true;
return;
case PRINT_EXPR:
case PRINT_ITEM_TO:
case PRINT_ITEM:
case PRINT_NEWLINE_TO:
case PRINT_NEWLINE:
mutable_code_detected_ = true;
return;
case BUILD_CLASS:
mutable_code_detected_ = true;
return;
case IMPORT_NAME:
case IMPORT_STAR:
case IMPORT_FROM:
case SETUP_EXCEPT:
case SETUP_FINALLY:
case WITH_CLEANUP:
mutable_code_detected_ = true;
return;
// TODO(vlif): allow exception handling.
case RAISE_VARARGS:
case END_FINALLY:
case SETUP_WITH:
mutable_code_detected_ = true;
return;
// TODO(vlif): allow closures.
case LOAD_CLOSURE:
mutable_code_detected_ = true;
return;
default:
LOG(WARNING) << "Unknown opcode " << static_cast<uint32>(opcode);
mutable_code_detected_ = true;
return;
}
}
}
void ImmutabilityTracer::ProcessCCall(PyObject* function) {
if (PyCFunction_Check(function)) {
// TODO(vlif): the application code can define its own "str" function
// that will do some evil things. Application can also override builtin
// "str" method. If we want to protect against it, we should load pointers
// to native functions when debugger initializes (which happens before
// any application code had a chance to mess up with Python state). Then
// instead of comparing names, we should look up function pointers. This
// will also improve performance.
auto c_function = reinterpret_cast<PyCFunctionObject*>(function);
const char* name = c_function->m_ml->ml_name;
for (uint32 i = 0; i < arraysize(kWhitelistedCFunctions); ++i) {
if (!strcmp(name, kWhitelistedCFunctions[i])) {
return;
}
}
LOG(INFO) << "Calling native function " << name << " is not allowed";
mutable_code_detected_ = true;
return;
}
LOG(WARNING) << "Unknown argument for C function call";
mutable_code_detected_ = true;
}
void ImmutabilityTracer::SetMutableCodeException() {
// TODO(vlif): use custom type for this exception. This way we can provide
// a more detailed error message.
PyErr_SetString(
PyExc_SystemError,
"Only immutable methods can be called from expressions");
}
} // namespace cdbg
} // namespace devtools
<commit_msg>Add missing comma<commit_after>/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Ensure that Python.h is included before any other header.
#include "common.h"
#include "immutability_tracer.h"
#include "python_util.h"
DEFINE_int32(
max_expression_lines,
10000,
"maximum number of Python lines to allow in a single expression");
namespace devtools {
namespace cdbg {
PyTypeObject ImmutabilityTracer::python_type_ =
DefaultTypeDefinition(CDBG_SCOPED_NAME("__ImmutabilityTracer"));
// Whitelisted C functions that we consider immutable. Some of these functions
// call Python code (like "repr"), but we can enforce immutability of these
// recursive calls.
static const char* kWhitelistedCFunctions[] = {
"abs",
"divmod",
"all",
"enumerate",
"int",
"ord",
"str",
"any",
"isinstance",
"pow",
"sum",
"issubclass",
"super",
"bin",
"iter",
"tuple",
"bool",
"filter",
"len",
"range",
"type",
"bytearray",
"float",
"list",
"unichr",
"format",
"locals",
"reduce",
"unicode",
"chr",
"frozenset",
"long",
"vars",
"getattr",
"map",
"repr",
"xrange",
"cmp",
"globals",
"max",
"reversed",
"zip",
"hasattr",
"round",
"complex",
"hash",
"min",
"set",
"apply",
"next",
"dict",
"hex",
"object",
"slice",
"coerce",
"dir",
"id",
"oct",
"sorted"
};
static const char* kBlacklistedCodeObjectNames[] = {
"__setattr__",
"__delattr__",
"__del__",
"__new__",
"__set__",
"__delete__",
"__call__",
"__setitem__",
"__delitem__",
"__setslice__",
"__delslice__",
};
ImmutabilityTracer::ImmutabilityTracer()
: self_(nullptr),
thread_state_(nullptr),
original_thread_state_tracing_(0),
line_count_(0),
mutable_code_detected_(false) {
}
ImmutabilityTracer::~ImmutabilityTracer() {
DCHECK(thread_state_ == nullptr);
}
void ImmutabilityTracer::Start(PyObject* self) {
self_ = self;
DCHECK(self_);
thread_state_ = PyThreadState_GET();
DCHECK(thread_state_);
original_thread_state_tracing_ = thread_state_->tracing;
// See "original_thread_state_tracing_" comment for explanation.
thread_state_->tracing = 0;
// We need to enable both "PyEval_SetTrace" and "PyEval_SetProfile". Enabling
// just the former will skip over "PyTrace_C_CALL" notification.
PyEval_SetTrace(OnTraceCallback, self_);
PyEval_SetProfile(OnTraceCallback, self_);
}
void ImmutabilityTracer::Stop() {
if (thread_state_ != nullptr) {
DCHECK_EQ(thread_state_, PyThreadState_GET());
PyEval_SetTrace(nullptr, nullptr);
PyEval_SetProfile(nullptr, nullptr);
// See "original_thread_state_tracing_" comment for explanation.
thread_state_->tracing = original_thread_state_tracing_;
thread_state_ = nullptr;
}
}
int ImmutabilityTracer::OnTraceCallbackInternal(
PyFrameObject* frame,
int what,
PyObject* arg) {
switch (what) {
case PyTrace_CALL:
VerifyCodeObject(ScopedPyCodeObject::NewReference(frame->f_code));
break;
case PyTrace_EXCEPTION:
break;
case PyTrace_LINE:
++line_count_;
ProcessCodeLine(frame->f_code, frame->f_lineno);
break;
case PyTrace_RETURN:
break;
case PyTrace_C_CALL:
++line_count_;
ProcessCCall(arg);
break;
case PyTrace_C_EXCEPTION:
break;
case PyTrace_C_RETURN:
break;
}
if (line_count_ > FLAGS_max_expression_lines) {
LOG(INFO) << "Expression evaluation exceeded quota";
mutable_code_detected_ = true;
}
if (mutable_code_detected_) {
SetMutableCodeException();
return -1;
}
return 0;
}
void ImmutabilityTracer::VerifyCodeObject(ScopedPyCodeObject code_object) {
if (code_object == nullptr) {
return;
}
if (verified_code_objects_.count(code_object) != 0) {
return;
}
// Try to block expressions like "x.__setattr__('a', 1)". Python interpreter
// doesn't generate any trace callback for calls to built-in primitives like
// "__setattr__". Our best effort is to enumerate over all names in the code
// object and block ones with names like "__setprop__". The user can still
// bypass it, so this is just best effort.
PyObject* names = code_object.get()->co_names;
if ((names == nullptr) || !PyTuple_CheckExact(names)) {
LOG(WARNING) << "Corrupted code object: co_names is not a valid tuple";
mutable_code_detected_ = true;
return;
}
int count = PyTuple_GET_SIZE(names);
for (int i = 0; i != count; ++i) {
const char* name = PyString_AsString(PyTuple_GET_ITEM(names, i));
if (name == nullptr) {
LOG(WARNING) << "Corrupted code object: name " << i << " is not a string";
mutable_code_detected_ = true;
return;
}
for (int j = 0; j != arraysize(kBlacklistedCodeObjectNames); ++j) {
if (!strcmp(kBlacklistedCodeObjectNames[j], name)) {
mutable_code_detected_ = true;
return;
}
}
}
verified_code_objects_.insert(code_object);
}
void ImmutabilityTracer::ProcessCodeLine(
PyCodeObject* code_object,
int line_number) {
int size = PyString_Size(code_object->co_code);
const uint8* opcodes =
reinterpret_cast<uint8*>(PyString_AsString(code_object->co_code));
DCHECK(opcodes != nullptr);
// Find all the code ranges mapping to the current line.
int start_offset = -1;
CodeObjectLinesEnumerator enumerator(code_object);
do {
if (start_offset != -1) {
ProcessCodeRange(
opcodes + start_offset,
enumerator.offset() - start_offset);
start_offset = -1;
}
if (line_number == enumerator.line_number()) {
start_offset = enumerator.offset();
}
} while (enumerator.Next());
if (start_offset != -1) {
ProcessCodeRange(opcodes + start_offset, size - start_offset);
}
}
void ImmutabilityTracer::ProcessCodeRange(const uint8* opcodes, int size) {
const uint8* end = opcodes + size;
while (opcodes < end) {
// Read opcode.
const uint8 opcode = *opcodes;
++opcodes;
if (HAS_ARG(opcode)) {
DCHECK_LE(opcodes + 2, end);
opcodes += 2;
// Opcode argument is:
// (static_cast<uint16>(opcodes[1]) << 8) | opcodes[0];
// and can extend to 32 bit if EXTENDED_ARG is used.
}
// Notes:
// * We allow changing local variables (i.e. STORE_FAST). Expression
// evaluation doesn't let changing local variables of the top frame
// because we use "Py_eval_input" when compiling the expression. Methods
// invoked by an expression can freely change local variables as it
// doesn't change the state of the program once the method exits.
// * We let opcodes calling methods like "PyObject_Repr". These will either
// be completely executed inside Python interpreter (with no side
// effects), or call object method (e.g. "__repr__"). In this case the
// tracer will kick in and will verify that the method has no side
// effects.
switch (opcode) {
case NOP:
case LOAD_FAST:
case LOAD_CONST:
case STORE_FAST:
case POP_TOP:
case ROT_TWO:
case ROT_THREE:
case ROT_FOUR:
case DUP_TOP:
case DUP_TOPX:
case UNARY_POSITIVE:
case UNARY_NEGATIVE:
case UNARY_NOT:
case UNARY_CONVERT:
case UNARY_INVERT:
case BINARY_POWER:
case BINARY_MULTIPLY:
case BINARY_DIVIDE:
case BINARY_TRUE_DIVIDE:
case BINARY_FLOOR_DIVIDE:
case BINARY_MODULO:
case BINARY_ADD:
case BINARY_SUBTRACT:
case BINARY_SUBSCR:
case BINARY_LSHIFT:
case BINARY_RSHIFT:
case BINARY_AND:
case BINARY_XOR:
case BINARY_OR:
case INPLACE_POWER:
case INPLACE_MULTIPLY:
case INPLACE_DIVIDE:
case INPLACE_TRUE_DIVIDE:
case INPLACE_FLOOR_DIVIDE:
case INPLACE_MODULO:
case INPLACE_ADD:
case INPLACE_SUBTRACT:
case INPLACE_LSHIFT:
case INPLACE_RSHIFT:
case INPLACE_AND:
case INPLACE_XOR:
case INPLACE_OR:
case SLICE+0:
case SLICE+1:
case SLICE+2:
case SLICE+3:
case LOAD_LOCALS:
case RETURN_VALUE:
case YIELD_VALUE:
case EXEC_STMT:
case UNPACK_SEQUENCE:
case LOAD_NAME:
case LOAD_GLOBAL:
case DELETE_FAST:
case LOAD_DEREF:
case BUILD_TUPLE:
case BUILD_LIST:
case BUILD_SET:
case BUILD_MAP:
case LOAD_ATTR:
case COMPARE_OP:
case JUMP_FORWARD:
case POP_JUMP_IF_FALSE:
case POP_JUMP_IF_TRUE:
case JUMP_IF_FALSE_OR_POP:
case JUMP_IF_TRUE_OR_POP:
case JUMP_ABSOLUTE:
case GET_ITER:
case FOR_ITER:
case BREAK_LOOP:
case CONTINUE_LOOP:
case SETUP_LOOP:
case CALL_FUNCTION:
case CALL_FUNCTION_VAR:
case CALL_FUNCTION_KW:
case CALL_FUNCTION_VAR_KW:
case MAKE_FUNCTION:
case MAKE_CLOSURE:
case BUILD_SLICE:
case POP_BLOCK:
break;
case EXTENDED_ARG:
// Go to the next opcode. The argument is going to be incorrect,
// but we don't really care.
break;
// TODO(vlif): allow changing fields of locally created objects/lists.
case LIST_APPEND:
case SET_ADD:
case STORE_SLICE+0:
case STORE_SLICE+1:
case STORE_SLICE+2:
case STORE_SLICE+3:
case DELETE_SLICE+0:
case DELETE_SLICE+1:
case DELETE_SLICE+2:
case DELETE_SLICE+3:
case STORE_SUBSCR:
case DELETE_SUBSCR:
case STORE_NAME:
case DELETE_NAME:
case STORE_ATTR:
case DELETE_ATTR:
case STORE_DEREF:
case STORE_MAP:
case MAP_ADD:
mutable_code_detected_ = true;
return;
case STORE_GLOBAL:
case DELETE_GLOBAL:
mutable_code_detected_ = true;
return;
case PRINT_EXPR:
case PRINT_ITEM_TO:
case PRINT_ITEM:
case PRINT_NEWLINE_TO:
case PRINT_NEWLINE:
mutable_code_detected_ = true;
return;
case BUILD_CLASS:
mutable_code_detected_ = true;
return;
case IMPORT_NAME:
case IMPORT_STAR:
case IMPORT_FROM:
case SETUP_EXCEPT:
case SETUP_FINALLY:
case WITH_CLEANUP:
mutable_code_detected_ = true;
return;
// TODO(vlif): allow exception handling.
case RAISE_VARARGS:
case END_FINALLY:
case SETUP_WITH:
mutable_code_detected_ = true;
return;
// TODO(vlif): allow closures.
case LOAD_CLOSURE:
mutable_code_detected_ = true;
return;
default:
LOG(WARNING) << "Unknown opcode " << static_cast<uint32>(opcode);
mutable_code_detected_ = true;
return;
}
}
}
void ImmutabilityTracer::ProcessCCall(PyObject* function) {
if (PyCFunction_Check(function)) {
// TODO(vlif): the application code can define its own "str" function
// that will do some evil things. Application can also override builtin
// "str" method. If we want to protect against it, we should load pointers
// to native functions when debugger initializes (which happens before
// any application code had a chance to mess up with Python state). Then
// instead of comparing names, we should look up function pointers. This
// will also improve performance.
auto c_function = reinterpret_cast<PyCFunctionObject*>(function);
const char* name = c_function->m_ml->ml_name;
for (uint32 i = 0; i < arraysize(kWhitelistedCFunctions); ++i) {
if (!strcmp(name, kWhitelistedCFunctions[i])) {
return;
}
}
LOG(INFO) << "Calling native function " << name << " is not allowed";
mutable_code_detected_ = true;
return;
}
LOG(WARNING) << "Unknown argument for C function call";
mutable_code_detected_ = true;
}
void ImmutabilityTracer::SetMutableCodeException() {
// TODO(vlif): use custom type for this exception. This way we can provide
// a more detailed error message.
PyErr_SetString(
PyExc_SystemError,
"Only immutable methods can be called from expressions");
}
} // namespace cdbg
} // namespace devtools
<|endoftext|>
|
<commit_before>// LexLua.cxx - lexer for Lua language
// Written by Paul Winwood
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <fcntl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
inline bool isLuaOperator(char ch) {
if (isalnum(ch))
return false;
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' ||ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '^' || ch == '.' )
return true;
return false;
}
static void classifyWordLua(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler)
{
char s[100];
bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
{
s[i] = styler[start + i];
s[i + 1] = '\0';
}
char chAttr = SCE_LUA_IDENTIFIER;
if (wordIsNumber)
chAttr = SCE_LUA_NUMBER;
else
{
if (keywords.InList(s))
{
chAttr = SCE_LUA_WORD;
}
}
styler.ColourTo(end, chAttr);
}
static void ColouriseLuaDoc(unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler)
{
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
styler.GetLine(startPos);
int state = initStyle;
char chPrev = ' ';
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
bool firstChar = true;
int literalString = 0;
styler.StartSegment(startPos);
for (unsigned int i = startPos; i <= lengthDoc; i++)
{
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (styler.IsLeadByte(ch))
{
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_LUA_STRINGEOL)
{
if (ch != '\r' && ch != '\n')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
if (state == SCE_LUA_LITERALSTRING && ch == '[' && chNext == '[')
{
literalString++;
}
else if (state == SCE_LUA_DEFAULT)
{
if (ch == '-' && chNext == '-')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '[' && chNext == '[')
{
state = SCE_LUA_LITERALSTRING;
literalString = 1;
}
else if (ch == '\"')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
styler.ColourTo(i-1, state);
state = SCE_LUA_PREPROCESSOR;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
else if (iswordstart(ch))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_WORD;
}
}
else if (state == SCE_LUA_WORD)
{
if (!iswordchar(ch))
{
classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_LUA_DEFAULT;
if (ch == '[' && chNext == '[')
{
literalString = 1;
state = SCE_LUA_LITERALSTRING;
}
else if (ch == '-' && chNext == '-')
{
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '\"')
{
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
state = SCE_LUA_PREPROCESSOR;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
}
else if (ch == '.' && chNext == '.')
{
classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler);
styler.ColourTo(i, SCE_LUA_OPERATOR);
state = SCE_LUA_DEFAULT;
}
}
else
{
if (state == SCE_LUA_LITERALSTRING)
{
if (ch == ']' && (chPrev == ']') && (--literalString == 0))
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_PREPROCESSOR)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_COMMENTLINE)
{
if (ch == '\r' || ch == '\n')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_STRING)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRINGEOL;
}
else if (ch == '\\')
{
if (chNext == '\"' || chNext == '\\')
{
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (ch == '\"')
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (state == SCE_LUA_CHARACTER)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRINGEOL;
}
else if (ch == '\\')
{
if (chNext == '\'' || chNext == '\\')
{
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (ch == '\'')
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
if (state == SCE_LUA_DEFAULT)
{
if (ch == '-' && chNext == '-')
{
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '\"')
{
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
state = SCE_LUA_PREPROCESSOR;
}
else if (iswordstart(ch))
{
state = SCE_LUA_WORD;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
}
}
chPrev = ch;
firstChar = (ch == '\r' || ch == '\n');
}
styler.ColourTo(lengthDoc - 1, state);
}
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc);
<commit_msg>Philippe added % and : operators and support for initial # line.<commit_after>// LexLua.cxx - lexer for Lua language
// Written by Paul Winwood
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <fcntl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
inline bool isLuaOperator(char ch) {
if (isalnum(ch))
return false;
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' ||ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':')
return true;
return false;
}
static void classifyWordLua(unsigned int start,
unsigned int end,
WordList &keywords,
Accessor &styler)
{
char s[100];
bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
{
s[i] = styler[start + i];
s[i + 1] = '\0';
}
char chAttr = SCE_LUA_IDENTIFIER;
if (wordIsNumber)
chAttr = SCE_LUA_NUMBER;
else
{
if (keywords.InList(s))
{
chAttr = SCE_LUA_WORD;
}
}
styler.ColourTo(end, chAttr);
}
static void ColouriseLuaDoc(unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler)
{
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
styler.GetLine(startPos);
int state = initStyle;
char chPrev = ' ';
char chNext = styler[startPos];
unsigned int lengthDoc = startPos + length;
bool firstChar = true;
int literalString = 0;
styler.StartSegment(startPos);
for (unsigned int i = startPos; i <= lengthDoc; i++)
{
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if (styler.IsLeadByte(ch))
{
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_LUA_STRINGEOL)
{
if (ch != '\r' && ch != '\n')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
if (state == SCE_LUA_LITERALSTRING && ch == '[' && chNext == '[')
{
literalString++;
}
else if (state == SCE_LUA_DEFAULT)
{
if (ch == '-' && chNext == '-')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '[' && chNext == '[')
{
state = SCE_LUA_LITERALSTRING;
literalString = 1;
}
else if (ch == '\"')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
styler.ColourTo(i-1, state);
state = SCE_LUA_PREPROCESSOR;
}
else if (ch == '#' && firstChar) // Should be only on the first line of the file! Cannot be tested here
{
styler.ColourTo(i-1, state);
state = SCE_LUA_COMMENTLINE;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
else if (iswordstart(ch))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_WORD;
}
}
else if (state == SCE_LUA_WORD)
{
if (!iswordchar(ch))
{
classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_LUA_DEFAULT;
if (ch == '[' && chNext == '[')
{
literalString = 1;
state = SCE_LUA_LITERALSTRING;
}
else if (ch == '-' && chNext == '-')
{
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '\"')
{
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
state = SCE_LUA_PREPROCESSOR;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
}
else if (ch == '.' && chNext == '.')
{
classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler);
styler.ColourTo(i, SCE_LUA_OPERATOR);
state = SCE_LUA_DEFAULT;
}
}
else
{
if (state == SCE_LUA_LITERALSTRING)
{
if (ch == ']' && (chPrev == ']') && (--literalString == 0))
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_PREPROCESSOR)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_COMMENTLINE)
{
if (ch == '\r' || ch == '\n')
{
styler.ColourTo(i-1, state);
state = SCE_LUA_DEFAULT;
}
}
else if (state == SCE_LUA_STRING)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRINGEOL;
}
else if (ch == '\\')
{
if (chNext == '\"' || chNext == '\\')
{
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (ch == '\"')
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (state == SCE_LUA_CHARACTER)
{
if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
{
styler.ColourTo(i-1, state);
state = SCE_LUA_STRINGEOL;
}
else if (ch == '\\')
{
if (chNext == '\'' || chNext == '\\')
{
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
else if (ch == '\'')
{
styler.ColourTo(i, state);
state = SCE_LUA_DEFAULT;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
if (state == SCE_LUA_DEFAULT)
{
if (ch == '-' && chNext == '-')
{
state = SCE_LUA_COMMENTLINE;
}
else if (ch == '\"')
{
state = SCE_LUA_STRING;
}
else if (ch == '\'')
{
state = SCE_LUA_CHARACTER;
}
else if (ch == '$' && firstChar)
{
state = SCE_LUA_PREPROCESSOR;
}
else if (iswordstart(ch))
{
state = SCE_LUA_WORD;
}
else if (isLuaOperator(ch))
{
styler.ColourTo(i, SCE_LUA_OPERATOR);
}
}
}
chPrev = ch;
firstChar = (ch == '\r' || ch == '\n');
}
styler.ColourTo(lengthDoc - 1, state);
}
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc);
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexSQL.cxx
** Lexer for SQL, including PL/SQL and SQL*Plus.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalpha(ch) || ch == '_');
}
static inline bool IsADoxygenChar(int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseSQLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords1 = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &kw_pldoc = *keywordlists[2];
WordList &kw_sqlplus = *keywordlists[3];
WordList &kw_user1 = *keywordlists[4];
WordList &kw_user2 = *keywordlists[5];
WordList &kw_user3 = *keywordlists[6];
WordList &kw_user4 = *keywordlists[7];
StyleContext sc(startPos, length, initStyle, styler);
// property sql.backslash.escapes
// Enables backslash as an escape character in SQL.
bool sqlBackslashEscapes = styler.GetPropertyInt("sql.backslash.escapes", 0) != 0;
bool sqlBackticksIdentifier = styler.GetPropertyInt("lexer.sql.backticks.identifier", 0) != 0;
int styleBeforeDCKeyword = SCE_SQL_DEFAULT;
for (; sc.More(); sc.Forward()) {
// Determine if the current state should terminate.
switch (sc.state) {
case SCE_SQL_OPERATOR:
sc.SetState(SCE_SQL_DEFAULT);
break;
case SCE_SQL_NUMBER:
// We stop the number definition on non-numerical non-dot non-eE non-sign char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_IDENTIFIER:
if (!IsAWordChar(sc.ch)) {
int nextState = SCE_SQL_DEFAULT;
char s[1000];
sc.GetCurrentLowered(s, sizeof(s));
if (keywords1.InList(s)) {
sc.ChangeState(SCE_SQL_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_SQL_WORD2);
} else if (kw_sqlplus.InListAbbreviated(s, '~')) {
sc.ChangeState(SCE_SQL_SQLPLUS);
if (strncmp(s, "rem", 3) == 0) {
nextState = SCE_SQL_SQLPLUS_COMMENT;
} else if (strncmp(s, "pro", 3) == 0) {
nextState = SCE_SQL_SQLPLUS_PROMPT;
}
} else if (kw_user1.InList(s)) {
sc.ChangeState(SCE_SQL_USER1);
} else if (kw_user2.InList(s)) {
sc.ChangeState(SCE_SQL_USER2);
} else if (kw_user3.InList(s)) {
sc.ChangeState(SCE_SQL_USER3);
} else if (kw_user4.InList(s)) {
sc.ChangeState(SCE_SQL_USER4);
}
sc.SetState(nextState);
}
break;
case SCE_SQL_QUOTEDIDENTIFIER:
if (sc.ch == 0x60) {
if (sc.chNext == 0x60) {
sc.Forward(); // Ignore it
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
case SCE_SQL_COMMENT:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_COMMENTDOC:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') { // Doxygen support
// Verify that we have the conditions to mark a comment-doc-keyword
if ((IsASpace(sc.chPrev) || sc.chPrev == '*') && (!IsASpace(sc.chNext))) {
styleBeforeDCKeyword = SCE_SQL_COMMENTDOC;
sc.SetState(SCE_SQL_COMMENTDOCKEYWORD);
}
}
break;
case SCE_SQL_COMMENTLINE:
case SCE_SQL_COMMENTLINEDOC:
case SCE_SQL_SQLPLUS_COMMENT:
case SCE_SQL_SQLPLUS_PROMPT:
if (sc.atLineStart) {
sc.SetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_COMMENTDOCKEYWORD:
if ((styleBeforeDCKeyword == SCE_SQL_COMMENTDOC) && sc.Match('*', '/')) {
sc.ChangeState(SCE_SQL_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (!isspace(sc.ch) || !kw_pldoc.InList(s + 1)) {
sc.ChangeState(SCE_SQL_COMMENTDOCKEYWORDERROR);
}
sc.SetState(styleBeforeDCKeyword);
}
break;
case SCE_SQL_CHARACTER:
if (sqlBackslashEscapes && sc.ch == '\\') {
sc.Forward();
} else if (sc.ch == '\'') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
case SCE_SQL_STRING:
if (sc.ch == '\\') {
// Escape sequence
sc.Forward();
} else if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
}
// Determine if a new state should be entered.
if (sc.state == SCE_SQL_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_SQL_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_SQL_IDENTIFIER);
} else if (sc.ch == 0x60 && sqlBackticksIdentifier) {
sc.SetState(SCE_SQL_QUOTEDIDENTIFIER);
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Doxygen doc. style
sc.SetState(SCE_SQL_COMMENTDOC);
} else {
sc.SetState(SCE_SQL_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('-', '-')) {
// MySQL requires a space or control char after --
// http://dev.mysql.com/doc/mysql/en/ansi-diff-comments.html
// Perhaps we should enforce that with proper property:
//~ } else if (sc.Match("-- ")) {
sc.SetState(SCE_SQL_COMMENTLINE);
} else if (sc.ch == '#') {
sc.SetState(SCE_SQL_COMMENTLINEDOC);
} else if (sc.ch == '\'') {
sc.SetState(SCE_SQL_CHARACTER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_SQL_STRING);
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_SQL_OPERATOR);
}
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_SQL_COMMENT ||
style == SCE_SQL_COMMENTDOC ||
style == SCE_SQL_COMMENTDOCKEYWORD ||
style == SCE_SQL_COMMENTDOCKEYWORDERROR;
}
// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment.
static void FoldSQLDoc(unsigned int startPos, int length, int initStyle,
WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
bool foldOnlyBegin = styler.GetPropertyInt("fold.sql.only.begin", 0) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0) {
levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16;
}
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
bool endFound = false;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelNext++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelNext--;
}
}
if (foldComment && (style == SCE_SQL_COMMENTLINE)) {
// MySQL needs -- comments to be followed by space or control char
if ((ch == '-') && (chNext == '-')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
char chNext3 = styler.SafeGetCharAt(i + 3);
if (chNext2 == '{' || chNext3 == '{') {
levelNext++;
} else if (chNext2 == '}' || chNext3 == '}') {
levelNext--;
}
}
}
if (style == SCE_SQL_OPERATOR) {
if (ch == '(') {
levelNext++;
} else if (ch == ')') {
levelNext--;
}
}
// If new keyword (cannot trigger on elseif or nullif, does less tests)
if (style == SCE_SQL_WORD && stylePrev != SCE_SQL_WORD) {
const int MAX_KW_LEN = 6; // Maximum length of folding keywords
char s[MAX_KW_LEN + 2];
unsigned int j = 0;
for (; j < MAX_KW_LEN + 1; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = static_cast<char>(tolower(styler[i + j]));
}
if (j == MAX_KW_LEN + 1) {
// Keyword too long, don't test it
s[0] = '\0';
} else {
s[j] = '\0';
}
if ((!foldOnlyBegin) && (strcmp(s, "if") == 0 || strcmp(s, "loop") == 0)) {
if (endFound) {
// ignore
endFound = false;
} else {
levelNext++;
}
} else if (strcmp(s, "begin") == 0) {
levelNext++;
} else if (strcmp(s, "end") == 0 ||
// DROP TABLE IF EXISTS or CREATE TABLE IF NOT EXISTS
strcmp(s, "exists") == 0) {
endFound = true;
levelNext--;
if (levelNext < SC_FOLDLEVELBASE) {
levelNext = SC_FOLDLEVELBASE;
}
}
}
if (atEOL) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
visibleChars = 0;
endFound = false;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
}
static const char * const sqlWordListDesc[] = {
"Keywords",
"Database Objects",
"PLDoc",
"SQL*Plus",
"User Keywords 1",
"User Keywords 2",
"User Keywords 3",
"User Keywords 4",
0
};
LexerModule lmSQL(SCLEX_SQL, ColouriseSQLDoc, "sql", FoldSQLDoc, sqlWordListDesc);
<commit_msg>Support for SQL Anywhere allowing "ENDIF" to terminate a fold and an option for "EXISTS" not to.<commit_after>// Scintilla source code edit control
/** @file LexSQL.cxx
** Lexer for SQL, including PL/SQL and SQL*Plus.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static inline bool IsAWordChar(int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return (ch < 0x80) && (isalpha(ch) || ch == '_');
}
static inline bool IsADoxygenChar(int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+');
}
static void ColouriseSQLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords1 = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &kw_pldoc = *keywordlists[2];
WordList &kw_sqlplus = *keywordlists[3];
WordList &kw_user1 = *keywordlists[4];
WordList &kw_user2 = *keywordlists[5];
WordList &kw_user3 = *keywordlists[6];
WordList &kw_user4 = *keywordlists[7];
StyleContext sc(startPos, length, initStyle, styler);
// property sql.backslash.escapes
// Enables backslash as an escape character in SQL.
bool sqlBackslashEscapes = styler.GetPropertyInt("sql.backslash.escapes", 0) != 0;
bool sqlBackticksIdentifier = styler.GetPropertyInt("lexer.sql.backticks.identifier", 0) != 0;
int styleBeforeDCKeyword = SCE_SQL_DEFAULT;
for (; sc.More(); sc.Forward()) {
// Determine if the current state should terminate.
switch (sc.state) {
case SCE_SQL_OPERATOR:
sc.SetState(SCE_SQL_DEFAULT);
break;
case SCE_SQL_NUMBER:
// We stop the number definition on non-numerical non-dot non-eE non-sign char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_IDENTIFIER:
if (!IsAWordChar(sc.ch)) {
int nextState = SCE_SQL_DEFAULT;
char s[1000];
sc.GetCurrentLowered(s, sizeof(s));
if (keywords1.InList(s)) {
sc.ChangeState(SCE_SQL_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_SQL_WORD2);
} else if (kw_sqlplus.InListAbbreviated(s, '~')) {
sc.ChangeState(SCE_SQL_SQLPLUS);
if (strncmp(s, "rem", 3) == 0) {
nextState = SCE_SQL_SQLPLUS_COMMENT;
} else if (strncmp(s, "pro", 3) == 0) {
nextState = SCE_SQL_SQLPLUS_PROMPT;
}
} else if (kw_user1.InList(s)) {
sc.ChangeState(SCE_SQL_USER1);
} else if (kw_user2.InList(s)) {
sc.ChangeState(SCE_SQL_USER2);
} else if (kw_user3.InList(s)) {
sc.ChangeState(SCE_SQL_USER3);
} else if (kw_user4.InList(s)) {
sc.ChangeState(SCE_SQL_USER4);
}
sc.SetState(nextState);
}
break;
case SCE_SQL_QUOTEDIDENTIFIER:
if (sc.ch == 0x60) {
if (sc.chNext == 0x60) {
sc.Forward(); // Ignore it
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
case SCE_SQL_COMMENT:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_COMMENTDOC:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') { // Doxygen support
// Verify that we have the conditions to mark a comment-doc-keyword
if ((IsASpace(sc.chPrev) || sc.chPrev == '*') && (!IsASpace(sc.chNext))) {
styleBeforeDCKeyword = SCE_SQL_COMMENTDOC;
sc.SetState(SCE_SQL_COMMENTDOCKEYWORD);
}
}
break;
case SCE_SQL_COMMENTLINE:
case SCE_SQL_COMMENTLINEDOC:
case SCE_SQL_SQLPLUS_COMMENT:
case SCE_SQL_SQLPLUS_PROMPT:
if (sc.atLineStart) {
sc.SetState(SCE_SQL_DEFAULT);
}
break;
case SCE_SQL_COMMENTDOCKEYWORD:
if ((styleBeforeDCKeyword == SCE_SQL_COMMENTDOC) && sc.Match('*', '/')) {
sc.ChangeState(SCE_SQL_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_SQL_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (!isspace(sc.ch) || !kw_pldoc.InList(s + 1)) {
sc.ChangeState(SCE_SQL_COMMENTDOCKEYWORDERROR);
}
sc.SetState(styleBeforeDCKeyword);
}
break;
case SCE_SQL_CHARACTER:
if (sqlBackslashEscapes && sc.ch == '\\') {
sc.Forward();
} else if (sc.ch == '\'') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
case SCE_SQL_STRING:
if (sc.ch == '\\') {
// Escape sequence
sc.Forward();
} else if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_SQL_DEFAULT);
}
}
break;
}
// Determine if a new state should be entered.
if (sc.state == SCE_SQL_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_SQL_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_SQL_IDENTIFIER);
} else if (sc.ch == 0x60 && sqlBackticksIdentifier) {
sc.SetState(SCE_SQL_QUOTEDIDENTIFIER);
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Doxygen doc. style
sc.SetState(SCE_SQL_COMMENTDOC);
} else {
sc.SetState(SCE_SQL_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('-', '-')) {
// MySQL requires a space or control char after --
// http://dev.mysql.com/doc/mysql/en/ansi-diff-comments.html
// Perhaps we should enforce that with proper property:
//~ } else if (sc.Match("-- ")) {
sc.SetState(SCE_SQL_COMMENTLINE);
} else if (sc.ch == '#') {
sc.SetState(SCE_SQL_COMMENTLINEDOC);
} else if (sc.ch == '\'') {
sc.SetState(SCE_SQL_CHARACTER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_SQL_STRING);
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_SQL_OPERATOR);
}
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_SQL_COMMENT ||
style == SCE_SQL_COMMENTDOC ||
style == SCE_SQL_COMMENTDOCKEYWORD ||
style == SCE_SQL_COMMENTDOCKEYWORDERROR;
}
// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment.
static void FoldSQLDoc(unsigned int startPos, int length, int initStyle,
WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
bool foldOnlyBegin = styler.GetPropertyInt("fold.sql.only.begin", 0) != 0;
// property fold.sql.exists
// Enables "EXISTS" to end a fold as is started by "IF" in "DROP TABLE IF EXISTS".
bool foldSqlExists = styler.GetPropertyInt("fold.sql.exists", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0) {
levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16;
}
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
bool endFound = false;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelNext++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelNext--;
}
}
if (foldComment && (style == SCE_SQL_COMMENTLINE)) {
// MySQL needs -- comments to be followed by space or control char
if ((ch == '-') && (chNext == '-')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
char chNext3 = styler.SafeGetCharAt(i + 3);
if (chNext2 == '{' || chNext3 == '{') {
levelNext++;
} else if (chNext2 == '}' || chNext3 == '}') {
levelNext--;
}
}
}
if (style == SCE_SQL_OPERATOR) {
if (ch == '(') {
levelNext++;
} else if (ch == ')') {
levelNext--;
}
}
// If new keyword (cannot trigger on elseif or nullif, does less tests)
if (style == SCE_SQL_WORD && stylePrev != SCE_SQL_WORD) {
const int MAX_KW_LEN = 6; // Maximum length of folding keywords
char s[MAX_KW_LEN + 2];
unsigned int j = 0;
for (; j < MAX_KW_LEN + 1; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = static_cast<char>(tolower(styler[i + j]));
}
if (j == MAX_KW_LEN + 1) {
// Keyword too long, don't test it
s[0] = '\0';
} else {
s[j] = '\0';
}
if ((!foldOnlyBegin) && (strcmp(s, "if") == 0 || strcmp(s, "loop") == 0)) {
if (endFound) {
// ignore
endFound = false;
} else {
levelNext++;
}
} else if (strcmp(s, "begin") == 0) {
levelNext++;
} else if ((strcmp(s, "end") == 0) ||
// // DROP TABLE IF EXISTS or CREATE TABLE IF NOT EXISTS
(foldSqlExists && (strcmp(s, "exists") == 0)) ||
// // SQL Anywhere permits IF ... ELSE ... ENDIF
// // will only be active if "endif" appears in the
// // keyword list.
(strcmp(s, "endif") == 0)) {
endFound = true;
levelNext--;
if (levelNext < SC_FOLDLEVELBASE) {
levelNext = SC_FOLDLEVELBASE;
}
}
}
if (atEOL) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
visibleChars = 0;
endFound = false;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
}
static const char * const sqlWordListDesc[] = {
"Keywords",
"Database Objects",
"PLDoc",
"SQL*Plus",
"User Keywords 1",
"User Keywords 2",
"User Keywords 3",
"User Keywords 4",
0
};
LexerModule lmSQL(SCLEX_SQL, ColouriseSQLDoc, "sql", FoldSQLDoc, sqlWordListDesc);
<|endoftext|>
|
<commit_before>#ifndef AX_MATRIX_H
#define AX_MATRIX_H
#include <array>
#include <iostream>
#include "MatrixExp.hpp"
namespace ax
{
template<std::size_t R, std::size_t C>
class RealMatrix
{
public:
using value_trait = Matrix;
constexpr static std::size_t row = R;//number of row
constexpr static std::size_t col = C;//number of column
/* C x R matrix
C O L U M N s
R ( M_00 M_01 ... M_0C )
O ( M_10 . . )
W ( ... . . )
s ( M_R0 ... M_RC )
*/
public:
// ~~~~~~~~~~ ctor~~~~~~~~~~~~~~~~~~~~~
RealMatrix()
{
for(std::size_t i(0); i<R; ++i)
values_[i].fill(0e0);
}
// to make Identity matrix or something
RealMatrix(const double d)
{
for(std::size_t i(0); i<R; ++i)
for(std::size_t j(0); j<C; ++j)
if(i == j)
values_[i][i] = d;
else
values_[i][j] = 0e0;
}
RealMatrix(const RealMatrix<R, C>& mat)
: values_(mat.values_)
{}
RealMatrix(const std::array<std::array<double, C>, R>& val)
: values_(val)
{}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix(const E& mat)
{
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
}
template<class E,
typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix(const E& mat)
{
if(mat.size_col() != col || mat.size_row() != row)
throw std::invalid_argument("different size dynamic matrix");
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
}
// ~~~~~~~~~~~~~~~~~~~~~ operator ~~~~~~~~~~~~~~~~~~~~~~~~~
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator=(const E& mat)
{
for(std::size_t i(0); i<R; ++i)
for(std::size_t j(0); j<C; ++j)
(*this)(i,j) = mat(i,j);
return *this;
}
template<class E,
typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix& operator=(const E& mat)
{
if(mat.size_col() != col || mat.size_row() != row)
throw std::invalid_argument("different size dynamic matrix");
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
return *this;
}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator+=(const E& mat)
{
*this = MatrixAdd<RealMatrix, E>(*this, mat);
return *this;
}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator-=(const E& mat)
{
*this = MatrixSub<RealMatrix, E>(*this, mat);
return *this;
}
//operator*= can be used in the case of same size matrix
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator*=(const E& mat)
{
*this = MatrixMul<RealMatrix, E>(*this, mat);
return *this;
}
template<class E,
typename std::enable_if<
is_ScalarType<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix& operator*=(const double rhs)
{
*this = MatrixSclMul<RealMatrix>(rhs, *this);
return *this;
}
template<class E,
typename std::enable_if<
is_ScalarType<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix& operator/=(const double rhs)
{
*this = MatrixSclDiv<RealMatrix>(*this, rhs);
return *this;
}
double operator()(const std::size_t i, const std::size_t j) const
{
return values_[i][j];
}
double& operator()(const std::size_t i, const std::size_t j)
{
return values_[i][j];
}
double at(const std::size_t i, const std::size_t j) const
{
return values_.at(i).at(j);
}
double& at(const std::size_t i, const std::size_t j)
{
return values_.at(i).at(j);
}
private:
std::array<std::array<double, C>, R> values_;
};
}
#endif//AX_MATRIX_NxN
<commit_msg>fix *= & /= operator of Matrix<commit_after>#ifndef AX_MATRIX_H
#define AX_MATRIX_H
#include <array>
#include <iostream>
#include "MatrixExp.hpp"
namespace ax
{
template<std::size_t R, std::size_t C>
class RealMatrix
{
public:
using value_trait = Matrix;
constexpr static std::size_t row = R;//number of row
constexpr static std::size_t col = C;//number of column
/* C x R matrix
C O L U M N s
R ( M_00 M_01 ... M_0C )
O ( M_10 . . )
W ( ... . . )
s ( M_R0 ... M_RC )
*/
public:
// ~~~~~~~~~~ ctor~~~~~~~~~~~~~~~~~~~~~
RealMatrix()
{
for(std::size_t i(0); i<R; ++i)
values_[i].fill(0e0);
}
// to make Identity matrix or something
RealMatrix(const double d)
{
for(std::size_t i(0); i<R; ++i)
for(std::size_t j(0); j<C; ++j)
if(i == j)
values_[i][i] = d;
else
values_[i][j] = 0e0;
}
RealMatrix(const RealMatrix<R, C>& mat)
: values_(mat.values_)
{}
RealMatrix(const std::array<std::array<double, C>, R>& val)
: values_(val)
{}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix(const E& mat)
{
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
}
template<class E,
typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix(const E& mat)
{
if(mat.size_col() != col || mat.size_row() != row)
throw std::invalid_argument("different size dynamic matrix");
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
}
// ~~~~~~~~~~~~~~~~~~~~~ operator ~~~~~~~~~~~~~~~~~~~~~~~~~
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator=(const E& mat)
{
for(std::size_t i(0); i<R; ++i)
for(std::size_t j(0); j<C; ++j)
(*this)(i,j) = mat(i,j);
return *this;
}
template<class E,
typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealMatrix& operator=(const E& mat)
{
if(mat.size_col() != col || mat.size_row() != row)
throw std::invalid_argument("different size dynamic matrix");
for(std::size_t i(0); i<row; ++i)
for(std::size_t j(0); j<col; ++j)
values_[i][j] = mat(i, j);
return *this;
}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator+=(const E& mat)
{
*this = MatrixAdd<RealMatrix, E>(*this, mat);
return *this;
}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator-=(const E& mat)
{
*this = MatrixSub<RealMatrix, E>(*this, mat);
return *this;
}
//operator*= can be used in the case of same size matrix
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value&&
is_SameSize<E::col, col>::value&&
is_SameSize<E::row, row>::value
>::type*& = enabler>
RealMatrix& operator*=(const E& mat)
{
*this = MatrixMul<RealMatrix, E>(*this, mat);
return *this;
}
RealMatrix& operator*=(const double rhs)
{
*this = MatrixSclMul<RealMatrix>(rhs, *this);
return *this;
}
RealMatrix& operator/=(const double rhs)
{
*this = MatrixSclDiv<RealMatrix>(*this, rhs);
return *this;
}
double operator()(const std::size_t i, const std::size_t j) const
{
return values_[i][j];
}
double& operator()(const std::size_t i, const std::size_t j)
{
return values_[i][j];
}
double at(const std::size_t i, const std::size_t j) const
{
return values_.at(i).at(j);
}
double& at(const std::size_t i, const std::size_t j)
{
return values_.at(i).at(j);
}
private:
std::array<std::array<double, C>, R> values_;
};
}
#endif//AX_MATRIX_NxN
<|endoftext|>
|
<commit_before>/* @(#)dtkComposerNodeDistributed.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2012 - Nicolas Niclausse, Inria.
* Created: 2012/03/26 09:03:42
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeDistributed.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterVariant.h"
#include <dtkDistributed/dtkDistributedCommunicator>
#include <dtkDistributed/dtkDistributedCommunicatorMpi>
#include <dtkDistributed/dtkDistributedCommunicatorTcp>
#include <dtkLog/dtkLog.h>
// /////////////////////////////////////////////////////////////////
// Communicator Init
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorInitPrivate
{
public:
dtkComposerTransmitterEmitter<dtkDistributedCommunicatorMpi> emitter;
public:
dtkDistributedCommunicatorMpi *communicator;
};
dtkComposerNodeCommunicatorInit::dtkComposerNodeCommunicatorInit(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorInitPrivate)
{
d->communicator = NULL;
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorInit::~dtkComposerNodeCommunicatorInit(void)
{
if (d->communicator)
delete d->communicator;
d->communicator = NULL;
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorInit::run(void)
{
if (!d->communicator) {
d->communicator = new dtkDistributedCommunicatorMpi;
d->emitter.setData(d->communicator);
}
if (!d->communicator->initialized())
d->communicator->initialize();
}
// /////////////////////////////////////////////////////////////////
// Communicator Uninitialize
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorUninitializePrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver;
dtkComposerTransmitterVariant receiver_fake;
};
dtkComposerNodeCommunicatorUninitialize::dtkComposerNodeCommunicatorUninitialize(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorUninitializePrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
this->appendReceiver(&(d->receiver_fake));
}
dtkComposerNodeCommunicatorUninitialize::~dtkComposerNodeCommunicatorUninitialize(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorUninitialize::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicator *communicator = d->receiver.data();
if (communicator) {
communicator->uninitialize();
} else {
dtkError() << "Input communicator not valid.";
return;
}
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
// /////////////////////////////////////////////////////////////////
// Communicator Rank
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorRankPrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver;
dtkComposerTransmitterEmitter<qlonglong> emitter;
public:
qlonglong rank;
};
dtkComposerNodeCommunicatorRank::dtkComposerNodeCommunicatorRank(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorRankPrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
d->rank = -1;
d->emitter.setData(&d->rank);
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorRank::~dtkComposerNodeCommunicatorRank(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorRank::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicator *communicator = d->receiver.data();
if (!communicator) {
d->rank = -1;
dtkError() << "Input communicator not valid.";
return;
}
d->rank = communicator->rank();
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
d->rank = 0;
}
}
// /////////////////////////////////////////////////////////////////
// Communicator Size
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorSizePrivate
{
public:
dtkComposerTransmitterEmitter<qlonglong> emitter;
dtkComposerTransmitterReceiver<dtkDistributedCommunicatorMpi> receiver;
public:
qlonglong size;
};
dtkComposerNodeCommunicatorSize::dtkComposerNodeCommunicatorSize(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorSizePrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
d->size = 0;
d->emitter.setData(&d->size);
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorSize::~dtkComposerNodeCommunicatorSize(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorSize::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicatorMpi *communicator = d->receiver.data();
if (!communicator) {
d->size = 0;
dtkError() << "Input communicator not valid.";
return;
}
d->size = communicator->size();
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
d->size = 0;
}
}
// /////////////////////////////////////////////////////////////////
// Send Variant
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorSendPrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver_comm;
dtkComposerTransmitterVariant receiver_data;
dtkComposerTransmitterReceiver<qlonglong> receiver_target;
};
dtkComposerNodeCommunicatorSend::dtkComposerNodeCommunicatorSend(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorSendPrivate)
{
d->receiver_comm.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver_comm));
this->appendReceiver(&(d->receiver_data));
this->appendReceiver(&(d->receiver_target));
}
dtkComposerNodeCommunicatorSend::~dtkComposerNodeCommunicatorSend(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorSend::run(void)
{
if (!d->receiver_data.isEmpty() && !d->receiver_comm.isEmpty() && !d->receiver_target.isEmpty() ) {
QByteArray array = d->receiver_data.dataToByteArray();
dtkTrace() << "Got data as byte array to be sent" << array.size();
dtkDistributedCommunicator *communicator = d->receiver_comm.data();
if (!communicator) {
dtkError() << "Input communicator not valid.";
return;
}
communicator->send(array, *d->receiver_target.data(), 0);
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
// /////////////////////////////////////////////////////////////////
// Receive Variant
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorReceivePrivate
{
public:
dtkComposerTransmitterVariant emitter;
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver_comm;
dtkComposerTransmitterReceiver<qlonglong> receiver_source;
};
dtkComposerNodeCommunicatorReceive::dtkComposerNodeCommunicatorReceive(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorReceivePrivate)
{
d->receiver_comm.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver_comm));
this->appendReceiver(&(d->receiver_source));
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorReceive::~dtkComposerNodeCommunicatorReceive(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorReceive::run(void)
{
if (!d->receiver_source.isEmpty() && !d->receiver_comm.isEmpty()) {
qlonglong source = *d->receiver_source.data();
dtkDistributedCommunicator *communicator = d->receiver_comm.data();
if (!communicator) {
dtkError() << "Input communicator not valid.";
return;
}
if (dtkDistributedCommunicatorTcp *tcp = dynamic_cast<dtkDistributedCommunicatorTcp *>(communicator)) {
dtkError() << "TCP communicator. Parse message from socket";
tcp->socket()->blockSignals(true); // needed ?
if (!tcp->socket()->waitForReadyRead(300000)) {
dtkWarn() << "Data not ready in receive for rank " << source;
} else {
dtkDistributedMessage *msg = tcp->socket()->parseRequest();
d->emitter.setTwinned(false);
d->emitter.setDataFrom(msg->content());
d->emitter.setTwinned(true);
delete msg;
}
tcp->socket()->blockSignals(false); // needed ?
} else {
dtkAbstractData *data = NULL;
communicator->receive(data, source, 0);
if (data)
d->emitter.setData(data);
else
d->emitter.clearData();
}
} else {
d->emitter.clearData();
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
<commit_msg>fix loglevel<commit_after>/* @(#)dtkComposerNodeDistributed.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2012 - Nicolas Niclausse, Inria.
* Created: 2012/03/26 09:03:42
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeDistributed.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterVariant.h"
#include <dtkDistributed/dtkDistributedCommunicator>
#include <dtkDistributed/dtkDistributedCommunicatorMpi>
#include <dtkDistributed/dtkDistributedCommunicatorTcp>
#include <dtkLog/dtkLog.h>
// /////////////////////////////////////////////////////////////////
// Communicator Init
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorInitPrivate
{
public:
dtkComposerTransmitterEmitter<dtkDistributedCommunicatorMpi> emitter;
public:
dtkDistributedCommunicatorMpi *communicator;
};
dtkComposerNodeCommunicatorInit::dtkComposerNodeCommunicatorInit(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorInitPrivate)
{
d->communicator = NULL;
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorInit::~dtkComposerNodeCommunicatorInit(void)
{
if (d->communicator)
delete d->communicator;
d->communicator = NULL;
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorInit::run(void)
{
if (!d->communicator) {
d->communicator = new dtkDistributedCommunicatorMpi;
d->emitter.setData(d->communicator);
}
if (!d->communicator->initialized())
d->communicator->initialize();
}
// /////////////////////////////////////////////////////////////////
// Communicator Uninitialize
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorUninitializePrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver;
dtkComposerTransmitterVariant receiver_fake;
};
dtkComposerNodeCommunicatorUninitialize::dtkComposerNodeCommunicatorUninitialize(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorUninitializePrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
this->appendReceiver(&(d->receiver_fake));
}
dtkComposerNodeCommunicatorUninitialize::~dtkComposerNodeCommunicatorUninitialize(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorUninitialize::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicator *communicator = d->receiver.data();
if (communicator) {
communicator->uninitialize();
} else {
dtkError() << "Input communicator not valid.";
return;
}
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
// /////////////////////////////////////////////////////////////////
// Communicator Rank
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorRankPrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver;
dtkComposerTransmitterEmitter<qlonglong> emitter;
public:
qlonglong rank;
};
dtkComposerNodeCommunicatorRank::dtkComposerNodeCommunicatorRank(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorRankPrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
d->rank = -1;
d->emitter.setData(&d->rank);
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorRank::~dtkComposerNodeCommunicatorRank(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorRank::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicator *communicator = d->receiver.data();
if (!communicator) {
d->rank = -1;
dtkError() << "Input communicator not valid.";
return;
}
d->rank = communicator->rank();
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
d->rank = 0;
}
}
// /////////////////////////////////////////////////////////////////
// Communicator Size
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorSizePrivate
{
public:
dtkComposerTransmitterEmitter<qlonglong> emitter;
dtkComposerTransmitterReceiver<dtkDistributedCommunicatorMpi> receiver;
public:
qlonglong size;
};
dtkComposerNodeCommunicatorSize::dtkComposerNodeCommunicatorSize(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorSizePrivate)
{
d->receiver.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver));
d->size = 0;
d->emitter.setData(&d->size);
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorSize::~dtkComposerNodeCommunicatorSize(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorSize::run(void)
{
if (!d->receiver.isEmpty()) {
dtkDistributedCommunicatorMpi *communicator = d->receiver.data();
if (!communicator) {
d->size = 0;
dtkError() << "Input communicator not valid.";
return;
}
d->size = communicator->size();
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
d->size = 0;
}
}
// /////////////////////////////////////////////////////////////////
// Send Variant
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorSendPrivate
{
public:
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver_comm;
dtkComposerTransmitterVariant receiver_data;
dtkComposerTransmitterReceiver<qlonglong> receiver_target;
};
dtkComposerNodeCommunicatorSend::dtkComposerNodeCommunicatorSend(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorSendPrivate)
{
d->receiver_comm.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver_comm));
this->appendReceiver(&(d->receiver_data));
this->appendReceiver(&(d->receiver_target));
}
dtkComposerNodeCommunicatorSend::~dtkComposerNodeCommunicatorSend(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorSend::run(void)
{
if (!d->receiver_data.isEmpty() && !d->receiver_comm.isEmpty() && !d->receiver_target.isEmpty() ) {
QByteArray array = d->receiver_data.dataToByteArray();
dtkTrace() << "Got data as byte array to be sent" << array.size();
dtkDistributedCommunicator *communicator = d->receiver_comm.data();
if (!communicator) {
dtkError() << "Input communicator not valid.";
return;
}
communicator->send(array, *d->receiver_target.data(), 0);
} else {
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
// /////////////////////////////////////////////////////////////////
// Receive Variant
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeCommunicatorReceivePrivate
{
public:
dtkComposerTransmitterVariant emitter;
dtkComposerTransmitterReceiver<dtkDistributedCommunicator> receiver_comm;
dtkComposerTransmitterReceiver<qlonglong> receiver_source;
};
dtkComposerNodeCommunicatorReceive::dtkComposerNodeCommunicatorReceive(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeCommunicatorReceivePrivate)
{
d->receiver_comm.setDataTransmission(dtkComposerTransmitter::Reference);
this->appendReceiver(&(d->receiver_comm));
this->appendReceiver(&(d->receiver_source));
this->appendEmitter(&(d->emitter));
}
dtkComposerNodeCommunicatorReceive::~dtkComposerNodeCommunicatorReceive(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeCommunicatorReceive::run(void)
{
if (!d->receiver_source.isEmpty() && !d->receiver_comm.isEmpty()) {
qlonglong source = *d->receiver_source.data();
dtkDistributedCommunicator *communicator = d->receiver_comm.data();
if (!communicator) {
dtkError() << "Input communicator not valid.";
return;
}
if (dtkDistributedCommunicatorTcp *tcp = dynamic_cast<dtkDistributedCommunicatorTcp *>(communicator)) {
dtDebug() << "TCP communicator. Parse message from socket";
tcp->socket()->blockSignals(true); // needed ?
if (!tcp->socket()->waitForReadyRead(300000)) {
dtkWarn() << "Data not ready in receive for rank " << source;
} else {
dtkDistributedMessage *msg = tcp->socket()->parseRequest();
d->emitter.setTwinned(false);
d->emitter.setDataFrom(msg->content());
d->emitter.setTwinned(true);
delete msg;
}
tcp->socket()->blockSignals(false); // needed ?
} else {
dtkAbstractData *data = NULL;
communicator->receive(data, source, 0);
if (data)
d->emitter.setData(data);
else
d->emitter.clearData();
}
} else {
d->emitter.clearData();
dtkWarn() << "Inputs not specified. Nothing is done";
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.