text
stringlengths
54
60.6k
<commit_before>/* * VTKExporter.cpp * * Created on: 9 sept. 2009 * Author: froy */ #include "VTKExporter.h" #include <sofa/core/ObjectFactory.h> #include <sofa/core/objectmodel/KeypressedEvent.h> #include <sofa/core/objectmodel/KeyreleasedEvent.h> namespace sofa { namespace component { namespace misc { SOFA_DECL_CLASS(VTKExporter) int VTKExporterClass = core::RegisterObject("Read State vectors from file at each timestep") .add< VTKExporter >(); VTKExporter::VTKExporter() : vtkFilename( initData(&vtkFilename, "filename", "output VTK file name")) , writeEdges( initData(&writeEdges, (bool) true, "edges", "write edge topology")) , writeTriangles( initData(&writeTriangles, (bool) false, "triangles", "write triangle topology")) , writeQuads( initData(&writeQuads, (bool) false, "quads", "write quad topology")) , writeTetras( initData(&writeTetras, (bool) false, "tetras", "write tetra topology")) , writeHexas( initData(&writeHexas, (bool) false, "hexas", "write hexa topology")) , dPointsDataFields( initData(&dPointsDataFields, "pointsDataFields", "Data to visualize (on points)")) , dCellsDataFields( initData(&dCellsDataFields, "cellsDataFields", "Data to visualize (on cells)")) { // TODO Auto-generated constructor stub } VTKExporter::~VTKExporter() { outfile->close(); delete outfile; } void VTKExporter::init() { sofa::core::objectmodel::BaseContext* context = this->getContext(); context->get(topology); const std::string& filename = vtkFilename.getFullPath(); if (!topology) { serr << "VTKExporter : error, no topology ." << sendl; return; } outfile = new std::ofstream(filename.c_str()); if( !outfile->is_open() ) { serr << "Error creating file "<<filename<<sendl; delete outfile; outfile = NULL; return; } const helper::vector<std::string>& pointsData = dPointsDataFields.getValue(); const helper::vector<std::string>& cellsData = dCellsDataFields.getValue(); if (!pointsData.empty()) { fetchDataFields(pointsData, pointsDataObject, pointsDataField); } if (!cellsData.empty()) { fetchDataFields(cellsData, cellsDataObject, cellsDataField); } } void VTKExporter::fetchDataFields(const helper::vector<std::string>& strData, helper::vector<std::string>& objects, helper::vector<std::string>& fields) { for (unsigned int i=0 ; i<strData.size() ; i++) { std::string objectName, dataFieldName; std::string::size_type loc = strData[i].find_first_of('.'); if ( loc != std::string::npos) { objectName = strData[i].substr(0, loc); dataFieldName = strData[i].substr(loc+1); objects.push_back(objectName); fields.push_back(dataFieldName); } else { serr << "VTKExporter : error while parsing dataField names" << sendl; } } } void VTKExporter::writeData(const helper::vector<std::string>& objects, const helper::vector<std::string>& fields) { sofa::core::objectmodel::BaseContext* context = this->getContext(); for (unsigned int i=0 ; i<objects.size() ; i++) { core::objectmodel::BaseObject* obj = context->get<core::objectmodel::BaseObject> (objects[i]); core::objectmodel::BaseData* field = NULL; if (obj) { std::vector< std::pair<std::string, core::objectmodel::BaseData*> > f = obj->getFields(); for (unsigned int j=0 ; j<f.size() && !field; j++) { if(fields[i].compare(f[j].first) == 0) field = f[j].second; } } if (!obj || !field) { serr << "VTKExporter : error while fetching data field, check object name or field name " << sendl; } else { std::cout << "Type: " << field->getValueTypeString() << std::endl; //retrieve data file type // if (dynamic_cast<Data< defaulttype::Vec3f >* >(field)) // std::cout << "Vec3f" << std::endl; // if (dynamic_cast<Data< defaulttype::Vec3d >* >(field)) // std::cout << "Vec3d" << std::endl; //Scalars std::string line; unsigned int sizeSeg=0; if (dynamic_cast<sofa::core::objectmodel::TData< helper::vector<float> >* >(field)) { line = "float 1"; sizeSeg = 1; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector<double> >* >(field)) { line = "double 1"; sizeSeg = 1; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec2f > >* > (field)) { line = "float 2"; sizeSeg = 2; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec2d > >* >(field)) { line = "double 2"; sizeSeg = 2; } //if this is a scalar if (!line.empty()) { *outfile << "SCALARS" << " " << fields[i] << " "; } else { //Vectors if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec3f > >* > (field)) { line = "float"; sizeSeg = 3; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec3d > >* >(field)) { line = "double"; sizeSeg = 3; } *outfile << "VECTORS" << " " << fields[i] << " "; } *outfile << line << std::endl; *outfile << segmentString(field->getValueString(),sizeSeg) << std::endl; *outfile << std::endl; } } } std::string VTKExporter::segmentString(std::string str, unsigned int n) { std::string::size_type loc = 0; unsigned int i=0; loc = str.find(' ', 0); while(loc != std::string::npos ) { i++; if (i == n) { str[loc] = '\n'; i=0; } loc = str.find(' ', loc+1); } return str; } void VTKExporter::writeVTK() { const helper::vector<std::string>& pointsData = dPointsDataFields.getValue(); const helper::vector<std::string>& cellsData = dCellsDataFields.getValue(); //Write header *outfile << "# vtk DataFile Version 2.0" << std::endl; //write Title *outfile << "Exported VTK file" << std::endl; //write Data type *outfile << "ASCII" << std::endl; *outfile << std::endl; //write dataset (geometry, unstructured grid) *outfile << "DATASET " << "UNSTRUCTURED_GRID" << std::endl; *outfile << "POINTS " << topology->getNbPoints() << " float" << std::endl; //write Points for (int i=0 ; i<topology->getNbPoints() ; i++) *outfile << topology->getPX(i) << " " << topology->getPY(i) << " " << topology->getPZ(i) << std::endl; *outfile << std::endl; //Write Cells unsigned int numberOfCells, totalSize; numberOfCells = ( (writeEdges.getValue()) ? topology->getNbEdges() : 0 ) +( (writeTriangles.getValue()) ? topology->getNbTriangles() : 0 ) +( (writeQuads.getValue()) ? topology->getNbQuads() : 0 ) +( (writeTetras.getValue()) ? topology->getNbTetras() : 0 ) +( (writeHexas.getValue()) ? topology->getNbHexas() : 0 ); totalSize = ( (writeEdges.getValue()) ? 3 * topology->getNbEdges() : 0 ) +( (writeTriangles.getValue()) ? 4 *topology->getNbTriangles() : 0 ) +( (writeQuads.getValue()) ? 5 *topology->getNbQuads() : 0 ) +( (writeTetras.getValue()) ? 5 *topology->getNbTetras() : 0 ) +( (writeHexas.getValue()) ? 9 *topology->getNbHexas() : 0 ); *outfile << "CELLS " << numberOfCells << " " << totalSize << std::endl; if (writeEdges.getValue()) { for (int i=0 ; i<topology->getNbEdges() ; i++) *outfile << 2 << " " << topology->getEdge(i) << std::endl; } if (writeTriangles.getValue()) { for (int i=0 ; i<topology->getNbTriangles() ; i++) *outfile << 3 << " " << topology->getTriangle(i) << std::endl; } if (writeQuads.getValue()) { for (int i=0 ; i<topology->getNbQuads() ; i++) *outfile << 4 << " " << topology->getQuad(i) << std::endl; } if (writeTetras.getValue()) { for (int i=0 ; i<topology->getNbTetras() ; i++) *outfile << 4 << " " << topology->getTetra(i) << std::endl; } if (writeHexas.getValue()) { for (int i=0 ; i<topology->getNbHexas() ; i++) *outfile << 8 << " " << topology->getHexa(i) << std::endl; } *outfile << std::endl; *outfile << "CELL_TYPES " << numberOfCells << std::endl; if (writeEdges.getValue()) { for (int i=0 ; i<topology->getNbEdges() ; i++) *outfile << 3 << std::endl; } if (writeTriangles.getValue()) { for (int i=0 ; i<topology->getNbTriangles() ; i++) *outfile << 5 << std::endl; } if (writeQuads.getValue()) { for (int i=0 ; i<topology->getNbQuads() ; i++) *outfile << 9 << std::endl; } if (writeTetras.getValue()) { for (int i=0 ; i<topology->getNbTetras() ; i++) *outfile << 10 << std::endl; } if (writeHexas.getValue()) { for (int i=0 ; i<topology->getNbHexas() ; i++) *outfile << 12 << std::endl; } *outfile << std::endl; //write dataset attributes if (!pointsData.empty()) { *outfile << "POINT_DATA " << topology->getNbPoints() << std::endl; writeData(pointsDataObject, pointsDataField); } if (!cellsData.empty()) { *outfile << "CELL_DATA " << numberOfCells << std::endl; writeData(cellsDataObject, cellsDataField); } std::cout << "VTK written" << std::endl; } void VTKExporter::handleEvent(sofa::core::objectmodel::Event *event) { if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event)) { switch(ev->getKey()) { case 'E': case 'e': writeVTK(); break; } } } } } } <commit_msg>r5356/sofa-dev : FIX: VTK export, when fetching objects path<commit_after>/* * VTKExporter.cpp * * Created on: 9 sept. 2009 * Author: froy */ #include "VTKExporter.h" #include <sofa/core/ObjectFactory.h> #include <sofa/core/objectmodel/KeypressedEvent.h> #include <sofa/core/objectmodel/KeyreleasedEvent.h> namespace sofa { namespace component { namespace misc { SOFA_DECL_CLASS(VTKExporter) int VTKExporterClass = core::RegisterObject("Read State vectors from file at each timestep") .add< VTKExporter >(); VTKExporter::VTKExporter() : vtkFilename( initData(&vtkFilename, "filename", "output VTK file name")) , writeEdges( initData(&writeEdges, (bool) true, "edges", "write edge topology")) , writeTriangles( initData(&writeTriangles, (bool) false, "triangles", "write triangle topology")) , writeQuads( initData(&writeQuads, (bool) false, "quads", "write quad topology")) , writeTetras( initData(&writeTetras, (bool) false, "tetras", "write tetra topology")) , writeHexas( initData(&writeHexas, (bool) false, "hexas", "write hexa topology")) , dPointsDataFields( initData(&dPointsDataFields, "pointsDataFields", "Data to visualize (on points)")) , dCellsDataFields( initData(&dCellsDataFields, "cellsDataFields", "Data to visualize (on cells)")) { // TODO Auto-generated constructor stub } VTKExporter::~VTKExporter() { delete outfile; } void VTKExporter::init() { sofa::core::objectmodel::BaseContext* context = this->getContext(); context->get(topology); if (!topology) { serr << "VTKExporter : error, no topology ." << sendl; return; } const helper::vector<std::string>& pointsData = dPointsDataFields.getValue(); const helper::vector<std::string>& cellsData = dCellsDataFields.getValue(); if (!pointsData.empty()) { fetchDataFields(pointsData, pointsDataObject, pointsDataField); } if (!cellsData.empty()) { fetchDataFields(cellsData, cellsDataObject, cellsDataField); } } void VTKExporter::fetchDataFields(const helper::vector<std::string>& strData, helper::vector<std::string>& objects, helper::vector<std::string>& fields) { for (unsigned int i=0 ; i<strData.size() ; i++) { std::string objectName, dataFieldName; std::string::size_type loc = strData[i].find_last_of('.'); if ( loc != std::string::npos) { objectName = strData[i].substr(0, loc); dataFieldName = strData[i].substr(loc+1); objects.push_back(objectName); fields.push_back(dataFieldName); } else { serr << "VTKExporter : error while parsing dataField names" << sendl; } } } void VTKExporter::writeData(const helper::vector<std::string>& objects, const helper::vector<std::string>& fields) { sofa::core::objectmodel::BaseContext* context = this->getContext(); //std::cout << "List o: " << objects << std::endl; //std::cout << "List f: " << fields << std::endl; for (unsigned int i=0 ; i<objects.size() ; i++) { core::objectmodel::BaseObject* obj = context->get<core::objectmodel::BaseObject> (objects[i]); core::objectmodel::BaseData* field = NULL; //std::cout << objects[i] << std::endl; if (obj) { std::vector< std::pair<std::string, core::objectmodel::BaseData*> > f = obj->getFields(); for (unsigned int j=0 ; j<f.size() && !field; j++) { if(fields[i].compare(f[j].first) == 0) field = f[j].second; } } if (!obj || !field) { serr << "VTKExporter : error while fetching data field, check object name or field name " << sendl; } else { std::cout << "Type: " << field->getValueTypeString() << std::endl; //retrieve data file type // if (dynamic_cast<Data< defaulttype::Vec3f >* >(field)) // std::cout << "Vec3f" << std::endl; // if (dynamic_cast<Data< defaulttype::Vec3d >* >(field)) // std::cout << "Vec3d" << std::endl; //Scalars std::string line; unsigned int sizeSeg=0; if (dynamic_cast<sofa::core::objectmodel::TData< helper::vector<float> >* >(field)) { line = "float 1"; sizeSeg = 1; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector<double> >* >(field)) { line = "double 1"; sizeSeg = 1; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec2f > >* > (field)) { line = "float 2"; sizeSeg = 2; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec2d > >* >(field)) { line = "double 2"; sizeSeg = 2; } //if this is a scalar if (!line.empty()) { *outfile << "SCALARS" << " " << fields[i] << " "; } else { //Vectors if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec3f > >* > (field)) { line = "float"; sizeSeg = 3; } if (dynamic_cast<sofa::core::objectmodel::TData<helper::vector< defaulttype::Vec3d > >* >(field)) { line = "double"; sizeSeg = 3; } *outfile << "VECTORS" << " " << fields[i] << " "; } *outfile << line << std::endl; *outfile << segmentString(field->getValueString(),sizeSeg) << std::endl; *outfile << std::endl; } } } std::string VTKExporter::segmentString(std::string str, unsigned int n) { std::string::size_type loc = 0; unsigned int i=0; loc = str.find(' ', 0); while(loc != std::string::npos ) { i++; if (i == n) { str[loc] = '\n'; i=0; } loc = str.find(' ', loc+1); } return str; } void VTKExporter::writeVTK() { const helper::vector<std::string>& pointsData = dPointsDataFields.getValue(); const helper::vector<std::string>& cellsData = dCellsDataFields.getValue(); const std::string& filename = vtkFilename.getFullPath(); outfile = new std::ofstream(filename.c_str()); if( !outfile->is_open() ) { serr << "Error creating file "<<filename<<sendl; delete outfile; outfile = NULL; return; } //Write header *outfile << "# vtk DataFile Version 2.0" << std::endl; //write Title *outfile << "Exported VTK file" << std::endl; //write Data type *outfile << "ASCII" << std::endl; *outfile << std::endl; //write dataset (geometry, unstructured grid) *outfile << "DATASET " << "UNSTRUCTURED_GRID" << std::endl; *outfile << "POINTS " << topology->getNbPoints() << " float" << std::endl; //write Points for (int i=0 ; i<topology->getNbPoints() ; i++) *outfile << topology->getPX(i) << " " << topology->getPY(i) << " " << topology->getPZ(i) << std::endl; *outfile << std::endl; //Write Cells unsigned int numberOfCells, totalSize; numberOfCells = ( (writeEdges.getValue()) ? topology->getNbEdges() : 0 ) +( (writeTriangles.getValue()) ? topology->getNbTriangles() : 0 ) +( (writeQuads.getValue()) ? topology->getNbQuads() : 0 ) +( (writeTetras.getValue()) ? topology->getNbTetras() : 0 ) +( (writeHexas.getValue()) ? topology->getNbHexas() : 0 ); totalSize = ( (writeEdges.getValue()) ? 3 * topology->getNbEdges() : 0 ) +( (writeTriangles.getValue()) ? 4 *topology->getNbTriangles() : 0 ) +( (writeQuads.getValue()) ? 5 *topology->getNbQuads() : 0 ) +( (writeTetras.getValue()) ? 5 *topology->getNbTetras() : 0 ) +( (writeHexas.getValue()) ? 9 *topology->getNbHexas() : 0 ); *outfile << "CELLS " << numberOfCells << " " << totalSize << std::endl; if (writeEdges.getValue()) { for (int i=0 ; i<topology->getNbEdges() ; i++) *outfile << 2 << " " << topology->getEdge(i) << std::endl; } if (writeTriangles.getValue()) { for (int i=0 ; i<topology->getNbTriangles() ; i++) *outfile << 3 << " " << topology->getTriangle(i) << std::endl; } if (writeQuads.getValue()) { for (int i=0 ; i<topology->getNbQuads() ; i++) *outfile << 4 << " " << topology->getQuad(i) << std::endl; } if (writeTetras.getValue()) { for (int i=0 ; i<topology->getNbTetras() ; i++) *outfile << 4 << " " << topology->getTetra(i) << std::endl; } if (writeHexas.getValue()) { for (int i=0 ; i<topology->getNbHexas() ; i++) *outfile << 8 << " " << topology->getHexa(i) << std::endl; } *outfile << std::endl; *outfile << "CELL_TYPES " << numberOfCells << std::endl; if (writeEdges.getValue()) { for (int i=0 ; i<topology->getNbEdges() ; i++) *outfile << 3 << std::endl; } if (writeTriangles.getValue()) { for (int i=0 ; i<topology->getNbTriangles() ; i++) *outfile << 5 << std::endl; } if (writeQuads.getValue()) { for (int i=0 ; i<topology->getNbQuads() ; i++) *outfile << 9 << std::endl; } if (writeTetras.getValue()) { for (int i=0 ; i<topology->getNbTetras() ; i++) *outfile << 10 << std::endl; } if (writeHexas.getValue()) { for (int i=0 ; i<topology->getNbHexas() ; i++) *outfile << 12 << std::endl; } *outfile << std::endl; //write dataset attributes if (!pointsData.empty()) { *outfile << "POINT_DATA " << topology->getNbPoints() << std::endl; writeData(pointsDataObject, pointsDataField); } if (!cellsData.empty()) { *outfile << "CELL_DATA " << numberOfCells << std::endl; writeData(cellsDataObject, cellsDataField); } outfile->close(); std::cout << "VTK written" << std::endl; } void VTKExporter::handleEvent(sofa::core::objectmodel::Event *event) { if (sofa::core::objectmodel::KeypressedEvent* ev = dynamic_cast<sofa::core::objectmodel::KeypressedEvent*>(event)) { switch(ev->getKey()) { case 'E': case 'e': writeVTK(); break; } } } } } } <|endoftext|>
<commit_before>#pragma once #include <vector> #include "geom.hpp" #include "global_config.hpp" #include "lattice.hpp" namespace mocc { class Plane { public: Plane(const std::vector<const Lattice*> &lattices, size_t nx, size_t ny); const Lattice& at(size_t ix, size_t iy) const { return *(lattices_[ix + nx_*iy]); } /** * \brief Return a const pointer to the \ref PinMesh that occupies the * passed \ref Point2. * * \param[in] p The point at which to find a \ref PinMesh * \param[inout] first_reg the first region index of the returned \ref * Pin. The value passed in is incremented by the region offset within * the Plane. */ const PinMesh* get_pinmesh( Point2 &p, int &first_reg) const; /** * \brief Return a const pointer to the \ref PinMesh that is at the * passed \ref Position. */ const PinMesh* get_pinmesh( Position pos ) const; /** * Return the number of solution mesh regions in the \ref Plane */ size_t n_reg() const { return n_reg_; } /** * Return the number of XS Mesh regions in the Plane */ size_t n_xsreg() const { return n_xsreg_; } /** * \brief Return a vector containing the FSR volumes */ VecF vols() const { VecF vols; for( auto &lat: lattices_ ) { for( auto &pin: *lat ) { vols.insert(vols.end(), pin->vols().begin(), pin->vols().end()); } } return vols; } /** * \brief Return the position of a pin, given its index. */ Position pin_position( size_t ipin ) const; /** * \breif Return the number of \ref Pins in this \ref Plane marked as * fuel. */ int n_fuel() const { return n_fuel_; } private: /** * Number of lattices in the x direction */ size_t nx_; /** * Number of lattices in the y direction */ size_t ny_; size_t n_reg_; size_t n_xsreg_; /** * Locations of \ref Lattice interfaces */ VecF hx_; VecF hy_; /** * Local list of \ref Lattice pointers */ std::vector<const Lattice*> lattices_; /** * List of the starting FSR index for each \ref Lattice in the plane */ VecI first_reg_lattice_; int n_fuel_; }; } <commit_msg>Fix documentation error<commit_after>#pragma once #include <vector> #include "geom.hpp" #include "global_config.hpp" #include "lattice.hpp" namespace mocc { class Plane { public: Plane(const std::vector<const Lattice*> &lattices, size_t nx, size_t ny); const Lattice& at(size_t ix, size_t iy) const { return *(lattices_[ix + nx_*iy]); } /** * \brief Return a const pointer to the \ref PinMesh that occupies the * passed \ref Point2. * * \param[in] p The point at which to find a \ref PinMesh * \param[inout] first_reg the first region index of the returned \ref * Pin. The value passed in is incremented by the region offset within * the Plane. */ const PinMesh* get_pinmesh( Point2 &p, int &first_reg) const; /** * \brief Return a const pointer to the \ref PinMesh that is at the * passed \ref Position. */ const PinMesh* get_pinmesh( Position pos ) const; /** * Return the number of solution mesh regions in the \ref Plane */ size_t n_reg() const { return n_reg_; } /** * Return the number of XS Mesh regions in the Plane */ size_t n_xsreg() const { return n_xsreg_; } /** * \brief Return a vector containing the FSR volumes */ VecF vols() const { VecF vols; for( auto &lat: lattices_ ) { for( auto &pin: *lat ) { vols.insert(vols.end(), pin->vols().begin(), pin->vols().end()); } } return vols; } /** * \brief Return the position of a pin, given its index. */ Position pin_position( size_t ipin ) const; /** * \brief Return the number of \ref Pin s in this \ref Plane marked as * fuel. */ int n_fuel() const { return n_fuel_; } private: /** * Number of lattices in the x direction */ size_t nx_; /** * Number of lattices in the y direction */ size_t ny_; size_t n_reg_; size_t n_xsreg_; /** * Locations of \ref Lattice interfaces */ VecF hx_; VecF hy_; /** * Local list of \ref Lattice pointers */ std::vector<const Lattice*> lattices_; /** * List of the starting FSR index for each \ref Lattice in the plane */ VecI first_reg_lattice_; int n_fuel_; }; } <|endoftext|>
<commit_before><commit_msg>Fix build breakage at r30320.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "base/lazy_instance.h" #include "base/string_util.h" #include "base/thread_local.h" #include "base/waitable_event.h" namespace base { // This task is used to trigger the message loop to exit. class ThreadQuitTask : public Task { public: virtual void Run() { MessageLoop::current()->Quit(); Thread::SetThreadWasQuitProperly(true); } }; // Used to pass data to ThreadMain. This structure is allocated on the stack // from within StartWithOptions. struct Thread::StartupData { // We get away with a const reference here because of how we are allocated. const Thread::Options& options; // Used to synchronize thread startup. WaitableEvent event; explicit StartupData(const Options& opt) : options(opt), event(false, false) {} }; Thread::Thread(const char *name) : stopping_(false), startup_data_(NULL), thread_(0), message_loop_(NULL), thread_id_(0), name_(name) { } Thread::~Thread() { Stop(); } namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::Quit() is called directly, which is unexpected when using a // Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool( base::LINKER_INITIALIZED); } // namespace void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } bool Thread::Start() { return StartWithOptions(Options()); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); SetThreadWasQuitProperly(false); StartupData startup_data(options); startup_data_ = &startup_data; if (!PlatformThread::Create(options.stack_size, this, &thread_)) { DLOG(ERROR) << "failed to create thread"; startup_data_ = NULL; // Record that we failed to start. return false; } // Wait for the thread to start and initialize message_loop_ startup_data.event.Wait(); DCHECK(message_loop_); return true; } void Thread::Stop() { if (!thread_was_started()) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. startup_data_ = NULL; stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. DCHECK_NE(thread_id_, PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; message_loop_->PostTask(FROM_HERE, new ThreadQuitTask()); } void Thread::Run(MessageLoop* message_loop) { message_loop->Run(); } void Thread::ThreadMain() { // The message loop for this thread. MessageLoop message_loop(startup_data_->options.message_loop_type); // Complete the initialization of our Thread object. thread_id_ = PlatformThread::CurrentId(); PlatformThread::SetName(name_.c_str()); message_loop.set_thread_name(name_); message_loop_ = &message_loop; // Let the thread do extra initialization. // Let's do this before signaling we are started. Init(); startup_data_->event.Signal(); // startup_data_ can't be touched anymore since the starting thread is now // unlocked. Run(message_loop_); // Let the thread do extra cleanup. CleanUp(); // Assert that MessageLoop::Quit was called by ThreadQuitTask. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. message_loop_ = NULL; thread_id_ = 0; } } // namespace base <commit_msg>Notify race detectors (e.g. ThreadSanitizer) about the thread names ThreadSanitizer will print the name of the threads in data race reports.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "base/dynamic_annotations.h" #include "base/lazy_instance.h" #include "base/string_util.h" #include "base/thread_local.h" #include "base/waitable_event.h" namespace base { // This task is used to trigger the message loop to exit. class ThreadQuitTask : public Task { public: virtual void Run() { MessageLoop::current()->Quit(); Thread::SetThreadWasQuitProperly(true); } }; // Used to pass data to ThreadMain. This structure is allocated on the stack // from within StartWithOptions. struct Thread::StartupData { // We get away with a const reference here because of how we are allocated. const Thread::Options& options; // Used to synchronize thread startup. WaitableEvent event; explicit StartupData(const Options& opt) : options(opt), event(false, false) {} }; Thread::Thread(const char *name) : stopping_(false), startup_data_(NULL), thread_(0), message_loop_(NULL), thread_id_(0), name_(name) { } Thread::~Thread() { Stop(); } namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::Quit() is called directly, which is unexpected when using a // Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool( base::LINKER_INITIALIZED); } // namespace void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } bool Thread::Start() { return StartWithOptions(Options()); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); SetThreadWasQuitProperly(false); StartupData startup_data(options); startup_data_ = &startup_data; if (!PlatformThread::Create(options.stack_size, this, &thread_)) { DLOG(ERROR) << "failed to create thread"; startup_data_ = NULL; // Record that we failed to start. return false; } // Wait for the thread to start and initialize message_loop_ startup_data.event.Wait(); DCHECK(message_loop_); return true; } void Thread::Stop() { if (!thread_was_started()) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. startup_data_ = NULL; stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. DCHECK_NE(thread_id_, PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; message_loop_->PostTask(FROM_HERE, new ThreadQuitTask()); } void Thread::Run(MessageLoop* message_loop) { message_loop->Run(); } void Thread::ThreadMain() { // The message loop for this thread. MessageLoop message_loop(startup_data_->options.message_loop_type); // Complete the initialization of our Thread object. thread_id_ = PlatformThread::CurrentId(); PlatformThread::SetName(name_.c_str()); ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. message_loop.set_thread_name(name_); message_loop_ = &message_loop; // Let the thread do extra initialization. // Let's do this before signaling we are started. Init(); startup_data_->event.Signal(); // startup_data_ can't be touched anymore since the starting thread is now // unlocked. Run(message_loop_); // Let the thread do extra cleanup. CleanUp(); // Assert that MessageLoop::Quit was called by ThreadQuitTask. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. message_loop_ = NULL; thread_id_ = 0; } } // namespace base <|endoftext|>
<commit_before>/// /// @file D3.cpp /// @brief Simple demonstration implementation of the D(x, y) formula /// in Xavier Gourdon's prime counting algorithm. This /// implementation runs single threaded and does not use the /// highly optimized Sieve.cpp. /// /// This implementation uses the DFactorTable lookup /// table instead of the mu, lpf and mpf lookup tables. /// DFactorTable uses much less memory and allows to /// check more quickly whether a number is a leaf or not. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <gourdon.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <min.hpp> #include <imath.hpp> #include <print.hpp> #include <PiTable.hpp> #include "DFactorTable.hpp" #include <stdint.h> #include <vector> using namespace std; namespace { /// Remove the multiples of the b-th prime from the sieve array. /// @return: Count of numbers unset for the 1st time. /// template <typename Sieve> int64_t cross_off(Sieve& sieve, int64_t prime, int64_t& next_multiple, int64_t low, int64_t high) { int64_t n = next_multiple; int64_t count = 0; for (; n < high; n += prime * 2) { count += sieve[n - low]; sieve[n - low] = 0; } next_multiple = n; return count; } } // namespace namespace primecount { int64_t D(int64_t x, int64_t y, int64_t z, int64_t k) { print(""); print("=== D(x, y) ==="); print(x, y, z, k, 1); double time = get_time(); int64_t sum = 0; int64_t limit = x / z + 1; int64_t segment_size = isqrt(limit); int64_t x_star = get_x_star_gourdon(x, y); PiTable pi(y); auto primes = generate_primes<int32_t>(y); DFactorTable<uint16_t> factor(y, z, 1); int64_t pi_sqrtz = pi[isqrt(z)]; int64_t pi_x_star = pi[x_star]; vector<char> sieve(segment_size); vector<int64_t> phi(pi_x_star + 1, 0); vector<int64_t> next(primes.begin(), primes.end()); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 1; // Reset the sieve array fill(sieve.begin(), sieve.end(), 1); // Pre-sieve multiples of first k primes for (; b <= k; b++) { int64_t j = next[b]; for (int64_t prime = primes[b]; j < high; j += prime) sieve[j - low] = 0; next[b] = j; } int64_t count_low_high = 0; for (int64_t i = low; i < high; i++) count_low_high += sieve[i - low]; // For k + 1 <= b <= pi_sqrtz // Find all special leaves: n = primes[b] * m // In the interval: low <= (x / n) < high // Which satisfy: mu[m] != 0 && lpf[m] > primes[b] && mpf[m] <= y for (; b <= pi_sqrtz; b++) { int64_t prime = primes[b]; int64_t max_m = min(x / (prime * low), x / ipow(prime, 3), z); int64_t min_m = max(x / (prime * high), z / prime, prime); int64_t count = 0; int64_t i = 0; if (prime >= max_m) goto next_segment; factor.to_index(&min_m); factor.to_index(&max_m); for (int64_t m = max_m; m > min_m; m--) { // mu[m] != 0 && // lpf[m] > prime && // mpf[m] <= y if (prime < factor.is_leaf(m)) { // We have found a special leaf. Compute it's contribution // phi(x / (primes[b] * m), b - 1) by counting the number // of unsieved elements <= x / (primes[b] * m) after having // removed the multiples of the first b - 1 primes. int64_t xpm = x / (prime * factor.get_number(m)); int64_t stop = xpm - low; for (; i <= stop; i++) count += sieve[i]; int64_t phi_xpm = phi[b] + count; sum -= factor.mu(m) * phi_xpm; } } phi[b] += count_low_high; count_low_high -= cross_off(sieve, prime, next[b], low, high); } // For pi_sqrtz < b <= pi_x_star // Find all special leaves: n = primes[b] * prime2 // which satisfy: low <= (x / n) < high && prime2 <= y for (; b <= pi_x_star; b++) { int64_t prime = primes[b]; int64_t max_m = min(x / (prime * low), x / ipow(prime, 3), y); int64_t min_m = max(x / (prime * high), z / prime, prime); int64_t l = pi[max_m]; int64_t i = 0; int64_t count = 0; if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_m; l--) { int64_t xpq = x / (prime * primes[l]); int64_t stop = xpq - low; for (; i <= stop; i++) count += sieve[i]; int64_t phi_xpq = phi[b] + count; sum += phi_xpq; } phi[b] += count_low_high; count_low_high -= cross_off(sieve, prime, next[b], low, high); } next_segment:; } print("D", sum, time); return sum; } } // namespace <commit_msg>Use Sieve class<commit_after>/// /// @file D3.cpp /// @brief Single threaded implementation of the D(x, y) formula in /// Xavier Gourdon's prime counting algorithm. This /// implementation uses the highly optimized Sieve class. /// /// This implementation also uses the DFactorTable lookup /// table instead of the mu, lpf and mpf lookup tables. /// DFactorTable uses much less memory and allows to check /// more quickly whether a number is a leaf or not. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <gourdon.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <min.hpp> #include <imath.hpp> #include <print.hpp> #include <PiTable.hpp> #include <Sieve.hpp> #include "DFactorTable.hpp" #include <stdint.h> #include <vector> using namespace std; namespace primecount { int64_t D(int64_t x, int64_t y, int64_t z, int64_t k) { print(""); print("=== D(x, y) ==="); print(x, y, z, k, 1); double time = get_time(); int64_t sum = 0; int64_t limit = x / z + 1; int64_t segment_size = Sieve::get_segment_size(isqrt(limit)); int64_t x_star = get_x_star_gourdon(x, y); int64_t low = 0; auto primes = generate_primes<int32_t>(y); DFactorTable<uint16_t> factor(y, z, 1); Sieve sieve(low, segment_size, primes.size()); PiTable pi(y); int64_t pi_sqrtz = pi[isqrt(z)]; int64_t pi_x_star = pi[x_star]; vector<int64_t> phi(pi_x_star + 1, 0); // Segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { // Current segment [low, high[ int64_t high = min(low + segment_size, limit); int64_t low1 = max(low, 1); // pre-sieve multiples of first k primes sieve.pre_sieve(k, low, high); int64_t count_low_high = sieve.count((high - 1) - low); int64_t b = k + 1; // For k + 1 <= b <= pi_sqrtz // Find all special leaves: n = primes[b] * m // In the interval: low <= (x / n) < high // Which satisfy: mu[m] != 0 && lpf[m] > primes[b] && mpf[m] <= y for (; b <= pi_sqrtz; b++) { int64_t prime = primes[b]; int64_t max_m = min(x / (prime * low1), x / ipow(prime, 3), z); int64_t min_m = max(x / (prime * high), z / prime, prime); int64_t start = 0; int64_t count = 0; if (prime >= max_m) goto next_segment; factor.to_index(&min_m); factor.to_index(&max_m); for (int64_t m = max_m; m > min_m; m--) { // mu[m] != 0 && // lpf[m] > prime && // mpf[m] <= y if (prime < factor.is_leaf(m)) { int64_t xpm = x / (prime * factor.get_number(m)); int64_t stop = xpm - low; count += sieve.count(start, stop); start = stop + 1; int64_t phi_xpm = phi[b] + count; sum -= factor.mu(m) * phi_xpm; } } phi[b] += count_low_high; count_low_high -= sieve.cross_off(b, prime); } // For pi_sqrtz < b <= pi_x_star // Find all special leaves: n = primes[b] * prime2 // which satisfy: low <= (x / n) < high && prime2 <= y for (; b <= pi_x_star; b++) { int64_t prime = primes[b]; int64_t max_m = min(x / (prime * low1), x / ipow(prime, 3), y); int64_t min_m = max(x / (prime * high), z / prime, prime); int64_t l = pi[max_m]; int64_t start = 0; int64_t count = 0; if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_m; l--) { int64_t xpq = x / (prime * primes[l]); int64_t stop = xpq - low; count += sieve.count(start, stop); start = stop + 1; int64_t phi_xpq = phi[b] + count; sum += phi_xpq; } phi[b] += count_low_high; count_low_high -= sieve.cross_off(b, prime); } next_segment:; } print("D", sum, time); return sum; } } // namespace <|endoftext|>
<commit_before><commit_msg>Fix for slider labels<commit_after><|endoftext|>
<commit_before><commit_msg>replace ByteString::Fill<commit_after><|endoftext|>
<commit_before>#include "io/file_io.hpp" #include <stdexcept> #include <fstream> #include "core/pll/pllhead.hpp" #include "seq/MSA.hpp" #include "util/constants.hpp" #include "core/pll/pll_util.hpp" #include "util/logging.hpp" typedef struct fasta_record_s { pll_fasta_t* file; char * sequence = NULL; char * header = NULL; } fasta_record_t; static unsigned long length_till_newl(char* line) { char c; unsigned long length = 0; while((c = *line++) and (c != '\n' or c != '\r')) { ++length; } return length; } int pll_fasta_fseek(pll_fasta_t* fd, const long int offset, const int whence) { auto status = fseek(fd->fp, offset, whence); /* reset stripped char frequencies */ fd->stripped_count = 0; for(size_t i=0; i<256; i++) { fd->stripped[i] = 0; } fd->line[0] = 0; if (!fgets(fd->line, PLL_LINEALLOC, fd->fp)) { pll_errno = PLL_ERROR_FILE_SEEK; snprintf(pll_errmsg, 200, "Unable to rewind and cache data"); return -1; } fd->lineno = 1; return status; } static void epa_read_fasta( const std::string& msa_file, std::function<void(fasta_record_t&)> fn, const size_t offset=0, const size_t span=std::numeric_limits<size_t>::max()) { fasta_record_t record; /* open the file */ record.file = pll_fasta_open(msa_file.c_str(), pll_map_fasta); if (!record.file) { throw std::runtime_error{std::string("Cannot open file ") + msa_file}; } if(pll_fasta_fseek(record.file, offset, SEEK_SET)) { throw std::runtime_error{"Unable to fseek on the fasta file."}; } long sequence_length; long header_length; long sequence_number; /* read sequences and make sure they are all of the same length */ int sites = 0; size_t read_seqs = 0; /* read the first sequence seperately, so that the MSA object can be constructed */ if (PLL_FAILURE == pll_fasta_getnext( record.file, &record.header, &header_length, &record.sequence, &sequence_length, &sequence_number)) { throw std::runtime_error{std::string("fasta_getnext failed: ") + pll_errmsg}; } sites = sequence_length; if (sites == -1 || sites == 0) { throw std::runtime_error{"Unable to read MSA record: invalid sequence length"}; } fn(record); ++read_seqs; free(record.sequence); free(record.header); /* read the rest */ while(read_seqs < span and pll_fasta_getnext(record.file, &record.header, &header_length, &record.sequence, &sequence_length, &sequence_number)) { if (sites && sites != sequence_length) { throw std::runtime_error{"MSA file does not contain equal size sequences"}; } if (!sites) sites = sequence_length; fn(record); ++read_seqs; free(record.sequence); free(record.header); } // if (pll_errno != PLL_ERROR_FILE_EOF) { // throw std::runtime_error{std::string("Error while reading file: ") + msa_file}; // } pll_fasta_close(record.file); } std::vector<size_t> get_offsets(const std::string& msa_file, MSA& msa) { std::vector<size_t> result; epa_read_fasta(msa_file, [&](auto& record){ result.push_back(ftell(record.file->fp) - length_till_newl(record.file->line)); msa.append(record.header, ""); }); return result; } MSA build_MSA_from_file(const std::string& msa_file, const size_t offset, const size_t span) { MSA msa; epa_read_fasta( msa_file, [&](auto& record){ msa.append(record.header, record.sequence); }, offset, span); return msa; } pll_utree_s * build_tree_from_file(const std::string& tree_file, Tree_Numbers& nums) { pll_utree_t * tree; pll_rtree_t * rtree; // load the tree unrooted if (!(rtree = pll_rtree_parse_newick(tree_file.c_str()))) { if (!(tree = pll_utree_parse_newick(tree_file.c_str()))) { throw std::runtime_error{"Treeparsing failed!"}; } } else { tree = pll_rtree_unroot(rtree); pll_rtree_destroy(rtree, nullptr); /* optional step if using default PLL clv/pmatrix index assignments */ pll_utree_reset_template_indices(get_root(tree), tree->tip_count); } if (tree->tip_count < 3) { throw std::runtime_error{"Number of tip nodes too small"}; } nums = Tree_Numbers(tree->tip_count); set_missing_branch_lengths(tree, DEFAULT_BRANCH_LENGTH); return tree; } static unsigned int simd_autodetect() { if (PLL_STAT(avx2_present)) return PLL_ATTRIB_ARCH_AVX2; else if (PLL_STAT(avx_present)) return PLL_ATTRIB_ARCH_AVX; else if (PLL_STAT(sse3_present)) return PLL_ATTRIB_ARCH_SSE; else return PLL_ATTRIB_ARCH_CPU; } pll_partition_t * build_partition_from_file( const raxml::Model& model, Tree_Numbers& nums, const int num_sites, const bool repeats) { assert(nums.tip_nodes); // nums must have been initialized correctly auto attributes = simd_autodetect(); if (repeats) { attributes |= PLL_ATTRIB_SITE_REPEATS; } else { attributes |= PLL_ATTRIB_PATTERN_TIP; } auto partition = pll_partition_create(nums.tip_nodes, nums.inner_nodes * 3, //number of extra clv buffers: 3 for every direction on the node model.num_states(), num_sites, 1, nums.branches, model.num_ratecats(), (nums.inner_nodes * 3) + nums.tip_nodes, /* number of scaler buffers */ attributes); if (!partition) { throw std::runtime_error{std::string("Could not create partition (build_partition_from_file). pll_errmsg: ") + pll_errmsg}; } std::vector<double> rate_cats(model.num_ratecats(), 0.0); /* compute the discretized category rates from a gamma distribution with alpha shape */ pll_compute_gamma_cats( model.alpha(), model.num_ratecats(), &rate_cats[0], PLL_GAMMA_RATES_MEAN); pll_set_frequencies(partition, 0, &(model.base_freqs(0)[0])); pll_set_subst_params( partition, 0, &(model.subst_rates(0)[0])); pll_set_category_rates( partition, &rate_cats[0]); // if (repeats) { // pll_resize_repeats_lookup(partition, ( REPEATS_LOOKUP_SIZE ) * 10); // } return partition; } void file_check(const std::string& file_path) { std::ifstream file(file_path.c_str()); if (!file.good()) { throw std::runtime_error{std::string("file_check failed: ") + file_path}; } file.close(); } <commit_msg>fix for gcc 7 compile error<commit_after>#include "io/file_io.hpp" #include <stdexcept> #include <fstream> #include <functional> #include "core/pll/pllhead.hpp" #include "seq/MSA.hpp" #include "util/constants.hpp" #include "core/pll/pll_util.hpp" #include "util/logging.hpp" typedef struct fasta_record_s { pll_fasta_t* file; char * sequence = NULL; char * header = NULL; } fasta_record_t; static unsigned long length_till_newl(char* line) { char c; unsigned long length = 0; while((c = *line++) and (c != '\n' or c != '\r')) { ++length; } return length; } int pll_fasta_fseek(pll_fasta_t* fd, const long int offset, const int whence) { auto status = fseek(fd->fp, offset, whence); /* reset stripped char frequencies */ fd->stripped_count = 0; for(size_t i=0; i<256; i++) { fd->stripped[i] = 0; } fd->line[0] = 0; if (!fgets(fd->line, PLL_LINEALLOC, fd->fp)) { pll_errno = PLL_ERROR_FILE_SEEK; snprintf(pll_errmsg, 200, "Unable to rewind and cache data"); return -1; } fd->lineno = 1; return status; } static void epa_read_fasta( const std::string& msa_file, std::function<void(fasta_record_t&)> fn, const size_t offset=0, const size_t span=std::numeric_limits<size_t>::max()) { fasta_record_t record; /* open the file */ record.file = pll_fasta_open(msa_file.c_str(), pll_map_fasta); if (!record.file) { throw std::runtime_error{std::string("Cannot open file ") + msa_file}; } if(pll_fasta_fseek(record.file, offset, SEEK_SET)) { throw std::runtime_error{"Unable to fseek on the fasta file."}; } long sequence_length; long header_length; long sequence_number; /* read sequences and make sure they are all of the same length */ int sites = 0; size_t read_seqs = 0; /* read the first sequence seperately, so that the MSA object can be constructed */ if (PLL_FAILURE == pll_fasta_getnext( record.file, &record.header, &header_length, &record.sequence, &sequence_length, &sequence_number)) { throw std::runtime_error{std::string("fasta_getnext failed: ") + pll_errmsg}; } sites = sequence_length; if (sites == -1 || sites == 0) { throw std::runtime_error{"Unable to read MSA record: invalid sequence length"}; } fn(record); ++read_seqs; free(record.sequence); free(record.header); /* read the rest */ while(read_seqs < span and pll_fasta_getnext(record.file, &record.header, &header_length, &record.sequence, &sequence_length, &sequence_number)) { if (sites && sites != sequence_length) { throw std::runtime_error{"MSA file does not contain equal size sequences"}; } if (!sites) sites = sequence_length; fn(record); ++read_seqs; free(record.sequence); free(record.header); } // if (pll_errno != PLL_ERROR_FILE_EOF) { // throw std::runtime_error{std::string("Error while reading file: ") + msa_file}; // } pll_fasta_close(record.file); } std::vector<size_t> get_offsets(const std::string& msa_file, MSA& msa) { std::vector<size_t> result; epa_read_fasta(msa_file, [&](auto& record){ result.push_back(ftell(record.file->fp) - length_till_newl(record.file->line)); msa.append(record.header, ""); }); return result; } MSA build_MSA_from_file(const std::string& msa_file, const size_t offset, const size_t span) { MSA msa; epa_read_fasta( msa_file, [&](auto& record){ msa.append(record.header, record.sequence); }, offset, span); return msa; } pll_utree_s * build_tree_from_file(const std::string& tree_file, Tree_Numbers& nums) { pll_utree_t * tree; pll_rtree_t * rtree; // load the tree unrooted if (!(rtree = pll_rtree_parse_newick(tree_file.c_str()))) { if (!(tree = pll_utree_parse_newick(tree_file.c_str()))) { throw std::runtime_error{"Treeparsing failed!"}; } } else { tree = pll_rtree_unroot(rtree); pll_rtree_destroy(rtree, nullptr); /* optional step if using default PLL clv/pmatrix index assignments */ pll_utree_reset_template_indices(get_root(tree), tree->tip_count); } if (tree->tip_count < 3) { throw std::runtime_error{"Number of tip nodes too small"}; } nums = Tree_Numbers(tree->tip_count); set_missing_branch_lengths(tree, DEFAULT_BRANCH_LENGTH); return tree; } static unsigned int simd_autodetect() { if (PLL_STAT(avx2_present)) return PLL_ATTRIB_ARCH_AVX2; else if (PLL_STAT(avx_present)) return PLL_ATTRIB_ARCH_AVX; else if (PLL_STAT(sse3_present)) return PLL_ATTRIB_ARCH_SSE; else return PLL_ATTRIB_ARCH_CPU; } pll_partition_t * build_partition_from_file( const raxml::Model& model, Tree_Numbers& nums, const int num_sites, const bool repeats) { assert(nums.tip_nodes); // nums must have been initialized correctly auto attributes = simd_autodetect(); if (repeats) { attributes |= PLL_ATTRIB_SITE_REPEATS; } else { attributes |= PLL_ATTRIB_PATTERN_TIP; } auto partition = pll_partition_create(nums.tip_nodes, nums.inner_nodes * 3, //number of extra clv buffers: 3 for every direction on the node model.num_states(), num_sites, 1, nums.branches, model.num_ratecats(), (nums.inner_nodes * 3) + nums.tip_nodes, /* number of scaler buffers */ attributes); if (!partition) { throw std::runtime_error{std::string("Could not create partition (build_partition_from_file). pll_errmsg: ") + pll_errmsg}; } std::vector<double> rate_cats(model.num_ratecats(), 0.0); /* compute the discretized category rates from a gamma distribution with alpha shape */ pll_compute_gamma_cats( model.alpha(), model.num_ratecats(), &rate_cats[0], PLL_GAMMA_RATES_MEAN); pll_set_frequencies(partition, 0, &(model.base_freqs(0)[0])); pll_set_subst_params( partition, 0, &(model.subst_rates(0)[0])); pll_set_category_rates( partition, &rate_cats[0]); // if (repeats) { // pll_resize_repeats_lookup(partition, ( REPEATS_LOOKUP_SIZE ) * 10); // } return partition; } void file_check(const std::string& file_path) { std::ifstream file(file_path.c_str()); if (!file.good()) { throw std::runtime_error{std::string("file_check failed: ") + file_path}; } file.close(); } <|endoftext|>
<commit_before><commit_msg>[test...diffusion-ipdg] fix element_integral usage<commit_after><|endoftext|>
<commit_before>#pragma once #include "PinNames.h" // ** PIN DECLARATIONS ============================= ** // This defines the mbed pins used for the primary SPI data bus. const PinName RJ_SPI_MOSI = p5; const PinName RJ_SPI_MISO = p6; const PinName RJ_SPI_SCK = p7; // This defines the Accel/Gyro's interrupt pin. const PinName RJ_MPU_INT = p8; // This defines the I/O Expander's interrupt pin. const PinName RJ_IOEXP_INT = p9; // This defines the Radio Transceiver's interrupt pin. const PinName RJ_RADIO_INT = p10; // This defines the FPGA's `PROG_B` pin. // 10k pull-up to 2.5V const PinName RJ_FPGA_PROG_B = p11; // This defines the robot's Green `RDY` LED. This should always be configured as // open drain output. const PinName RJ_RDY_LED = p12; // This defines the FPGA's Chip Select pin. This should always be configured as const PinName RJ_FPGA_nCS = p13; // This defines the Kicker Board's Chip Select pin. This should always be const PinName RJ_KICKER_nCS = p14; // This defines the ball sensor's detector pin. This should always be configured // analog input const PinName RJ_BALL_DETECTOR = p15; // This defines the Battery Voltage pin. This should always be configured as an // analog input const PinName RJ_BATT_SENSE = p16; // This defines the +5V Voltage pin. This should always be configured as an // analog input const PinName RJ_5V_SENSE = p17; // This defines the Piezo Speaker's pin. const PinName RJ_SPEAKER = p18; // This defines the FPGA's `INIT_B` pin. // 10k pull-up to 3.3V (HSWAP_EN = NC?) const PinName RJ_FPGA_INIT_B = p19; // This defines one of the mbed's unused pins. It is not connected to anything // on the 2015 Control Board rev. 1. const PinName RJ_KICKER_nRESET = p20; // This defines the pin used for communicating with the Mechanical Base's ID#. const PinName RJ_BASE_ID = p21; // This defines the radio's `TX` LED for transmitting packets. This should // open drain const PinName RJ_TX_LED = p22; // This defines the radio's `RX` LED for receiving packets. This should always // open drain const PinName RJ_RX_LED = p23; // This defines the `BALL` LED for ball detection. This should always be // open drain const PinName RJ_BALL_LED = p24; // This defines the pin used for driving the Breakbeam's Ball Emitter LED. const PinName RJ_BALL_EMIT = p25; // This defines the pin used for writing color values to the `STATUS` LED. const PinName RJ_NEOPIXEL = p26; // This defines the set of pins used for the primary I2C data bus. const PinName RJ_I2C_SCL = p27; const PinName RJ_I2C_SDA = p28; // This defines the radio transceiver's Chip Select pin. This should always be const PinName RJ_RADIO_nCS = p29; // This defines the FPGA's `DONE` pin. // 300 ohm pull-up to 2.5V const PinName RJ_FPGA_DONE = p30; // This defines the pins used for a `Serial Connection` over the mbed's USB port // (for use with a virtual serial connection to a computer) #define RJ_SERIAL_RXTX MBED_UARTUSB // ** IO-EXPANDER PINS ** ============================= ** const int RJ_IO_EXPANDER_I2C_ADDRESS = 0x42; // Port A bit masks const uint8_t RJ_IOEXP_A0 = 0; const uint8_t RJ_IOEXP_A1 = 1; const uint8_t RJ_IOEXP_A2 = 2; const uint8_t RJ_IOEXP_A3 = 3; const uint8_t RJ_IOEXP_A4 = 4; const uint8_t RJ_IOEXP_A5 = 5; const uint8_t RJ_IOEXP_A6 = 6; const uint8_t RJ_IOEXP_A7 = 7; // Port B bit masks const uint8_t RJ_IOEXP_B0 = 8; const uint8_t RJ_IOEXP_B1 = 9; const uint8_t RJ_IOEXP_B2 = 10; const uint8_t RJ_IOEXP_B3 = 11; const uint8_t RJ_IOEXP_B4 = 12; const uint8_t RJ_IOEXP_B5 = 13; const uint8_t RJ_IOEXP_B6 = 14; const uint8_t RJ_IOEXP_B7 = 15; enum IOExpanderPin { RJ_HEX_SWITCH_BIT0 = RJ_IOEXP_A0, RJ_HEX_SWITCH_BIT1 = RJ_IOEXP_A1, RJ_HEX_SWITCH_BIT2 = RJ_IOEXP_A2, RJ_HEX_SWITCH_BIT3 = RJ_IOEXP_A3, RJ_DIP_SWITCH_1 = RJ_IOEXP_A4, RJ_DIP_SWITCH_2 = RJ_IOEXP_A5, RJ_DIP_SWITCH_3 = RJ_IOEXP_A6, RJ_PUSHBUTTON = RJ_IOEXP_A7, RJ_ERR_LED_M1 = RJ_IOEXP_B0, RJ_ERR_LED_M2 = RJ_IOEXP_B1, RJ_ERR_LED_M3 = RJ_IOEXP_B2, RJ_ERR_LED_M4 = RJ_IOEXP_B3, RJ_ERR_LED_MPU = RJ_IOEXP_B4, RJ_ERR_LED_BSENSE = RJ_IOEXP_B5, RJ_ERR_LED_DRIB = RJ_IOEXP_B6, RJ_ERR_LED_RADIO = RJ_IOEXP_B7, }; constexpr uint16_t IOExpanderErrorLEDMask = 0xFF00; <commit_msg>fixed status led pin mapping<commit_after>#pragma once #include "PinNames.h" // ** PIN DECLARATIONS ============================= ** // This defines the mbed pins used for the primary SPI data bus. const PinName RJ_SPI_MOSI = p5; const PinName RJ_SPI_MISO = p6; const PinName RJ_SPI_SCK = p7; // This defines the Accel/Gyro's interrupt pin. const PinName RJ_MPU_INT = p8; // This defines the I/O Expander's interrupt pin. const PinName RJ_IOEXP_INT = p9; // This defines the Radio Transceiver's interrupt pin. const PinName RJ_RADIO_INT = p10; // This defines the FPGA's `PROG_B` pin. // 10k pull-up to 2.5V const PinName RJ_FPGA_PROG_B = p11; // This defines the robot's Green `RDY` LED. This should always be configured as // open drain output. const PinName RJ_RDY_LED = p12; // This defines the FPGA's Chip Select pin. This should always be configured as const PinName RJ_FPGA_nCS = p13; // This defines the Kicker Board's Chip Select pin. This should always be const PinName RJ_KICKER_nCS = p14; // This defines the ball sensor's detector pin. This should always be configured // analog input const PinName RJ_BALL_DETECTOR = p15; // This defines the Battery Voltage pin. This should always be configured as an // analog input const PinName RJ_BATT_SENSE = p16; // This defines the +5V Voltage pin. This should always be configured as an // analog input const PinName RJ_5V_SENSE = p17; // This defines the Piezo Speaker's pin. const PinName RJ_SPEAKER = p18; // This defines the FPGA's `INIT_B` pin. // 10k pull-up to 3.3V (HSWAP_EN = NC?) const PinName RJ_FPGA_INIT_B = p19; // This defines one of the mbed's unused pins. It is not connected to anything // on the 2015 Control Board rev. 1. const PinName RJ_KICKER_nRESET = p20; // This defines the pin used for communicating with the Mechanical Base's ID#. const PinName RJ_BASE_ID = p21; // This defines the radio's `TX` LED for transmitting packets. This should // open drain const PinName RJ_TX_LED = p22; // This defines the radio's `RX` LED for receiving packets. This should always // open drain const PinName RJ_RX_LED = p23; // This defines the `BALL` LED for ball detection. This should always be // open drain const PinName RJ_BALL_LED = p24; // This defines the pin used for driving the Breakbeam's Ball Emitter LED. const PinName RJ_BALL_EMIT = p25; // This defines the pin used for writing color values to the `STATUS` LED. const PinName RJ_NEOPIXEL = p26; // This defines the set of pins used for the primary I2C data bus. const PinName RJ_I2C_SCL = p27; const PinName RJ_I2C_SDA = p28; // This defines the radio transceiver's Chip Select pin. This should always be const PinName RJ_RADIO_nCS = p29; // This defines the FPGA's `DONE` pin. // 300 ohm pull-up to 2.5V const PinName RJ_FPGA_DONE = p30; // This defines the pins used for a `Serial Connection` over the mbed's USB port // (for use with a virtual serial connection to a computer) #define RJ_SERIAL_RXTX MBED_UARTUSB // ** IO-EXPANDER PINS ** ============================= ** const int RJ_IO_EXPANDER_I2C_ADDRESS = 0x42; // Port A bit masks const uint8_t RJ_IOEXP_A0 = 0; const uint8_t RJ_IOEXP_A1 = 1; const uint8_t RJ_IOEXP_A2 = 2; const uint8_t RJ_IOEXP_A3 = 3; const uint8_t RJ_IOEXP_A4 = 4; const uint8_t RJ_IOEXP_A5 = 5; const uint8_t RJ_IOEXP_A6 = 6; const uint8_t RJ_IOEXP_A7 = 7; // Port B bit masks const uint8_t RJ_IOEXP_B0 = 8; const uint8_t RJ_IOEXP_B1 = 9; const uint8_t RJ_IOEXP_B2 = 10; const uint8_t RJ_IOEXP_B3 = 11; const uint8_t RJ_IOEXP_B4 = 12; const uint8_t RJ_IOEXP_B5 = 13; const uint8_t RJ_IOEXP_B6 = 14; const uint8_t RJ_IOEXP_B7 = 15; enum IOExpanderPin { RJ_HEX_SWITCH_BIT0 = RJ_IOEXP_A0, RJ_HEX_SWITCH_BIT1 = RJ_IOEXP_A1, RJ_HEX_SWITCH_BIT2 = RJ_IOEXP_A2, RJ_HEX_SWITCH_BIT3 = RJ_IOEXP_A3, RJ_DIP_SWITCH_1 = RJ_IOEXP_A4, RJ_DIP_SWITCH_2 = RJ_IOEXP_A5, RJ_DIP_SWITCH_3 = RJ_IOEXP_A6, RJ_PUSHBUTTON = RJ_IOEXP_A7, RJ_ERR_LED_M1 = RJ_IOEXP_B1, RJ_ERR_LED_M2 = RJ_IOEXP_B0, RJ_ERR_LED_M3 = RJ_IOEXP_B5, RJ_ERR_LED_M4 = RJ_IOEXP_B7, RJ_ERR_LED_MPU = RJ_IOEXP_B6, RJ_ERR_LED_BSENSE = RJ_IOEXP_B4, RJ_ERR_LED_DRIB = RJ_IOEXP_B3, RJ_ERR_LED_RADIO = RJ_IOEXP_B2, }; constexpr uint16_t IOExpanderErrorLEDMask = 0xFF00; <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <cmath> #include <ctime> #include <string> #include <vector> #include <fstream> #include <algorithm> #include <Eigen/Dense> using Eigen::MatrixXd; using Eigen::VectorXd; using namespace std; const int MATCH_MIN = 0; const int MATCH_MAX = 1; /* * readMatrix * read a file into a matrix object * file must have matrix dimension as first line * matrix must be square */ void readMatrix(const char* filename, MatrixXd& m) { ifstream fin(filename); if (!fin) { cout << "Cannot open file." << endl; return; } // read in matrix dimensions and // create a matrix of that size int n_rows, n_cols; fin >> n_rows >> n_cols; MatrixXd temp(n_rows, n_cols); // read elements into the temporary matrix for (int i=0; i<n_rows; i++) { for (int j=0; j<n_cols; j++) { fin >> temp(i,j); } } fin.close(); // if the dimensions are equal (square matrix), we're done // else, have to figure out larger dimension and pad with matrix max if (n_rows == n_cols) { m = temp; } else { float max_elem = temp.maxCoeff(); // find the max element float dim = max(n_rows, n_cols); // find the dimension for the new, square matrix m.resize(dim,dim); // fill the matrix with the elements from temp and pad with max element for (int i=0; i < dim; i++) { for (int j=0; j < dim; j++) { if (i >= n_rows || j >= n_cols) m(i,j) = max_elem; else m(i,j) = temp(i,j); } } } } /* * reduce * reduces matrix based on row and column minimums */ void reduce(MatrixXd& m) { // subtract row minimum from each row for (int i=0; i<m.rows(); i++) { float minElement = m.row(i).minCoeff(); VectorXd rMinusMin(m.rows()); rMinusMin.fill(-minElement); m.row(i) += rMinusMin; } } /* * hasMark * if there is a starred/primed zero in the given row/col, returns it's index * else, returns -1 */ int hasMark(VectorXd& v) { for (int i=0; i<v.size(); i++) { if (v(i)) { return i; } } return -1; } /* * swapStarsAndPrimes * Swap stars and primes based on step 5 of Hungarian algorithm * Z0 is uncovered primed zero we've found * Z1 is the stared zero in the column of Z0 (if any) * Z2 is the primed zero in the row of Z1 (will always be one) * ...continue series until we reach a primed zero with no starred zero in its column * Unstar each starred zero, star each primed zero, erase all primes and uncover every line in the matrix */ void swapStarsAndPrimes(int i, int j, MatrixXd& stars, MatrixXd& primes) { int primeRow = i; int primeCol = j; bool done = false; while (!done) { // find row index of row that has a 0* in the same col as the current 0' VectorXd col = stars.col(primeCol); int starInPrimeColRow = hasMark(col); if (starInPrimeColRow < 0) { // star the prime we're looking at primes(primeRow, primeCol) = 0; stars(primeRow, primeCol) = 1; done = true; } else { // find which col has a 0' in the same row as z1 VectorXd row = primes.row(starInPrimeColRow); int primeInStarRowCol = hasMark(row); // star first primed zero primes(primeRow, primeCol) = 0; stars(primeRow, primeCol) = 1; //primes(starInPrimeColRow, primeInStarRowCol) = 0; //stars(starInPrimeColRow, primeInStarRowCol) = 1; // unstar starred zero stars(starInPrimeColRow, primeCol) = 0; // set index of last prime, will check it's column for 0*s next primeRow = starInPrimeColRow; primeCol = primeInStarRowCol; } } // clear primes primes.fill(0); } /* * findMatching * implementation of the Hungarian matching algorithm * referenced from: http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html */ void findMatching(MatrixXd& m, MatrixXd& result, int type) { MatrixXd n = m; // make a copy of m for reducing int dim = n.rows(); // dimension of matrix, used for checking if we've reduced // the matrix enough yet MatrixXd stars(m.rows(), m.cols()); // matrix for storing our "starred" 0s (0*) stars.fill(0); MatrixXd primes(m.rows(), m.cols()); // matrix for storing our "primed" 0s (0') primes.fill(0); VectorXd rowCover(m.rows()); // keep track of which rows are "covered" rowCover.fill(0); VectorXd colCover(m.cols()); // keep track of which columns are "covered" colCover.fill(0); // to do maximization rather than minimization, we have to // transform the matrix by subtracting every value from the maximum if (type == MATCH_MAX) { float max = n.maxCoeff(); MatrixXd maxMat(n.rows(), n.cols()); maxMat.fill(max); n = maxMat - n; } // Step 1 // Reduce matrix reduce(n); // Step 2 // Find a zero in the matrix. If there is no starred zero in // its row or column, star Z. Repeat for each element in the matrix. for (int i=0; i<n.rows(); i++) { for (int j=0; j<n.cols(); j++) { if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) { stars(i,j) = 1; rowCover(i) = 1; colCover(j) = 1; } } } // covers need to be cleared for following steps rowCover.fill(0); colCover.fill(0); while (true) { // Step 3 // Cover all columns that have a starred zero // If the number of columns with starred zeroes equals the matrix // dimensions, we are done! Otherwise, move on to step 4. step3: for (int j=0; j<n.cols(); j++) { VectorXd col = stars.col(j); if (hasMark(col) >= 0) { colCover(j) = 1; } } if (colCover.sum() == dim) { result = stars; return; } // Step 4 // Find a non-covered zero and prime it step4: for (int i=0; i<n.rows(); i++) { for (int j=0; j<n.cols(); j++) { if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) { primes(i,j) = 1; // if no starred zero in the row... VectorXd row = stars.row(i); if (hasMark(row) < 0) { // Step 5 // swap stars and primes swapStarsAndPrimes(i, j, stars, primes); // clear lines rowCover.fill(0); colCover.fill(0); goto step3; } else { // cover row rowCover(i) = 1; // uncover column of the starred zero in the same row int col = hasMark(row); colCover(col) = 0; } } } } // Step 6 // Should now be no more uncovered zeroes // Get the minimum uncovered element float min = 1000000; for (int i=0; i<n.rows(); i++) { for (int j=0; j<n.cols(); j++) { if (!rowCover(i) && !colCover(j) && n(i,j) < min) { min = n(i,j); } } } // Subtract minimum from uncovered elements, add it to elements covered twice for (int i=0; i<n.rows(); i++) { for (int j=0; j<n.cols(); j++) { if (!rowCover(i) && !colCover(j)) { n(i,j) -= min; } else if (rowCover(i) && colCover(j)) { n(i,j) += min; } } } goto step4; } } /* * main() */ int main(int argc, char *argv[]) { if (argc != 2) { cout << "Usage: ./a.out [matrixfile]" << endl; return 0; } // times clock_t start, end; float elapsedTime; // random seed srand((unsigned)time(0)); // start time start = clock(); // read in the matrix file MatrixXd m(1,1); readMatrix(argv[1], m); // create an empty matrix to put the result in MatrixXd result(m.rows(), m.cols()); result.fill(0); // run the Hungarian (Munkres) algorithm to find the maximal matching findMatching(m, result, MATCH_MIN); MatrixXd mask = m.cwiseProduct(result); int sum = mask.sum(); cout << "ORIGINAL MATRIX" << endl; cout << m << endl; cout << endl; cout << "ASSIGNMENT RESULT" << endl; cout << result << endl; cout << endl; cout << "FINAL SUM" << endl; cout << sum << endl; // stop time end = clock(); elapsedTime = (float)(end - start) / CLOCKS_PER_SEC; cout << "Completed in: " << elapsedTime << " s" << endl; return 0; } <commit_msg>New hungarian algorithm implementation<commit_after>#include <cstdlib> #include <iostream> #include <cmath> #include <ctime> #include <string> #include <vector> #include <fstream> #include <algorithm> #include <Eigen/Dense> using Eigen::MatrixXd; using Eigen::VectorXd; using namespace std; void findMatching(MatrixXd& m, VectorXd& assignment); void step2a(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim); void step2b(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim); void step3(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim); void step4(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim, int row, int col); void step5(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim); void buildassignmentvector(VectorXd& assignment, MatrixXd& starMatrix, int nOfRows, int nOfColumns); void findMatching(MatrixXd& m, VectorXd& assignment) { int nOfRows = m.rows(); int nOfColumns = m.cols(); int minDim, row, col; double value, minValue; MatrixXd starMatrix(m.rows(), m.cols()); MatrixXd newStarMatrix(m.rows(), m.cols()); MatrixXd primeMatrix(m.rows(), m.cols()); VectorXd coveredColumns(m.rows()); VectorXd coveredRows(m.cols()); starMatrix.fill(0); newStarMatrix.fill(0); primeMatrix.fill(0); coveredColumns.fill(0); coveredRows.fill(0); assignment.fill(0); for (row = 0; row<nOfRows; row++) for (col = 0; col<nOfColumns; col++) if (m(row, col) < 0) throw std::invalid_argument("All matrix elements have to be positive!"); /* preliminary steps */ if (nOfRows <= nOfColumns) { minDim = nOfRows; for (row = 0; row<nOfRows; row++) { /* find the smallest element in the row */ minValue = m(row, 0); for (col = 0; col<nOfColumns; col++) { value = m(row, col); if (value < minValue) minValue = value; } /* subtract the smallest element from each element of the row */ for (col = 0; col<nOfColumns; col++) m(row, col) -= minValue; } /* Steps 1 and 2a */ for (row = 0; row<nOfRows; row++) for (col = 0; col<nOfColumns; col++) if (m(row, col) == 0) if (!coveredColumns(col)) { starMatrix(row, col) = true; coveredColumns(col) = true; break; } } else /* if(nOfRows > nOfColumns) */ { minDim = nOfColumns; for (col = 0; col<nOfColumns; col++) { /* find the smallest element in the column */ minValue = m(0, col); for (row = 0; row<nOfRows; row++) { value = m(row, col); if (value < minValue) minValue = value; } /* subtract the smallest element from each element of the column */ for (row = 0; row<nOfRows; row++) m(row, col) -= minValue; } /* Steps 1 and 2a */ for (col = 0; col<nOfColumns; col++) for (row = 0; row<nOfRows; row++) if (m(row, col) == 0) if (!coveredRows(row)) { starMatrix(row, col) = true; coveredColumns(col) = true; coveredRows(row) = true; break; } coveredRows.fill(0); } /* move to step 2b */ step2b(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); return; } void step2a(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim) { /* cover every column containing a starred zero */ for (int col = 0; col<nOfColumns; col++) { for (int row = 0; row < nOfRows; row++) { if (starMatrix(row, col)) { coveredColumns(col) = true; break; } } } /* move to step 3 */ step2b(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void step2b(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim) { /* count covered columns */ int nOfCoveredColumns = 0; for (int col = 0; col<nOfColumns; col++) if (coveredColumns(col)) nOfCoveredColumns++; if (nOfCoveredColumns == minDim) { /* algorithm finished */ buildassignmentvector(assignment, starMatrix, nOfRows, nOfColumns); } else { /* move to step 3 */ step3(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } } void step3(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim) { int starCol; bool zerosFound = true; while (zerosFound) { zerosFound = false; for (int col = 0; col<nOfColumns; col++) if (!coveredColumns(col)) for (int row = 0; row<nOfRows; row++) if ((!coveredRows(row)) && (m(row, col) == 0)) { /* prime zero */ primeMatrix(row, col) = true; /* find starred zero in current row */ for (starCol = 0; starCol<nOfColumns; starCol++) if (starMatrix(row, starCol)) break; if (starCol == nOfColumns) /* no starred zero found */ { /* move to step 4 */ step4(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim, row, col); return; } else { coveredRows(row) = true; coveredColumns(starCol) = false; zerosFound = true; break; } } } /* move to step 5 */ step5(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void step4(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim, int row, int col) { int starRow, starCol, primeRow, primeCol; int nOfElements = nOfRows*nOfColumns; /* generate temporary copy of starMatrix */ for (int n = 0; n<nOfElements; n++) newStarMatrix(n) = starMatrix(n); /* star current zero */ newStarMatrix(row, col) = true; /* find starred zero in current column */ starCol = col; for (starRow = 0; starRow<nOfRows; starRow++) if (starMatrix(starRow, starCol)) break; while (starRow<nOfRows) { /* unstar the starred zero */ newStarMatrix(starRow, starCol) = false; /* find primed zero in current row */ primeRow = starRow; for (primeCol = 0; primeCol<nOfColumns; primeCol++) if (primeMatrix(primeRow, primeCol)) break; /* star the primed zero */ newStarMatrix(primeRow, primeCol) = true; /* find starred zero in current column */ starCol = primeCol; for (starRow = 0; starRow<nOfRows; starRow++) if (starMatrix(starRow, starCol)) break; } /* use temporary copy as new starMatrix */ /* delete all primes, uncover all rows */ for (int n = 0; n<nOfElements; n++) { primeMatrix(n) = false; starMatrix(n) = newStarMatrix(n); } for (int n = 0; n<nOfRows; n++) coveredRows(n) = false; /* move to step 2a */ step2a(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void step5(VectorXd& assignment, MatrixXd& m, MatrixXd& starMatrix, MatrixXd& newStarMatrix, MatrixXd& primeMatrix, VectorXd& coveredColumns, VectorXd& coveredRows, int nOfRows, int nOfColumns, int minDim) { double h, value; int row, col; /* find smallest uncovered element h */ h = std::numeric_limits<int>::max(); for (row = 0; row<nOfRows; row++) if (!coveredRows(row)) for (col = 0; col<nOfColumns; col++) if (!coveredColumns(col)) { value = m(row, col); if (value < h) h = value; } /* add h to each covered row */ for (row = 0; row<nOfRows; row++) if (coveredRows(row)) for (col = 0; col<nOfColumns; col++) m(row, col) += h; /* subtract h from each uncovered column */ for (col = 0; col<nOfColumns; col++) if (!coveredColumns(col)) for (row = 0; row<nOfRows; row++) m(row, col) -= h; /* move to step 3 */ step3(assignment, m, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void buildassignmentvector(VectorXd& assignment, MatrixXd& starMatrix, int nOfRows, int nOfColumns) { for (int row = 0; row<nOfRows; row++) for (int col = 0; col<nOfColumns; col++) if (starMatrix(row, col)) { assignment(row) = col; break; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: LConnection.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-09-08 16:20:00 $ * * 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_EVOAB_LCONNECTION_HXX_ #include "LConnection.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_ #include "LDatabaseMetaData.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_ #include "LCatalog.hxx" #endif #ifndef _CONNECTIVITY_RESOURCE_HRC_ #include "Resource.hrc" #endif #ifndef _CONNECTIVITY_MODULECONTEXT_HXX_ #include "ModuleContext.hxx" #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _URLOBJ_HXX //autogen wg. INetURLObject #include <tools/urlobj.hxx> #endif #ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_ #include "LPreparedStatement.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_ #include "LStatement.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _DBHELPER_DBCHARSET_HXX_ #include <connectivity/dbcharset.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX #include "LDebug.hxx" #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif using namespace connectivity::evoab; using namespace connectivity::file; using namespace vos; typedef connectivity::file::OConnection OConnection_B; //------------------------------------------------------------------------------ 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::lang; ::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ ) { ::rtl::OUString aExceptionType = aExceptionType_; if( aExceptionType.getLength() == 0 ) aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) ); ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) ); aTypeLine += aExceptionType; ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) ); aMessageLine += ::rtl::OUString( e.Message ); ::rtl::OUString aMsg(aTypeLine); aMsg += aMessageLine; return aMsg; } // Exception type unknown ::rtl::OUString implGetExceptionMsg( Exception& e ) { ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() ); return aMsg; } // -------------------------------------------------------------------------------- OEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver) ,m_bFixedLength(sal_False) ,m_bHeaderLine(sal_True) ,m_cFieldDelimiter(',') ,m_cStringDelimiter('"') ,m_cDecimalDelimiter('.') ,m_cThousandDelimiter(' ') { // Initialise m_aColumnAlias. m_aColumnAlias.setAlias(_pDriver->getFactory()); } //----------------------------------------------------------------------------- OEvoabConnection::~OEvoabConnection() { } // XServiceInfo // -------------------------------------------------------------------------------- IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection") //----------------------------------------------------------------------------- void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException) { osl_incrementInterlockedCount( &m_refCount ); EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url ); ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand(); ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath(); ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS()); ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX()); aArg2 += aWorkingDirPath; aArg2 += getDriver()->getEvoFolderListFileName(); OArgumentList aArgs(2,&aArg1,&aArg2); EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand ); EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath ); EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 ); EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 ); OProcess aApp( aCLICommand,aWorkingDirPath); OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs); DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards"); Sequence<PropertyValue> aDriverParam; ::std::vector<PropertyValue> aParam; aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE)); ::dbtools::OCharsetMap aLookupIanaName; ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0, makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE)); // build a new parameter sequence from the original parameters, appended b the new parameters from above PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0]; aDriverParam = ::comphelper::concatSequences( info, Sequence< PropertyValue >( pParams, aParam.size() ) ); // transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..." // sal_Int32 nLen = url.indexOf(':'); nLen = url.indexOf(':',nLen+1); ::rtl::OUString aAddrbookURI(url.copy(nLen+1)); // Get Scheme nLen = aAddrbookURI.indexOf(':'); ::rtl::OUString aAddrbookScheme; if ( nLen == -1 ) { // There isn't any subschema: - but could be just subschema if ( aAddrbookURI.getLength() > 0 ) { aAddrbookScheme= aAddrbookURI; } else { OSL_TRACE( "No subschema given!!!\n"); ::dbtools::throwGenericSQLException( ::rtl::OUString::createFromAscii("No subschema provided"),NULL); } } else { aAddrbookScheme = aAddrbookURI.copy(0, nLen); } EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI ); EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme ); // // Now we have a URI convert it to a Evolution CLI flat file URI // // The Mapping being used is: // // * for Evolution // "sdbc:address:evolution:" -> "sdbc:flat:file:///(file path generated) rtl::OUString aEvoFlatURI; if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 ) { aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" )); } aEvoFlatURI += getDriver()->getWorkingDirURL(); EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI ); //setURL(aEvoFlatURI); m_aEvoFlatURI = aEvoFlatURI; osl_decrementInterlockedCount( &m_refCount ); OConnection::construct(aEvoFlatURI,aDriverParam); } // -------------------------------------------------------------------------------- Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); Reference< XDatabaseMetaData > xMetaData = m_xMetaData; if(!xMetaData.is()) { xMetaData = new OEvoabDatabaseMetaData(this); m_xMetaData = xMetaData; } return xMetaData; } //------------------------------------------------------------------------------ ::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog() { ::osl::MutexGuard aGuard( m_aMutex ); Reference< XTablesSupplier > xTab = m_xCatalog; if(!xTab.is()) { OEvoabCatalog *pCat = new OEvoabCatalog(this); xTab = pCat; m_xCatalog = xTab; } return xTab; } // -------------------------------------------------------------------------------- Reference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); OEvoabStatement* pStmt = new OEvoabStatement(this); Reference< XStatement > xStmt = pStmt; m_aStatements.push_back(WeakReferenceHelper(*pStmt)); return xStmt; } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this); Reference< XPreparedStatement > xStmt = pStmt; pStmt->construct(sql); m_aStatements.push_back(WeakReferenceHelper(*pStmt)); return xStmt; } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); return NULL; } // ------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dr33 (1.4.52); FILE MERGED 2005/02/14 16:37:27 dr 1.4.52.1: #i42367# remove non-ASCII characters from C++ sources<commit_after>/************************************************************************* * * $RCSfile: LConnection.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2005-02-16 17:24:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_ #include "LConnection.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_ #include "LDatabaseMetaData.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_ #include "LCatalog.hxx" #endif #ifndef _CONNECTIVITY_RESOURCE_HRC_ #include "Resource.hrc" #endif #ifndef _CONNECTIVITY_MODULECONTEXT_HXX_ #include "ModuleContext.hxx" #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _URLOBJ_HXX //autogen wg. INetURLObject #include <tools/urlobj.hxx> #endif #ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_ #include "LPreparedStatement.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_ #include "LStatement.hxx" #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _DBHELPER_DBCHARSET_HXX_ #include <connectivity/dbcharset.hxx> #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include <connectivity/dbexception.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX #include "LDebug.hxx" #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif using namespace connectivity::evoab; using namespace connectivity::file; using namespace vos; typedef connectivity::file::OConnection OConnection_B; //------------------------------------------------------------------------------ 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::lang; ::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ ) { ::rtl::OUString aExceptionType = aExceptionType_; if( aExceptionType.getLength() == 0 ) aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) ); ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) ); aTypeLine += aExceptionType; ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) ); aMessageLine += ::rtl::OUString( e.Message ); ::rtl::OUString aMsg(aTypeLine); aMsg += aMessageLine; return aMsg; } // Exception type unknown ::rtl::OUString implGetExceptionMsg( Exception& e ) { ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() ); return aMsg; } // -------------------------------------------------------------------------------- OEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver) ,m_bFixedLength(sal_False) ,m_bHeaderLine(sal_True) ,m_cFieldDelimiter(',') ,m_cStringDelimiter('"') ,m_cDecimalDelimiter('.') ,m_cThousandDelimiter(' ') { // Initialise m_aColumnAlias. m_aColumnAlias.setAlias(_pDriver->getFactory()); } //----------------------------------------------------------------------------- OEvoabConnection::~OEvoabConnection() { } // XServiceInfo // -------------------------------------------------------------------------------- IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection") //----------------------------------------------------------------------------- void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException) { osl_incrementInterlockedCount( &m_refCount ); EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url ); ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand(); ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath(); ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS()); ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX()); aArg2 += aWorkingDirPath; aArg2 += getDriver()->getEvoFolderListFileName(); OArgumentList aArgs(2,&aArg1,&aArg2); EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand ); EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath ); EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 ); EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 ); OProcess aApp( aCLICommand,aWorkingDirPath); OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs); DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards"); Sequence<PropertyValue> aDriverParam; ::std::vector<PropertyValue> aParam; aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE)); ::dbtools::OCharsetMap aLookupIanaName; ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0, makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE)); aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE)); // build a new parameter sequence from the original parameters, appended by the new parameters from above PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0]; aDriverParam = ::comphelper::concatSequences( info, Sequence< PropertyValue >( pParams, aParam.size() ) ); // transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..." // sal_Int32 nLen = url.indexOf(':'); nLen = url.indexOf(':',nLen+1); ::rtl::OUString aAddrbookURI(url.copy(nLen+1)); // Get Scheme nLen = aAddrbookURI.indexOf(':'); ::rtl::OUString aAddrbookScheme; if ( nLen == -1 ) { // There isn't any subschema: - but could be just subschema if ( aAddrbookURI.getLength() > 0 ) { aAddrbookScheme= aAddrbookURI; } else { OSL_TRACE( "No subschema given!!!\n"); ::dbtools::throwGenericSQLException( ::rtl::OUString::createFromAscii("No subschema provided"),NULL); } } else { aAddrbookScheme = aAddrbookURI.copy(0, nLen); } EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI ); EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme ); // // Now we have a URI convert it to a Evolution CLI flat file URI // // The Mapping being used is: // // * for Evolution // "sdbc:address:evolution:" -> "sdbc:flat:file:///(file path generated) rtl::OUString aEvoFlatURI; if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 ) { aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" )); } aEvoFlatURI += getDriver()->getWorkingDirURL(); EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI ); //setURL(aEvoFlatURI); m_aEvoFlatURI = aEvoFlatURI; osl_decrementInterlockedCount( &m_refCount ); OConnection::construct(aEvoFlatURI,aDriverParam); } // -------------------------------------------------------------------------------- Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); Reference< XDatabaseMetaData > xMetaData = m_xMetaData; if(!xMetaData.is()) { xMetaData = new OEvoabDatabaseMetaData(this); m_xMetaData = xMetaData; } return xMetaData; } //------------------------------------------------------------------------------ ::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog() { ::osl::MutexGuard aGuard( m_aMutex ); Reference< XTablesSupplier > xTab = m_xCatalog; if(!xTab.is()) { OEvoabCatalog *pCat = new OEvoabCatalog(this); xTab = pCat; m_xCatalog = xTab; } return xTab; } // -------------------------------------------------------------------------------- Reference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); OEvoabStatement* pStmt = new OEvoabStatement(this); Reference< XStatement > xStmt = pStmt; m_aStatements.push_back(WeakReferenceHelper(*pStmt)); return xStmt; } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this); Reference< XPreparedStatement > xStmt = pStmt; pStmt->construct(sql); m_aStatements.push_back(WeakReferenceHelper(*pStmt)); return xStmt; } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(OConnection_B::rBHelper.bDisposed); return NULL; } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName NFIClusterClientModule.hpp // @Author LvSheng.Huang // @Date 2015-01-4 // @Module NFIClusterClientModule // // ------------------------------------------------------------------------- #ifndef _NFI_CLUSTER_CLIENT_MODULE_H_ #define _NFI_CLUSTER_CLIENT_MODULE_H_ #include <iostream> #include "NFILogicModule.h" #include "NFINetModule.h" struct ServerData { ServerData() { nGameID = 0; nPort = 0; strName = ""; strIP = ""; eServerType = NFST_NONE; eState = NFMsg::EServerState::EST_CRASH; } int nGameID; NF_SERVER_TYPE eServerType; std::string strIP; int nPort; std::string strName; NFMsg::EServerState eState; NF_SHARE_PTR<NFINetModule> mxNetModule; }; class NFIClusterClientModule { public: virtual void OnNetCreated(NF_SHARE_PTR<ServerData> xServerData) = 0; virtual bool Execute(const float fLastFrametime, const float fStartedTime) { ServerData* pServerData = mxServerMap.First(); while (pServerData) { pServerData->mxNetModule->Execute(fLastFrametime, fStartedTime); pServerData = mxServerMap.Next(); } return true; } void AddServer(const ServerData& xInfo) { NF_SHARE_PTR<ServerData> xServerData = mxServerMap.find(xInfo.nGameID); if (xServerData) { if (EServerState.EST_MAINTEN == xServerData->eState || EServerState.EST_CRASH == xServerData->eState) { //ˣ } else { //޸ϸ״̬ } } else { if (EServerState.EST_MAINTEN == xInfo->eState || EServerState.EST_CRASH == xInfo->eState) { // } else { //· xServerData = NF_SHARE_PTR<ServerData>(NF_NEW ServerData()); xServerData->nGameID = xInfo.nGameID; xServerData->eServerType = xInfo->eState; xServerData->strIP = xInfo.strIP; xServerData->strName = xInfo.strName; xServerData->eState = xInfo.eState; xServerData->mxNetModule = NF_SHARE_PTR<NFINetModule>(NF_NEW NFINetModule()); OnNetCreated(xServerData); //xServerData->m_pNetModule->Initialization(NFIMsgHead::NF_Head::NF_HEAD_LENGTH, this, &NFCGameServerNet_ServerModule::OnRecivePack, &NFCGameServerNet_ServerModule::OnSocketEvent, nMaxConnect, nPort, nCpus); mxServerMap.AddElement(xInfo.nGameID, xServerData); } } } virtual void SendByServerID(const int nServerID, const std::string& strData) { } virtual void SendBySuit(const std::string& strData) { } protected: private: NFMapEx<int, ServerData> mxServerMap; };<commit_msg>fixed<commit_after>// ------------------------------------------------------------------------- // @FileName NFIClusterClientModule.hpp // @Author LvSheng.Huang // @Date 2015-01-4 // @Module NFIClusterClientModule // // ------------------------------------------------------------------------- #ifndef _NFI_CLUSTER_CLIENT_MODULE_H_ #define _NFI_CLUSTER_CLIENT_MODULE_H_ #include <iostream> #include "NFILogicModule.h" #include "NFINetModule.h" struct ServerData { ServerData() { nGameID = 0; nPort = 0; strName = ""; strIP = ""; eServerType = NFST_NONE; eState = NFMsg::EServerState::EST_CRASH; } int nGameID; NF_SERVER_TYPE eServerType; std::string strIP; int nPort; std::string strName; NFMsg::EServerState eState; NF_SHARE_PTR<NFINetModule> mxNetModule; }; class NFIClusterClientModule { public: virtual void OnNetCreated(NF_SHARE_PTR<ServerData> xServerData) = 0; virtual bool Execute(const float fLastFrametime, const float fStartedTime) { ServerData* pServerData = mxServerMap.First(); while (pServerData) { pServerData->mxNetModule->Execute(fLastFrametime, fStartedTime); pServerData = mxServerMap.Next(); } return true; } void AddServer(const ServerData& xInfo) { NF_SHARE_PTR<ServerData> xServerData = mxServerMap.find(xInfo.nGameID); if (xServerData) { //µϢ } else { if (EServerState.EST_MAINTEN != xInfo->eState && EServerState.EST_CRASH != xInfo->eState) { //· xServerData = NF_SHARE_PTR<ServerData>(NF_NEW ServerData()); xServerData->nGameID = xInfo.nGameID; xServerData->eServerType = xInfo->eState; xServerData->strIP = xInfo.strIP; xServerData->strName = xInfo.strName; xServerData->eState = xInfo.eState; xServerData->mxNetModule = NF_SHARE_PTR<NFINetModule>(NF_NEW NFINetModule()); OnNetCreated(xServerData); //xServerData->m_pNetModule->Initialization(NFIMsgHead::NF_Head::NF_HEAD_LENGTH, this, &NFCGameServerNet_ServerModule::OnRecivePack, &NFCGameServerNet_ServerModule::OnSocketEvent, nMaxConnect, nPort, nCpus); mxServerMap.AddElement(xInfo.nGameID, xServerData); } } } virtual void SendByServerID(const int nServerID, const std::string& strData) { } virtual void SendBySuit(const std::string& strData) { } protected: private: NFMapEx<int, ServerData> mxServerMap; };<|endoftext|>
<commit_before>// Copyright 2013 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 "content/shell/browser/shell_browser_main_parts.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "cc/base/switches.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "content/public/common/url_constants.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_devtools_delegate.h" #include "content/shell/browser/shell_net_log.h" #include "content/shell/common/shell_switches.h" #include "grit/net_resources.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "ui/base/resource/resource_bundle.h" #include "url/gurl.h" #include "webkit/browser/quota/quota_manager.h" #if defined(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #include "content/shell/browser/shell_plugin_service_filter.h" #endif #if defined(OS_ANDROID) #include "components/breakpad/browser/crash_dump_manager_android.h" #include "net/android/network_change_notifier_factory_android.h" #include "net/base/network_change_notifier.h" #endif #if defined(USE_AURA) && defined(USE_X11) #include "ui/events/x/touch_factory_x11.h" #endif #if defined(OS_MACOSX) #include "components/breakpad/app/breakpad_mac.h" #endif #if defined(OS_POSIX) && !defined(OS_MACOSX) #include "components/breakpad/app/breakpad_linux.h" #endif #if defined(OS_WIN) #include "components/breakpad/app/breakpad_win.h" #endif namespace content { namespace { // Default quota for each origin is 5MB. const int kDefaultLayoutTestQuotaBytes = 5 * 1024 * 1024; GURL GetStartupURL() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kContentBrowserTest)) return GURL(); const CommandLine::StringVector& args = command_line->GetArgs(); #if defined(OS_ANDROID) // Delay renderer creation on Android until surface is ready. return GURL(); #endif if (args.empty()) return GURL("http://www.google.com/"); GURL url(args[0]); if (url.is_valid() && url.has_scheme()) return url; return net::FilePathToFileURL(base::FilePath(args[0])); } base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace ShellBrowserMainParts::ShellBrowserMainParts( const MainFunctionParams& parameters) : BrowserMainParts(), parameters_(parameters), run_message_loop_(true) {} ShellBrowserMainParts::~ShellBrowserMainParts() { } #if !defined(OS_MACOSX) void ShellBrowserMainParts::PreMainMessageLoopStart() { #if defined(USE_AURA) && defined(USE_X11) ui::TouchFactory::SetTouchDeviceListFromCommandLine(); #endif } #endif void ShellBrowserMainParts::PostMainMessageLoopStart() { #if defined(OS_ANDROID) base::MessageLoopForUI::current()->Start(); #endif } void ShellBrowserMainParts::PreEarlyInitialization() { #if defined(OS_ANDROID) net::NetworkChangeNotifier::SetFactory( new net::NetworkChangeNotifierFactoryAndroid()); CommandLine::ForCurrentProcess()->AppendSwitch( cc::switches::kCompositeToMailbox); #endif } void ShellBrowserMainParts::PreMainMessageLoopRun() { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { breakpad::InitCrashReporter(); #if defined(OS_ANDROID) base::FilePath crash_dumps_dir = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kCrashDumpsDir); crash_dump_manager_.reset(new breakpad::CrashDumpManager(crash_dumps_dir)); #endif } net_log_.reset(new ShellNetLog()); browser_context_.reset(new ShellBrowserContext(false, net_log_.get())); off_the_record_browser_context_.reset( new ShellBrowserContext(true, net_log_.get())); Shell::Initialize(); net::NetModule::SetResourceProvider(PlatformResourceProvider); devtools_delegate_.reset(new ShellDevToolsDelegate(browser_context_.get())); if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { Shell::CreateNewWindow(browser_context_.get(), GetStartupURL(), NULL, MSG_ROUTING_NONE, gfx::Size()); } if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { quota::QuotaManager* quota_manager = BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&quota::QuotaManager::SetTemporaryGlobalOverrideQuota, quota_manager, kDefaultLayoutTestQuotaBytes * quota::QuotaManager::kPerHostTemporaryPortion, quota::QuotaCallback())); #if defined(ENABLE_PLUGINS) PluginService* plugin_service = PluginService::GetInstance(); plugin_service_filter_.reset(new ShellPluginServiceFilter); plugin_service->SetFilter(plugin_service_filter_.get()); #endif } if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_message_loop_ = false; } } bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) { return !run_message_loop_; } void ShellBrowserMainParts::PostMainMessageLoopRun() { #if defined(USE_AURA) Shell::PlatformExit(); #endif if (devtools_delegate_) devtools_delegate_->Stop(); browser_context_.reset(); off_the_record_browser_context_.reset(); } } // namespace <commit_msg>Only initialize breakpad from browser main parts on posix<commit_after>// Copyright 2013 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 "content/shell/browser/shell_browser_main_parts.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "cc/base/switches.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "content/public/common/url_constants.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_browser_context.h" #include "content/shell/browser/shell_devtools_delegate.h" #include "content/shell/browser/shell_net_log.h" #include "content/shell/common/shell_switches.h" #include "grit/net_resources.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "ui/base/resource/resource_bundle.h" #include "url/gurl.h" #include "webkit/browser/quota/quota_manager.h" #if defined(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #include "content/shell/browser/shell_plugin_service_filter.h" #endif #if defined(OS_ANDROID) #include "components/breakpad/browser/crash_dump_manager_android.h" #include "net/android/network_change_notifier_factory_android.h" #include "net/base/network_change_notifier.h" #endif #if defined(USE_AURA) && defined(USE_X11) #include "ui/events/x/touch_factory_x11.h" #endif #if defined(OS_MACOSX) #include "components/breakpad/app/breakpad_mac.h" #endif #if defined(OS_POSIX) && !defined(OS_MACOSX) #include "components/breakpad/app/breakpad_linux.h" #endif #if defined(OS_WIN) #include "components/breakpad/app/breakpad_win.h" #endif namespace content { namespace { // Default quota for each origin is 5MB. const int kDefaultLayoutTestQuotaBytes = 5 * 1024 * 1024; GURL GetStartupURL() { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kContentBrowserTest)) return GURL(); const CommandLine::StringVector& args = command_line->GetArgs(); #if defined(OS_ANDROID) // Delay renderer creation on Android until surface is ready. return GURL(); #endif if (args.empty()) return GURL("http://www.google.com/"); GURL url(args[0]); if (url.is_valid() && url.has_scheme()) return url; return net::FilePathToFileURL(base::FilePath(args[0])); } base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace ShellBrowserMainParts::ShellBrowserMainParts( const MainFunctionParams& parameters) : BrowserMainParts(), parameters_(parameters), run_message_loop_(true) {} ShellBrowserMainParts::~ShellBrowserMainParts() { } #if !defined(OS_MACOSX) void ShellBrowserMainParts::PreMainMessageLoopStart() { #if defined(USE_AURA) && defined(USE_X11) ui::TouchFactory::SetTouchDeviceListFromCommandLine(); #endif } #endif void ShellBrowserMainParts::PostMainMessageLoopStart() { #if defined(OS_ANDROID) base::MessageLoopForUI::current()->Start(); #endif } void ShellBrowserMainParts::PreEarlyInitialization() { #if defined(OS_ANDROID) net::NetworkChangeNotifier::SetFactory( new net::NetworkChangeNotifierFactoryAndroid()); CommandLine::ForCurrentProcess()->AppendSwitch( cc::switches::kCompositeToMailbox); #endif } void ShellBrowserMainParts::PreMainMessageLoopRun() { #if defined(OS_POSIX) && !defined(OS_MACOSX) if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { breakpad::InitCrashReporter(); #if defined(OS_ANDROID) base::FilePath crash_dumps_dir = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kCrashDumpsDir); crash_dump_manager_.reset(new breakpad::CrashDumpManager(crash_dumps_dir)); #endif } #endif net_log_.reset(new ShellNetLog()); browser_context_.reset(new ShellBrowserContext(false, net_log_.get())); off_the_record_browser_context_.reset( new ShellBrowserContext(true, net_log_.get())); Shell::Initialize(); net::NetModule::SetResourceProvider(PlatformResourceProvider); devtools_delegate_.reset(new ShellDevToolsDelegate(browser_context_.get())); if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { Shell::CreateNewWindow(browser_context_.get(), GetStartupURL(), NULL, MSG_ROUTING_NONE, gfx::Size()); } if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) { quota::QuotaManager* quota_manager = BrowserContext::GetDefaultStoragePartition(browser_context()) ->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&quota::QuotaManager::SetTemporaryGlobalOverrideQuota, quota_manager, kDefaultLayoutTestQuotaBytes * quota::QuotaManager::kPerHostTemporaryPortion, quota::QuotaCallback())); #if defined(ENABLE_PLUGINS) PluginService* plugin_service = PluginService::GetInstance(); plugin_service_filter_.reset(new ShellPluginServiceFilter); plugin_service->SetFilter(plugin_service_filter_.get()); #endif } if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_message_loop_ = false; } } bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) { return !run_message_loop_; } void ShellBrowserMainParts::PostMainMessageLoopRun() { #if defined(USE_AURA) Shell::PlatformExit(); #endif if (devtools_delegate_) devtools_delegate_->Stop(); browser_context_.reset(); off_the_record_browser_context_.reset(); } } // namespace <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- dialogs/lookupcertificatesdialog.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 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 "lookupcertificatesdialog.h" #include "ui_lookupcertificatesdialog.h" #include <models/keylistmodel.h> #include <models/keylistsortfilterproxymodel.h> #include <utils/headerview.h> #include <gpgme++/key.h> #include <KLineEdit> #include <KLocale> #include <QTreeView> #include <QLayout> #include <QPushButton> #include <QHeaderView> #include <QLabel> #include <cassert> using namespace Kleo; using namespace Kleo::Dialogs; using namespace GpgME; static const int minimalSearchTextLength = 2; // ### TODO: make that KIOSK-able static const QHeaderView::ResizeMode resize_modes[AbstractKeyListModel::NumColumns] = { QHeaderView::Stretch, // Name QHeaderView::Stretch, // EMail QHeaderView::Fixed, // Valid From QHeaderView::Fixed, // Valid Until QHeaderView::Fixed, // Details QHeaderView::Fixed, // Fingerprint }; static void adjust_header( HeaderView * hv ) { for ( int i = 0, end = AbstractKeyListModel::NumColumns ; i < end ; ++i ) hv->setSectionResizeMode( i, resize_modes[i] ); } class LookupCertificatesDialog::Private { friend class ::Kleo::Dialogs::LookupCertificatesDialog; LookupCertificatesDialog * const q; public: explicit Private( LookupCertificatesDialog * qq ); ~Private(); private: void slotSelectionChanged() { enableDisableWidgets(); } void slotSearchTextChanged() { enableDisableWidgets(); } void slotSearchClicked() { emit q->searchTextChanged( ui.findED->text() ); } void slotDetailsClicked() { assert( q->selectedCertificates().size() == 1 ); emit q->detailsRequested( q->selectedCertificates().front() ); } void slotSaveAsClicked() { emit q->saveAsRequested( q->selectedCertificates() ); } void enableDisableWidgets(); QString searchText() const { return ui.findED->text().trimmed(); } QModelIndexList selectedIndexes() const { return ui.resultTV->selectionModel()->selectedRows(); } private: AbstractKeyListModel * model; KeyListSortFilterProxyModel proxy; bool passive; struct Ui : Ui_LookupCertificatesDialog { explicit Ui( LookupCertificatesDialog * q ) : Ui_LookupCertificatesDialog() { setupUi( q ); saveAsPB->hide(); // ### not yet implemented in LookupCertificatesCommand findED->setClearButtonShown( true ); importPB()->setText( i18n("Import") ); HeaderView * hv = new HeaderView( Qt::Horizontal ); KDAB_SET_OBJECT_NAME( hv ); resultTV->setHeader( hv ); adjust_header( hv ); connect( resultTV, SIGNAL(itemDoubleClicked(QModelIndex)), importPB(), SLOT(animateClick()) ); connect( resultTV->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); findED->setFocus(); } QPushButton * importPB() const { return buttonBox->button( QDialogButtonBox::Save ); } QPushButton * closePB() const { return buttonBox->button( QDialogButtonBox::Close ); } } ui; }; LookupCertificatesDialog::Private::Private( LookupCertificatesDialog * qq ) : q( qq ), model( AbstractKeyListModel::createFlatKeyListModel() ), proxy(), passive( false ), ui( q ) { KDAB_SET_OBJECT_NAME( model ); KDAB_SET_OBJECT_NAME( proxy ); proxy.setSourceModel( model ); ui.resultTV->setModel( &proxy ); enableDisableWidgets(); } LookupCertificatesDialog::Private::~Private() {} LookupCertificatesDialog::LookupCertificatesDialog( QWidget * p, Qt::WindowFlags f ) : QDialog( p, f ), d( new Private( this ) ) { } LookupCertificatesDialog::~LookupCertificatesDialog() {} void LookupCertificatesDialog::setCertificates( const std::vector<Key> & certs ) { d->model->setKeys( certs ); } std::vector<Key> LookupCertificatesDialog::selectedCertificates() const { return d->proxy.keys( d->selectedIndexes() ); } void LookupCertificatesDialog::setPassive( bool on ) { if ( d->passive == on ) return; d->passive = on; d->enableDisableWidgets(); } bool LookupCertificatesDialog::isPassive() const { return d->passive; } void LookupCertificatesDialog::accept() { assert( !d->selectedIndexes().empty() ); emit importRequested( selectedCertificates() ); QDialog::accept(); } void LookupCertificatesDialog::Private::enableDisableWidgets() { // enable/disable everything except 'close', based on passive: Q_FOREACH( QObject * const o, q->children() ) if ( QWidget * const w = qobject_cast<QWidget*>( o ) ) w->setDisabled( passive && w != ui.closePB() ); if ( passive ) return; ui.findPB->setEnabled( searchText().length() > minimalSearchTextLength ); const QModelIndexList selection = selectedIndexes(); ui.detailsPB->setEnabled( selection.size() == 1 ); ui.saveAsPB->setEnabled( selection.size() == 1 ); ui.importPB()->setEnabled( !selection.empty() ); } #include "moc_lookupcertificatesdialog.cpp" <commit_msg>Fix connections<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- dialogs/lookupcertificatesdialog.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 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 "lookupcertificatesdialog.h" #include "ui_lookupcertificatesdialog.h" #include <models/keylistmodel.h> #include <models/keylistsortfilterproxymodel.h> #include <utils/headerview.h> #include <gpgme++/key.h> #include <KLineEdit> #include <KLocale> #include <QTreeView> #include <QLayout> #include <QPushButton> #include <QHeaderView> #include <QLabel> #include <cassert> using namespace Kleo; using namespace Kleo::Dialogs; using namespace GpgME; static const int minimalSearchTextLength = 2; // ### TODO: make that KIOSK-able static const QHeaderView::ResizeMode resize_modes[AbstractKeyListModel::NumColumns] = { QHeaderView::Stretch, // Name QHeaderView::Stretch, // EMail QHeaderView::Fixed, // Valid From QHeaderView::Fixed, // Valid Until QHeaderView::Fixed, // Details QHeaderView::Fixed, // Fingerprint }; static void adjust_header( HeaderView * hv ) { for ( int i = 0, end = AbstractKeyListModel::NumColumns ; i < end ; ++i ) hv->setSectionResizeMode( i, resize_modes[i] ); } class LookupCertificatesDialog::Private { friend class ::Kleo::Dialogs::LookupCertificatesDialog; LookupCertificatesDialog * const q; public: explicit Private( LookupCertificatesDialog * qq ); ~Private(); private: void slotSelectionChanged() { enableDisableWidgets(); } void slotSearchTextChanged() { enableDisableWidgets(); } void slotSearchClicked() { emit q->searchTextChanged( ui.findED->text() ); } void slotDetailsClicked() { assert( q->selectedCertificates().size() == 1 ); emit q->detailsRequested( q->selectedCertificates().front() ); } void slotSaveAsClicked() { emit q->saveAsRequested( q->selectedCertificates() ); } void enableDisableWidgets(); QString searchText() const { return ui.findED->text().trimmed(); } QModelIndexList selectedIndexes() const { return ui.resultTV->selectionModel()->selectedRows(); } private: AbstractKeyListModel * model; KeyListSortFilterProxyModel proxy; bool passive; struct Ui : Ui_LookupCertificatesDialog { explicit Ui( LookupCertificatesDialog * q ) : Ui_LookupCertificatesDialog() { setupUi( q ); saveAsPB->hide(); // ### not yet implemented in LookupCertificatesCommand findED->setClearButtonShown( true ); importPB()->setText( i18n("Import") ); HeaderView * hv = new HeaderView( Qt::Horizontal ); KDAB_SET_OBJECT_NAME( hv ); resultTV->setHeader( hv ); adjust_header( hv ); connect( resultTV, SIGNAL(doubleClicked(QModelIndex)), importPB(), SLOT(animateClick()) ); findED->setFocus(); } QPushButton * importPB() const { return buttonBox->button( QDialogButtonBox::Save ); } QPushButton * closePB() const { return buttonBox->button( QDialogButtonBox::Close ); } } ui; }; LookupCertificatesDialog::Private::Private( LookupCertificatesDialog * qq ) : q( qq ), model( AbstractKeyListModel::createFlatKeyListModel() ), proxy(), passive( false ), ui( q ) { KDAB_SET_OBJECT_NAME( model ); KDAB_SET_OBJECT_NAME( proxy ); proxy.setSourceModel( model ); ui.resultTV->setModel( &proxy ); connect( ui.resultTV->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SLOT(slotSelectionChanged()) ); enableDisableWidgets(); } LookupCertificatesDialog::Private::~Private() {} LookupCertificatesDialog::LookupCertificatesDialog( QWidget * p, Qt::WindowFlags f ) : QDialog( p, f ), d( new Private( this ) ) { } LookupCertificatesDialog::~LookupCertificatesDialog() {} void LookupCertificatesDialog::setCertificates( const std::vector<Key> & certs ) { d->model->setKeys( certs ); } std::vector<Key> LookupCertificatesDialog::selectedCertificates() const { return d->proxy.keys( d->selectedIndexes() ); } void LookupCertificatesDialog::setPassive( bool on ) { if ( d->passive == on ) return; d->passive = on; d->enableDisableWidgets(); } bool LookupCertificatesDialog::isPassive() const { return d->passive; } void LookupCertificatesDialog::accept() { assert( !d->selectedIndexes().empty() ); emit importRequested( selectedCertificates() ); QDialog::accept(); } void LookupCertificatesDialog::Private::enableDisableWidgets() { // enable/disable everything except 'close', based on passive: Q_FOREACH( QObject * const o, q->children() ) if ( QWidget * const w = qobject_cast<QWidget*>( o ) ) w->setDisabled( passive && w != ui.closePB() ); if ( passive ) return; ui.findPB->setEnabled( searchText().length() > minimalSearchTextLength ); const QModelIndexList selection = selectedIndexes(); ui.detailsPB->setEnabled( selection.size() == 1 ); ui.saveAsPB->setEnabled( selection.size() == 1 ); ui.importPB()->setEnabled( !selection.empty() ); } #include "moc_lookupcertificatesdialog.cpp" <|endoftext|>
<commit_before>/*! @file @author Albert Semenov @date 12/2008 @module */ #include "precompiled.h" #include "DemoKeeper.h" #include "MyGUI_LayerKeeper.h" namespace demo { MyGUI::VectorWidgetPtr all_widgets; void diagnosticRenderItem(MyGUI::WidgetPtr _widget) { //return; // , , 0, // MyGUI::LayerKeeper * layer = _widget->getLayerKeeper(); // , .. , , , // , MyGUI::LayerItemKeeper * layer_item = _widget->getLayerItemKeeper(); // if (layer) { if (!_widget->isRootWidget()) { MYGUI_EXCEPT("layer != nullptr && !isRootWidget()"); } if (!layer_item) { MYGUI_EXCEPT("layer != nullptr && layer_item == nullptr"); } // bool exist = layer->existItem(layer_item); if (!exist) { MYGUI_EXCEPT("layer item is not exist"); } } // else { if (layer_item) { // MyGUI::ICroppedRectangle * parent = _widget->getCroppedParent(); if (!parent) { MYGUI_EXCEPT("cropped parent == nullptr"); } while (parent->getCroppedParent()) { // , MyGUI::LayerKeeper * layer3 = static_cast<MyGUI::WidgetPtr>(parent)->getLayerKeeper(); if (layer3) { MYGUI_EXCEPT("layer != nullptr"); } parent = parent->getCroppedParent(); }; MyGUI::LayerKeeper * layer3 = static_cast<MyGUI::WidgetPtr>(parent)->getLayerKeeper(); // if (!layer3) { MYGUI_EXCEPT("layer == nullptr"); } // bool exist = layer3->existItem(layer_item); if (!exist) { MYGUI_EXCEPT("layer item is not exist"); } } // else { } // } } void test_widgets() { std::set<std::string> layers; size_t count_nodes = 0; size_t count_nodes2 = 0; for (MyGUI::VectorWidgetPtr::iterator iter = all_widgets.begin(); iter!=all_widgets.end(); ++iter) { // MYGUI_VALIDATE_PTR(*iter); diagnosticRenderItem(*iter); if ( ! (*iter)->isRootWidget() && (*iter)->getWidgetStyle() == MyGUI::WidgetStyle::Overlapped && (*iter)->getLayerItemKeeper() ) { count_nodes ++; MyGUI::WidgetPtr root = (*iter); while (!root->getLayerKeeper()) { root = root->getParent(); } layers.insert(root->getLayerKeeper()->getName()); } } MyGUI::EnumeratorLayerKeeperPtr layer = MyGUI::LayerManager::getInstance().getEnumerator(); while (layer.next()) { if (layers.find(layer->getName()) == layers.end()) continue; count_nodes2 += layer->getSubItemCount(); } MYGUI_ASSERT(count_nodes == count_nodes2, "find lost nodes") } int random(int _max) { int result = rand() % _max; return result < 0 ? 0 : result; } MyGUI::WidgetStyle get_type() { const int SIZE = 3; static MyGUI::WidgetStyle types[SIZE] = { MyGUI::WidgetStyle::Child, MyGUI::WidgetStyle::Popup, MyGUI::WidgetStyle::Overlapped }; return types[random(SIZE)]; } void erase_widget(MyGUI::VectorWidgetPtr & _mass, MyGUI::WidgetPtr _widget) { for (MyGUI::VectorWidgetPtr::iterator iter = _mass.begin(); iter!=_mass.end(); ++iter) { if (*iter == _widget) { *iter = _mass.back(); _mass.pop_back(); return; } } //MYGUI_EXCEPT(MyGUI::utility::toString("pointer ", _widget, " not found"); } MyGUI::WidgetPtr get_random(MyGUI::VectorWidgetPtr & _mass) { if (_mass.empty()) return 0; return _mass.at(random((int)_mass.size())); } const char * get_skin() { const int SIZE = 8; static const char * names[SIZE] = { "WindowCSX", "ScrollView", "ButtonX", "ButtonV" , "Button", "EditStretch", "RadioBox", "CheckBox" }; return names[random(SIZE)]; } const char * get_layer() { const int SIZE = 4; static const char * names[SIZE] = { "", "Main", "Overlapped", "Popup" }; return names[random(SIZE)]; } MyGUI::IntCoord get_coord() { return MyGUI::IntCoord(random(500), random(500), random(500), random(500)); } void step_detach_layer() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; MyGUI::LayerManager::getInstance().detachFromLayerKeeper(widget); test_widgets(); } void step_detach_layer(int _count) { int count = random(_count); while (count > 0) { step_detach_layer(); --count; }; } void step_attach_layer() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; if (widget->isRootWidget()) { std::string layername = get_layer(); if (!layername.empty()) MyGUI::LayerManager::getInstance().attachToLayerKeeper(layername, widget); } test_widgets(); } void step_attach_layer(int _count) { int count = random(_count); while (count > 0) { step_attach_layer(); --count; }; } void step_detach_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->detachFromWidget(); test_widgets(); } void step_detach_widget(int _count) { int count = random(_count); while (count > 0) { step_detach_widget(); --count; }; } void step_attach_widget() { MyGUI::WidgetPtr widget1 = get_random(all_widgets); MyGUI::WidgetPtr widget2 = get_random(all_widgets); if (!widget1 || !widget2) return; MyGUI::WidgetPtr test = widget1; do { if (test == widget2) return; test = test->getParent(); } while (test); widget2->attachToWidget(widget1); test_widgets(); } void step_attach_widget(int _count) { int count = random(_count); while (count > 0) { step_attach_widget(); --count; }; } void step_destroy_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; /*if (!widget->isRootWidget()) */MyGUI::WidgetManager::getInstance().destroyWidget(widget); test_widgets(); } void step_destroy_widget(int _count) { int count = random(_count); while (count > 0) { step_destroy_widget(); --count; }; } void step_create_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (widget) { int select = random(3); if (select == 0) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Child, get_skin(), get_coord(), MyGUI::Align::Default); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } else if (select == 1) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Popup, get_skin(), get_coord(), MyGUI::Align::Default, get_layer()); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } else if (select == 2) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Overlapped, get_skin(), get_coord(), MyGUI::Align::Default); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } } else { MyGUI::WidgetPtr child = MyGUI::Gui::getInstance().createWidget<MyGUI::Widget>(get_skin(), get_coord(), MyGUI::Align::Default, get_layer()); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } test_widgets(); } void step_create_widget(int _count) { int count = random(_count); while (count > 0) { step_create_widget(); --count; }; } void step_change_skin() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->changeWidgetSkin(get_skin()); test_widgets(); } void step_change_skin(int _count) { int count = random(_count); while (count > 0) { step_change_skin(); --count; }; } void step_change_type() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->setWidgetStyle(get_type()); test_widgets(); } void step_change_type(int _count) { int count = random(_count); while (count > 0) { step_change_type(); --count; }; } class Unlink : public MyGUI::IUnlinkWidget { public: void _unlinkWidget(MyGUI::WidgetPtr _widget) { erase_widget(all_widgets, _widget); } }; Unlink unlink_holder; void DemoKeeper::createScene() { //base::BaseManager::getInstance().addResourceLocation("../../Media/Common/Wallpapers"); //base::BaseManager::getInstance().setWallpaper("wallpaper0.jpg"); const MyGUI::IntSize & view = MyGUI::Gui::getInstance().getViewSize(); const MyGUI::IntSize size(100, 100); MyGUI::WidgetManager::getInstance().registerUnlinker(&unlink_holder); } void DemoKeeper::destroyScene() { MyGUI::WidgetManager::getInstance().unregisterUnlinker(&unlink_holder); } bool DemoKeeper::frameStarted(const Ogre::FrameEvent& evt) { if (all_widgets.size() > 500) { step_destroy_widget(200); } else { int step = random(8); if (step == 0) { step_detach_layer(10); } else if (step == 1) { step_attach_layer(30); } else if (step == 2) { step_attach_widget(10); } else if (step == 3) { step_detach_widget(10); } else if (step == 4) { step_destroy_widget(2); } else if (step == 5) { step_create_widget(30); } else if (step == 6) { step_change_skin(30); } else if (step == 7) { step_change_type(30); } } mInfo->change("COUNT", all_widgets.size()); MyGUI::EnumeratorLayerKeeperPtr layer = MyGUI::LayerManager::getInstance().getEnumerator(); while (layer.next()) { size_t count = layer->getItemCount(); if (count > 0) { mInfo->change(layer->getName(), count); } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 ::Sleep(10); #endif return base::BaseManager::frameStarted(evt); } } // namespace demo <commit_msg>для порядка<commit_after>/*! @file @author Albert Semenov @date 12/2008 @module */ #include "precompiled.h" #include "DemoKeeper.h" #include "MyGUI_LayerKeeper.h" namespace demo { MyGUI::VectorWidgetPtr all_widgets; void diagnosticRenderItem(MyGUI::WidgetPtr _widget) { //return; // , , 0, // MyGUI::LayerKeeper * layer = _widget->getLayerKeeper(); // , .. , , , // , MyGUI::LayerItemKeeper * layer_item = _widget->getLayerItemKeeper(); // if (layer) { if (!_widget->isRootWidget()) { MYGUI_EXCEPT("layer != nullptr && !isRootWidget()"); } if (!layer_item) { MYGUI_EXCEPT("layer != nullptr && layer_item == nullptr"); } // bool exist = layer->existItem(layer_item); if (!exist) { MYGUI_EXCEPT("layer item is not exist"); } } // else { if (layer_item) { // MyGUI::ICroppedRectangle * parent = _widget->getCroppedParent(); if (!parent) { MYGUI_EXCEPT("cropped parent == nullptr"); } while (parent->getCroppedParent()) { // , MyGUI::LayerKeeper * layer3 = static_cast<MyGUI::WidgetPtr>(parent)->getLayerKeeper(); if (layer3) { MYGUI_EXCEPT("layer != nullptr"); } parent = parent->getCroppedParent(); }; MyGUI::LayerKeeper * layer3 = static_cast<MyGUI::WidgetPtr>(parent)->getLayerKeeper(); // if (!layer3) { MYGUI_EXCEPT("layer == nullptr"); } // bool exist = layer3->existItem(layer_item); if (!exist) { MYGUI_EXCEPT("layer item is not exist"); } } // else { } // } } void test_widgets() { std::set<std::string> layers; size_t count_nodes = 0; size_t count_nodes2 = 0; for (MyGUI::VectorWidgetPtr::iterator iter = all_widgets.begin(); iter!=all_widgets.end(); ++iter) { // MYGUI_VALIDATE_PTR(*iter); diagnosticRenderItem(*iter); if ( ! (*iter)->isRootWidget() && (*iter)->getWidgetStyle() == MyGUI::WidgetStyle::Overlapped && (*iter)->getLayerItemKeeper() ) { count_nodes ++; MyGUI::WidgetPtr root = (*iter); while (!root->getLayerKeeper()) { root = root->getParent(); } layers.insert(root->getLayerKeeper()->getName()); } } MyGUI::EnumeratorLayerKeeperPtr layer = MyGUI::LayerManager::getInstance().getEnumerator(); while (layer.next()) { if (layers.find(layer->getName()) == layers.end()) continue; count_nodes2 += layer->getSubItemCount(); } MYGUI_ASSERT(count_nodes == count_nodes2, "find lost nodes") } int random(int _max) { int result = rand() % _max; return result < 0 ? 0 : result; } MyGUI::WidgetStyle get_type() { const int SIZE = 3; static MyGUI::WidgetStyle types[SIZE] = { MyGUI::WidgetStyle::Child, MyGUI::WidgetStyle::Popup, MyGUI::WidgetStyle::Overlapped }; return types[random(SIZE)]; } void erase_widget(MyGUI::VectorWidgetPtr & _mass, MyGUI::WidgetPtr _widget) { for (MyGUI::VectorWidgetPtr::iterator iter = _mass.begin(); iter!=_mass.end(); ++iter) { if (*iter == _widget) { *iter = _mass.back(); _mass.pop_back(); return; } } //MYGUI_EXCEPT(MyGUI::utility::toString("pointer ", _widget, " not found"); } MyGUI::WidgetPtr get_random(MyGUI::VectorWidgetPtr & _mass) { if (_mass.empty()) return 0; return _mass.at(random((int)_mass.size())); } const char * get_skin() { const int SIZE = 8; static const char * names[SIZE] = { "WindowCSX", "ScrollView", "ButtonX", "ButtonV" , "Button", "EditStretch", "RadioBox", "CheckBox" }; return names[random(SIZE)]; } const char * get_layer() { const int SIZE = 4; static const char * names[SIZE] = { "", "Main", "Overlapped", "Popup" }; return names[random(SIZE)]; } MyGUI::IntCoord get_coord() { return MyGUI::IntCoord(random(500), random(500), random(500), random(500)); } void step_detach_layer() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; MyGUI::LayerManager::getInstance().detachFromLayerKeeper(widget); test_widgets(); } void step_detach_layer(int _count) { int count = random(_count); while (count > 0) { step_detach_layer(); --count; }; } void step_attach_layer() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; if (widget->isRootWidget()) { std::string layername = get_layer(); if (!layername.empty()) MyGUI::LayerManager::getInstance().attachToLayerKeeper(layername, widget); } test_widgets(); } void step_attach_layer(int _count) { int count = random(_count); while (count > 0) { step_attach_layer(); --count; }; } void step_detach_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->detachFromWidget(); test_widgets(); } void step_detach_widget(int _count) { int count = random(_count); while (count > 0) { step_detach_widget(); --count; }; } void step_attach_widget() { MyGUI::WidgetPtr widget1 = get_random(all_widgets); MyGUI::WidgetPtr widget2 = get_random(all_widgets); if (!widget1 || !widget2) return; MyGUI::WidgetPtr test = widget1; do { if (test == widget2) return; test = test->getParent(); } while (test); widget2->attachToWidget(widget1); test_widgets(); } void step_attach_widget(int _count) { int count = random(_count); while (count > 0) { step_attach_widget(); --count; }; } void step_destroy_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; /*if (!widget->isRootWidget()) */MyGUI::WidgetManager::getInstance().destroyWidget(widget); test_widgets(); } void step_destroy_widget(int _count) { int count = random(_count); while (count > 0) { step_destroy_widget(); --count; }; } void step_create_widget() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (widget) { int select = random(3); if (select == 0) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Child, get_skin(), get_coord(), MyGUI::Align::Default); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } else if (select == 1) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Popup, get_skin(), get_coord(), MyGUI::Align::Default, get_layer()); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } else if (select == 2) { MyGUI::WidgetPtr child = widget->createWidget<MyGUI::Widget>(MyGUI::WidgetStyle::Overlapped, get_skin(), get_coord(), MyGUI::Align::Default); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } } else { MyGUI::WidgetPtr child = MyGUI::Gui::getInstance().createWidget<MyGUI::Widget>(get_skin(), get_coord(), MyGUI::Align::Default, get_layer()); MYGUI_ASSERT(child, "child nullptr"); all_widgets.push_back(child); } test_widgets(); } void step_create_widget(int _count) { int count = random(_count); while (count > 0) { step_create_widget(); --count; }; } void step_change_skin() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->changeWidgetSkin(get_skin()); test_widgets(); } void step_change_skin(int _count) { int count = random(_count); while (count > 0) { step_change_skin(); --count; }; } void step_change_type() { MyGUI::WidgetPtr widget = get_random(all_widgets); if (!widget) return; widget->setWidgetStyle(get_type()); test_widgets(); } void step_change_type(int _count) { int count = random(_count); while (count > 0) { step_change_type(); --count; }; } class Unlink : public MyGUI::IUnlinkWidget { public: void _unlinkWidget(MyGUI::WidgetPtr _widget) { erase_widget(all_widgets, _widget); } }; Unlink unlink_holder; void DemoKeeper::createScene() { //base::BaseManager::getInstance().addResourceLocation("../../Media/Common/Wallpapers"); //base::BaseManager::getInstance().setWallpaper("wallpaper0.jpg"); const MyGUI::IntSize & view = MyGUI::Gui::getInstance().getViewSize(); const MyGUI::IntSize size(100, 100); MyGUI::WidgetManager::getInstance().registerUnlinker(&unlink_holder); } void DemoKeeper::destroyScene() { MyGUI::WidgetManager::getInstance().unregisterUnlinker(&unlink_holder); } bool DemoKeeper::frameStarted(const Ogre::FrameEvent& evt) { if (all_widgets.size() > 500) { step_destroy_widget(200); } else { int step = random(8); if (step == 0) { step_detach_layer(10); } else if (step == 1) { step_attach_layer(30); } else if (step == 2) { step_attach_widget(10); } else if (step == 3) { step_detach_widget(10); } else if (step == 4) { step_destroy_widget(2); } else if (step == 5) { step_create_widget(30); } else if (step == 6) { step_change_skin(30); } else if (step == 7) { step_change_type(30); } } mInfo->change("COUNT", all_widgets.size()); MyGUI::EnumeratorLayerKeeperPtr layer = MyGUI::LayerManager::getInstance().getEnumerator(); while (layer.next()) { size_t count = layer->getItemCount(); if (count > 0) { mInfo->change(layer->getName(), count); } } #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 ::Sleep(10); #endif return base::BaseManager::frameStarted(evt); } } // namespace demo <|endoftext|>
<commit_before>//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the inline assembler pieces of the AsmPrinter class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/InlineAsm.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCParser/AsmParser.h" #include "llvm/Target/TargetAsmParser.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegistry.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; /// EmitInlineAsm - Emit a blob of inline asm to the output streamer. void AsmPrinter::EmitInlineAsm(StringRef Str) const { assert(!Str.empty() && "Can't emit empty inline asm block"); // Remember if the buffer is nul terminated or not so we can avoid a copy. bool isNullTerminated = Str.back() == 0; if (isNullTerminated) Str = Str.substr(0, Str.size()-1); // If the output streamer is actually a .s file, just emit the blob textually. // This is useful in case the asm parser doesn't handle something but the // system assembler does. if (OutStreamer.hasRawTextSupport()) { OutStreamer.EmitRawText(Str); return; } SourceMgr SrcMgr; MemoryBuffer *Buffer; if (isNullTerminated) Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>"); else Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>"); // Tell SrcMgr about this buffer, it takes ownership of the buffer. SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); AsmParser Parser(SrcMgr, OutContext, OutStreamer, *MAI); OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser)); if (!TAP) llvm_report_error("Inline asm not supported by this streamer because" " we don't have an asm parser for this target\n"); Parser.setTargetParser(*TAP.get()); // Don't implicitly switch to the text section before the asm. int Res = Parser.Run(/*NoInitialTextSection*/ true, /*NoFinalize*/ true); if (Res) llvm_report_error("Error parsing inline asm\n"); } /// EmitInlineAsm - This method formats and emits the specified machine /// instruction that is an inline asm. void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const { assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms"); unsigned NumOperands = MI->getNumOperands(); // Count the number of register definitions to find the asm string. unsigned NumDefs = 0; for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); ++NumDefs) assert(NumDefs != NumOperands-1 && "No asm string?"); assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); // If this asmstr is empty, just print the #APP/#NOAPP markers. // These are useful to see where empty asm's wound up. if (AsmStr[0] == 0) { // Don't emit the comments if writing to a .o file. if (!OutStreamer.hasRawTextSupport()) return; OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmStart()); OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmEnd()); return; } // Emit the #APP start marker. This has to happen even if verbose-asm isn't // enabled, so we use EmitRawText. if (OutStreamer.hasRawTextSupport()) OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmStart()); // Emit the inline asm to a temporary string so we can emit it through // EmitInlineAsm. SmallString<256> StringData; raw_svector_ostream OS(StringData); OS << '\t'; // The variant of the current asmprinter. int AsmPrinterVariant = MAI->getAssemblerDialect(); int CurVariant = -1; // The number of the {.|.|.} region we are in. const char *LastEmitted = AsmStr; // One past the last character emitted. while (*LastEmitted) { switch (*LastEmitted) { default: { // Not a special case, emit the string section literally. const char *LiteralEnd = LastEmitted+1; while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') ++LiteralEnd; if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS.write(LastEmitted, LiteralEnd-LastEmitted); LastEmitted = LiteralEnd; break; } case '\n': ++LastEmitted; // Consume newline character. OS << '\n'; // Indent code with newline. break; case '$': { ++LastEmitted; // Consume '$' character. bool Done = true; // Handle escapes. switch (*LastEmitted) { default: Done = false; break; case '$': // $$ -> $ if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS << '$'; ++LastEmitted; // Consume second '$' character. break; case '(': // $( -> same as GCC's { character. ++LastEmitted; // Consume '(' character. if (CurVariant != -1) { llvm_report_error("Nested variants found in inline asm string: '" + std::string(AsmStr) + "'"); } CurVariant = 0; // We're in the first variant now. break; case '|': ++LastEmitted; // consume '|' character. if (CurVariant == -1) OS << '|'; // this is gcc's behavior for | outside a variant else ++CurVariant; // We're in the next variant. break; case ')': // $) -> same as GCC's } char. ++LastEmitted; // consume ')' character. if (CurVariant == -1) OS << '}'; // this is gcc's behavior for } outside a variant else CurVariant = -1; break; } if (Done) break; bool HasCurlyBraces = false; if (*LastEmitted == '{') { // ${variable} ++LastEmitted; // Consume '{' character. HasCurlyBraces = true; } // If we have ${:foo}, then this is not a real operand reference, it is a // "magic" string reference, just like in .td files. Arrange to call // PrintSpecial. if (HasCurlyBraces && *LastEmitted == ':') { ++LastEmitted; const char *StrStart = LastEmitted; const char *StrEnd = strchr(StrStart, '}'); if (StrEnd == 0) llvm_report_error(Twine("Unterminated ${:foo} operand in inline asm" " string: '") + Twine(AsmStr) + "'"); std::string Val(StrStart, StrEnd); PrintSpecial(MI, OS, Val.c_str()); LastEmitted = StrEnd+1; break; } const char *IDStart = LastEmitted; const char *IDEnd = IDStart; while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd; unsigned Val; if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val)) llvm_report_error("Bad $ operand number in inline asm string: '" + std::string(AsmStr) + "'"); LastEmitted = IDEnd; char Modifier[2] = { 0, 0 }; if (HasCurlyBraces) { // If we have curly braces, check for a modifier character. This // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. if (*LastEmitted == ':') { ++LastEmitted; // Consume ':' character. if (*LastEmitted == 0) llvm_report_error("Bad ${:} expression in inline asm string: '" + std::string(AsmStr) + "'"); Modifier[0] = *LastEmitted; ++LastEmitted; // Consume modifier character. } if (*LastEmitted != '}') llvm_report_error("Bad ${} expression in inline asm string: '" + std::string(AsmStr) + "'"); ++LastEmitted; // Consume '}' character. } if (Val >= NumOperands-1) llvm_report_error("Invalid $ operand number in inline asm string: '" + std::string(AsmStr) + "'"); // Okay, we finally have a value number. Ask the target to print this // operand! if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { unsigned OpNo = 1; bool Error = false; // Scan to find the machine operand number for the operand. for (; Val; --Val) { if (OpNo >= MI->getNumOperands()) break; unsigned OpFlags = MI->getOperand(OpNo).getImm(); OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; } if (OpNo >= MI->getNumOperands()) { Error = true; } else { unsigned OpFlags = MI->getOperand(OpNo).getImm(); ++OpNo; // Skip over the ID number. if (Modifier[0] == 'l') // labels are target independent // FIXME: What if the operand isn't an MBB, report error? OS << *MI->getOperand(OpNo).getMBB()->getSymbol(); else { AsmPrinter *AP = const_cast<AsmPrinter*>(this); if ((OpFlags & 7) == 4) { Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, Modifier[0] ? Modifier : 0, OS); } else { Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, Modifier[0] ? Modifier : 0, OS); } } } if (Error) { std::string msg; raw_string_ostream Msg(msg); Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n"; MI->print(Msg); llvm_report_error(Msg.str()); } } break; } } } OS << '\n' << (char)0; // null terminate string. EmitInlineAsm(OS.str()); // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't // enabled, so we use EmitRawText. if (OutStreamer.hasRawTextSupport()) OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmEnd()); } /// PrintSpecial - Print information related to the specified machine instr /// that is independent of the operand, and may be independent of the instr /// itself. This can be useful for portably encoding the comment character /// or other bits of target-specific knowledge into the asmstrings. The /// syntax used is ${:comment}. Targets can override this to add support /// for their own strange codes. void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const { if (!strcmp(Code, "private")) { OS << MAI->getPrivateGlobalPrefix(); } else if (!strcmp(Code, "comment")) { OS << MAI->getCommentString(); } else if (!strcmp(Code, "uid")) { // Comparing the address of MI isn't sufficient, because machineinstrs may // be allocated to the same address across functions. // If this is a new LastFn instruction, bump the counter. if (LastMI != MI || LastFn != getFunctionNumber()) { ++Counter; LastMI = MI; LastFn = getFunctionNumber(); } OS << Counter; } else { std::string msg; raw_string_ostream Msg(msg); Msg << "Unknown special formatter '" << Code << "' for machine instr: " << *MI; llvm_report_error(Msg.str()); } } /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM /// instruction, using the specified assembler variant. Targets should /// override this to format as appropriate. bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Target doesn't support this yet! return true; } bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Target doesn't support this yet! return true; } <commit_msg>report errors through LLVMContext's inline asm handler if available.<commit_after>//===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the inline assembler pieces of the AsmPrinter class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/InlineAsm.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/MC/MCParser/AsmParser.h" #include "llvm/Target/TargetAsmParser.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegistry.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; /// EmitInlineAsm - Emit a blob of inline asm to the output streamer. void AsmPrinter::EmitInlineAsm(StringRef Str) const { assert(!Str.empty() && "Can't emit empty inline asm block"); // Remember if the buffer is nul terminated or not so we can avoid a copy. bool isNullTerminated = Str.back() == 0; if (isNullTerminated) Str = Str.substr(0, Str.size()-1); // If the output streamer is actually a .s file, just emit the blob textually. // This is useful in case the asm parser doesn't handle something but the // system assembler does. if (OutStreamer.hasRawTextSupport()) { OutStreamer.EmitRawText(Str); return; } SourceMgr SrcMgr; // If the current LLVMContext has an inline asm handler, set it in SourceMgr. LLVMContext &LLVMCtx = MMI->getModule()->getContext(); bool HasDiagHandler = false; if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) { unsigned Cookie = 0; // no cookie yet. SrcMgr.setDiagHandler((SourceMgr::DiagHandlerTy)(intptr_t)DiagHandler, LLVMCtx.getInlineAsmDiagnosticContext(), Cookie); HasDiagHandler = true; } MemoryBuffer *Buffer; if (isNullTerminated) Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>"); else Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>"); // Tell SrcMgr about this buffer, it takes ownership of the buffer. SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); AsmParser Parser(SrcMgr, OutContext, OutStreamer, *MAI); OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(Parser)); if (!TAP) llvm_report_error("Inline asm not supported by this streamer because" " we don't have an asm parser for this target\n"); Parser.setTargetParser(*TAP.get()); // Don't implicitly switch to the text section before the asm. int Res = Parser.Run(/*NoInitialTextSection*/ true, /*NoFinalize*/ true); if (Res && !HasDiagHandler) llvm_report_error("Error parsing inline asm\n"); } /// EmitInlineAsm - This method formats and emits the specified machine /// instruction that is an inline asm. void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const { assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms"); unsigned NumOperands = MI->getNumOperands(); // Count the number of register definitions to find the asm string. unsigned NumDefs = 0; for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); ++NumDefs) assert(NumDefs != NumOperands-1 && "No asm string?"); assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); // If this asmstr is empty, just print the #APP/#NOAPP markers. // These are useful to see where empty asm's wound up. if (AsmStr[0] == 0) { // Don't emit the comments if writing to a .o file. if (!OutStreamer.hasRawTextSupport()) return; OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmStart()); OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmEnd()); return; } // Emit the #APP start marker. This has to happen even if verbose-asm isn't // enabled, so we use EmitRawText. if (OutStreamer.hasRawTextSupport()) OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmStart()); // Emit the inline asm to a temporary string so we can emit it through // EmitInlineAsm. SmallString<256> StringData; raw_svector_ostream OS(StringData); OS << '\t'; // The variant of the current asmprinter. int AsmPrinterVariant = MAI->getAssemblerDialect(); int CurVariant = -1; // The number of the {.|.|.} region we are in. const char *LastEmitted = AsmStr; // One past the last character emitted. while (*LastEmitted) { switch (*LastEmitted) { default: { // Not a special case, emit the string section literally. const char *LiteralEnd = LastEmitted+1; while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') ++LiteralEnd; if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS.write(LastEmitted, LiteralEnd-LastEmitted); LastEmitted = LiteralEnd; break; } case '\n': ++LastEmitted; // Consume newline character. OS << '\n'; // Indent code with newline. break; case '$': { ++LastEmitted; // Consume '$' character. bool Done = true; // Handle escapes. switch (*LastEmitted) { default: Done = false; break; case '$': // $$ -> $ if (CurVariant == -1 || CurVariant == AsmPrinterVariant) OS << '$'; ++LastEmitted; // Consume second '$' character. break; case '(': // $( -> same as GCC's { character. ++LastEmitted; // Consume '(' character. if (CurVariant != -1) { llvm_report_error("Nested variants found in inline asm string: '" + std::string(AsmStr) + "'"); } CurVariant = 0; // We're in the first variant now. break; case '|': ++LastEmitted; // consume '|' character. if (CurVariant == -1) OS << '|'; // this is gcc's behavior for | outside a variant else ++CurVariant; // We're in the next variant. break; case ')': // $) -> same as GCC's } char. ++LastEmitted; // consume ')' character. if (CurVariant == -1) OS << '}'; // this is gcc's behavior for } outside a variant else CurVariant = -1; break; } if (Done) break; bool HasCurlyBraces = false; if (*LastEmitted == '{') { // ${variable} ++LastEmitted; // Consume '{' character. HasCurlyBraces = true; } // If we have ${:foo}, then this is not a real operand reference, it is a // "magic" string reference, just like in .td files. Arrange to call // PrintSpecial. if (HasCurlyBraces && *LastEmitted == ':') { ++LastEmitted; const char *StrStart = LastEmitted; const char *StrEnd = strchr(StrStart, '}'); if (StrEnd == 0) llvm_report_error(Twine("Unterminated ${:foo} operand in inline asm" " string: '") + Twine(AsmStr) + "'"); std::string Val(StrStart, StrEnd); PrintSpecial(MI, OS, Val.c_str()); LastEmitted = StrEnd+1; break; } const char *IDStart = LastEmitted; const char *IDEnd = IDStart; while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd; unsigned Val; if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val)) llvm_report_error("Bad $ operand number in inline asm string: '" + std::string(AsmStr) + "'"); LastEmitted = IDEnd; char Modifier[2] = { 0, 0 }; if (HasCurlyBraces) { // If we have curly braces, check for a modifier character. This // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. if (*LastEmitted == ':') { ++LastEmitted; // Consume ':' character. if (*LastEmitted == 0) llvm_report_error("Bad ${:} expression in inline asm string: '" + std::string(AsmStr) + "'"); Modifier[0] = *LastEmitted; ++LastEmitted; // Consume modifier character. } if (*LastEmitted != '}') llvm_report_error("Bad ${} expression in inline asm string: '" + std::string(AsmStr) + "'"); ++LastEmitted; // Consume '}' character. } if (Val >= NumOperands-1) llvm_report_error("Invalid $ operand number in inline asm string: '" + std::string(AsmStr) + "'"); // Okay, we finally have a value number. Ask the target to print this // operand! if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { unsigned OpNo = 1; bool Error = false; // Scan to find the machine operand number for the operand. for (; Val; --Val) { if (OpNo >= MI->getNumOperands()) break; unsigned OpFlags = MI->getOperand(OpNo).getImm(); OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; } if (OpNo >= MI->getNumOperands()) { Error = true; } else { unsigned OpFlags = MI->getOperand(OpNo).getImm(); ++OpNo; // Skip over the ID number. if (Modifier[0] == 'l') // labels are target independent // FIXME: What if the operand isn't an MBB, report error? OS << *MI->getOperand(OpNo).getMBB()->getSymbol(); else { AsmPrinter *AP = const_cast<AsmPrinter*>(this); if ((OpFlags & 7) == 4) { Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, Modifier[0] ? Modifier : 0, OS); } else { Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, Modifier[0] ? Modifier : 0, OS); } } } if (Error) { std::string msg; raw_string_ostream Msg(msg); Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n"; MI->print(Msg); llvm_report_error(Msg.str()); } } break; } } } OS << '\n' << (char)0; // null terminate string. EmitInlineAsm(OS.str()); // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't // enabled, so we use EmitRawText. if (OutStreamer.hasRawTextSupport()) OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+ MAI->getInlineAsmEnd()); } /// PrintSpecial - Print information related to the specified machine instr /// that is independent of the operand, and may be independent of the instr /// itself. This can be useful for portably encoding the comment character /// or other bits of target-specific knowledge into the asmstrings. The /// syntax used is ${:comment}. Targets can override this to add support /// for their own strange codes. void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS, const char *Code) const { if (!strcmp(Code, "private")) { OS << MAI->getPrivateGlobalPrefix(); } else if (!strcmp(Code, "comment")) { OS << MAI->getCommentString(); } else if (!strcmp(Code, "uid")) { // Comparing the address of MI isn't sufficient, because machineinstrs may // be allocated to the same address across functions. // If this is a new LastFn instruction, bump the counter. if (LastMI != MI || LastFn != getFunctionNumber()) { ++Counter; LastMI = MI; LastFn = getFunctionNumber(); } OS << Counter; } else { std::string msg; raw_string_ostream Msg(msg); Msg << "Unknown special formatter '" << Code << "' for machine instr: " << *MI; llvm_report_error(Msg.str()); } } /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM /// instruction, using the specified assembler variant. Targets should /// override this to format as appropriate. bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Target doesn't support this yet! return true; } bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &O) { // Target doesn't support this yet! return true; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "probe.h" #include "msvcprobe.h" #include <logging/logger.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <QCoreApplication> #include <QDir> #include <QDirIterator> #include <QProcess> #include <QStringList> using namespace qbs; static QString searchPath(const QString &path, const QString &me) { foreach (const QString &ppath, path.split(HostOsInfo::pathListSeparator())) { const QString fullPath = ppath + QLatin1Char('/') + me; if (QFileInfo(fullPath).exists()) return QDir::cleanPath(fullPath); } return QString(); } static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForStarted(); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } static void specific_probe(Settings *settings, QList<Profile> &profiles, QString cc) { qbsInfo() << DontPrintLogLevel << Tr::tr("Trying to detect %1...").arg(cc); QString toolchainType; if (cc.contains("clang")) toolchainType = "clang"; else if (cc.contains("gcc")) toolchainType = "gcc"; QString path = QString::fromLocal8Bit(qgetenv("PATH")); QString cxx = QString::fromLocal8Bit(qgetenv("CXX")); QString ld = QString::fromLocal8Bit(qgetenv("LD")); QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE")); QString arch = QString::fromLocal8Bit(qgetenv("ARCH")); QString pathToGcc; QString architecture; QString endianness; QString uname = qsystem("uname", QStringList() << "-m").simplified(); if (arch.isEmpty()) arch = uname; // HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS. if (HostOsInfo::isMacHost() && arch == "i386") arch = "i686"; if (ld.isEmpty()) ld = "ld"; if (cxx.isEmpty()) { if (toolchainType == "gcc") cxx = "g++"; else if(toolchainType == "clang") cxx = "clang++"; } if(!cross.isEmpty() && !cc.startsWith("/")) { pathToGcc = searchPath(path, cross + cc); if (QFileInfo(pathToGcc).exists()) { if (!cc.contains(cross)) cc.prepend(cross); if (!cxx.contains(cross)) cxx.prepend(cross); if (!ld.contains(cross)) ld.prepend(cross); } } if (cc.startsWith("/")) pathToGcc = cc; else pathToGcc = searchPath(path, cc); if (!QFileInfo(pathToGcc).exists()) { qbsInfo() << DontPrintLogLevel << Tr::tr("%1 not found.").arg(cc); return; } QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified(); QStringList compilerTripletl = compilerTriplet.split('-'); if (compilerTripletl.count() < 2 || !(compilerTripletl.at(0).contains(QRegExp(".86")) || compilerTripletl.at(0).contains("arm") ) ) { qbsError("Detected '%s', but I don't understand its architecture '%s'.", qPrintable(pathToGcc), qPrintable(compilerTriplet)); return; } architecture = compilerTripletl.at(0); if (architecture.contains("arm")) { endianness = "big-endian"; } else { endianness = "little-endian"; } QStringList pathToGccL = pathToGcc.split('/'); QString compilerName = pathToGccL.takeLast().replace(cc, cxx); qbsInfo() << DontPrintLogLevel << Tr::tr("Toolchain detected:\n" " binary: %1\n" " triplet: %2\n" " arch: %3\n" " cc: %4").arg(pathToGcc, compilerTriplet, architecture, cc); if (!cxx.isEmpty()) qbsInfo() << DontPrintLogLevel << Tr::tr(" cxx: %1").arg(cxx); if (!ld.isEmpty()) qbsInfo() << DontPrintLogLevel << Tr::tr(" ld: %1").arg(ld); Profile profile(toolchainType, settings); profile.removeProfile(); // fixme should be cpp.toolchain // also there is no toolchain:clang profile.setValue("qbs.toolchain", "gcc"); profile.setValue("qbs.architecture", architecture); profile.setValue("qbs.endianness", endianness); if (HostOsInfo::isMacHost()) profile.setValue("qbs.targetOS", "mac"); else if (HostOsInfo::isLinuxHost()) profile.setValue("qbs.targetOS", "linux"); else profile.setValue("qbs.targetOS", "unknown"); //fixme if (compilerName.contains('-')) { QStringList nl = compilerName.split('-'); profile.setValue("cpp.compilerName", nl.takeLast()); profile.setValue("cpp.toolchainPrefix", nl.join("-") + '-'); } else { profile.setValue("cpp.compilerName", compilerName); } profile.setValue("cpp.toolchainInstallPath", pathToGccL.join("/")); profiles << profile; } static void mingwProbe(Settings *settings, QList<Profile> &profiles) { QString mingwPath; QString mingwBinPath; QString gccPath; QByteArray envPath = qgetenv("PATH"); foreach (const QByteArray &dir, envPath.split(';')) { QFileInfo fi(dir + "/gcc.exe"); if (fi.exists()) { mingwPath = QFileInfo(dir + "/..").canonicalFilePath(); gccPath = fi.absoluteFilePath(); mingwBinPath = fi.absolutePath(); break; } } if (gccPath.isEmpty()) return; QProcess process; process.start(gccPath, QStringList() << "-dumpmachine"); if (!process.waitForStarted()) { qbsError("Could not start \"gcc -dumpmachine\"."); return; } process.waitForFinished(-1); QByteArray gccMachineName = process.readAll().trimmed(); if (gccMachineName != "mingw32" && gccMachineName != "mingw64") { qbsError("Detected gcc platform '%s' is not supported.", gccMachineName.data()); return; } Profile profile(QString::fromLocal8Bit(gccMachineName), settings); qbsInfo() << DontPrintLogLevel << Tr::tr("Platform '%1' detected in '%2'.").arg(profile.name(), mingwPath); profile.setValue("qbs.targetOS", "windows"); profile.setValue("cpp.toolchainInstallPath", mingwBinPath); profile.setValue("qbs.toolchain", "mingw"); profiles << profile; } int probe() { QList<Profile> profiles; Settings settings; if (HostOsInfo::isWindowsHost()) { msvcProbe(&settings, profiles); mingwProbe(&settings, profiles); } else { specific_probe(&settings, profiles, QLatin1String("gcc")); specific_probe(&settings, profiles, QLatin1String("clang")); } if (profiles.isEmpty()) { qbsWarning() << Tr::tr("Could not detect any toolchains. No profile created."); } else if (profiles.count() == 1 && settings.defaultProfile().isEmpty()) { qbsInfo() << DontPrintLogLevel << Tr::tr("Making profile '%1' the default."); settings.setValue(QLatin1String("defaultProfile"), profiles.first().name()); } return 0; } <commit_msg>Fix output problem in toolchain detector.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "probe.h" #include "msvcprobe.h" #include <logging/logger.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <QCoreApplication> #include <QDir> #include <QDirIterator> #include <QProcess> #include <QStringList> using namespace qbs; static QString searchPath(const QString &path, const QString &me) { foreach (const QString &ppath, path.split(HostOsInfo::pathListSeparator())) { const QString fullPath = ppath + QLatin1Char('/') + me; if (QFileInfo(fullPath).exists()) return QDir::cleanPath(fullPath); } return QString(); } static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForStarted(); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } static void specific_probe(Settings *settings, QList<Profile> &profiles, QString cc) { qbsInfo() << DontPrintLogLevel << Tr::tr("Trying to detect %1...").arg(cc); QString toolchainType; if (cc.contains("clang")) toolchainType = "clang"; else if (cc.contains("gcc")) toolchainType = "gcc"; QString path = QString::fromLocal8Bit(qgetenv("PATH")); QString cxx = QString::fromLocal8Bit(qgetenv("CXX")); QString ld = QString::fromLocal8Bit(qgetenv("LD")); QString cross = QString::fromLocal8Bit(qgetenv("CROSS_COMPILE")); QString arch = QString::fromLocal8Bit(qgetenv("ARCH")); QString pathToGcc; QString architecture; QString endianness; QString uname = qsystem("uname", QStringList() << "-m").simplified(); if (arch.isEmpty()) arch = uname; // HACK: "uname -m" reports "i386" but "gcc -dumpmachine" reports "i686" on MacOS. if (HostOsInfo::isMacHost() && arch == "i386") arch = "i686"; if (ld.isEmpty()) ld = "ld"; if (cxx.isEmpty()) { if (toolchainType == "gcc") cxx = "g++"; else if(toolchainType == "clang") cxx = "clang++"; } if(!cross.isEmpty() && !cc.startsWith("/")) { pathToGcc = searchPath(path, cross + cc); if (QFileInfo(pathToGcc).exists()) { if (!cc.contains(cross)) cc.prepend(cross); if (!cxx.contains(cross)) cxx.prepend(cross); if (!ld.contains(cross)) ld.prepend(cross); } } if (cc.startsWith("/")) pathToGcc = cc; else pathToGcc = searchPath(path, cc); if (!QFileInfo(pathToGcc).exists()) { qbsInfo() << DontPrintLogLevel << Tr::tr("%1 not found.").arg(cc); return; } QString compilerTriplet = qsystem(pathToGcc, QStringList() << "-dumpmachine").simplified(); QStringList compilerTripletl = compilerTriplet.split('-'); if (compilerTripletl.count() < 2 || !(compilerTripletl.at(0).contains(QRegExp(".86")) || compilerTripletl.at(0).contains("arm") ) ) { qbsError("Detected '%s', but I don't understand its architecture '%s'.", qPrintable(pathToGcc), qPrintable(compilerTriplet)); return; } architecture = compilerTripletl.at(0); if (architecture.contains("arm")) { endianness = "big-endian"; } else { endianness = "little-endian"; } QStringList pathToGccL = pathToGcc.split('/'); QString compilerName = pathToGccL.takeLast().replace(cc, cxx); qbsInfo() << DontPrintLogLevel << Tr::tr("Toolchain detected:\n" " binary: %1\n" " triplet: %2\n" " arch: %3\n" " cc: %4").arg(pathToGcc, compilerTriplet, architecture, cc); if (!cxx.isEmpty()) qbsInfo() << DontPrintLogLevel << Tr::tr(" cxx: %1").arg(cxx); if (!ld.isEmpty()) qbsInfo() << DontPrintLogLevel << Tr::tr(" ld: %1").arg(ld); Profile profile(toolchainType, settings); profile.removeProfile(); // fixme should be cpp.toolchain // also there is no toolchain:clang profile.setValue("qbs.toolchain", "gcc"); profile.setValue("qbs.architecture", architecture); profile.setValue("qbs.endianness", endianness); if (HostOsInfo::isMacHost()) profile.setValue("qbs.targetOS", "mac"); else if (HostOsInfo::isLinuxHost()) profile.setValue("qbs.targetOS", "linux"); else profile.setValue("qbs.targetOS", "unknown"); //fixme if (compilerName.contains('-')) { QStringList nl = compilerName.split('-'); profile.setValue("cpp.compilerName", nl.takeLast()); profile.setValue("cpp.toolchainPrefix", nl.join("-") + '-'); } else { profile.setValue("cpp.compilerName", compilerName); } profile.setValue("cpp.toolchainInstallPath", pathToGccL.join("/")); profiles << profile; } static void mingwProbe(Settings *settings, QList<Profile> &profiles) { QString mingwPath; QString mingwBinPath; QString gccPath; QByteArray envPath = qgetenv("PATH"); foreach (const QByteArray &dir, envPath.split(';')) { QFileInfo fi(dir + "/gcc.exe"); if (fi.exists()) { mingwPath = QFileInfo(dir + "/..").canonicalFilePath(); gccPath = fi.absoluteFilePath(); mingwBinPath = fi.absolutePath(); break; } } if (gccPath.isEmpty()) return; QProcess process; process.start(gccPath, QStringList() << "-dumpmachine"); if (!process.waitForStarted()) { qbsError("Could not start \"gcc -dumpmachine\"."); return; } process.waitForFinished(-1); QByteArray gccMachineName = process.readAll().trimmed(); if (gccMachineName != "mingw32" && gccMachineName != "mingw64") { qbsError("Detected gcc platform '%s' is not supported.", gccMachineName.data()); return; } Profile profile(QString::fromLocal8Bit(gccMachineName), settings); qbsInfo() << DontPrintLogLevel << Tr::tr("Platform '%1' detected in '%2'.").arg(profile.name(), mingwPath); profile.setValue("qbs.targetOS", "windows"); profile.setValue("cpp.toolchainInstallPath", mingwBinPath); profile.setValue("qbs.toolchain", "mingw"); profiles << profile; } int probe() { QList<Profile> profiles; Settings settings; if (HostOsInfo::isWindowsHost()) { msvcProbe(&settings, profiles); mingwProbe(&settings, profiles); } else { specific_probe(&settings, profiles, QLatin1String("gcc")); specific_probe(&settings, profiles, QLatin1String("clang")); } if (profiles.isEmpty()) { qbsWarning() << Tr::tr("Could not detect any toolchains. No profile created."); } else if (profiles.count() == 1 && settings.defaultProfile().isEmpty()) { const QString profileName = profiles.first().name(); qbsInfo() << DontPrintLogLevel << Tr::tr("Making profile '%1' the default.") .arg(profileName); settings.setValue(QLatin1String("defaultProfile"), profileName); } return 0; } <|endoftext|>
<commit_before>/*-------------------------------------------------------------------------- File : timer_hf_nrf5x.cpp Author : Hoang Nguyen Hoan Sep. 7, 2017 Desc : timer class implementation on Nordic nRF5x series using high frequency timer (TIMERx) Copyright (c) 2017, 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 ----------------------------------------------------------------------------*/ #include "nrf.h" #include "timer_nrf5x.h" #include "iopinctrl.h" #define INTERRUPT_LATENCY 11 static TimerHFnRF5x *s_pDevObj[TIMER_NRF5X_HF_MAX] = { NULL, }; void TimerHFnRF5x::IRQHandler() { uint32_t evt = 0; uint32_t count; vpReg->TASKS_CAPTURE[0] = 1; count = vpReg->CC[0]; for (int i = 0; i < vMaxNbTrigEvt; i++) { if (vpReg->EVENTS_COMPARE[i]) { evt |= 1 << (i + 2); vpReg->EVENTS_COMPARE[i] = 0; if (vTrigType[i] == TIMER_TRIG_TYPE_CONTINUOUS) { vpReg->CC[i] = count + vCC[i] - INTERRUPT_LATENCY; } } } if (count < vLastCount) { // Counter wrap arround evt |= TIMER_EVT_COUNTER_OVR; vRollover += vFreq; } vLastCount = count; if (vEvtHandler) { vEvtHandler(this, evt); } } extern "C" { void TIMER0_IRQHandler() { if (s_pDevObj[0]) s_pDevObj[0]->IRQHandler(); } void TIMER1_IRQHandler() { if (s_pDevObj[1]) s_pDevObj[1]->IRQHandler(); } void TIMER2_IRQHandler() { if (s_pDevObj[2]) s_pDevObj[2]->IRQHandler(); } void TIMER3_IRQHandler() { if (s_pDevObj[3]) s_pDevObj[3]->IRQHandler(); } void TIMER4_IRQHandler() { if (s_pDevObj[4]) s_pDevObj[4]->IRQHandler(); } } // extern "C" TimerHFnRF5x::TimerHFnRF5x() { } TimerHFnRF5x::~TimerHFnRF5x() { } bool TimerHFnRF5x::Init(const TIMER_CFG &Cfg) { if (Cfg.DevNo < 0 || Cfg.DevNo >= TIMER_NRF5X_HF_MAX) return false; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT - 2; switch (Cfg.DevNo) { case 0: s_pDevObj[0] = this; vpReg = NRF_TIMER0; break; case 1: s_pDevObj[1] = this; vpReg = NRF_TIMER1; break; case 2: s_pDevObj[2] = this; vpReg = NRF_TIMER2; break; case 3: s_pDevObj[3] = this; vpReg = NRF_TIMER3; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT; break; case 4: s_pDevObj[4] = this; vpReg = NRF_TIMER4; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT; break; } vpReg->TASKS_STOP = 1; vpReg->TASKS_CLEAR = 1; NRF_CLOCK->TASKS_HFCLKSTOP = 1; vEvtHandler = Cfg.EvtHandler; vDevNo = Cfg.DevNo; // Only support timer mode, 32bits counter vpReg->MODE = TIMER_MODE_MODE_Timer; vpReg->BITMODE = TIMER_BITMODE_BITMODE_32Bit; uint32_t prescaler = 0; if (Cfg.Freq > 0) { uint32_t divisor = 16000000 / Cfg.Freq; prescaler = 31 - __builtin_clzl(divisor); if (prescaler > 9) { prescaler = 9; } } vpReg->PRESCALER = prescaler; vFreq = 16000000 / (1 << prescaler); // Pre-calculate periods for faster timer counter to time conversion use later vnsPeriod = 10000000000ULL / vFreq; // Period in nsec if (Cfg.EvtHandler) { switch (Cfg.DevNo) { case 0: NVIC_ClearPendingIRQ(TIMER0_IRQn); NVIC_SetPriority(TIMER0_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER0_IRQn); break; case 1: NVIC_ClearPendingIRQ(TIMER1_IRQn); NVIC_SetPriority(TIMER1_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER1_IRQn); break; case 2: NVIC_ClearPendingIRQ(TIMER2_IRQn); NVIC_SetPriority(TIMER2_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER2_IRQn); break; case 3: NVIC_ClearPendingIRQ(TIMER3_IRQn); NVIC_SetPriority(TIMER3_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER3_IRQn); break; case 4: NVIC_ClearPendingIRQ(TIMER4_IRQn); NVIC_SetPriority(TIMER4_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER4_IRQn); break; } } // Clock source not available. Only 64MHz XTAL NRF_CLOCK->TASKS_HFCLKSTART = 1; int timout = 1000000; do { if ((NRF_CLOCK->HFCLKSTAT & CLOCK_HFCLKSTAT_STATE_Msk) || NRF_CLOCK->EVENTS_HFCLKSTARTED) break; } while (timout-- > 0); if (timout <= 0) return false; NRF_CLOCK->EVENTS_HFCLKSTARTED = 0; vpReg->TASKS_START = 1; return true; } bool TimerHFnRF5x::Enable() { return true; } void TimerHFnRF5x::Disable() { } void TimerHFnRF5x::Reset() { vpReg->TASKS_CLEAR = 1; } uint32_t TimerHFnRF5x::Frequency(uint32_t Freq) { } uint64_t TimerHFnRF5x::TickCount() { if (vpReg->INTENSET == 0) { vpReg->TASKS_CAPTURE[vDevNo] = 1; uint32_t count = vpReg->CC[vDevNo]; if (count < vLastCount) { // Counter wrap arround vRollover += vFreq; } vLastCount = count; } return vLastCount + vRollover; } uint64_t TimerHFnRF5x::EnableTimerTrigger(int TrigNo, uint64_t nsPeriod, TIMER_TRIG_TYPE Type) { if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt) return 0; uint32_t cc = (nsPeriod * 10ULL + (vnsPeriod >> 1)) / vnsPeriod; if (cc <= 0) { return 0; } vTrigType[TrigNo] = Type; vCC[TrigNo] = cc; vpReg->TASKS_CAPTURE[TrigNo] = 1; uint32_t count = vpReg->CC[TrigNo]; vpReg->SHORTS |= TIMER_SHORTS_COMPARE0_CLEAR_Msk << TrigNo; if (vEvtHandler) { vpReg->INTENSET = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos); } vpReg->CC[TrigNo] = count + cc - INTERRUPT_LATENCY; if (count < vLastCount) { // Counter wrap arround vRollover += vFreq; } vLastCount = count; return vnsPeriod * (uint64_t)cc / 10ULL; // Return real period in nsec } void TimerHFnRF5x::DisableTimerTrigger(int TrigNo) { if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt) return; vTrigType[TrigNo] = TIMER_TRIG_TYPE_SINGLE; vCC[TrigNo] = 0; vpReg->CC[TrigNo] = 0; vpReg->INTENCLR = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos); } <commit_msg>Full counting<commit_after>/*-------------------------------------------------------------------------- File : timer_hf_nrf5x.cpp Author : Hoang Nguyen Hoan Sep. 7, 2017 Desc : timer class implementation on Nordic nRF5x series using high frequency timer (TIMERx) Copyright (c) 2017, 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 ----------------------------------------------------------------------------*/ #include "nrf.h" #include "timer_nrf5x.h" #include "iopinctrl.h" #define INTERRUPT_LATENCY 11 static TimerHFnRF5x *s_pDevObj[TIMER_NRF5X_HF_MAX] = { NULL, }; void TimerHFnRF5x::IRQHandler() { uint32_t evt = 0; uint32_t count; vpReg->TASKS_CAPTURE[0] = 1; count = vpReg->CC[0]; for (int i = 0; i < vMaxNbTrigEvt; i++) { if (vpReg->EVENTS_COMPARE[i]) { evt |= 1 << (i + 2); vpReg->EVENTS_COMPARE[i] = 0; if (vTrigType[i] == TIMER_TRIG_TYPE_CONTINUOUS) { vpReg->CC[i] = count + vCC[i] - INTERRUPT_LATENCY; } } } if (count < vLastCount) { // Counter wrap arround evt |= TIMER_EVT_COUNTER_OVR; vRollover += vFreq; } vLastCount = count; if (vEvtHandler) { vEvtHandler(this, evt); } } extern "C" { void TIMER0_IRQHandler() { if (s_pDevObj[0]) s_pDevObj[0]->IRQHandler(); } void TIMER1_IRQHandler() { if (s_pDevObj[1]) s_pDevObj[1]->IRQHandler(); } void TIMER2_IRQHandler() { if (s_pDevObj[2]) s_pDevObj[2]->IRQHandler(); } void TIMER3_IRQHandler() { if (s_pDevObj[3]) s_pDevObj[3]->IRQHandler(); } void TIMER4_IRQHandler() { if (s_pDevObj[4]) s_pDevObj[4]->IRQHandler(); } } // extern "C" TimerHFnRF5x::TimerHFnRF5x() { } TimerHFnRF5x::~TimerHFnRF5x() { } bool TimerHFnRF5x::Init(const TIMER_CFG &Cfg) { if (Cfg.DevNo < 0 || Cfg.DevNo >= TIMER_NRF5X_HF_MAX) return false; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT - 2; switch (Cfg.DevNo) { case 0: s_pDevObj[0] = this; vpReg = NRF_TIMER0; break; case 1: s_pDevObj[1] = this; vpReg = NRF_TIMER1; break; case 2: s_pDevObj[2] = this; vpReg = NRF_TIMER2; break; case 3: s_pDevObj[3] = this; vpReg = NRF_TIMER3; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT; break; case 4: s_pDevObj[4] = this; vpReg = NRF_TIMER4; vMaxNbTrigEvt = TIMER_NRF5X_HF_MAX_TRIGGER_EVT; break; } vpReg->TASKS_STOP = 1; vpReg->TASKS_CLEAR = 1; NRF_CLOCK->TASKS_HFCLKSTOP = 1; vEvtHandler = Cfg.EvtHandler; vDevNo = Cfg.DevNo; // Only support timer mode, 32bits counter vpReg->MODE = TIMER_MODE_MODE_Timer; vpReg->BITMODE = TIMER_BITMODE_BITMODE_32Bit; uint32_t prescaler = 0; if (Cfg.Freq > 0) { uint32_t divisor = 16000000 / Cfg.Freq; prescaler = 31 - __builtin_clzl(divisor); if (prescaler > 9) { prescaler = 9; } } vpReg->PRESCALER = prescaler; vFreq = 16000000 / (1 << prescaler); // Pre-calculate periods for faster timer counter to time conversion use later vnsPeriod = 10000000000ULL / vFreq; // Period in nsec if (Cfg.EvtHandler) { switch (Cfg.DevNo) { case 0: NVIC_ClearPendingIRQ(TIMER0_IRQn); NVIC_SetPriority(TIMER0_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER0_IRQn); break; case 1: NVIC_ClearPendingIRQ(TIMER1_IRQn); NVIC_SetPriority(TIMER1_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER1_IRQn); break; case 2: NVIC_ClearPendingIRQ(TIMER2_IRQn); NVIC_SetPriority(TIMER2_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER2_IRQn); break; case 3: NVIC_ClearPendingIRQ(TIMER3_IRQn); NVIC_SetPriority(TIMER3_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER3_IRQn); break; case 4: NVIC_ClearPendingIRQ(TIMER4_IRQn); NVIC_SetPriority(TIMER4_IRQn, Cfg.IntPrio); NVIC_EnableIRQ(TIMER4_IRQn); break; } } // Clock source not available. Only 64MHz XTAL NRF_CLOCK->TASKS_HFCLKSTART = 1; int timout = 1000000; do { if ((NRF_CLOCK->HFCLKSTAT & CLOCK_HFCLKSTAT_STATE_Msk) || NRF_CLOCK->EVENTS_HFCLKSTARTED) break; } while (timout-- > 0); if (timout <= 0) return false; NRF_CLOCK->EVENTS_HFCLKSTARTED = 0; vpReg->TASKS_START = 1; return true; } bool TimerHFnRF5x::Enable() { return true; } void TimerHFnRF5x::Disable() { } void TimerHFnRF5x::Reset() { vpReg->TASKS_CLEAR = 1; } uint32_t TimerHFnRF5x::Frequency(uint32_t Freq) { } uint64_t TimerHFnRF5x::TickCount() { if (vpReg->INTENSET == 0) { vpReg->TASKS_CAPTURE[vDevNo] = 1; uint32_t count = vpReg->CC[vDevNo]; if (count < vLastCount) { // Counter wrap arround vRollover += vFreq; } vLastCount = count; } return (uint64_t)vLastCount + vRollover; } uint64_t TimerHFnRF5x::EnableTimerTrigger(int TrigNo, uint64_t nsPeriod, TIMER_TRIG_TYPE Type) { if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt) return 0; uint32_t cc = (nsPeriod * 10ULL + (vnsPeriod >> 1)) / vnsPeriod; if (cc <= 0) { return 0; } vTrigType[TrigNo] = Type; vCC[TrigNo] = cc; vpReg->TASKS_CAPTURE[TrigNo] = 1; uint32_t count = vpReg->CC[TrigNo]; if (vEvtHandler) { vpReg->INTENSET = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos); } vpReg->CC[TrigNo] = count + cc - INTERRUPT_LATENCY; if (count < vLastCount) { // Counter wrap arround vRollover += vFreq; } vLastCount = count; return vnsPeriod * (uint64_t)cc / 10ULL; // Return real period in nsec } void TimerHFnRF5x::DisableTimerTrigger(int TrigNo) { if (TrigNo < 0 || TrigNo >= vMaxNbTrigEvt) return; vTrigType[TrigNo] = TIMER_TRIG_TYPE_SINGLE; vCC[TrigNo] = 0; vpReg->CC[TrigNo] = 0; vpReg->INTENCLR = 1 << (TrigNo + TIMER_INTENSET_COMPARE0_Pos); } <|endoftext|>
<commit_before>/* * A client for the logging protocol. * * author: Max Kellermann <mk@cm4all.com> */ #include "log_client.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <unistd.h> #include <sys/socket.h> #include <errno.h> #include <string.h> struct LogClient { int fd; size_t position; char buffer[32768]; }; LogClient * log_client_new(int fd) { assert(fd >= 0); LogClient *l = g_new(LogClient, 1); l->fd = fd; return l; } void log_client_free(LogClient *l) { close(l->fd); g_free(l); } static void log_client_append(LogClient *client, const void *p, size_t length) { if (client->position + length <= sizeof(client->buffer)) memcpy(client->buffer + client->position, p, length); client->position += length; } void log_client_begin(LogClient *client) { client->position = 0; log_client_append(client, &log_magic, sizeof(log_magic)); } void log_client_append_attribute(LogClient *client, enum beng_log_attribute attribute, const void *value, size_t length) { uint8_t attribute8 = (uint8_t)attribute; log_client_append(client, &attribute8, sizeof(attribute8)); log_client_append(client, value, length); } void log_client_append_u16(LogClient *client, enum beng_log_attribute attribute, uint16_t value) { const uint16_t value2 = GUINT16_TO_BE(value); log_client_append_attribute(client, attribute, &value2, sizeof(value2)); } void log_client_append_u64(LogClient *client, enum beng_log_attribute attribute, uint64_t value) { const uint64_t value2 = GUINT64_TO_BE(value); log_client_append_attribute(client, attribute, &value2, sizeof(value2)); } void log_client_append_string(LogClient *client, enum beng_log_attribute attribute, const char *value) { assert(value != nullptr); log_client_append_attribute(client, attribute, value, strlen(value) + 1); } bool log_client_commit(LogClient *client) { assert(client != nullptr); assert(client->fd >= 0); assert(client->position > 0); if (client->position > sizeof(client->buffer)) /* datagram is too large */ return false; ssize_t nbytes = send(client->fd, client->buffer, client->position, MSG_DONTWAIT|MSG_NOSIGNAL); if (nbytes < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) /* silently ignore EAGAIN */ return true; daemon_log(1, "Failed to send to logger: %s\n", strerror(errno)); return false; } if ((size_t)nbytes != client->position) daemon_log(1, "Short send to logger: %s\n", strerror(errno)); return true; } <commit_msg>log_client: use util/ByteOrder.hxx instead of GLib<commit_after>/* * A client for the logging protocol. * * author: Max Kellermann <mk@cm4all.com> */ #include "log_client.hxx" #include "util/ByteOrder.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <unistd.h> #include <sys/socket.h> #include <errno.h> #include <string.h> struct LogClient { int fd; size_t position; char buffer[32768]; }; LogClient * log_client_new(int fd) { assert(fd >= 0); LogClient *l = g_new(LogClient, 1); l->fd = fd; return l; } void log_client_free(LogClient *l) { close(l->fd); g_free(l); } static void log_client_append(LogClient *client, const void *p, size_t length) { if (client->position + length <= sizeof(client->buffer)) memcpy(client->buffer + client->position, p, length); client->position += length; } void log_client_begin(LogClient *client) { client->position = 0; log_client_append(client, &log_magic, sizeof(log_magic)); } void log_client_append_attribute(LogClient *client, enum beng_log_attribute attribute, const void *value, size_t length) { uint8_t attribute8 = (uint8_t)attribute; log_client_append(client, &attribute8, sizeof(attribute8)); log_client_append(client, value, length); } void log_client_append_u16(LogClient *client, enum beng_log_attribute attribute, uint16_t value) { const uint16_t value2 = ToBE16(value); log_client_append_attribute(client, attribute, &value2, sizeof(value2)); } void log_client_append_u64(LogClient *client, enum beng_log_attribute attribute, uint64_t value) { const uint64_t value2 = ToBE64(value); log_client_append_attribute(client, attribute, &value2, sizeof(value2)); } void log_client_append_string(LogClient *client, enum beng_log_attribute attribute, const char *value) { assert(value != nullptr); log_client_append_attribute(client, attribute, value, strlen(value) + 1); } bool log_client_commit(LogClient *client) { assert(client != nullptr); assert(client->fd >= 0); assert(client->position > 0); if (client->position > sizeof(client->buffer)) /* datagram is too large */ return false; ssize_t nbytes = send(client->fd, client->buffer, client->position, MSG_DONTWAIT|MSG_NOSIGNAL); if (nbytes < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) /* silently ignore EAGAIN */ return true; daemon_log(1, "Failed to send to logger: %s\n", strerror(errno)); return false; } if ((size_t)nbytes != client->position) daemon_log(1, "Short send to logger: %s\n", strerror(errno)); return true; } <|endoftext|>
<commit_before><commit_msg>Ensure object host streams are closed on disconnect.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2015-2016 Andrew Sutton // All rights reserved #include "parser.hpp" #include "ast.hpp" #include <iostream> namespace banjo { namespace { // Returns a spelling for the current token. If the token // stream is at the end of input, then the spelling will // reflect that state. String const& token_spelling(Token_stream& ts) { static String end = "end-of-input"; if (ts.eof()) return end; else return ts.peek().spelling(); } } // namespace // Return the symbol table. Symbol_table& Parser::symbols() { return cxt.symbols(); } // Returns true if at the end of input. bool Parser::is_eof() const { return !peek(); } // Returns the current token. Token Parser::peek() const { return tokens.peek(); } // Returns the first token of lookahead. Token_kind Parser::lookahead() const { return Token_kind(peek().kind()); } // Returns the nth token of lookahead. Token_kind Parser::lookahead(int n) const { return Token_kind(tokens.peek(n).kind()); } // Returns true if the next token has the given kind. bool Parser::next_token_is(Token_kind k) { return lookahead() == k; } // Returns true if the next token is an identifier with // the given spelling. bool Parser::next_token_is(char const* s) { return next_token_is(identifier_tok) && peek().spelling() == s; } // Returns true if the next token does not have the given kind. bool Parser::next_token_is_not(Token_kind k) { return lookahead() != k; } // Returns true if the next token is not identifier with // the given spelling. bool Parser::next_token_is_not(char const* s) { if (next_token_is_not(identifier_tok)) return false; return peek().spelling() == s; } // Require that the next token matches in kind. Emit a diagnostic // message if it does not. Token Parser::match(Token_kind k) { if (lookahead() == k) return accept(); String msg = format("expected '{}' but got '{}'", get_spelling(k), token_spelling(tokens)); throw Syntax_error(cxt, msg); } // If the current token matches k, return the token // and advance the stream. Otherwise, return an // invalid token. // // Note that invalid tokens evaluate to false. Token Parser::match_if(Token_kind k) { if (lookahead() == k) return accept(); else return Token(); } // Require a token of the given kind. Behavior is udefined if the token // does not match. Token Parser::require(Token_kind k) { lingo_assert(lookahead() == k); return accept(); } // Require an identifier matching the spelling of s. Token Parser::require(char const* s) { lingo_assert(next_token_is(s)); return accept(); } // Emit an error if the next token is not of the kind given. Note that // this does not consume the token. void Parser::expect(Token_kind k) { if (next_token_is_not(k)) { String msg = format("expected '{}' but got '{}'", get_spelling(k), token_spelling(tokens)); throw Syntax_error(cxt, msg); } } // Returns the current token and advances the underlying // token stream. // // TODO: Record information about matching braces here. Token Parser::accept() { Token tok = tokens.get(); // Update the global input location. cxt.input_location(tok.location()); // If the token is a brace, then record that for the purpose of // brace matching and diagnostics. switch (tok.kind()) { case lparen_tok: case lbrace_tok: case lbracket_tok: open_brace(tok); break; case rparen_tok: case rbrace_tok: case rbracket_tok: close_brace(tok); break; } return tok; } void Parser::open_brace(Token tok) { Braces& braces = state.braces; braces.open(tok); } // Return the the kind of closing brace that would match the closing // token. static inline Token_kind get_closing_brace(Token tok) { switch (tok.kind()) { case lparen_tok: return rparen_tok; case lbrace_tok: return rbrace_tok; case lbracket_tok: return rbracket_tok; default: lingo_unreachable(); } } // TODO: It might be nice to have a function that returns the opener // for a closer. static inline bool is_matching_brace(Token left, Token right) { return get_closing_brace(left) == right.kind(); } void Parser::close_brace(Token tok) { Braces& braces = state.braces; if (braces.empty()) { error(cxt, "unmatched brace '{}'", tok); throw Syntax_error("mismatched brace"); } Token prev = braces.back(); if (!is_matching_brace(prev, tok)) { // FIXME: show the location of the matching brace. error(cxt, "unbalanced brace '{}'", tok); throw Syntax_error("unbalanced brace"); } braces.close(); } // Return true if the current brace nesting level is non-zero. That is, // we have accepted at least one bracketing character, but not its matching // closing brace. bool Parser::in_braces() const { return !state.braces.empty(); } // Returns true when the current brace nesting level is n. This is useful // when checking for closing tokens at a non-empty nesting level (e.g., // inside function parameter lists). bool Parser::in_level(int n) const { return brace_level() == n; } // Returns the current brace nesting level. int Parser::brace_level() const { return state.braces.size(); } // -------------------------------------------------------------------------- // // Scope management // Returns the current scope. Scope& Parser::current_scope() { return cxt.current_scope(); } // -------------------------------------------------------------------------- // // Miscellaneous parsing // Parse a translation unit. // // input: // [statement-list] // // FIXME: This should return a single node, not a sequence. Stmt& Parser::translation() { // TODO: We should enter the global scope and not create a temporary // one. Enter_scope scope(cxt); Stmt_list ss = statement_seq(); return on_translation_statement(std::move(ss)); } Stmt& Parser::operator()() { return translation(); } } // namespace banjo <commit_msg>Adding notes to translation parsing.<commit_after>// Copyright (c) 2015-2016 Andrew Sutton // All rights reserved #include "parser.hpp" #include "ast.hpp" #include <iostream> namespace banjo { namespace { // Returns a spelling for the current token. If the token // stream is at the end of input, then the spelling will // reflect that state. String const& token_spelling(Token_stream& ts) { static String end = "end-of-input"; if (ts.eof()) return end; else return ts.peek().spelling(); } } // namespace // Return the symbol table. Symbol_table& Parser::symbols() { return cxt.symbols(); } // Returns true if at the end of input. bool Parser::is_eof() const { return !peek(); } // Returns the current token. Token Parser::peek() const { return tokens.peek(); } // Returns the first token of lookahead. Token_kind Parser::lookahead() const { return Token_kind(peek().kind()); } // Returns the nth token of lookahead. Token_kind Parser::lookahead(int n) const { return Token_kind(tokens.peek(n).kind()); } // Returns true if the next token has the given kind. bool Parser::next_token_is(Token_kind k) { return lookahead() == k; } // Returns true if the next token is an identifier with // the given spelling. bool Parser::next_token_is(char const* s) { return next_token_is(identifier_tok) && peek().spelling() == s; } // Returns true if the next token does not have the given kind. bool Parser::next_token_is_not(Token_kind k) { return lookahead() != k; } // Returns true if the next token is not identifier with // the given spelling. bool Parser::next_token_is_not(char const* s) { if (next_token_is_not(identifier_tok)) return false; return peek().spelling() == s; } // Require that the next token matches in kind. Emit a diagnostic // message if it does not. Token Parser::match(Token_kind k) { if (lookahead() == k) return accept(); String msg = format("expected '{}' but got '{}'", get_spelling(k), token_spelling(tokens)); throw Syntax_error(cxt, msg); } // If the current token matches k, return the token // and advance the stream. Otherwise, return an // invalid token. // // Note that invalid tokens evaluate to false. Token Parser::match_if(Token_kind k) { if (lookahead() == k) return accept(); else return Token(); } // Require a token of the given kind. Behavior is udefined if the token // does not match. Token Parser::require(Token_kind k) { lingo_assert(lookahead() == k); return accept(); } // Require an identifier matching the spelling of s. Token Parser::require(char const* s) { lingo_assert(next_token_is(s)); return accept(); } // Emit an error if the next token is not of the kind given. Note that // this does not consume the token. void Parser::expect(Token_kind k) { if (next_token_is_not(k)) { String msg = format("expected '{}' but got '{}'", get_spelling(k), token_spelling(tokens)); throw Syntax_error(cxt, msg); } } // Returns the current token and advances the underlying // token stream. // // TODO: Record information about matching braces here. Token Parser::accept() { Token tok = tokens.get(); // Update the global input location. cxt.input_location(tok.location()); // If the token is a brace, then record that for the purpose of // brace matching and diagnostics. switch (tok.kind()) { case lparen_tok: case lbrace_tok: case lbracket_tok: open_brace(tok); break; case rparen_tok: case rbrace_tok: case rbracket_tok: close_brace(tok); break; } return tok; } void Parser::open_brace(Token tok) { Braces& braces = state.braces; braces.open(tok); } // Return the the kind of closing brace that would match the closing // token. static inline Token_kind get_closing_brace(Token tok) { switch (tok.kind()) { case lparen_tok: return rparen_tok; case lbrace_tok: return rbrace_tok; case lbracket_tok: return rbracket_tok; default: lingo_unreachable(); } } // TODO: It might be nice to have a function that returns the opener // for a closer. static inline bool is_matching_brace(Token left, Token right) { return get_closing_brace(left) == right.kind(); } void Parser::close_brace(Token tok) { Braces& braces = state.braces; if (braces.empty()) { error(cxt, "unmatched brace '{}'", tok); throw Syntax_error("mismatched brace"); } Token prev = braces.back(); if (!is_matching_brace(prev, tok)) { // FIXME: show the location of the matching brace. error(cxt, "unbalanced brace '{}'", tok); throw Syntax_error("unbalanced brace"); } braces.close(); } // Return true if the current brace nesting level is non-zero. That is, // we have accepted at least one bracketing character, but not its matching // closing brace. bool Parser::in_braces() const { return !state.braces.empty(); } // Returns true when the current brace nesting level is n. This is useful // when checking for closing tokens at a non-empty nesting level (e.g., // inside function parameter lists). bool Parser::in_level(int n) const { return brace_level() == n; } // Returns the current brace nesting level. int Parser::brace_level() const { return state.braces.size(); } // -------------------------------------------------------------------------- // // Scope management // Returns the current scope. Scope& Parser::current_scope() { return cxt.current_scope(); } // -------------------------------------------------------------------------- // // Miscellaneous parsing // Parse a translation unit. // // translation: // [statement-list] // // FIXME: Rethink the program structure for the language. In particular, // we should prefer to think in terms of program fragments. Fragments can // be combined to define libraries (archives?), modules, and programs. // This can probably be achieved by simply renaming Translation_stmt to // Fragment_stmt, although it would probably be nice to revisit the design // of compound statements in general. Stmt& Parser::translation() { // TODO: We should enter the global scope and not create a temporary. Enter_scope scope(cxt); Stmt_list ss = statement_seq(); return on_translation_statement(std::move(ss)); } Stmt& Parser::operator()() { return translation(); } } // namespace banjo <|endoftext|>
<commit_before>/* * Copyright (C) 2015-present ScyllaDB */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #include "failure_detector.hh" #include "api/api-doc/failure_detector.json.hh" #include "gms/failure_detector.hh" #include "gms/application_state.hh" #include "gms/gossiper.hh" namespace api { namespace fd = httpd::failure_detector_json; void set_failure_detector(http_context& ctx, routes& r, gms::gossiper& g) { fd::get_all_endpoint_states.set(r, [&g](std::unique_ptr<request> req) { std::vector<fd::endpoint_state> res; for (auto i : g.get_endpoint_states()) { fd::endpoint_state val; val.addrs = boost::lexical_cast<std::string>(i.first); val.is_alive = i.second.is_alive(); val.generation = i.second.get_heart_beat_state().get_generation(); val.version = i.second.get_heart_beat_state().get_heart_beat_version(); val.update_time = i.second.get_update_timestamp().time_since_epoch().count(); for (auto a : i.second.get_application_state_map()) { fd::version_value version_val; // We return the enum index and not it's name to stay compatible to origin // method that the state index are static but the name can be changed. version_val.application_state = static_cast<std::underlying_type<gms::application_state>::type>(a.first); version_val.value = a.second.value; version_val.version = a.second.version; val.application_state.push(version_val); } res.push_back(val); } return make_ready_future<json::json_return_type>(res); }); fd::get_up_endpoint_count.set(r, [&g](std::unique_ptr<request> req) { return gms::get_up_endpoint_count(g).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); fd::get_down_endpoint_count.set(r, [&g](std::unique_ptr<request> req) { return gms::get_down_endpoint_count(g).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); fd::get_phi_convict_threshold.set(r, [] (std::unique_ptr<request> req) { return make_ready_future<json::json_return_type>(8); }); fd::get_simple_states.set(r, [&g] (std::unique_ptr<request> req) { std::map<sstring, sstring> nodes_status; for (auto& entry : g.get_endpoint_states()) { nodes_status.emplace(entry.first.to_sstring(), entry.second.is_alive() ? "UP" : "DOWN"); } return make_ready_future<json::json_return_type>(map_to_key_value<fd::mapper>(nodes_status)); }); fd::set_phi_convict_threshold.set(r, [](std::unique_ptr<request> req) { double phi = atof(req->get_query_param("phi").c_str()); return make_ready_future<json::json_return_type>(""); }); fd::get_endpoint_state.set(r, [&g] (std::unique_ptr<request> req) { auto* state = g.get_endpoint_state_for_endpoint_ptr(gms::inet_address(req->param["addr"])); if (!state) { return make_ready_future<json::json_return_type>(format("unknown endpoint {}", req->param["addr"])); } std::stringstream ss; g.append_endpoint_state(ss, *state); return make_ready_future<json::json_return_type>(sstring(ss.str())); }); fd::get_endpoint_phi_values.set(r, [](std::unique_ptr<request> req) { std::map<gms::inet_address, gms::arrival_window> map; std::vector<fd::endpoint_phi_value> res; auto now = gms::arrival_window::clk::now(); for (auto& p : map) { fd::endpoint_phi_value val; val.endpoint = p.first.to_sstring(); val.phi = p.second.phi(now); res.emplace_back(std::move(val)); } return make_ready_future<json::json_return_type>(res); }); } } <commit_msg>api: Fix indentation after previous patch<commit_after>/* * Copyright (C) 2015-present ScyllaDB */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #include "failure_detector.hh" #include "api/api-doc/failure_detector.json.hh" #include "gms/failure_detector.hh" #include "gms/application_state.hh" #include "gms/gossiper.hh" namespace api { namespace fd = httpd::failure_detector_json; void set_failure_detector(http_context& ctx, routes& r, gms::gossiper& g) { fd::get_all_endpoint_states.set(r, [&g](std::unique_ptr<request> req) { std::vector<fd::endpoint_state> res; for (auto i : g.get_endpoint_states()) { fd::endpoint_state val; val.addrs = boost::lexical_cast<std::string>(i.first); val.is_alive = i.second.is_alive(); val.generation = i.second.get_heart_beat_state().get_generation(); val.version = i.second.get_heart_beat_state().get_heart_beat_version(); val.update_time = i.second.get_update_timestamp().time_since_epoch().count(); for (auto a : i.second.get_application_state_map()) { fd::version_value version_val; // We return the enum index and not it's name to stay compatible to origin // method that the state index are static but the name can be changed. version_val.application_state = static_cast<std::underlying_type<gms::application_state>::type>(a.first); version_val.value = a.second.value; version_val.version = a.second.version; val.application_state.push(version_val); } res.push_back(val); } return make_ready_future<json::json_return_type>(res); }); fd::get_up_endpoint_count.set(r, [&g](std::unique_ptr<request> req) { return gms::get_up_endpoint_count(g).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); fd::get_down_endpoint_count.set(r, [&g](std::unique_ptr<request> req) { return gms::get_down_endpoint_count(g).then([](int res) { return make_ready_future<json::json_return_type>(res); }); }); fd::get_phi_convict_threshold.set(r, [] (std::unique_ptr<request> req) { return make_ready_future<json::json_return_type>(8); }); fd::get_simple_states.set(r, [&g] (std::unique_ptr<request> req) { std::map<sstring, sstring> nodes_status; for (auto& entry : g.get_endpoint_states()) { nodes_status.emplace(entry.first.to_sstring(), entry.second.is_alive() ? "UP" : "DOWN"); } return make_ready_future<json::json_return_type>(map_to_key_value<fd::mapper>(nodes_status)); }); fd::set_phi_convict_threshold.set(r, [](std::unique_ptr<request> req) { double phi = atof(req->get_query_param("phi").c_str()); return make_ready_future<json::json_return_type>(""); }); fd::get_endpoint_state.set(r, [&g] (std::unique_ptr<request> req) { auto* state = g.get_endpoint_state_for_endpoint_ptr(gms::inet_address(req->param["addr"])); if (!state) { return make_ready_future<json::json_return_type>(format("unknown endpoint {}", req->param["addr"])); } std::stringstream ss; g.append_endpoint_state(ss, *state); return make_ready_future<json::json_return_type>(sstring(ss.str())); }); fd::get_endpoint_phi_values.set(r, [](std::unique_ptr<request> req) { std::map<gms::inet_address, gms::arrival_window> map; std::vector<fd::endpoint_phi_value> res; auto now = gms::arrival_window::clk::now(); for (auto& p : map) { fd::endpoint_phi_value val; val.endpoint = p.first.to_sstring(); val.phi = p.second.phi(now); res.emplace_back(std::move(val)); } return make_ready_future<json::json_return_type>(res); }); } } <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanMethod class. * This class describes the Scan method * * Created for COPASI by Rohan Luktuke 2002 */ #include <string> #include <cmath> #include "copasi.h" #include "model/CModel.h" #include "model/CState.h" #include "utilities/CReadConfig.h" #include "randomGenerator/CRandom.h" //#include "utilities/CWriteConfig.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "CScanTask.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include <utilities/CCopasiMessage.h> // this will have to be defined somewhere else with the // values of other distribution types //#define SD_UNIFORM 0 //#define SD_GAUSS 1 //#define SD_BOLTZ 2 //#define SD_REGULAR 3 //**************** CScanItem classes *************************** //static CScanItem* CScanItem::createScanItemFromParameterGroup(CCopasiParameterGroup* si, CRandom* rg, const bool & continueFromCurrentState) { if (!si) return NULL; CScanProblem::Type type = *(CScanProblem::Type*)(si->getValue("Type").pUINT); CScanItem* tmp = NULL; if (type == CScanProblem::SCAN_REPEAT) tmp = new CScanItemRepeat(si, continueFromCurrentState); if (type == CScanProblem::SCAN_LINEAR) tmp = new CScanItemLinear(si, continueFromCurrentState); if (type == CScanProblem::SCAN_RANDOM) tmp = new CScanItemRandom(si, rg, continueFromCurrentState); /* if (type == CScanProblem::SCAN_BREAK) tmp = new CScanItemBreak(si, st);*/ return tmp; } CScanItem::CScanItem(): mNumSteps(0), mpObject(NULL), mpInitialObject(NULL), mStoreValue(0.0), mIndex(0), mFlagFinished(false), mIsStateVariable(false) {} CScanItem::CScanItem(CCopasiParameterGroup* si, const bool & continueFromCurrentState): mNumSteps(0), mpObject(NULL), mpInitialObject(NULL), mStoreValue(0.0), mIndex(0), mFlagFinished(false), mIsStateVariable(false) { assert(si != NULL); mNumSteps = * si->getValue("Number of steps").pUINT; std::string tmpString = * si->getValue("Object").pCN; CCopasiDataModel* pDataModel = si->getObjectDataModel(); assert(pDataModel != NULL); CCopasiObject * tmpObject = pDataModel->getDataObject(tmpString); if (tmpObject == NULL || !tmpObject->isValueDbl()) { return; } mpInitialObject = tmpObject; if (continueFromCurrentState) { // Determine whether the object is the initial value of a state variable; const CModel * pModel = static_cast< CModel * >(mpInitialObject->getObjectAncestor("Model")); if (pModel != NULL) { mIsStateVariable = pModel->isStateVariable(tmpObject); if (!mIsStateVariable) { // We need to find the object for the transient value if it exists so that we can update while continuing. mpObject = pModel->getCorrespondingTransientObject(tmpObject); } } } else { mpObject = mpInitialObject; } } size_t CScanItem::getNumSteps() const {return mNumSteps;}; void CScanItem::restoreValue() const { if (mpObject) mpObject->setObjectValue(mStoreValue); }; void CScanItem::storeValue() { if (mpObject) { assert(mpObject->isValueDbl()); mStoreValue = * (C_FLOAT64 *) mpObject->getValuePointer(); } }; void CScanItem::reset() { mIndex = 0; mFlagFinished = false; this->step(); //purely virtual } bool CScanItem::isFinished() const {return mFlagFinished;}; bool CScanItem::isValidScanItem(const bool & continueFromCurrentState) { if (continueFromCurrentState && mIsStateVariable && mpObject == NULL) { CCopasiMessage(CCopasiMessage::WARNING, MCScan + 1, mpInitialObject->getObjectDisplayName().c_str()); return true; } if (mpInitialObject == NULL) { CCopasiMessage(CCopasiMessage::ERROR, "Invalid or missing scan parameter."); return false; } return true; } const CCopasiObject * CScanItem::getObject() const { return mpObject; } //******* CScanItemRepeat::CScanItemRepeat(CCopasiParameterGroup* si, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState) { if (mNumSteps >= 1) --mNumSteps; // for the repeat item mNumSteps is the number of iterations, not of intervals } void CScanItemRepeat::step() { //do something ... //the index if (mIndex > mNumSteps) mFlagFinished = true; ++mIndex; } bool CScanItemRepeat::isValidScanItem(const bool & /* continueFromCurrentState */) { return true; } //******* CScanItemLinear::CScanItemLinear(CCopasiParameterGroup* si, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState), mLog(false) { mLog = * si->getValue("log").pBOOL; mMin = * si->getValue("Minimum").pDOUBLE; mMax = * si->getValue("Maximum").pDOUBLE; if (mLog) { mMin = log(mMin); mMax = log(mMax); } mFaktor = (mMax - mMin) / mNumSteps; //TODO: log scanning of negative values? } void CScanItemLinear::step() { //do something ... C_FLOAT64 Value = mMin + mIndex * mFaktor; if (mLog) Value = exp(Value); //the index if (mIndex > mNumSteps) mFlagFinished = true; if (mpObject) mpObject->setObjectValue(Value); ++mIndex; } bool CScanItemLinear::isValidScanItem(const bool & continueFromCurrentState) { if (!CScanItem::isValidScanItem(continueFromCurrentState)) return false; if (mLog) { if (isnan(mFaktor) || mFaktor < - std::numeric_limits< C_FLOAT64 >::max() || std::numeric_limits< C_FLOAT64 >::max() < mFaktor) { //not a valid range for log CCopasiMessage(CCopasiMessage::ERROR, "Only positive values for min and max are possible for a logarithmic scan."); return false; } } return true; } //******* CScanItemRandom::CScanItemRandom(CCopasiParameterGroup* si, CRandom* rg, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState), mRg(rg), mRandomType(0), mLog(false) { mRandomType = * si->getValue("Distribution type").pUINT; mLog = * si->getValue("log").pBOOL; mMin = * si->getValue("Minimum").pDOUBLE; mMax = * si->getValue("Maximum").pDOUBLE; if (mLog && mRandomType == 0) { mMin = log(mMin); mMax = log(mMax); } mNumSteps = 0; mFaktor = (mMax - mMin); } void CScanItemRandom::step() { C_FLOAT64 Value; //the index if (mIndex > mNumSteps) mFlagFinished = true; else { C_FLOAT64 tmpF; switch (mRandomType) { case 0: // uniform Value = mMin + mRg->getRandomCC() * mFaktor; if (mLog) Value = exp(Value); break; case 1: // normal tmpF = mRg->getRandomNormal01(); Value = mMin + tmpF * mMax; if (mLog) Value = exp(Value); break; case 2: // poisson if (mMin < 0) CCopasiMessage(CCopasiMessage::WARNING, "Invalid ScanItem: Requested Poisson random variable for negative argument: %lf", mMin); Value = mRg->getRandomPoisson(mMin); break; case 3: // gamma Value = mRg->getRandomGamma(mMin, mMax); if (mLog) Value = exp(Value); break; } } if (mpObject) mpObject->setObjectValue(Value); ++mIndex; } //**************** CScanMethod class *************************** CScanMethod * CScanMethod::createMethod(CCopasiMethod::SubType /* subType */) { return new CScanMethod(); } CScanMethod::CScanMethod(): CCopasiMethod(CCopasiTask::scan, CCopasiMethod::scanMethod), mpProblem(NULL), mpTask(NULL), mpRandomGenerator(NULL), mTotalSteps(1), mLastNestingItem(C_INVALID_INDEX), mContinueFromCurrentState(false) { mpRandomGenerator = CRandom::createGenerator(CRandom::r250); } CScanMethod::~CScanMethod() { cleanupScanItems(); delete mpRandomGenerator; mpRandomGenerator = NULL; } bool CScanMethod::cleanupScanItems() { if (!mpProblem) return false; size_t i, imax = mScanItems.size(); for (i = 0; i < imax; ++i) if (mScanItems[i]) delete mScanItems[i]; mScanItems.clear(); return true; } bool CScanMethod::init() { if (!mpProblem) return false; mpTask = dynamic_cast< CScanTask * >(getObjectParent()); if (mpTask == NULL) return false; cleanupScanItems(); mInitialRefreshes.clear(); //mTransientRefreshes.clear(); mTotalSteps = 1; std::set< const CCopasiObject * > InitialObjectSet; std::set< const CCopasiObject * > TransientObjectSet; size_t i, imax = mpProblem->getNumberOfScanItems(); mContinueFromCurrentState = mpProblem->getContinueFromCurrentState(); for (i = 0; i < imax; ++i) { CScanItem * pItem = CScanItem::createScanItemFromParameterGroup(mpProblem->getScanItem(i), mpRandomGenerator, mContinueFromCurrentState); if (pItem == NULL) { continue; } mScanItems.push_back(pItem); mTotalSteps *= pItem->getNumSteps() + 1; if (pItem->getObject() != NULL) { InitialObjectSet.insert(pItem->getObject()); } } if (mContinueFromCurrentState) { mInitialRefreshes = CCopasiObject::buildUpdateSequence(mpProblem->getModel()->getUptoDateObjects(), InitialObjectSet); } else { mInitialRefreshes = mpProblem->getModel()->buildInitialRefreshSequence(InitialObjectSet); } //set mLastNestingItem mLastNestingItem = C_INVALID_INDEX; if (imax != 0) { //search from the end size_t j; for (j = mScanItems.size() - 1; j != C_INVALID_INDEX; --j) { if (mScanItems[j]->isNesting()) { mLastNestingItem = j; break; } } } return true; } bool CScanMethod::scan() { if (!mpProblem) return false; //a hack to ensure that the first subtask is run with initial conditions //pDataModel->getModel()->setState(&mpProblem->getInitialState()); bool success = true; size_t i, imax = mScanItems.size(); //store old parameter values for (i = 0; i < imax; ++i) mScanItems[i]->storeValue(); //Do the scan... if (imax) //there are scan items success = loop(0); else success = calculate(); //nothing to scan, only one call to the subtask //restore old parameter values for (i = 0; i < imax; ++i) mScanItems[i]->restoreValue(); return success; } bool CScanMethod::loop(size_t level) { bool isLastMasterItem = (level == (mScanItems.size() - 1)); //TODO CScanItem* currentSI = mScanItems[level]; for (currentSI->reset(); !currentSI->isFinished(); currentSI->step()) { //TODO: handle slave SIs if (isLastMasterItem) { if (!calculate()) return false; } else { if (!loop(level + 1)) return false; } //TODO //separator needs to be handled slightly differently if we are at the last item if (currentSI->isNesting()) ((CScanTask*)(getObjectParent()))->outputSeparatorCallback(level == mLastNestingItem); } return true; } bool CScanMethod::calculate() { std::vector< Refresh * >::iterator it = mInitialRefreshes.begin(); std::vector< Refresh * >::iterator end = mInitialRefreshes.end(); while (it != end) (**it++)(); return mpTask->processCallback(); } void CScanMethod::setProblem(CScanProblem * problem) {mpProblem = problem;} //virtual bool CScanMethod::isValidProblem(const CCopasiProblem * pProblem) { if (!CCopasiMethod::isValidProblem(pProblem)) return false; const CScanProblem * pP = dynamic_cast<const CScanProblem *>(pProblem); if (!pP) { //not a TrajectoryProblem CCopasiMessage(CCopasiMessage::EXCEPTION, "Problem is not a Scan problem."); return false; } mContinueFromCurrentState = pP->getContinueFromCurrentState(); size_t i, imax = pP->getNumberOfScanItems(); if (imax <= 0) { //no scan items CCopasiMessage(CCopasiMessage::WARNING, "There is nothing to scan."); return false; } for (i = 0; i < imax; ++i) { CScanItem * si = CScanItem::createScanItemFromParameterGroup(mpProblem->getScanItem(i), mpRandomGenerator, mContinueFromCurrentState); if (!si) { //parameter group could not be interpreted CCopasiMessage(CCopasiMessage::ERROR, "Internal problem with scan definition."); return false; } if (!si->isValidScanItem(mContinueFromCurrentState)) { //the self check of the scan item failed. //the message should be generated by the isValidScanItem() method. delete si; return false; } delete si; //mTotalSteps *= mScanItems[i]->getNumSteps(); } return true; } <commit_msg>Fixed Bug 2117. The initial values are now also updated when "continue from current state" is selected.<commit_after>// Copyright (C) 2010 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CScanMethod class. * This class describes the Scan method * * Created for COPASI by Rohan Luktuke 2002 */ #include <string> #include <cmath> #include "copasi.h" #include "model/CModel.h" #include "model/CState.h" #include "utilities/CReadConfig.h" #include "randomGenerator/CRandom.h" //#include "utilities/CWriteConfig.h" #include "CScanProblem.h" #include "CScanMethod.h" #include "CScanTask.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include <utilities/CCopasiMessage.h> // this will have to be defined somewhere else with the // values of other distribution types //#define SD_UNIFORM 0 //#define SD_GAUSS 1 //#define SD_BOLTZ 2 //#define SD_REGULAR 3 //**************** CScanItem classes *************************** //static CScanItem* CScanItem::createScanItemFromParameterGroup(CCopasiParameterGroup* si, CRandom* rg, const bool & continueFromCurrentState) { if (!si) return NULL; CScanProblem::Type type = *(CScanProblem::Type*)(si->getValue("Type").pUINT); CScanItem* tmp = NULL; if (type == CScanProblem::SCAN_REPEAT) tmp = new CScanItemRepeat(si, continueFromCurrentState); if (type == CScanProblem::SCAN_LINEAR) tmp = new CScanItemLinear(si, continueFromCurrentState); if (type == CScanProblem::SCAN_RANDOM) tmp = new CScanItemRandom(si, rg, continueFromCurrentState); /* if (type == CScanProblem::SCAN_BREAK) tmp = new CScanItemBreak(si, st);*/ return tmp; } CScanItem::CScanItem(): mNumSteps(0), mpObject(NULL), mpInitialObject(NULL), mStoreValue(0.0), mIndex(0), mFlagFinished(false), mIsStateVariable(false) {} CScanItem::CScanItem(CCopasiParameterGroup* si, const bool & continueFromCurrentState): mNumSteps(0), mpObject(NULL), mpInitialObject(NULL), mStoreValue(0.0), mIndex(0), mFlagFinished(false), mIsStateVariable(false) { assert(si != NULL); mNumSteps = * si->getValue("Number of steps").pUINT; std::string tmpString = * si->getValue("Object").pCN; CCopasiDataModel* pDataModel = si->getObjectDataModel(); assert(pDataModel != NULL); CCopasiObject * tmpObject = pDataModel->getDataObject(tmpString); if (tmpObject == NULL || !tmpObject->isValueDbl()) { return; } mpInitialObject = tmpObject; if (continueFromCurrentState) { // Determine whether the object is the initial value of a state variable; const CModel * pModel = static_cast< CModel * >(mpInitialObject->getObjectAncestor("Model")); if (pModel != NULL) { mIsStateVariable = pModel->isStateVariable(tmpObject); if (!mIsStateVariable) { // We need to find the object for the transient value if it exists so that we can update while continuing. mpObject = pModel->getCorrespondingTransientObject(tmpObject); } } } else { mpObject = mpInitialObject; } } size_t CScanItem::getNumSteps() const {return mNumSteps;}; void CScanItem::restoreValue() const { if (mpObject) mpObject->setObjectValue(mStoreValue); }; void CScanItem::storeValue() { if (mpObject) { assert(mpObject->isValueDbl()); mStoreValue = * (C_FLOAT64 *) mpObject->getValuePointer(); } }; void CScanItem::reset() { mIndex = 0; mFlagFinished = false; this->step(); //purely virtual } bool CScanItem::isFinished() const {return mFlagFinished;}; bool CScanItem::isValidScanItem(const bool & continueFromCurrentState) { if (continueFromCurrentState && mIsStateVariable && mpObject == NULL) { CCopasiMessage(CCopasiMessage::WARNING, MCScan + 1, mpInitialObject->getObjectDisplayName().c_str()); return true; } if (mpInitialObject == NULL) { CCopasiMessage(CCopasiMessage::ERROR, "Invalid or missing scan parameter."); return false; } return true; } const CCopasiObject * CScanItem::getObject() const { return mpObject; } //******* CScanItemRepeat::CScanItemRepeat(CCopasiParameterGroup* si, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState) { if (mNumSteps >= 1) --mNumSteps; // for the repeat item mNumSteps is the number of iterations, not of intervals } void CScanItemRepeat::step() { //do something ... //the index if (mIndex > mNumSteps) mFlagFinished = true; ++mIndex; } bool CScanItemRepeat::isValidScanItem(const bool & /* continueFromCurrentState */) { return true; } //******* CScanItemLinear::CScanItemLinear(CCopasiParameterGroup* si, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState), mLog(false) { mLog = * si->getValue("log").pBOOL; mMin = * si->getValue("Minimum").pDOUBLE; mMax = * si->getValue("Maximum").pDOUBLE; if (mLog) { mMin = log(mMin); mMax = log(mMax); } mFaktor = (mMax - mMin) / mNumSteps; //TODO: log scanning of negative values? } void CScanItemLinear::step() { //do something ... C_FLOAT64 Value = mMin + mIndex * mFaktor; if (mLog) Value = exp(Value); //the index if (mIndex > mNumSteps) mFlagFinished = true; if (mpObject) mpObject->setObjectValue(Value); if (mpInitialObject) mpInitialObject->setObjectValue(Value); ++mIndex; } bool CScanItemLinear::isValidScanItem(const bool & continueFromCurrentState) { if (!CScanItem::isValidScanItem(continueFromCurrentState)) return false; if (mLog) { if (isnan(mFaktor) || mFaktor < - std::numeric_limits< C_FLOAT64 >::max() || std::numeric_limits< C_FLOAT64 >::max() < mFaktor) { //not a valid range for log CCopasiMessage(CCopasiMessage::ERROR, "Only positive values for min and max are possible for a logarithmic scan."); return false; } } return true; } //******* CScanItemRandom::CScanItemRandom(CCopasiParameterGroup* si, CRandom* rg, const bool & continueFromCurrentState): CScanItem(si, continueFromCurrentState), mRg(rg), mRandomType(0), mLog(false) { mRandomType = * si->getValue("Distribution type").pUINT; mLog = * si->getValue("log").pBOOL; mMin = * si->getValue("Minimum").pDOUBLE; mMax = * si->getValue("Maximum").pDOUBLE; if (mLog && mRandomType == 0) { mMin = log(mMin); mMax = log(mMax); } mNumSteps = 0; mFaktor = (mMax - mMin); } void CScanItemRandom::step() { C_FLOAT64 Value; //the index if (mIndex > mNumSteps) mFlagFinished = true; else { C_FLOAT64 tmpF; switch (mRandomType) { case 0: // uniform Value = mMin + mRg->getRandomCC() * mFaktor; if (mLog) Value = exp(Value); break; case 1: // normal tmpF = mRg->getRandomNormal01(); Value = mMin + tmpF * mMax; if (mLog) Value = exp(Value); break; case 2: // poisson if (mMin < 0) CCopasiMessage(CCopasiMessage::WARNING, "Invalid ScanItem: Requested Poisson random variable for negative argument: %lf", mMin); Value = mRg->getRandomPoisson(mMin); break; case 3: // gamma Value = mRg->getRandomGamma(mMin, mMax); if (mLog) Value = exp(Value); break; } } if (mpObject) mpObject->setObjectValue(Value); if (mpInitialObject) mpInitialObject->setObjectValue(Value); ++mIndex; } //**************** CScanMethod class *************************** CScanMethod * CScanMethod::createMethod(CCopasiMethod::SubType /* subType */) { return new CScanMethod(); } CScanMethod::CScanMethod(): CCopasiMethod(CCopasiTask::scan, CCopasiMethod::scanMethod), mpProblem(NULL), mpTask(NULL), mpRandomGenerator(NULL), mTotalSteps(1), mLastNestingItem(C_INVALID_INDEX), mContinueFromCurrentState(false) { mpRandomGenerator = CRandom::createGenerator(CRandom::r250); } CScanMethod::~CScanMethod() { cleanupScanItems(); delete mpRandomGenerator; mpRandomGenerator = NULL; } bool CScanMethod::cleanupScanItems() { if (!mpProblem) return false; size_t i, imax = mScanItems.size(); for (i = 0; i < imax; ++i) if (mScanItems[i]) delete mScanItems[i]; mScanItems.clear(); return true; } bool CScanMethod::init() { if (!mpProblem) return false; mpTask = dynamic_cast< CScanTask * >(getObjectParent()); if (mpTask == NULL) return false; cleanupScanItems(); mInitialRefreshes.clear(); //mTransientRefreshes.clear(); mTotalSteps = 1; std::set< const CCopasiObject * > InitialObjectSet; std::set< const CCopasiObject * > TransientObjectSet; size_t i, imax = mpProblem->getNumberOfScanItems(); mContinueFromCurrentState = mpProblem->getContinueFromCurrentState(); for (i = 0; i < imax; ++i) { CScanItem * pItem = CScanItem::createScanItemFromParameterGroup(mpProblem->getScanItem(i), mpRandomGenerator, mContinueFromCurrentState); if (pItem == NULL) { continue; } mScanItems.push_back(pItem); mTotalSteps *= pItem->getNumSteps() + 1; if (pItem->getObject() != NULL) { InitialObjectSet.insert(pItem->getObject()); } } if (mContinueFromCurrentState) { mInitialRefreshes = CCopasiObject::buildUpdateSequence(mpProblem->getModel()->getUptoDateObjects(), InitialObjectSet); } else { mInitialRefreshes = mpProblem->getModel()->buildInitialRefreshSequence(InitialObjectSet); } //set mLastNestingItem mLastNestingItem = C_INVALID_INDEX; if (imax != 0) { //search from the end size_t j; for (j = mScanItems.size() - 1; j != C_INVALID_INDEX; --j) { if (mScanItems[j]->isNesting()) { mLastNestingItem = j; break; } } } return true; } bool CScanMethod::scan() { if (!mpProblem) return false; //a hack to ensure that the first subtask is run with initial conditions //pDataModel->getModel()->setState(&mpProblem->getInitialState()); bool success = true; size_t i, imax = mScanItems.size(); //store old parameter values for (i = 0; i < imax; ++i) mScanItems[i]->storeValue(); //Do the scan... if (imax) //there are scan items success = loop(0); else success = calculate(); //nothing to scan, only one call to the subtask //restore old parameter values for (i = 0; i < imax; ++i) mScanItems[i]->restoreValue(); return success; } bool CScanMethod::loop(size_t level) { bool isLastMasterItem = (level == (mScanItems.size() - 1)); //TODO CScanItem* currentSI = mScanItems[level]; for (currentSI->reset(); !currentSI->isFinished(); currentSI->step()) { //TODO: handle slave SIs if (isLastMasterItem) { if (!calculate()) return false; } else { if (!loop(level + 1)) return false; } //TODO //separator needs to be handled slightly differently if we are at the last item if (currentSI->isNesting()) ((CScanTask*)(getObjectParent()))->outputSeparatorCallback(level == mLastNestingItem); } return true; } bool CScanMethod::calculate() { std::vector< Refresh * >::iterator it = mInitialRefreshes.begin(); std::vector< Refresh * >::iterator end = mInitialRefreshes.end(); while (it != end) (**it++)(); return mpTask->processCallback(); } void CScanMethod::setProblem(CScanProblem * problem) {mpProblem = problem;} //virtual bool CScanMethod::isValidProblem(const CCopasiProblem * pProblem) { if (!CCopasiMethod::isValidProblem(pProblem)) return false; const CScanProblem * pP = dynamic_cast<const CScanProblem *>(pProblem); if (!pP) { //not a TrajectoryProblem CCopasiMessage(CCopasiMessage::EXCEPTION, "Problem is not a Scan problem."); return false; } mContinueFromCurrentState = pP->getContinueFromCurrentState(); size_t i, imax = pP->getNumberOfScanItems(); if (imax <= 0) { //no scan items CCopasiMessage(CCopasiMessage::WARNING, "There is nothing to scan."); return false; } for (i = 0; i < imax; ++i) { CScanItem * si = CScanItem::createScanItemFromParameterGroup(mpProblem->getScanItem(i), mpRandomGenerator, mContinueFromCurrentState); if (!si) { //parameter group could not be interpreted CCopasiMessage(CCopasiMessage::ERROR, "Internal problem with scan definition."); return false; } if (!si->isValidScanItem(mContinueFromCurrentState)) { //the self check of the scan item failed. //the message should be generated by the isValidScanItem() method. delete si; return false; } delete si; //mTotalSteps *= mScanItems[i]->getNumSteps(); } return true; } <|endoftext|>
<commit_before>// // main_image.c // climso-auto // // Created by Maël Valais on 21/04/2014. // Copyright (c) 2014 Maël Valais. All rights reserved. // #define IMPULSION_PIXEL_H 25 //ms #define IMPULSION_PIXEL_V 25 //ms #define PIN_NORD 12 #define PIN_SUD 11 #define PIN_EST 10 #define PIN_OUEST 9 #define ARDUINO_DEV_LIST "/dev/ttyACM0 /dev/ttyACM1 /dev/ttyACM2 /dev/tty.usbmodemfa131 /dev/tty.usbmodemfd111" #include <iostream> #include <iomanip> // Pour cout << setprecision(4) #include <csignal> // Pour éviter de ctrl+C sans supprimer les objets en mémoire using namespace std; #include "image.h" #include "cmd_arduino.h" // Emplacement des images const string emplacement = "images-de-correlation/test-sbig/\0"; CSBIGCam* initialiserCamera() { CSBIGCam *cam = NULL; PAR_ERROR err; int num_essai = 0; do { if (num_essai > 0) { sleep(5); cout << "Essai de connexion à la caméra numéro " << num_essai << ":"<< endl; } if(cam != NULL) delete cam; cam = new CSBIGCam(DEV_USB); // Création du device USB if ((err = cam->GetError()) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la création de l'objet caméra : " << cam->GetErrorString() << endl; } else if ((err=cam->EstablishLink()) != CE_NO_ERROR) { // Connexion à la caméra cerr << "Erreur avec la camera lors de l'établissement du lien: " << cam->GetErrorString() << endl; } else { // Ajustement du mode de lecture en binning 8x8 (cf "start exposure 2 parameters" dans la doc) // Pbms rencontrés : le readout-mode "RM_NXN" ne semblait pas fonctionner : il a fallu corriger // le mode numéro 10 dans csbigcam.cpp. Je suspecte que cette fonctionnalité n'a pas été implémentée // dans csbigcam.cpp. cam->SetReadoutMode(RM_3X3); // Binning 3x3 matériel } num_essai++; } while(err != CE_NO_ERROR); return cam; } int initialiserArduino() { int num_essai = 0; int fd_arduino; do { if (num_essai > 0) { sleep(5); cout << "Essai de connexion à l'arduino numéro " << num_essai << endl; } if((fd_arduino=arduinoInitialiserCom(ARDUINO_DEV_LIST)) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; char rep[300]; arduinoRecevoirReponse(fd_arduino,rep); printf("%s",rep); } num_essai++; } while(fd_arduino == ARDUINO_ERR); return fd_arduino; } void signalHandler(int signum) { cout << "Interruption " << signum << " recue\n"; exit(signum); } int main(int argc, char **argv) { signal(SIGINT, signalHandler); signal(SIGABRT, signalHandler); int fd_arduino = initialiserArduino(); /* * Création de l'image ayant la forme du soleil puis laplacien */ Image *ref = Image::dessinerMasqueDeSoleil(256); Image *ref_lapl = ref->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); int larg_img_cam, haut_img_cam; double l_max_initial,c_max_initial; double l_max, c_max; /* * Connexion à la caméra */ CSBIGImg *obj_sbig = new CSBIGImg; CSBIGCam *cam = initialiserCamera(); /* * Prise de vue, corrélation et interpolation pour trouver le centre du Soleil */ while (cam->GrabImage(obj_sbig, SBDF_DARK_ALSO) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la capture d'une image : " << cam->GetErrorString() << endl; delete cam; cam = initialiserCamera(); } obj_sbig->AutoBackgroundAndRange(); Image *obj_no_bin = Image::depuisSBIGImg(*obj_sbig); Image *obj = obj_no_bin->reduire(2); Image *obj_lapl = obj->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); Image *correl = obj_lapl->correlation_lk(*ref_lapl, 0.70); correl->maxParInterpolation(&l_max_initial, &c_max_initial); #if DEBUG obj->versTiff(emplacement+"obj_t0.tif"); correl->versTiff(emplacement+"correl_t0.tif"); obj_lapl->versTiff(emplacement+"obj_lapl_t0.tif"); ref_lapl->versTiff(emplacement+"ref_lapl_t0.tif"); ref->versTiff(emplacement+"ref_t0.tif"); #endif delete obj_sbig; delete obj; delete correl; delete obj_lapl; delete obj_no_bin; cout << fixed << showpoint << setprecision(2); cout << "La première prise de vue indique le Soleil à la position (x= " <<c_max_initial<< ", y=" <<l_max_initial<<")" << endl; do { sleep(5); // attendre N secondes obj_sbig = new CSBIGImg(); while (cam->GrabImage(obj_sbig, SBDF_DARK_ALSO) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la capture d'une image : " << cam->GetErrorString() << endl; delete cam; cam = initialiserCamera(); } obj_sbig->AutoBackgroundAndRange(); obj_no_bin = Image::depuisSBIGImg(*obj_sbig); obj = obj_no_bin->reduire(2); // Binning 2x2 logiciel obj_lapl = obj->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); correl = obj_lapl->correlation_lk(*ref_lapl, 0.70); correl->maxParInterpolation(&l_max, &c_max); #if DEBUG obj->versTiff(emplacement+"obj.tif"); correl->versTiff(emplacement+"correl.tif"); obj_lapl->versTiff(emplacement+"obj_lapl.tif"); #endif delete obj_sbig; // On devrait éviter de créer autant d'objet à chaque itération delete obj; // Mais bon, re-coder tout est pénible delete correl; delete obj_lapl; delete obj_no_bin; /* * Calcul du décalage x,y entre la position initiale */ double l_decal = l_max - l_max_initial; double c_decal = c_max - c_max_initial; cout << "La prise de vue indique le Soleil à la position (x= " << c_max << ", y=" <<l_max<<")" << endl; cout << "Le décalage avec l'image d'origine est de (x= " << c_decal << ", y=" <<l_decal<<")" << endl; while(arduinoEnvoyerCmd((l_decal<0)?PIN_SUD:PIN_NORD, ((l_decal<0)?l_decal*(-1):l_decal)*IMPULSION_PIXEL_V, fd_arduino) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; fd_arduino = initialiserArduino(); } while(arduinoEnvoyerCmd((c_decal<0)?PIN_OUEST:PIN_EST, ((c_decal<0)?c_decal*(-1):c_decal)*IMPULSION_PIXEL_H, fd_arduino) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; fd_arduino = initialiserArduino(); } } while(true); // Extinction du lien avec la caméra if (cam->CloseDevice() != CE_NO_ERROR) { cerr << "Erreur avec la camera : " << cam->GetErrorString() << endl; exit(1); } return 0; } int main_fuite_memoire(int argc, char **argv) { Image* i = new Image(10000,10000); i->~Image(); return 0; } <commit_msg>Probleme de fuite de mémoire réglé<commit_after>// // main_image.c // climso-auto // // Created by Maël Valais on 21/04/2014. // Copyright (c) 2014 Maël Valais. All rights reserved. // #define IMPULSION_PIXEL_H 25 //ms #define IMPULSION_PIXEL_V 25 //ms #define PIN_NORD 12 #define PIN_SUD 11 #define PIN_EST 10 #define PIN_OUEST 9 #define ARDUINO_DEV_LIST "/dev/ttyACM0 /dev/ttyACM1 /dev/ttyACM2 /dev/tty.usbmodemfa131 /dev/tty.usbmodemfd111" #include <iostream> #include <iomanip> // Pour cout << setprecision(4) #include <csignal> // Pour éviter de ctrl+C sans supprimer les objets en mémoire using namespace std; #include "image.h" #include "cmd_arduino.h" // Emplacement des images const string emplacement = "images-de-correlation/test-sbig/\0"; CSBIGCam* initialiserCamera() { CSBIGCam *cam = NULL; PAR_ERROR err; int num_essai = 0; do { if (num_essai > 0) { sleep(5); cout << "Essai de connexion à la caméra numéro " << num_essai << ":"<< endl; } if(cam != NULL) delete cam; cam = new CSBIGCam(DEV_USB); // Création du device USB if ((err = cam->GetError()) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la création de l'objet caméra : " << cam->GetErrorString() << endl; } else if ((err=cam->EstablishLink()) != CE_NO_ERROR) { // Connexion à la caméra cerr << "Erreur avec la camera lors de l'établissement du lien: " << cam->GetErrorString() << endl; } else { // Ajustement du mode de lecture en binning 8x8 (cf "start exposure 2 parameters" dans la doc) // Pbms rencontrés : le readout-mode "RM_NXN" ne semblait pas fonctionner : il a fallu corriger // le mode numéro 10 dans csbigcam.cpp. Je suspecte que cette fonctionnalité n'a pas été implémentée // dans csbigcam.cpp. cam->SetReadoutMode(RM_3X3); // Binning 3x3 matériel } num_essai++; } while(err != CE_NO_ERROR); return cam; } int initialiserArduino() { int num_essai = 0; int fd_arduino; do { if (num_essai > 0) { sleep(5); cout << "Essai de connexion à l'arduino numéro " << num_essai << endl; } if((fd_arduino=arduinoInitialiserCom(ARDUINO_DEV_LIST)) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; char rep[300]; arduinoRecevoirReponse(fd_arduino,rep); printf("%s",rep); } num_essai++; } while(fd_arduino == ARDUINO_ERR); return fd_arduino; } void signalHandler(int signum) { cout << "Interruption " << signum << " recue\n"; exit(signum); } int main(int argc, char **argv) { signal(SIGINT, signalHandler); signal(SIGABRT, signalHandler); int fd_arduino = initialiserArduino(); /* * Création de l'image ayant la forme du soleil puis laplacien */ Image *ref = Image::dessinerMasqueDeSoleil(256); Image *ref_lapl = ref->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); int larg_img_cam, haut_img_cam; double l_max_initial,c_max_initial; double l_max, c_max; /* * Connexion à la caméra */ CSBIGImg *obj_sbig = new CSBIGImg; CSBIGCam *cam = initialiserCamera(); /* * Prise de vue, corrélation et interpolation pour trouver le centre du Soleil */ while (cam->GrabImage(obj_sbig, SBDF_DARK_ALSO) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la capture d'une image : " << cam->GetErrorString() << endl; delete cam; cam = initialiserCamera(); } obj_sbig->AutoBackgroundAndRange(); Image *obj_no_bin = Image::depuisSBIGImg(*obj_sbig); Image *obj = obj_no_bin->reduire(2); Image *obj_lapl = obj->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); Image *correl = obj_lapl->correlation_lk(*ref_lapl, 0.70); correl->maxParInterpolation(&l_max_initial, &c_max_initial); #if DEBUG obj->versTiff(emplacement+"obj_t0.tif"); correl->versTiff(emplacement+"correl_t0.tif"); obj_lapl->versTiff(emplacement+"obj_lapl_t0.tif"); ref_lapl->versTiff(emplacement+"ref_lapl_t0.tif"); ref->versTiff(emplacement+"ref_t0.tif"); #endif delete obj_sbig; delete obj; delete correl; delete obj_lapl; delete obj_no_bin; cout << fixed << showpoint << setprecision(2); cout << "La première prise de vue indique le Soleil à la position (x= " <<c_max_initial<< ", y=" <<l_max_initial<<")" << endl; do { sleep(5); // attendre N secondes obj_sbig = new CSBIGImg(); while (cam->GrabImage(obj_sbig, SBDF_DARK_ALSO) != CE_NO_ERROR) { cerr << "Erreur avec la camera lors de la capture d'une image : " << cam->GetErrorString() << endl; delete cam; cam = initialiserCamera(); } obj_sbig->AutoBackgroundAndRange(); obj_no_bin = Image::depuisSBIGImg(*obj_sbig); obj = obj_no_bin->reduire(2); // Binning 2x2 logiciel obj_lapl = obj->convoluer(NOYAU_LAPLACIEN_TAB, NOYAU_LAPLACIEN_TAILLE); correl = obj_lapl->correlation_lk(*ref_lapl, 0.70); correl->maxParInterpolation(&l_max, &c_max); #if DEBUG obj->versTiff(emplacement+"obj.tif"); correl->versTiff(emplacement+"correl.tif"); obj_lapl->versTiff(emplacement+"obj_lapl.tif"); #endif delete obj_sbig; // On devrait éviter de créer autant d'objet à chaque itération delete obj; // Mais bon, re-coder tout est pénible delete correl; delete obj_lapl; delete obj_no_bin; /* * Calcul du décalage x,y entre la position initiale */ double l_decal = l_max - l_max_initial; double c_decal = c_max - c_max_initial; cout << "La prise de vue indique le Soleil à la position (x= " << c_max << ", y=" <<l_max<<")" << endl; cout << "Le décalage avec l'image d'origine est de (x= " << c_decal << ", y=" <<l_decal<<")" << endl; while(arduinoEnvoyerCmd((l_decal<0)?PIN_SUD:PIN_NORD, ((l_decal<0)?l_decal*(-1):l_decal)*IMPULSION_PIXEL_V, fd_arduino) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; fd_arduino = initialiserArduino(); } while(arduinoEnvoyerCmd((c_decal<0)?PIN_OUEST:PIN_EST, ((c_decal<0)?c_decal*(-1):c_decal)*IMPULSION_PIXEL_H, fd_arduino) == ARDUINO_ERR) { cerr << "Erreur de communication avec Arduino" << endl; fd_arduino = initialiserArduino(); } } while(true); // Extinction du lien avec la caméra if (cam->CloseDevice() != CE_NO_ERROR) { cerr << "Erreur avec la camera : " << cam->GetErrorString() << endl; exit(1); } return 0; } <|endoftext|>
<commit_before>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include "Support/StringExtras.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); private: bool isSafeElementUse(Value *Ptr); bool isSafeUseOfAllocation(Instruction *User); bool isSafeStructAllocaToPromote(AllocationInst *AI); bool isSafeArrayAllocaToPromote(AllocationInst *AI); AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } // runOnFunction - This algorithm is a simple worklist driven algorithm, which // runs on all of the malloc/alloca instructions in the function, removing them // if they are only used by getelementptr instructions. // bool SROA::runOnFunction(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; // Check that all of the users of the allocation are capable of being // transformed. if (isa<StructType>(AI->getAllocatedType())) { if (!isSafeStructAllocaToPromote(AI)) continue; } else if (!isSafeArrayAllocaToPromote(AI)) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... std::vector<Value*> NewArgs; NewArgs.push_back(Constant::getNullValue(Type::LongTy)); NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end()); GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an /// aggregate allocation. /// bool SROA::isSafeUseOfAllocation(Instruction *User) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) return false; } else { return false; } return true; } /// isSafeElementUse - Check to see if this use is an allowed use for a /// getelementptr instruction of an array aggregate allocation. /// bool SROA::isSafeElementUse(Value *Ptr) { for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); switch (User->getOpcode()) { case Instruction::Load: return true; case Instruction::Store: return User->getOperand(0) != Ptr; case Instruction::GetElementPtr: { GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); if (GEP->getNumOperands() > 1) { if (!isa<Constant>(GEP->getOperand(1)) || !cast<Constant>(GEP->getOperand(1))->isNullValue()) return false; // Using pointer arithmetic to navigate the array... } return isSafeElementUse(GEP); } default: DEBUG(std::cerr << " Transformation preventing inst: " << *User); return false; } } return true; // All users look ok :) } /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) { // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { if (!isSafeUseOfAllocation(cast<Instruction>(*I))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << *I); return false; } // Pedantic check to avoid breaking broken programs... if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I)) if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI)) return false; } return true; } /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); int64_t NumElements = AT->getNumElements(); // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. Array allocas have extra constraints to // meet though. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (!isSafeUseOfAllocation(User)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); return false; } // Check to make sure that getelementptr follow the extra rules for arrays: if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // Check to make sure that index falls within the array. If not, // something funny is going on, so we won't do the optimization. // if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements) return false; // Check to make sure that the only thing that uses the resultant pointer // is safe for an array access. For example, code that looks like: // P = &A[0]; P = P + 1 // is legal, and should prevent promotion. // if (!isSafeElementUse(GEPI)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to uses of user: " << *GEPI); return false; } } } return true; } <commit_msg>ScalarRepl does not modify the CFG. Say so!<commit_after>//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// // // This transformation implements the well known scalar replacement of // aggregates transformation. This xform breaks up alloca instructions of // aggregate type (structure or array) into individual alloca instructions for // each member (if possible). // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Pass.h" #include "llvm/iMemory.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include "Support/StringExtras.h" namespace { Statistic<> NumReplaced("scalarrepl", "Number of alloca's broken up"); struct SROA : public FunctionPass { bool runOnFunction(Function &F); // getAnalysisUsage - This pass does not require any passes, but we know it // will not alter the CFG, so say so. virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } private: bool isSafeElementUse(Value *Ptr); bool isSafeUseOfAllocation(Instruction *User); bool isSafeStructAllocaToPromote(AllocationInst *AI); bool isSafeArrayAllocaToPromote(AllocationInst *AI); AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); }; RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); } Pass *createScalarReplAggregatesPass() { return new SROA(); } // runOnFunction - This algorithm is a simple worklist driven algorithm, which // runs on all of the malloc/alloca instructions in the function, removing them // if they are only used by getelementptr instructions. // bool SROA::runOnFunction(Function &F) { std::vector<AllocationInst*> WorkList; // Scan the entry basic block, adding any alloca's and mallocs to the worklist BasicBlock &BB = F.getEntryNode(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (AllocationInst *A = dyn_cast<AllocationInst>(I)) WorkList.push_back(A); // Process the worklist bool Changed = false; while (!WorkList.empty()) { AllocationInst *AI = WorkList.back(); WorkList.pop_back(); // We cannot transform the allocation instruction if it is an array // allocation (allocations OF arrays are ok though), and an allocation of a // scalar value cannot be decomposed at all. // if (AI->isArrayAllocation() || (!isa<StructType>(AI->getAllocatedType()) && !isa<ArrayType>(AI->getAllocatedType()))) continue; // Check that all of the users of the allocation are capable of being // transformed. if (isa<StructType>(AI->getAllocatedType())) { if (!isSafeStructAllocaToPromote(AI)) continue; } else if (!isSafeArrayAllocaToPromote(AI)) continue; DEBUG(std::cerr << "Found inst to xform: " << *AI); Changed = true; std::vector<AllocaInst*> ElementAllocas; if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { ElementAllocas.reserve(ST->getNumContainedTypes()); for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } else { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); ElementAllocas.reserve(AT->getNumElements()); const Type *ElTy = AT->getElementType(); for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getName() + "." + utostr(i), AI); ElementAllocas.push_back(NA); WorkList.push_back(NA); // Add to worklist for recursive processing } } // Now that we have created the alloca instructions that we want to use, // expand the getelementptr instructions to use them. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue(); assert(Idx < ElementAllocas.size() && "Index out of range?"); AllocaInst *AllocaToUse = ElementAllocas[Idx]; Value *RepValue; if (GEPI->getNumOperands() == 3) { // Do not insert a new getelementptr instruction with zero indices, // only to have it optimized out later. RepValue = AllocaToUse; } else { // We are indexing deeply into the structure, so we still need a // getelement ptr instruction to finish the indexing. This may be // expanded itself once the worklist is rerun. // std::string OldName = GEPI->getName(); // Steal the old name... std::vector<Value*> NewArgs; NewArgs.push_back(Constant::getNullValue(Type::LongTy)); NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end()); GEPI->setName(""); RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI); } // Move all of the users over to the new GEP. GEPI->replaceAllUsesWith(RepValue); // Delete the old GEP GEPI->getParent()->getInstList().erase(GEPI); } else { assert(0 && "Unexpected instruction type!"); } } // Finally, delete the Alloca instruction AI->getParent()->getInstList().erase(AI); NumReplaced++; } return Changed; } /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an /// aggregate allocation. /// bool SROA::isSafeUseOfAllocation(Instruction *User) { if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst> if (GEPI->getNumOperands() <= 2 || GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) || !isa<Constant>(GEPI->getOperand(2)) || isa<ConstantExpr>(GEPI->getOperand(2))) return false; } else { return false; } return true; } /// isSafeElementUse - Check to see if this use is an allowed use for a /// getelementptr instruction of an array aggregate allocation. /// bool SROA::isSafeElementUse(Value *Ptr) { for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); switch (User->getOpcode()) { case Instruction::Load: return true; case Instruction::Store: return User->getOperand(0) != Ptr; case Instruction::GetElementPtr: { GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); if (GEP->getNumOperands() > 1) { if (!isa<Constant>(GEP->getOperand(1)) || !cast<Constant>(GEP->getOperand(1))->isNullValue()) return false; // Using pointer arithmetic to navigate the array... } return isSafeElementUse(GEP); } default: DEBUG(std::cerr << " Transformation preventing inst: " << *User); return false; } } return true; // All users look ok :) } /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) { // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { if (!isSafeUseOfAllocation(cast<Instruction>(*I))) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << *I); return false; } // Pedantic check to avoid breaking broken programs... if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I)) if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI)) return false; } return true; } /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a /// structure can be broken down into elements. /// bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) { const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); int64_t NumElements = AT->getNumElements(); // Loop over the use list of the alloca. We can only transform it if all of // the users are safe to transform. Array allocas have extra constraints to // meet though. // for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E; ++I) { Instruction *User = cast<Instruction>(*I); if (!isSafeUseOfAllocation(User)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: " << User); return false; } // Check to make sure that getelementptr follow the extra rules for arrays: if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { // Check to make sure that index falls within the array. If not, // something funny is going on, so we won't do the optimization. // if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements) return false; // Check to make sure that the only thing that uses the resultant pointer // is safe for an array access. For example, code that looks like: // P = &A[0]; P = P + 1 // is legal, and should prevent promotion. // if (!isSafeElementUse(GEPI)) { DEBUG(std::cerr << "Cannot transform: " << *AI << " due to uses of user: " << *GEPI); return false; } } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER 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 <algorithm> #include <chrono> #include <functional> #include <iostream> #include <iterator> #include <set> #include <mutex> #include <thread> #include <Chaos/Types.h> #include "object.h" #include "parallel_sweep.h" namespace gc { class Worker { int order_{}; bool stop_{}; bool run_tracing_{}; std::mutex mutex_; std::unique_ptr<std::thread> thread_; std::vector<BaseObject*> roots_; std::vector<BaseObject*> mark_objects_; friend class ParallelSweep; void acquire_work(void) { if (!mark_objects_.empty()) return; { std::unique_lock<std::mutex> g(mutex_); transfer(roots_.size() / 2, mark_objects_); } if (mark_objects_.empty()) ParallelSweep::get_instance().acquire_work(order_, mark_objects_); } void perform_work(void) { while (!mark_objects_.empty()) { auto* obj = mark_objects_.back(); mark_objects_.pop_back(); obj->set_marked(); if (obj->is_pair()) { auto append_fn = [this](BaseObject* o) { if (o != nullptr && !o->is_marked()) { o->set_marked(); mark_objects_.push_back(o); } }; append_fn(Chaos::down_cast<Pair*>(obj)->first()); append_fn(Chaos::down_cast<Pair*>(obj)->second()); } } } void generate_work(void) { if (roots_.empty()) { std::unique_lock<std::mutex> g(mutex_); std::copy(mark_objects_.begin(), mark_objects_.end(), std::back_inserter(roots_)); mark_objects_.clear(); } } void worker_routine(void) { while (!stop_) { if (run_tracing_) { acquire_work(); perform_work(); generate_work(); } if (run_tracing_ && mark_objects_.empty()) run_tracing_ = false; std::this_thread::sleep_for(std::chrono::microseconds(10)); } } public: Worker(int order) : order_(order) , thread_(new std::thread(std::bind(&Worker::worker_routine, this))) {} ~Worker(void) { stop(); thread_->join(); } void stop(void) { stop_ = true; } void run_tracing(void) { run_tracing_ = true; } void put_in(BaseObject* obj) { roots_.push_back(obj); } BaseObject* fetch_out(void) { if (!roots_.empty()) { auto* obj = roots_.back(); roots_.pop_back(); return obj; } return nullptr; } void transfer(std::size_t n, std::vector<BaseObject*>& objects) { std::copy_n(roots_.begin(), n, std::back_inserter(objects)); roots_.erase(roots_.begin(), roots_.begin() + n); } }; ParallelSweep::ParallelSweep(void) { start_workers(); } ParallelSweep::~ParallelSweep(void) { stop_workers(); } void ParallelSweep::start_workers(int nworkers) { nworkers_ = nworkers; for (auto i = 0; i < nworkers_; ++i) workers_.emplace_back(new Worker(i)); } void ParallelSweep::stop_workers(void) { for (auto i = 0; i < nworkers_; ++i) workers_[i]->stop(); } int ParallelSweep::put_in_order(void) { int r = order_; order_ = (order_ + 1) % nworkers_; return r; } int ParallelSweep::fetch_out_order(void) { order_ = (order_ - 1 + nworkers_) % nworkers_; return order_; } void ParallelSweep::sweep(void) { for (auto it = objects_.begin(); it != objects_.end();) { if (!(*it)->is_marked()) { delete *it; objects_.erase(it++); } else { (*it)->unset_marked(); ++it; } } } ParallelSweep& ParallelSweep::get_instance(void) { static ParallelSweep ins; return ins; } void ParallelSweep::acquire_work( int own_order, std::vector<BaseObject*>& objects) { for (auto i = 0; i < nworkers_; ++i) { if (i == own_order) continue; if (workers_[i]->mutex_.try_lock()) { workers_[i]->transfer(workers_[i]->roots_.size() / 2, objects); workers_[i]->mutex_.unlock(); break; } } } void ParallelSweep::collect(void) { auto old_count = objects_.size(); for (auto i = 0; i < nworkers_; ++i) workers_[i]->run_tracing(); std::set<int> finished; while (true) { for (auto i = 0; i < nworkers_; ++i) { if (!workers_[i]->run_tracing_) finished.insert(i); } if (finished.size() == static_cast<std::size_t>(nworkers_)) break; std::this_thread::sleep_for(std::chrono::microseconds(10)); } finished.clear(); sweep(); std::cout << "[" << old_count - objects_.size() << "] objects collected, " << "[" << objects_.size() << "] objects remaining." << std::endl; } BaseObject* ParallelSweep::put_in(int value) { if (objects_.size() >= kMaxObjects) collect(); auto* obj = new Int(); obj->set_value(value); auto order = put_in_order(); workers_[order]->put_in(obj); objects_.push_back(obj); return obj; } BaseObject* ParallelSweep::put_in(BaseObject* first, BaseObject* second) { if (objects_.size() >= kMaxObjects) collect(); auto* obj = new Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); auto order = put_in_order(); workers_[order]->put_in(obj); objects_.push_back(obj); return obj; } BaseObject* ParallelSweep::fetch_out(void) { auto order = fetch_out_order(); return workers_[order]->fetch_out(); } } <commit_msg>:construction: chore(ParallelSweep): updated the worker implementation for parallel sweeping gc<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER 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 <algorithm> #include <chrono> #include <functional> #include <iostream> #include <iterator> #include <set> #include <mutex> #include <thread> #include <Chaos/Types.h> #include "object.h" #include "parallel_sweep.h" namespace gc { class Worker { int order_{}; bool stop_{}; bool run_tracing_{}; std::mutex mutex_; std::unique_ptr<std::thread> thread_; std::vector<BaseObject*> roots_; std::vector<BaseObject*> mark_objects_; friend class ParallelSweep; void acquire_work(void) { if (!mark_objects_.empty()) return; { std::unique_lock<std::mutex> g(mutex_); transfer(roots_.size() / 2, mark_objects_); } if (mark_objects_.empty()) ParallelSweep::get_instance().acquire_work(order_, mark_objects_); } void perform_work(void) { while (!mark_objects_.empty()) { auto* obj = mark_objects_.back(); mark_objects_.pop_back(); obj->set_marked(); if (obj->is_pair()) { auto append_fn = [this](BaseObject* o) { if (o != nullptr && !o->is_marked()) { o->set_marked(); mark_objects_.push_back(o); } }; append_fn(Chaos::down_cast<Pair*>(obj)->first()); append_fn(Chaos::down_cast<Pair*>(obj)->second()); } } } void generate_work(void) { if (roots_.empty()) { std::unique_lock<std::mutex> g(mutex_); std::copy(mark_objects_.begin(), mark_objects_.end(), std::back_inserter(roots_)); mark_objects_.clear(); } } void worker_routine(void) { while (!stop_) { if (run_tracing_) { acquire_work(); perform_work(); generate_work(); } if (run_tracing_ && mark_objects_.empty()) run_tracing_ = false; std::this_thread::sleep_for(std::chrono::microseconds(10)); } } public: Worker(int order) : order_(order) , thread_(new std::thread(std::bind(&Worker::worker_routine, this))) {} ~Worker(void) { stop(); thread_->join(); } void stop(void) { stop_ = true; } void run_tracing(void) { run_tracing_ = true; } bool is_tracing(void) const { return run_tracing_; } std::size_t roots_count(void) const { return roots_.size(); } bool try_lock(void) { return mutex_.try_lock(); } void unlock(void) { mutex_.unlock(); } void put_in(BaseObject* obj) { roots_.push_back(obj); } BaseObject* fetch_out(void) { if (!roots_.empty()) { auto* obj = roots_.back(); roots_.pop_back(); return obj; } return nullptr; } void transfer(std::size_t n, std::vector<BaseObject*>& objects) { std::copy_n(roots_.begin(), n, std::back_inserter(objects)); roots_.erase(roots_.begin(), roots_.begin() + n); } }; ParallelSweep::ParallelSweep(void) { start_workers(); } ParallelSweep::~ParallelSweep(void) { stop_workers(); } void ParallelSweep::start_workers(int nworkers) { nworkers_ = nworkers; for (auto i = 0; i < nworkers_; ++i) workers_.emplace_back(new Worker(i)); } void ParallelSweep::stop_workers(void) { for (auto i = 0; i < nworkers_; ++i) workers_[i]->stop(); } int ParallelSweep::put_in_order(void) { int r = order_; order_ = (order_ + 1) % nworkers_; return r; } int ParallelSweep::fetch_out_order(void) { order_ = (order_ - 1 + nworkers_) % nworkers_; return order_; } void ParallelSweep::sweep(void) { for (auto it = objects_.begin(); it != objects_.end();) { if (!(*it)->is_marked()) { delete *it; objects_.erase(it++); } else { (*it)->unset_marked(); ++it; } } } ParallelSweep& ParallelSweep::get_instance(void) { static ParallelSweep ins; return ins; } void ParallelSweep::acquire_work( int own_order, std::vector<BaseObject*>& objects) { for (auto i = 0; i < nworkers_; ++i) { if (i == own_order) continue; if (workers_[i]->try_lock()) { workers_[i]->transfer(workers_[i]->roots_count() / 2, objects); workers_[i]->unlock(); break; } } } void ParallelSweep::collect(void) { auto old_count = objects_.size(); for (auto i = 0; i < nworkers_; ++i) workers_[i]->run_tracing(); std::set<int> finished; while (true) { for (auto i = 0; i < nworkers_; ++i) { if (!workers_[i]->is_tracing()) finished.insert(i); } if (finished.size() == static_cast<std::size_t>(nworkers_)) break; std::this_thread::sleep_for(std::chrono::microseconds(10)); } finished.clear(); sweep(); std::cout << "[" << old_count - objects_.size() << "] objects collected, " << "[" << objects_.size() << "] objects remaining." << std::endl; } BaseObject* ParallelSweep::put_in(int value) { if (objects_.size() >= kMaxObjects) collect(); auto* obj = new Int(); obj->set_value(value); auto order = put_in_order(); workers_[order]->put_in(obj); objects_.push_back(obj); return obj; } BaseObject* ParallelSweep::put_in(BaseObject* first, BaseObject* second) { if (objects_.size() >= kMaxObjects) collect(); auto* obj = new Pair(); if (first != nullptr) obj->set_first(first); if (second != nullptr) obj->set_second(second); auto order = put_in_order(); workers_[order]->put_in(obj); objects_.push_back(obj); return obj; } BaseObject* ParallelSweep::fetch_out(void) { auto order = fetch_out_order(); return workers_[order]->fetch_out(); } } <|endoftext|>
<commit_before>#include <errno.h> #include <math.h> #include <QCloseEvent> #include <QDateTime> #include <QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" const char MainWindow::pol_pm[] = "<span style='font-weight:600;'><span style='color:#ff0000;'>+</span> <span style='color:#0000ff;'>-</span></span>"; const char MainWindow::pol_mp[] = "<span style='font-weight:600;'><span style='color:#0000ff;'>-</span> <span style='color:#ff0000;'>+</span></span>"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), configUI() { ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); currentTimer.setInterval(currentDwell); currentTimer.setSingleShot(false); QObject::connect(&currentTimer, SIGNAL(timeout()), this, SLOT(on_currentTimer_timeout())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeDevs() { currentTimer.stop(); ui->sweppingLabel->setEnabled(false); csvFile.close(); ps622Hack.close(); pwrPolSwitch.close(); sdp_close(&sdp); } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { closeDevs(); event->ignore(); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double ) { ui->sweppingLabel->setEnabled(true); } void MainWindow::on_coilPolCrossCheckBox_toggled(bool checked) { ui->sweppingLabel->setEnabled(true); if (checked) ui->polarityLabel->setText(pol_mp); else ui->polarityLabel->setText(pol_pm); } void MainWindow::on_coilPowerCheckBox_toggled(bool) { ui->sweppingLabel->setEnabled(true); } void MainWindow::on_currentTimer_timeout() { sdp_va_data_t va_data; // tweak coil current while (ui->sweppingLabel->isEnabled()) { /** Curent trought coil */ double wantI, procI; /** Coil power state, on/off */ bool wantCoilPower, procCoilPower; /** Coil power switch state direct/cross */ PwrPolSwitch::state_t wantCoilSwitchState, procCoilSwitchState; /* Get all values necesary for process decisions. */ // wanted values if (ui->coilPolCrossCheckBox->isChecked()) wantCoilSwitchState = PwrPolSwitch::cross; else wantCoilSwitchState = PwrPolSwitch::direct; wantCoilPower = ui->coilPowerCheckBox->isChecked(); if (wantCoilPower) { wantI = ui->coilCurrDoubleSpinBox->value(); if (wantCoilSwitchState == PwrPolSwitch::cross) wantI = -wantI; } else wantI = 0; // proc values procCoilSwitchState = pwrPolSwitch.polarity(); sdp_lcd_info_t lcd_info; sdp_get_lcd_info(&sdp, &lcd_info); // TODO check procCoilPower = lcd_info.output; procI = lcd_info.set_A; if (procCoilSwitchState == PwrPolSwitch::cross) procI = -procI; ui->plainTextEdit->appendPlainText(QString("procI: %1, procCoilSwitchState: %2, procCoilPower: %3").arg(procI).arg(procCoilSwitchState).arg(procCoilPower)); ui->plainTextEdit->appendPlainText(QString("wantI: %1, wantCoilSwitchState: %2, wantCoilPower: %3\n").arg(wantI).arg(wantCoilSwitchState).arg(wantCoilPower)); /* process decision */ // Target reach, finish job if (fabs(procI - wantI) < currentSlope) { ui->sweppingLabel->setEnabled(false); if (!wantCoilPower && procI <= currentSlope && procCoilPower) sdp_set_output(&sdp, 0); // TODO check break; } // Need switch polarity? if (procCoilSwitchState != wantCoilSwitchState) { // Is polarity switch posible? (power is off) if (!procCoilPower) { pwrPolSwitch.setPolarity(wantCoilSwitchState); // TODO check break; } // Is posible power-off in order to swich polarity? if (fabs(procI) < currentSlope) { sdp_set_output(&sdp, 0); break; } // set current near to zero before polarity switching } // want current but power is off -> set power on at current 0.0 A if (procCoilPower != wantCoilPower && wantCoilPower) { sdp_set_curr(&sdp, 0.0); sdp_set_output(&sdp, 1); break; } // power is on, but current neet to be adjusted, do one step if (procI > wantI) procI -= currentSlope; else procI += currentSlope; sdp_set_curr(&sdp, fabs(procI)); break; } if (sdp_get_va_data(&sdp, &va_data) < 0) { // TODO close(); return; } ui->coilCurrMeasDoubleSpinBox->setValue(va_data.curr); ui->coilVoltMeasDoubleSpinBox->setValue(va_data.volt); } void MainWindow::on_measurePushButton_clicked() { QString line("%1,%2,%3,%4,%5\r\n"); QString s; int row; row = ui->dataTableWidget->rowCount(); ui->dataTableWidget->insertRow(row); s = QDateTime::currentDateTime().toString("yyyy-MM-dd mm:ss"); ui->dataTableWidget->setItem(row, 3, new QTableWidgetItem(s)); line = line.arg(s); s = ui->coilCurrMeasDoubleSpinBox->text().replace(",", "."); ui->dataTableWidget->setItem(row, 0, new QTableWidgetItem(s)); line = line.arg(s); s = ui->coilVoltMeasDoubleSpinBox->text().replace(",", "."); line = line.arg(s); s = ui->coilCurrDoubleSpinBox->text().replace(",", "."); line = line.arg(s); s = ui->sampleCurrDoubleSpinBox->text().replace(",", "."); ui->dataTableWidget->setItem(row, 1, new QTableWidgetItem(s)); line = line.arg(s); csvFile.write(line.toLocal8Bit()); } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double value) { ps622Hack.setCurrent(value); } void MainWindow::on_samplePolCrossCheckBox_toggled(bool ) { } void MainWindow::on_samplePowerCheckBox_toggled(bool checked) { ps622Hack.setOutput(checked); } bool MainWindow::openDevs() { QString csvHeader("Time, coil curr. meas. [A], coil volt. meas. [V], coil curr want. [A], sample curr. want. [A]\r\n"); QString err_text, err_title; QString s; int err; s = settings.value(ConfigUI::cfg_powerSupplyPort).toString(); err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN); if (err < 0) goto sdp_err0; /* Set value limit in current input spin box. */ sdp_va_t limits; err = sdp_get_va_maximums(&sdp, &limits); if (err < 0) goto sdp_err; ui->coilCurrDoubleSpinBox->setMaximum(limits.curr); /* Set actual current as wanted value, avoiding anny jumps. */ sdp_va_data_t va_data; err = sdp_get_va_data(&sdp, &va_data); if (err < 0) goto sdp_err; err = sdp_set_curr(&sdp, va_data.curr); if (err < 0) goto sdp_err; /* Set voltage to maximum, Hall is current driven. */ err = sdp_set_volt_limit(&sdp, va_data.volt); if (err < 0) goto sdp_err; err = sdp_set_volt(&sdp, va_data.volt); if (err < 0) goto sdp_err; sdp_lcd_info_t lcd_info; sdp_get_lcd_info(&sdp, &lcd_info); // TODO check if (err < 0) goto sdp_err; ui->coilPowerCheckBox->setChecked(lcd_info.output); s = settings.value(ConfigUI::cfg_polSwitchPort).toString(); if (!pwrPolSwitch.open(s.toLocal8Bit().constData())) { err = errno; goto mag_pwr_switch_err; } bool cross; cross = (pwrPolSwitch.polarity() == PwrPolSwitch::cross); ui->coilPolCrossCheckBox->setChecked(cross); s = settings.value(ConfigUI::cfg_samplePSPort).toString(); if (!ps622Hack.open(s.toLocal8Bit().constData())) { err = errno; goto sample_pwr_err; } ui->sampleCurrDoubleSpinBox->setValue(ps622Hack.current()); ui->samplePowerCheckBox->setChecked(ps622Hack.output()); s= settings.value(ConfigUI::cfg_fileName).toString(); csvFile.setFileName(s); if (!csvFile.open(QFile::WriteOnly | QFile::Truncate)) goto file_err; csvFile.write(csvHeader.toLocal8Bit()); /* TODO ... */ ui->sweppingLabel->setEnabled(true); currentTimer.start(); return true; file_err: ps622Hack.close(); if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open output file"); err_text = csvFile.errorString(); } sample_pwr_err: pwrPolSwitch.close(); if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open sample power supply (Keithaly 6220)"); err_text = QString::fromLocal8Bit(strerror(err)); } mag_pwr_switch_err: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open power supply switch"); err_text = QString::fromLocal8Bit(strerror(err)); } sdp_err: sdp_close(&sdp); sdp_err0: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open Manson SDP power supply"); err_text = QString::fromLocal8Bit(sdp_strerror(err)); } err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text); QMessageBox::critical(this, err_title, err_text); statusBar()->showMessage(err_title); return false; } void MainWindow::show() { if (!openDevs()) { configUI.show(); return; } QWidget::show(); } void MainWindow::startApp() { configUI.show(); } void MainWindow::updateCurrent() { double current; current = ui->coilCurrDoubleSpinBox->value(); if (ui->coilPolCrossCheckBox->isChecked()) current = -current; sdp_set_curr(&sdp, current); /* TODO */ } <commit_msg>Make CSV header more readable in source<commit_after>#include <errno.h> #include <math.h> #include <QCloseEvent> #include <QDateTime> #include <QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" const char MainWindow::pol_pm[] = "<span style='font-weight:600;'><span style='color:#ff0000;'>+</span> <span style='color:#0000ff;'>-</span></span>"; const char MainWindow::pol_mp[] = "<span style='font-weight:600;'><span style='color:#0000ff;'>-</span> <span style='color:#ff0000;'>+</span></span>"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), configUI() { ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); currentTimer.setInterval(currentDwell); currentTimer.setSingleShot(false); QObject::connect(&currentTimer, SIGNAL(timeout()), this, SLOT(on_currentTimer_timeout())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeDevs() { currentTimer.stop(); ui->sweppingLabel->setEnabled(false); csvFile.close(); ps622Hack.close(); pwrPolSwitch.close(); sdp_close(&sdp); } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { closeDevs(); event->ignore(); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double ) { ui->sweppingLabel->setEnabled(true); } void MainWindow::on_coilPolCrossCheckBox_toggled(bool checked) { ui->sweppingLabel->setEnabled(true); if (checked) ui->polarityLabel->setText(pol_mp); else ui->polarityLabel->setText(pol_pm); } void MainWindow::on_coilPowerCheckBox_toggled(bool) { ui->sweppingLabel->setEnabled(true); } void MainWindow::on_currentTimer_timeout() { sdp_va_data_t va_data; // tweak coil current while (ui->sweppingLabel->isEnabled()) { /** Curent trought coil */ double wantI, procI; /** Coil power state, on/off */ bool wantCoilPower, procCoilPower; /** Coil power switch state direct/cross */ PwrPolSwitch::state_t wantCoilSwitchState, procCoilSwitchState; /* Get all values necesary for process decisions. */ // wanted values if (ui->coilPolCrossCheckBox->isChecked()) wantCoilSwitchState = PwrPolSwitch::cross; else wantCoilSwitchState = PwrPolSwitch::direct; wantCoilPower = ui->coilPowerCheckBox->isChecked(); if (wantCoilPower) { wantI = ui->coilCurrDoubleSpinBox->value(); if (wantCoilSwitchState == PwrPolSwitch::cross) wantI = -wantI; } else wantI = 0; // proc values procCoilSwitchState = pwrPolSwitch.polarity(); sdp_lcd_info_t lcd_info; sdp_get_lcd_info(&sdp, &lcd_info); // TODO check procCoilPower = lcd_info.output; procI = lcd_info.set_A; if (procCoilSwitchState == PwrPolSwitch::cross) procI = -procI; ui->plainTextEdit->appendPlainText(QString("procI: %1, procCoilSwitchState: %2, procCoilPower: %3").arg(procI).arg(procCoilSwitchState).arg(procCoilPower)); ui->plainTextEdit->appendPlainText(QString("wantI: %1, wantCoilSwitchState: %2, wantCoilPower: %3\n").arg(wantI).arg(wantCoilSwitchState).arg(wantCoilPower)); /* process decision */ // Target reach, finish job if (fabs(procI - wantI) < currentSlope) { ui->sweppingLabel->setEnabled(false); if (!wantCoilPower && procI <= currentSlope && procCoilPower) sdp_set_output(&sdp, 0); // TODO check break; } // Need switch polarity? if (procCoilSwitchState != wantCoilSwitchState) { // Is polarity switch posible? (power is off) if (!procCoilPower) { pwrPolSwitch.setPolarity(wantCoilSwitchState); // TODO check break; } // Is posible power-off in order to swich polarity? if (fabs(procI) < currentSlope) { sdp_set_output(&sdp, 0); break; } // set current near to zero before polarity switching } // want current but power is off -> set power on at current 0.0 A if (procCoilPower != wantCoilPower && wantCoilPower) { sdp_set_curr(&sdp, 0.0); sdp_set_output(&sdp, 1); break; } // power is on, but current neet to be adjusted, do one step if (procI > wantI) procI -= currentSlope; else procI += currentSlope; sdp_set_curr(&sdp, fabs(procI)); break; } if (sdp_get_va_data(&sdp, &va_data) < 0) { // TODO close(); return; } ui->coilCurrMeasDoubleSpinBox->setValue(va_data.curr); ui->coilVoltMeasDoubleSpinBox->setValue(va_data.volt); } void MainWindow::on_measurePushButton_clicked() { QString line("%1,%2,%3,%4,%5\r\n"); QString s; int row; row = ui->dataTableWidget->rowCount(); ui->dataTableWidget->insertRow(row); s = QDateTime::currentDateTime().toString("yyyy-MM-dd mm:ss"); ui->dataTableWidget->setItem(row, 3, new QTableWidgetItem(s)); line = line.arg(s); s = ui->coilCurrMeasDoubleSpinBox->text().replace(",", "."); ui->dataTableWidget->setItem(row, 0, new QTableWidgetItem(s)); line = line.arg(s); s = ui->coilVoltMeasDoubleSpinBox->text().replace(",", "."); line = line.arg(s); s = ui->coilCurrDoubleSpinBox->text().replace(",", "."); line = line.arg(s); s = ui->sampleCurrDoubleSpinBox->text().replace(",", "."); ui->dataTableWidget->setItem(row, 1, new QTableWidgetItem(s)); line = line.arg(s); // TODO: inset hall U csvFile.write(line.toLocal8Bit()); } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double value) { ps622Hack.setCurrent(value); } void MainWindow::on_samplePolCrossCheckBox_toggled(bool ) { } void MainWindow::on_samplePowerCheckBox_toggled(bool checked) { ps622Hack.setOutput(checked); } bool MainWindow::openDevs() { QString csvHeader("Time, coil curr. meas. [A]," "coil volt. meas. [V]," " coil curr want. [A]," " sample curr. want. [A]," " sample hall [V]\r\n"); QString err_text, err_title; QString s; int err; s = settings.value(ConfigUI::cfg_powerSupplyPort).toString(); err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN); if (err < 0) goto sdp_err0; /* Set value limit in current input spin box. */ sdp_va_t limits; err = sdp_get_va_maximums(&sdp, &limits); if (err < 0) goto sdp_err; ui->coilCurrDoubleSpinBox->setMaximum(limits.curr); /* Set actual current as wanted value, avoiding anny jumps. */ sdp_va_data_t va_data; err = sdp_get_va_data(&sdp, &va_data); if (err < 0) goto sdp_err; err = sdp_set_curr(&sdp, va_data.curr); if (err < 0) goto sdp_err; /* Set voltage to maximum, Hall is current driven. */ err = sdp_set_volt_limit(&sdp, va_data.volt); if (err < 0) goto sdp_err; err = sdp_set_volt(&sdp, va_data.volt); if (err < 0) goto sdp_err; sdp_lcd_info_t lcd_info; sdp_get_lcd_info(&sdp, &lcd_info); // TODO check if (err < 0) goto sdp_err; ui->coilPowerCheckBox->setChecked(lcd_info.output); s = settings.value(ConfigUI::cfg_polSwitchPort).toString(); if (!pwrPolSwitch.open(s.toLocal8Bit().constData())) { err = errno; goto mag_pwr_switch_err; } bool cross; cross = (pwrPolSwitch.polarity() == PwrPolSwitch::cross); ui->coilPolCrossCheckBox->setChecked(cross); s = settings.value(ConfigUI::cfg_samplePSPort).toString(); if (!ps622Hack.open(s.toLocal8Bit().constData())) { err = errno; goto sample_pwr_err; } ui->sampleCurrDoubleSpinBox->setValue(ps622Hack.current()); ui->samplePowerCheckBox->setChecked(ps622Hack.output()); s= settings.value(ConfigUI::cfg_fileName).toString(); csvFile.setFileName(s); if (!csvFile.open(QFile::WriteOnly | QFile::Truncate)) goto file_err; csvFile.write(csvHeader.toLocal8Bit()); /* TODO ... */ ui->sweppingLabel->setEnabled(true); currentTimer.start(); return true; file_err: ps622Hack.close(); if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open output file"); err_text = csvFile.errorString(); } sample_pwr_err: pwrPolSwitch.close(); if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open sample power supply (Keithaly 6220)"); err_text = QString::fromLocal8Bit(strerror(err)); } mag_pwr_switch_err: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open power supply switch"); err_text = QString::fromLocal8Bit(strerror(err)); } sdp_err: sdp_close(&sdp); sdp_err0: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open Manson SDP power supply"); err_text = QString::fromLocal8Bit(sdp_strerror(err)); } err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text); QMessageBox::critical(this, err_title, err_text); statusBar()->showMessage(err_title); return false; } void MainWindow::show() { if (!openDevs()) { configUI.show(); return; } QWidget::show(); } void MainWindow::startApp() { configUI.show(); } void MainWindow::updateCurrent() { double current; current = ui->coilCurrDoubleSpinBox->value(); if (ui->coilPolCrossCheckBox->isChecked()) current = -current; sdp_set_curr(&sdp, current); /* TODO */ } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbObjectList.h" namespace otb { namespace Wrapper { class BandMath : public Application { public: /** Standard class typedefs. */ typedef BandMath Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMath, otb::Application); typedef otb::MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, FloatImageType::PixelType> ExtractROIFilterType; typedef otb::ObjectList<ExtractROIFilterType> ExtractROIFilterListType; typedef otb::BandMathImageFilter<FloatImageType> BandMathImageFilterType; private: BandMath() { SetName("BandMath"); SetDescription("Perform a mathematical operation on monoband images"); } void DoCreateParameters() { AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image"); AddParameter(ParameterType_String, "exp", "Expression"); SetParameterDescription("exp","The mathematical expression to apply. \nUse im1b1 for the first band, im1b2 for the second one..."); } void DoUpdateParameters() { // Check if the expression is correctly set if (HasValue("il")) { LiveCheck(); } } void LiveCheck() { // Initialize a bandMath Filter first m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); unsigned int nbInputs = inList->Size(); unsigned int imageId = 0, bandId = 0; for (unsigned int i = 0; i < nbInputs; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } otb::Parser::Pointer dummyParser = otb::Parser::New(); std::vector<double> dummyVars; double value = 0.; std::string success = "The expression is Valid"; std::ostringstream failure; if (HasValue("exp")) { // Setup the dummy parser for (unsigned int i = 0; i < nbInputs; ++i) { dummyVars.push_back(1); dummyParser->DefineVar(m_Filter->GetNthInputName(i), &(dummyVars.at(i))); } dummyParser->SetExpr(GetParameterString("exp")); // Check the expression try { value = dummyParser->Eval(); } catch(itk::ExceptionObject& err) { std::cout << err.GetDescription() << std::endl; } } } void DoExecute() { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages) { itkExceptionMacro("No input Image set...; please set at least one input image"); } m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); unsigned int bandId = 0; unsigned int imageId = 0; for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } m_Filter->SetExpression(GetParameterString("exp")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ExtractROIFilterListType::Pointer m_ChannelExtractorList; BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMath) <commit_msg>ENH: check the expression while the user typing it, put in the ParameterString ToolTip the result of the parsing<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbObjectList.h" namespace otb { namespace Wrapper { class BandMath : public Application { public: /** Standard class typedefs. */ typedef BandMath Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(BandMath, otb::Application); typedef otb::MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, FloatImageType::PixelType> ExtractROIFilterType; typedef otb::ObjectList<ExtractROIFilterType> ExtractROIFilterListType; typedef otb::BandMathImageFilter<FloatImageType> BandMathImageFilterType; private: BandMath() { SetName("BandMath"); SetDescription("Perform a mathematical operation on monoband images"); } void DoCreateParameters() { AddParameter(ParameterType_InputImageList, "il", "Input image list"); SetParameterDescription("il", "Image list to perform computation on"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image"); AddParameter(ParameterType_String, "exp", "Expression"); SetParameterDescription("exp", "The mathematical expression to apply. \nUse im1b1 for the first band, im1b2 for the second one..."); } void DoUpdateParameters() { // Check if the expression is correctly set if (HasValue("il")) { LiveCheck(); } } void LiveCheck() { // Initialize a bandMath Filter first m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); unsigned int nbInputs = inList->Size(); unsigned int imageId = 0, bandId = 0; for (unsigned int i = 0; i < nbInputs; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } otb::Parser::Pointer dummyParser = otb::Parser::New(); std::vector<double> dummyVars; std::string success = "The expression is Valid"; SetParameterDescription("exp",success); std::ostringstream failure; if (HasValue("exp")) { // Setup the dummy parser for (unsigned int i = 0; i < bandId; i++) { dummyVars.push_back(1.); dummyParser->DefineVar(m_Filter->GetNthInputName(i), &(dummyVars.at(i))); } dummyParser->SetExpr(GetParameterString("exp")); // Check the expression try { dummyParser->Eval(); } catch(itk::ExceptionObject& err) { // Change the parameter description to be able to have the // parser errors in the tooltip SetParameterDescription("exp",err.GetDescription()); } } } void DoExecute() { // Get the input image list FloatVectorImageListType::Pointer inList = GetParameterImageList("il"); // checking the input images list validity const unsigned int nbImages = inList->Size(); if (nbImages) { itkExceptionMacro("No input Image set...; please set at least one input image"); } m_ChannelExtractorList = ExtractROIFilterListType::New(); m_Filter = BandMathImageFilterType::New(); unsigned int bandId = 0; unsigned int imageId = 0; for (unsigned int i = 0; i < nbImages; i++) { FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i); currentImage->UpdateOutputInformation(); otbAppLogINFO( << "Image #" << i + 1 << " has " << currentImage->GetNumberOfComponentsPerPixel() << " components" << std::endl ); for (unsigned int j = 0; j < currentImage->GetNumberOfComponentsPerPixel(); j++) { std::ostringstream tmpParserVarName; tmpParserVarName << "im" << imageId + 1 << "b" << j + 1; m_ExtractROIFilter = ExtractROIFilterType::New(); m_ExtractROIFilter->SetInput(currentImage); m_ExtractROIFilter->SetChannel(j + 1); m_ExtractROIFilter->GetOutput()->UpdateOutputInformation(); m_ChannelExtractorList->PushBack(m_ExtractROIFilter); m_Filter->SetNthInput(bandId, m_ChannelExtractorList->Back()->GetOutput(), tmpParserVarName.str()); bandId++; } imageId++; } m_Filter->SetExpression(GetParameterString("exp")); // Set the output image SetParameterOutputImage("out", m_Filter->GetOutput()); } ExtractROIFilterType::Pointer m_ExtractROIFilter; ExtractROIFilterListType::Pointer m_ChannelExtractorList; BandMathImageFilterType::Pointer m_Filter; }; } // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::BandMath) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DColumns.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:21:07 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_DBASE_COLUMNS_HXX_ #include "dbase/DColumns.hxx" #endif #ifndef _CONNECTIVITY_DBASE_TABLE_HXX_ #include "dbase/DTable.hxx" #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include "connectivity/sdbcx/VColumn.hxx" #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif using namespace connectivity::dbase; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; typedef file::OColumns ODbaseColumns_BASE; sdbcx::ObjectType ODbaseColumns::createObject(const ::rtl::OUString& _rName) { ODbaseTable* pTable = (ODbaseTable*)m_pTable; // Reference< XFastPropertySet> xCol(pTable->getColumns()[_rName],UNO_QUERY); ::vos::ORef<OSQLColumns> aCols = pTable->getTableColumns(); OSQLColumns::const_iterator aIter = find(aCols->begin(),aCols->end(),_rName,::comphelper::UStringMixEqual(isCaseSensitive())); sdbcx::ObjectType xRet; if(aIter != aCols->end()) xRet = sdbcx::ObjectType(*aIter,UNO_QUERY); return xRet; } // ------------------------------------------------------------------------- void ODbaseColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- Reference< XPropertySet > ODbaseColumns::createDescriptor() { return new sdbcx::OColumn(isCaseSensitive()); } // ----------------------------------------------------------------------------- // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType ODbaseColumns::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor ) { if ( m_pTable->isNew() ) return cloneDescriptor( descriptor ); m_pTable->addColumn( descriptor ); return createObject( _rForName ); } // ----------------------------------------------------------------------------- // ------------------------------------------------------------------------- // XDrop void ODbaseColumns::dropObject(sal_Int32 _nPos,const ::rtl::OUString /*_sElementName*/) { if(!m_pTable->isNew()) m_pTable->dropColumn(_nPos); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.15.216); FILE MERGED 2008/04/01 15:08:40 thb 1.15.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:52 thb 1.15.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:28 rt 1.15.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DColumns.cxx,v $ * $Revision: 1.16 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "dbase/DColumns.hxx" #include "dbase/DTable.hxx" #include "connectivity/sdbcx/VColumn.hxx" #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #include <comphelper/property.hxx> using namespace connectivity::dbase; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; typedef file::OColumns ODbaseColumns_BASE; sdbcx::ObjectType ODbaseColumns::createObject(const ::rtl::OUString& _rName) { ODbaseTable* pTable = (ODbaseTable*)m_pTable; // Reference< XFastPropertySet> xCol(pTable->getColumns()[_rName],UNO_QUERY); ::vos::ORef<OSQLColumns> aCols = pTable->getTableColumns(); OSQLColumns::const_iterator aIter = find(aCols->begin(),aCols->end(),_rName,::comphelper::UStringMixEqual(isCaseSensitive())); sdbcx::ObjectType xRet; if(aIter != aCols->end()) xRet = sdbcx::ObjectType(*aIter,UNO_QUERY); return xRet; } // ------------------------------------------------------------------------- void ODbaseColumns::impl_refresh() throw(RuntimeException) { m_pTable->refreshColumns(); } // ------------------------------------------------------------------------- Reference< XPropertySet > ODbaseColumns::createDescriptor() { return new sdbcx::OColumn(isCaseSensitive()); } // ----------------------------------------------------------------------------- // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType ODbaseColumns::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor ) { if ( m_pTable->isNew() ) return cloneDescriptor( descriptor ); m_pTable->addColumn( descriptor ); return createObject( _rForName ); } // ----------------------------------------------------------------------------- // ------------------------------------------------------------------------- // XDrop void ODbaseColumns::dropObject(sal_Int32 _nPos,const ::rtl::OUString /*_sElementName*/) { if(!m_pTable->isNew()) m_pTable->dropColumn(_nPos); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>// @(#)root/thread:$Id$ // Author: Danilo Piparo August 2017 /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RConfigure.h" #include "ROOT/TTaskGroup.hxx" #ifdef R__USE_IMT #include "TROOT.h" #include "tbb/task_group.h" #include "tbb/task_arena.h" #endif #include <type_traits> /** \class ROOT::Experimental::TTaskGroup \ingroup Parallelism \brief A class to manage the asynchronous execution of work items. A TTaskGroup represents concurrent execution of a group of tasks. Tasks may be dynamically added to the group as it is executing. Nesting TTaskGroup instances may result in a runtime overhead. */ namespace ROOT { namespace Internal { tbb::task_group *CastToTG(void* p) { return (tbb::task_group *) p; } tbb::task_arena *CastToTA(void *p) { return (tbb::task_arena *)p; } } // namespace Internal namespace Experimental { using namespace ROOT::Internal; // in the constructor and destructor the casts are present in order to be able // to be independent from the runtime used. // This leaves the door open for other TTaskGroup implementations. TTaskGroup::TTaskGroup() { #ifdef R__USE_IMT if (!ROOT::IsImplicitMTEnabled()) { throw std::runtime_error("Implicit parallelism not enabled. Cannot instantiate a TTaskGroup."); } fTaskContainer = ((void *)new tbb::task_group()); fTaskArena = ((void *)new tbb::task_arena(ROOT::GetImplicitMTPoolSize())); #endif } TTaskGroup::TTaskGroup(TTaskGroup &&other) { *this = std::move(other); } TTaskGroup &TTaskGroup::operator=(TTaskGroup &&other) { fTaskContainer = other.fTaskContainer; other.fTaskContainer = nullptr; fTaskArena = other.fTaskArena; fTaskArena = nullptr; fCanRun.store(other.fCanRun); return *this; } TTaskGroup::~TTaskGroup() { #ifdef R__USE_IMT if (!fTaskContainer) return; Wait(); delete CastToTG(fTaskContainer); delete CastToTA(fTaskArena); #endif } ///////////////////////////////////////////////////////////////////////////// /// Run operation in the internal task arena to implement work isolation, i.e. /// prevent stealing of work items spawned by ancestors. void TTaskGroup::ExecuteInIsolation(const std::function<void(void)> &operation) { #ifdef R__USE_IMT CastToTA(fTaskArena)->execute([&] { operation(); }); #else operation(); #endif } ///////////////////////////////////////////////////////////////////////////// /// Cancel all submitted tasks immediately. void TTaskGroup::Cancel() { #ifdef R__USE_IMT fCanRun = false; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->cancel(); }); fCanRun = true; #endif } ///////////////////////////////////////////////////////////////////////////// /// Add to the group an item of work which will be ran asynchronously. /// Adding many small items of work to the TTaskGroup is not efficient, /// unless they run for long enough. If the work to be done is little, look /// try to express nested parallelism or resort to other constructs such as /// the TThreadExecutor. /// Trying to add a work item to the group while it is in waiting state /// makes the method block. void TTaskGroup::Run(const std::function<void(void)> &closure) { #ifdef R__USE_IMT while (!fCanRun) /* empty */; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->run(closure); }); #else closure(); #endif } ///////////////////////////////////////////////////////////////////////////// /// Wait until all submitted items of work are completed. This method /// is blocking. void TTaskGroup::Wait() { #ifdef R__USE_IMT fCanRun = false; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->wait(); }); fCanRun = true; #endif } } // namespace Experimental } // namespace ROOT <commit_msg>[IMT] Fix noimt builds<commit_after>// @(#)root/thread:$Id$ // Author: Danilo Piparo August 2017 /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "RConfigure.h" #include "ROOT/TTaskGroup.hxx" #ifdef R__USE_IMT #include "TROOT.h" #include "tbb/task_group.h" #include "tbb/task_arena.h" #endif #include <type_traits> /** \class ROOT::Experimental::TTaskGroup \ingroup Parallelism \brief A class to manage the asynchronous execution of work items. A TTaskGroup represents concurrent execution of a group of tasks. Tasks may be dynamically added to the group as it is executing. Nesting TTaskGroup instances may result in a runtime overhead. */ namespace ROOT { namespace Internal { #ifdef R__USE_IMT tbb::task_group *CastToTG(void* p) { return (tbb::task_group *) p; } tbb::task_arena *CastToTA(void *p) { return (tbb::task_arena *)p; } #endif } // namespace Internal namespace Experimental { using namespace ROOT::Internal; // in the constructor and destructor the casts are present in order to be able // to be independent from the runtime used. // This leaves the door open for other TTaskGroup implementations. TTaskGroup::TTaskGroup() { #ifdef R__USE_IMT if (!ROOT::IsImplicitMTEnabled()) { throw std::runtime_error("Implicit parallelism not enabled. Cannot instantiate a TTaskGroup."); } fTaskContainer = ((void *)new tbb::task_group()); fTaskArena = ((void *)new tbb::task_arena(ROOT::GetImplicitMTPoolSize())); #endif } TTaskGroup::TTaskGroup(TTaskGroup &&other) { *this = std::move(other); } TTaskGroup &TTaskGroup::operator=(TTaskGroup &&other) { fTaskContainer = other.fTaskContainer; other.fTaskContainer = nullptr; fTaskArena = other.fTaskArena; fTaskArena = nullptr; fCanRun.store(other.fCanRun); return *this; } TTaskGroup::~TTaskGroup() { #ifdef R__USE_IMT if (!fTaskContainer) return; Wait(); delete CastToTG(fTaskContainer); delete CastToTA(fTaskArena); #endif } ///////////////////////////////////////////////////////////////////////////// /// Run operation in the internal task arena to implement work isolation, i.e. /// prevent stealing of work items spawned by ancestors. void TTaskGroup::ExecuteInIsolation(const std::function<void(void)> &operation) { #ifdef R__USE_IMT CastToTA(fTaskArena)->execute([&] { operation(); }); #else operation(); #endif } ///////////////////////////////////////////////////////////////////////////// /// Cancel all submitted tasks immediately. void TTaskGroup::Cancel() { #ifdef R__USE_IMT fCanRun = false; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->cancel(); }); fCanRun = true; #endif } ///////////////////////////////////////////////////////////////////////////// /// Add to the group an item of work which will be ran asynchronously. /// Adding many small items of work to the TTaskGroup is not efficient, /// unless they run for long enough. If the work to be done is little, look /// try to express nested parallelism or resort to other constructs such as /// the TThreadExecutor. /// Trying to add a work item to the group while it is in waiting state /// makes the method block. void TTaskGroup::Run(const std::function<void(void)> &closure) { #ifdef R__USE_IMT while (!fCanRun) /* empty */; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->run(closure); }); #else closure(); #endif } ///////////////////////////////////////////////////////////////////////////// /// Wait until all submitted items of work are completed. This method /// is blocking. void TTaskGroup::Wait() { #ifdef R__USE_IMT fCanRun = false; ExecuteInIsolation([&] { CastToTG(fTaskContainer)->wait(); }); fCanRun = true; #endif } } // namespace Experimental } // namespace ROOT <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: irendermodule.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2005-11-02 12:45:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_CANVAS_IRENDERMODULE_HXX #define INCLUDED_CANVAS_IRENDERMODULE_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <boost/shared_ptr.hpp> #include <boost/utility.hpp> namespace basegfx { class B2DRange; class B2IRange; class B2IVector; class B2IPoint; } namespace canvas { struct ISurface; struct Vertex { float r,g,b,a; float u,v; float x,y,z; }; /** Output module interface for backend render implementations. Implement this interface for each operating system- or library-specific rendering backend, which needs coupling with the canvas rendering framework (which can be shared between all backend implementations). */ struct IRenderModule { /** Type of primitive passed to the render module via pushVertex() */ enum PrimitiveType { PRIMITIVE_TYPE_UNKNONWN, PRIMITIVE_TYPE_TRIANGLE, PRIMITIVE_TYPE_QUAD }; virtual ~IRenderModule() {} /// Lock rendermodule against concurrent access virtual void lock() const = 0; /// Unlock rendermodule for concurrent access virtual void unlock() const = 0; /** Maximal size of VRAM pages available This is typically the maximum texture size of the hardware, or some arbitrary limit if the backend is software. */ virtual ::basegfx::B2IVector getPageSize() = 0; /** Create a (possibly hardware-accelerated) surface @return a pointer to a surface, which is an abstraction of a piece of (possibly hardware-accelerated) texture memory. */ virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0; /** Begin rendering the given primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void beginPrimitive( PrimitiveType eType ) = 0; /** Finish rendering a primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void endPrimitive() = 0; /** Add given vertex to current primitive After issuing a beginPrimitive(), each pushVertex() adds a vertex to the active primitive. */ virtual void pushVertex( const Vertex& vertex ) = 0; /** Query error status @returns true, if an error occured during primitive construction. */ virtual bool isError() = 0; }; typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr; /// Little RAII wrapper for guarding access to IRenderModule interface class RenderModuleGuard : private ::boost::noncopyable { public: explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) : mpRenderModule( rRenderModule ) { mpRenderModule->lock(); } ~RenderModuleGuard() { mpRenderModule->unlock(); } private: const IRenderModuleSharedPtr mpRenderModule; }; } #endif /* INCLUDED_CANVAS_IRENDERMODULE_HXX */ <commit_msg>INTEGRATION: CWS presfixes09 (1.2.32); FILE MERGED 2006/11/09 14:36:43 thb 1.2.32.1: #126453# Corrected typo in enum<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: irendermodule.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-12-13 14:37:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_CANVAS_IRENDERMODULE_HXX #define INCLUDED_CANVAS_IRENDERMODULE_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <boost/shared_ptr.hpp> #include <boost/utility.hpp> namespace basegfx { class B2DRange; class B2IRange; class B2IVector; class B2IPoint; } namespace canvas { struct ISurface; struct Vertex { float r,g,b,a; float u,v; float x,y,z; }; /** Output module interface for backend render implementations. Implement this interface for each operating system- or library-specific rendering backend, which needs coupling with the canvas rendering framework (which can be shared between all backend implementations). */ struct IRenderModule { /** Type of primitive passed to the render module via pushVertex() */ enum PrimitiveType { PRIMITIVE_TYPE_UNKNOWN, PRIMITIVE_TYPE_TRIANGLE, PRIMITIVE_TYPE_QUAD }; virtual ~IRenderModule() {} /// Lock rendermodule against concurrent access virtual void lock() const = 0; /// Unlock rendermodule for concurrent access virtual void unlock() const = 0; /** Maximal size of VRAM pages available This is typically the maximum texture size of the hardware, or some arbitrary limit if the backend is software. */ virtual ::basegfx::B2IVector getPageSize() = 0; /** Create a (possibly hardware-accelerated) surface @return a pointer to a surface, which is an abstraction of a piece of (possibly hardware-accelerated) texture memory. */ virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0; /** Begin rendering the given primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void beginPrimitive( PrimitiveType eType ) = 0; /** Finish rendering a primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void endPrimitive() = 0; /** Add given vertex to current primitive After issuing a beginPrimitive(), each pushVertex() adds a vertex to the active primitive. */ virtual void pushVertex( const Vertex& vertex ) = 0; /** Query error status @returns true, if an error occured during primitive construction. */ virtual bool isError() = 0; }; typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr; /// Little RAII wrapper for guarding access to IRenderModule interface class RenderModuleGuard : private ::boost::noncopyable { public: explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) : mpRenderModule( rRenderModule ) { mpRenderModule->lock(); } ~RenderModuleGuard() { mpRenderModule->unlock(); } private: const IRenderModuleSharedPtr mpRenderModule; }; } #endif /* INCLUDED_CANVAS_IRENDERMODULE_HXX */ <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_TYPETRAITS_HPP_INCLUDED #define LUABIND_TYPETRAITS_HPP_INCLUDED #include <luabind/config.hpp> #include <boost/mpl/if.hpp> #include <boost/type_traits/is_reference.hpp> #include <boost/type_traits/is_const.hpp> #include <luabind/detail/primitives.hpp> namespace luabind { namespace detail { #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template<class T> struct is_const_type { typedef typename boost::mpl::if_<boost::is_const<T> , yes_t , no_t >::type type; }; template<bool is_Reference = false> struct is_const_reference_helper { template<class> struct apply { enum { value = false }; }; }; template<class T> typename is_const_type<T>::type is_const_reference_tester(T&); no_t is_const_reference_tester(...); template<> struct is_const_reference_helper<true> { template<class T> struct apply { static T getT(); enum { value = sizeof(is_const_reference_tester(getT())) == sizeof(yes_t) }; }; }; template<class T> struct is_const_reference : is_const_reference_helper<boost::is_reference<T>::value>::template apply<T> { typedef boost::mpl::bool_<value> type; }; #else template<class T> struct is_const_reference { enum { value = false }; typedef boost::mpl::bool_<value> type; }; template<class T> struct is_const_reference<const T&> { enum { value = true }; typedef boost::mpl::bool_<value> type; }; #endif template<class T> struct is_nonconst_reference { enum { #ifdef BOOST_HAS_RVALUE_REFS value = boost::is_lvalue_reference<T>::value && !is_const_reference<T>::value #else value = boost::is_reference<T>::value && !is_const_reference<T>::value #endif }; typedef boost::mpl::bool_<value> type; }; template<class A> yes_t is_const_pointer_helper(void(*)(const A*)); no_t is_const_pointer_helper(...); template<class T> struct is_const_pointer { enum { value = sizeof(is_const_pointer_helper((void(*)(T))0)) == sizeof(yes_t) }; typedef boost::mpl::bool_<value> type; }; template<class A> yes_t is_nonconst_pointer_helper(void(*)(A*)); no_t is_nonconst_pointer_helper(...); template<class T> struct is_nonconst_pointer { enum { value = sizeof(is_nonconst_pointer_helper((void(*)(T))0)) == sizeof(yes_t) && !is_const_pointer<T>::value }; typedef boost::mpl::bool_<value> type; }; /* template<class T> struct is_constructable_from_helper { static yes_t check(const T&); static no_t check(...); }; template<class T, class From> struct is_constructable_from { static From getFrom(); enum { value = sizeof(is_constructable_from_helper<T>::check(getFrom())) == sizeof(yes_t) }; }; template<class T> struct is_const_member_function_helper { static no_t test(...); template<class R> static yes_t test(R(T::*)() const); template<class R, class A1> static yes_t test(R(T::*)(A1) const); template<class R, class A1, class A2> static yes_t test(R(T::*)(A1,A2) const); template<class R, class A1, class A2, class A3> static yes_t test(R(T::*)(A1,A2,A3) const); }; template<class T, class U> struct is_const_member_function { static U getU(); enum { value = sizeof(is_const_member_function_helper<T>::test(getU())) == sizeof(yes_t) }; }; */ template<int v1, int v2> struct max_c { enum { value = (v1>v2)?v1:v2 }; }; }} #endif // LUABIND_TYPETRAITS_HPP_INCLUDED <commit_msg>Substitute boost::is_lvalue_reference with partial template specialisation.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_TYPETRAITS_HPP_INCLUDED #define LUABIND_TYPETRAITS_HPP_INCLUDED #include <luabind/config.hpp> #include <boost/mpl/if.hpp> #include <boost/type_traits/is_reference.hpp> #include <boost/type_traits/is_const.hpp> #include <luabind/detail/primitives.hpp> namespace luabind { namespace detail { #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template<class T> struct is_const_type { typedef typename boost::mpl::if_<boost::is_const<T> , yes_t , no_t >::type type; }; template<bool is_Reference = false> struct is_const_reference_helper { template<class> struct apply { enum { value = false }; }; }; template<class T> typename is_const_type<T>::type is_const_reference_tester(T&); no_t is_const_reference_tester(...); template<> struct is_const_reference_helper<true> { template<class T> struct apply { static T getT(); enum { value = sizeof(is_const_reference_tester(getT())) == sizeof(yes_t) }; }; }; template<class T> struct is_const_reference : is_const_reference_helper<boost::is_reference<T>::value>::template apply<T> { typedef boost::mpl::bool_<value> type; }; template<class T> struct is_nonconst_reference { enum { value = boost::is_reference<T>::value && !is_const_reference<T>::value }; typedef boost::mpl::bool_<value> type; }; #else template<class T> struct is_const_reference { enum { value = false }; typedef boost::mpl::bool_<value> type; }; template<class T> struct is_const_reference<const T&> { enum { value = true }; typedef boost::mpl::bool_<value> type; }; template<class T> struct is_nonconst_reference { enum { value = false }; typedef boost::mpl::bool_<value> type; }; template<class T> struct is_nonconst_reference<T&> { enum { value = !is_const_reference<T&>::value }; typedef boost::mpl::bool_<value> type; }; #endif template<class A> yes_t is_const_pointer_helper(void(*)(const A*)); no_t is_const_pointer_helper(...); template<class T> struct is_const_pointer { enum { value = sizeof(is_const_pointer_helper((void(*)(T))0)) == sizeof(yes_t) }; typedef boost::mpl::bool_<value> type; }; template<class A> yes_t is_nonconst_pointer_helper(void(*)(A*)); no_t is_nonconst_pointer_helper(...); template<class T> struct is_nonconst_pointer { enum { value = sizeof(is_nonconst_pointer_helper((void(*)(T))0)) == sizeof(yes_t) && !is_const_pointer<T>::value }; typedef boost::mpl::bool_<value> type; }; /* template<class T> struct is_constructable_from_helper { static yes_t check(const T&); static no_t check(...); }; template<class T, class From> struct is_constructable_from { static From getFrom(); enum { value = sizeof(is_constructable_from_helper<T>::check(getFrom())) == sizeof(yes_t) }; }; template<class T> struct is_const_member_function_helper { static no_t test(...); template<class R> static yes_t test(R(T::*)() const); template<class R, class A1> static yes_t test(R(T::*)(A1) const); template<class R, class A1, class A2> static yes_t test(R(T::*)(A1,A2) const); template<class R, class A1, class A2, class A3> static yes_t test(R(T::*)(A1,A2,A3) const); }; template<class T, class U> struct is_const_member_function { static U getU(); enum { value = sizeof(is_const_member_function_helper<T>::test(getU())) == sizeof(yes_t) }; }; */ template<int v1, int v2> struct max_c { enum { value = (v1>v2)?v1:v2 }; }; }} #endif // LUABIND_TYPETRAITS_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Platform-specific code for Linux goes here. For the POSIX-compatible // parts, the implementation is in platform-posix.cc. #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> // Ubuntu Dapper requires memory pages to be marked as // executable. Otherwise, OS raises an exception when executing code // in that page. #include <errno.h> #include <fcntl.h> // open #include <stdarg.h> #include <strings.h> // index #include <sys/mman.h> // mmap & munmap #include <sys/stat.h> // open #include <sys/types.h> // mmap & munmap #include <unistd.h> // sysconf // GLibc on ARM defines mcontext_t has a typedef for 'struct sigcontext'. // Old versions of the C library <signal.h> didn't define the type. #if defined(__ANDROID__) && !defined(__BIONIC_HAVE_UCONTEXT_T) && \ (defined(__arm__) || defined(__aarch64__)) && \ !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT) #include <asm/sigcontext.h> // NOLINT #endif #if defined(LEAK_SANITIZER) #include <sanitizer/lsan_interface.h> #endif #include <cmath> #undef MAP_TYPE #include "src/base/macros.h" #include "src/base/platform/platform.h" #if V8_OS_NACL #if !defined(MAP_NORESERVE) // PNaCL doesn't have this, so we always grab all of the memory, which is bad. #define MAP_NORESERVE 0 #endif #else #include <sys/prctl.h> #include <sys/syscall.h> #endif namespace v8 { namespace base { #ifdef __arm__ bool OS::ArmUsingHardFloat() { // GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify // the Floating Point ABI used (PCS stands for Procedure Call Standard). // We use these as well as a couple of other defines to statically determine // what FP ABI used. // GCC versions 4.4 and below don't support hard-fp. // GCC versions 4.5 may support hard-fp without defining __ARM_PCS or // __ARM_PCS_VFP. #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if GCC_VERSION >= 40600 #if defined(__ARM_PCS_VFP) return true; #else return false; #endif #elif GCC_VERSION < 40500 return false; #else #if defined(__ARM_PCS_VFP) return true; #elif defined(__ARM_PCS) || defined(__SOFTFP__) || defined(__SOFTFP) || \ !defined(__VFP_FP__) return false; #else #error "Your version of GCC does not report the FP ABI compiled for." \ "Please report it on this issue" \ "http://code.google.com/p/v8/issues/detail?id=2140" #endif #endif #undef GCC_VERSION } #endif // def __arm__ const char* OS::LocalTimezone(double time, TimezoneCache* cache) { #if V8_OS_NACL // Missing support for tm_zone field. return ""; #else if (std::isnan(time)) return ""; time_t tv = static_cast<time_t>(std::floor(time/msPerSecond)); struct tm* t = localtime(&tv); if (NULL == t) return ""; return t->tm_zone; #endif } double OS::LocalTimeOffset(TimezoneCache* cache) { #if V8_OS_NACL // Missing support for tm_zone field. return 0; #else time_t tv = time(NULL); struct tm* t = localtime(&tv); // tm_gmtoff includes any daylight savings offset, so subtract it. return static_cast<double>(t->tm_gmtoff * msPerSecond - (t->tm_isdst > 0 ? 3600 * msPerSecond : 0)); #endif } void* OS::Allocate(const size_t requested, size_t* allocated, bool is_executable) { const size_t msize = RoundUp(requested, AllocateAlignment()); int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); void* addr = OS::GetRandomMmapAddr(); void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (mbase == MAP_FAILED) return NULL; *allocated = msize; return mbase; } class PosixMemoryMappedFile : public OS::MemoryMappedFile { public: PosixMemoryMappedFile(FILE* file, void* memory, int size) : file_(file), memory_(memory), size_(size) { } virtual ~PosixMemoryMappedFile(); virtual void* memory() { return memory_; } virtual int size() { return size_; } private: FILE* file_; void* memory_; int size_; }; OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { FILE* file = fopen(name, "r+"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); void* memory = mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, void* initial) { FILE* file = fopen(name, "w+"); if (file == NULL) return NULL; int result = fwrite(initial, size, 1, file); if (result < 1) { fclose(file); return NULL; } void* memory = mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } PosixMemoryMappedFile::~PosixMemoryMappedFile() { if (memory_) OS::Free(memory_, size_); fclose(file_); } std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() { std::vector<SharedLibraryAddress> result; // This function assumes that the layout of the file is as follows: // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name] // If we encounter an unexpected situation we abort scanning further entries. FILE* fp = fopen("/proc/self/maps", "r"); if (fp == NULL) return result; // Allocate enough room to be able to store a full file name. const int kLibNameLen = FILENAME_MAX + 1; char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen)); // This loop will terminate once the scanning hits an EOF. while (true) { uintptr_t start, end; char attr_r, attr_w, attr_x, attr_p; // Parse the addresses and permission bits at the beginning of the line. if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break; if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break; int c; if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') { // Found a read-only executable entry. Skip characters until we reach // the beginning of the filename or the end of the line. do { c = getc(fp); } while ((c != EOF) && (c != '\n') && (c != '/') && (c != '[')); if (c == EOF) break; // EOF: Was unexpected, just exit. // Process the filename if found. if ((c == '/') || (c == '[')) { // Push the '/' or '[' back into the stream to be read below. ungetc(c, fp); // Read to the end of the line. Exit if the read fails. if (fgets(lib_name, kLibNameLen, fp) == NULL) break; // Drop the newline character read by fgets. We do not need to check // for a zero-length string because we know that we at least read the // '/' or '[' character. lib_name[strlen(lib_name) - 1] = '\0'; } else { // No library name found, just record the raw address range. snprintf(lib_name, kLibNameLen, "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end); } result.push_back(SharedLibraryAddress(lib_name, start, end)); } else { // Entry not describing executable data. Skip to end of line to set up // reading the next entry. do { c = getc(fp); } while ((c != EOF) && (c != '\n')); if (c == EOF) break; } } free(lib_name); fclose(fp); return result; } void OS::SignalCodeMovingGC() { // Support for ll_prof.py. // // The Linux profiler built into the kernel logs all mmap's with // PROT_EXEC so that analysis tools can properly attribute ticks. We // do a mmap with a name known by ll_prof.py and immediately munmap // it. This injects a GC marker into the stream of events generated // by the kernel and allows us to synchronize V8 code log and the // kernel log. int size = sysconf(_SC_PAGESIZE); FILE* f = fopen(OS::GetGCFakeMMapFile(), "w+"); if (f == NULL) { OS::PrintError("Failed to open %s\n", OS::GetGCFakeMMapFile()); OS::Abort(); } void* addr = mmap(OS::GetRandomMmapAddr(), size, #if V8_OS_NACL // The Native Client port of V8 uses an interpreter, // so code pages don't need PROT_EXEC. PROT_READ, #else PROT_READ | PROT_EXEC, #endif MAP_PRIVATE, fileno(f), 0); DCHECK(addr != MAP_FAILED); OS::Free(addr, size); fclose(f); } // Constants used for mmap. static const int kMmapFd = -1; static const int kMmapFdOffset = 0; VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } VirtualMemory::VirtualMemory(size_t size) : address_(ReserveRegion(size)), size_(size) { } VirtualMemory::VirtualMemory(size_t size, size_t alignment) : address_(NULL), size_(0) { DCHECK((alignment % OS::AllocateAlignment()) == 0); size_t request_size = RoundUp(size + alignment, static_cast<intptr_t>(OS::AllocateAlignment())); void* reservation = mmap(OS::GetRandomMmapAddr(), request_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (reservation == MAP_FAILED) return; uint8_t* base = static_cast<uint8_t*>(reservation); uint8_t* aligned_base = RoundUp(base, alignment); DCHECK_LE(base, aligned_base); // Unmap extra memory reserved before and after the desired block. if (aligned_base != base) { size_t prefix_size = static_cast<size_t>(aligned_base - base); OS::Free(base, prefix_size); request_size -= prefix_size; } size_t aligned_size = RoundUp(size, OS::AllocateAlignment()); DCHECK_LE(aligned_size, request_size); if (aligned_size != request_size) { size_t suffix_size = request_size - aligned_size; OS::Free(aligned_base + aligned_size, suffix_size); request_size -= suffix_size; } DCHECK(aligned_size == request_size); address_ = static_cast<void*>(aligned_base); size_ = aligned_size; #if defined(LEAK_SANITIZER) __lsan_register_root_region(address_, size_); #endif } VirtualMemory::~VirtualMemory() { if (IsReserved()) { bool result = ReleaseRegion(address(), size()); DCHECK(result); USE(result); } } bool VirtualMemory::IsReserved() { return address_ != NULL; } void VirtualMemory::Reset() { address_ = NULL; size_ = 0; } bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { return CommitRegion(address, size, is_executable); } bool VirtualMemory::Uncommit(void* address, size_t size) { return UncommitRegion(address, size); } bool VirtualMemory::Guard(void* address) { OS::Guard(address, OS::CommitPageSize()); return true; } void* VirtualMemory::ReserveRegion(size_t size) { void* result = mmap(OS::GetRandomMmapAddr(), size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (result == MAP_FAILED) return NULL; #if defined(LEAK_SANITIZER) __lsan_register_root_region(result, size); #endif return result; } bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { #if V8_OS_NACL // The Native Client port of V8 uses an interpreter, // so code pages don't need PROT_EXEC. int prot = PROT_READ | PROT_WRITE; #else int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); #endif if (MAP_FAILED == mmap(base, size, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, kMmapFd, kMmapFdOffset)) { return false; } return true; } bool VirtualMemory::UncommitRegion(void* base, size_t size) { return mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED, kMmapFd, kMmapFdOffset) != MAP_FAILED; } bool VirtualMemory::ReleaseRegion(void* base, size_t size) { #if defined(LEAK_SANITIZER) __lsan_unregister_root_region(base, size); #endif return munmap(base, size) == 0; } bool VirtualMemory::HasLazyCommits() { return true; } } } // namespace v8::base <commit_msg>Don't crash if the tm_zone field returned by localtime is NULL<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Platform-specific code for Linux goes here. For the POSIX-compatible // parts, the implementation is in platform-posix.cc. #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> // Ubuntu Dapper requires memory pages to be marked as // executable. Otherwise, OS raises an exception when executing code // in that page. #include <errno.h> #include <fcntl.h> // open #include <stdarg.h> #include <strings.h> // index #include <sys/mman.h> // mmap & munmap #include <sys/stat.h> // open #include <sys/types.h> // mmap & munmap #include <unistd.h> // sysconf // GLibc on ARM defines mcontext_t has a typedef for 'struct sigcontext'. // Old versions of the C library <signal.h> didn't define the type. #if defined(__ANDROID__) && !defined(__BIONIC_HAVE_UCONTEXT_T) && \ (defined(__arm__) || defined(__aarch64__)) && \ !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT) #include <asm/sigcontext.h> // NOLINT #endif #if defined(LEAK_SANITIZER) #include <sanitizer/lsan_interface.h> #endif #include <cmath> #undef MAP_TYPE #include "src/base/macros.h" #include "src/base/platform/platform.h" #if V8_OS_NACL #if !defined(MAP_NORESERVE) // PNaCL doesn't have this, so we always grab all of the memory, which is bad. #define MAP_NORESERVE 0 #endif #else #include <sys/prctl.h> #include <sys/syscall.h> #endif namespace v8 { namespace base { #ifdef __arm__ bool OS::ArmUsingHardFloat() { // GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify // the Floating Point ABI used (PCS stands for Procedure Call Standard). // We use these as well as a couple of other defines to statically determine // what FP ABI used. // GCC versions 4.4 and below don't support hard-fp. // GCC versions 4.5 may support hard-fp without defining __ARM_PCS or // __ARM_PCS_VFP. #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if GCC_VERSION >= 40600 #if defined(__ARM_PCS_VFP) return true; #else return false; #endif #elif GCC_VERSION < 40500 return false; #else #if defined(__ARM_PCS_VFP) return true; #elif defined(__ARM_PCS) || defined(__SOFTFP__) || defined(__SOFTFP) || \ !defined(__VFP_FP__) return false; #else #error "Your version of GCC does not report the FP ABI compiled for." \ "Please report it on this issue" \ "http://code.google.com/p/v8/issues/detail?id=2140" #endif #endif #undef GCC_VERSION } #endif // def __arm__ const char* OS::LocalTimezone(double time, TimezoneCache* cache) { #if V8_OS_NACL // Missing support for tm_zone field. return ""; #else if (std::isnan(time)) return ""; time_t tv = static_cast<time_t>(std::floor(time/msPerSecond)); struct tm* t = localtime(&tv); if (!t || !t->tm_zone) return ""; return t->tm_zone; #endif } double OS::LocalTimeOffset(TimezoneCache* cache) { #if V8_OS_NACL // Missing support for tm_zone field. return 0; #else time_t tv = time(NULL); struct tm* t = localtime(&tv); // tm_gmtoff includes any daylight savings offset, so subtract it. return static_cast<double>(t->tm_gmtoff * msPerSecond - (t->tm_isdst > 0 ? 3600 * msPerSecond : 0)); #endif } void* OS::Allocate(const size_t requested, size_t* allocated, bool is_executable) { const size_t msize = RoundUp(requested, AllocateAlignment()); int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); void* addr = OS::GetRandomMmapAddr(); void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (mbase == MAP_FAILED) return NULL; *allocated = msize; return mbase; } class PosixMemoryMappedFile : public OS::MemoryMappedFile { public: PosixMemoryMappedFile(FILE* file, void* memory, int size) : file_(file), memory_(memory), size_(size) { } virtual ~PosixMemoryMappedFile(); virtual void* memory() { return memory_; } virtual int size() { return size_; } private: FILE* file_; void* memory_; int size_; }; OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { FILE* file = fopen(name, "r+"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); void* memory = mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, void* initial) { FILE* file = fopen(name, "w+"); if (file == NULL) return NULL; int result = fwrite(initial, size, 1, file); if (result < 1) { fclose(file); return NULL; } void* memory = mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } PosixMemoryMappedFile::~PosixMemoryMappedFile() { if (memory_) OS::Free(memory_, size_); fclose(file_); } std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() { std::vector<SharedLibraryAddress> result; // This function assumes that the layout of the file is as follows: // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name] // If we encounter an unexpected situation we abort scanning further entries. FILE* fp = fopen("/proc/self/maps", "r"); if (fp == NULL) return result; // Allocate enough room to be able to store a full file name. const int kLibNameLen = FILENAME_MAX + 1; char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen)); // This loop will terminate once the scanning hits an EOF. while (true) { uintptr_t start, end; char attr_r, attr_w, attr_x, attr_p; // Parse the addresses and permission bits at the beginning of the line. if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break; if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break; int c; if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') { // Found a read-only executable entry. Skip characters until we reach // the beginning of the filename or the end of the line. do { c = getc(fp); } while ((c != EOF) && (c != '\n') && (c != '/') && (c != '[')); if (c == EOF) break; // EOF: Was unexpected, just exit. // Process the filename if found. if ((c == '/') || (c == '[')) { // Push the '/' or '[' back into the stream to be read below. ungetc(c, fp); // Read to the end of the line. Exit if the read fails. if (fgets(lib_name, kLibNameLen, fp) == NULL) break; // Drop the newline character read by fgets. We do not need to check // for a zero-length string because we know that we at least read the // '/' or '[' character. lib_name[strlen(lib_name) - 1] = '\0'; } else { // No library name found, just record the raw address range. snprintf(lib_name, kLibNameLen, "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end); } result.push_back(SharedLibraryAddress(lib_name, start, end)); } else { // Entry not describing executable data. Skip to end of line to set up // reading the next entry. do { c = getc(fp); } while ((c != EOF) && (c != '\n')); if (c == EOF) break; } } free(lib_name); fclose(fp); return result; } void OS::SignalCodeMovingGC() { // Support for ll_prof.py. // // The Linux profiler built into the kernel logs all mmap's with // PROT_EXEC so that analysis tools can properly attribute ticks. We // do a mmap with a name known by ll_prof.py and immediately munmap // it. This injects a GC marker into the stream of events generated // by the kernel and allows us to synchronize V8 code log and the // kernel log. int size = sysconf(_SC_PAGESIZE); FILE* f = fopen(OS::GetGCFakeMMapFile(), "w+"); if (f == NULL) { OS::PrintError("Failed to open %s\n", OS::GetGCFakeMMapFile()); OS::Abort(); } void* addr = mmap(OS::GetRandomMmapAddr(), size, #if V8_OS_NACL // The Native Client port of V8 uses an interpreter, // so code pages don't need PROT_EXEC. PROT_READ, #else PROT_READ | PROT_EXEC, #endif MAP_PRIVATE, fileno(f), 0); DCHECK(addr != MAP_FAILED); OS::Free(addr, size); fclose(f); } // Constants used for mmap. static const int kMmapFd = -1; static const int kMmapFdOffset = 0; VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } VirtualMemory::VirtualMemory(size_t size) : address_(ReserveRegion(size)), size_(size) { } VirtualMemory::VirtualMemory(size_t size, size_t alignment) : address_(NULL), size_(0) { DCHECK((alignment % OS::AllocateAlignment()) == 0); size_t request_size = RoundUp(size + alignment, static_cast<intptr_t>(OS::AllocateAlignment())); void* reservation = mmap(OS::GetRandomMmapAddr(), request_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (reservation == MAP_FAILED) return; uint8_t* base = static_cast<uint8_t*>(reservation); uint8_t* aligned_base = RoundUp(base, alignment); DCHECK_LE(base, aligned_base); // Unmap extra memory reserved before and after the desired block. if (aligned_base != base) { size_t prefix_size = static_cast<size_t>(aligned_base - base); OS::Free(base, prefix_size); request_size -= prefix_size; } size_t aligned_size = RoundUp(size, OS::AllocateAlignment()); DCHECK_LE(aligned_size, request_size); if (aligned_size != request_size) { size_t suffix_size = request_size - aligned_size; OS::Free(aligned_base + aligned_size, suffix_size); request_size -= suffix_size; } DCHECK(aligned_size == request_size); address_ = static_cast<void*>(aligned_base); size_ = aligned_size; #if defined(LEAK_SANITIZER) __lsan_register_root_region(address_, size_); #endif } VirtualMemory::~VirtualMemory() { if (IsReserved()) { bool result = ReleaseRegion(address(), size()); DCHECK(result); USE(result); } } bool VirtualMemory::IsReserved() { return address_ != NULL; } void VirtualMemory::Reset() { address_ = NULL; size_ = 0; } bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { return CommitRegion(address, size, is_executable); } bool VirtualMemory::Uncommit(void* address, size_t size) { return UncommitRegion(address, size); } bool VirtualMemory::Guard(void* address) { OS::Guard(address, OS::CommitPageSize()); return true; } void* VirtualMemory::ReserveRegion(size_t size) { void* result = mmap(OS::GetRandomMmapAddr(), size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (result == MAP_FAILED) return NULL; #if defined(LEAK_SANITIZER) __lsan_register_root_region(result, size); #endif return result; } bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { #if V8_OS_NACL // The Native Client port of V8 uses an interpreter, // so code pages don't need PROT_EXEC. int prot = PROT_READ | PROT_WRITE; #else int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); #endif if (MAP_FAILED == mmap(base, size, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, kMmapFd, kMmapFdOffset)) { return false; } return true; } bool VirtualMemory::UncommitRegion(void* base, size_t size) { return mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED, kMmapFd, kMmapFdOffset) != MAP_FAILED; } bool VirtualMemory::ReleaseRegion(void* base, size_t size) { #if defined(LEAK_SANITIZER) __lsan_unregister_root_region(base, size); #endif return munmap(base, size) == 0; } bool VirtualMemory::HasLazyCommits() { return true; } } } // namespace v8::base <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: clipboardmanager.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 16:56:12 $ * * 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_dtrans.hxx" #include <clipboardmanager.hxx> #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif using namespace com::sun::star::container; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace cppu; using namespace osl; using namespace std; using ::dtrans::ClipboardManager; using ::rtl::OUString; // ------------------------------------------------------------------------ ClipboardManager::ClipboardManager(): WeakComponentImplHelper3< XClipboardManager, XEventListener, XServiceInfo > (m_aMutex), m_aDefaultName(OUString::createFromAscii("default")) { } // ------------------------------------------------------------------------ ClipboardManager::~ClipboardManager() { } // ------------------------------------------------------------------------ OUString SAL_CALL ClipboardManager::getImplementationName( ) throw(RuntimeException) { return OUString::createFromAscii(CLIPBOARDMANAGER_IMPLEMENTATION_NAME); } // ------------------------------------------------------------------------ sal_Bool SAL_CALL ClipboardManager::supportsService( const OUString& ServiceName ) throw(RuntimeException) { Sequence < OUString > SupportedServicesNames = ClipboardManager_getSupportedServiceNames(); for ( sal_Int32 n = 0, nmax = SupportedServicesNames.getLength(); n < nmax; n++ ) if (SupportedServicesNames[n].compareTo(ServiceName) == 0) return sal_True; return sal_False; } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager::getSupportedServiceNames( ) throw(RuntimeException) { return ClipboardManager_getSupportedServiceNames(); } // ------------------------------------------------------------------------ Reference< XClipboard > SAL_CALL ClipboardManager::getClipboard( const OUString& aName ) throw(NoSuchElementException, RuntimeException) { MutexGuard aGuard(m_aMutex); // object is disposed already if (rBHelper.bDisposed) throw DisposedException(OUString::createFromAscii("object is disposed."), static_cast < XClipboardManager * > (this)); ClipboardMap::iterator iter = m_aClipboardMap.find(aName.getLength() ? aName : m_aDefaultName); if (iter != m_aClipboardMap.end()) return iter->second; throw NoSuchElementException(aName, static_cast < XClipboardManager * > (this)); } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::addClipboard( const Reference< XClipboard >& xClipboard ) throw(IllegalArgumentException, ElementExistException, RuntimeException) { OSL_ASSERT(xClipboard.is()); // check parameter if (!xClipboard.is()) throw IllegalArgumentException(OUString::createFromAscii("empty reference"), static_cast < XClipboardManager * > (this), 1); // the name "default" is reserved for internal use OUString aName = xClipboard->getName(); if (m_aDefaultName.compareTo(aName) == 0) throw IllegalArgumentException(OUString::createFromAscii("name reserved"), static_cast < XClipboardManager * > (this), 1); // try to add new clipboard to the list ClearableMutexGuard aGuard(m_aMutex); if (!rBHelper.bDisposed && !rBHelper.bInDispose) { pair< const OUString, Reference< XClipboard > > value ( aName.getLength() ? aName : m_aDefaultName, xClipboard ); pair< ClipboardMap::iterator, bool > p = m_aClipboardMap.insert(value); aGuard.clear(); // insert failed, element must exist already if (!p.second) throw ElementExistException(aName, static_cast < XClipboardManager * > (this)); // request disposing notifications Reference< XComponent > xComponent(xClipboard, UNO_QUERY); if (xComponent.is()) xComponent->addEventListener(static_cast < XEventListener * > (this)); } } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::removeClipboard( const OUString& aName ) throw(RuntimeException) { MutexGuard aGuard(m_aMutex); if (!rBHelper.bDisposed) m_aClipboardMap.erase(aName.getLength() ? aName : m_aDefaultName ); } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager::listClipboardNames() throw(RuntimeException) { MutexGuard aGuard(m_aMutex); if (rBHelper.bDisposed) throw DisposedException(OUString::createFromAscii("object is disposed."), static_cast < XClipboardManager * > (this)); if (rBHelper.bInDispose) return Sequence< OUString > (); Sequence< OUString > aRet(m_aClipboardMap.size()); ClipboardMap::iterator iter = m_aClipboardMap.begin(); ClipboardMap::iterator imax = m_aClipboardMap.end(); for (sal_Int32 n = 0; iter != imax; iter++) aRet[n++] = iter->first; return aRet; } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::dispose() throw(RuntimeException) { ClearableMutexGuard aGuard( rBHelper.rMutex ); if (!rBHelper.bDisposed && !rBHelper.bInDispose) { rBHelper.bInDispose = sal_True; aGuard.clear(); // give everyone a chance to save his clipboard instance EventObject aEvt(static_cast < XClipboardManager * > (this)); rBHelper.aLC.disposeAndClear( aEvt ); // removeClipboard is still allowed here, so make a copy of the // list (to ensure integrety) and clear the original. ClearableMutexGuard aGuard2( rBHelper.rMutex ); ClipboardMap aCopy(m_aClipboardMap); m_aClipboardMap.clear(); aGuard2.clear(); // dispose all clipboards still in list ClipboardMap::iterator iter = aCopy.begin(); ClipboardMap::iterator imax = aCopy.end(); for (; iter != imax; iter++) { Reference< XComponent > xComponent(iter->second, UNO_QUERY); if (xComponent.is()) { try { xComponent->removeEventListener(static_cast < XEventListener * > (this)); xComponent->dispose(); } catch(Exception e) { // exceptions can be safely ignored here. } } } rBHelper.bDisposed = sal_True; rBHelper.bInDispose = sal_False; } } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::disposing( const EventObject& event ) throw(RuntimeException) { Reference < XClipboard > xClipboard(event.Source, UNO_QUERY); if (xClipboard.is()) removeClipboard(xClipboard->getName()); } // ------------------------------------------------------------------------ Reference< XInterface > SAL_CALL ClipboardManager_createInstance( const Reference< XMultiServiceFactory > & /*xMultiServiceFactory*/) { return Reference < XInterface >( ( OWeakObject * ) new ClipboardManager()); } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager_getSupportedServiceNames() { Sequence < OUString > SupportedServicesNames( 1 ); SupportedServicesNames[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.ClipboardManager"); return SupportedServicesNames; } <commit_msg>INTEGRATION: CWS changefileheader (1.5.62); FILE MERGED 2008/04/01 12:28:28 thb 1.5.62.2: #i85898# Stripping all external header guards 2008/03/31 13:08:55 rt 1.5.62.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: clipboardmanager.cxx,v $ * $Revision: 1.6 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dtrans.hxx" #include <clipboardmanager.hxx> #include <com/sun/star/lang/DisposedException.hpp> using namespace com::sun::star::container; using namespace com::sun::star::datatransfer; using namespace com::sun::star::datatransfer::clipboard; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace cppu; using namespace osl; using namespace std; using ::dtrans::ClipboardManager; using ::rtl::OUString; // ------------------------------------------------------------------------ ClipboardManager::ClipboardManager(): WeakComponentImplHelper3< XClipboardManager, XEventListener, XServiceInfo > (m_aMutex), m_aDefaultName(OUString::createFromAscii("default")) { } // ------------------------------------------------------------------------ ClipboardManager::~ClipboardManager() { } // ------------------------------------------------------------------------ OUString SAL_CALL ClipboardManager::getImplementationName( ) throw(RuntimeException) { return OUString::createFromAscii(CLIPBOARDMANAGER_IMPLEMENTATION_NAME); } // ------------------------------------------------------------------------ sal_Bool SAL_CALL ClipboardManager::supportsService( const OUString& ServiceName ) throw(RuntimeException) { Sequence < OUString > SupportedServicesNames = ClipboardManager_getSupportedServiceNames(); for ( sal_Int32 n = 0, nmax = SupportedServicesNames.getLength(); n < nmax; n++ ) if (SupportedServicesNames[n].compareTo(ServiceName) == 0) return sal_True; return sal_False; } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager::getSupportedServiceNames( ) throw(RuntimeException) { return ClipboardManager_getSupportedServiceNames(); } // ------------------------------------------------------------------------ Reference< XClipboard > SAL_CALL ClipboardManager::getClipboard( const OUString& aName ) throw(NoSuchElementException, RuntimeException) { MutexGuard aGuard(m_aMutex); // object is disposed already if (rBHelper.bDisposed) throw DisposedException(OUString::createFromAscii("object is disposed."), static_cast < XClipboardManager * > (this)); ClipboardMap::iterator iter = m_aClipboardMap.find(aName.getLength() ? aName : m_aDefaultName); if (iter != m_aClipboardMap.end()) return iter->second; throw NoSuchElementException(aName, static_cast < XClipboardManager * > (this)); } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::addClipboard( const Reference< XClipboard >& xClipboard ) throw(IllegalArgumentException, ElementExistException, RuntimeException) { OSL_ASSERT(xClipboard.is()); // check parameter if (!xClipboard.is()) throw IllegalArgumentException(OUString::createFromAscii("empty reference"), static_cast < XClipboardManager * > (this), 1); // the name "default" is reserved for internal use OUString aName = xClipboard->getName(); if (m_aDefaultName.compareTo(aName) == 0) throw IllegalArgumentException(OUString::createFromAscii("name reserved"), static_cast < XClipboardManager * > (this), 1); // try to add new clipboard to the list ClearableMutexGuard aGuard(m_aMutex); if (!rBHelper.bDisposed && !rBHelper.bInDispose) { pair< const OUString, Reference< XClipboard > > value ( aName.getLength() ? aName : m_aDefaultName, xClipboard ); pair< ClipboardMap::iterator, bool > p = m_aClipboardMap.insert(value); aGuard.clear(); // insert failed, element must exist already if (!p.second) throw ElementExistException(aName, static_cast < XClipboardManager * > (this)); // request disposing notifications Reference< XComponent > xComponent(xClipboard, UNO_QUERY); if (xComponent.is()) xComponent->addEventListener(static_cast < XEventListener * > (this)); } } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::removeClipboard( const OUString& aName ) throw(RuntimeException) { MutexGuard aGuard(m_aMutex); if (!rBHelper.bDisposed) m_aClipboardMap.erase(aName.getLength() ? aName : m_aDefaultName ); } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager::listClipboardNames() throw(RuntimeException) { MutexGuard aGuard(m_aMutex); if (rBHelper.bDisposed) throw DisposedException(OUString::createFromAscii("object is disposed."), static_cast < XClipboardManager * > (this)); if (rBHelper.bInDispose) return Sequence< OUString > (); Sequence< OUString > aRet(m_aClipboardMap.size()); ClipboardMap::iterator iter = m_aClipboardMap.begin(); ClipboardMap::iterator imax = m_aClipboardMap.end(); for (sal_Int32 n = 0; iter != imax; iter++) aRet[n++] = iter->first; return aRet; } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::dispose() throw(RuntimeException) { ClearableMutexGuard aGuard( rBHelper.rMutex ); if (!rBHelper.bDisposed && !rBHelper.bInDispose) { rBHelper.bInDispose = sal_True; aGuard.clear(); // give everyone a chance to save his clipboard instance EventObject aEvt(static_cast < XClipboardManager * > (this)); rBHelper.aLC.disposeAndClear( aEvt ); // removeClipboard is still allowed here, so make a copy of the // list (to ensure integrety) and clear the original. ClearableMutexGuard aGuard2( rBHelper.rMutex ); ClipboardMap aCopy(m_aClipboardMap); m_aClipboardMap.clear(); aGuard2.clear(); // dispose all clipboards still in list ClipboardMap::iterator iter = aCopy.begin(); ClipboardMap::iterator imax = aCopy.end(); for (; iter != imax; iter++) { Reference< XComponent > xComponent(iter->second, UNO_QUERY); if (xComponent.is()) { try { xComponent->removeEventListener(static_cast < XEventListener * > (this)); xComponent->dispose(); } catch(Exception e) { // exceptions can be safely ignored here. } } } rBHelper.bDisposed = sal_True; rBHelper.bInDispose = sal_False; } } // ------------------------------------------------------------------------ void SAL_CALL ClipboardManager::disposing( const EventObject& event ) throw(RuntimeException) { Reference < XClipboard > xClipboard(event.Source, UNO_QUERY); if (xClipboard.is()) removeClipboard(xClipboard->getName()); } // ------------------------------------------------------------------------ Reference< XInterface > SAL_CALL ClipboardManager_createInstance( const Reference< XMultiServiceFactory > & /*xMultiServiceFactory*/) { return Reference < XInterface >( ( OWeakObject * ) new ClipboardManager()); } // ------------------------------------------------------------------------ Sequence< OUString > SAL_CALL ClipboardManager_getSupportedServiceNames() { Sequence < OUString > SupportedServicesNames( 1 ); SupportedServicesNames[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.ClipboardManager"); return SupportedServicesNames; } <|endoftext|>
<commit_before>#include "mccdisplayfilter.h" #include <QRect> #include <QColor> #include <QBrush> #include <iostream> #include <QFont> using namespace std; MCCDisplayFilter::MCCDisplayFilter(QObject *parent) : QObject(parent) { setName("MCC Display Filter"); ///read file } bool MCCDisplayFilter::init(FilterContext *pcContext) { QString strHightlightFilename = "mccVal.txt"; QString strOneLine; QRegExp cMatchTarget; QFile cFile; QTextStream cInputStream; cFile.setFileName(strHightlightFilename); if( !(cFile.open(QIODevice::ReadOnly)) ) return false; cInputStream.setDevice(&cFile); QTextStream *pcInputStream = &cInputStream; cMatchTarget.setPattern("<([0-9]+),([0-9]+)>([0-9]+)"); while( !pcInputStream->atEnd() ) { strOneLine = pcInputStream->readLine(); if( cMatchTarget.indexIn(strOneLine) != -1 ) { /// poc and lcu addr int iPoc = cMatchTarget.cap(1).toInt(); int iAddr = cMatchTarget.cap(2).toInt(); int mcc = cMatchTarget.cap(3).toInt(); cout << mcc << endl; m_ccLCU[iPoc][iAddr] = mcc; } } cFile.close(); //AnalyzerMsgSender::getInstance()->msgOut(QString("%1 LCU(s) Skipped").arg(m_cTargetLCU.size())); return true; } bool MCCDisplayFilter::drawCTU (QPainter* pcPainter, FilterContext* pcContext, ComSequence* pcSequence, int iPoc, int iAddr, int iCTUX, int iCTUY, int iCTUSize) { int mcc = m_ccLCU[iPoc][iAddr]; cout << iAddr << " " << iPoc << " " << mcc << endl; pcPainter->setBrush(Qt::NoBrush); pcPainter->setPen(QColor(255,0,0)); QRect cCTURect(iCTUX, iCTUY, iCTUSize, iCTUSize); QFont cFont = pcPainter->font(); cFont.setPointSize(12); pcPainter->setFont(cFont); pcPainter->drawText(cCTURect,Qt::AlignCenter, QString("%1").arg(mcc)); return true; } <commit_msg>mcc filter<commit_after>#include "mccdisplayfilter.h" #include <QRect> #include <QColor> #include <QBrush> #include <iostream> #include <QFont> using namespace std; MCCDisplayFilter::MCCDisplayFilter(QObject *parent) : QObject(parent) { setName("MCC Display Filter"); ///read file } bool MCCDisplayFilter::init(FilterContext *pcContext) { QString strHightlightFilename = "mccVal.txt"; QString strOneLine; QRegExp cMatchTarget; QFile cFile; QTextStream cInputStream; cFile.setFileName(strHightlightFilename); if( !(cFile.open(QIODevice::ReadOnly)) ) return false; cInputStream.setDevice(&cFile); QTextStream *pcInputStream = &cInputStream; cMatchTarget.setPattern("<([0-9]+),([0-9]+)>([0-9]+)"); while( !pcInputStream->atEnd() ) { strOneLine = pcInputStream->readLine(); if( cMatchTarget.indexIn(strOneLine) != -1 ) { /// poc and lcu addr int iPoc = cMatchTarget.cap(1).toInt(); int iAddr = cMatchTarget.cap(2).toInt(); int mcc = cMatchTarget.cap(3).toInt(); m_ccLCU[iPoc][iAddr] = mcc; } } cFile.close(); //AnalyzerMsgSender::getInstance()->msgOut(QString("%1 LCU(s) Skipped").arg(m_cTargetLCU.size())); return true; } bool MCCDisplayFilter::drawCTU (QPainter* pcPainter, FilterContext* pcContext, ComSequence* pcSequence, int iPoc, int iAddr, int iCTUX, int iCTUY, int iCTUSize) { int mcc = m_ccLCU[iPoc][iAddr]; //cout << iAddr << " " << iPoc << " " << mcc << endl; pcPainter->setBrush(Qt::NoBrush); pcPainter->setPen(QColor(255,0,0)); QRect cCTURect(iCTUX, iCTUY, iCTUSize, iCTUSize); QFont cFont = pcPainter->font(); pcPainter->setPen(QColor(0,0,255)); cFont.setPointSize(18); pcPainter->setFont(cFont); pcPainter->drawText(cCTURect,Qt::AlignCenter, QString("%1").arg(mcc)); //if(mcc>6) //{ int iAlpha = 255-mcc*15; iAlpha=((iAlpha<0)?(0):(iAlpha)); iAlpha=((iAlpha>175)?(175):(iAlpha)); pcPainter->setPen(Qt::NoPen); pcPainter->setBrush(QColor(0,0,0,iAlpha)); pcPainter->drawRect(cCTURect); //} // else if(mcc == 0) // { // pcPainter->setPen(QColor(0,255,0)); // pcPainter->drawRect(cCTURect); // } return true; } <|endoftext|>
<commit_before>#include "arithmetics.hpp" #include "gtest/gtest.h" TEST(AddTest, PerformsAdditionOnTwoIntegers) { EXPECT_EQ(2, arithmetics::add(1, 1)); EXPECT_EQ(2, arithmetics::add_buggy(1, 1)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>Split tests into 2 distict tests<commit_after>#include "arithmetics.hpp" #include "gtest/gtest.h" TEST(TestAdd, PerformsAdditionOnTwoIntegers) { EXPECT_EQ(2, arithmetics::add(1, 1)); } TEST(TestAdd, PerformsAdditionOnTwoIntegers_2) { EXPECT_EQ(2, arithmetics::add_buggy(1, 1)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "World.h" #include "qtopenc2e.h" #include <QtGui> #include "openc2eview.h" #include "Engine.h" #include "OpenALBackend.h" #include "MetaRoom.h" #include "AgentInjector.h" #include "BrainViewer.h" #include "CreatureGrapher.h" #include "Creature.h" #include "SkeletalCreature.h" #include "PointerAgent.h" // Constructor which creates the main window. QtOpenc2e::QtOpenc2e(boost::shared_ptr<QtBackend> backend) { viewport = new openc2eView(this, backend); setCentralWidget(viewport); connect(this, SIGNAL(creatureChanged()), this, SLOT(onCreatureChange())); // idle timer // TODO: should prbly have an every-X-seconds timer or a background thread to do this QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(tick())); timer->start(); (void)statusBar(); std::string titlebar = engine.getGameName() + " - openc2e (development build)"; setWindowTitle(titlebar.c_str()); resize(800, 600); /* File menu */ exitAct = new QAction(tr("&Exit"), this); exitAct->setStatusTip(tr("Exit openc2e")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(exitAct); /* View menu */ viewMenu = menuBar()->addMenu(tr("&View")); toggleScrollbarsAct = new QAction(tr("Show &Scrollbars"), this); toggleScrollbarsAct->setCheckable(true); connect(toggleScrollbarsAct, SIGNAL(triggered()), this, SLOT(toggleShowScrollbars())); viewMenu->addAction(toggleScrollbarsAct); // only enable scrollbars for c1/c2, by default toggleScrollbarsAct->setChecked(engine.version < 3); toggleShowScrollbars(); /* Control menu */ controlMenu = menuBar()->addMenu(tr("C&ontrol")); connect(controlMenu, SIGNAL(aboutToShow()), this, SLOT(updateMenus())); pauseAct = new QAction(tr("&Pause"), this); connect(pauseAct, SIGNAL(triggered()), this, SLOT(togglePause())); controlMenu->addAction(pauseAct); muteAct = new QAction(tr("&Mute"), this); muteAct->setCheckable(true); connect(muteAct, SIGNAL(triggered()), this, SLOT(toggleMute())); controlMenu->addAction(muteAct); controlMenu->addSeparator(); fastSpeedAct = new QAction(tr("&Fast speed"), this); fastSpeedAct->setCheckable(true); connect(fastSpeedAct, SIGNAL(triggered()), this, SLOT(toggleFastSpeed())); controlMenu->addAction(fastSpeedAct); displayUpdatesAct = new QAction(tr("Slow &display updates"), this); displayUpdatesAct->setCheckable(true); displayUpdatesAct->setEnabled(false); connect(displayUpdatesAct, SIGNAL(triggered()), this, SLOT(toggleDisplayUpdates())); controlMenu->addAction(displayUpdatesAct); autokillAct = new QAction(tr("&Autokill"), this); autokillAct->setCheckable(true); autokillAct->setChecked(world.autokill); connect(autokillAct, SIGNAL(triggered()), this, SLOT(toggleAutokill())); controlMenu->addAction(autokillAct); /* Debug menu */ debugMenu = menuBar()->addMenu(tr("&Debug")); connect(debugMenu, SIGNAL(aboutToShow()), this, SLOT(updateMenus())); showMapAct = new QAction(tr("Show &Map"), this); showMapAct->setCheckable(true); connect(showMapAct, SIGNAL(triggered()), this, SLOT(toggleShowMap())); debugMenu->addAction(showMapAct); newNornAct = new QAction(tr("Create a new (debug) &Norn"), this); if (engine.version > 2) newNornAct->setEnabled(false); // TODO connect(newNornAct, SIGNAL(triggered()), this, SLOT(newNorn())); debugMenu->addAction(newNornAct); /* Tools menu */ toolsMenu = menuBar()->addMenu(tr("&Tools")); agentInjectorAct = new QAction(tr("&Agent Injector"), this); connect(agentInjectorAct, SIGNAL(triggered()), this, SLOT(showAgentInjector())); toolsMenu->addAction(agentInjectorAct); brainViewerAct = new QAction(tr("&Brain Viewer"), this); connect(brainViewerAct, SIGNAL(triggered()), this, SLOT(showBrainViewer())); toolsMenu->addAction(brainViewerAct); agentInjector = new AgentInjector(); brainViewer = new BrainViewer(); connect(this, SIGNAL(ticked()), brainViewer, SLOT(onTick())); creatureGrapher = new CreatureGrapher(this); connect(this, SIGNAL(ticked()), creatureGrapher, SLOT(onCreatureTick())); // TODO creatureGrapherDock = new QDockWidget(this); creatureGrapherDock->hide(); creatureGrapherDock->setWidget(creatureGrapher); creatureGrapherDock->setFloating(true); creatureGrapherDock->resize(QSize(300, 300)); creatureGrapherDock->setWindowTitle(tr("Creature Grapher")); toolsMenu->addAction(creatureGrapherDock->toggleViewAction()); /* Creatures menu */ creaturesMenu = menuBar()->addMenu(tr("&Creatures")); connect(creaturesMenu, SIGNAL(aboutToShow()), this, SLOT(updateCreaturesMenu())); /* Help menu */ menuBar()->addSeparator(); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Find out about openc2e")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } QtOpenc2e::~QtOpenc2e() { } monikerData &monikerDataFor(AgentRef a) { shared_ptr<class genomeFile> g = a->getSlot(0); assert(g); std::string moniker = world.history.findMoniker(g); return world.history.getMoniker(moniker); } std::string creatureNameFor(AgentRef a) { return monikerDataFor(a).name; } void QtOpenc2e::selectCreature() { QObject *src = sender(); QAction *srcaction = dynamic_cast<QAction *>(src); assert(srcaction); Agent *a = (Agent *)srcaction->data().value<void *>(); for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) { boost::shared_ptr<Agent> p = *i; if (!p) continue; // grr, but needed if (a == p.get()) { world.selectCreature(p); return; } } // looks like the creature disappeared from under us.. } void QtOpenc2e::updateCreaturesMenu() { creaturesMenu->clear(); for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) { boost::shared_ptr<Agent> p = *i; if (!p) continue; // grr, but needed CreatureAgent *a = dynamic_cast<CreatureAgent *>(p.get()); if (a) { // TODO: add breed? std::string creaturename = creatureNameFor(a); if (creaturename.empty()) creaturename = "<Unnamed>"; creaturename += std::string(" (") + (a->getCreature()->isFemale() ? "Female" : "Male") + ")"; // create a new action with menu as parent, so it'll be destroyed on clear() QAction *creatureSelectAct = new QAction(creaturename.c_str(), creaturesMenu); creatureSelectAct->setData(QVariant::fromValue((void *)a)); creatureSelectAct->setCheckable(true); if (world.selectedcreature == p) creatureSelectAct->setChecked(true); connect(creatureSelectAct, SIGNAL(triggered()), this, SLOT(selectCreature())); if (monikerDataFor(a).getStatus() != borncreature) creatureSelectAct->setDisabled(true); creaturesMenu->addAction(creatureSelectAct); } } if (creaturesMenu->isEmpty()) { QAction *dummyAct = new QAction("<none available>", creaturesMenu); dummyAct->setEnabled(false); creaturesMenu->addAction(dummyAct); } } void QtOpenc2e::onCreatureChange() { std::string titlebar = engine.getGameName() + " - openc2e (development build)"; if (world.selectedcreature) { oldcreaturename = creatureNameFor(world.selectedcreature); if (oldcreaturename.empty()) titlebar += " - <Unnamed>"; else titlebar += " - " + oldcreaturename; } setWindowTitle(titlebar.c_str()); } void QtOpenc2e::tick() { // set refreshdisplay occasionally, for updates when dorendering is false if (world.worldtickcount % world.ticktime == 0) // every 10 in-world seconds, with default times engine.refreshdisplay = true; bool didtick = engine.tick(); int y = world.camera.getY(); int x = world.camera.getX(); viewport->tick(); viewport->horizontalScrollBar()->setValue(x - world.camera.getMetaRoom()->x()); viewport->verticalScrollBar()->setValue(y - world.camera.getMetaRoom()->y()); if (engine.done) close(); if (didtick) { if (world.selectedcreature != selectedcreature) { selectedcreature = world.selectedcreature; emit creatureChanged(); } else if (world.selectedcreature) { // pick up name changes if (creatureNameFor(world.selectedcreature) != oldcreaturename) onCreatureChange(); } // TODO: emit creatureTicked() if necessary emit ticked(); } if (viewport->needsRender()) { viewport->viewport()->repaint(); } } // action handlers void QtOpenc2e::updateMenus() { showMapAct->setChecked(world.showrooms); fastSpeedAct->setChecked(engine.fastticks); displayUpdatesAct->setChecked(!engine.dorendering); autokillAct->setChecked(world.autokill); muteAct->setChecked(engine.audio->isMuted()); if (world.paused) pauseAct->setText("&Play"); else pauseAct->setText("&Pause"); } void QtOpenc2e::about() { QMessageBox::about(this, tr("openc2e"), tr("An open-source game engine to run the Creatures series of games.")); } void QtOpenc2e::showAgentInjector() { agentInjector->show(); agentInjector->activateWindow(); } void QtOpenc2e::showBrainViewer() { brainViewer->show(); brainViewer->activateWindow(); } void QtOpenc2e::toggleShowMap() { world.showrooms = !world.showrooms; } void QtOpenc2e::toggleShowScrollbars() { if (toggleScrollbarsAct->isChecked()) { viewport->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); viewport->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); } else { viewport->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); viewport->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } } void QtOpenc2e::toggleFastSpeed() { engine.fastticks = !engine.fastticks; displayUpdatesAct->setEnabled(engine.fastticks); if (!engine.fastticks) { engine.dorendering = true; displayUpdatesAct->setChecked(false); } } void QtOpenc2e::toggleDisplayUpdates() { engine.dorendering = !engine.dorendering; } void QtOpenc2e::toggleAutokill() { world.autokill = !world.autokill; } void QtOpenc2e::togglePause() { world.paused = !world.paused; } void QtOpenc2e::toggleMute() { engine.audio->setMute(!engine.audio->isMuted()); } #undef slots void QtOpenc2e::newNorn() { if (engine.version > 2) return; // TODO: fixme std::string genomefile = "test"; shared_ptr<genomeFile> genome; try { genome = world.loadGenome(genomefile); } catch (creaturesException &e) { QMessageBox::warning(this, tr("Couldn't load genome file:"), e.prettyPrint().c_str()); return; } if (!genome) { // return; } SkeletalCreature *a = new SkeletalCreature(4); int sex = 1 + (int) (2.0 * (rand() / (RAND_MAX + 1.0))); oldCreature *c; try { if (engine.version == 1) c = new c1Creature(genome, (sex == 2), 0, a); else c = new c2Creature(genome, (sex == 2), 0, a); } catch (creaturesException &e) { delete a; QMessageBox::warning(this, tr("Couldn't create creature:"), e.prettyPrint().c_str()); return; } a->setCreature(c); a->finishInit(); // if you make this work for c2e, you should probably set sane attributes here? a->slots[0] = genome; world.newMoniker(genome, genomefile, a); world.history.getMoniker(world.history.findMoniker(genome)).moveToCreature(a); // TODO: set it dreaming c->born(); world.hand()->addCarried(a); } Creature *QtOpenc2e::getSelectedCreature() { if (world.selectedcreature) { CreatureAgent *a = dynamic_cast<CreatureAgent *>(world.selectedcreature.get()); if (a) { return a->getCreature(); } } return 0; } <commit_msg>don't include OpenALBackend.h in qtgui/qtopenc2e.cpp<commit_after>/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "World.h" #include "qtopenc2e.h" #include <QtGui> #include "openc2eview.h" #include "Engine.h" #include "AudioBackend.h" #include "MetaRoom.h" #include "AgentInjector.h" #include "BrainViewer.h" #include "CreatureGrapher.h" #include "Creature.h" #include "SkeletalCreature.h" #include "PointerAgent.h" // Constructor which creates the main window. QtOpenc2e::QtOpenc2e(boost::shared_ptr<QtBackend> backend) { viewport = new openc2eView(this, backend); setCentralWidget(viewport); connect(this, SIGNAL(creatureChanged()), this, SLOT(onCreatureChange())); // idle timer // TODO: should prbly have an every-X-seconds timer or a background thread to do this QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(tick())); timer->start(); (void)statusBar(); std::string titlebar = engine.getGameName() + " - openc2e (development build)"; setWindowTitle(titlebar.c_str()); resize(800, 600); /* File menu */ exitAct = new QAction(tr("&Exit"), this); exitAct->setStatusTip(tr("Exit openc2e")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(exitAct); /* View menu */ viewMenu = menuBar()->addMenu(tr("&View")); toggleScrollbarsAct = new QAction(tr("Show &Scrollbars"), this); toggleScrollbarsAct->setCheckable(true); connect(toggleScrollbarsAct, SIGNAL(triggered()), this, SLOT(toggleShowScrollbars())); viewMenu->addAction(toggleScrollbarsAct); // only enable scrollbars for c1/c2, by default toggleScrollbarsAct->setChecked(engine.version < 3); toggleShowScrollbars(); /* Control menu */ controlMenu = menuBar()->addMenu(tr("C&ontrol")); connect(controlMenu, SIGNAL(aboutToShow()), this, SLOT(updateMenus())); pauseAct = new QAction(tr("&Pause"), this); connect(pauseAct, SIGNAL(triggered()), this, SLOT(togglePause())); controlMenu->addAction(pauseAct); muteAct = new QAction(tr("&Mute"), this); muteAct->setCheckable(true); connect(muteAct, SIGNAL(triggered()), this, SLOT(toggleMute())); controlMenu->addAction(muteAct); controlMenu->addSeparator(); fastSpeedAct = new QAction(tr("&Fast speed"), this); fastSpeedAct->setCheckable(true); connect(fastSpeedAct, SIGNAL(triggered()), this, SLOT(toggleFastSpeed())); controlMenu->addAction(fastSpeedAct); displayUpdatesAct = new QAction(tr("Slow &display updates"), this); displayUpdatesAct->setCheckable(true); displayUpdatesAct->setEnabled(false); connect(displayUpdatesAct, SIGNAL(triggered()), this, SLOT(toggleDisplayUpdates())); controlMenu->addAction(displayUpdatesAct); autokillAct = new QAction(tr("&Autokill"), this); autokillAct->setCheckable(true); autokillAct->setChecked(world.autokill); connect(autokillAct, SIGNAL(triggered()), this, SLOT(toggleAutokill())); controlMenu->addAction(autokillAct); /* Debug menu */ debugMenu = menuBar()->addMenu(tr("&Debug")); connect(debugMenu, SIGNAL(aboutToShow()), this, SLOT(updateMenus())); showMapAct = new QAction(tr("Show &Map"), this); showMapAct->setCheckable(true); connect(showMapAct, SIGNAL(triggered()), this, SLOT(toggleShowMap())); debugMenu->addAction(showMapAct); newNornAct = new QAction(tr("Create a new (debug) &Norn"), this); if (engine.version > 2) newNornAct->setEnabled(false); // TODO connect(newNornAct, SIGNAL(triggered()), this, SLOT(newNorn())); debugMenu->addAction(newNornAct); /* Tools menu */ toolsMenu = menuBar()->addMenu(tr("&Tools")); agentInjectorAct = new QAction(tr("&Agent Injector"), this); connect(agentInjectorAct, SIGNAL(triggered()), this, SLOT(showAgentInjector())); toolsMenu->addAction(agentInjectorAct); brainViewerAct = new QAction(tr("&Brain Viewer"), this); connect(brainViewerAct, SIGNAL(triggered()), this, SLOT(showBrainViewer())); toolsMenu->addAction(brainViewerAct); agentInjector = new AgentInjector(); brainViewer = new BrainViewer(); connect(this, SIGNAL(ticked()), brainViewer, SLOT(onTick())); creatureGrapher = new CreatureGrapher(this); connect(this, SIGNAL(ticked()), creatureGrapher, SLOT(onCreatureTick())); // TODO creatureGrapherDock = new QDockWidget(this); creatureGrapherDock->hide(); creatureGrapherDock->setWidget(creatureGrapher); creatureGrapherDock->setFloating(true); creatureGrapherDock->resize(QSize(300, 300)); creatureGrapherDock->setWindowTitle(tr("Creature Grapher")); toolsMenu->addAction(creatureGrapherDock->toggleViewAction()); /* Creatures menu */ creaturesMenu = menuBar()->addMenu(tr("&Creatures")); connect(creaturesMenu, SIGNAL(aboutToShow()), this, SLOT(updateCreaturesMenu())); /* Help menu */ menuBar()->addSeparator(); aboutAct = new QAction(tr("&About"), this); aboutAct->setStatusTip(tr("Find out about openc2e")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } QtOpenc2e::~QtOpenc2e() { } monikerData &monikerDataFor(AgentRef a) { shared_ptr<class genomeFile> g = a->getSlot(0); assert(g); std::string moniker = world.history.findMoniker(g); return world.history.getMoniker(moniker); } std::string creatureNameFor(AgentRef a) { return monikerDataFor(a).name; } void QtOpenc2e::selectCreature() { QObject *src = sender(); QAction *srcaction = dynamic_cast<QAction *>(src); assert(srcaction); Agent *a = (Agent *)srcaction->data().value<void *>(); for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) { boost::shared_ptr<Agent> p = *i; if (!p) continue; // grr, but needed if (a == p.get()) { world.selectCreature(p); return; } } // looks like the creature disappeared from under us.. } void QtOpenc2e::updateCreaturesMenu() { creaturesMenu->clear(); for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) { boost::shared_ptr<Agent> p = *i; if (!p) continue; // grr, but needed CreatureAgent *a = dynamic_cast<CreatureAgent *>(p.get()); if (a) { // TODO: add breed? std::string creaturename = creatureNameFor(a); if (creaturename.empty()) creaturename = "<Unnamed>"; creaturename += std::string(" (") + (a->getCreature()->isFemale() ? "Female" : "Male") + ")"; // create a new action with menu as parent, so it'll be destroyed on clear() QAction *creatureSelectAct = new QAction(creaturename.c_str(), creaturesMenu); creatureSelectAct->setData(QVariant::fromValue((void *)a)); creatureSelectAct->setCheckable(true); if (world.selectedcreature == p) creatureSelectAct->setChecked(true); connect(creatureSelectAct, SIGNAL(triggered()), this, SLOT(selectCreature())); if (monikerDataFor(a).getStatus() != borncreature) creatureSelectAct->setDisabled(true); creaturesMenu->addAction(creatureSelectAct); } } if (creaturesMenu->isEmpty()) { QAction *dummyAct = new QAction("<none available>", creaturesMenu); dummyAct->setEnabled(false); creaturesMenu->addAction(dummyAct); } } void QtOpenc2e::onCreatureChange() { std::string titlebar = engine.getGameName() + " - openc2e (development build)"; if (world.selectedcreature) { oldcreaturename = creatureNameFor(world.selectedcreature); if (oldcreaturename.empty()) titlebar += " - <Unnamed>"; else titlebar += " - " + oldcreaturename; } setWindowTitle(titlebar.c_str()); } void QtOpenc2e::tick() { // set refreshdisplay occasionally, for updates when dorendering is false if (world.worldtickcount % world.ticktime == 0) // every 10 in-world seconds, with default times engine.refreshdisplay = true; bool didtick = engine.tick(); int y = world.camera.getY(); int x = world.camera.getX(); viewport->tick(); viewport->horizontalScrollBar()->setValue(x - world.camera.getMetaRoom()->x()); viewport->verticalScrollBar()->setValue(y - world.camera.getMetaRoom()->y()); if (engine.done) close(); if (didtick) { if (world.selectedcreature != selectedcreature) { selectedcreature = world.selectedcreature; emit creatureChanged(); } else if (world.selectedcreature) { // pick up name changes if (creatureNameFor(world.selectedcreature) != oldcreaturename) onCreatureChange(); } // TODO: emit creatureTicked() if necessary emit ticked(); } if (viewport->needsRender()) { viewport->viewport()->repaint(); } } // action handlers void QtOpenc2e::updateMenus() { showMapAct->setChecked(world.showrooms); fastSpeedAct->setChecked(engine.fastticks); displayUpdatesAct->setChecked(!engine.dorendering); autokillAct->setChecked(world.autokill); muteAct->setChecked(engine.audio->isMuted()); if (world.paused) pauseAct->setText("&Play"); else pauseAct->setText("&Pause"); } void QtOpenc2e::about() { QMessageBox::about(this, tr("openc2e"), tr("An open-source game engine to run the Creatures series of games.")); } void QtOpenc2e::showAgentInjector() { agentInjector->show(); agentInjector->activateWindow(); } void QtOpenc2e::showBrainViewer() { brainViewer->show(); brainViewer->activateWindow(); } void QtOpenc2e::toggleShowMap() { world.showrooms = !world.showrooms; } void QtOpenc2e::toggleShowScrollbars() { if (toggleScrollbarsAct->isChecked()) { viewport->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); viewport->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); } else { viewport->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); viewport->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } } void QtOpenc2e::toggleFastSpeed() { engine.fastticks = !engine.fastticks; displayUpdatesAct->setEnabled(engine.fastticks); if (!engine.fastticks) { engine.dorendering = true; displayUpdatesAct->setChecked(false); } } void QtOpenc2e::toggleDisplayUpdates() { engine.dorendering = !engine.dorendering; } void QtOpenc2e::toggleAutokill() { world.autokill = !world.autokill; } void QtOpenc2e::togglePause() { world.paused = !world.paused; } void QtOpenc2e::toggleMute() { engine.audio->setMute(!engine.audio->isMuted()); } #undef slots void QtOpenc2e::newNorn() { if (engine.version > 2) return; // TODO: fixme std::string genomefile = "test"; shared_ptr<genomeFile> genome; try { genome = world.loadGenome(genomefile); } catch (creaturesException &e) { QMessageBox::warning(this, tr("Couldn't load genome file:"), e.prettyPrint().c_str()); return; } if (!genome) { // return; } SkeletalCreature *a = new SkeletalCreature(4); int sex = 1 + (int) (2.0 * (rand() / (RAND_MAX + 1.0))); oldCreature *c; try { if (engine.version == 1) c = new c1Creature(genome, (sex == 2), 0, a); else c = new c2Creature(genome, (sex == 2), 0, a); } catch (creaturesException &e) { delete a; QMessageBox::warning(this, tr("Couldn't create creature:"), e.prettyPrint().c_str()); return; } a->setCreature(c); a->finishInit(); // if you make this work for c2e, you should probably set sane attributes here? a->slots[0] = genome; world.newMoniker(genome, genomefile, a); world.history.getMoniker(world.history.findMoniker(genome)).moveToCreature(a); // TODO: set it dreaming c->born(); world.hand()->addCarried(a); } Creature *QtOpenc2e::getSelectedCreature() { if (world.selectedcreature) { CreatureAgent *a = dynamic_cast<CreatureAgent *>(world.selectedcreature.get()); if (a) { return a->getCreature(); } } return 0; } <|endoftext|>
<commit_before>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = num_feat(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat()); beta().setZero(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); // residual (Uhat is later overwritten): //uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); // BBt = beta * beta' //uses: beta // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_feat()); } // uses: U, F // writes: Ft_y // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::compute_Ft_y(Eigen::MatrixXd& Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ D x F ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat Ft_y += std::sqrt(beta_precision) * HyperU2; } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream& MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto BB = beta * beta.transpose(); double nux = nu + beta.rows() * beta.cols(); double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu); return rgamma(gamma_post.first, gamma_post.second); } <commit_msg>Reorganized comments in MacauPrior<commit_after>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = num_feat(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat()); beta().setZero(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); //uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; //uses: beta // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_feat()); } // uses: U, F // writes: Ft_y // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::compute_Ft_y(Eigen::MatrixXd& Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ num_latent x num_feat ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat Ft_y += std::sqrt(beta_precision) * HyperU2; } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream& MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto BB = beta * beta.transpose(); double nux = nu + beta.rows() * beta.cols(); double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu) { auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu); return rgamma(gamma_post.first, gamma_post.second); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "sparse.h" template<typename Scalar> void initSPD(double density, Matrix<Scalar,Dynamic,Dynamic>& refMat, SparseMatrix<Scalar>& sparseMat) { Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols()); initSparse(density,refMat,sparseMat); refMat = refMat * refMat.adjoint(); for (int k=0; k<2; ++k) { initSparse(density,aux,sparseMat,ForceNonZeroDiag); refMat += aux * aux.adjoint(); } sparseMat.setZero(); for (int j=0 ; j<sparseMat.cols(); ++j) for (int i=j ; i<sparseMat.rows(); ++i) if (refMat(i,j)!=Scalar(0)) sparseMat.insert(i,j) = refMat(i,j); sparseMat.finalize(); } template<typename Scalar> void sparse_solvers(int rows, int cols) { double density = std::max(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; // Scalar eps = 1e-6; DenseVector vec1 = DenseVector::Random(rows); std::vector<Vector2i> zeroCoords; std::vector<Vector2i> nonzeroCoords; // test triangular solver { DenseVector vec2 = vec1, vec3 = vec1; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols); // lower - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2), m2.template triangular<LowerTriangular>().solve(vec3)); // upper - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<UpperTriangular>().solveTriangular(vec2), m2.template triangular<UpperTriangular>().solve(vec3)); // TODO test row major SparseMatrix<Scalar> matB(rows, rows); DenseMatrix refMatB = DenseMatrix::Zero(rows, rows); // lower - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template marked<LowerTriangular>().solveTriangularInPlace(refMatB); m2.template triangular<LowerTriangular>().solveInPlace(matB); VERIFY_IS_APPROX(matB.toDense(), refMatB); // upper - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template marked<UpperTriangular>().solveTriangularInPlace(refMatB); m2.template triangular<UpperTriangular>().solveInPlace(matB); VERIFY_IS_APPROX(matB, refMatB); // test deprecated API initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2), m2.template marked<LowerTriangular>().solveTriangular(vec3)); } // test LLT { // TODO fix the issue with complex (see SparseLLT::solveInPlace) SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); initSPD(density, refMat2, m2); refMat2.llt().solve(b, &refX); typedef SparseMatrix<Scalar,LowerTriangular|SelfAdjoint> SparseSelfAdjointMatrix; if (!NumTraits<Scalar>::IsComplex) { x = b; SparseLLT<SparseSelfAdjointMatrix> (m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: default"); } #ifdef EIGEN_CHOLMOD_SUPPORT x = b; SparseLLT<SparseSelfAdjointMatrix,Cholmod>(m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod"); #endif if (!NumTraits<Scalar>::IsComplex) { #ifdef EIGEN_TAUCS_SUPPORT x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,IncompleteFactorization).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (IncompleteFactorization)"); x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalMultifrontal).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalMultifrontal)"); x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalLeftLooking).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalLeftLooking)"); #endif } } // test LDLT if (!NumTraits<Scalar>::IsComplex) { // TODO fix the issue with complex (see SparseLDLT::solveInPlace) SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); //initSPD(density, refMat2, m2); initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, 0, 0); refMat2 += refMat2.adjoint(); refMat2.diagonal() *= 0.5; refMat2.ldlt().solve(b, &refX); typedef SparseMatrix<Scalar,UpperTriangular|SelfAdjoint> SparseSelfAdjointMatrix; x = b; SparseLDLT<SparseSelfAdjointMatrix> ldlt(m2); if (ldlt.succeeded()) ldlt.solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LDLT: default"); } // test LU { static int count = 0; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag, &zeroCoords, &nonzeroCoords); LU<DenseMatrix> refLu(refMat2); refLu.solve(b, &refX); #if defined(EIGEN_SUPERLU_SUPPORT) || defined(EIGEN_UMFPACK_SUPPORT) Scalar refDet = refLu.determinant(); #endif x.setZero(); // // SparseLU<SparseMatrix<Scalar> > (m2).solve(b,&x); // // VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: default"); #ifdef EIGEN_SUPERLU_SUPPORT { x.setZero(); SparseLU<SparseMatrix<Scalar>,SuperLU> slu(m2); if (slu.succeeded()) { if (slu.solve(b,&x)) { VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: SuperLU"); } // std::cerr << refDet << " == " << slu.determinant() << "\n"; if (slu.solve(b, &x, SvTranspose)) { VERIFY(b.isApprox(m2.transpose() * x, test_precision<Scalar>())); } if (slu.solve(b, &x, SvAdjoint)) { // VERIFY(b.isApprox(m2.adjoint() * x, test_precision<Scalar>())); } if (count==0) { VERIFY_IS_APPROX(refDet,slu.determinant()); // FIXME det is not very stable for complex } } } #endif #ifdef EIGEN_UMFPACK_SUPPORT { // check solve x.setZero(); SparseLU<SparseMatrix<Scalar>,UmfPack> slu(m2); if (slu.succeeded()) { if (slu.solve(b,&x)) { if (count==0) { VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: umfpack"); // FIXME solve is not very stable for complex } } VERIFY_IS_APPROX(refDet,slu.determinant()); // TODO check the extracted data //std::cerr << slu.matrixL() << "\n"; } } #endif count++; } } void test_sparse_solvers() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( sparse_solvers<double>(8, 8) ); CALL_SUBTEST( sparse_solvers<std::complex<double> >(16, 16) ); CALL_SUBTEST( sparse_solvers<double>(101, 101) ); } } <commit_msg>enable testing of complex numbers for taucs<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "sparse.h" template<typename Scalar> void initSPD(double density, Matrix<Scalar,Dynamic,Dynamic>& refMat, SparseMatrix<Scalar>& sparseMat) { Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols()); initSparse(density,refMat,sparseMat); refMat = refMat * refMat.adjoint(); for (int k=0; k<2; ++k) { initSparse(density,aux,sparseMat,ForceNonZeroDiag); refMat += aux * aux.adjoint(); } sparseMat.setZero(); for (int j=0 ; j<sparseMat.cols(); ++j) for (int i=j ; i<sparseMat.rows(); ++i) if (refMat(i,j)!=Scalar(0)) sparseMat.insert(i,j) = refMat(i,j); sparseMat.finalize(); } template<typename Scalar> void sparse_solvers(int rows, int cols) { double density = std::max(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; // Scalar eps = 1e-6; DenseVector vec1 = DenseVector::Random(rows); std::vector<Vector2i> zeroCoords; std::vector<Vector2i> nonzeroCoords; // test triangular solver { DenseVector vec2 = vec1, vec3 = vec1; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols); // lower - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2), m2.template triangular<LowerTriangular>().solve(vec3)); // upper - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<UpperTriangular>().solveTriangular(vec2), m2.template triangular<UpperTriangular>().solve(vec3)); // TODO test row major SparseMatrix<Scalar> matB(rows, rows); DenseMatrix refMatB = DenseMatrix::Zero(rows, rows); // lower - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template marked<LowerTriangular>().solveTriangularInPlace(refMatB); m2.template triangular<LowerTriangular>().solveInPlace(matB); VERIFY_IS_APPROX(matB.toDense(), refMatB); // upper - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template marked<UpperTriangular>().solveTriangularInPlace(refMatB); m2.template triangular<UpperTriangular>().solveInPlace(matB); VERIFY_IS_APPROX(matB, refMatB); // test deprecated API initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template marked<LowerTriangular>().solveTriangular(vec2), m2.template marked<LowerTriangular>().solveTriangular(vec3)); } // test LLT { // TODO fix the issue with complex (see SparseLLT::solveInPlace) SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); initSPD(density, refMat2, m2); refMat2.llt().solve(b, &refX); typedef SparseMatrix<Scalar,LowerTriangular|SelfAdjoint> SparseSelfAdjointMatrix; if (!NumTraits<Scalar>::IsComplex) { x = b; SparseLLT<SparseSelfAdjointMatrix> (m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: default"); } #ifdef EIGEN_CHOLMOD_SUPPORT x = b; SparseLLT<SparseSelfAdjointMatrix,Cholmod>(m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod"); #endif #ifdef EIGEN_TAUCS_SUPPORT x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,IncompleteFactorization).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (IncompleteFactorization)"); x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalMultifrontal).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalMultifrontal)"); x = b; SparseLLT<SparseSelfAdjointMatrix,Taucs>(m2,SupernodalLeftLooking).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalLeftLooking)"); #endif } // test LDLT if (!NumTraits<Scalar>::IsComplex) { // TODO fix the issue with complex (see SparseLDLT::solveInPlace) SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); //initSPD(density, refMat2, m2); initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, 0, 0); refMat2 += refMat2.adjoint(); refMat2.diagonal() *= 0.5; refMat2.ldlt().solve(b, &refX); typedef SparseMatrix<Scalar,UpperTriangular|SelfAdjoint> SparseSelfAdjointMatrix; x = b; SparseLDLT<SparseSelfAdjointMatrix> ldlt(m2); if (ldlt.succeeded()) ldlt.solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LDLT: default"); } // test LU { static int count = 0; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag, &zeroCoords, &nonzeroCoords); LU<DenseMatrix> refLu(refMat2); refLu.solve(b, &refX); #if defined(EIGEN_SUPERLU_SUPPORT) || defined(EIGEN_UMFPACK_SUPPORT) Scalar refDet = refLu.determinant(); #endif x.setZero(); // // SparseLU<SparseMatrix<Scalar> > (m2).solve(b,&x); // // VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: default"); #ifdef EIGEN_SUPERLU_SUPPORT { x.setZero(); SparseLU<SparseMatrix<Scalar>,SuperLU> slu(m2); if (slu.succeeded()) { if (slu.solve(b,&x)) { VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: SuperLU"); } // std::cerr << refDet << " == " << slu.determinant() << "\n"; if (slu.solve(b, &x, SvTranspose)) { VERIFY(b.isApprox(m2.transpose() * x, test_precision<Scalar>())); } if (slu.solve(b, &x, SvAdjoint)) { // VERIFY(b.isApprox(m2.adjoint() * x, test_precision<Scalar>())); } if (count==0) { VERIFY_IS_APPROX(refDet,slu.determinant()); // FIXME det is not very stable for complex } } } #endif #ifdef EIGEN_UMFPACK_SUPPORT { // check solve x.setZero(); SparseLU<SparseMatrix<Scalar>,UmfPack> slu(m2); if (slu.succeeded()) { if (slu.solve(b,&x)) { if (count==0) { VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LU: umfpack"); // FIXME solve is not very stable for complex } } VERIFY_IS_APPROX(refDet,slu.determinant()); // TODO check the extracted data //std::cerr << slu.matrixL() << "\n"; } } #endif count++; } } void test_sparse_solvers() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST( sparse_solvers<double>(8, 8) ); CALL_SUBTEST( sparse_solvers<std::complex<double> >(16, 16) ); CALL_SUBTEST( sparse_solvers<double>(101, 101) ); } } <|endoftext|>
<commit_before>/* proxyImage.cpp Arsh Chauhan 05/02/2016 Source for class Proxyimage */ #include "proxyImage.hpp" Proxyimage::Proxyimage(string fileName): fileName_(fileName) { cout << "Proxy image created for file " << fileName << endl; } void Proxyimage::display() { realImage_ = Realimage(fileName_); realImage_.display(); }<commit_msg>Added pre and post conditions<commit_after>/* proxyImage.cpp Arsh Chauhan 05/02/2016 Source for class Proxyimage */ #include "proxyImage.hpp" /* 2 parameter constructor Pre: None Post: Creates new Proxyimage with filename fileName */ Proxyimage::Proxyimage(string fileName): fileName_(fileName) { cout << "Proxy image created for file " << fileName << endl; } /* display Pre: None Post: Creates a bew RealImage with filename fileName_ and sets realImage_ to that object Calls RealImage's display function with realImage_ */ void Proxyimage::display() { realImage_ = Realimage(fileName_); realImage_.display(); }<|endoftext|>
<commit_before>#include "ppasskeeper.h" #include "tokenizer.h" #include <string> #include <iostream> #include <fstream> #include <string.h> #include "safelock.h" #define STR_STRING "str :" #define BLOB_STRING "blob:" //Parameters std::map<std::string, cvariant> parameters; std::map<std::string, ppk_settings_group*> params_group; std::map<std::string, ppk_proto_param*> proto_params; ppk_proto_param** availParams; #define PARAM_MOD_PASSPHRASE "module passphrase" #define PARAM_CLOSING_DELAY "closing delay" #define PARAM_SAFELOCKER_PATH "SafeLocker's filepath" #define PARAM_FTP_USE "Use FTP" #define PARAM_FTP_HOST "FTP host" #define PARAM_FTP_PORT "FTP port" #define PARAM_FTP_LOGIN "FTP login" #define PARAM_FTP_PWD "FTP password" #define PARAM_FTP_PATH "FTP dir path" #define PARAM_MOD_PASSPHRASE_DEFAULT "AskForPass_Qt" #define PARAM_CLOSING_DELAY_DEFAULT 10 #define PARAM_FTP_USE_DEFAULT cvariant_true #define PARAM_FTP_HOST_DEFAULT "" #define PARAM_FTP_PORT_DEFAULT 21 #define PARAM_FTP_LOGIN_DEFAULT "" #define PARAM_FTP_PWD_DEFAULT "" #define PARAM_FTP_PATH_DEFAULT "" // extern "C" const char* getModuleID(); //Private functions QString safelockDefaultPath() { return QString::fromUtf8(ppk_settings_directory())+QString::fromUtf8("/ppk_safelock.crypted"); } SafeLock& safeLock() { const char* path=cvariant_get_string(parameters[PARAM_SAFELOCKER_PATH]); static SafeLock sf(QString::fromUtf8(path)); return sf; } ppk_error lazyInit() { if(!safeLock().isOpen()) return safeLock().open(); return PPK_OK; } //functions extern "C" { void constructor() { availParams=NULL; //Create the group categories ppk_settings_group *ppk_settings_security, *ppk_settings_network; ppk_settings_security=ppk_settings_group_create("Security", "Security related parameters"); ppk_settings_network=ppk_settings_group_create("Network", "Network related parameters"); params_group["Security"]=ppk_settings_security; params_group["Network"]=ppk_settings_network; //Create the parameters' prototypes ppk_proto_param *mod_passphrase, *close_dly, *ftp_use, *ftp_host, *ftp_port, *ftp_login, *ftp_pwd, *ftp_path; mod_passphrase=ppk_param_proto_create_module(PARAM_MOD_PASSPHRASE, "The ppk module you would like the passphrase to be got from.", PARAM_MOD_PASSPHRASE_DEFAULT, ppk_settings_security, PPK_FALSE, //Allow self PPK_FALSE, //writable only ppk_sec_lowest, ppk_rf_none, ppk_wf_none, ppk_lf_none); proto_params[PARAM_MOD_PASSPHRASE]=mod_passphrase; close_dly=ppk_param_proto_create_ranged_int(PARAM_CLOSING_DELAY, "Closing delay when the module is not used. Set it to 0 if you would like it not to be closed.", PARAM_CLOSING_DELAY_DEFAULT, ppk_settings_security, 0, 99); proto_params[PARAM_CLOSING_DELAY]=close_dly; ftp_use=ppk_param_proto_create_boolean(PARAM_FTP_USE, "Would you like to centralize your passwords on an FTP server ?", PARAM_FTP_USE_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_USE]=ftp_use; ftp_host=ppk_param_proto_create_string(PARAM_FTP_HOST, "The hostname of your ftp server", PARAM_FTP_HOST_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_HOST]=ftp_host; ftp_port=ppk_param_proto_create_ranged_int(PARAM_FTP_PORT, "The port of your ftp server", PARAM_FTP_PORT_DEFAULT, ppk_settings_network, 0, 65535); proto_params[PARAM_FTP_PORT]=ftp_port; ftp_login=ppk_param_proto_create_string(PARAM_FTP_LOGIN, "The login on your ftp server", PARAM_FTP_LOGIN_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_LOGIN]=ftp_login; ftp_pwd=ppk_param_proto_create_string(PARAM_FTP_PWD, "The password on your ftp server", PARAM_FTP_PWD_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_PWD]=ftp_pwd; ftp_path=ppk_param_proto_create_string(PARAM_FTP_PATH, "The path on your ftp server where you would like to store the safelocker (must already exist)", PARAM_FTP_PATH_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_PATH]=ftp_path; //Get a list of available parameters availParams=new ppk_proto_param*[proto_params.size()+1]; availParams[0]=mod_passphrase; availParams[1]=close_dly; availParams[2]=ftp_use; availParams[3]=ftp_host; availParams[4]=ftp_port; availParams[5]=ftp_login; availParams[6]=ftp_pwd; availParams[7]=ftp_path; availParams[8]=NULL; //Set parameters's default value parameters[PARAM_MOD_PASSPHRASE]=cvariant_from_string(PARAM_MOD_PASSPHRASE_DEFAULT); parameters[PARAM_CLOSING_DELAY]=cvariant_from_int(PARAM_CLOSING_DELAY_DEFAULT); parameters[PARAM_FTP_USE]=cvariant_from_bool(PARAM_FTP_USE_DEFAULT); parameters[PARAM_FTP_HOST]=cvariant_from_string(PARAM_FTP_HOST_DEFAULT); parameters[PARAM_FTP_PORT]=cvariant_from_int(PARAM_FTP_PORT_DEFAULT); parameters[PARAM_FTP_LOGIN]=cvariant_from_string(PARAM_FTP_LOGIN_DEFAULT); parameters[PARAM_FTP_PWD]=cvariant_from_string(PARAM_FTP_PWD_DEFAULT); parameters[PARAM_FTP_PATH]=cvariant_from_string(PARAM_FTP_PATH_DEFAULT); //Set up values const char* module=cvariant_get_string(parameters[PARAM_MOD_PASSPHRASE]); safeLock().setPPKModuleForPassphrase(QString::fromUtf8(module)); int closingDelay=cvariant_get_int(parameters[PARAM_CLOSING_DELAY]); safeLock().setClosingDelay(closingDelay); } void destructor() { //Free the list of parameter delete[] availParams; //Free the param prototypes std::map<std::string, ppk_proto_param*>::const_iterator itr; for(itr = proto_params.begin(); itr != proto_params.end(); ++itr) ppk_param_proto_free(itr->second); //Free the setting groups std::map<std::string, ppk_settings_group*>::const_iterator itr2; for(itr2 = params_group.begin(); itr2 != params_group.end(); ++itr2) ppk_settings_group_free(itr2->second); } const char* getModuleID() { return "PPKSafeLocker"; } const char* getModuleName() { return "PPK SafeLocker - PPassKeeper's Safe Locker"; } const int getABIVersion() { return 1; } ppk_security_level securityLevel(const char* module_id) { return ppk_sec_safe; } ppk_boolean isWritable() { return PPK_TRUE; } //Get available flags unsigned int readFlagsAvailable() { return ppk_rf_none|ppk_rf_silent; } unsigned int writeFlagsAvailable() { return ppk_wf_none|ppk_wf_silent; } unsigned int listingFlagsAvailable() { return ppk_lf_none|ppk_lf_silent; } ppk_error getSimpleEntryList(char*** list, unsigned int flags) { if(list==NULL) return PPK_INVALID_ARGUMENTS; (*list)=NULL; ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; QList<QString> entries=safeLock().list(); if(entries.size()>0) { //Copy to a char** list (*list)=new char*[entries.size()+1]; if((*list)!=NULL) { for(int i=0; i<entries.size(); i++) { QString entry=entries.at(i); (*list)[i]=(char*)malloc((entry.size()+1)*sizeof(char)); strncpy((*list)[i], qPrintable(entry), entry.size()+1); } (*list)[entries.size()]=NULL; } } else *list=NULL; return PPK_OK; } //Get and Set passwords #include "ppasskeeper/data.h" ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; const SFEntry sfentry=safeLock().get(entry); if(sfentry==SFEntry()) return PPK_ENTRY_UNAVAILABLE; *edata=sfentry.ppkData_new(); return PPK_OK; } ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; if(!safeLock().reset(entry, edata)) return PPK_ENTRY_UNAVAILABLE; else return PPK_OK; } ppk_error removeEntry(const ppk_entry* entry, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; if(safeLock().remove(entry)==false) return PPK_ENTRY_UNAVAILABLE; else return PPK_OK; } ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return PPK_FALSE; if(safeLock().get(entry)==SFEntry()) return PPK_FALSE; else return PPK_TRUE; } unsigned int maxDataSize(ppk_data_type type) { switch(type) { case ppk_string: return (unsigned int)-1; case ppk_blob: return (unsigned int)-1; } return 0; } const ppk_proto_param** availableParameters() { return const_cast<const ppk_proto_param**>(availParams); } void setParam(const char* paramName, const cvariant value) { std::string key(paramName); if(key == PARAM_MOD_PASSPHRASE) { if(cvariant_get_type(value)==cvariant_string) { parameters[PARAM_MOD_PASSPHRASE]=value; //Update the module const char* module=cvariant_get_string(parameters[PARAM_MOD_PASSPHRASE]); safeLock().setPPKModuleForPassphrase(QString::fromUtf8(module)); } else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_CLOSING_DELAY) { if(cvariant_get_type(value)==cvariant_int) { parameters[PARAM_CLOSING_DELAY]=value; //Update the value int closingDelay=cvariant_get_int(parameters[PARAM_CLOSING_DELAY]); safeLock().setClosingDelay(closingDelay); } else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_USE) { if(cvariant_get_type(value)==cvariant_boolean) parameters[PARAM_FTP_USE]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_HOST) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_HOST]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PORT) { if(cvariant_get_type(value)==cvariant_int) parameters[PARAM_FTP_PORT]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_LOGIN) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_LOGIN]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PWD) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_PWD]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PATH) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_PATH]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else printf("%s: Unknown param(%s) !!\n", getModuleID(), paramName); } } <commit_msg>SafeLocker: We are now able to specify where the database actually is<commit_after>#include "ppasskeeper.h" #include "tokenizer.h" #include <string> #include <iostream> #include <fstream> #include <string.h> #include "safelock.h" #define STR_STRING "str :" #define BLOB_STRING "blob:" //Parameters std::map<std::string, cvariant> parameters; std::map<std::string, ppk_settings_group*> params_group; std::map<std::string, ppk_proto_param*> proto_params; ppk_proto_param** availParams; #define PARAM_MOD_PASSPHRASE "module passphrase" #define PARAM_CLOSING_DELAY "closing delay" #define PARAM_SAFELOCKER_PATH "SafeLocker's filepath" #define PARAM_FTP_USE "Use FTP" #define PARAM_FTP_HOST "FTP host" #define PARAM_FTP_PORT "FTP port" #define PARAM_FTP_LOGIN "FTP login" #define PARAM_FTP_PWD "FTP password" #define PARAM_FTP_PATH "FTP dir path" #define PARAM_MOD_PASSPHRASE_DEFAULT "AskForPass_Qt" #define PARAM_CLOSING_DELAY_DEFAULT 10 #define PARAM_SAFELOCKER_PATH_DEFAULT (qPrintable(safelockDefaultPath())) #define PARAM_FTP_USE_DEFAULT cvariant_true #define PARAM_FTP_HOST_DEFAULT "" #define PARAM_FTP_PORT_DEFAULT 21 #define PARAM_FTP_LOGIN_DEFAULT "" #define PARAM_FTP_PWD_DEFAULT "" #define PARAM_FTP_PATH_DEFAULT "" // extern "C" const char* getModuleID(); //Private functions QString safelockDefaultPath() { return QString::fromUtf8(ppk_settings_directory())+QString::fromUtf8("ppk_safelock.ppksl"); } SafeLock& safeLock() { const char* path=cvariant_get_string(parameters[PARAM_SAFELOCKER_PATH]); static SafeLock sf(QString::fromUtf8(path)); return sf; } ppk_error lazyInit() { if(!safeLock().isOpen()) return safeLock().open(); return PPK_OK; } //functions extern "C" { void constructor() { availParams=NULL; //Create the group categories ppk_settings_group *ppk_settings_security, *ppk_settings_network; ppk_settings_security=ppk_settings_group_create("Security", "Security related parameters"); ppk_settings_network=ppk_settings_group_create("Network", "Network related parameters"); params_group["Security"]=ppk_settings_security; params_group["Network"]=ppk_settings_network; //Create the parameters' prototypes ppk_proto_param *mod_passphrase, *close_dly, *safelocker_path, *ftp_use, *ftp_host, *ftp_port, *ftp_login, *ftp_pwd, *ftp_path; mod_passphrase=ppk_param_proto_create_module(PARAM_MOD_PASSPHRASE, "The ppk module you would like the passphrase to be got from.", PARAM_MOD_PASSPHRASE_DEFAULT, ppk_settings_security, PPK_FALSE, //Allow self PPK_FALSE, //writable only ppk_sec_lowest, ppk_rf_none, ppk_wf_none, ppk_lf_none); proto_params[PARAM_MOD_PASSPHRASE]=mod_passphrase; close_dly=ppk_param_proto_create_ranged_int(PARAM_CLOSING_DELAY, "Closing delay when the module is not used. Set it to 0 if you would like it not to be closed.", PARAM_CLOSING_DELAY_DEFAULT, ppk_settings_security, 0, 99); proto_params[PARAM_CLOSING_DELAY]=close_dly; safelocker_path=ppk_param_proto_create_file(PARAM_SAFELOCKER_PATH, "Where would you like to save the safelock.", qPrintable(safelockDefaultPath()), ppk_settings_security, "PPassKeeper's safeLocker files(*.ppksl)"); proto_params[PARAM_SAFELOCKER_PATH]=safelocker_path; ftp_use=ppk_param_proto_create_boolean(PARAM_FTP_USE, "Would you like to centralize your passwords on an FTP server ?", PARAM_FTP_USE_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_USE]=ftp_use; ftp_host=ppk_param_proto_create_string(PARAM_FTP_HOST, "The hostname of your ftp server", PARAM_FTP_HOST_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_HOST]=ftp_host; ftp_port=ppk_param_proto_create_ranged_int(PARAM_FTP_PORT, "The port of your ftp server", PARAM_FTP_PORT_DEFAULT, ppk_settings_network, 0, 65535); proto_params[PARAM_FTP_PORT]=ftp_port; ftp_login=ppk_param_proto_create_string(PARAM_FTP_LOGIN, "The login on your ftp server", PARAM_FTP_LOGIN_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_LOGIN]=ftp_login; ftp_pwd=ppk_param_proto_create_string(PARAM_FTP_PWD, "The password on your ftp server", PARAM_FTP_PWD_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_PWD]=ftp_pwd; ftp_path=ppk_param_proto_create_string(PARAM_FTP_PATH, "The path on your ftp server where you would like to store the safelocker (must already exist)", PARAM_FTP_PATH_DEFAULT, ppk_settings_network); proto_params[PARAM_FTP_PATH]=ftp_path; //Get a list of available parameters availParams=new ppk_proto_param*[proto_params.size()+1]; availParams[0]=mod_passphrase; availParams[1]=close_dly; availParams[2]=safelocker_path; availParams[3]=ftp_use; availParams[4]=ftp_host; availParams[5]=ftp_port; availParams[6]=ftp_login; availParams[7]=ftp_pwd; availParams[8]=ftp_path; availParams[9]=NULL; //Set parameters's default value parameters[PARAM_MOD_PASSPHRASE]=cvariant_from_string(PARAM_MOD_PASSPHRASE_DEFAULT); parameters[PARAM_CLOSING_DELAY]=cvariant_from_int(PARAM_CLOSING_DELAY_DEFAULT); parameters[PARAM_SAFELOCKER_PATH]=cvariant_from_string(qPrintable(safelockDefaultPath())); parameters[PARAM_FTP_USE]=cvariant_from_bool(PARAM_FTP_USE_DEFAULT); parameters[PARAM_FTP_HOST]=cvariant_from_string(PARAM_FTP_HOST_DEFAULT); parameters[PARAM_FTP_PORT]=cvariant_from_int(PARAM_FTP_PORT_DEFAULT); parameters[PARAM_FTP_LOGIN]=cvariant_from_string(PARAM_FTP_LOGIN_DEFAULT); parameters[PARAM_FTP_PWD]=cvariant_from_string(PARAM_FTP_PWD_DEFAULT); parameters[PARAM_FTP_PATH]=cvariant_from_string(PARAM_FTP_PATH_DEFAULT); //Set up values const char* module=cvariant_get_string(parameters[PARAM_MOD_PASSPHRASE]); safeLock().setPPKModuleForPassphrase(QString::fromUtf8(module)); int closingDelay=cvariant_get_int(parameters[PARAM_CLOSING_DELAY]); safeLock().setClosingDelay(closingDelay); } void destructor() { //Free the list of parameter delete[] availParams; //Free the param prototypes std::map<std::string, ppk_proto_param*>::const_iterator itr; for(itr = proto_params.begin(); itr != proto_params.end(); ++itr) ppk_param_proto_free(itr->second); //Free the setting groups std::map<std::string, ppk_settings_group*>::const_iterator itr2; for(itr2 = params_group.begin(); itr2 != params_group.end(); ++itr2) ppk_settings_group_free(itr2->second); } const char* getModuleID() { return "PPKSafeLocker"; } const char* getModuleName() { return "PPK SafeLocker - PPassKeeper's Safe Locker"; } const int getABIVersion() { return 1; } ppk_security_level securityLevel(const char* module_id) { return ppk_sec_safe; } ppk_boolean isWritable() { return PPK_TRUE; } //Get available flags unsigned int readFlagsAvailable() { return ppk_rf_none|ppk_rf_silent; } unsigned int writeFlagsAvailable() { return ppk_wf_none|ppk_wf_silent; } unsigned int listingFlagsAvailable() { return ppk_lf_none|ppk_lf_silent; } ppk_error getSimpleEntryList(char*** list, unsigned int flags) { if(list==NULL) return PPK_INVALID_ARGUMENTS; (*list)=NULL; ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; QList<QString> entries=safeLock().list(); if(entries.size()>0) { //Copy to a char** list (*list)=new char*[entries.size()+1]; if((*list)!=NULL) { for(int i=0; i<entries.size(); i++) { QString entry=entries.at(i); (*list)[i]=(char*)malloc((entry.size()+1)*sizeof(char)); strncpy((*list)[i], qPrintable(entry), entry.size()+1); } (*list)[entries.size()]=NULL; } } else *list=NULL; return PPK_OK; } //Get and Set passwords #include "ppasskeeper/data.h" ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; const SFEntry sfentry=safeLock().get(entry); if(sfentry==SFEntry()) return PPK_ENTRY_UNAVAILABLE; *edata=sfentry.ppkData_new(); return PPK_OK; } ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; if(!safeLock().reset(entry, edata)) return PPK_ENTRY_UNAVAILABLE; else return PPK_OK; } ppk_error removeEntry(const ppk_entry* entry, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return ret; if(safeLock().remove(entry)==false) return PPK_ENTRY_UNAVAILABLE; else return PPK_OK; } ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags) { ppk_error ret=lazyInit(); if(ret!=PPK_OK) return PPK_FALSE; if(safeLock().get(entry)==SFEntry()) return PPK_FALSE; else return PPK_TRUE; } unsigned int maxDataSize(ppk_data_type type) { switch(type) { case ppk_string: return (unsigned int)-1; case ppk_blob: return (unsigned int)-1; } return 0; } const ppk_proto_param** availableParameters() { return const_cast<const ppk_proto_param**>(availParams); } void setParam(const char* paramName, const cvariant value) { std::string key(paramName); if(key == PARAM_MOD_PASSPHRASE) { if(cvariant_get_type(value)==cvariant_string) { parameters[PARAM_MOD_PASSPHRASE]=value; //Update the module const char* module=cvariant_get_string(parameters[PARAM_MOD_PASSPHRASE]); safeLock().setPPKModuleForPassphrase(QString::fromUtf8(module)); } else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_CLOSING_DELAY) { if(cvariant_get_type(value)==cvariant_int) { parameters[PARAM_CLOSING_DELAY]=value; //Update the value int closingDelay=cvariant_get_int(parameters[PARAM_CLOSING_DELAY]); safeLock().setClosingDelay(closingDelay); } else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_SAFELOCKER_PATH) { if(cvariant_get_type(value)==cvariant_string) { parameters[PARAM_SAFELOCKER_PATH]=value; //Update the module const char* path=cvariant_get_string(parameters[PARAM_SAFELOCKER_PATH]); safeLock().setSafeLockPath(QString::fromUtf8(path)); } else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_USE) { if(cvariant_get_type(value)==cvariant_boolean) parameters[PARAM_FTP_USE]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_HOST) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_HOST]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PORT) { if(cvariant_get_type(value)==cvariant_int) parameters[PARAM_FTP_PORT]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_LOGIN) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_LOGIN]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PWD) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_PWD]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else if(key == PARAM_FTP_PATH) { if(cvariant_get_type(value)==cvariant_string) parameters[PARAM_FTP_PATH]=value; else printf("%s: Wrong data type for the parameter '%s' !\n", getModuleID(), paramName); } else printf("%s: Unknown param(%s) !!\n", getModuleID(), paramName); } } <|endoftext|>
<commit_before>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER 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. #pragma once #include <cstdint> #include <memory> #include <sstream> #include <string> #include <string_view> #if !defined(TADPOLE_UNUSED) # define TADPOLE_UNUSED(x) ((void)x) #endif namespace tadpole { using nil_t = std::nullptr_t; using byte_t = std::uint8_t; using i8_t = std::int8_t; using u8_t = std::uint8_t; using i16_t = std::int16_t; using u16_t = std::uint16_t; using i32_t = std::int32_t; using u32_t = std::uint32_t; using i64_t = std::int64_t; using u64_t = std::uint64_t; using sz_t = std::size_t; using str_t = std::string; using strv_t = std::string_view; using ss_t = std::stringstream; class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T, typename S> inline T as_type(S x) noexcept { return static_cast<T>(x); } template <typename T, typename S> inline T* as_down(S* x) noexcept { return dynamic_cast<T*>(x); } template <typename T> inline T* get_rawptr(const std::unique_ptr<T>& p) noexcept { return p.get(); } template <typename T> inline T* get_rawptr(const std::shared_ptr<T>& p) noexcept { return p.get(); } inline str_t as_string(double d) noexcept { ss_t ss; ss << d; return ss.str(); } template <typename T, typename... Args> inline str_t as_string(T&& x, Args&&... args) noexcept { ss_t ss; ss << std::forward<T>(x); ((ss << std::forward<Args>(args)), ...); return ss.str(); } template <typename... Args> inline str_t string_format(strv_t fmt, const Args&... args) { int sz = std::snprintf(nullptr, 0, fmt.data(), args...); std::unique_ptr<char[]> buf{new char[sz + 1]}; std::snprintf(buf.get(), sz, fmt.data(), args...); return str_t(buf.get(), buf.get() + sz); } } <commit_msg>:construction: chore(common): updated the common utils<commit_after>// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER 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. #pragma once #include <cstdint> #include <iomanip> #include <limits> #include <memory> #include <sstream> #include <string> #include <string_view> #if !defined(TADPOLE_UNUSED) # define TADPOLE_UNUSED(x) ((void)x) #endif namespace tadpole { using nil_t = std::nullptr_t; using byte_t = std::uint8_t; using i8_t = std::int8_t; using u8_t = std::uint8_t; using i16_t = std::int16_t; using u16_t = std::uint16_t; using i32_t = std::int32_t; using u32_t = std::uint32_t; using i64_t = std::int64_t; using u64_t = std::uint64_t; using sz_t = std::size_t; using str_t = std::string; using strv_t = std::string_view; using ss_t = std::stringstream; class Copyable { protected: Copyable() noexcept = default; ~Copyable() noexcept = default; Copyable(const Copyable&) noexcept = default; Copyable(Copyable&&) noexcept = default; Copyable& operator=(const Copyable&) noexcept = default; Copyable& operator=(Copyable&&) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) noexcept = delete; UnCopyable(UnCopyable&&) noexcept = delete; UnCopyable& operator=(const UnCopyable&) noexcept = delete; UnCopyable& operator=(UnCopyable&&) noexcept = delete; protected: UnCopyable() noexcept = default; ~UnCopyable() noexcept = default; }; template <typename T, typename S> inline T as_type(S x) noexcept { return static_cast<T>(x); } template <typename T, typename S> inline T* as_down(S* x) noexcept { return dynamic_cast<T*>(x); } template <typename T> inline T* get_rawptr(const std::unique_ptr<T>& p) noexcept { return p.get(); } template <typename T> inline T* get_rawptr(const std::shared_ptr<T>& p) noexcept { return p.get(); } inline str_t as_string(double d) noexcept { ss_t ss; ss << std::setprecision(std::numeric_limits<double>::max_digits10) << d; return ss.str(); } template <typename T, typename... Args> inline str_t as_string(T&& x, Args&&... args) noexcept { ss_t ss; ss << std::forward<T>(x); ((ss << std::forward<Args>(args)), ...); return ss.str(); } template <typename... Args> inline str_t string_format(strv_t fmt, const Args&... args) { int sz = std::snprintf(nullptr, 0, fmt.data(), args...); std::unique_ptr<char[]> buf{new char[sz + 1]}; std::snprintf(buf.get(), sz, fmt.data(), args...); return str_t(buf.get(), buf.get() + sz); } } <|endoftext|>
<commit_before>// // frame-io.cpp // // Created by Peter Gusev on 17 March 2016. // Copyright 2013-2016 Regents of the University of California // #include <stdexcept> #include <sstream> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include "frame-io.hpp" #ifdef HAVE_NANOMSG #include "ipc-shim.h" #endif using namespace std; RawFrame::RawFrame(unsigned int width, unsigned int height) : bufferSize_(0), width_(width), height_(height), frameInfo_({0, 0, ""}) {} RawFrame::~RawFrame() {} void RawFrame::setFrameInfo(const ndnrtc::FrameInfo& frameInfo) { frameInfo_ = frameInfo; } //****************************************************************************** ArgbFrame::ArgbFrame(unsigned int width, unsigned int height) : RawFrame(width, height) { unsigned long bufSize = getFrameSizeInBytes(); setBuffer(bufSize, boost::shared_ptr<uint8_t>(new uint8_t[bufSize])); } void ArgbFrame::getFrameResolution(unsigned int &width, unsigned int &height) const { width = width_; height = height_; } unsigned long ArgbFrame::getFrameSizeInBytes() const { return width_ * height_ * 4; } //****************************************************************************** void FileFrameStorage::openFile() { if (path_ == "") throw runtime_error("invalid file path provided"); file_ = openFile_impl(path_); if (!file_) throw runtime_error("couldn't create sink file at path " + path_); fseek(file_, 0, SEEK_END); fileSize_ = ftell(file_); rewind(file_); } void FileFrameStorage::closeFile() { if (file_) { fclose(file_); file_ = nullptr; } } //****************************************************************************** IFrameSink &FileSink::operator<<(const RawFrame &frame) { int res = fwrite(frame.getBuffer().get(), sizeof(uint8_t), frame.getFrameSizeInBytes(), file_); isLastWriteSuccessful_ = (res > 0); return *this; } FILE *FileSink::openFile_impl(string path) { return fopen(path.c_str(), "wb"); } //****************************************************************************** PipeSink::PipeSink(const std::string &path) : pipePath_(path), pipe_(-1), isLastWriteSuccessful_(false), isWriting_(false), writeFrameInfo_(false) { createPipe(pipePath_); openPipe(pipePath_); } PipeSink::~PipeSink() { if (pipe_ > 0) close(pipe_); } IFrameSink &PipeSink::operator<<(const RawFrame &frame) { if (pipe_ < 0) openPipe(pipePath_); if (pipe_ > 0) { isWriting_ = true; uint8_t *buf = frame.getBuffer().get(); int written = 0, r = 0; bool continueWrite = false; do { r = write(pipe_, buf + written, frame.getFrameSizeInBytes() - written); if (r > 0) written += r; isLastWriteSuccessful_ = (r > 0); // keep writing if has not written all buffer and no errors occured or // there was an error and this error is EAGAIN continueWrite = (r > 0 && written != frame.getFrameSizeInBytes()) || (r < 0 && errno == EAGAIN); } while (continueWrite); isWriting_ = false; } else isLastWriteSuccessful_ = false; return *this; } void PipeSink::createPipe(const std::string &path) { int res = mkfifo(path.c_str(), 0644); if (res < 0 && errno != EEXIST) { std::stringstream ss; ss << "Error creating pipe(" << errno << "): " << strerror(errno); throw std::runtime_error(ss.str()); } } void PipeSink::openPipe(const std::string &path) { pipe_ = open(path.c_str(), O_WRONLY | O_NONBLOCK | O_EXCL); } #ifdef HAVE_LIBNANOMSG #include <iostream> NanoMsgSink::NanoMsgSink(const std::string &handle) : writeFrameInfo_(false) { nnSocket_ = ipc_setupPubSourceSocket(handle.c_str()); if (nnSocket_ < 0) throw std::runtime_error(ipc_lastError()); } NanoMsgSink::~NanoMsgSink() { ipc_shutdownSocket(nnSocket_); } unsigned char* mallocPackFrameInfo(const ndnrtc::FrameInfo& finfo, size_t *packedSize) { *packedSize = sizeof(finfo)-sizeof(std::string) + finfo.ndnName_.size() + 1; unsigned char *buf = (unsigned char*)malloc(*packedSize); memset(buf, 0, *packedSize); ((ndnrtc::FrameInfo*)buf)->timestamp_ = finfo.timestamp_; ((ndnrtc::FrameInfo*)buf)->playbackNo_ = finfo.playbackNo_; size_t stringCopyOffset = sizeof(finfo)-sizeof(std::string); memcpy(buf+stringCopyOffset, finfo.ndnName_.c_str(), finfo.ndnName_.size()); return buf; } IFrameSink &NanoMsgSink::operator<<(const RawFrame &frame) { uint8_t *buf = frame.getBuffer().get(); if (writeFrameInfo_) { size_t frameInfoPacked = 0; unsigned char* buf = mallocPackFrameInfo(frame.getFrameInfo(), &frameInfoPacked); isLastWriteSuccessful_ = (ipc_sendFrame(nnSocket_, frameInfoPacked, (const void*)(buf), buf, frame.getFrameSizeInBytes()) > 0); free(buf); } else isLastWriteSuccessful_ = (ipc_sendData(nnSocket_, buf, frame.getFrameSizeInBytes()) > 0); return *this; } #endif //****************************************************************************** FileFrameSource::FileFrameSource(const string &path) : FileFrameStorage(path), current_(0), readError_(false) { openFile(); } IFrameSource &FileFrameSource::operator>>(RawFrame &frame) noexcept { uint8_t *buf = frame.getBuffer().get(); size_t readBytes = fread(buf, sizeof(uint8_t), frame.getFrameSizeInBytes(), file_); current_ = ftell(file_); readError_ = (readBytes != frame.getFrameSizeInBytes()); // { // stringstream msg; // msg << "error trying to read frame of " << frame.getFrameSizeInBytes() // << " bytes from file (read " << readBytes << " bytes): error " // << ferror(file_) << " eof: " << feof(file_) // << " current " << current_ << " size " << fileSize_ // << " ftell " << ftell(file_); // throw runtime_error(msg.str()); // } return *this; } bool FileFrameSource::checkSourceForFrame(const std::string &path, const RawFrame &frame) { FILE *f = fopen(path.c_str(), "rb"); if (!f) return false; else fseek(f, 0, SEEK_END); long lSize = ftell(f); int nFrames = lSize % frame.getFrameSizeInBytes(); fclose(f); return (nFrames == 0); } FILE *FileFrameSource::openFile_impl(string path) { return fopen(path.c_str(), "rb"); } <commit_msg>(ᕗ ͠° ਊ ͠° )ᕗ<commit_after>// // frame-io.cpp // // Created by Peter Gusev on 17 March 2016. // Copyright 2013-2016 Regents of the University of California // #include <stdexcept> #include <sstream> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include "frame-io.hpp" #ifdef HAVE_NANOMSG #include "ipc-shim.h" #endif using namespace std; RawFrame::RawFrame(unsigned int width, unsigned int height) : bufferSize_(0), width_(width), height_(height), frameInfo_({0, 0, ""}) {} RawFrame::~RawFrame() {} void RawFrame::setFrameInfo(const ndnrtc::FrameInfo& frameInfo) { frameInfo_ = frameInfo; } //****************************************************************************** ArgbFrame::ArgbFrame(unsigned int width, unsigned int height) : RawFrame(width, height) { unsigned long bufSize = getFrameSizeInBytes(); setBuffer(bufSize, boost::shared_ptr<uint8_t>(new uint8_t[bufSize])); } void ArgbFrame::getFrameResolution(unsigned int &width, unsigned int &height) const { width = width_; height = height_; } unsigned long ArgbFrame::getFrameSizeInBytes() const { return width_ * height_ * 4; } //****************************************************************************** void FileFrameStorage::openFile() { if (path_ == "") throw runtime_error("invalid file path provided"); file_ = openFile_impl(path_); if (!file_) throw runtime_error("couldn't create sink file at path " + path_); fseek(file_, 0, SEEK_END); fileSize_ = ftell(file_); rewind(file_); } void FileFrameStorage::closeFile() { if (file_) { fclose(file_); file_ = nullptr; } } //****************************************************************************** IFrameSink &FileSink::operator<<(const RawFrame &frame) { int res = fwrite(frame.getBuffer().get(), sizeof(uint8_t), frame.getFrameSizeInBytes(), file_); isLastWriteSuccessful_ = (res > 0); return *this; } FILE *FileSink::openFile_impl(string path) { return fopen(path.c_str(), "wb"); } //****************************************************************************** PipeSink::PipeSink(const std::string &path) : pipePath_(path), pipe_(-1), isLastWriteSuccessful_(false), isWriting_(false), writeFrameInfo_(false) { createPipe(pipePath_); openPipe(pipePath_); } PipeSink::~PipeSink() { if (pipe_ > 0) close(pipe_); } IFrameSink &PipeSink::operator<<(const RawFrame &frame) { if (pipe_ < 0) openPipe(pipePath_); if (pipe_ > 0) { isWriting_ = true; uint8_t *buf = frame.getBuffer().get(); int written = 0, r = 0; bool continueWrite = false; do { r = write(pipe_, buf + written, frame.getFrameSizeInBytes() - written); if (r > 0) written += r; isLastWriteSuccessful_ = (r > 0); // keep writing if has not written all buffer and no errors occured or // there was an error and this error is EAGAIN continueWrite = (r > 0 && written != frame.getFrameSizeInBytes()) || (r < 0 && errno == EAGAIN); } while (continueWrite); isWriting_ = false; } else isLastWriteSuccessful_ = false; return *this; } void PipeSink::createPipe(const std::string &path) { int res = mkfifo(path.c_str(), 0644); if (res < 0 && errno != EEXIST) { std::stringstream ss; ss << "Error creating pipe(" << errno << "): " << strerror(errno); throw std::runtime_error(ss.str()); } } void PipeSink::openPipe(const std::string &path) { pipe_ = open(path.c_str(), O_WRONLY | O_NONBLOCK | O_EXCL); } #ifdef HAVE_LIBNANOMSG #include <iostream> NanoMsgSink::NanoMsgSink(const std::string &handle) : writeFrameInfo_(false) { nnSocket_ = ipc_setupPubSourceSocket(handle.c_str()); if (nnSocket_ < 0) throw std::runtime_error(ipc_lastError()); } NanoMsgSink::~NanoMsgSink() { ipc_shutdownSocket(nnSocket_); } unsigned char* mallocPackFrameInfo(const ndnrtc::FrameInfo& finfo, size_t *packedSize) { *packedSize = sizeof(finfo)-sizeof(std::string) + finfo.ndnName_.size() + 1; unsigned char *buf = (unsigned char*)malloc(*packedSize); memset(buf, 0, *packedSize); ((ndnrtc::FrameInfo*)buf)->timestamp_ = finfo.timestamp_; ((ndnrtc::FrameInfo*)buf)->playbackNo_ = finfo.playbackNo_; size_t stringCopyOffset = sizeof(finfo)-sizeof(std::string); memcpy(buf+stringCopyOffset, finfo.ndnName_.c_str(), finfo.ndnName_.size()); return buf; } IFrameSink &NanoMsgSink::operator<<(const RawFrame &frame) { uint8_t *buf = frame.getBuffer().get(); if (writeFrameInfo_) { size_t frameInfoPacked = 0; unsigned char* header = mallocPackFrameInfo(frame.getFrameInfo(), &frameInfoPacked); isLastWriteSuccessful_ = (ipc_sendFrame(nnSocket_, frameInfoPacked, (const void*)(header), buf, frame.getFrameSizeInBytes()) > 0); free(header); } else isLastWriteSuccessful_ = (ipc_sendData(nnSocket_, buf, frame.getFrameSizeInBytes()) > 0); return *this; } #endif //****************************************************************************** FileFrameSource::FileFrameSource(const string &path) : FileFrameStorage(path), current_(0), readError_(false) { openFile(); } IFrameSource &FileFrameSource::operator>>(RawFrame &frame) noexcept { uint8_t *buf = frame.getBuffer().get(); size_t readBytes = fread(buf, sizeof(uint8_t), frame.getFrameSizeInBytes(), file_); current_ = ftell(file_); readError_ = (readBytes != frame.getFrameSizeInBytes()); // { // stringstream msg; // msg << "error trying to read frame of " << frame.getFrameSizeInBytes() // << " bytes from file (read " << readBytes << " bytes): error " // << ferror(file_) << " eof: " << feof(file_) // << " current " << current_ << " size " << fileSize_ // << " ftell " << ftell(file_); // throw runtime_error(msg.str()); // } return *this; } bool FileFrameSource::checkSourceForFrame(const std::string &path, const RawFrame &frame) { FILE *f = fopen(path.c_str(), "rb"); if (!f) return false; else fseek(f, 0, SEEK_END); long lSize = ftell(f); int nFrames = lSize % frame.getFrameSizeInBytes(); fclose(f); return (nFrames == 0); } FILE *FileFrameSource::openFile_impl(string path) { return fopen(path.c_str(), "rb"); } <|endoftext|>
<commit_before>#pragma once #include <rai/lib/interface.h> #include <rai/secure/common.hpp> #include <boost/asio.hpp> #include <bitset> #include <xxhash/xxhash.h> namespace rai { using endpoint = boost::asio::ip::udp::endpoint; bool parse_port (std::string const &, uint16_t &); bool parse_address_port (std::string const &, boost::asio::ip::address &, uint16_t &); using tcp_endpoint = boost::asio::ip::tcp::endpoint; bool parse_endpoint (std::string const &, rai::endpoint &); bool parse_tcp_endpoint (std::string const &, rai::tcp_endpoint &); bool reserved_address (rai::endpoint const &, bool); } static uint64_t endpoint_hash_raw (rai::endpoint const & endpoint_a) { assert (endpoint_a.address ().is_v6 ()); rai::uint128_union address; address.bytes = endpoint_a.address ().to_v6 ().to_bytes (); XXH64_state_t hash; XXH64_reset (&hash, 0); XXH64_update (&hash, address.bytes.data (), address.bytes.size ()); auto port (endpoint_a.port ()); XXH64_update (&hash, &port, sizeof (port)); auto result (XXH64_digest (&hash)); return result; } static uint64_t ip_address_hash_raw (boost::asio::ip::address const & ip_a) { assert (ip_a.is_v6 ()); rai::uint128_union bytes; bytes.bytes = ip_a.to_v6 ().to_bytes (); XXH64_state_t hash; XXH64_reset (&hash, 0); XXH64_update (&hash, bytes.bytes.data (), bytes.bytes.size ()); auto result (XXH64_digest (&hash)); return result; } namespace std { template <size_t size> struct endpoint_hash { }; template <> struct endpoint_hash<8> { size_t operator() (rai::endpoint const & endpoint_a) const { return endpoint_hash_raw (endpoint_a); } }; template <> struct endpoint_hash<4> { size_t operator() (rai::endpoint const & endpoint_a) const { uint64_t big (endpoint_hash_raw (endpoint_a)); uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32)); return result; } }; template <> struct hash<rai::endpoint> { size_t operator() (rai::endpoint const & endpoint_a) const { endpoint_hash<sizeof (size_t)> ehash; return ehash (endpoint_a); } }; template <size_t size> struct ip_address_hash { }; template <> struct ip_address_hash<8> { size_t operator() (boost::asio::ip::address const & ip_address_a) const { return ip_address_hash_raw (ip_address_a); } }; template <> struct ip_address_hash<4> { size_t operator() (boost::asio::ip::address const & ip_address_a) const { uint64_t big (ip_address_hash_raw (ip_address_a)); uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32)); return result; } }; template <> struct hash<boost::asio::ip::address> { size_t operator() (boost::asio::ip::address const & ip_a) const { ip_address_hash<sizeof (size_t)> ihash; return ihash (ip_a); } }; } namespace boost { template <> struct hash<rai::endpoint> { size_t operator() (rai::endpoint const & endpoint_a) const { std::hash<rai::endpoint> hash; return hash (endpoint_a); } }; } namespace rai { enum class message_type : uint8_t { invalid, not_a_type, keepalive, publish, confirm_req, confirm_ack, bulk_pull, bulk_push, frontier_req, bulk_pull_blocks, node_id_handshake }; enum class bulk_pull_blocks_mode : uint8_t { list_blocks, checksum_blocks }; class message_visitor; class message_header { public: message_header (rai::message_type); message_header (bool &, rai::stream &); void serialize (rai::stream &); bool deserialize (rai::stream &); rai::block_type block_type () const; void block_type_set (rai::block_type); bool ipv4_only (); void ipv4_only_set (bool); static std::array<uint8_t, 2> constexpr magic_number = rai::rai_network == rai::rai_networks::rai_test_network ? std::array<uint8_t, 2>{ { 'R', 'A' } } : rai::rai_network == rai::rai_networks::rai_beta_network ? std::array<uint8_t, 2>{ { 'R', 'B' } } : std::array<uint8_t, 2>{ { 'R', 'C' } }; uint8_t version_max; uint8_t version_using; uint8_t version_min; rai::message_type type; std::bitset<16> extensions; static size_t constexpr ipv4_only_position = 1; static size_t constexpr bootstrap_server_position = 2; static std::bitset<16> constexpr block_type_mask = std::bitset<16> (0x0f00); }; class message { public: message (rai::message_type); message (rai::message_header const &); virtual ~message () = default; virtual void serialize (rai::stream &) = 0; virtual bool deserialize (rai::stream &) = 0; virtual void visit (rai::message_visitor &) const = 0; rai::message_header header; }; class work_pool; class message_parser { public: enum class parse_status { success, insufficient_work, invalid_header, invalid_message_type, invalid_keepalive_message, invalid_publish_message, invalid_confirm_req_message, invalid_confirm_ack_message, invalid_node_id_handshake_message, outdated_version }; message_parser (rai::message_visitor &, rai::work_pool &); void deserialize_buffer (uint8_t const *, size_t); void deserialize_keepalive (rai::stream &, rai::message_header const &); void deserialize_publish (rai::stream &, rai::message_header const &); void deserialize_confirm_req (rai::stream &, rai::message_header const &); void deserialize_confirm_ack (rai::stream &, rai::message_header const &); void deserialize_node_id_handshake (rai::stream &, rai::message_header const &); bool at_end (rai::stream &); rai::message_visitor & visitor; rai::work_pool & pool; parse_status status; }; class keepalive : public message { public: keepalive (bool &, rai::stream &, rai::message_header const &); keepalive (); void visit (rai::message_visitor &) const override; bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; bool operator== (rai::keepalive const &) const; std::array<rai::endpoint, 8> peers; }; class publish : public message { public: publish (bool &, rai::stream &, rai::message_header const &); publish (std::shared_ptr<rai::block>); void visit (rai::message_visitor &) const override; bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; bool operator== (rai::publish const &) const; std::shared_ptr<rai::block> block; }; class confirm_req : public message { public: confirm_req (bool &, rai::stream &, rai::message_header const &); confirm_req (std::shared_ptr<rai::block>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::confirm_req const &) const; std::shared_ptr<rai::block> block; }; class confirm_ack : public message { public: confirm_ack (bool &, rai::stream &, rai::message_header const &); confirm_ack (std::shared_ptr<rai::vote>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::confirm_ack const &) const; std::shared_ptr<rai::vote> vote; }; class frontier_req : public message { public: frontier_req (); frontier_req (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::frontier_req const &) const; rai::account start; uint32_t age; uint32_t count; }; class bulk_pull : public message { public: bulk_pull (); bulk_pull (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; rai::uint256_union start; rai::block_hash end; }; class bulk_pull_blocks : public message { public: bulk_pull_blocks (); bulk_pull_blocks (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; rai::block_hash min_hash; rai::block_hash max_hash; bulk_pull_blocks_mode mode; uint32_t max_count; }; class bulk_push : public message { public: bulk_push (); bulk_push (rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; }; class node_id_handshake : public message { public: node_id_handshake (bool &, rai::stream &, rai::message_header const &); node_id_handshake (boost::optional<rai::block_hash>, boost::optional<std::pair<rai::account, rai::signature>>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::node_id_handshake const &) const; boost::optional<rai::uint256_union> query; boost::optional<std::pair<rai::account, rai::signature>> response; static size_t constexpr query_flag = 0; static size_t constexpr response_flag = 1; }; class message_visitor { public: virtual void keepalive (rai::keepalive const &) = 0; virtual void publish (rai::publish const &) = 0; virtual void confirm_req (rai::confirm_req const &) = 0; virtual void confirm_ack (rai::confirm_ack const &) = 0; virtual void bulk_pull (rai::bulk_pull const &) = 0; virtual void bulk_pull_blocks (rai::bulk_pull_blocks const &) = 0; virtual void bulk_push (rai::bulk_push const &) = 0; virtual void frontier_req (rai::frontier_req const &) = 0; virtual void node_id_handshake (rai::node_id_handshake const &) = 0; virtual ~message_visitor (); }; /** * Returns seconds passed since unix epoch (posix time) */ inline uint64_t seconds_since_epoch () { return std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now ().time_since_epoch ()).count (); } } <commit_msg>Explicitly set message type values<commit_after>#pragma once #include <rai/lib/interface.h> #include <rai/secure/common.hpp> #include <boost/asio.hpp> #include <bitset> #include <xxhash/xxhash.h> namespace rai { using endpoint = boost::asio::ip::udp::endpoint; bool parse_port (std::string const &, uint16_t &); bool parse_address_port (std::string const &, boost::asio::ip::address &, uint16_t &); using tcp_endpoint = boost::asio::ip::tcp::endpoint; bool parse_endpoint (std::string const &, rai::endpoint &); bool parse_tcp_endpoint (std::string const &, rai::tcp_endpoint &); bool reserved_address (rai::endpoint const &, bool); } static uint64_t endpoint_hash_raw (rai::endpoint const & endpoint_a) { assert (endpoint_a.address ().is_v6 ()); rai::uint128_union address; address.bytes = endpoint_a.address ().to_v6 ().to_bytes (); XXH64_state_t hash; XXH64_reset (&hash, 0); XXH64_update (&hash, address.bytes.data (), address.bytes.size ()); auto port (endpoint_a.port ()); XXH64_update (&hash, &port, sizeof (port)); auto result (XXH64_digest (&hash)); return result; } static uint64_t ip_address_hash_raw (boost::asio::ip::address const & ip_a) { assert (ip_a.is_v6 ()); rai::uint128_union bytes; bytes.bytes = ip_a.to_v6 ().to_bytes (); XXH64_state_t hash; XXH64_reset (&hash, 0); XXH64_update (&hash, bytes.bytes.data (), bytes.bytes.size ()); auto result (XXH64_digest (&hash)); return result; } namespace std { template <size_t size> struct endpoint_hash { }; template <> struct endpoint_hash<8> { size_t operator() (rai::endpoint const & endpoint_a) const { return endpoint_hash_raw (endpoint_a); } }; template <> struct endpoint_hash<4> { size_t operator() (rai::endpoint const & endpoint_a) const { uint64_t big (endpoint_hash_raw (endpoint_a)); uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32)); return result; } }; template <> struct hash<rai::endpoint> { size_t operator() (rai::endpoint const & endpoint_a) const { endpoint_hash<sizeof (size_t)> ehash; return ehash (endpoint_a); } }; template <size_t size> struct ip_address_hash { }; template <> struct ip_address_hash<8> { size_t operator() (boost::asio::ip::address const & ip_address_a) const { return ip_address_hash_raw (ip_address_a); } }; template <> struct ip_address_hash<4> { size_t operator() (boost::asio::ip::address const & ip_address_a) const { uint64_t big (ip_address_hash_raw (ip_address_a)); uint32_t result (static_cast<uint32_t> (big) ^ static_cast<uint32_t> (big >> 32)); return result; } }; template <> struct hash<boost::asio::ip::address> { size_t operator() (boost::asio::ip::address const & ip_a) const { ip_address_hash<sizeof (size_t)> ihash; return ihash (ip_a); } }; } namespace boost { template <> struct hash<rai::endpoint> { size_t operator() (rai::endpoint const & endpoint_a) const { std::hash<rai::endpoint> hash; return hash (endpoint_a); } }; } namespace rai { /** * Message types are serialized to the network and existing values must thus never change as * types are added, removed and reordered in the enum. */ enum class message_type : uint8_t { invalid = 0x0, not_a_type = 0x1, keepalive = 0x2, publish = 0x3, confirm_req = 0x4, confirm_ack = 0x5, bulk_pull = 0x6, bulk_push = 0x7, frontier_req = 0x8, bulk_pull_blocks = 0x9, node_id_handshake = 0x0a }; enum class bulk_pull_blocks_mode : uint8_t { list_blocks, checksum_blocks }; class message_visitor; class message_header { public: message_header (rai::message_type); message_header (bool &, rai::stream &); void serialize (rai::stream &); bool deserialize (rai::stream &); rai::block_type block_type () const; void block_type_set (rai::block_type); bool ipv4_only (); void ipv4_only_set (bool); static std::array<uint8_t, 2> constexpr magic_number = rai::rai_network == rai::rai_networks::rai_test_network ? std::array<uint8_t, 2>{ { 'R', 'A' } } : rai::rai_network == rai::rai_networks::rai_beta_network ? std::array<uint8_t, 2>{ { 'R', 'B' } } : std::array<uint8_t, 2>{ { 'R', 'C' } }; uint8_t version_max; uint8_t version_using; uint8_t version_min; rai::message_type type; std::bitset<16> extensions; static size_t constexpr ipv4_only_position = 1; static size_t constexpr bootstrap_server_position = 2; static std::bitset<16> constexpr block_type_mask = std::bitset<16> (0x0f00); }; class message { public: message (rai::message_type); message (rai::message_header const &); virtual ~message () = default; virtual void serialize (rai::stream &) = 0; virtual bool deserialize (rai::stream &) = 0; virtual void visit (rai::message_visitor &) const = 0; rai::message_header header; }; class work_pool; class message_parser { public: enum class parse_status { success, insufficient_work, invalid_header, invalid_message_type, invalid_keepalive_message, invalid_publish_message, invalid_confirm_req_message, invalid_confirm_ack_message, invalid_node_id_handshake_message, outdated_version }; message_parser (rai::message_visitor &, rai::work_pool &); void deserialize_buffer (uint8_t const *, size_t); void deserialize_keepalive (rai::stream &, rai::message_header const &); void deserialize_publish (rai::stream &, rai::message_header const &); void deserialize_confirm_req (rai::stream &, rai::message_header const &); void deserialize_confirm_ack (rai::stream &, rai::message_header const &); void deserialize_node_id_handshake (rai::stream &, rai::message_header const &); bool at_end (rai::stream &); rai::message_visitor & visitor; rai::work_pool & pool; parse_status status; }; class keepalive : public message { public: keepalive (bool &, rai::stream &, rai::message_header const &); keepalive (); void visit (rai::message_visitor &) const override; bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; bool operator== (rai::keepalive const &) const; std::array<rai::endpoint, 8> peers; }; class publish : public message { public: publish (bool &, rai::stream &, rai::message_header const &); publish (std::shared_ptr<rai::block>); void visit (rai::message_visitor &) const override; bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; bool operator== (rai::publish const &) const; std::shared_ptr<rai::block> block; }; class confirm_req : public message { public: confirm_req (bool &, rai::stream &, rai::message_header const &); confirm_req (std::shared_ptr<rai::block>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::confirm_req const &) const; std::shared_ptr<rai::block> block; }; class confirm_ack : public message { public: confirm_ack (bool &, rai::stream &, rai::message_header const &); confirm_ack (std::shared_ptr<rai::vote>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::confirm_ack const &) const; std::shared_ptr<rai::vote> vote; }; class frontier_req : public message { public: frontier_req (); frontier_req (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::frontier_req const &) const; rai::account start; uint32_t age; uint32_t count; }; class bulk_pull : public message { public: bulk_pull (); bulk_pull (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; rai::uint256_union start; rai::block_hash end; }; class bulk_pull_blocks : public message { public: bulk_pull_blocks (); bulk_pull_blocks (bool &, rai::stream &, rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; rai::block_hash min_hash; rai::block_hash max_hash; bulk_pull_blocks_mode mode; uint32_t max_count; }; class bulk_push : public message { public: bulk_push (); bulk_push (rai::message_header const &); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; }; class node_id_handshake : public message { public: node_id_handshake (bool &, rai::stream &, rai::message_header const &); node_id_handshake (boost::optional<rai::block_hash>, boost::optional<std::pair<rai::account, rai::signature>>); bool deserialize (rai::stream &) override; void serialize (rai::stream &) override; void visit (rai::message_visitor &) const override; bool operator== (rai::node_id_handshake const &) const; boost::optional<rai::uint256_union> query; boost::optional<std::pair<rai::account, rai::signature>> response; static size_t constexpr query_flag = 0; static size_t constexpr response_flag = 1; }; class message_visitor { public: virtual void keepalive (rai::keepalive const &) = 0; virtual void publish (rai::publish const &) = 0; virtual void confirm_req (rai::confirm_req const &) = 0; virtual void confirm_ack (rai::confirm_ack const &) = 0; virtual void bulk_pull (rai::bulk_pull const &) = 0; virtual void bulk_pull_blocks (rai::bulk_pull_blocks const &) = 0; virtual void bulk_push (rai::bulk_push const &) = 0; virtual void frontier_req (rai::frontier_req const &) = 0; virtual void node_id_handshake (rai::node_id_handshake const &) = 0; virtual ~message_visitor (); }; /** * Returns seconds passed since unix epoch (posix time) */ inline uint64_t seconds_since_epoch () { return std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now ().time_since_epoch ()).count (); } } <|endoftext|>
<commit_before>/** \file RegexMatcher.cc * \brief Implementation of the RegexMatcher class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015,2017,2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "RegexMatcher.h" #include <unordered_map> #include "Compiler.h" #include "util.h" bool RegexMatcher::utf8_configured_; bool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg, ::pcre_extra **pcre_extra_arg, std::string * const err_msg) { if (err_msg != nullptr) err_msg->clear(); const char *errptr; int erroffset; int pcre_options(0); if (options & RegexMatcher::ENABLE_UTF8) pcre_options |= PCRE_UTF8; if (options & RegexMatcher::CASE_INSENSITIVE) pcre_options |= PCRE_CASELESS; if (options & RegexMatcher::MULTILINE) pcre_options |= PCRE_MULTILINE; *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr); if (*pcre_arg == nullptr) { *pcre_extra_arg = nullptr; if (err_msg != nullptr) *err_msg = "failed to compile invalid regular expression: \"" + pattern + "\"! (" + std::string(errptr) + ")"; return false; } // Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe. *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr); if (*pcre_extra_arg == nullptr and errptr != nullptr) { ::pcre_free(*pcre_arg); *pcre_arg = nullptr; if (err_msg != nullptr) *err_msg = "failed to \"study\" the compiled pattern \"" + pattern + "\"! (" + std::string(errptr) + ")"; return false; } return true; } RegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg, const unsigned options) { // Make sure the PCRE library supports UTF8: if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) { int utf8_available; if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) { if (err_msg != nullptr) *err_msg = "PCRE library does not know PCRE_CONFIG_UTF8!"; return nullptr; } if (utf8_available != 1) { if (err_msg != nullptr) *err_msg = "This version of the PCRE library does not support UTF8!"; return nullptr; } RegexMatcher::utf8_configured_ = true; } ::pcre *pcre_ptr; ::pcre_extra *pcre_extra_ptr; if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg)) { if (err_msg != nullptr and err_msg->empty()) *err_msg = "failed to compile pattern: \"" + pattern + "\""; return nullptr; } return new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr); } RegexMatcher *RegexMatcher::RegexMatcherFactoryOrDie(const std::string &regex, const unsigned options) { std::string error_message; RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options)); if (regex_matcher == nullptr or not error_message.empty()) LOG_ERROR("failed to compile regex \"" + regex + "\": " + error_message); return regex_matcher; } RegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) { if (this == &that) return; if (that.pcre_ == nullptr) { pcre_ = nullptr; pcre_extra_ = nullptr; } else { std::string err_msg; if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg)) logger->error("In RegexMatcher copy constructor: unexpected error: " + err_msg); substr_vector_ = that.substr_vector_; last_match_count_ = that.last_match_count_; } } RegexMatcher::RegexMatcher(RegexMatcher &&that) : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_), pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)), substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_) { that.pcre_ = nullptr; that.pcre_extra_ = nullptr; } bool RegexMatcher::matched(const std::string &subject, const size_t subject_start_offset, std::string * const err_msg, size_t * const start_pos, size_t * const end_pos) { if (err_msg != nullptr) err_msg->clear(); const int retcode(::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), subject_start_offset, 0, &substr_vector_[0], substr_vector_.size())); if (retcode == 0) { if (err_msg != nullptr) *err_msg = "Too many captured substrings! (We only support " + std::to_string(substr_vector_.size() / 3 - 1) + " substrings.)"; return false; } if (retcode > 0) { last_match_count_ = retcode; last_subject_ = subject; if (start_pos != nullptr) *start_pos = substr_vector_[0]; if (end_pos != nullptr) *end_pos = substr_vector_[1]; return true; } if (retcode != PCRE_ERROR_NOMATCH) { if (retcode == PCRE_ERROR_BADUTF8) { if (err_msg != nullptr) *err_msg = "A \"subject\" with invalid UTF-8 was passed into RegexMatcher::matched()!"; } else if (err_msg != nullptr) *err_msg = "Unknown error!"; } return false; } std::string RegexMatcher::replaceAll(const std::string &subject, const std::string &replacement) { if (not matched(subject)) return subject; std::string replaced_string; // the matches need to be sequentially sorted from left to right size_t subject_start_offset(0), match_start_offset(0), match_end_offset(0); while (subject_start_offset < subject.length() and matched(subject, subject_start_offset, /* err_msg */ nullptr, &match_start_offset, &match_end_offset)) { replaced_string += subject.substr(subject_start_offset, match_start_offset - subject_start_offset); replaced_string += replacement; subject_start_offset = match_end_offset; } return replaced_string; } bool RegexMatcher::Matched(const std::string &regex, const std::string &subject, const unsigned options, std::string * const err_msg, size_t * const start_pos, size_t * const end_pos) { static std::unordered_map<std::string, RegexMatcher *> regex_to_matcher_map; const std::string KEY(regex + ":" + std::to_string(options)); const auto regex_and_matcher(regex_to_matcher_map.find(KEY)); if (regex_and_matcher != regex_to_matcher_map.cend()) return regex_and_matcher->second->matched(subject, err_msg, start_pos, end_pos); RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex, err_msg, options)); if (matcher == nullptr) LOG_ERROR("Failed to compile pattern \"" + regex + "\": " + *err_msg); regex_to_matcher_map[KEY] = matcher; return matcher->matched(subject, err_msg, start_pos, end_pos); } std::string RegexMatcher::operator[](const unsigned group) const { if (unlikely(group >= last_match_count_)) throw std::out_of_range("in RegexMatcher::operator[]: group(" + std::to_string(group) + ") >= " + std::to_string(last_match_count_) + "!"); const unsigned first_index(group * 2); const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]); return (substring_length == 0) ? "" : last_subject_.substr(substr_vector_[first_index], substring_length); } <commit_msg>RegexMatcher: fix infinite loop in replaceAll()<commit_after>/** \file RegexMatcher.cc * \brief Implementation of the RegexMatcher class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015,2017,2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "RegexMatcher.h" #include <unordered_map> #include "Compiler.h" #include "util.h" bool RegexMatcher::utf8_configured_; bool CompileRegex(const std::string &pattern, const unsigned options, ::pcre **pcre_arg, ::pcre_extra **pcre_extra_arg, std::string * const err_msg) { if (err_msg != nullptr) err_msg->clear(); const char *errptr; int erroffset; int pcre_options(0); if (options & RegexMatcher::ENABLE_UTF8) pcre_options |= PCRE_UTF8; if (options & RegexMatcher::CASE_INSENSITIVE) pcre_options |= PCRE_CASELESS; if (options & RegexMatcher::MULTILINE) pcre_options |= PCRE_MULTILINE; *pcre_arg = ::pcre_compile(pattern.c_str(), pcre_options, &errptr, &erroffset, nullptr); if (*pcre_arg == nullptr) { *pcre_extra_arg = nullptr; if (err_msg != nullptr) *err_msg = "failed to compile invalid regular expression: \"" + pattern + "\"! (" + std::string(errptr) + ")"; return false; } // Can't use PCRE_STUDY_JIT_COMPILE because it's not thread safe. *pcre_extra_arg = ::pcre_study(*pcre_arg, 0, &errptr); if (*pcre_extra_arg == nullptr and errptr != nullptr) { ::pcre_free(*pcre_arg); *pcre_arg = nullptr; if (err_msg != nullptr) *err_msg = "failed to \"study\" the compiled pattern \"" + pattern + "\"! (" + std::string(errptr) + ")"; return false; } return true; } RegexMatcher *RegexMatcher::RegexMatcherFactory(const std::string &pattern, std::string * const err_msg, const unsigned options) { // Make sure the PCRE library supports UTF8: if ((options & RegexMatcher::ENABLE_UTF8) and not RegexMatcher::utf8_configured_) { int utf8_available; if (::pcre_config(PCRE_CONFIG_UTF8, reinterpret_cast<void *>(&utf8_available)) == PCRE_ERROR_BADOPTION) { if (err_msg != nullptr) *err_msg = "PCRE library does not know PCRE_CONFIG_UTF8!"; return nullptr; } if (utf8_available != 1) { if (err_msg != nullptr) *err_msg = "This version of the PCRE library does not support UTF8!"; return nullptr; } RegexMatcher::utf8_configured_ = true; } ::pcre *pcre_ptr; ::pcre_extra *pcre_extra_ptr; if (not CompileRegex(pattern, options, &pcre_ptr, &pcre_extra_ptr, err_msg)) { if (err_msg != nullptr and err_msg->empty()) *err_msg = "failed to compile pattern: \"" + pattern + "\""; return nullptr; } return new RegexMatcher(pattern, options, pcre_ptr, pcre_extra_ptr); } RegexMatcher *RegexMatcher::RegexMatcherFactoryOrDie(const std::string &regex, const unsigned options) { std::string error_message; RegexMatcher *regex_matcher(RegexMatcher::RegexMatcherFactory(regex, &error_message, options)); if (regex_matcher == nullptr or not error_message.empty()) LOG_ERROR("failed to compile regex \"" + regex + "\": " + error_message); return regex_matcher; } RegexMatcher::RegexMatcher(const RegexMatcher &that): pattern_(that.pattern_) { if (this == &that) return; if (that.pcre_ == nullptr) { pcre_ = nullptr; pcre_extra_ = nullptr; } else { std::string err_msg; if (not CompileRegex(pattern_, that.options_, &pcre_, &pcre_extra_, &err_msg)) logger->error("In RegexMatcher copy constructor: unexpected error: " + err_msg); substr_vector_ = that.substr_vector_; last_match_count_ = that.last_match_count_; } } RegexMatcher::RegexMatcher(RegexMatcher &&that) : pattern_(std::move(that.pattern_)), options_(that.options_), pcre_(that.pcre_), pcre_extra_(that.pcre_extra_), last_subject_(std::move(that.last_subject_)), substr_vector_(std::move(that.substr_vector_)), last_match_count_(that.last_match_count_) { that.pcre_ = nullptr; that.pcre_extra_ = nullptr; } bool RegexMatcher::matched(const std::string &subject, const size_t subject_start_offset, std::string * const err_msg, size_t * const start_pos, size_t * const end_pos) { if (err_msg != nullptr) err_msg->clear(); const int retcode(::pcre_exec(pcre_, pcre_extra_, subject.data(), subject.length(), subject_start_offset, 0, &substr_vector_[0], substr_vector_.size())); if (retcode == 0) { if (err_msg != nullptr) *err_msg = "Too many captured substrings! (We only support " + std::to_string(substr_vector_.size() / 3 - 1) + " substrings.)"; return false; } if (retcode > 0) { last_match_count_ = retcode; last_subject_ = subject; if (start_pos != nullptr) *start_pos = substr_vector_[0]; if (end_pos != nullptr) *end_pos = substr_vector_[1]; return true; } if (retcode != PCRE_ERROR_NOMATCH) { if (retcode == PCRE_ERROR_BADUTF8) { if (err_msg != nullptr) *err_msg = "A \"subject\" with invalid UTF-8 was passed into RegexMatcher::matched()!"; } else if (err_msg != nullptr) *err_msg = "Unknown error!"; } return false; } std::string RegexMatcher::replaceAll(const std::string &subject, const std::string &replacement) { if (not matched(subject)) return subject; std::string replaced_string; // the matches need to be sequentially sorted from left to right size_t subject_start_offset(0), match_start_offset(0), match_end_offset(0); while (subject_start_offset < subject.length() and matched(subject, subject_start_offset, /* err_msg */ nullptr, &match_start_offset, &match_end_offset)) { if (subject_start_offset == match_start_offset and subject_start_offset == match_end_offset) { replaced_string += subject[subject_start_offset++]; continue; } replaced_string += subject.substr(subject_start_offset, match_start_offset - subject_start_offset); replaced_string += replacement; subject_start_offset = match_end_offset; } return replaced_string; } bool RegexMatcher::Matched(const std::string &regex, const std::string &subject, const unsigned options, std::string * const err_msg, size_t * const start_pos, size_t * const end_pos) { static std::unordered_map<std::string, RegexMatcher *> regex_to_matcher_map; const std::string KEY(regex + ":" + std::to_string(options)); const auto regex_and_matcher(regex_to_matcher_map.find(KEY)); if (regex_and_matcher != regex_to_matcher_map.cend()) return regex_and_matcher->second->matched(subject, err_msg, start_pos, end_pos); RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(regex, err_msg, options)); if (matcher == nullptr) LOG_ERROR("Failed to compile pattern \"" + regex + "\": " + *err_msg); regex_to_matcher_map[KEY] = matcher; return matcher->matched(subject, err_msg, start_pos, end_pos); } std::string RegexMatcher::operator[](const unsigned group) const { if (unlikely(group >= last_match_count_)) throw std::out_of_range("in RegexMatcher::operator[]: group(" + std::to_string(group) + ") >= " + std::to_string(last_match_count_) + "!"); const unsigned first_index(group * 2); const unsigned substring_length(substr_vector_[first_index + 1] - substr_vector_[first_index]); return (substring_length == 0) ? "" : last_subject_.substr(substr_vector_[first_index], substring_length); } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> // Local includes #include "libmesh/diva_io.h" #include "libmesh/boundary_mesh.h" #include "libmesh/mesh_tools.h" #include "libmesh/elem.h" #include "libmesh/boundary_info.h" namespace libMesh { // ------------------------------------------------------------ // DivaIO class members void DivaIO::write (const std::string& fname) { // We may need to gather a ParallelMesh to output it, making that // const qualifier in our constructor a dirty lie MeshSerializer serialize(const_cast<MeshBase&>(this->mesh()), !_is_parallel_format); // Open the output file stream std::ofstream out(fname.c_str()); // Make sure it opened correctly if (!out.good()) libmesh_file_error(fname.c_str()); this->write_stream (out); } void DivaIO::write_stream (std::ostream& out) { /* From Kelly: (kelly@tacc.utexas.edu) Ok, the following is the format: #points #triangles #quads #tets #prisms #pyramids #hexs loop over all points (written out x y z x y z ...) loop over all triangles (written out i1 i2 i3) (These are indices into the points going from 1 to #points) loop over all quads (written out i1 i2 i3 i4) (Same numbering scheme) loop over all triangles and quads (write out b1) (This is a boundary condition for each triangle and each hex. You can put anything you want here) loop over all tets (written out i1 i2 i3 i4) (Same) loop over all pyramids (written out i1 i2 i3 i4 i5) (Same) loop over all prisms (written out i1 i2 i3 i4 i5 i6) (Same) loop over all hexs (written out i1 i2 i3 i4 i5 i6 i7 i8) (Same) */ // Be sure the stream has been created successfully. libmesh_assert (out.good()); // Can't use a constant mesh reference since we have to // sync the boundary info. libmesh_here(); libMesh::err << "WARNING... Sure you want to do this?" << std::endl; MeshBase& mesh = const_cast<MeshBase&> (MeshOutput<MeshBase>::mesh()); if (mesh.mesh_dimension() < 3) { libMesh::err << "WARNING: DIVA only supports 3D meshes.\n\n" << "Exiting without producing output.\n"; return; } BoundaryMesh boundary_mesh (mesh.mesh_dimension()-1); mesh.boundary_info->sync(boundary_mesh); /** * Write the header */ out << mesh.n_nodes() << " " << (MeshTools::n_active_elem_of_type(boundary_mesh,TRI3) + MeshTools::n_active_elem_of_type(boundary_mesh,TRI6)*4) << " " << (MeshTools::n_active_elem_of_type(boundary_mesh, QUAD4) + MeshTools::n_active_elem_of_type(boundary_mesh, QUAD8) + MeshTools::n_active_elem_of_type(boundary_mesh, QUAD9)*4) << " " << (MeshTools::n_active_elem_of_type(mesh, TET4) + MeshTools::n_active_elem_of_type(mesh, TET10)*8) << " " << MeshTools::n_active_elem_of_type(mesh, PYRAMID5) << " " << (MeshTools::n_active_elem_of_type(mesh, PRISM6) + MeshTools::n_active_elem_of_type(mesh, PRISM18)*8) << " " << (MeshTools::n_active_elem_of_type(mesh, HEX8) + MeshTools::n_active_elem_of_type(mesh, HEX20) + MeshTools::n_active_elem_of_type(mesh, HEX27)*8) << " " << '\n'; boundary_mesh.clear(); /** * Write the nodes */ for (unsigned int v=0; v<mesh.n_nodes(); v++) mesh.point(v).write_unformatted(out); /** * Write the BC faces */ { /** * Write the triangles */ for(unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) for (unsigned int s=0; s<mesh.elem(e)->n_sides(); s++) if (mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(mesh.elem(e)->build_side(s)); if (side->type() == TRI3) { out << side->node(0)+1 << " " << side->node(1)+1 << " " << side->node(2)+1 << '\n'; } else if (side->type() == TRI6) { out << side->node(0)+1 << " " << side->node(3)+1 << " " << side->node(5)+1 << '\n' << side->node(3)+1 << " " << side->node(1)+1 << " " << side->node(4)+1 << '\n' << side->node(5)+1 << " " << side->node(4)+1 << " " << side->node(2)+1 << '\n' << side->node(3)+1 << " " << side->node(4)+1 << " " << side->node(5)+1 << '\n'; } } /** * Write the quadrilaterals */ for(unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) for (unsigned int s=0; s<mesh.elem(e)->n_sides(); s++) if (mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(mesh.elem(e)->build_side(s)); if ((side->type() == QUAD4) || (side->type() == QUAD8) ) { out << side->node(0)+1 << " " << side->node(1)+1 << " " << side->node(2)+1 << " " << side->node(3)+1 << '\n'; } else if (side->type() == QUAD9) { out << side->node(0)+1 << " " << side->node(4)+1 << " " << side->node(8)+1 << " " << side->node(7)+1 << '\n' << side->node(4)+1 << " " << side->node(1)+1 << " " << side->node(5)+1 << " " << side->node(8)+1 << '\n' << side->node(7)+1 << " " << side->node(8)+1 << " " << side->node(6)+1 << " " << side->node(3)+1 << '\n' << side->node(8)+1 << " " << side->node(5)+1 << " " << side->node(2)+1 << " " << side->node(6)+1 << '\n'; } } } /** * Write the BC IDs */ { /** * Write the triangles */ for(unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) for (unsigned int s=0; s<mesh.elem(e)->n_sides(); s++) if (mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(mesh.elem(e)->build_side(s)); if ((side->type() == TRI3) || (side->type() == TRI6) ) out << mesh.boundary_info->boundary_id(mesh.elem(e), s) << '\n'; } /** * Write the quadrilaterals */ for(unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) for (unsigned int s=0; s<mesh.elem(e)->n_sides(); s++) if (mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(mesh.elem(e)->build_side(s)); if ((side->type() == QUAD4) || (side->type() == QUAD8) || (side->type() == QUAD9) ) out << mesh.boundary_info->boundary_id(mesh.elem(e), s); } } /** * Write all the Tets */ for (unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) { if (mesh.elem(e)->type() == TET4) { out << mesh.elem(e)->node(0)+1 << " " << mesh.elem(e)->node(1)+1 << " " << mesh.elem(e)->node(2)+1 << " " << mesh.elem(e)->node(3)+1 << '\n'; } else if (mesh.elem(e)->type() == TET10) { out << mesh.elem(e)->node(0)+1 << " " << mesh.elem(e)->node(4)+1 << " " << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(7)+1 << '\n'; out << mesh.elem(e)->node(4)+1 << " " << mesh.elem(e)->node(1)+1 << " " << mesh.elem(e)->node(5)+1 << " " << mesh.elem(e)->node(8)+1 << '\n'; out << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(5)+1 << " " << mesh.elem(e)->node(2)+1 << " " << mesh.elem(e)->node(9)+1 << '\n'; out << mesh.elem(e)->node(7)+1 << " " << mesh.elem(e)->node(8)+1 << " " << mesh.elem(e)->node(9)+1 << " " << mesh.elem(e)->node(3)+1 << '\n'; out << mesh.elem(e)->node(4)+1 << " " << mesh.elem(e)->node(8)+1 << " " << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(7)+1 << '\n'; out << mesh.elem(e)->node(4)+1 << " " << mesh.elem(e)->node(5)+1 << " " << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(8)+1 << '\n'; out << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(5)+1 << " " << mesh.elem(e)->node(9)+1 << " " << mesh.elem(e)->node(8)+1 << '\n'; out << mesh.elem(e)->node(6)+1 << " " << mesh.elem(e)->node(8)+1 << " " << mesh.elem(e)->node(9)+1 << " " << mesh.elem(e)->node(7)+1 << '\n'; } } /** * Write all the Pyramids */ for (unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) if (mesh.elem(e)->type() == PYRAMID5) { out << mesh.elem(e)->node(0)+1 << " " << mesh.elem(e)->node(1)+1 << " " << mesh.elem(e)->node(2)+1 << " " << mesh.elem(e)->node(3)+1 << " " << mesh.elem(e)->node(4)+1 << '\n'; } /** * Write all the Prisms */ for (unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) { if (mesh.elem(e)->type() == PRISM6) { out << mesh.elem(e)->node(0)+1 << " " << mesh.elem(e)->node(1)+1 << " " << mesh.elem(e)->node(2)+1 << " " << mesh.elem(e)->node(3)+1 << " " << mesh.elem(e)->node(4)+1 << " " << mesh.elem(e)->node(5)+1 << '\n'; } else if (mesh.elem(e)->type() == PRISM18) { libmesh_error(); } } /** * Write all the Hexes */ for (unsigned int e=0; e<mesh.n_elem(); e++) if (mesh.elem(e)->active()) if ((mesh.elem(e)->type() == HEX8) || (mesh.elem(e)->type() == HEX20) || (mesh.elem(e)->type() == HEX27) ) { std::vector<dof_id_type> conn; for (unsigned int se=0; se<mesh.elem(e)->n_sub_elem(); se++) { mesh.elem(e)->connectivity(se, TECPLOT, conn); out << conn[0] << " " << conn[1] << " " << conn[2] << " " << conn[3] << " " << conn[4] << " " << conn[5] << " " << conn[6] << " " << conn[7] << '\n'; } } } } // namespace libMesh <commit_msg>Changes in diva_io.C for -Wshadow.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> // Local includes #include "libmesh/diva_io.h" #include "libmesh/boundary_mesh.h" #include "libmesh/mesh_tools.h" #include "libmesh/elem.h" #include "libmesh/boundary_info.h" namespace libMesh { // ------------------------------------------------------------ // DivaIO class members void DivaIO::write (const std::string& fname) { // We may need to gather a ParallelMesh to output it, making that // const qualifier in our constructor a dirty lie MeshSerializer serialize(const_cast<MeshBase&>(this->mesh()), !_is_parallel_format); // Open the output file stream std::ofstream out_file(fname.c_str()); // Make sure it opened correctly if (!out_file.good()) libmesh_file_error(fname.c_str()); this->write_stream (out_file); } void DivaIO::write_stream (std::ostream& out_file) { /* From Kelly: (kelly@tacc.utexas.edu) Ok, the following is the format: #points #triangles #quads #tets #prisms #pyramids #hexs loop over all points (written out x y z x y z ...) loop over all triangles (written out i1 i2 i3) (These are indices into the points going from 1 to #points) loop over all quads (written out i1 i2 i3 i4) (Same numbering scheme) loop over all triangles and quads (write out b1) (This is a boundary condition for each triangle and each hex. You can put anything you want here) loop over all tets (written out i1 i2 i3 i4) (Same) loop over all pyramids (written out i1 i2 i3 i4 i5) (Same) loop over all prisms (written out i1 i2 i3 i4 i5 i6) (Same) loop over all hexs (written out i1 i2 i3 i4 i5 i6 i7 i8) (Same) */ // Be sure the stream has been created successfully. libmesh_assert (out_file.good()); // Can't use a constant mesh reference since we have to // sync the boundary info. libmesh_here(); libMesh::err << "WARNING... Sure you want to do this?" << std::endl; MeshBase& the_mesh = const_cast<MeshBase&> (MeshOutput<MeshBase>::mesh()); if (the_mesh.mesh_dimension() < 3) { libMesh::err << "WARNING: DIVA only supports 3D meshes.\n\n" << "Exiting without producing output.\n"; return; } BoundaryMesh boundary_mesh (the_mesh.mesh_dimension()-1); the_mesh.boundary_info->sync(boundary_mesh); /** * Write the header */ out_file << the_mesh.n_nodes() << ' ' << (MeshTools::n_active_elem_of_type(boundary_mesh,TRI3) + MeshTools::n_active_elem_of_type(boundary_mesh,TRI6)*4) << ' ' << (MeshTools::n_active_elem_of_type(boundary_mesh, QUAD4) + MeshTools::n_active_elem_of_type(boundary_mesh, QUAD8) + MeshTools::n_active_elem_of_type(boundary_mesh, QUAD9)*4) << ' ' << (MeshTools::n_active_elem_of_type(the_mesh, TET4) + MeshTools::n_active_elem_of_type(the_mesh, TET10)*8) << ' ' << MeshTools::n_active_elem_of_type(the_mesh, PYRAMID5) << ' ' << (MeshTools::n_active_elem_of_type(the_mesh, PRISM6) + MeshTools::n_active_elem_of_type(the_mesh, PRISM18)*8) << ' ' << (MeshTools::n_active_elem_of_type(the_mesh, HEX8) + MeshTools::n_active_elem_of_type(the_mesh, HEX20) + MeshTools::n_active_elem_of_type(the_mesh, HEX27)*8) << ' ' << '\n'; boundary_mesh.clear(); /** * Write the nodes */ for (unsigned int v=0; v<the_mesh.n_nodes(); v++) the_mesh.point(v).write_unformatted(out_file); /** * Write the BC faces */ { /** * Write the triangles */ for(unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) for (unsigned int s=0; s<the_mesh.elem(e)->n_sides(); s++) if (the_mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(the_mesh.elem(e)->build_side(s)); if (side->type() == TRI3) { out_file << side->node(0)+1 << " " << side->node(1)+1 << " " << side->node(2)+1 << '\n'; } else if (side->type() == TRI6) { out_file << side->node(0)+1 << " " << side->node(3)+1 << " " << side->node(5)+1 << '\n' << side->node(3)+1 << " " << side->node(1)+1 << " " << side->node(4)+1 << '\n' << side->node(5)+1 << " " << side->node(4)+1 << " " << side->node(2)+1 << '\n' << side->node(3)+1 << " " << side->node(4)+1 << " " << side->node(5)+1 << '\n'; } } /** * Write the quadrilaterals */ for(unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) for (unsigned int s=0; s<the_mesh.elem(e)->n_sides(); s++) if (the_mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(the_mesh.elem(e)->build_side(s)); if ((side->type() == QUAD4) || (side->type() == QUAD8) ) { out_file << side->node(0)+1 << " " << side->node(1)+1 << " " << side->node(2)+1 << " " << side->node(3)+1 << '\n'; } else if (side->type() == QUAD9) { out_file << side->node(0)+1 << " " << side->node(4)+1 << " " << side->node(8)+1 << " " << side->node(7)+1 << '\n' << side->node(4)+1 << " " << side->node(1)+1 << " " << side->node(5)+1 << " " << side->node(8)+1 << '\n' << side->node(7)+1 << " " << side->node(8)+1 << " " << side->node(6)+1 << " " << side->node(3)+1 << '\n' << side->node(8)+1 << " " << side->node(5)+1 << " " << side->node(2)+1 << " " << side->node(6)+1 << '\n'; } } } /** * Write the BC IDs */ { /** * Write the triangles */ for(unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) for (unsigned int s=0; s<the_mesh.elem(e)->n_sides(); s++) if (the_mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(the_mesh.elem(e)->build_side(s)); if ((side->type() == TRI3) || (side->type() == TRI6) ) out_file << the_mesh.boundary_info->boundary_id(the_mesh.elem(e), s) << '\n'; } /** * Write the quadrilaterals */ for(unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) for (unsigned int s=0; s<the_mesh.elem(e)->n_sides(); s++) if (the_mesh.elem(e)->neighbor(s) == NULL) { const AutoPtr<Elem> side(the_mesh.elem(e)->build_side(s)); if ((side->type() == QUAD4) || (side->type() == QUAD8) || (side->type() == QUAD9)) out_file << the_mesh.boundary_info->boundary_id(the_mesh.elem(e), s); } } /** * Write all the Tets */ for (unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) { if (the_mesh.elem(e)->type() == TET4) { out_file << the_mesh.elem(e)->node(0)+1 << " " << the_mesh.elem(e)->node(1)+1 << " " << the_mesh.elem(e)->node(2)+1 << " " << the_mesh.elem(e)->node(3)+1 << '\n'; } else if (the_mesh.elem(e)->type() == TET10) { out_file << the_mesh.elem(e)->node(0)+1 << " " << the_mesh.elem(e)->node(4)+1 << " " << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(7)+1 << '\n'; out_file << the_mesh.elem(e)->node(4)+1 << " " << the_mesh.elem(e)->node(1)+1 << " " << the_mesh.elem(e)->node(5)+1 << " " << the_mesh.elem(e)->node(8)+1 << '\n'; out_file << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(5)+1 << " " << the_mesh.elem(e)->node(2)+1 << " " << the_mesh.elem(e)->node(9)+1 << '\n'; out_file << the_mesh.elem(e)->node(7)+1 << " " << the_mesh.elem(e)->node(8)+1 << " " << the_mesh.elem(e)->node(9)+1 << " " << the_mesh.elem(e)->node(3)+1 << '\n'; out_file << the_mesh.elem(e)->node(4)+1 << " " << the_mesh.elem(e)->node(8)+1 << " " << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(7)+1 << '\n'; out_file << the_mesh.elem(e)->node(4)+1 << " " << the_mesh.elem(e)->node(5)+1 << " " << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(8)+1 << '\n'; out_file << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(5)+1 << " " << the_mesh.elem(e)->node(9)+1 << " " << the_mesh.elem(e)->node(8)+1 << '\n'; out_file << the_mesh.elem(e)->node(6)+1 << " " << the_mesh.elem(e)->node(8)+1 << " " << the_mesh.elem(e)->node(9)+1 << " " << the_mesh.elem(e)->node(7)+1 << '\n'; } } /** * Write all the Pyramids */ for (unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) if (the_mesh.elem(e)->type() == PYRAMID5) { out_file << the_mesh.elem(e)->node(0)+1 << " " << the_mesh.elem(e)->node(1)+1 << " " << the_mesh.elem(e)->node(2)+1 << " " << the_mesh.elem(e)->node(3)+1 << " " << the_mesh.elem(e)->node(4)+1 << '\n'; } /** * Write all the Prisms */ for (unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) { if (the_mesh.elem(e)->type() == PRISM6) { out_file << the_mesh.elem(e)->node(0)+1 << " " << the_mesh.elem(e)->node(1)+1 << " " << the_mesh.elem(e)->node(2)+1 << " " << the_mesh.elem(e)->node(3)+1 << " " << the_mesh.elem(e)->node(4)+1 << " " << the_mesh.elem(e)->node(5)+1 << '\n'; } else if (the_mesh.elem(e)->type() == PRISM18) { libmesh_error(); } } /** * Write all the Hexes */ for (unsigned int e=0; e<the_mesh.n_elem(); e++) if (the_mesh.elem(e)->active()) if ((the_mesh.elem(e)->type() == HEX8) || (the_mesh.elem(e)->type() == HEX20) || (the_mesh.elem(e)->type() == HEX27) ) { std::vector<dof_id_type> conn; for (unsigned int se=0; se<the_mesh.elem(e)->n_sub_elem(); se++) { the_mesh.elem(e)->connectivity(se, TECPLOT, conn); out_file << conn[0] << ' ' << conn[1] << ' ' << conn[2] << ' ' << conn[3] << ' ' << conn[4] << ' ' << conn[5] << ' ' << conn[6] << ' ' << conn[7] << '\n'; } } } } // namespace libMesh <|endoftext|>
<commit_before>#include "FImage.h" #include <sys/time.h> using namespace FImage; int main(int argc, char **argv) { Var x; Func f, g; printf("Defining function...\n"); f(x) = 2.0f; g(x) = f(x+1) + f(x-1); Var xo, xi; g.split(x, xo, xi, 4); //f.chunk(xi); f.chunk(xi, Range(xo*4, 4)); //f.vectorize(x); //g.vectorize(xi); printf("Realizing function...\n"); Image im = g.realize(1024); return 0; } <commit_msg>add template<commit_after>#include "FImage.h" #include <sys/time.h> using namespace FImage; int main(int argc, char **argv) { Var x; Func f, g; printf("Defining function...\n"); f(x) = 2.0f; g(x) = f(x+1) + f(x-1); Var xo, xi; g.split(x, xo, xi, 4); //f.chunk(xi); f.chunk(xi, Range(xo*4, 4)); //f.vectorize(x); //g.vectorize(xi); printf("Realizing function...\n"); Image<double> im = g.realize(1024); return 0; } <|endoftext|>
<commit_before>// // yas_operation.cpp // #include "yas_operation.h" #include <atomic> #include <deque> #include <mutex> #include <thread> #include <vector> #include "yas_stl_utils.h" using namespace yas; #pragma mark - operation class operation::impl : public base::impl, public controllable_operation::impl { public: std::atomic<bool> canceled; operation_option_t option; impl(execution_f const &exe, operation_option_t &&option) : canceled(false), execution(exe), option(std::move(option)) { } impl(execution_f &&exe, operation_option_t &&option) : canceled(false), execution(std::move(exe)), option(std::move(option)) { } void execute() { if (execution) { if (!canceled) { execution(cast<operation>()); } } } void cancel() { canceled = true; } private: execution_f execution; }; operation::operation(execution_f const &exe, operation_option_t option) : base(std::make_unique<impl>(exe, std::move(option))) { } operation::operation(execution_f &&exe, operation_option_t opt) : base(std::make_unique<impl>(std::move(exe), std::move(opt))) { } operation::operation(std::nullptr_t) : base(nullptr) { } void operation::cancel() { impl_ptr<impl>()->cancel(); } bool operation::is_canceled() const { return impl_ptr<impl>()->canceled; } operation_option_t const &operation::option() const { return impl_ptr<impl>()->option; } controllable_operation operation::controllable() const { return controllable_operation{impl_ptr<controllable_operation::impl>()}; } #pragma mark - queue class operation_queue::impl : public base::impl { public: impl(size_t const count) : _operations(count) { } ~impl() { cancel(); } void push_back(operation &&op) { std::lock_guard<std::recursive_mutex> lock(_mutex); auto &cancel_id = op.option().push_cancel_id; for (auto &dq : _operations) { erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; }); } if (_current_operation) { if (_current_operation.option().push_cancel_id == cancel_id) { _current_operation.cancel(); } } auto &dq = _operations.at(op.option().priority); dq.emplace_back(std::move(op)); _start_next_operation_if_needed(); } void push_front(operation &&op) { std::lock_guard<std::recursive_mutex> lock(_mutex); auto &cancel_id = op.option().push_cancel_id; for (auto &dq : _operations) { erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; }); } if (_current_operation) { if (_current_operation.option().push_cancel_id == cancel_id) { _current_operation.cancel(); } } auto &dq = _operations.at(op.option().priority); dq.emplace_front(std::move(op)); _start_next_operation_if_needed(); } void cancel(operation const &operation) { std::lock_guard<std::recursive_mutex> lock(_mutex); for (auto &dq : _operations) { for (auto &op : dq) { if (operation == op) { op.cancel(); } } } if (_current_operation) { if (_current_operation == operation) { _current_operation.cancel(); } } } void cancel() { std::lock_guard<std::recursive_mutex> lock(_mutex); for (auto &dq : _operations) { for (auto &op : dq) { op.cancel(); } dq.clear(); } if (_current_operation) { _current_operation.cancel(); } } void wait_until_all_operations_are_finished() { while (true) { std::lock_guard<std::recursive_mutex> lock(_mutex); bool op_exists = _current_operation != nullptr; if (!op_exists) { for (auto &dq : _operations) { if (dq.size() > 0) { op_exists = true; } } } if (op_exists) { if (_suspended) { throw "operation_queue is suspended."; } std::this_thread::yield(); } else { break; } } } void suspend() { std::lock_guard<std::recursive_mutex> lock(_mutex); _suspended = true; } void resume() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_suspended) { _suspended = false; _start_next_operation_if_needed(); } } bool is_suspended() const { return _suspended; } bool is_operating() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_current_operation) { return true; } for (auto const &dq : _operations) { if (dq.size() > 0) { return true; } } return false; } private: operation _current_operation = nullptr; std::vector<std::deque<operation>> _operations; bool _suspended = false; mutable std::recursive_mutex _mutex; void _start_next_operation_if_needed() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (!_current_operation && !_suspended) { operation op{nullptr}; for (auto &dq : _operations) { if (!dq.empty()) { op = dq.front(); dq.pop_front(); break; } } if (op) { _current_operation = op; auto weak_ope = to_weak(op); auto weak_queue = to_weak(cast<operation_queue>()); std::thread thread{[weak_ope, weak_queue]() { auto ope = weak_ope.lock(); if (ope) { ope.controllable().execute(); if (auto queue = weak_queue.lock()) { queue.impl_ptr<impl>()->_operation_did_finish(ope); } } }}; thread.detach(); } } } void _operation_did_finish(operation const &prev_op) { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_current_operation == prev_op) { _current_operation = nullptr; } _start_next_operation_if_needed(); } }; operation_queue::operation_queue(size_t const count) : base(std::make_unique<impl>(count)) { } operation_queue::operation_queue(std::nullptr_t) : base(nullptr) { } void operation_queue::push_back(operation op) { impl_ptr<impl>()->push_back(std::move(op)); } void operation_queue::push_front(operation op) { impl_ptr<impl>()->push_front(std::move(op)); } void operation_queue::cancel(operation const &op) { impl_ptr<impl>()->cancel(op); } void operation_queue::cancel() { impl_ptr<impl>()->cancel(); } void operation_queue::wait_until_all_operations_are_finished() { impl_ptr<impl>()->wait_until_all_operations_are_finished(); } void operation_queue::suspend() { impl_ptr<impl>()->suspend(); } void operation_queue::resume() { impl_ptr<impl>()->resume(); } bool operation_queue::is_suspended() const { return impl_ptr<impl>()->is_suspended(); } bool operation_queue::is_operating() const { return impl_ptr<impl>()->is_operating(); } <commit_msg>rename execution to _execution<commit_after>// // yas_operation.cpp // #include "yas_operation.h" #include <atomic> #include <deque> #include <mutex> #include <thread> #include <vector> #include "yas_stl_utils.h" using namespace yas; #pragma mark - operation class operation::impl : public base::impl, public controllable_operation::impl { public: std::atomic<bool> canceled; operation_option_t option; impl(execution_f const &exe, operation_option_t &&option) : canceled(false), _execution(exe), option(std::move(option)) { } impl(execution_f &&exe, operation_option_t &&option) : canceled(false), _execution(std::move(exe)), option(std::move(option)) { } void execute() { if (_execution) { if (!canceled) { _execution(cast<operation>()); } } } void cancel() { canceled = true; } private: execution_f _execution; }; operation::operation(execution_f const &exe, operation_option_t option) : base(std::make_unique<impl>(exe, std::move(option))) { } operation::operation(execution_f &&exe, operation_option_t opt) : base(std::make_unique<impl>(std::move(exe), std::move(opt))) { } operation::operation(std::nullptr_t) : base(nullptr) { } void operation::cancel() { impl_ptr<impl>()->cancel(); } bool operation::is_canceled() const { return impl_ptr<impl>()->canceled; } operation_option_t const &operation::option() const { return impl_ptr<impl>()->option; } controllable_operation operation::controllable() const { return controllable_operation{impl_ptr<controllable_operation::impl>()}; } #pragma mark - queue class operation_queue::impl : public base::impl { public: impl(size_t const count) : _operations(count) { } ~impl() { cancel(); } void push_back(operation &&op) { std::lock_guard<std::recursive_mutex> lock(_mutex); auto &cancel_id = op.option().push_cancel_id; for (auto &dq : _operations) { erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; }); } if (_current_operation) { if (_current_operation.option().push_cancel_id == cancel_id) { _current_operation.cancel(); } } auto &dq = _operations.at(op.option().priority); dq.emplace_back(std::move(op)); _start_next_operation_if_needed(); } void push_front(operation &&op) { std::lock_guard<std::recursive_mutex> lock(_mutex); auto &cancel_id = op.option().push_cancel_id; for (auto &dq : _operations) { erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; }); } if (_current_operation) { if (_current_operation.option().push_cancel_id == cancel_id) { _current_operation.cancel(); } } auto &dq = _operations.at(op.option().priority); dq.emplace_front(std::move(op)); _start_next_operation_if_needed(); } void cancel(operation const &operation) { std::lock_guard<std::recursive_mutex> lock(_mutex); for (auto &dq : _operations) { for (auto &op : dq) { if (operation == op) { op.cancel(); } } } if (_current_operation) { if (_current_operation == operation) { _current_operation.cancel(); } } } void cancel() { std::lock_guard<std::recursive_mutex> lock(_mutex); for (auto &dq : _operations) { for (auto &op : dq) { op.cancel(); } dq.clear(); } if (_current_operation) { _current_operation.cancel(); } } void wait_until_all_operations_are_finished() { while (true) { std::lock_guard<std::recursive_mutex> lock(_mutex); bool op_exists = _current_operation != nullptr; if (!op_exists) { for (auto &dq : _operations) { if (dq.size() > 0) { op_exists = true; } } } if (op_exists) { if (_suspended) { throw "operation_queue is suspended."; } std::this_thread::yield(); } else { break; } } } void suspend() { std::lock_guard<std::recursive_mutex> lock(_mutex); _suspended = true; } void resume() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_suspended) { _suspended = false; _start_next_operation_if_needed(); } } bool is_suspended() const { return _suspended; } bool is_operating() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_current_operation) { return true; } for (auto const &dq : _operations) { if (dq.size() > 0) { return true; } } return false; } private: operation _current_operation = nullptr; std::vector<std::deque<operation>> _operations; bool _suspended = false; mutable std::recursive_mutex _mutex; void _start_next_operation_if_needed() { std::lock_guard<std::recursive_mutex> lock(_mutex); if (!_current_operation && !_suspended) { operation op{nullptr}; for (auto &dq : _operations) { if (!dq.empty()) { op = dq.front(); dq.pop_front(); break; } } if (op) { _current_operation = op; auto weak_ope = to_weak(op); auto weak_queue = to_weak(cast<operation_queue>()); std::thread thread{[weak_ope, weak_queue]() { auto ope = weak_ope.lock(); if (ope) { ope.controllable().execute(); if (auto queue = weak_queue.lock()) { queue.impl_ptr<impl>()->_operation_did_finish(ope); } } }}; thread.detach(); } } } void _operation_did_finish(operation const &prev_op) { std::lock_guard<std::recursive_mutex> lock(_mutex); if (_current_operation == prev_op) { _current_operation = nullptr; } _start_next_operation_if_needed(); } }; operation_queue::operation_queue(size_t const count) : base(std::make_unique<impl>(count)) { } operation_queue::operation_queue(std::nullptr_t) : base(nullptr) { } void operation_queue::push_back(operation op) { impl_ptr<impl>()->push_back(std::move(op)); } void operation_queue::push_front(operation op) { impl_ptr<impl>()->push_front(std::move(op)); } void operation_queue::cancel(operation const &op) { impl_ptr<impl>()->cancel(op); } void operation_queue::cancel() { impl_ptr<impl>()->cancel(); } void operation_queue::wait_until_all_operations_are_finished() { impl_ptr<impl>()->wait_until_all_operations_are_finished(); } void operation_queue::suspend() { impl_ptr<impl>()->suspend(); } void operation_queue::resume() { impl_ptr<impl>()->resume(); } bool operation_queue::is_suspended() const { return impl_ptr<impl>()->is_suspended(); } bool operation_queue::is_operating() const { return impl_ptr<impl>()->is_operating(); } <|endoftext|>
<commit_before>#include <string> #include <cstring> #include <cassert> #include <cmath> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include "rolling.h" #include "city.h" /* as per instructions at top of stb_image_write.h */ #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" using namespace std; #define PROGRAM "collision" static const char USAGE_MESSAGE[] = "Usage:" PROGRAM " [OPTIONS] [FASTA]...\n" "Measure number of hash collisions using CityHash64 or rolling hash.\n" "K-mers from [FASTA] are hashed to positions within a fixed-size\n" "window (using the modulus operator).\n" "\n" "Options:\n" " -d, --max-density N stop hashing k-mers when\n" " DISTINCT_KMERS / WINDOW_SIZE > N [0.05]\n" " -h, --help show this message\n" " -H, --hash HASH hash function to use ('city' or 'rolling')\n" " [rolling]\n" " -k, --kmer-size size of k-mer [20]\n" " -p, --png FILE write bitmap of hash positions\n" " to FILE; dimensions of output PNG are\n" " approximately sqrt(WINDOW_SIZE) by \n" " sqrt(WINDOW_SIZE)\n" " -P, --progress-step N show progress message after hashing\n" " every N k-mers [10000]\n" " -v, --verbose show progress messages\n" " -w, --window-size N window size; this should normally\n" " be a prime number [1048573]\n" "\n" "Sample Prime Numbers (for window size):\n" "\n" " 1048573\n" " 2047541\n" " 3055471\n" " 4051051\n" " 5051143\n"; namespace opt { static float maxDensity = 0.05f; static int help = 0; static string hashFunc("rolling"); static unsigned k = 20; static string pngPath; static size_t progressStep = 10000; static int verbose = 0; static size_t windowSize = 1048573; } static const char shortopts[] = "d:hH:k:p:P:vw:"; static const struct option longopts[] = { { "max-density", required_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "hash", required_argument, NULL, 'H' }, { "kmer-size", required_argument, NULL, 'k' }, { "png", required_argument, NULL, 'p' }, { "progress-step", required_argument, NULL, 'P' }, { "verbose", no_argument, NULL, 'v' }, { "window-size", required_argument, NULL, 'w' }, { NULL, 0, NULL, 0 } }; #define RGB_FORMAT 3 #define BYTES_PER_PIXEL 3 /** Dimensions and pixel data for output PNG file */ struct PNG { int width; int height; /* 3 bytes per pixel: R,G,B */ void* data; void setPixel(unsigned x, unsigned y, uint8_t r, uint8_t g, uint8_t b) { size_t offset = (y * width + x) * BYTES_PER_PIXEL; uint8_t* bytes = (uint8_t*)data; bytes[offset] = r; bytes[offset + 1] = g; bytes[offset + 2] = b; } }; typedef unordered_map<uint64_t, uint8_t> HashCountMap; static char complement[256] = { 0, 0, 0, 0, 0, 0, 0, 0, // 0..7 0, 0, 0, 0, 0, 0, 0, 0, // 8..15 0, 0, 0, 0, 0, 0, 0, 0, // 16..23 0, 0, 0, 0, 0, 0, 0, 0, // 24..31 0, 0, 0, 0, 0, 0, 0, 0, // 32..39 0, 0, 0, 0, 0, 0, 0, 0, // 40..47 0, 0, 0, 0, 0, 0, 0, 0, // 48..55 0, 0, 0, 0, 0, 0, 0, 0, // 56..63 0, 84, 0, 71, 0, 0, 0, 67, // 64..71 (A,C,G) 0, 0, 0, 0, 0, 0, 0, 0, // 72..79 0, 0, 0, 0, 65, 0, 0, 0, // 80..87 (T) 0, 0, 0, 0, 0, 0, 0, 0, // 88..95 0,116, 0,103, 0, 0, 0, 99, // 96..103 (a,c,g) 0, 0, 0, 0, 0, 0, 0, 0, // 104..111 0, 0, 0, 0, 97, 0, 0, 0, // 112..119 (t) 0, 0, 0, 0, 0, 0, 0, 0, // 120..127 0, 0, 0, 0, 0, 0, 0, 0, // 128..135 0, 0, 0, 0, 0, 0, 0, 0, // 136..143 0, 0, 0, 0, 0, 0, 0, 0, // 144..151 0, 0, 0, 0, 0, 0, 0, 0, // 152..159 0, 0, 0, 0, 0, 0, 0, 0, // 160..167 0, 0, 0, 0, 0, 0, 0, 0, // 168..175 0, 0, 0, 0, 0, 0, 0, 0, // 176..183 0, 0, 0, 0, 0, 0, 0, 0, // 184..191 0, 0, 0, 0, 0, 0, 0, 0, // 192..199 0, 0, 0, 0, 0, 0, 0, 0, // 200..207 0, 0, 0, 0, 0, 0, 0, 0, // 208..215 0, 0, 0, 0, 0, 0, 0, 0, // 216..223 0, 0, 0, 0, 0, 0, 0, 0, // 224..231 0, 0, 0, 0, 0, 0, 0, 0, // 232..239 0, 0, 0, 0, 0, 0, 0, 0, // 240..247 0, 0, 0, 0, 0, 0, 0, 0 // 248..255 }; static inline void canonicalize(string& seq) { unsigned k = seq.length(); string rc(k, 'N'); for (unsigned i = 0; i < k; ++i) { unsigned char rcChar = complement[seq.at(i)]; rc.at(k-i-1) = rcChar; if (seq.at(i) != rcChar) { if (seq.at(i) < rcChar) { return; } else { /* finish constructing reverse complement */ for (unsigned j = i + 1; j < k; ++j) rc.at(k-j-1) = complement[seq.at(j)]; seq = rc; return; } } } } static inline bool hashSeq(string seq, unordered_set<string>& kmers, HashCountMap& hashCounts) { transform(seq.begin(), seq.end(), seq.begin(), ::toupper); uint64_t fwdHash, rcHash, hash; string prevKmer; for (unsigned i = 0; i < seq.length() - opt::k + 1; ++i) { string kmer = seq.substr(i, opt::k); size_t pos = kmer.find_first_not_of("ACGT"); if (pos != string::npos) { i += pos; prevKmer.clear(); continue; } if (opt::hashFunc == "city") { hash = CityHash64(kmer.c_str(), kmer.length()); } else { /* hashFunc == "rolling" */ if (prevKmer.empty()) { hash = initHashes(kmer, fwdHash, rcHash); } else { hash = rollHashesRight(fwdHash, rcHash, prevKmer.at(0), kmer.at(opt::k-1), opt::k); } /* * The rolling hash returns the same hash value for * both orientations of a k-mer. In order to count * the number of collisions correctly, we must store * only the canonical version of each k-mer. */ canonicalize(kmer); } hash %= opt::windowSize; kmers.insert(kmer); hashCounts[hash]++; prevKmer = kmer; if ((float)kmers.size() / opt::windowSize > opt::maxDensity) return false; if (opt::verbose && kmers.size() % opt::progressStep == 0) { cerr << "hashed " << kmers.size() << " k-mers" << endl; } } return true; } static inline void drawPNG(HashCountMap& hashCounts, PNG& png) { /* white background */ memset(png.data, 255, png.width * png.height * BYTES_PER_PIXEL); for(HashCountMap::iterator it = hashCounts.begin(); it != hashCounts.end(); ++it) { uint64_t hash = it->first; uint8_t count = it->second; unsigned x = hash % png.width; unsigned y = hash / png.width; if (y >= png.height) { cerr << "y >= png.height!" << endl; cerr << "hash: " << hash << endl; cerr << "y: " << y << endl; cerr << "png.width: " << png.width << endl; cerr << "png.height: " << png.height << endl; } assert(y < png.height); assert(count > 0); if (count > 1) { /* red to indicate collision */ png.setPixel(x, y, 255, 0, 0); } else { /* black to indicate non-collision */ png.setPixel(x, y, 0, 0, 0); } } } int main(int argc, char** argv) { bool die = false; for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'd': arg >> opt::maxDensity; break; case 'h': cout << USAGE_MESSAGE; exit(EXIT_SUCCESS); case 'H': arg >> opt::hashFunc; break; case 'k': arg >> opt::k; break; case 'p': arg >> opt::pngPath; break; case 'P': arg >> opt::progressStep; break; case 'v': opt::verbose++; break; case 'w': arg >> opt::windowSize; break; case '?': die = true; break; } if (optarg != NULL && !arg.eof()) { cerr << PROGRAM ": invalid option: `-" << (char)c << optarg << "'\n"; exit(EXIT_FAILURE); } } if (opt::maxDensity < 0.0f || opt::maxDensity > 1.0f) { cerr << "error: value for -d (--max-density) must be in " " range [0,1]" << endl; die = true; } if (opt::hashFunc != "rolling" && opt::hashFunc != "city") { cerr << "error: unrecognized argument for -h (--hash); " " legal values are: 'rolling', 'city'" << endl; } if (die) { cerr << USAGE_MESSAGE; exit(EXIT_FAILURE); } ifstream fin; if (argc > optind) fin.open(argv[optind]); istream& in = (argc > optind) ? fin : cin; assert(in); /* k-mers inserted so far */ unordered_set<string> kmers; /* number of occurrences of each hash value (usually 1) */ HashCountMap hashCounts; /* read and hash FASTA sequences */ string line; while(getline(in, line)) { if (line.empty() || line.at(0) == '>') continue; /* return false when window exceeds opt::maxDensity */ if(!hashSeq(line, kmers, hashCounts)) break; } /* count collisions */ uint64_t collisions = kmers.size() - hashCounts.size(); cout << "distinct_kmers\tcollisions\n"; cout << kmers.size() << "\t" << collisions << "\n"; /* create PNG image */ if (!opt::pngPath.empty()) { PNG png; png.width = (int)ceil(sqrt(opt::windowSize)); png.height = (int)ceil((double)opt::windowSize / png.width); png.data = malloc(png.width * png.height * BYTES_PER_PIXEL); drawPNG(hashCounts, png); stbi_write_png(opt::pngPath.c_str(), png.width, png.height, RGB_FORMAT, png.data, png.width*BYTES_PER_PIXEL); } return 0; } <commit_msg>collision.cpp: track/report time in hash functions<commit_after>#include <string> #include <cstring> #include <cassert> #include <cmath> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <getopt.h> #include <iomanip> #include <time.h> #include "rolling.h" #include "city.h" /* as per instructions at top of stb_image_write.h */ #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" using namespace std; #define PROGRAM "collision" static const char USAGE_MESSAGE[] = "Usage:" PROGRAM " [OPTIONS] [FASTA]...\n" "Measure number of hash collisions using CityHash64 or rolling hash.\n" "K-mers from [FASTA] are hashed to positions within a fixed-size\n" "window (using the modulus operator).\n" "\n" "Options:\n" " -d, --max-density N stop hashing k-mers when\n" " DISTINCT_KMERS / WINDOW_SIZE > N [0.05]\n" " -h, --help show this message\n" " -H, --hash HASH hash function to use ('city' or 'rolling')\n" " [rolling]\n" " -k, --kmer-size size of k-mer [20]\n" " -p, --png FILE write bitmap of hash positions\n" " to FILE; dimensions of output PNG are\n" " approximately sqrt(WINDOW_SIZE) by \n" " sqrt(WINDOW_SIZE)\n" " -P, --progress-step N show progress message after hashing\n" " every N k-mers [10000]\n" " -v, --verbose show progress messages\n" " -w, --window-size N window size; this should normally\n" " be a prime number [1048573]\n" "\n" "Sample Prime Numbers (for window size):\n" "\n" " 1048573\n" " 2047541\n" " 3055471\n" " 4051051\n" " 5051143\n"; namespace opt { static float maxDensity = 0.05f; static int help = 0; static string hashFunc("rolling"); static unsigned k = 20; static string pngPath; static size_t progressStep = 10000; static int verbose = 0; static size_t windowSize = 1048573; } static const char shortopts[] = "d:hH:k:p:P:vw:"; static const struct option longopts[] = { { "max-density", required_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "hash", required_argument, NULL, 'H' }, { "kmer-size", required_argument, NULL, 'k' }, { "png", required_argument, NULL, 'p' }, { "progress-step", required_argument, NULL, 'P' }, { "verbose", no_argument, NULL, 'v' }, { "window-size", required_argument, NULL, 'w' }, { NULL, 0, NULL, 0 } }; #define RGB_FORMAT 3 #define BYTES_PER_PIXEL 3 /** Dimensions and pixel data for output PNG file */ struct PNG { int width; int height; /* 3 bytes per pixel: R,G,B */ void* data; void setPixel(unsigned x, unsigned y, uint8_t r, uint8_t g, uint8_t b) { size_t offset = (y * width + x) * BYTES_PER_PIXEL; uint8_t* bytes = (uint8_t*)data; bytes[offset] = r; bytes[offset + 1] = g; bytes[offset + 2] = b; } }; typedef unordered_map<uint64_t, uint8_t> HashCountMap; static char complement[256] = { 0, 0, 0, 0, 0, 0, 0, 0, // 0..7 0, 0, 0, 0, 0, 0, 0, 0, // 8..15 0, 0, 0, 0, 0, 0, 0, 0, // 16..23 0, 0, 0, 0, 0, 0, 0, 0, // 24..31 0, 0, 0, 0, 0, 0, 0, 0, // 32..39 0, 0, 0, 0, 0, 0, 0, 0, // 40..47 0, 0, 0, 0, 0, 0, 0, 0, // 48..55 0, 0, 0, 0, 0, 0, 0, 0, // 56..63 0, 84, 0, 71, 0, 0, 0, 67, // 64..71 (A,C,G) 0, 0, 0, 0, 0, 0, 0, 0, // 72..79 0, 0, 0, 0, 65, 0, 0, 0, // 80..87 (T) 0, 0, 0, 0, 0, 0, 0, 0, // 88..95 0,116, 0,103, 0, 0, 0, 99, // 96..103 (a,c,g) 0, 0, 0, 0, 0, 0, 0, 0, // 104..111 0, 0, 0, 0, 97, 0, 0, 0, // 112..119 (t) 0, 0, 0, 0, 0, 0, 0, 0, // 120..127 0, 0, 0, 0, 0, 0, 0, 0, // 128..135 0, 0, 0, 0, 0, 0, 0, 0, // 136..143 0, 0, 0, 0, 0, 0, 0, 0, // 144..151 0, 0, 0, 0, 0, 0, 0, 0, // 152..159 0, 0, 0, 0, 0, 0, 0, 0, // 160..167 0, 0, 0, 0, 0, 0, 0, 0, // 168..175 0, 0, 0, 0, 0, 0, 0, 0, // 176..183 0, 0, 0, 0, 0, 0, 0, 0, // 184..191 0, 0, 0, 0, 0, 0, 0, 0, // 192..199 0, 0, 0, 0, 0, 0, 0, 0, // 200..207 0, 0, 0, 0, 0, 0, 0, 0, // 208..215 0, 0, 0, 0, 0, 0, 0, 0, // 216..223 0, 0, 0, 0, 0, 0, 0, 0, // 224..231 0, 0, 0, 0, 0, 0, 0, 0, // 232..239 0, 0, 0, 0, 0, 0, 0, 0, // 240..247 0, 0, 0, 0, 0, 0, 0, 0 // 248..255 }; static inline void canonicalize(string& seq) { unsigned k = seq.length(); string rc(k, 'N'); for (unsigned i = 0; i < k; ++i) { unsigned char rcChar = complement[seq.at(i)]; rc.at(k-i-1) = rcChar; if (seq.at(i) != rcChar) { if (seq.at(i) < rcChar) { return; } else { /* finish constructing reverse complement */ for (unsigned j = i + 1; j < k; ++j) rc.at(k-j-1) = complement[seq.at(j)]; seq = rc; return; } } } } static inline pair<clock_t, bool> hashSeq(string seq, unordered_set<string>& kmers, HashCountMap& hashCounts) { /* return values */ clock_t hashTime = 0; bool hitMaxDensity = false; transform(seq.begin(), seq.end(), seq.begin(), ::toupper); uint64_t fwdHash, rcHash, hash; string prevKmer; for (unsigned i = 0; i < seq.length() - opt::k + 1; ++i) { string kmer = seq.substr(i, opt::k); size_t pos = kmer.find_first_not_of("ACGT"); if (pos != string::npos) { i += pos; prevKmer.clear(); continue; } if (opt::hashFunc == "city") { clock_t start = clock(); hash = CityHash64(kmer.c_str(), kmer.length()); hashTime += clock() - start; } else { /* hashFunc == "rolling" */ clock_t start = clock(); if (prevKmer.empty()) { hash = initHashes(kmer, fwdHash, rcHash); } else { hash = rollHashesRight(fwdHash, rcHash, prevKmer.at(0), kmer.at(opt::k-1), opt::k); } hashTime += clock() - start; /* * The rolling hash returns the same hash value for * both orientations of a k-mer. In order to count * the number of collisions correctly, we must store * only the canonical version of each k-mer. */ canonicalize(kmer); } hash %= opt::windowSize; kmers.insert(kmer); hashCounts[hash]++; prevKmer = kmer; /* we have reached max density, so stop early */ if ((float)kmers.size() / opt::windowSize > opt::maxDensity) { hitMaxDensity = true; break; } if (opt::verbose && kmers.size() % opt::progressStep == 0) { cerr << "hashed " << kmers.size() << " k-mers" << endl; } } return make_pair(hashTime, hitMaxDensity); } static inline void drawPNG(HashCountMap& hashCounts, PNG& png) { /* white background */ memset(png.data, 255, png.width * png.height * BYTES_PER_PIXEL); for(HashCountMap::iterator it = hashCounts.begin(); it != hashCounts.end(); ++it) { uint64_t hash = it->first; uint8_t count = it->second; unsigned x = hash % png.width; unsigned y = hash / png.width; if (y >= png.height) { cerr << "y >= png.height!" << endl; cerr << "hash: " << hash << endl; cerr << "y: " << y << endl; cerr << "png.width: " << png.width << endl; cerr << "png.height: " << png.height << endl; } assert(y < png.height); assert(count > 0); if (count > 1) { /* red to indicate collision */ png.setPixel(x, y, 255, 0, 0); } else { /* black to indicate non-collision */ png.setPixel(x, y, 0, 0, 0); } } } int main(int argc, char** argv) { bool die = false; for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case 'd': arg >> opt::maxDensity; break; case 'h': cout << USAGE_MESSAGE; exit(EXIT_SUCCESS); case 'H': arg >> opt::hashFunc; break; case 'k': arg >> opt::k; break; case 'p': arg >> opt::pngPath; break; case 'P': arg >> opt::progressStep; break; case 'v': opt::verbose++; break; case 'w': arg >> opt::windowSize; break; case '?': die = true; break; } if (optarg != NULL && !arg.eof()) { cerr << PROGRAM ": invalid option: `-" << (char)c << optarg << "'\n"; exit(EXIT_FAILURE); } } if (opt::maxDensity < 0.0f || opt::maxDensity > 1.0f) { cerr << "error: value for -d (--max-density) must be in " " range [0,1]" << endl; die = true; } if (opt::hashFunc != "rolling" && opt::hashFunc != "city") { cerr << "error: unrecognized argument for -h (--hash); " " legal values are: 'rolling', 'city'" << endl; } if (die) { cerr << USAGE_MESSAGE; exit(EXIT_FAILURE); } ifstream fin; if (argc > optind) fin.open(argv[optind]); istream& in = (argc > optind) ? fin : cin; assert(in); /* k-mers inserted so far */ unordered_set<string> kmers; /* number of occurrences of each hash value (usually 1) */ HashCountMap hashCounts; /* read and hash FASTA sequences */ string line; clock_t hashTime = 0; while(getline(in, line)) { if (line.empty() || line.at(0) == '>') continue; pair<clock_t, bool> result = hashSeq(line, kmers, hashCounts); hashTime += result.first; /* if max density threshold exceeded */ if (result.second) break; } /* count collisions */ uint64_t collisions = kmers.size() - hashCounts.size(); cout << "distinct_kmers\tcollisions\tcpu_sec\n"; cout << kmers.size() << "\t" << collisions << "\t" << setprecision(3) << (double)hashTime / CLOCKS_PER_SEC << "\n"; /* create PNG image */ if (!opt::pngPath.empty()) { PNG png; png.width = (int)ceil(sqrt(opt::windowSize)); png.height = (int)ceil((double)opt::windowSize / png.width); png.data = malloc(png.width * png.height * BYTES_PER_PIXEL); drawPNG(hashCounts, png); stbi_write_png(opt::pngPath.c_str(), png.width, png.height, RGB_FORMAT, png.data, png.width*BYTES_PER_PIXEL); } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" #if 0 #define ___methods_of_interface___IBuzzMath(_, ...) \ _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\ _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__) ___as_interface(IBuzzMath, __with_interface_id(1)) #endif //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { /*TODO: using static_assert to assure name length of interface and method*/ const size_t k_max_interface_name_len = 40; const size_t k_max_method_name_len = 40; /*TODO: consider make msgHeader encoded through thrift*/ struct MsgHeader { unsigned char msgrpc_version_; unsigned char method_index_in_interface_; unsigned short interface_index_in_service_; }; struct Request : MsgHeader { }; struct RpcInvokeHandler { void handleInvoke(const MsgHeader& msg_header) { } }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; struct UdpMsgChannel : msgrpc::MsgChannel { virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); cout << "send msg len: " << msg_len_with_msgid << endl; g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return 0; } }; } //////////////////////////////////////////////////////////////////////////////// using namespace demo; const msgrpc::service_id_t k_remote_service_id = 2222; const msgrpc::service_id_t k_loacl_service_id = 3333; struct IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0; virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0; }; //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathStub : IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&); virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&); }; msgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) { uint8_t* pbuf; uint32_t len; /*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/ if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log*/ cout << "encode failed." << endl; return msgrpc::Ret<ResponseBar>(); } //TODO: find k_remote_service_id by interface name "IBuzzMath" size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len; char* mem = (char*)malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return msgrpc::Ret<ResponseBar>(); } auto header = (msgrpc::MsgHeader*)mem; header->msgrpc_version_ = 0; header->interface_index_in_service_ = 1; header->method_index_in_interface_ = 1; memcpy(header + 1, (const char*)pbuf, len); cout << "stub sending msg with length: " << msg_len_with_header << endl; msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return msgrpc::Ret<ResponseBar>(); } msgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) { return msgrpc::Ret<ResponseBar>(); } void local_service() { std::this_thread::sleep_for(std::chrono::seconds(1)); msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_loacl_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { IBuzzMathStub buzzMath; RequestFoo foo; foo.fooa = 97; foo.__set_foob(98); buzzMath.negative_fields(foo); } else { cout << "local received msg: " << string(msg, len) << endl; channel.close(); } } ); } //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathImpl { bool onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); //todo:remote_id virtual ResponseBar negative_fields(const RequestFoo&); virtual ResponseBar plus1_to_fields(const RequestFoo&); }; bool IBuzzMathImpl::onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) { cout << (int)msg_header.msgrpc_version_ << endl; cout << (int)msg_header.interface_index_in_service_ << endl; cout << (int)msg_header.method_index_in_interface_ << endl; RequestFoo req; if (!ThriftDecoder::decode(req, (uint8_t*)msg, len)) { cout << "decode failed on remote side." << endl; return false; } ResponseBar bar = this->negative_fields(req); if (!ThriftEncoder::encode(bar, &pout_buf, &out_buf_len)) { cout << "encode failed on remtoe side." << endl; return false; } return true; } ResponseBar IBuzzMathImpl::negative_fields(const RequestFoo& req) { ResponseBar bar; /*TODO:change bar to inout parameter*/ bar.__set_bara(req.get_foob()); if (req.__isset.foob) { bar.__set_barb(req.fooa); } return bar; } ResponseBar IBuzzMathImpl::plus1_to_fields(const RequestFoo& req) { ResponseBar bar; bar.__set_bara(1 + req.fooa); if (req.__isset.foob) { bar.__set_barb(1 + req.get_foob()); } return bar; } void remote_service() { msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_remote_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return; } cout << "remote received msg with length: " << len << endl; /*TODO: should first check msg_id == msgrpc_msg_request_id */ if (len < sizeof(msgrpc::MsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } auto msg_header = (msgrpc::MsgHeader*)msg; msg += sizeof(msgrpc::MsgHeader); IBuzzMathImpl buzzMath; uint8_t* pout_buf; uint32_t out_buf_len; if (buzzMath.onRpcInvoke(*msg_header, msg, len - sizeof(msgrpc::MsgHeader), pout_buf, out_buf_len)) { msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pout_buf, out_buf_len); } channel.close(); } ); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) { demo::RequestFoo req; req.fooa = 1; req.__set_foob(2); std::thread local_thread(local_service); std::thread remote_thread(remote_service); local_thread.join(); remote_thread.join(); }; <commit_msg>refactor<commit_after>#include <iostream> #include <gtest/gtest.h> #include <thread> #include <chrono> #include <msgrpc/thrift_struct/thrift_codec.h> using namespace std; using namespace std::chrono; #include "demo/demo_api_declare.h" #if 0 #define ___methods_of_interface___IBuzzMath(_, ...) \ _(1, ResponseBar, negative_fields, RequestFoo, __VA_ARGS__)\ _(2, ResponseBar, plus1_to_fields, RequestFoo, __VA_ARGS__) ___as_interface(IBuzzMath, __with_interface_id(1)) #endif //////////////////////////////////////////////////////////////////////////////// namespace msgrpc { template <typename T> struct Ret {}; typedef unsigned short msg_id_t; typedef unsigned short service_id_t; //TODO: how to deal with different service id types struct MsgChannel { virtual uint32_t send_msg(const service_id_t& remote_service_id, msg_id_t msg_id, const char* buf, size_t len) const = 0; }; struct Config { void initWith(MsgChannel* msg_channel, msgrpc::msg_id_t request_msg_id, msgrpc::msg_id_t response_msg_id) { instance().msg_channel_ = msg_channel; request_msg_id_ = request_msg_id; response_msg_id_ = response_msg_id; } static inline Config& instance() { static thread_local Config instance; return instance; } MsgChannel* msg_channel_; msg_id_t request_msg_id_; msg_id_t response_msg_id_; }; } namespace msgrpc { /*TODO: using static_assert to assure name length of interface and method*/ const size_t k_max_interface_name_len = 40; const size_t k_max_method_name_len = 40; /*TODO: consider make msgHeader encoded through thrift*/ struct MsgHeader { unsigned char msgrpc_version_; unsigned char method_index_in_interface_; unsigned short interface_index_in_service_; }; struct Request : MsgHeader { }; struct RpcInvokeHandler { void handleInvoke(const MsgHeader& msg_header) { } }; } //////////////////////////////////////////////////////////////////////////////// #include "test_util/UdpChannel.h" namespace demo { const msgrpc::msg_id_t k_msgrpc_request_msg_id = 101; const msgrpc::msg_id_t k_msgrpc_response_msg_id = 102; struct UdpMsgChannel : msgrpc::MsgChannel { virtual uint32_t send_msg(const msgrpc::service_id_t& remote_service_id, msgrpc::msg_id_t msg_id, const char* buf, size_t len) const { size_t msg_len_with_msgid = sizeof(msgrpc::msg_id_t) + len; char* mem = (char*)malloc(msg_len_with_msgid); if (mem) { *(msgrpc::msg_id_t*)(mem) = msg_id; memcpy(mem + sizeof(msgrpc::msg_id_t), buf, len); cout << "send msg len: " << msg_len_with_msgid << endl; g_msg_channel->send_msg_to_remote(string(mem, msg_len_with_msgid), udp::endpoint(udp::v4(), remote_service_id)); free(mem); } else { cout << "send msg failed: allocation failure." << endl; } return 0; } }; } //////////////////////////////////////////////////////////////////////////////// using namespace demo; const msgrpc::service_id_t k_remote_service_id = 2222; const msgrpc::service_id_t k_loacl_service_id = 3333; struct IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&) = 0; virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&) = 0; }; //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathStub : IBuzzMath { virtual msgrpc::Ret<ResponseBar> negative_fields(const RequestFoo&); virtual msgrpc::Ret<ResponseBar> plus1_to_fields(const RequestFoo&); }; msgrpc::Ret<ResponseBar> IBuzzMathStub::negative_fields(const RequestFoo& req) { uint8_t* pbuf; uint32_t len; /*TODO: extract interface for encode/decode for other protocol adoption such as protobuf*/ if (!ThriftEncoder::encode(req, &pbuf, &len)) { /*TODO: how to do with log*/ cout << "encode failed." << endl; return msgrpc::Ret<ResponseBar>(); } //TODO: find k_remote_service_id by interface name "IBuzzMath" size_t msg_len_with_header = sizeof(msgrpc::MsgHeader) + len; char* mem = (char*)malloc(msg_len_with_header); if (!mem) { cout << "alloc mem failed, during sending rpc request." << endl; return msgrpc::Ret<ResponseBar>(); } auto header = (msgrpc::MsgHeader*)mem; header->msgrpc_version_ = 0; header->interface_index_in_service_ = 1; header->method_index_in_interface_ = 1; memcpy(header + 1, (const char*)pbuf, len); cout << "stub sending msg with length: " << msg_len_with_header << endl; msgrpc::Config::instance().msg_channel_->send_msg(k_remote_service_id, k_msgrpc_request_msg_id, mem, msg_len_with_header); free(mem); return msgrpc::Ret<ResponseBar>(); } msgrpc::Ret<ResponseBar> IBuzzMathStub::plus1_to_fields(const RequestFoo& req) { return msgrpc::Ret<ResponseBar>(); } void local_service() { std::this_thread::sleep_for(std::chrono::seconds(1)); msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_loacl_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { IBuzzMathStub buzzMath; RequestFoo foo; foo.fooa = 97; foo.__set_foob(98); buzzMath.negative_fields(foo); } else { cout << "local received msg: " << string(msg, len) << endl; channel.close(); } } ); } //////////////////////////////////////////////////////////////////////////////// struct IBuzzMathImpl { bool onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); //todo:remote_id bool do_negative_fields(const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len); bool do_plus1_to_fields(const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) {/*TODO:*/ return false;} }; bool IBuzzMathImpl::onRpcInvoke(const msgrpc::MsgHeader& msg_header, const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) { cout << (int)msg_header.msgrpc_version_ << endl; cout << (int)msg_header.interface_index_in_service_ << endl; cout << (int)msg_header.method_index_in_interface_ << endl; this->do_negative_fields(msg, len, pout_buf, out_buf_len); return true; } bool IBuzzMathImpl::do_negative_fields(const char* msg, size_t len, uint8_t*& pout_buf, uint32_t& out_buf_len) { RequestFoo req; if (!ThriftDecoder::decode(req, (uint8_t*)msg, len)) { cout << "decode failed on remote side." << endl; return false; } ResponseBar bar; /*TODO:change bar to inout parameter*/ bar.__set_bara(req.get_foob()); if (req.__isset.foob) { bar.__set_barb(req.fooa); } if (!ThriftEncoder::encode(bar, &pout_buf, &out_buf_len)) { cout << "encode failed on remtoe side." << endl; return false; } return true; } //ResponseBar IBuzzMathImpl::do_plus1_to_fields(const RequestFoo&, ResponseBar& bar) { // ResponseBar bar; // bar.__set_bara(1 + req.fooa); // if (req.__isset.foob) { // bar.__set_barb(1 + req.get_foob()); // } // return bar; //} void remote_service() { msgrpc::Config::instance().initWith(new UdpMsgChannel(), k_msgrpc_request_msg_id, k_msgrpc_response_msg_id); UdpChannel channel(k_remote_service_id, [&channel](msgrpc::msg_id_t msg_id, const char* msg, size_t len) { if (0 == strcmp(msg, "init")) { return; } cout << "remote received msg with length: " << len << endl; /*TODO: should first check msg_id == msgrpc_msg_request_id */ if (len < sizeof(msgrpc::MsgHeader)) { cout << "invalid msg: without sufficient msg header info." << endl; return; } auto msg_header = (msgrpc::MsgHeader*)msg; msg += sizeof(msgrpc::MsgHeader); IBuzzMathImpl buzzMath; uint8_t* pout_buf; uint32_t out_buf_len; if (buzzMath.onRpcInvoke(*msg_header, msg, len - sizeof(msgrpc::MsgHeader), pout_buf, out_buf_len)) { /*TODO: send out msg with msgheader*/ msgrpc::Config::instance().msg_channel_->send_msg(k_loacl_service_id, k_msgrpc_response_msg_id,(const char*)pout_buf, out_buf_len); } channel.close(); } ); } //////////////////////////////////////////////////////////////////////////////// TEST(async_rpc, should_able_to__auto__register_rpc_interface__after__application_startup) { demo::RequestFoo req; req.fooa = 1; req.__set_foob(2); std::thread local_thread(local_service); std::thread remote_thread(remote_service); local_thread.join(); remote_thread.join(); }; <|endoftext|>
<commit_before>#include "merkle.h" #define NEWDB #ifdef NEWDB ptr<dbfe> db = NULL; #else database *db = NULL; #endif #ifdef NEWDB #define DBNAME "tmpdb" #endif ptr<dbrec> FAKE_DATA = New refcounted<dbrec> ("FAKE", strlen ("FAKE")); void dumpdb () { merkle_hash prevkey(0); warn << ">> dumpdb\n"; ptr<dbEnumeration> iter = db->enumerate (); ptr<dbPair> entry = iter->nextElement (todbrec(merkle_hash(0))); for (int i = 0; entry ; i++) { merkle_hash key = to_merkle_hash (entry->key); warn << "[" << i << "] " << key << "\n"; assert (prevkey <= key); entry = iter->nextElement (); prevkey = key; } warn << "<< dumpdb\n"; } void insert_blocks (merkle_tree *mtree, int upto, bool random) { for (int i = 1; i <= upto; i++) { merkle_hash key; if (random) key.randomize (); else key = i; mtree->insert (New block (key, FAKE_DATA)); //mtree->dump (); if (i % 1000 == 0) { warn << "inserted " << i << " blocks..\n"; //mtree->dump (); //dumpdb (); mtree->check_invariants (); } } mtree->check_invariants (); } void insert_incr (merkle_tree *mtree, int upto) { insert_blocks (mtree, upto, false); } void insert_rand (merkle_tree *mtree, int upto) { insert_blocks (mtree, upto, true); } #ifdef NEWDB void remove_all (merkle_tree *mtree) { ptr<dbEnumeration> iter = db->enumerate (); ref<dbrec> zero = todbrec(merkle_hash(0)); ptr<dbPair> entry = iter->nextElement (zero); while (entry) { block b (to_merkle_hash (entry->key), FAKE_DATA); // XXX change remove's interface to take just the key mtree->remove (&b); entry = iter->nextElement (); } } #else void remove_all (merkle_tree *mtree) { u_int i = 0; block *b; while (1) { b = mtree->db->cursor (0); if (!b) break; mtree->remove (b); delete b; i++; if (i % 1000 == 0) { warn << "removed " << i << " blocks..\n"; mtree->check_invariants (); } } } #endif void test_incr (int upto) { warn << "\n=================== test_incr upto " << upto << "\n"; merkle_tree mtree (db); insert_incr (&mtree, upto); remove_all (&mtree); mtree.dump (); } void test_rand (int upto) { warn << "\n=================== test_rand upto " << upto << "\n"; merkle_tree mtree (db); insert_rand (&mtree, upto); remove_all (&mtree); mtree.dump (); } static void create_database () { #ifdef NEWDB unlink (DBNAME); db = New refcounted<dbfe> (); //set up the options we want dbOptions opts; opts.addOption("opt_async", 1); opts.addOption("opt_cachesize", 1000); opts.addOption("opt_nodesize", 4096); if (int err = db->opendb(DBNAME, opts)) { warn << "open returned: " << strerror(err) << err << "\n"; exit (-1); } #else db = New database (); #endif } int main () { // XXX call random_init () ??? // -- between tests...??? create_database (); test_incr (0); test_incr (1); test_incr (64); test_incr (65); test_incr (64 * 64); test_incr (64 * 64 + 1); test_incr (10000); do { test_rand (1); test_rand (64); test_rand (65); test_rand (64 * 64); test_rand (64 * 64 + 1); test_rand (10000); } while (0); #ifdef NEWDB unlink (DBNAME); #endif } <commit_msg>Remove old code. Disable environments, since that seems to be important for having this code work... see issue94.<commit_after>#include "merkle.h" ptr<dbfe> db = NULL; #define DBNAME "tmpdb" ptr<dbrec> FAKE_DATA = New refcounted<dbrec> ("FAKE", strlen ("FAKE")); void dumpdb () { merkle_hash prevkey(0); warn << ">> dumpdb\n"; ptr<dbEnumeration> iter = db->enumerate (); ptr<dbPair> entry = iter->nextElement (todbrec(merkle_hash(0))); for (int i = 0; entry ; i++) { merkle_hash key = to_merkle_hash (entry->key); warn << "[" << i << "] " << key << "\n"; assert (prevkey <= key); entry = iter->nextElement (); prevkey = key; } warn << "<< dumpdb\n"; } void insert_blocks (merkle_tree *mtree, int upto, bool random) { for (int i = 1; i <= upto; i++) { merkle_hash key; if (random) key.randomize (); else key = i; mtree->insert (New block (key, FAKE_DATA)); //mtree->dump (); if (i % 1000 == 0) { warn << "inserted " << i << " blocks..\n"; //mtree->dump (); //dumpdb (); mtree->check_invariants (); } } mtree->check_invariants (); } void insert_incr (merkle_tree *mtree, int upto) { insert_blocks (mtree, upto, false); } void insert_rand (merkle_tree *mtree, int upto) { insert_blocks (mtree, upto, true); } void remove_all (merkle_tree *mtree) { ptr<dbEnumeration> iter = db->enumerate (); ref<dbrec> zero = todbrec(merkle_hash(0)); ptr<dbPair> entry = iter->nextElement (zero); while (entry) { block b (to_merkle_hash (entry->key), FAKE_DATA); // XXX change remove's interface to take just the key mtree->remove (&b); entry = iter->nextElement (); } } void test_incr (int upto) { warn << "\n=================== test_incr upto " << upto << "\n"; merkle_tree mtree (db); insert_incr (&mtree, upto); remove_all (&mtree); mtree.dump (); } void test_rand (int upto) { warn << "\n=================== test_rand upto " << upto << "\n"; merkle_tree mtree (db); insert_rand (&mtree, upto); remove_all (&mtree); mtree.dump (); } static void create_database () { unlink (DBNAME); db = New refcounted<dbfe> (); //set up the options we want dbOptions opts; opts.addOption("opt_dbenv", 0); if (int err = db->opendb(DBNAME, opts)) { warn << "open returned: " << strerror(err) << err << "\n"; exit (-1); } } int main () { // XXX call random_init () ??? // -- between tests...??? create_database (); test_incr (0); test_incr (1); test_incr (64); test_incr (65); test_incr (64 * 64); test_incr (64 * 64 + 1); test_incr (10000); do { test_rand (1); test_rand (64); test_rand (65); test_rand (64 * 64); test_rand (64 * 64 + 1); test_rand (10000); } while (0); unlink (DBNAME); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Notify> #include <string> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; osg::NotifySeverity g_NotifyLevel = osg::NOTICE; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { static bool s_NotifyInit = false; if (s_NotifyInit) return true; // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char* OSGNOTIFYLEVEL=getenv("OSG_NOTIFY_LEVEL"); if (!OSGNOTIFYLEVEL) OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else std::cout << "Warning: invalid OSG_NOTIFY_LEVEL set ("<<stringOSGNOTIFYLEVEL<<")"<<std::endl; } s_NotifyInit = true; return true; } bool osg::isNotifyEnabled( osg::NotifySeverity severity ) { return severity<=g_NotifyLevel; } class NullStreamBuffer : public std::streambuf { private: virtual streamsize xsputn (const char_type*, streamsize n) { return n; } }; struct NullStream : public std::ostream { NullStream(): std::ostream(new NullStreamBuffer) {} virtual ~NullStream() { delete rdbuf(); rdbuf(0); } }; std::ostream& osg::notify(const osg::NotifySeverity severity) { // set up global notify null stream for inline notify static NullStream s_NotifyNulStream; static bool initialized = false; if (!initialized) { std::cerr<<""; // dummy op to force construction of cerr, before a reference is passed back to calling code. std::cout<<""; // dummy op to force construction of cout, before a reference is passed back to calling code. initialized = osg::initNotifyLevel(); } if (severity<=g_NotifyLevel) { if (severity<=osg::WARN) return std::cerr; else return std::cout; } return s_NotifyNulStream; } <commit_msg>From Eric Sokolowsky, "osgviewer (and all other OSG-based utilities) fails to provide help for the OSG_NOTIFY_LEVEL environment variable. This submission fixes that problem."<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Notify> #include <osg/ApplicationUsage> #include <string> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; static osg::ApplicationUsageProxy Notify_e0(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_NOTIFY_LEVEL <mode>", "FATAL | WARN | NOTICE | DEBUG_INFO | DEBUG_FP | DEBUG | INFO | ALWAYS"); osg::NotifySeverity g_NotifyLevel = osg::NOTICE; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { static bool s_NotifyInit = false; if (s_NotifyInit) return true; // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char* OSGNOTIFYLEVEL=getenv("OSG_NOTIFY_LEVEL"); if (!OSGNOTIFYLEVEL) OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else std::cout << "Warning: invalid OSG_NOTIFY_LEVEL set ("<<stringOSGNOTIFYLEVEL<<")"<<std::endl; } s_NotifyInit = true; return true; } bool osg::isNotifyEnabled( osg::NotifySeverity severity ) { return severity<=g_NotifyLevel; } class NullStreamBuffer : public std::streambuf { private: virtual streamsize xsputn (const char_type*, streamsize n) { return n; } }; struct NullStream : public std::ostream { NullStream(): std::ostream(new NullStreamBuffer) {} virtual ~NullStream() { delete rdbuf(); rdbuf(0); } }; std::ostream& osg::notify(const osg::NotifySeverity severity) { // set up global notify null stream for inline notify static NullStream s_NotifyNulStream; static bool initialized = false; if (!initialized) { std::cerr<<""; // dummy op to force construction of cerr, before a reference is passed back to calling code. std::cout<<""; // dummy op to force construction of cout, before a reference is passed back to calling code. initialized = osg::initNotifyLevel(); } if (severity<=g_NotifyLevel) { if (severity<=osg::WARN) return std::cerr; else return std::cout; } return s_NotifyNulStream; } <|endoftext|>
<commit_before>#include "unit_morph.h" #include <hook_tools.h> #include <SCBW/api.h> #include <cassert> namespace { //-------- CMDRECV_UnitMorph --------// const u32 Func_AddUnitToBuildQueue = 0x00467250; bool addUnitToBuildQueue(const CUnit *unit, u16 unitId) { static u32 result; u32 unitId_ = unitId; __asm { PUSHAD PUSH unitId_ MOV EDI, unit CALL Func_AddUnitToBuildQueue MOV result, EAX POPAD } return result != 0; } void __stdcall unitMorphWrapper_CMDRECV_UnitMorph(u8 *commandData) { const u16 morphUnitId = *((u16*)&commandData[1]); *selectionIndexStart = 0; while (CUnit *unit = getActivePlayerNextSelection()) { if (hooks::unitCanMorphHook(unit, morphUnitId) && unit->mainOrderId != OrderId::Morph1 && addUnitToBuildQueue(unit, morphUnitId)) { unit->orderTo(OrderId::Morph1, NULL); } } scbw::refreshConsole(); } //-------- BTNSCOND_CanBuildUnit --------// s32 __fastcall unitMorphWrapper_BTNSCOND_CanBuildUnit(u16 buildUnitId, s32 playerId, const CUnit *unit) { if (*clientSelectionCount <= 1 || hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) return unit->canBuild(buildUnitId, playerId); return 0; } //-------- Orders_Morph1 --------// const u32 Hook_Orders_Morph1_Check_Success = 0x0045DFCA; void __declspec(naked) unitMorphWrapper_Orders_Morph1_Check() { static CUnit *unit; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } if (hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) { __asm { POPAD JMP Hook_Orders_Morph1_Check_Success } } else { __asm { POPAD POP EDI POP ESI MOV ESP, EBP POP EBP RETN } } } const u32 Hook_Orders_Morph1_EggType_Return = 0x0045E048; void __declspec(naked) unitMorphWrapper_Orders_Morph1_EggType() { static CUnit *unit; static u32 morphEggType; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } unit->status &= ~(UnitStatus::Completed); morphEggType = hooks::getUnitMorphEggTypeHook(unit->id); assert(hooks::isEggUnitHook(morphEggType)); __asm { POPAD PUSH morphEggType JMP Hook_Orders_Morph1_EggType_Return } } //-------- hasSuppliesForUnit --------// Bool32 __stdcall hasSuppliesForUnitWrapper(s8 playerId, u16 unitId, Bool32 canShowErrorMessage) { if (hooks::hasSuppliesForUnitHook(playerId, unitId, canShowErrorMessage != 0)) return 1; else return 0; } //-------- cancelBuild --------// typedef void (__stdcall *CancelZergBuildingFunc)(CUnit*); CancelZergBuildingFunc cancelZergBuilding = (CancelZergBuildingFunc) 0x0045DA40; const u32 Func_ChangeUnitType = 0x0049FED0; void changeUnitType(CUnit *unit, u16 newUnitId) { u32 newUnitId_ = newUnitId; __asm { PUSHAD PUSH newUnitId_ MOV EAX, unit CALL Func_ChangeUnitType POPAD } } const u32 Func_ReplaceSpriteImages = 0x00499BB0; void replaceSpriteImages(CSprite *sprite, u16 imageId, u8 imageDirection) { u32 imageId_ = imageId, imageDirection_ = imageDirection; __asm { PUSHAD PUSH imageDirection_ PUSH imageId_ MOV EAX, sprite CALL Func_ReplaceSpriteImages POPAD } } //Cancel a unit being morphed or constructed. void __fastcall cancelUnitWrapper(CUnit *unit) { //Default StarCraft behavior if (!unit->sprite) return; if (unit->mainOrderId == OrderId::Die) return; if (unit->status & UnitStatus::Completed) return; if (unit->id == UnitId::nydus_canal && unit->building.nydusExit) return; //Don't bother if unit is not morphed yet if (unit->id == UnitId::mutalisk || unit->id == UnitId::hydralisk) return; //Don't bother if unit has finished morphing if (unit->id == UnitId::guardian || unit->id == UnitId::devourer || unit->id == UnitId::lurker) return; if (unit->status & UnitStatus::GroundedBuilding) { if (Unit::GroupFlags[unit->id].isZerg) { cancelZergBuilding(unit); return; } resources->minerals[unit->playerId] += Unit::MineralCost[unit->id] * 3 / 4; resources->gas[unit->playerId] += Unit::GasCost[unit->id] * 3 / 4; } else { u16 refundUnitId; if (hooks::isEggUnitHook(unit->id)) refundUnitId = unit->buildQueue[unit->buildQueueSlot % 5]; else refundUnitId = unit->id; resources->minerals[unit->playerId] += Unit::MineralCost[refundUnitId]; resources->gas[unit->playerId] += Unit::GasCost[refundUnitId]; } u16 cancelChangeUnitId = hooks::getCancelUnitChangeTypeHook(unit->id); if (cancelChangeUnitId == UnitId::None) { if (unit->id == UnitId::nuclear_missile) { CUnit *silo = unit->connectedUnit; if (silo) { silo->building.silo.nuke = NULL; silo->mainOrderState = 0; } scbw::refreshConsole(); } unit->remove(); } else { changeUnitType(unit, cancelChangeUnitId); unit->remainingBuildTime = 0; unit->buildQueue[unit->buildQueueSlot] = UnitId::None; replaceSpriteImages(unit->sprite, Sprite::ImageId[Flingy::SpriteID[Unit::Graphic[unit->displayedUnitId]]], 0); unit->orderSignal &= ~0x4; unit->playIscriptAnim(IscriptAnimation::SpecialState2); unit->orderTo(OrderId::ZergBirth); } } } //unnamed namespace namespace hooks { void injectUnitMorphHooks() { callPatch(unitMorphWrapper_CMDRECV_UnitMorph, 0x00486B50); jmpPatch(unitMorphWrapper_BTNSCOND_CanBuildUnit, 0x00428E60); jmpPatch(unitMorphWrapper_Orders_Morph1_Check, 0x0045DFB0); jmpPatch(unitMorphWrapper_Orders_Morph1_EggType, 0x0045E019); jmpPatch(hasSuppliesForUnitWrapper, 0x0042CF70); jmpPatch(cancelUnitWrapper, 0x00468280); } } //hooks <commit_msg>GPTP: Minor code fix<commit_after>#include "unit_morph.h" #include <hook_tools.h> #include <SCBW/api.h> #include <cassert> namespace { //-------- CMDRECV_UnitMorph --------// const u32 Func_AddUnitToBuildQueue = 0x00467250; bool addUnitToBuildQueue(const CUnit *unit, u16 unitId) { static u32 result; u32 unitId_ = unitId; __asm { PUSHAD PUSH unitId_ MOV EDI, unit CALL Func_AddUnitToBuildQueue MOV result, EAX POPAD } return result != 0; } void __stdcall unitMorphWrapper_CMDRECV_UnitMorph(u8 *commandData) { const u16 morphUnitId = *((u16*)&commandData[1]); *selectionIndexStart = 0; while (CUnit *unit = getActivePlayerNextSelection()) { if (hooks::unitCanMorphHook(unit, morphUnitId) && unit->mainOrderId != OrderId::Morph1 && addUnitToBuildQueue(unit, morphUnitId)) { unit->orderTo(OrderId::Morph1); } } scbw::refreshConsole(); } //-------- BTNSCOND_CanBuildUnit --------// s32 __fastcall unitMorphWrapper_BTNSCOND_CanBuildUnit(u16 buildUnitId, s32 playerId, const CUnit *unit) { if (*clientSelectionCount <= 1 || hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) return unit->canBuild(buildUnitId, playerId); return 0; } //-------- Orders_Morph1 --------// const u32 Hook_Orders_Morph1_Check_Success = 0x0045DFCA; void __declspec(naked) unitMorphWrapper_Orders_Morph1_Check() { static CUnit *unit; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } if (hooks::getUnitMorphEggTypeHook(unit->id) != UnitId::None) { __asm { POPAD JMP Hook_Orders_Morph1_Check_Success } } else { __asm { POPAD POP EDI POP ESI MOV ESP, EBP POP EBP RETN } } } const u32 Hook_Orders_Morph1_EggType_Return = 0x0045E048; void __declspec(naked) unitMorphWrapper_Orders_Morph1_EggType() { static CUnit *unit; static u32 morphEggType; __asm { PUSHAD MOV EBP, ESP MOV unit, ESI } unit->status &= ~(UnitStatus::Completed); morphEggType = hooks::getUnitMorphEggTypeHook(unit->id); assert(hooks::isEggUnitHook(morphEggType)); __asm { POPAD PUSH morphEggType JMP Hook_Orders_Morph1_EggType_Return } } //-------- hasSuppliesForUnit --------// Bool32 __stdcall hasSuppliesForUnitWrapper(s8 playerId, u16 unitId, Bool32 canShowErrorMessage) { if (hooks::hasSuppliesForUnitHook(playerId, unitId, canShowErrorMessage != 0)) return 1; else return 0; } //-------- cancelBuild --------// typedef void (__stdcall *CancelZergBuildingFunc)(CUnit*); CancelZergBuildingFunc cancelZergBuilding = (CancelZergBuildingFunc) 0x0045DA40; const u32 Func_ChangeUnitType = 0x0049FED0; void changeUnitType(CUnit *unit, u16 newUnitId) { u32 newUnitId_ = newUnitId; __asm { PUSHAD PUSH newUnitId_ MOV EAX, unit CALL Func_ChangeUnitType POPAD } } const u32 Func_ReplaceSpriteImages = 0x00499BB0; void replaceSpriteImages(CSprite *sprite, u16 imageId, u8 imageDirection) { u32 imageId_ = imageId, imageDirection_ = imageDirection; __asm { PUSHAD PUSH imageDirection_ PUSH imageId_ MOV EAX, sprite CALL Func_ReplaceSpriteImages POPAD } } //Cancel a unit being morphed or constructed. void __fastcall cancelUnitWrapper(CUnit *unit) { //Default StarCraft behavior if (!unit->sprite) return; if (unit->mainOrderId == OrderId::Die) return; if (unit->status & UnitStatus::Completed) return; if (unit->id == UnitId::nydus_canal && unit->building.nydusExit) return; //Don't bother if unit is not morphed yet if (unit->id == UnitId::mutalisk || unit->id == UnitId::hydralisk) return; //Don't bother if unit has finished morphing if (unit->id == UnitId::guardian || unit->id == UnitId::devourer || unit->id == UnitId::lurker) return; if (unit->status & UnitStatus::GroundedBuilding) { if (Unit::GroupFlags[unit->id].isZerg) { cancelZergBuilding(unit); return; } resources->minerals[unit->playerId] += Unit::MineralCost[unit->id] * 3 / 4; resources->gas[unit->playerId] += Unit::GasCost[unit->id] * 3 / 4; } else { u16 refundUnitId; if (hooks::isEggUnitHook(unit->id)) refundUnitId = unit->buildQueue[unit->buildQueueSlot % 5]; else refundUnitId = unit->id; resources->minerals[unit->playerId] += Unit::MineralCost[refundUnitId]; resources->gas[unit->playerId] += Unit::GasCost[refundUnitId]; } u16 cancelChangeUnitId = hooks::getCancelUnitChangeTypeHook(unit->id); if (cancelChangeUnitId == UnitId::None) { if (unit->id == UnitId::nuclear_missile) { CUnit *silo = unit->connectedUnit; if (silo) { silo->building.silo.nuke = NULL; silo->mainOrderState = 0; } scbw::refreshConsole(); } unit->remove(); } else { changeUnitType(unit, cancelChangeUnitId); unit->remainingBuildTime = 0; unit->buildQueue[unit->buildQueueSlot] = UnitId::None; replaceSpriteImages(unit->sprite, Sprite::ImageId[Flingy::SpriteID[Unit::Graphic[unit->displayedUnitId]]], 0); unit->orderSignal &= ~0x4; unit->playIscriptAnim(IscriptAnimation::SpecialState2); unit->orderTo(OrderId::ZergBirth); } } } //unnamed namespace namespace hooks { void injectUnitMorphHooks() { callPatch(unitMorphWrapper_CMDRECV_UnitMorph, 0x00486B50); jmpPatch(unitMorphWrapper_BTNSCOND_CanBuildUnit, 0x00428E60); jmpPatch(unitMorphWrapper_Orders_Morph1_Check, 0x0045DFB0); jmpPatch(unitMorphWrapper_Orders_Morph1_EggType, 0x0045E019); jmpPatch(hasSuppliesForUnitWrapper, 0x0042CF70); jmpPatch(cancelUnitWrapper, 0x00468280); } } //hooks <|endoftext|>
<commit_before> #include <signalzeug/ScopedConnection.h> namespace signalzeug { ScopedConnection::ScopedConnection() { } ScopedConnection::ScopedConnection(const Connection & connection) : m_connection(connection) { } ScopedConnection::ScopedConnection(ScopedConnection && other) : m_connection(other.m_connection) { other.m_connection = Connection(); } ScopedConnection::~ScopedConnection() { m_connection.disconnect(); } ScopedConnection& ScopedConnection::operator=(const Connection & connection) { m_connection.disconnect(); m_connection = connection; return *this; } ScopedConnection& ScopedConnection::operator=(ScopedConnection && other) { m_connection.disconnect(); m_connection = other.m_connection; other.m_connection = Connection(); return *this; } } // namespace signalzeug <commit_msg>Use std::move for m_connection<commit_after> #include <signalzeug/ScopedConnection.h> namespace signalzeug { ScopedConnection::ScopedConnection() { } ScopedConnection::ScopedConnection(const Connection & connection) : m_connection(connection) { } ScopedConnection::ScopedConnection(ScopedConnection && other) : m_connection(std::move(other.m_connection)) { } ScopedConnection::~ScopedConnection() { m_connection.disconnect(); } ScopedConnection& ScopedConnection::operator=(const Connection & connection) { m_connection.disconnect(); m_connection = connection; return *this; } ScopedConnection& ScopedConnection::operator=(ScopedConnection && other) { m_connection.disconnect(); m_connection = std::move(other.m_connection); return *this; } } // namespace signalzeug <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h" namespace { // TODO(phoglund): These tests are generally broken on mac. // http://code.google.com/p/webrtc/issues/detail?id=1268 class DISABLED_ON_MAC(ViEApiIntegrationTest) : public LegacyFixture { }; TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsBaseTestWithoutErrors) { tests_->ViEBaseAPITest(); } // TODO(phoglund): Crashes on the v4l2loopback camera. TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), DISABLED_RunsCaptureTestWithoutErrors) { tests_->ViECaptureAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsCodecTestWithoutErrors) { tests_->ViECodecAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsEncryptionTestWithoutErrors) { tests_->ViEEncryptionAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsImageProcessTestWithoutErrors) { tests_->ViEImageProcessAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRenderTestWithoutErrors) { tests_->ViERenderAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRtpRtcpTestWithoutErrors) { tests_->ViERtpRtcpAPITest(); } } // namespace <commit_msg>Disable flaky RunsRtpRtcpTestWithoutErrors.<commit_after>/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h" namespace { // TODO(phoglund): These tests are generally broken on mac. // http://code.google.com/p/webrtc/issues/detail?id=1268 class DISABLED_ON_MAC(ViEApiIntegrationTest) : public LegacyFixture { }; TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsBaseTestWithoutErrors) { tests_->ViEBaseAPITest(); } // TODO(phoglund): Crashes on the v4l2loopback camera. TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), DISABLED_RunsCaptureTestWithoutErrors) { tests_->ViECaptureAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsCodecTestWithoutErrors) { tests_->ViECodecAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsEncryptionTestWithoutErrors) { tests_->ViEEncryptionAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsImageProcessTestWithoutErrors) { tests_->ViEImageProcessAPITest(); } TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRenderTestWithoutErrors) { tests_->ViERenderAPITest(); } // See: https://code.google.com/p/webrtc/issues/detail?id=2415 TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), DISABLED_RunsRtpRtcpTestWithoutErrors) { tests_->ViERtpRtcpAPITest(); } } // namespace <|endoftext|>
<commit_before>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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. */ #pragma once #include <string> #include <boost/concept_check.hpp> #include "underscore.hpp" namespace underscore{ class string{ std::string _str; typedef ::underscore::underscore<std::vector<string>> string_list; typedef std::vector<string> std_string_list; public: string(std::string &&str) : _str(std::move(str)){}; string(const std::string &str) : _str(str){}; string(const char *str) : _str(str){}; string_list split(const char &sep=',', bool insert_empty_elements=false) const { std_string_list v; std::string el; std::string::const_iterator I=_str.begin(), endI=_str.end(); std::string::const_iterator p; do{ p=std::find(I, endI, sep); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(std::move(el)); I=p+1; }while(p!=endI); return string_list(std::move(v)); } string_list split(const std::string &sep, bool insert_empty_elements=false) const { std_string_list v; std::string el; auto I=_str.begin(), endI=_str.end(), sepBegin=sep.begin(), sepEnd=sep.end(); std::string::const_iterator p; do{ p=std::search(I, endI, sepBegin, sepEnd); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(el); I=p+sep.size(); }while(p!=endI); return string_list(std::move(v)); } string lower() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::tolower(c)); return string(std::move(ret)); }; string upper() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::toupper(c)); return string(std::move(ret)); }; bool startswith(const std::string &starting){ if (_str.size()<starting.size()) return false; return (_str.substr(0,starting.size())==starting); } bool endswith(const std::string &ending){ if (_str.size()<ending.size()) return false; return (_str.substr(_str.size()-ending.size())==ending); } operator std::string(){ return _str; } size_t size(){ return _str.size(); } string slice(ssize_t start, ssize_t end){ ssize_t s=size(); if (end<0) end=s+end+1; if (end<0) return std::string(); if (end>s) end=s; if (start<0) start=s+start; if (start<0) start=0; if (start>s) return std::string(); if (start==0 && end==s) return *this; return _str.substr(start, end-start); } long to_long(){ size_t n; long l=stol(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return l; } double to_double(){ size_t n; double f=stod(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } float to_float(){ size_t n; float f=stof(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } friend std::ostream& operator <<(std::ostream &output, const string &str) { output << "" << str._str; return output; } }; string _(std::string &&s){ return string(std::move(s)); } string _(const char *s){ return string(std::string(s)); } };<commit_msg>Fixed const methods.<commit_after>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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. */ #pragma once #include <string> #include <boost/concept_check.hpp> #include "underscore.hpp" namespace underscore{ class string{ std::string _str; typedef ::underscore::underscore<std::vector<string>> string_list; typedef std::vector<string> std_string_list; public: string(std::string &&str) : _str(std::move(str)){}; string(const std::string &str) : _str(str){}; string(const char *str) : _str(str){}; string_list split(const char &sep=',', bool insert_empty_elements=false) const { std_string_list v; std::string el; std::string::const_iterator I=_str.begin(), endI=_str.end(); std::string::const_iterator p; do{ p=std::find(I, endI, sep); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(std::move(el)); I=p+1; }while(p!=endI); return string_list(std::move(v)); } string_list split(const std::string &sep, bool insert_empty_elements=false) const { std_string_list v; std::string el; auto I=_str.begin(), endI=_str.end(), sepBegin=sep.begin(), sepEnd=sep.end(); std::string::const_iterator p; do{ p=std::search(I, endI, sepBegin, sepEnd); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(el); I=p+sep.size(); }while(p!=endI); return string_list(std::move(v)); } string lower() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::tolower(c)); return string(std::move(ret)); }; string upper() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::toupper(c)); return string(std::move(ret)); }; bool startswith(const std::string &starting) const { if (_str.size()<starting.size()) return false; return (_str.substr(0,starting.size())==starting); } bool endswith(const std::string &ending) const { if (_str.size()<ending.size()) return false; return (_str.substr(_str.size()-ending.size())==ending); } operator std::string() const{ return _str; } size_t size() const { return _str.size(); } size_t length() const{ return size(); } string slice(ssize_t start, ssize_t end) const{ ssize_t s=size(); if (end<0) end=s+end+1; if (end<0) return std::string(); if (end>s) end=s; if (start<0) start=s+start; if (start<0) start=0; if (start>s) return std::string(); if (start==0 && end==s) return *this; return _str.substr(start, end-start); } long to_long() const { size_t n; long l=stol(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return l; } double to_double() const { size_t n; double f=stod(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } float to_float() const { size_t n; float f=stof(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } friend std::ostream& operator <<(std::ostream &output, const string &str) { output << "" << str._str; return output; } }; string _(std::string &&s){ return string(std::move(s)); } string _(const char *s){ return string(std::string(s)); } };<|endoftext|>
<commit_before>/** * test.cpp - Unit tests * @author Dmitry Ustyugov, Pavel Zaichenkov * Copyright 2009 MDSP team */ #include "memory.h" #include "operation.h" #include "register_file.h" #include "cout_wrapper.h" void testByte() { Byte a( 7); Byte b( 7); Byte c = a&b; b.setBinOut(); a.setDecOut(); c.setHexOut(); cout<<"test byte class:"<<endl; cout<<"a:outputFormat "<<a.getOutputFormat()<<endl; cout<<"a: "<<'\t'<<a<<endl; cout<<"b:outputFormat "<<b.getOutputFormat()<<endl; cout<<"b: "<<'\t'<<b<<endl; cout<<"c:outputFormat "<<c.getOutputFormat()<<endl; cout<<"c=a&b: "<<'\t'<<c<<endl; cout<<"c>>2: "<<'\t'<< ( c>>2) <<endl; cout<<"b<<2: "<<'\t'<<( b<<2)<<endl; cout<<"c==a: "<<'\t'<<( c == a)<<endl; cout<<"c!=b: "<<'\t'<<( c != b)<<endl; } void testByteLine() { Byte a( 7); Byte b( 205); Byte c( 110); hostUInt8 q; hostUInt16 w; hostUInt32 e; q=044;//oct w=0x34c6; e=45678; cout<<"test byteline class:"<<endl; cout<<"a: "<<'\t'<<a<<endl; cout<<"b: "<<'\t'<<b<<endl; cout<<"c: "<<'\t'<<c<<endl; ByteLine f( a + c + b); ByteLine d = f; ByteLine r( q, LOW_FIRST); ByteLine t( w, LOW_FIRST); ByteLine y( e, LOW_FIRST); ByteLine u( q, HIGH_FIRST); ByteLine i( w, HIGH_FIRST); ByteLine o( e, HIGH_FIRST); r.setBinOut(); t.setBinOut(); y.setBinOut(); u.setBinOut(); i.setBinOut(); o.setBinOut(); cout<<"q :"<<q<<endl; cout<<"w :"<<w<<endl; cout<<"e :"<<e<<endl; cout<<"r :"<<r<<endl; cout<<"t :"<<t<<endl; cout<<"y :"<<y<<endl; cout<<"u :"<<u<<endl; cout<<"i :"<<i<<endl; cout<<"o :"<<o<<endl; q = u.getHostUInt8(); w = i.getHostUInt16(); e = o.getHostUInt32(); int m = 0; m += q; cout<<"q -ret:"<< oct <<m<<endl; cout<<"w -ret:"<<dec<<w<<endl; cout<<"e -ret:"<<dec<<e<<endl; cout<<"f( a + c + b): "<<'\t'<<f<<endl; cout<<"d = f: "<<'\t'<<d<<endl; f.addByte( a&b); cout<<"f.addByte( a&b) : "<<'\t'<<f<<endl; f.setByte( 1, 1); cout<<"f.setByte(1,1): "<<f<<endl; cout<<"f.getByte(2): "<<( int)( f.getByteVal( 2))<<endl; cout<<"f.getByte(2): "<<( f.getByte( 2))<<endl; f.setByte( 1, a); cout<<"f.setByte(1,a): "<<f<<endl; cout<<"f.getSizeOfLine() : "<<'\t'<<f.getSizeOfLine()<<endl; f.resizeByteLine( 5); cout<<"f.resizeByteLine( 5) : "<<'\t'<<f<<endl; cout<<"f.getSizeOfLine() : "<<'\t'<<f.getSizeOfLine()<<endl; } void testMemVal() { Byte a( 7); Byte b( 205); Byte c( 110); Byte e( 255); ByteLine f( a + c + b); ByteLine d( a+( c&b)); ByteLine dd = e + e; cout<<"a: "<<'\t'<<a<<endl; cout<<"b: "<<'\t'<<b<<endl; cout<<"c: "<<'\t'<<c<<endl; cout<<"e: "<<'\t'<<e<<endl; cout<<"f( a + c + b): "<<'\t'<<f<<endl; cout<<"d( a+(c&b)): "<<'\t'<<d<<endl; cout<<"dd = e + e: "<<'\t'<<dd<<endl; MemVal mem1(f); MemVal mem2(mem1); MemVal mem3; MemVal mem4(5); MemVal mem5 = mem1+mem4; cout<<"test MemVal class:"<<endl; cout<<" MemVal mem1(f): "<<'\t'<<mem1<<endl; cout<<" MemVal mem2(mem1): "<<'\t'<<mem2<<endl; cout<<" MemVal mem3: "<<'\t'<<mem3<<endl; cout<<" MemVal mem4(5): "<<'\t'<<mem4<<endl; cout<<" MemVal mem5 = mem1+mem3: "<<'\t'<<mem5<<endl; mem3 = dd; cout<<" mem3 = dd: "<<'\t'<<mem3<<endl; mem3.setSizeOfSegment(5); cout<<" mem3.setSizeOfSegment(5): "<<'\t'<<mem3<<endl; cout<<" mem1.getByteLine(): "<<'\t'<<mem1.getByteLine()<<endl; cout<<" mem3.getByteLine(0,3): "<<'\t'<<mem3.getByteLine(0,3)<<endl; mem3.writeByteLine(d,3); cout<<" mem1.writeByteLine(d,3): "<<'\t'<<mem3<<endl; mem3.writeByteLine(d); cout<<" mem1.writeByteLine(d): "<<'\t'<<mem3<<endl; mem3.resizeMemVal(6); cout<<" mem3.resizeMemVal(6): "<<'\t'<<mem3<<endl; cout<<" mem3.getSizeOfMemVal(): "<<'\t'<<mem3.getSizeOfMemVal()<<endl; cout<<" mem3.getSizeOfSegment(): "<<'\t'<<mem3.getSizeOfSegment()<<endl; } void testMemModel() { Byte a( 7); Byte b( 205); Byte c( 110); ByteLine f( a + c + b); mathAddr aa =10; mathAddr bb = 6; MemoryModel model(1); model.write(bb,f); cout<<" model.write(bb,f): \n"<<model<<endl; model.write(aa,a); cout<<" model.write(aa,a): \n"<<model<<endl; model.write(9,b); cout<<" model.write(9,b): \n"<<model<<endl; cout<<" model.read(7,3): \n"<<model.read(7,3)<<endl; cout<<" model: \n"<<model<<endl;; model.write(8,f); cout<<" model.write(8,f): \n"<<model<<endl; // cout << "hostUInt test: \n\n" << endl; hostUInt8 ha = 7; hostUInt16 hb = 205; hostUInt32 hc = 110; MemoryModel model1( 3), model2( 3), model3( 3); model1.write8( aa, ha); cout<<" model.write(aa,ha): \n"<<model1<<endl; model2.write16( 9,hb); cout<<" model.write(9,hb): \n"<<model1<<endl; model3.write32( 9,hc); cout<<" model.write(9,hc): \n"<<model1<<endl; ha = model1.read8(aa); hb = model2.read16(9); hc = model3.read32(9); unsigned int dd = ( unsigned int) ha; cout<<"model1.read8(aa);"<<dd<<endl; cout<<"model2.read16(9);"<<hb<<endl; cout<<"model3.read32(9);"<<hc<<endl; MemVal mv = model2.read( 9, 2); cout << mv.getByteLine().getHostUInt16() << endl; } void testOperation() { Operation *op = new Operation(); setTestingCoutHandler(); op->set(MOVE, BRR, NOP, NOP, 0, 0, 0, 0, 1, 0, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("brr 1, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(MOVE, BRM, NOP, NOP, 1, 0, 0, 0, 1, 0, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("brm 1, r1, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(MOVE, LD, NOP, NOP, 0, 0, 0, 1, 0, 0, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("ld 0, r1, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(ALU, NOP, ADD, NOP, 0, 1, 6, 0, 0, 0, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("add 1, 6, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(ALU, NOP, SUB, NOP, 0, 0, 0, 0, 1, 3, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("sub 0, r1, r3, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(P_FLOW, JMP, NOP, NOP, 1, 0, 0, 5, 0, 0, 0); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("jmp 1, r5;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(P_FLOW, JGT, NOP, NOP, 1, 0, 0, 10, 0, 0, 0); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("jmp 1, r10;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(P_FLOW, JMP, NOP, NOP, 0, 0, 0, 0, 0, 0, 2); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("jmp 0, r2;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(P_FLOW, JGT, NOP, NOP, 0, 0, 0, 0, 0, 0, 5); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("jmp 0, r5;\n")) { cout << "fail!" << endl; assert(0); } setTestingCoutHandler(); op->set(P_FLOW, JGT, NOP, NOP, 0, 0, 0, 0, 0, 0, 5); op->dump(); setStandardCoutHandler(); if (getTestingCoutBuffer() != string("jmp 0, r5;\n")) { cout << "fail!" << endl; assert(0); } delete op; } void testRegisterFileModel() { RegisterFileModel* rfm = new RegisterFileModel( 2, 1); RegVal* rv = new RegVal( 1); RegVal rv1( 1); Byte* b1 = new Byte( 5); Byte* b2 = new Byte( 2); rv->setByte( 0, *b1); rv1.setByte( 0, *b2); rfm->writeReg( 1, *rv); rfm->writeReg( 0, rv1); cout << ( int)rfm->readReg( 0)->getByte( 0).getByteVal() << " " << ( int)rfm->readReg( 1)->getByte( 0).getByteVal() << "\n"; delete b1; delete b2; delete rv; delete rfm; // cout << "Testing write/read8,16,32" << endl; RegisterFileModel* rfm1 = new RegisterFileModel( 2, 1); RegisterFileModel* rfm2 = new RegisterFileModel( 2, 2); RegisterFileModel* rfm3 = new RegisterFileModel( 2, 4); hostUInt8 ha = 8, haa = 88; hostUInt16 hb = 1666, hbb = 6111; hostUInt32 hc = 32222, hcc = 23333; rfm1->write8( 1, ha); rfm1->write8( 0, haa); rfm2->write16( 1, hb); rfm2->write16( 0, hbb); rfm3->write32( 1, hc); rfm3->write32( 0, hcc); cout << ( int)rfm1->read8( 1) << " " << ( int)rfm1->read8( 0) << "\n"; cout << ( int)rfm2->read16( 1) << " " << ( int)rfm2->read16( 0) << "\n"; cout << ( int)rfm3->read32( 1) << " " << ( int)rfm3->read32( 0) << "\n"; } int main() { //testByte(); //testByteLine(); //testMemVal(); //testMemModel(); testOperation(); //testRegisterFileModel(); return 0; } <commit_msg>cleaning directory<commit_after><|endoftext|>
<commit_before>#include "scene_editor_canvas.h" #include "halley/core/game/scene_editor_interface.h" #include "src/project/core_api_wrapper.h" using namespace Halley; SceneEditorCanvas::SceneEditorCanvas(String id, Resources& resources, const HalleyAPI& api) : UIWidget(std::move(id)) , api(api) , resources(resources) { border.setImage(resources, "whitebox.png").setColour(Colour4f()); } SceneEditorCanvas::~SceneEditorCanvas() { unloadDLL(); } void SceneEditorCanvas::update(Time t, bool moved) { updateInterface(t); updateCanvas(Vector2i(getSize()) - Vector2i(2, 2)); } void SceneEditorCanvas::draw(UIPainter& painter) const { const auto pos = getPosition(); const auto size = getSize(); painter.draw(border.clone().setPos(pos).setSize(Vector2f(size.x, 1)), true); painter.draw(border.clone().setPos(pos + Vector2f(0, size.y - 1)).setSize(Vector2f(size.x, 1)), true); painter.draw(border.clone().setPos(pos).setSize(Vector2f(1, size.y)), true); painter.draw(border.clone().setPos(pos + Vector2f(size.x - 1, 0)).setSize(Vector2f(1, size.y)), true); auto canvas = Sprite() .setPos(getPosition() + Vector2f(1, 1)).setSize(getSize() - Vector2f(2, 2)); if (interface && renderTarget) { const auto& tex = renderTarget->getTexture(0); canvas .setImage(tex, resources.get<MaterialDefinition>("Halley/SpriteOpaque")) .setSize(Vector2f(curRenderSize)) .setTexRect(Rect4f(Vector2f(), Vector2f(curRenderSize) / Vector2f(tex->getSize()))); } else { canvas.setImage(resources, "whitebox.png").setColour(Colour4f(0.2f, 0.2f, 0.2f)); } painter.draw(canvas, true); } void SceneEditorCanvas::render(RenderContext& rc) const { renderInterface(rc); } void SceneEditorCanvas::setGameDLL(std::shared_ptr<DynamicLibrary> dll, Resources& gameResources) { this->gameResources = &gameResources; gameDLL = std::move(dll); if (gameDLL) { loadDLL(); } } bool SceneEditorCanvas::needsReload() const { if (gameDLL) { return gameDLL->hasChanged(); } return false; } void SceneEditorCanvas::reload() { reloadDLL(); } void SceneEditorCanvas::updateInterface(Time t) { if (errorState) { unloadDLL(); } if (interface) { guardedRun([&] () { interface->update(t); }); } } void SceneEditorCanvas::renderInterface(RenderContext& rc) const { if (errorState) { return; } if (interface) { guardedRun([&]() { auto context = rc.with(*renderTarget); interface->render(context); }); } } void SceneEditorCanvas::updateCanvas(Vector2i size) { if (size != curRenderSize && size.x > 0 && size.y > 0) { curRenderSize = size; const auto textureSize = Vector2i(nextPowerOf2(size.x), nextPowerOf2(size.y)); if (textureSize != curTextureSize) { curTextureSize = textureSize; std::shared_ptr<Texture> tex = api.video->createTexture(textureSize); auto desc = TextureDescriptor(textureSize, TextureFormat::RGBA); desc.isRenderTarget = true; tex->load(std::move(desc)); renderTarget = api.video->createTextureRenderTarget(); renderTarget->setTarget(0, tex); } renderTarget->setViewPort(Rect4i(Vector2i(), size)); } } void SceneEditorCanvas::loadDLL() { Expects(gameDLL); gameDLL->load(true); auto getHalleyEntry = reinterpret_cast<IHalleyEntryPoint * (HALLEY_STDCALL*)()>(gameDLL->getFunction("getHalleyEntry")); auto game = getHalleyEntry()->createGame(); interface = game->createSceneEditorInterface(); if (interface) { gameCoreAPI = std::make_unique<CoreAPIWrapper>(*api.core); gameAPI = api.clone(); gameAPI->replaceCoreAPI(gameCoreAPI.get()); SceneEditorContext context; context.resources = gameResources; context.api = gameAPI.get(); guardedRun([&]() { interface->init(context); }); if (errorState) { unloadDLL(); } } } void SceneEditorCanvas::unloadDLL() { Expects(gameDLL); interface.reset(); gameDLL->unload(); gameAPI.reset(); gameCoreAPI.reset(); errorState = false; } void SceneEditorCanvas::reloadDLL() { // TODO Logger::logWarning("SceneEditorCanvas::reloadDLL() not implemented yet"); } void SceneEditorCanvas::guardedRun(const std::function<void()>& f) const { try { f(); } catch (const std::exception& e) { Logger::logException(e); errorState = true; } catch (...) { Logger::logError("Unknown error in SceneEditorCanvas, probably from game dll"); errorState = true; } } <commit_msg>Add depth target to render target.<commit_after>#include "scene_editor_canvas.h" #include "halley/core/game/scene_editor_interface.h" #include "src/project/core_api_wrapper.h" using namespace Halley; SceneEditorCanvas::SceneEditorCanvas(String id, Resources& resources, const HalleyAPI& api) : UIWidget(std::move(id)) , api(api) , resources(resources) { border.setImage(resources, "whitebox.png").setColour(Colour4f()); } SceneEditorCanvas::~SceneEditorCanvas() { unloadDLL(); } void SceneEditorCanvas::update(Time t, bool moved) { updateInterface(t); updateCanvas(Vector2i(getSize()) - Vector2i(2, 2)); } void SceneEditorCanvas::draw(UIPainter& painter) const { const auto pos = getPosition(); const auto size = getSize(); painter.draw(border.clone().setPos(pos).setSize(Vector2f(size.x, 1)), true); painter.draw(border.clone().setPos(pos + Vector2f(0, size.y - 1)).setSize(Vector2f(size.x, 1)), true); painter.draw(border.clone().setPos(pos).setSize(Vector2f(1, size.y)), true); painter.draw(border.clone().setPos(pos + Vector2f(size.x - 1, 0)).setSize(Vector2f(1, size.y)), true); auto canvas = Sprite() .setPos(getPosition() + Vector2f(1, 1)).setSize(getSize() - Vector2f(2, 2)); if (interface && renderTarget) { const auto& tex = renderTarget->getTexture(0); canvas .setImage(tex, resources.get<MaterialDefinition>("Halley/SpriteOpaque")) .setSize(Vector2f(curRenderSize)) .setTexRect(Rect4f(Vector2f(), Vector2f(curRenderSize) / Vector2f(tex->getSize()))); } else { canvas.setImage(resources, "whitebox.png").setColour(Colour4f(0.2f, 0.2f, 0.2f)); } painter.draw(canvas, true); } void SceneEditorCanvas::render(RenderContext& rc) const { renderInterface(rc); } void SceneEditorCanvas::setGameDLL(std::shared_ptr<DynamicLibrary> dll, Resources& gameResources) { this->gameResources = &gameResources; gameDLL = std::move(dll); if (gameDLL) { loadDLL(); } } bool SceneEditorCanvas::needsReload() const { if (gameDLL) { return gameDLL->hasChanged(); } return false; } void SceneEditorCanvas::reload() { reloadDLL(); } void SceneEditorCanvas::updateInterface(Time t) { if (errorState) { unloadDLL(); } if (interface) { guardedRun([&] () { interface->update(t); }); } } void SceneEditorCanvas::renderInterface(RenderContext& rc) const { if (errorState) { return; } if (interface) { guardedRun([&]() { auto context = rc.with(*renderTarget); interface->render(context); }); } } void SceneEditorCanvas::updateCanvas(Vector2i size) { if (size != curRenderSize && size.x > 0 && size.y > 0) { curRenderSize = size; const auto textureSize = Vector2i(nextPowerOf2(size.x), nextPowerOf2(size.y)); if (textureSize != curTextureSize) { curTextureSize = textureSize; std::shared_ptr<Texture> colourTarget = api.video->createTexture(textureSize); auto colourDesc = TextureDescriptor(textureSize, TextureFormat::RGBA); colourDesc.isRenderTarget = true; colourTarget->load(std::move(colourDesc)); std::shared_ptr<Texture> depthTarget = api.video->createTexture(textureSize); auto depthDesc = TextureDescriptor(textureSize, TextureFormat::DEPTH); depthDesc.isDepthStencil = true; depthTarget->load(std::move(depthDesc)); renderTarget = api.video->createTextureRenderTarget(); renderTarget->setTarget(0, colourTarget); renderTarget->setDepthTexture(depthTarget); } renderTarget->setViewPort(Rect4i(Vector2i(), size)); } } void SceneEditorCanvas::loadDLL() { Expects(gameDLL); gameDLL->load(true); auto getHalleyEntry = reinterpret_cast<IHalleyEntryPoint * (HALLEY_STDCALL*)()>(gameDLL->getFunction("getHalleyEntry")); auto game = getHalleyEntry()->createGame(); interface = game->createSceneEditorInterface(); if (interface) { gameCoreAPI = std::make_unique<CoreAPIWrapper>(*api.core); gameAPI = api.clone(); gameAPI->replaceCoreAPI(gameCoreAPI.get()); SceneEditorContext context; context.resources = gameResources; context.api = gameAPI.get(); guardedRun([&]() { interface->init(context); }); if (errorState) { unloadDLL(); } } } void SceneEditorCanvas::unloadDLL() { Expects(gameDLL); interface.reset(); gameDLL->unload(); gameAPI.reset(); gameCoreAPI.reset(); errorState = false; } void SceneEditorCanvas::reloadDLL() { // TODO Logger::logWarning("SceneEditorCanvas::reloadDLL() not implemented yet"); } void SceneEditorCanvas::guardedRun(const std::function<void()>& f) const { try { f(); } catch (const std::exception& e) { Logger::logException(e); errorState = true; } catch (...) { Logger::logError("Unknown error in SceneEditorCanvas, probably from game dll"); errorState = true; } } <|endoftext|>
<commit_before>#include <dirent.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <string> #include <boost/multiprecision/cpp_int.hpp> #include <map> #include <sys/mman.h> #include <openssl/evp.h> typedef off_t fsize_t; class File { public: __ino_t inode; std::string name; std::string relativepath; fsize_t size; unsigned char *sha = 0; static std::map<__ino_t, File *> uk_inode; static std::multimap<fsize_t, __ino_t> cx_size; File(const std::string &path, const std::string &filename) { name = filename; relativepath.append(path) += std::string("/") += filename; std::cout << relativepath << std::endl; struct stat sb; if (stat(relativepath.c_str(), &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } inode = sb.st_ino; size = sb.st_size; uk_inode.insert(std::pair<__ino_t, File *>(inode, this)); cx_size.insert(std::pair<fsize_t, __ino_t>(size, inode)); if (cx_size.count(sb.st_size) > 1) { // calc the md5 for this entrant sha = calc_sha(); } if (cx_size.count(sb.st_size) == 2) { // find the other identically sized file and calc it's sha512 std::multimap<fsize_t, __ino_t>::iterator it = cx_size.find(sb.st_size); File *f = uk_inode[it->second]; f->sha = f->calc_sha(); } // the others files should have already had there sha512s calc'd } private: unsigned char *calc_sha() { EVP_MD_CTX *mdctx; const EVP_MD *md; char *file_buffer; unsigned int md_len, i; unsigned char *md_value = new unsigned char [EVP_MAX_MD_SIZE+1]; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha512"); if(!md) { printf("Unknown message digest \n"); exit(EXIT_FAILURE); } int file_descript = open(relativepath.c_str(), O_RDONLY); if(file_descript < 0) exit(-1); file_buffer = (char *)mmap(NULL, size, PROT_READ, MAP_SHARED, file_descript, 0); mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, file_buffer, strlen(file_buffer)); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); std::cout << md_len << std::endl; printf("Digest is: "); for(i = 0; i < md_len; i++) printf("%02x", md_value[i]); printf("\n"); /* Call this once before exit. */ EVP_cleanup(); return md_value; }; }; std::map<__ino_t, File *> File::uk_inode; std::multimap<fsize_t, __ino_t> File::cx_size; void statdir(const std::string& path) { struct dirent **de; int n = scandirat(AT_FDCWD,path.c_str(), &de, NULL, alphasort); if (n == -1) return; while(n--) { if (!strcmp(de[n]->d_name, "..") || !strcmp(de[n]->d_name, ".")) continue; if (de[n]->d_type == DT_DIR) { continue; //XXX just testing for now //directory std::string p(path); p+=std::string("/")+=std::string(de[n]->d_name); statdir(p); //to iterate is human, recurse devine! } if (de[n]->d_type == DT_REG) { //regular file std::string filename(de[n]->d_name); std::cout << filename << std::endl; new File(path, filename); } } } int main(int argv, char **argc) { if (argv != 2) { perror("Insuficient arguments"); exit(EXIT_FAILURE); } statdir(argc[1]); std::cout << "By inode:"<< std::endl; for (auto f : File::uk_inode) { File *ff = f.second; std::cout<<ff->inode<<"\t "<<ff->size<<"\t "<<"\t "<<ff->name <<"\t "; if (ff->sha) { for(int i = 0; i < 64 ; i++) printf("%02x", ff->sha[i]); printf("\n"); } else { std::cout << std::endl; } } std::cout << std::endl << "By size:"<< std::endl; for (auto f : File::cx_size) { __ino_t i = f.second; File *ff = File::uk_inode[i]; std::cout<<ff->inode<<"\t "<<ff->size<<"\t "<<"\t "<<ff->name<<"\t "; if (ff->sha) { for(int i = 0; i < 64 ; i++) printf("%02x", ff->sha[i]); printf("\n"); } else { std::cout << std::endl; } } exit(EXIT_SUCCESS); } <commit_msg>a bit of cleanup befor cpplint<commit_after>#include <dirent.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <string> #include <boost/multiprecision/cpp_int.hpp> #include <map> #include <sys/mman.h> #include <openssl/evp.h> typedef off_t fsize_t; class File { public: __ino_t inode; std::string name; std::string relativepath; fsize_t size; unsigned char *sha = 0; static std::map<__ino_t, File *> uk_inode; static std::multimap<fsize_t, __ino_t> cx_size; File(const std::string &path, const std::string &filename) { name = filename; relativepath.append(path) += std::string("/") += filename; std::cout << relativepath << std::endl; struct stat sb; if (stat(relativepath.c_str(), &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } inode = sb.st_ino; size = sb.st_size; uk_inode.insert(std::pair<__ino_t, File *>(inode, this)); cx_size.insert(std::pair<fsize_t, __ino_t>(size, inode)); if (cx_size.count(sb.st_size) > 1) { // calc the md5 for this entrant sha = calc_sha(); } if (cx_size.count(sb.st_size) == 2) { // find the other identically sized file and calc it's sha512 std::multimap<fsize_t, __ino_t>::iterator it = cx_size.find(sb.st_size); File *f = uk_inode[it->second]; f->sha = f->calc_sha(); } // the others files should have already had there sha512s calc'd } private: unsigned char *calc_sha() { EVP_MD_CTX *mdctx; const EVP_MD *md; char *file_buffer; unsigned int md_len, i; unsigned char *md_value = new unsigned char [EVP_MAX_MD_SIZE+1]; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha512"); if(!md) { printf("Unknown message digest \n"); exit(EXIT_FAILURE); } int file_descript = open(relativepath.c_str(), O_RDONLY); if(file_descript < 0) exit(-1); file_buffer = (char *)mmap(NULL, size, PROT_READ, MAP_SHARED, file_descript, 0); mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, file_buffer, strlen(file_buffer)); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); std::cout << md_len << std::endl; printf("Digest is: "); for(i = 0; i < md_len; i++) printf("%02x", md_value[i]); printf("\n"); /* Call this once before exit. */ EVP_cleanup(); return md_value; }; }; std::map<__ino_t, File *> File::uk_inode; std::multimap<fsize_t, __ino_t> File::cx_size; void statdir(const std::string& path) { struct dirent **de; int n = scandirat(AT_FDCWD,path.c_str(), &de, NULL, alphasort); if (n == -1) return; while(n--) { if (!strcmp(de[n]->d_name, "..") || !strcmp(de[n]->d_name, ".")) continue; if (de[n]->d_type == DT_DIR) { continue; //XXX just testing for now //directory std::string p(path); p+=std::string("/")+=std::string(de[n]->d_name); statdir(p); //recurse } if (de[n]->d_type == DT_REG) { //regular file std::string filename(de[n]->d_name); std::cout << filename << std::endl; new File(path, filename); } } } int main(int argv, char **argc) { if (argv != 2) { perror("Insuficient arguments"); exit(EXIT_FAILURE); } statdir(argc[1]); std::cout << "By inode:"<< std::endl; for (auto f : File::uk_inode) { File *ff = f.second; std::cout<<ff->inode<<"\t "<<ff->size<<"\t "<<"\t "<<ff->name <<"\t "; if (ff->sha) { for(int i = 0; i < 64 ; i++) printf("%02x", ff->sha[i]); printf("\n"); } else { std::cout << std::endl; } } std::cout << std::endl << "By size:"<< std::endl; for (auto f : File::cx_size) { __ino_t i = f.second; File *ff = File::uk_inode[i]; std::cout<<ff->inode<<"\t "<<ff->size<<"\t "<<"\t "<<ff->name<<"\t "; if (ff->sha) { for(int i = 0; i < 64 ; i++) printf("%02x", ff->sha[i]); printf("\n"); } else { std::cout << std::endl; } } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * IP address for the multicast group 224.0.0.224 * Port for multicast group 45454 * * * broadcasts are of the format * [type][channel][nick][contents] * type is a 4 byte string, currently "edct" for normal edicts, "mdct" for medicts. * channel is a 64 byte string which contains the destination channel for the message terminated with zero characters. * nick is the same size and idea as channel, except it contains the nick of the sender. * contents is a max 256 byte string of whatever the text being sent is. If the contents are shorter, the broadcast is shorter to match. * * * To Do: * make sure the nick/channel/message length being broadcast is short enough * toss a notify to the UI if ^ fails */ #include <thread> #include <iostream> #include <QtCore/QByteArray> #include <QtCore/QString> #include <QSettings> #include <QtNetwork> #include <unordered_set> #include "blocker_messages.h" #include "edict_messages.h" #include "received_messages.h" #include "lirch_plugin.h" #include "lirch_constants.h" using namespace std; namespace std { template <> struct hash<QHostAddress> { size_t operator()(const QHostAddress& v) const { return std::hash<std::string>()(v.toString().toStdString()); } }; } QByteArray formatMessage(QString type, QString channel, QString nick, QString contents); void run(plugin_pipe p, string name) { unordered_set<QHostAddress> blocklist; //register for the message types the antenna can handle p.write(registration_message::create(0, name, "block")); p.write(registration_message::create(0, name, "unblock")); p.write(registration_message::create(100, name, "edict")); p.write(registration_message::create(100, name, "me_edict")); //connect to multicast group QUdpSocket udpSocket; QHostAddress groupAddress("224.0.0.224"); quint16 port = 45454; if (!(udpSocket.bind(groupAddress,port) && udpSocket.joinMulticastGroup(groupAddress))) { //flip out, you failed to connect } //needed to send nick with your messages QSettings settings(QSettings::IniFormat, QSettings::UserScope, LIRCH_COMPANY_NAME, "Lirch"); settings.beginGroup("UserData"); while(true) { while (p.has_message()) { message m = p.read(); if (m.type=="shutdown") { udpSocket.leaveMulticastGroup(groupAddress); udpSocket.close(); return; } else if (m.type=="registration_status") { auto s=dynamic_cast<registration_status *>(m.getdata()); if (!s) continue; //Retry 1900 or 2000 times until we succeed if (!s->status && s->priority<2000) p.write(registration_message::create(s->priority+1, name, s->type)); } else if(m.type=="block") { auto castMessage=dynamic_cast<block_message *>(m.getdata()); //if it's not actually a block message, ignore it and move on if (!castMessage) continue; auto toBlock=castMessage->ip; //adds the ip from m to the blocklist //if it is already there, it does nothing. blocklist.insert(toBlock); } else if(m.type=="unblock") { auto castMessage=dynamic_cast<unblock_message *>(m.getdata()); //if it's not actually an unblock message, ignore it and move on if (!castMessage) continue; auto toUnblock=castMessage->ip; //removes the ip in castMessage from the blocklist //if it is not there, it does nothing. blocklist.erase(toUnblock); } else if(m.type=="edict") { auto castMessage=dynamic_cast<edict_message *>(m.getdata()); //if it's not actually an edict message, ignore it and move on if (!castMessage) continue; QString nick=settings.value("nick","spartacus").value<QString>(); QString channel=castMessage->channel; QString contents=castMessage->contents; QByteArray message = formatMessage("edct",channel,nick,contents); if(message.length()>0) udpSocket.writeDatagram(message,groupAddress,port); } else if(m.type=="me_edict") { auto castMessage=dynamic_cast<me_edict_message *>(m.getdata()); //if it's not actually a medict message, ignore it and move on if (!castMessage) continue; QString nick=settings.value("nick","spartacus").value<QString>(); QString channel=castMessage->channel; QString contents=castMessage->contents; QByteArray message = formatMessage("mdct",channel,nick,contents); if(message.length()>0) udpSocket.writeDatagram(message,groupAddress,port); } //if somehow a message is recieved that is not of these types, send it back. else { p.write(m.decrement_priority()); } } while (udpSocket.hasPendingDatagrams()) { char broadcast[512]; QHostAddress senderIP; quint16 senderPort; udpSocket.readDatagram(broadcast,512,&senderIP,&senderPort); QString destinationChannel=QString::fromUtf8(broadcast+4); QString senderNick=QString::fromUtf8(broadcast+68); QString sentContents=QString::fromUtf8(broadcast+132); string type(broadcast,4); if (type=="edct") { p.write(received_message::create(destinationChannel,senderNick,sentContents,senderIP)); } else if (type=="mdct") { p.write(received_me_message::create(destinationChannel,senderNick,sentContents,senderIP)); } else { continue; } } this_thread::sleep_for(chrono::milliseconds(50)); } }; //if components are too long, the cropped version might not have a \0 to terminate it. might need fixing later. QByteArray formatMessage(QString type, QString channel, QString nick, QString contents) { QByteArray output; output += type.toUtf8(); output += channel.toUtf8().leftJustified(64,'\0',true); output += nick.toUtf8().leftJustified(64,'\0',true); QByteArray holder =contents.toUtf8(); if (holder.length()>256) { return QByteArray(); } output += holder; return output; }; <commit_msg>fixed an issue with garbage being broadcast by the antenna<commit_after>/* * IP address for the multicast group 224.0.0.224 * Port for multicast group 45454 * * * broadcasts are of the format * [type][channel][nick][contents] * type is a 4 byte string, currently "edct" for normal edicts, "mdct" for medicts. * channel is a 64 byte string which contains the destination channel for the message terminated with zero characters. * nick is the same size and idea as channel, except it contains the nick of the sender. * contents is a max 256 byte string of whatever the text being sent is. If the contents are shorter, the broadcast is shorter to match. * * * To Do: * make sure the nick/channel/message length being broadcast is short enough * toss a notify to the UI if ^ fails */ #include <thread> #include <iostream> #include <QtCore/QByteArray> #include <QtCore/QString> #include <QSettings> #include <QtNetwork> #include <unordered_set> #include "blocker_messages.h" #include "edict_messages.h" #include "received_messages.h" #include "lirch_plugin.h" #include "lirch_constants.h" using namespace std; namespace std { template <> struct hash<QHostAddress> { size_t operator()(const QHostAddress& v) const { return std::hash<std::string>()(v.toString().toStdString()); } }; } QByteArray formatMessage(QString type, QString channel, QString nick, QString contents); void run(plugin_pipe p, string name) { unordered_set<QHostAddress> blocklist; //register for the message types the antenna can handle p.write(registration_message::create(0, name, "block")); p.write(registration_message::create(0, name, "unblock")); p.write(registration_message::create(100, name, "edict")); p.write(registration_message::create(100, name, "me_edict")); //connect to multicast group QUdpSocket udpSocket; QHostAddress groupAddress("224.0.0.224"); quint16 port = 45454; if (!(udpSocket.bind(groupAddress,port) && udpSocket.joinMulticastGroup(groupAddress))) { //flip out, you failed to connect } //needed to send nick with your messages QSettings settings(QSettings::IniFormat, QSettings::UserScope, LIRCH_COMPANY_NAME, "Lirch"); settings.beginGroup("UserData"); while(true) { while (p.has_message()) { message m = p.read(); if (m.type=="shutdown") { udpSocket.leaveMulticastGroup(groupAddress); udpSocket.close(); return; } else if (m.type=="registration_status") { auto s=dynamic_cast<registration_status *>(m.getdata()); if (!s) continue; //Retry 1900 or 2000 times until we succeed if (!s->status && s->priority<2000) p.write(registration_message::create(s->priority+1, name, s->type)); } else if(m.type=="block") { auto castMessage=dynamic_cast<block_message *>(m.getdata()); //if it's not actually a block message, ignore it and move on if (!castMessage) continue; auto toBlock=castMessage->ip; //adds the ip from m to the blocklist //if it is already there, it does nothing. blocklist.insert(toBlock); } else if(m.type=="unblock") { auto castMessage=dynamic_cast<unblock_message *>(m.getdata()); //if it's not actually an unblock message, ignore it and move on if (!castMessage) continue; auto toUnblock=castMessage->ip; //removes the ip in castMessage from the blocklist //if it is not there, it does nothing. blocklist.erase(toUnblock); } else if(m.type=="edict") { auto castMessage=dynamic_cast<edict_message *>(m.getdata()); //if it's not actually an edict message, ignore it and move on if (!castMessage) continue; QString nick=settings.value("nick","spartacus").value<QString>(); QString channel=castMessage->channel; QString contents=castMessage->contents; QByteArray message = formatMessage("edct",channel,nick,contents); //change to use write() function when we have time if(message.length()>0) udpSocket.writeDatagram(message,groupAddress,port); } else if(m.type=="me_edict") { auto castMessage=dynamic_cast<me_edict_message *>(m.getdata()); //if it's not actually a medict message, ignore it and move on if (!castMessage) continue; QString nick=settings.value("nick","spartacus").value<QString>(); QString channel=castMessage->channel; QString contents=castMessage->contents; QByteArray message = formatMessage("mdct",channel,nick,contents); //change to use write() function when we have time if(message.length()>0) udpSocket.writeDatagram(message,groupAddress,port); } //if somehow a message is recieved that is not of these types, send it back. else { p.write(m.decrement_priority()); } } while (udpSocket.hasPendingDatagrams()) { char broadcast[512]; QHostAddress senderIP; quint16 senderPort; qint64 size = udpSocket.readDatagram(broadcast,512,&senderIP,&senderPort); broadcast[size]='\0'; QString destinationChannel=QString::fromUtf8(broadcast+4); QString senderNick=QString::fromUtf8(broadcast+68); QString sentContents=QString::fromUtf8(broadcast+132); string type(broadcast,4); if (type=="edct") { p.write(received_message::create(destinationChannel,senderNick,sentContents,senderIP)); } else if (type=="mdct") { p.write(received_me_message::create(destinationChannel,senderNick,sentContents,senderIP)); } else { continue; } } this_thread::sleep_for(chrono::milliseconds(50)); } }; //if components are too long, the cropped version might not have a \0 to terminate it. might need fixing later. QByteArray formatMessage(QString type, QString channel, QString nick, QString contents) { QByteArray output; output += type.toUtf8(); output += channel.toUtf8().leftJustified(64,'\0',true); output += nick.toUtf8().leftJustified(64,'\0',true); QByteArray holder =contents.toUtf8(); if (holder.length()>256) { return QByteArray(); } output += holder; output += '\0'; return output; }; <|endoftext|>
<commit_before>#include "KVMainWindow.h" #include <QMenuBar> #include <QMenu> #include <QWebFrame> #include <QMessageBox> #include <QInputDialog> #include <QFile> #include <QUrl> #include <QUrlQuery> #include <QApplication> #include <QNetworkProxy> #include <QSettings> #include <QStandardPaths> #include <QDebug> KVMainWindow::KVMainWindow(QWidget *parent, Qt::WindowFlags flags): QMainWindow(parent, flags) { // Set up the window and menus and stuff QMenuBar *menuBar = new QMenuBar(this); QMenu *viewerMenu = menuBar->addMenu("Viewer"); viewerMenu->addAction("Change API Link", this, SLOT(askForAPILink()))->setShortcut(Qt::CTRL + Qt::Key_L); viewerMenu->addSeparator(); viewerMenu->addAction("Quit", qApp, SLOT(quit()))->setShortcut(Qt::CTRL + Qt::Key_Q); QMenu *helpMenu = menuBar->addMenu("Help"); helpMenu->addAction("About", this, SLOT(showAbout())); this->setMenuBar(menuBar); this->setWindowTitle("KanColleTool Viewer"); // Set a custom network access manager to let us set up a cache and proxy. // Without a cache, the game takes ages to load. // Without a proxy, we can't do cool things like translating the game. netManager = new QNetworkAccessManager(this); // Set up a cache; a larger-than-normal disk cache is quite enough for our purposes cache = new QNetworkDiskCache(this); cache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); netManager->setCache(cache); // Set up a local proxy proxy = new KVProxyServer(this); proxy->listen(); netManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, "localhost", proxy->serverPort())); // Set up the web view, using our custom Network Access Manager webView = new QWebView(this); webView->page()->setNetworkAccessManager(netManager); // The context menu only contains "Reload" anyways webView->setContextMenuPolicy(Qt::PreventContextMenu); // These are so large that they create a need for themselves >_> webView->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); webView->page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); connect(webView, SIGNAL(loadStarted()), this, SLOT(onLoadStarted())); connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool))); // To set the window size right, we have to first set the central widget (which we set to // the web view)'s size to a fixed size, ask the window to auto-adjust to that, and then // fix its size to what it adjusted itself to. A bit clumsy, but it works, and won't stop // us from adding any additional elements to the window, as this will account for ANYTHING. this->setCentralWidget(webView); this->centralWidget()->setFixedSize(800, 480); this->adjustSize(); this->setFixedSize(this->width(), this->height()); // Ask for an API Link if we don't have one already, otherwise just restore it this->loadAPILink(); // Load the bundled index.html file this->loadBundledIndex(); } void KVMainWindow::loadBundledIndex() { QFile file(":/index.html"); if(file.open(QIODevice::ReadOnly)) { webView->setHtml(file.readAll(), apiLink); } else { QMessageBox::critical(this, "Can't load resource", "Couldn't load the local resources needed to start the client.<br /><br />I have no idea how you even managed to make this happen, since the resources are supposed to be inside the executable, but it probably involved a recompilation that went wrong.<br /><br /><code>index.html</code> needs to be in the root of <code>resources.qrc</code>."); exit(1); } } void KVMainWindow::loadAPILink() { QSettings settings; server = settings.value("server").toString(); apiToken = settings.value("apiToken").toString(); if(server.isEmpty() || apiToken.isEmpty()) { this->askForAPILink(); if(server.isEmpty() || apiToken.isEmpty()) exit(0); } else this->generateAPILinkURL(); qDebug() << "Server:" << server; qDebug() << "API Token:" << apiToken; qDebug() << "API Link:" << apiLink.toString(); } void KVMainWindow::generateAPILinkURL() { apiLink = QUrl(QString("http://%1/kcs/mainD2.swf?api_token=%2").arg(server, apiToken)); } void KVMainWindow::askForAPILink() { // Get the link from the user QString link = QInputDialog::getText(this, "Enter API Link", "Please enter your API Link.<br /><br />It should look something like:<br /><code>http://125.6.XXX.XXX/kcs/mainD2.swf?api_token=xxxxxxxxxx...</code>"); // If the link is empty, the user pressed cancel, for whatever reason if(link.isEmpty()) return; // Make an URL and a Query from it QUrl url(link); QUrlQuery query(url); // Extract the important bits, and generate a well-formed URL from that // (It's important that nothing we're doing is noticeable to the staff!) server = url.host(); apiToken = query.queryItemValue("api_token"); this->generateAPILinkURL(); // Put it in the settings and force a sync QSettings settings; settings.setValue("server", server); settings.setValue("apiToken", apiToken); settings.sync(); } void KVMainWindow::showAbout() { QMessageBox::about(this, "About KCTViewer", QString( "<h1>KCTViewer&nbsp;<small>%1</small></h1>" ).arg( QCoreApplication::applicationVersion() ) ); } void KVMainWindow::onLoadStarted() { qDebug() << "Loading Started..."; } void KVMainWindow::onLoadFinished(bool ok) { qDebug() << "Finished Loading!" << ok; if(ok) webView->page()->mainFrame()->evaluateJavaScript(QString("setAPILink(\"%1\"); null").arg(apiLink.toString())); } <commit_msg>Only listen on localhost<commit_after>#include "KVMainWindow.h" #include <QMenuBar> #include <QMenu> #include <QWebFrame> #include <QMessageBox> #include <QInputDialog> #include <QFile> #include <QUrl> #include <QUrlQuery> #include <QApplication> #include <QNetworkProxy> #include <QHostAddress> #include <QSettings> #include <QStandardPaths> #include <QDebug> KVMainWindow::KVMainWindow(QWidget *parent, Qt::WindowFlags flags): QMainWindow(parent, flags) { // Set up the window and menus and stuff QMenuBar *menuBar = new QMenuBar(this); QMenu *viewerMenu = menuBar->addMenu("Viewer"); viewerMenu->addAction("Change API Link", this, SLOT(askForAPILink()))->setShortcut(Qt::CTRL + Qt::Key_L); viewerMenu->addSeparator(); viewerMenu->addAction("Quit", qApp, SLOT(quit()))->setShortcut(Qt::CTRL + Qt::Key_Q); QMenu *helpMenu = menuBar->addMenu("Help"); helpMenu->addAction("About", this, SLOT(showAbout())); this->setMenuBar(menuBar); this->setWindowTitle("KanColleTool Viewer"); // Set a custom network access manager to let us set up a cache and proxy. // Without a cache, the game takes ages to load. // Without a proxy, we can't do cool things like translating the game. netManager = new QNetworkAccessManager(this); // Set up a cache; a larger-than-normal disk cache is quite enough for our purposes cache = new QNetworkDiskCache(this); cache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)); netManager->setCache(cache); // Set up a local proxy proxy = new KVProxyServer(this); proxy->listen(QHostAddress::LocalHost); netManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, "localhost", proxy->serverPort())); // Set up the web view, using our custom Network Access Manager webView = new QWebView(this); webView->page()->setNetworkAccessManager(netManager); // The context menu only contains "Reload" anyways webView->setContextMenuPolicy(Qt::PreventContextMenu); // These are so large that they create a need for themselves >_> webView->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff); webView->page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); connect(webView, SIGNAL(loadStarted()), this, SLOT(onLoadStarted())); connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool))); // To set the window size right, we have to first set the central widget (which we set to // the web view)'s size to a fixed size, ask the window to auto-adjust to that, and then // fix its size to what it adjusted itself to. A bit clumsy, but it works, and won't stop // us from adding any additional elements to the window, as this will account for ANYTHING. this->setCentralWidget(webView); this->centralWidget()->setFixedSize(800, 480); this->adjustSize(); this->setFixedSize(this->width(), this->height()); // Ask for an API Link if we don't have one already, otherwise just restore it this->loadAPILink(); // Load the bundled index.html file this->loadBundledIndex(); } void KVMainWindow::loadBundledIndex() { QFile file(":/index.html"); if(file.open(QIODevice::ReadOnly)) { webView->setHtml(file.readAll(), apiLink); } else { QMessageBox::critical(this, "Can't load resource", "Couldn't load the local resources needed to start the client.<br /><br />I have no idea how you even managed to make this happen, since the resources are supposed to be inside the executable, but it probably involved a recompilation that went wrong.<br /><br /><code>index.html</code> needs to be in the root of <code>resources.qrc</code>."); exit(1); } } void KVMainWindow::loadAPILink() { QSettings settings; server = settings.value("server").toString(); apiToken = settings.value("apiToken").toString(); if(server.isEmpty() || apiToken.isEmpty()) { this->askForAPILink(); if(server.isEmpty() || apiToken.isEmpty()) exit(0); } else this->generateAPILinkURL(); qDebug() << "Server:" << server; qDebug() << "API Token:" << apiToken; qDebug() << "API Link:" << apiLink.toString(); } void KVMainWindow::generateAPILinkURL() { apiLink = QUrl(QString("http://%1/kcs/mainD2.swf?api_token=%2").arg(server, apiToken)); } void KVMainWindow::askForAPILink() { // Get the link from the user QString link = QInputDialog::getText(this, "Enter API Link", "Please enter your API Link.<br /><br />It should look something like:<br /><code>http://125.6.XXX.XXX/kcs/mainD2.swf?api_token=xxxxxxxxxx...</code>"); // If the link is empty, the user pressed cancel, for whatever reason if(link.isEmpty()) return; // Make an URL and a Query from it QUrl url(link); QUrlQuery query(url); // Extract the important bits, and generate a well-formed URL from that // (It's important that nothing we're doing is noticeable to the staff!) server = url.host(); apiToken = query.queryItemValue("api_token"); this->generateAPILinkURL(); // Put it in the settings and force a sync QSettings settings; settings.setValue("server", server); settings.setValue("apiToken", apiToken); settings.sync(); } void KVMainWindow::showAbout() { QMessageBox::about(this, "About KCTViewer", QString( "<h1>KCTViewer&nbsp;<small>%1</small></h1>" ).arg( QCoreApplication::applicationVersion() ) ); } void KVMainWindow::onLoadStarted() { qDebug() << "Loading Started..."; } void KVMainWindow::onLoadFinished(bool ok) { qDebug() << "Finished Loading!" << ok; if(ok) webView->page()->mainFrame()->evaluateJavaScript(QString("setAPILink(\"%1\"); null").arg(apiLink.toString())); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scanunx.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-16 13:28:01 $ * * 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_extensions.hxx" #include <scanner.hxx> #include <sanedlg.hxx> #include <vos/thread.hxx> #include <tools/list.hxx> #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif BitmapTransporter::BitmapTransporter() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "BitmapTransporter\n" ); #endif } BitmapTransporter::~BitmapTransporter() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "~BitmapTransporter\n" ); #endif } // ----------------------------------------------------------------------------- ANY SAL_CALL BitmapTransporter::queryInterface( const Type& rType ) throw( RuntimeException ) { const ANY aRet( cppu::queryInterface( rType, static_cast< AWT::XBitmap* >( this ) ) ); return( aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ) ); } // ----------------------------------------------------------------------------- AWT::Size BitmapTransporter::getSize() throw() { vos::OGuard aGuard( m_aProtector ); int nPreviousPos = m_aStream.Tell(); AWT::Size aRet; // ensure that there is at least a header m_aStream.Seek( STREAM_SEEK_TO_END ); int nLen = m_aStream.Tell(); if( nLen > 15 ) { m_aStream.Seek( 4 ); m_aStream >> aRet.Width >> aRet.Height; } else aRet.Width = aRet.Height = 0; m_aStream.Seek( nPreviousPos ); return aRet; } // ----------------------------------------------------------------------------- SEQ( sal_Int8 ) BitmapTransporter::getDIB() throw() { vos::OGuard aGuard( m_aProtector ); int nPreviousPos = m_aStream.Tell(); // create return value m_aStream.Seek( STREAM_SEEK_TO_END ); int nBytes = m_aStream.Tell(); m_aStream.Seek( 0 ); SEQ( sal_Int8 ) aValue( nBytes ); m_aStream.Read( aValue.getArray(), nBytes ); m_aStream.Seek( nPreviousPos ); return aValue; } // -------------- // - SaneHolder - // -------------- struct SaneHolder { Sane m_aSane; REF( AWT::XBitmap ) m_xBitmap; vos::OMutex m_aProtector; ScanError m_nError; bool m_bBusy; }; DECLARE_LIST( SaneHolderList, SaneHolder* ); static SaneHolderList allSanes; static vos::OMutex aSaneProtector; // ----------------- // - ScannerThread - // ----------------- class ScannerThread : public vos::OThread { SaneHolder* m_pHolder; REF( com::sun::star::lang::XEventListener ) m_xListener; ScannerManager* m_pManager; // just for the disposing call public: virtual void run(); virtual void onTerminated() { delete this; } public: ScannerThread( SaneHolder* pHolder, const REF( com::sun::star::lang::XEventListener )& listener, ScannerManager* pManager ); virtual ~ScannerThread(); }; // ----------------------------------------------------------------------------- ScannerThread::ScannerThread( SaneHolder* pHolder, const REF( com::sun::star::lang::XEventListener )& listener, ScannerManager* pManager ) : m_pHolder( pHolder ), m_xListener( listener ), m_pManager( pManager ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerThread\n" ); #endif } ScannerThread::~ScannerThread() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "~ScannerThread\n" ); #endif } void ScannerThread::run() { vos::OGuard aGuard( m_pHolder->m_aProtector ); BitmapTransporter* pTransporter = new BitmapTransporter; REF( XInterface ) aIf( static_cast< OWeakObject* >( pTransporter ) ); m_pHolder->m_xBitmap = REF( AWT::XBitmap )( aIf, UNO_QUERY ); m_pHolder->m_bBusy = true; if( m_pHolder->m_aSane.IsOpen() ) { int nOption = m_pHolder->m_aSane.GetOptionByName( "preview" ); if( nOption != -1 ) m_pHolder->m_aSane.SetOptionValue( nOption, (BOOL)FALSE ); m_pHolder->m_nError = m_pHolder->m_aSane.Start( *pTransporter ) ? ScanError_ScanErrorNone : ScanError_ScanCanceled; } else m_pHolder->m_nError = ScanError_ScannerNotAvailable; REF( XInterface ) xXInterface( static_cast< OWeakObject* >( m_pManager ) ); m_xListener->disposing( com::sun::star::lang::EventObject(xXInterface) ); m_pHolder->m_bBusy = false; } // ------------------ // - ScannerManager - // ------------------ void ScannerManager::DestroyData() { // unused } // ----------------------------------------------------------------------------- AWT::Size ScannerManager::getSize() throw() { AWT::Size aRet; aRet.Width = aRet.Height = 0; return aRet; } // ----------------------------------------------------------------------------- SEQ( sal_Int8 ) ScannerManager::getDIB() throw() { return SEQ( sal_Int8 )(); } // ----------------------------------------------------------------------------- SEQ( ScannerContext ) ScannerManager::getAvailableScanners() throw() { vos::OGuard aGuard( aSaneProtector ); if( ! allSanes.Count() ) { SaneHolder* pSaneHolder = new SaneHolder; pSaneHolder->m_nError = ScanError_ScanErrorNone; pSaneHolder->m_bBusy = false; if( Sane::IsSane() ) allSanes.Insert( pSaneHolder ); else delete pSaneHolder; } if( Sane::IsSane() ) { SEQ( ScannerContext ) aRet(1); aRet.getArray()[0].ScannerName = ::rtl::OUString::createFromAscii( "SANE" ); aRet.getArray()[0].InternalData = 0; return aRet; } return SEQ( ScannerContext )(); } // ----------------------------------------------------------------------------- BOOL ScannerManager::configureScanner( ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerManager::configureScanner\n" ); #endif if( scanner_context.InternalData < 0 || scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); if( pHolder->m_bBusy ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner is busy" ), REF( XScannerManager )( this ), ScanError_ScanInProgress ); pHolder->m_bBusy = true; SaneDlg aDlg( NULL, pHolder->m_aSane ); BOOL bRet = (BOOL)aDlg.Execute(); pHolder->m_bBusy = false; return bRet; } // ----------------------------------------------------------------------------- void ScannerManager::startScan( const ScannerContext& scanner_context, const REF( com::sun::star::lang::XEventListener )& listener ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerManager::startScan\n" ); #endif if( scanner_context.InternalData < 0 || scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); if( pHolder->m_bBusy ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner is busy" ), REF( XScannerManager )( this ), ScanError_ScanInProgress ); pHolder->m_bBusy = true; ScannerThread* pThread = new ScannerThread( pHolder, listener, this ); pThread->create(); } // ----------------------------------------------------------------------------- ScanError ScannerManager::getError( const ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); if( scanner_context.InternalData < 0 || scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); return pHolder->m_nError; } // ----------------------------------------------------------------------------- REF( AWT::XBitmap ) ScannerManager::getBitmap( const ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); if( scanner_context.InternalData < 0 || scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); vos::OGuard aProtGuard( pHolder->m_aProtector ); REF( AWT::XBitmap ) xRet( pHolder->m_xBitmap ); pHolder->m_xBitmap = REF( AWT::XBitmap )(); return xRet; } <commit_msg>INTEGRATION: CWS wae4extensions (1.8.192); FILE MERGED 2007/10/01 13:24:31 fs 1.8.192.2: #i81612# warning-free code (unxsoli4) 2007/09/27 12:18:50 fs 1.8.192.1: #i81612# warning-free on unxlngi6/.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scanunx.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2008-01-14 15:03:52 $ * * 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_extensions.hxx" #include <scanner.hxx> #include <sanedlg.hxx> #include <vos/thread.hxx> #include <tools/list.hxx> #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif BitmapTransporter::BitmapTransporter() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "BitmapTransporter\n" ); #endif } BitmapTransporter::~BitmapTransporter() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "~BitmapTransporter\n" ); #endif } // ----------------------------------------------------------------------------- ANY SAL_CALL BitmapTransporter::queryInterface( const Type& rType ) throw( RuntimeException ) { const ANY aRet( cppu::queryInterface( rType, static_cast< AWT::XBitmap* >( this ) ) ); return( aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ) ); } // ----------------------------------------------------------------------------- AWT::Size BitmapTransporter::getSize() throw() { vos::OGuard aGuard( m_aProtector ); int nPreviousPos = m_aStream.Tell(); AWT::Size aRet; // ensure that there is at least a header m_aStream.Seek( STREAM_SEEK_TO_END ); int nLen = m_aStream.Tell(); if( nLen > 15 ) { m_aStream.Seek( 4 ); m_aStream >> aRet.Width >> aRet.Height; } else aRet.Width = aRet.Height = 0; m_aStream.Seek( nPreviousPos ); return aRet; } // ----------------------------------------------------------------------------- SEQ( sal_Int8 ) BitmapTransporter::getDIB() throw() { vos::OGuard aGuard( m_aProtector ); int nPreviousPos = m_aStream.Tell(); // create return value m_aStream.Seek( STREAM_SEEK_TO_END ); int nBytes = m_aStream.Tell(); m_aStream.Seek( 0 ); SEQ( sal_Int8 ) aValue( nBytes ); m_aStream.Read( aValue.getArray(), nBytes ); m_aStream.Seek( nPreviousPos ); return aValue; } // -------------- // - SaneHolder - // -------------- struct SaneHolder { Sane m_aSane; REF( AWT::XBitmap ) m_xBitmap; vos::OMutex m_aProtector; ScanError m_nError; bool m_bBusy; }; DECLARE_LIST( SaneHolderList, SaneHolder* ) static SaneHolderList allSanes; static vos::OMutex aSaneProtector; // ----------------- // - ScannerThread - // ----------------- class ScannerThread : public vos::OThread { SaneHolder* m_pHolder; REF( com::sun::star::lang::XEventListener ) m_xListener; ScannerManager* m_pManager; // just for the disposing call public: virtual void run(); virtual void onTerminated() { delete this; } public: ScannerThread( SaneHolder* pHolder, const REF( com::sun::star::lang::XEventListener )& listener, ScannerManager* pManager ); virtual ~ScannerThread(); }; // ----------------------------------------------------------------------------- ScannerThread::ScannerThread( SaneHolder* pHolder, const REF( com::sun::star::lang::XEventListener )& listener, ScannerManager* pManager ) : m_pHolder( pHolder ), m_xListener( listener ), m_pManager( pManager ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerThread\n" ); #endif } ScannerThread::~ScannerThread() { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "~ScannerThread\n" ); #endif } void ScannerThread::run() { vos::OGuard aGuard( m_pHolder->m_aProtector ); BitmapTransporter* pTransporter = new BitmapTransporter; REF( XInterface ) aIf( static_cast< OWeakObject* >( pTransporter ) ); m_pHolder->m_xBitmap = REF( AWT::XBitmap )( aIf, UNO_QUERY ); m_pHolder->m_bBusy = true; if( m_pHolder->m_aSane.IsOpen() ) { int nOption = m_pHolder->m_aSane.GetOptionByName( "preview" ); if( nOption != -1 ) m_pHolder->m_aSane.SetOptionValue( nOption, (BOOL)FALSE ); m_pHolder->m_nError = m_pHolder->m_aSane.Start( *pTransporter ) ? ScanError_ScanErrorNone : ScanError_ScanCanceled; } else m_pHolder->m_nError = ScanError_ScannerNotAvailable; REF( XInterface ) xXInterface( static_cast< OWeakObject* >( m_pManager ) ); m_xListener->disposing( com::sun::star::lang::EventObject(xXInterface) ); m_pHolder->m_bBusy = false; } // ------------------ // - ScannerManager - // ------------------ void ScannerManager::DestroyData() { // unused } // ----------------------------------------------------------------------------- AWT::Size ScannerManager::getSize() throw() { AWT::Size aRet; aRet.Width = aRet.Height = 0; return aRet; } // ----------------------------------------------------------------------------- SEQ( sal_Int8 ) ScannerManager::getDIB() throw() { return SEQ( sal_Int8 )(); } // ----------------------------------------------------------------------------- SEQ( ScannerContext ) ScannerManager::getAvailableScanners() throw() { vos::OGuard aGuard( aSaneProtector ); if( ! allSanes.Count() ) { SaneHolder* pSaneHolder = new SaneHolder; pSaneHolder->m_nError = ScanError_ScanErrorNone; pSaneHolder->m_bBusy = false; if( Sane::IsSane() ) allSanes.Insert( pSaneHolder ); else delete pSaneHolder; } if( Sane::IsSane() ) { SEQ( ScannerContext ) aRet(1); aRet.getArray()[0].ScannerName = ::rtl::OUString::createFromAscii( "SANE" ); aRet.getArray()[0].InternalData = 0; return aRet; } return SEQ( ScannerContext )(); } // ----------------------------------------------------------------------------- BOOL ScannerManager::configureScanner( ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerManager::configureScanner\n" ); #endif if( scanner_context.InternalData < 0 || (ULONG)scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); if( pHolder->m_bBusy ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner is busy" ), REF( XScannerManager )( this ), ScanError_ScanInProgress ); pHolder->m_bBusy = true; SaneDlg aDlg( NULL, pHolder->m_aSane ); BOOL bRet = (BOOL)aDlg.Execute(); pHolder->m_bBusy = false; return bRet; } // ----------------------------------------------------------------------------- void ScannerManager::startScan( const ScannerContext& scanner_context, const REF( com::sun::star::lang::XEventListener )& listener ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "ScannerManager::startScan\n" ); #endif if( scanner_context.InternalData < 0 || (ULONG)scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); if( pHolder->m_bBusy ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner is busy" ), REF( XScannerManager )( this ), ScanError_ScanInProgress ); pHolder->m_bBusy = true; ScannerThread* pThread = new ScannerThread( pHolder, listener, this ); pThread->create(); } // ----------------------------------------------------------------------------- ScanError ScannerManager::getError( const ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); if( scanner_context.InternalData < 0 || (ULONG)scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); return pHolder->m_nError; } // ----------------------------------------------------------------------------- REF( AWT::XBitmap ) ScannerManager::getBitmap( const ScannerContext& scanner_context ) throw( ScannerException ) { vos::OGuard aGuard( aSaneProtector ); if( scanner_context.InternalData < 0 || (ULONG)scanner_context.InternalData >= allSanes.Count() ) throw ScannerException( ::rtl::OUString::createFromAscii( "Scanner does not exist" ), REF( XScannerManager )( this ), ScanError_InvalidContext ); SaneHolder* pHolder = allSanes.GetObject( scanner_context.InternalData ); vos::OGuard aProtGuard( pHolder->m_aProtector ); REF( AWT::XBitmap ) xRet( pHolder->m_xBitmap ); pHolder->m_xBitmap = REF( AWT::XBitmap )(); return xRet; } <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "xwalk/extensions/browser/xwalk_extension_service.h" #include "xwalk/extensions/test/xwalk_extensions_test_base.h" #include "xwalk/runtime/browser/runtime.h" #include "xwalk/test/base/xwalk_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" using xwalk::extensions::XWalkExtensionService; class ExternalExtensionTest : public XWalkExtensionsTestBase { public: virtual void SetUp() OVERRIDE { XWalkExtensionService::SetExternalExtensionsPathForTesting( GetExternalExtensionTestPath(FILE_PATH_LITERAL("echo_extension"))); XWalkExtensionsTestBase::SetUp(); } }; class MultipleEntryPointsExtension : public XWalkExtensionsTestBase { public: virtual void SetUp() OVERRIDE { XWalkExtensionService::SetExternalExtensionsPathForTesting( GetExternalExtensionTestPath(FILE_PATH_LITERAL("mutiple_extension"))); XWalkExtensionsTestBase::SetUp(); } }; IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, ExternalExtension) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL(base::FilePath(), base::FilePath().AppendASCII("echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, NavigateWithExternalExtension) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL(base::FilePath(), base::FilePath().AppendASCII("echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); for (int i = 0; i < 5; i++) { xwalk_test_utils::NavigateToURL(runtime(), url); WaitForLoadStop(runtime()->web_contents()); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } } IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, ExternalExtensionSync) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL( base::FilePath(), base::FilePath().AppendASCII("sync_echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } IN_PROC_BROWSER_TEST_F(MultipleEntryPointsExtension, DISABLED_MultipleEntryPoints) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL( base::FilePath(), base::FilePath().AppendASCII("entry_points.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } <commit_msg>[Extensions] "Fix" and enable test MultipleEntryPointsExtension.MultipleEntryPoints<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/native_library.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "xwalk/extensions/browser/xwalk_extension_service.h" #include "xwalk/extensions/test/xwalk_extensions_test_base.h" #include "xwalk/runtime/browser/runtime.h" #include "xwalk/test/base/xwalk_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" using xwalk::extensions::XWalkExtensionService; class ExternalExtensionTest : public XWalkExtensionsTestBase { public: virtual void SetUp() OVERRIDE { XWalkExtensionService::SetExternalExtensionsPathForTesting( GetExternalExtensionTestPath(FILE_PATH_LITERAL("echo_extension"))); XWalkExtensionsTestBase::SetUp(); } }; class MultipleEntryPointsExtension : public XWalkExtensionsTestBase { public: virtual void SetUp() OVERRIDE { XWalkExtensionService::SetExternalExtensionsPathForTesting( GetExternalExtensionTestPath(FILE_PATH_LITERAL("multiple_extension"))); XWalkExtensionsTestBase::SetUp(); } }; IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, ExternalExtension) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL(base::FilePath(), base::FilePath().AppendASCII("echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, NavigateWithExternalExtension) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL(base::FilePath(), base::FilePath().AppendASCII("echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); for (int i = 0; i < 5; i++) { xwalk_test_utils::NavigateToURL(runtime(), url); WaitForLoadStop(runtime()->web_contents()); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } } IN_PROC_BROWSER_TEST_F(ExternalExtensionTest, ExternalExtensionSync) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL( base::FilePath(), base::FilePath().AppendASCII("sync_echo.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } IN_PROC_BROWSER_TEST_F(MultipleEntryPointsExtension, MultipleEntryPoints) { content::RunAllPendingInMessageLoop(); GURL url = GetExtensionsTestURL( base::FilePath(), base::FilePath().AppendASCII("entry_points.html")); content::TitleWatcher title_watcher(runtime()->web_contents(), kPassString); title_watcher.AlsoWaitForTitle(kFailString); xwalk_test_utils::NavigateToURL(runtime(), url); EXPECT_EQ(kPassString, title_watcher.WaitAndGetTitle()); } <|endoftext|>
<commit_before>/* <x0/plugins/ssl/ssl.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <trapni@gentoo.org> */ #include "SslContext.h" #include "SslDriver.h" #include "SslSocket.h" #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpListener.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpResponse.h> #include <x0/http/HttpHeader.h> #include <x0/io/BufferSource.h> #include <x0/strutils.h> #include <x0/Types.h> #include <boost/lexical_cast.hpp> #include <cstring> #include <cerrno> #include <cstddef> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <gnutls/gnutls.h> #include <gnutls/x509.h> #include <gnutls/extra.h> #include <pthread.h> #include <gcrypt.h> GCRY_THREAD_OPTION_PTHREAD_IMPL; #if 0 # define TRACE(msg...) DEBUG("ssl: " msg) #else # define TRACE(msg...) /*!*/ #endif /* * possible flow API: * * void ssl.listen('IP:PORT'); * void ssl.listen('IP:PORT', backlog); * void ssl.listen('IP:PORT', backlog, defaultKey, defaultCrt); * * void ssl.add(hostname, certfile, keyfile); * * * EXAMPLE: * ssl.listen '0.0.0.0:8443'; * * ssl.add 'hostname' => 'www.trapni.de', * 'certfile' => '/path/to/my.crt', * 'keyfile' => '/path/to/my.key', * 'crlfile' => '/path/to/my.crl'; * */ /** * \ingroup plugins * \brief SSL plugin */ class ssl_plugin : public x0::HttpPlugin, public SslContextSelector { public: ssl_plugin(x0::HttpServer& srv, const std::string& name) : x0::HttpPlugin(srv, name) { gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); int rv = gnutls_global_init(); if (rv != GNUTLS_E_SUCCESS) { TRACE("gnutls_global_init: %s", gnutls_strerror(rv)); return; //Error::CouldNotInitializeSslLibrary; } gnutls_global_init_extra(); server().addComponent(std::string("GnuTLS/") + gnutls_check_version(NULL)); registerSetupFunction<ssl_plugin, &ssl_plugin::add_listener>("ssl.listen", Flow::Value::VOID); registerSetupFunction<ssl_plugin, &ssl_plugin::add_context>("ssl.context", Flow::Value::VOID); registerSetupProperty<ssl_plugin, &ssl_plugin::set_loglevel>("ssl.loglevel", Flow::Value::VOID); } ~ssl_plugin() { gnutls_global_deinit(); } std::vector<SslContext *> contexts_; /** select the SSL context based on host name or NULL if nothing found. */ virtual SslContext *select(const std::string& dnsName) const { if (dnsName.empty()) return contexts_.front(); for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i) { SslContext *cx = *i; if (cx->isValidDnsName(dnsName)) { TRACE("select SslContext: CN:%s, dnsName:%s", cx->commonName().c_str(), dnsName.c_str()); return cx; } } return NULL; } virtual bool post_config() { for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i) (*i)->post_config(); return true; } virtual bool post_check() { // TODO do some post-config checks here. return true; } // {{{ config private: // ssl.listener(BINDADDR_PORT); void add_listener(Flow::Value& result, const x0::Params& args) { std::string arg(args[0].toString()); size_t n = arg.find(':'); std::string ip = n != std::string::npos ? arg.substr(0, n) : "0.0.0.0"; int port = atoi(n != std::string::npos ? arg.substr(n + 1).c_str() : arg.c_str()); int backlog = args[1].isNumber() ? args[1].toNumber() : 0; x0::HttpListener *listener = server().setupListener(port, ip); if (listener && backlog) listener->backlog(backlog); SslDriver *driver = new SslDriver(this); listener->setSocketDriver(driver); } void set_loglevel(Flow::Value& result, const x0::Params& args) { if (args.count() == 1) { if (args[0].isNumber()) setLogLevel(args[0].toNumber()); } } void setLogLevel(int value) { value = std::max(-10, std::min(10, value)); TRACE("setLogLevel: %d", value); gnutls_global_set_log_level(value); gnutls_global_set_log_function(&ssl_plugin::gnutls_logger); } static void gnutls_logger(int level, const char *message) { std::string msg(message); msg.resize(msg.size() - 1); TRACE("gnutls [%d] %s", level, msg.c_str()); } SslContext *acquire(x0::Scope& s) { SslContext *cx = s.acquire<SslContext>(this); cx->setLogger(server().logger()); return cx; } // ssl.add( // 'keyfile' => PATH, // 'crtfile' => PATH, // 'crlfile' => PATH); // void add_context(Flow::Value& result, const x0::Params& args) { std::auto_ptr<SslContext> cx(new SslContext()); cx->setLogger(server().logger()); std::string keyname; for (std::size_t i = 0, e = args.count(); i != e; ++i) { if (!args[i].isArray()) continue; const Flow::Value *key = args[i].toArray(); const Flow::Value *value = key + 1; if (!key->isString()) continue; keyname = key->toString(); if (!value->isString() && !value->isNumber() && !value->isBool()) continue; std::string sval; if (keyname == "certfile") { if (!value->load(sval)) return; cx->certFile = sval; } else if (keyname == "keyfile") { if (!value->load(sval)) return; cx->keyFile = sval; } else if (keyname == "trustfile") { if (!value->load(sval)) return; cx->trustFile = sval; } else if (keyname == "priorities") { if (!value->load(sval)) return; cx->priorities = sval; } else { server().log(x0::Severity::error, "ssl: Unknown ssl.context key: '%s'\n", keyname.c_str()); return; } } // context setup successful -> put into our ssl context set. contexts_.push_back(cx.release()); } // }}} }; X0_EXPORT_PLUGIN(ssl) <commit_msg>compile fix<commit_after>/* <x0/plugins/ssl/ssl.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <trapni@gentoo.org> */ #include "SslContext.h" #include "SslDriver.h" #include "SslSocket.h" #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpListener.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpHeader.h> #include <x0/io/BufferSource.h> #include <x0/strutils.h> #include <x0/Types.h> #include <boost/lexical_cast.hpp> #include <cstring> #include <cerrno> #include <cstddef> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <gnutls/gnutls.h> #include <gnutls/x509.h> #include <gnutls/extra.h> #include <pthread.h> #include <gcrypt.h> GCRY_THREAD_OPTION_PTHREAD_IMPL; #if 0 # define TRACE(msg...) DEBUG("ssl: " msg) #else # define TRACE(msg...) /*!*/ #endif /* * possible flow API: * * void ssl.listen('IP:PORT'); * void ssl.listen('IP:PORT', backlog); * void ssl.listen('IP:PORT', backlog, defaultKey, defaultCrt); * * void ssl.add(hostname, certfile, keyfile); * * * EXAMPLE: * ssl.listen '0.0.0.0:8443'; * * ssl.add 'hostname' => 'www.trapni.de', * 'certfile' => '/path/to/my.crt', * 'keyfile' => '/path/to/my.key', * 'crlfile' => '/path/to/my.crl'; * */ /** * \ingroup plugins * \brief SSL plugin */ class ssl_plugin : public x0::HttpPlugin, public SslContextSelector { public: ssl_plugin(x0::HttpServer& srv, const std::string& name) : x0::HttpPlugin(srv, name) { gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); int rv = gnutls_global_init(); if (rv != GNUTLS_E_SUCCESS) { TRACE("gnutls_global_init: %s", gnutls_strerror(rv)); return; //Error::CouldNotInitializeSslLibrary; } gnutls_global_init_extra(); server().addComponent(std::string("GnuTLS/") + gnutls_check_version(NULL)); registerSetupFunction<ssl_plugin, &ssl_plugin::add_listener>("ssl.listen", Flow::Value::VOID); registerSetupFunction<ssl_plugin, &ssl_plugin::add_context>("ssl.context", Flow::Value::VOID); registerSetupProperty<ssl_plugin, &ssl_plugin::set_loglevel>("ssl.loglevel", Flow::Value::VOID); } ~ssl_plugin() { gnutls_global_deinit(); } std::vector<SslContext *> contexts_; /** select the SSL context based on host name or NULL if nothing found. */ virtual SslContext *select(const std::string& dnsName) const { if (dnsName.empty()) return contexts_.front(); for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i) { SslContext *cx = *i; if (cx->isValidDnsName(dnsName)) { TRACE("select SslContext: CN:%s, dnsName:%s", cx->commonName().c_str(), dnsName.c_str()); return cx; } } return NULL; } virtual bool post_config() { for (auto i = contexts_.begin(), e = contexts_.end(); i != e; ++i) (*i)->post_config(); return true; } virtual bool post_check() { // TODO do some post-config checks here. return true; } // {{{ config private: // ssl.listener(BINDADDR_PORT); void add_listener(Flow::Value& result, const x0::Params& args) { std::string arg(args[0].toString()); size_t n = arg.find(':'); std::string ip = n != std::string::npos ? arg.substr(0, n) : "0.0.0.0"; int port = atoi(n != std::string::npos ? arg.substr(n + 1).c_str() : arg.c_str()); int backlog = args[1].isNumber() ? args[1].toNumber() : 0; x0::HttpListener *listener = server().setupListener(port, ip); if (listener && backlog) listener->backlog(backlog); SslDriver *driver = new SslDriver(this); listener->setSocketDriver(driver); } void set_loglevel(Flow::Value& result, const x0::Params& args) { if (args.count() == 1) { if (args[0].isNumber()) setLogLevel(args[0].toNumber()); } } void setLogLevel(int value) { value = std::max(-10, std::min(10, value)); TRACE("setLogLevel: %d", value); gnutls_global_set_log_level(value); gnutls_global_set_log_function(&ssl_plugin::gnutls_logger); } static void gnutls_logger(int level, const char *message) { std::string msg(message); msg.resize(msg.size() - 1); TRACE("gnutls [%d] %s", level, msg.c_str()); } SslContext *acquire(x0::Scope& s) { SslContext *cx = s.acquire<SslContext>(this); cx->setLogger(server().logger()); return cx; } // ssl.add( // 'keyfile' => PATH, // 'crtfile' => PATH, // 'crlfile' => PATH); // void add_context(Flow::Value& result, const x0::Params& args) { std::auto_ptr<SslContext> cx(new SslContext()); cx->setLogger(server().logger()); std::string keyname; for (std::size_t i = 0, e = args.count(); i != e; ++i) { if (!args[i].isArray()) continue; const Flow::Value *key = args[i].toArray(); const Flow::Value *value = key + 1; if (!key->isString()) continue; keyname = key->toString(); if (!value->isString() && !value->isNumber() && !value->isBool()) continue; std::string sval; if (keyname == "certfile") { if (!value->load(sval)) return; cx->certFile = sval; } else if (keyname == "keyfile") { if (!value->load(sval)) return; cx->keyFile = sval; } else if (keyname == "trustfile") { if (!value->load(sval)) return; cx->trustFile = sval; } else if (keyname == "priorities") { if (!value->load(sval)) return; cx->priorities = sval; } else { server().log(x0::Severity::error, "ssl: Unknown ssl.context key: '%s'\n", keyname.c_str()); return; } } // context setup successful -> put into our ssl context set. contexts_.push_back(cx.release()); } // }}} }; X0_EXPORT_PLUGIN(ssl) <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: mapnik_map.cc 17 2005-03-08 23:58:43Z pavlenko $ #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> using mapnik::Color; using mapnik::coord; using mapnik::Envelope; using mapnik::Layer; using mapnik::Map; struct map_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const Map& m) { return boost::python::make_tuple(m.getWidth(),m.getHeight(),m.srs()); } static boost::python::tuple getstate(const Map& m) { boost::python::list l; for (unsigned i=0;i<m.layerCount();++i) { l.append(m.getLayer(i)); } return boost::python::make_tuple(m.getCurrentExtent(),m.getBackground(),l); } static void setstate (Map& m, boost::python::tuple state) { using namespace boost::python; if (len(state) != 3) { PyErr_SetObject(PyExc_ValueError, ("expected 3-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } Envelope<double> ext = extract<Envelope<double> >(state[0]); Color bg = extract<Color>(state[1]); m.zoomToBox(ext); m.setBackground(bg); boost::python::list l=extract<boost::python::list>(state[2]); for (int i=0;i<len(l);++i) { m.addLayer(extract<Layer>(l[i])); } } }; std::vector<Layer>& (Map::*layers_nonconst)() = &Map::layers; std::vector<Layer> const& (Map::*layers_const)() const = &Map::layers; void export_map() { using namespace boost::python; class_<std::vector<Layer> >("Layers") .def(vector_indexing_suite<std::vector<Layer> >()) ; class_<Map>("Map","The map object.",init<int,int,optional<std::string const&> >()) .add_property("width",&Map::getWidth,"The width of the map image.") .add_property("height",&Map::getHeight,"The height of the map image.") .add_property("srs",make_function(&Map::srs,return_value_policy<copy_const_reference>()), &Map::set_srs,"Spatial reference in proj4 format e.g. \"+proj=latlong +datum=WGS84\"") .add_property("background",make_function (&Map::getBackground,return_value_policy<copy_const_reference>()), &Map::setBackground, "The background color of the map.") .def("envelope",make_function(&Map::getCurrentExtent, return_value_policy<copy_const_reference>()), "The current extent of the map") .def("scale", &Map::scale) .def("zoom_all",&Map::zoom_all, "Set the geographical extent of the map " "to the combined extents of all active layers") .def("zoom_to_box",&Map::zoomToBox, "Set the geographical extent of the map.") .def("pan",&Map::pan) .def("zoom",&Map::zoom) .def("zoom_all",&Map::zoom_all) .def("pan_and_zoom",&Map::pan_and_zoom) .def("append_style",&Map::insert_style) .def("remove_style",&Map::remove_style) .add_property("layers",make_function (layers_nonconst,return_value_policy<reference_existing_object>()), "Get the list of layers in this map.") .def("find_style",&Map::find_style,return_value_policy<copy_const_reference>()) .def_pickle(map_pickle_suite()) ; } <commit_msg>made width and height read-write <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: mapnik_map.cc 17 2005-03-08 23:58:43Z pavlenko $ #include <boost/python.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> using mapnik::Color; using mapnik::coord; using mapnik::Envelope; using mapnik::Layer; using mapnik::Map; struct map_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const Map& m) { return boost::python::make_tuple(m.getWidth(),m.getHeight(),m.srs()); } static boost::python::tuple getstate(const Map& m) { boost::python::list l; for (unsigned i=0;i<m.layerCount();++i) { l.append(m.getLayer(i)); } return boost::python::make_tuple(m.getCurrentExtent(),m.getBackground(),l); } static void setstate (Map& m, boost::python::tuple state) { using namespace boost::python; if (len(state) != 3) { PyErr_SetObject(PyExc_ValueError, ("expected 3-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } Envelope<double> ext = extract<Envelope<double> >(state[0]); Color bg = extract<Color>(state[1]); m.zoomToBox(ext); m.setBackground(bg); boost::python::list l=extract<boost::python::list>(state[2]); for (int i=0;i<len(l);++i) { m.addLayer(extract<Layer>(l[i])); } } }; std::vector<Layer>& (Map::*layers_nonconst)() = &Map::layers; std::vector<Layer> const& (Map::*layers_const)() const = &Map::layers; void export_map() { using namespace boost::python; class_<std::vector<Layer> >("Layers") .def(vector_indexing_suite<std::vector<Layer> >()) ; class_<Map>("Map","The map object.",init<int,int,optional<std::string const&> >()) .add_property("width",&Map::getWidth, &Map::setWidth, "The width of the map.") .add_property("height",&Map::getHeight, &Map::setHeight, "The height of the map.") .add_property("srs",make_function(&Map::srs,return_value_policy<copy_const_reference>()), &Map::set_srs,"Spatial reference in proj4 format e.g. \"+proj=latlong +datum=WGS84\"") .add_property("background",make_function (&Map::getBackground,return_value_policy<copy_const_reference>()), &Map::setBackground, "The background color of the map.") .def("envelope",make_function(&Map::getCurrentExtent, return_value_policy<copy_const_reference>()), "The current extent of the map") .def("scale", &Map::scale) .def("zoom_all",&Map::zoom_all, "Set the geographical extent of the map " "to the combined extents of all active layers") .def("zoom_to_box",&Map::zoomToBox, "Set the geographical extent of the map.") .def("pan",&Map::pan) .def("zoom",&Map::zoom) .def("zoom_all",&Map::zoom_all) .def("pan_and_zoom",&Map::pan_and_zoom) .def("append_style",&Map::insert_style) .def("remove_style",&Map::remove_style) .add_property("layers",make_function (layers_nonconst,return_value_policy<reference_existing_object>()), "Get the list of layers in this map.") .def("find_style",&Map::find_style,return_value_policy<copy_const_reference>()) .def_pickle(map_pickle_suite()) ; } <|endoftext|>
<commit_before>#include "vm.hpp" #include "prelude.hpp" #include "environment.hpp" #include "internal_threads.hpp" #include "builtin/native_method.hpp" #include "dtrace/dtrace.h" #include "util/logger.hpp" namespace rubinius { using namespace utilities; #define AUXILIARY_THREAD_STACK_SIZE 0x100000 InternalThread::InternalThread(STATE, std::string name) : vm_(state->shared().new_vm()) , name_(name) , thread_running_(false) , metrics_(vm_->metrics()) , thread_exit_(false) { state->shared().internal_threads()->register_thread(this); } void* InternalThread::run(void* ptr) { InternalThread* thread = reinterpret_cast<InternalThread*>(ptr); VM* vm = thread->vm(); SharedState& shared = vm->shared; State state_obj(vm), *state = &state_obj; state->vm()->set_run_state(ManagedThread::eIndependent); RBX_DTRACE_CHAR_P thread_name = const_cast<RBX_DTRACE_CHAR_P>(thread->name_.c_str()); vm->set_name(thread_name); RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CHAR_P>(thread_name), vm->thread_id(), 1); NativeMethod::init_thread(state); thread->thread_running_ = true; thread->run(state); thread->thread_running_ = false; NativeMethod::cleanup_thread(state); RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CHAR_P>(thread_name), vm->thread_id(), 1); if(state->vm()->run_state() != ManagedThread::eIndependent) { shared.gc_independent(); } return 0; } void InternalThread::initialize(STATE) { thread_exit_ = false; thread_running_ = false; } void InternalThread::start(STATE) { initialize(state); start_thread(state); } void InternalThread::start_thread(STATE) { pthread_attr_t attrs; pthread_attr_init(&attrs); pthread_attr_setstacksize(&attrs, AUXILIARY_THREAD_STACK_SIZE); if(int error = pthread_create(&vm_->os_thread(), &attrs, InternalThread::run, (void*)this)) { logger::error("%s: %s: create thread failed", strerror(error), name_.c_str()); } } void InternalThread::wakeup(STATE) { thread_exit_ = true; atomic::memory_barrier(); } void InternalThread::stop_thread(STATE) { GCIndependent guard(state, 0); wakeup(state); void* return_value; pthread_t os = vm_->os_thread(); pthread_join(os, &return_value); } void InternalThread::stop(STATE) { state->shared().internal_threads()->unregister_thread(this); stop_thread(state); VM::discard(state, vm_); } void InternalThread::after_fork_child(STATE) { vm_ = state->shared().new_vm(); start(state); } void InternalThreads::register_thread(InternalThread* thread) { threads_.push_back(thread); } void InternalThreads::unregister_thread(InternalThread* thread) { threads_.remove(thread); } void InternalThreads::shutdown(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(shutdown_in_progress_) return; shutdown_in_progress_ = true; while(!threads_.empty()) { threads_.front()->stop(state); } shutdown_in_progress_ = false; } void InternalThreads::before_exec(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(exec_in_progress_) return; exec_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_exec(state); } state->shared().env()->before_exec(state); } void InternalThreads::after_exec(STATE) { // We don't guard here on the assumption that only one thread is running // after execvp() call. state->shared().env()->after_exec(state); for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_exec(state); } exec_in_progress_ = false; } void InternalThreads::before_fork_exec(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(fork_exec_in_progress_) return; fork_exec_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_fork_exec(state); } } void InternalThreads::after_fork_exec_parent(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_exec_parent(state); } fork_in_progress_ = false; } void InternalThreads::after_fork_exec_child(STATE) { // We don't guard here on the assumption that only one thread is running // after execvp() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_exec_child(state); } state->shared().env()->after_fork_exec_child(state); fork_exec_in_progress_ = false; } void InternalThreads::before_fork(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(fork_in_progress_) return; fork_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_fork(state); } } void InternalThreads::after_fork_parent(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_parent(state); } fork_in_progress_ = false; } void InternalThreads::after_fork_child(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_child(state); } state->shared().env()->after_fork_child(state); fork_in_progress_ = false; } void InternalThreads::init() { mutex_.init(); } } <commit_msg>Fixed order for Environment::after_fork_child.<commit_after>#include "vm.hpp" #include "prelude.hpp" #include "environment.hpp" #include "internal_threads.hpp" #include "builtin/native_method.hpp" #include "dtrace/dtrace.h" #include "util/logger.hpp" namespace rubinius { using namespace utilities; #define AUXILIARY_THREAD_STACK_SIZE 0x100000 InternalThread::InternalThread(STATE, std::string name) : vm_(state->shared().new_vm()) , name_(name) , thread_running_(false) , metrics_(vm_->metrics()) , thread_exit_(false) { state->shared().internal_threads()->register_thread(this); } void* InternalThread::run(void* ptr) { InternalThread* thread = reinterpret_cast<InternalThread*>(ptr); VM* vm = thread->vm(); SharedState& shared = vm->shared; State state_obj(vm), *state = &state_obj; state->vm()->set_run_state(ManagedThread::eIndependent); RBX_DTRACE_CHAR_P thread_name = const_cast<RBX_DTRACE_CHAR_P>(thread->name_.c_str()); vm->set_name(thread_name); RUBINIUS_THREAD_START(const_cast<RBX_DTRACE_CHAR_P>(thread_name), vm->thread_id(), 1); NativeMethod::init_thread(state); thread->thread_running_ = true; thread->run(state); thread->thread_running_ = false; NativeMethod::cleanup_thread(state); RUBINIUS_THREAD_STOP(const_cast<RBX_DTRACE_CHAR_P>(thread_name), vm->thread_id(), 1); if(state->vm()->run_state() != ManagedThread::eIndependent) { shared.gc_independent(); } return 0; } void InternalThread::initialize(STATE) { thread_exit_ = false; thread_running_ = false; } void InternalThread::start(STATE) { initialize(state); start_thread(state); } void InternalThread::start_thread(STATE) { pthread_attr_t attrs; pthread_attr_init(&attrs); pthread_attr_setstacksize(&attrs, AUXILIARY_THREAD_STACK_SIZE); if(int error = pthread_create(&vm_->os_thread(), &attrs, InternalThread::run, (void*)this)) { logger::error("%s: %s: create thread failed", strerror(error), name_.c_str()); } } void InternalThread::wakeup(STATE) { thread_exit_ = true; atomic::memory_barrier(); } void InternalThread::stop_thread(STATE) { GCIndependent guard(state, 0); wakeup(state); void* return_value; pthread_t os = vm_->os_thread(); pthread_join(os, &return_value); } void InternalThread::stop(STATE) { state->shared().internal_threads()->unregister_thread(this); stop_thread(state); VM::discard(state, vm_); } void InternalThread::after_fork_child(STATE) { vm_ = state->shared().new_vm(); start(state); } void InternalThreads::register_thread(InternalThread* thread) { threads_.push_back(thread); } void InternalThreads::unregister_thread(InternalThread* thread) { threads_.remove(thread); } void InternalThreads::shutdown(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(shutdown_in_progress_) return; shutdown_in_progress_ = true; while(!threads_.empty()) { threads_.front()->stop(state); } shutdown_in_progress_ = false; } void InternalThreads::before_exec(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(exec_in_progress_) return; exec_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_exec(state); } state->shared().env()->before_exec(state); } void InternalThreads::after_exec(STATE) { // We don't guard here on the assumption that only one thread is running // after execvp() call. state->shared().env()->after_exec(state); for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_exec(state); } exec_in_progress_ = false; } void InternalThreads::before_fork_exec(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(fork_exec_in_progress_) return; fork_exec_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_fork_exec(state); } } void InternalThreads::after_fork_exec_parent(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_exec_parent(state); } fork_in_progress_ = false; } void InternalThreads::after_fork_exec_child(STATE) { // We don't guard here on the assumption that only one thread is running // after execvp() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_exec_child(state); } state->shared().env()->after_fork_exec_child(state); fork_exec_in_progress_ = false; } void InternalThreads::before_fork(STATE) { utilities::thread::Mutex::LockGuard guard(mutex_); if(fork_in_progress_) return; fork_in_progress_ = true; for(std::list<InternalThread*>::reverse_iterator i = threads_.rbegin(); i != threads_.rend(); ++i) { (*i)->before_fork(state); } } void InternalThreads::after_fork_parent(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_parent(state); } fork_in_progress_ = false; } void InternalThreads::after_fork_child(STATE) { // We don't guard here on the assumption that only one thread is running // after fork() call. state->shared().env()->after_fork_child(state); for(std::list<InternalThread*>::iterator i = threads_.begin(); i != threads_.end(); ++i) { (*i)->after_fork_child(state); } fork_in_progress_ = false; } void InternalThreads::init() { mutex_.init(); } } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <fstream> #include <cstdio> #include <sstream> #include <cassert> #include <vector> #include <string> #include <cstdlib> #include <iomanip> #include "bond_angle.h" using namespace std; extern unsigned int totalatoms; //referring to totalatoms in extraction.cpp extern vector< vector<string> > vector_coords; int bond_distance = 1.55; //average bond distance in Angstroms int i, j, k; string atom1_string, atom2_string; string x1_string, x2_string, y1_string, y2_string, z1_string, z2_string; //xyz coordinates as strings double x1_double, x2_double, y1_double, y2_double, z1_double, z2_double; //xyz coordinates as doubles double x1_unit, x2_unit, y1_unit, y2_unit, z1_unit, z2_unit; //xyz unit vectors vector<double> atomic_distance; //creation of 2D vector for interatomic distances vector< vector<int> > bond_exist; //creation of 2D vector: 1 for bond exists and 0 for bond does not exist vector< vector<double> > unit_vector; //creation of 2D vector for xyz unit vectors vector< vector< vector<double> > > bond_angle; //creation of 3D vector for bond angles void Bond_Angle::atom_dist() { ofstream log; log.open("log.txt", ios::app); cout << "Interatomic distances (in Angstroms): " << endl; for(i = 0; i < i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { atom1_string = (vector_coords[i][0]); atom2_string = (vector_coords[j][0]); x1_string = (vector_coords[i][2]); x2_string = (vector_coords[j][2]); y1_string = (vector_coords[i][3]); y2_string = (vector_coords[j][3]); z1_string = (vector_coords[i][4]); z2_string = (vector_coords[j][4]); x1_double = atof(x1_string.c_str()); //converting xyz coordinate strings to doubles x2_double = atof(x2_string.c_str()); y1_double = atof(y1_string.c_str()); y2_double = atof(y2_string.c_str()); z1_double = atof(z1_string.c_str()); z2_double = atof(z2_string.c_str()); double distance = (sqrt( ((pow(x2_double - x1_double, 2))) + ((pow(y2_double - y1_double, 2))) + //calculation of interatomic distances ((pow(z2_double - z1_double, 2))))); atomic_distance.push_back(distance); cout << atom1_string << " " << atom2_string << " " << distance << endl; } } for(i = 0; i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { if(atomic_distance[i] > bond_distance) { //if interatomic distance is greater than 1.55 Angstroms bond_exist[i][j] = 0; //0 for non-bonding } else bond_exist[i][j] = 1; //1 for bonding } } } void Bond_Angle::angle_phi() { ofstream log; log.open("log.txt", ios::app); cout << "Bond angles (in degrees): " << endl; for(i = 0; i < totalatoms; i++) { for(j = i + 1; j <= 4 ; j++) { x1_unit = unit_vector[i][2]; //placement of unit vectors in unit_vector x2_unit = unit_vector[j][2]; y1_unit = unit_vector[i][3]; y2_unit = unit_vector[j][3]; z1_unit = unit_vector[i][4]; z2_unit = unit_vector[j][4]; if(bond_exist[i][j] == 1) { x1_unit = ((-(x2_double - x1_double)) / atomic_distance[i]); //calculation of unit vectors between bonded atoms x2_unit = ((-(x2_double - x1_double)) / atomic_distance[i]); y1_unit = ((-(y2_double - y1_double)) / atomic_distance[i]); y2_unit = ((-(y2_double - y1_double)) / atomic_distance[i]); z1_unit = ((-(z2_double - z1_double)) / atomic_distance[i]); z2_unit = ((-(z2_double - z1_double)) / atomic_distance[i]); } } } for(i = 0; i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { for(k = j + 1; k < totalatoms; k++) { bond_angle[i][j][k] = (acos( (x1_unit) * (x2_unit) + (y1_unit) * (y2_unit) + //calculation of bond angle (z1_unit) * (z2_unit))); double angle_phi = bond_angle[i][j][k]; cout << i << " " << j << " " << k << " " << angle_phi << endl; } } } } <commit_msg>deleted distance stuff<commit_after>#include <iostream> #include <cmath> #include <fstream> #include <cstdio> #include <sstream> #include <cassert> #include <vector> #include <string> #include <cstdlib> #include <iomanip> #include "bond_angle.h" using namespace std; extern unsigned int totalatoms; //referring to totalatoms in extraction.cpp extern vector< vector<string> > vector_coords; int i, j, k; string atom1_string, atom2_string; string x1_string, x2_string, y1_string, y2_string, z1_string, z2_string; //xyz coordinates as strings double x1_double, x2_double, y1_double, y2_double, z1_double, z2_double; //xyz coordinates as doubles double x1_unit, x2_unit, y1_unit, y2_unit, z1_unit, z2_unit; //xyz unit vectors vector<double> atomic_distance; //creation of 2D vector for interatomic distances vector< vector<int> > bond_exist; //creation of 2D vector: 1 for bond exists and 0 for bond does not exist vector< vector<double> > unit_vector; //creation of 2D vector for xyz unit vectors vector< vector< vector<double> > > bond_angle; //creation of 3D vector for bond angles void Bond_Angle::angle_phi() { ofstream log; log.open("log.txt", ios::app); cout << "Bond angles (in degrees): " << endl; for(i = 0; i < totalatoms; i++) { for(j = i + 1; j <= 4 ; j++) { x1_unit = unit_vector[i][2]; //placement of unit vectors in unit_vector x2_unit = unit_vector[j][2]; y1_unit = unit_vector[i][3]; y2_unit = unit_vector[j][3]; z1_unit = unit_vector[i][4]; z2_unit = unit_vector[j][4]; if(bond_exist[i][j] == 1) { x1_unit = ((-(x2_double - x1_double)) / atomic_distance[i]); //calculation of unit vectors between bonded atoms x2_unit = ((-(x2_double - x1_double)) / atomic_distance[i]); y1_unit = ((-(y2_double - y1_double)) / atomic_distance[i]); y2_unit = ((-(y2_double - y1_double)) / atomic_distance[i]); z1_unit = ((-(z2_double - z1_double)) / atomic_distance[i]); z2_unit = ((-(z2_double - z1_double)) / atomic_distance[i]); } } } for(i = 0; i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { for(k = j + 1; k < totalatoms; k++) { bond_angle[i][j][k] = (acos( (x1_unit) * (x2_unit) + (y1_unit) * (y2_unit) + //calculation of bond angle (z1_unit) * (z2_unit))); double angle_phi = bond_angle[i][j][k]; cout << i << " " << j << " " << k << " " << angle_phi << endl; } } } } <|endoftext|>
<commit_before>#include "Platform.hpp" #include "genome.pb.h" #include "CellComponent.hpp" #include "ActivityStats.hpp" #include "Neuron.hpp" #include "Branch.hpp" #include "Synapse.hpp" #include "Base64.hpp" #include "Brain.hpp" #include "SimpleProteinEnvironment.hpp" #include <time.h> namespace Elysia { void testTwoConnectedNeurons() { ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment(); Brain *brain= new Brain(myProteinEnvironment); FILE *dendriteTree=NULL; dendriteTree = fopen("Dendritic_Tree.txt", "w"); std::vector<Neuron *> createdList; int neuronNumber = 2; for(int i=0;i<neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_bounds(); sourcebb->set_minx(i); sourcebb->set_miny(i); sourcebb->set_minz(i); sourcebb->set_maxx(i); sourcebb->set_maxy(i); sourcebb->set_maxz(i); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(1-i); targetbb->set_maxy(1-i); targetbb->set_maxz(2); Vector3f v; v.x = i; v.y = i; v.z = 1; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; n->developSynapse(n->getActivityStats()); size_t parent; parent = 0; n->visualizeTree(dendriteTree, parent); //const Vector3f &location): mNeuronLocation(location){)); } for(int j=0; j<10; j++){ for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; if(j== 0 && i==0){n->activateComponent(*brain,100);} //if(j== 2){brain->inactivateNeuron(n);} n->tick(); //const Vector3f &location): mNeuronLocation(location){)); } brain ->tick(); } fclose(dendriteTree); delete brain; } void testDevelopment(){ ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment(); Brain *brain= new Brain(myProteinEnvironment); FILE *dendriteTree=NULL; dendriteTree = fopen("Development_Tree.txt", "w"); std::vector<Neuron *> createdList; int neuronNumber = 4; for(int i=0;i<neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_target_region(); sourcebb->set_minx(50+i); sourcebb->set_miny(50+i); sourcebb->set_minz(50+i); sourcebb->set_maxx(150+i); sourcebb->set_maxy(150+i); sourcebb->set_maxz(150+i); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(i+1); targetbb->set_maxy(i+1); targetbb->set_maxz(i+1); Vector3f v; v.x = i; v.y = i; v.z = i; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(int i=100;i<100+neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_target_region(); sourcebb->set_minx(0); sourcebb->set_miny(0); sourcebb->set_minz(0); sourcebb->set_maxx(20); sourcebb->set_maxy(20); sourcebb->set_maxz(20); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(i+1); targetbb->set_maxy(i+1); targetbb->set_maxz(i+1); Vector3f v; v.x = i; v.y = i; v.z = i; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(float i=0;i<2*neuronNumber;i++){ Neuron *n = createdList[i]; n->developSynapse(n->getActivityStats()); size_t parent; parent = 0; n->visualizeTree(dendriteTree, parent); //const Vector3f &location): mNeuronLocation(location){)); } for(int j=0; j<10; j++){ for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; if(j==0){n->activateComponent(*brain,100);} n->tick(); //const Vector3f &location): mNeuronLocation(location){)); } brain ->tick(); } fclose(dendriteTree); delete brain; } void testResultHelper(const std::vector<std::pair<Elysia::Genome::Effect, float> >&combinedResult, float*grow_leaf_count,float*grow_neuron_count,float*other_count){ using namespace Elysia::Genome; *grow_neuron_count=0; *grow_leaf_count=0; *other_count=0; for (size_t i=0;i<combinedResult.size();++i) { switch(combinedResult[i].first) { case GROW_NEURON: *grow_neuron_count+=combinedResult[i].second; break; case GROW_LEAF: *grow_leaf_count+=combinedResult[i].second; break; default: *other_count+=combinedResult[i].second; break; } } } void testProteinEnvironment() { using namespace Elysia::Genome; Elysia::Genome::Genome twoOverlappingGenes; Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers(); Elysia::Genome::Gene firstGene; Elysia::Genome::Protein firstProtein; firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where firstProtein.set_density(0.125); Elysia::Genome::Protein firstAuxProtein; firstAuxProtein.set_protein_code(GROW_LEAF);//so we see that they are additive firstAuxProtein.set_density(0.25); *firstGene.add_external_proteins()=firstProtein; assert(firstGene.external_proteins(0).protein_code()==GROW_NEURON); *firstGene.add_external_proteins()=firstAuxProtein; assert(firstGene.external_proteins(1).protein_code()==GROW_LEAF); Elysia::Genome::TemporalBoundingBox firstRegion; firstRegion.set_minx(0); firstRegion.set_miny(0); firstRegion.set_minz(0); firstRegion.set_maxx(2); firstRegion.set_maxy(2); firstRegion.set_maxz(2); *firstGene.add_bounds()=firstRegion; Elysia::Genome::TemporalBoundingBox firstTargetRegion; firstTargetRegion.set_minx(5); firstTargetRegion.set_miny(5); firstTargetRegion.set_minz(5); firstTargetRegion.set_maxx(8); firstTargetRegion.set_maxy(8); firstTargetRegion.set_maxz(8); *firstGene.add_target_region()=firstTargetRegion; Elysia::Genome::Gene secondGene; Elysia::Genome::Protein secondProtein; secondProtein.set_protein_code(GROW_LEAF); secondProtein.set_density(0.5); *secondGene.add_external_proteins()=secondProtein; Elysia::Genome::TemporalBoundingBox secondRegion; secondRegion.set_minx(-1); secondRegion.set_miny(-1); secondRegion.set_minz(-1); secondRegion.set_maxx(1); secondRegion.set_maxy(1); secondRegion.set_maxz(1); *secondGene.add_bounds()=secondRegion; Elysia::Genome::TemporalBoundingBox secondTargetRegion; secondTargetRegion.set_minx(-5); secondTargetRegion.set_miny(-5); secondTargetRegion.set_minz(-5); secondTargetRegion.set_maxx(3); secondTargetRegion.set_maxy(3); secondTargetRegion.set_maxz(3); *secondGene.add_target_region()=secondTargetRegion; *father->add_genes()=firstGene; *father->add_genes()=secondGene; ProteinEnvironment * pe=new SimpleProteinEnvironment; pe->initialize(twoOverlappingGenes); std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,0)); //check that firstResult matches expectations std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,0)); //check that secondResult matches expectations std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,0)); float grow_leaf_count=0; float grow_neuron_count=0; float other_count=0; testResultHelper(combinedResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.75); assert(grow_neuron_count==.125); assert(other_count==0); testResultHelper(firstResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.25); assert(grow_neuron_count==.125); assert(other_count==0); testResultHelper(secondResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.5); assert(grow_neuron_count==0); assert(other_count==0); //return;//UNCOMMENT TO GET FAILING TEST const Gene * grow_neuron_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0), GROW_NEURON); const Gene * combined_grow_leaf_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0), GROW_LEAF); const Gene * first_grow_leaf_gene = &pe->retrieveGene(Vector3f(1.5,1.5,0), GROW_LEAF); const Gene * second_grow_leaf_gene = &pe->retrieveGene(Vector3f(-0.5,-0.5,0), GROW_LEAF); assert(grow_neuron_gene->target_region(0).minx()==5); assert(combined_grow_leaf_gene->target_region(0).minx()==5||combined_grow_leaf_gene->target_region(0).minx()==-5); assert(first_grow_leaf_gene->target_region(0).minx()==5); assert(second_grow_leaf_gene->target_region(0).minx()==-5); delete pe; } } int runtest(){ //Elysia::testTwoConnectedNeurons(); Elysia::testDevelopment(); Elysia::testProteinEnvironment(); if (0) for (int i=0;i<30000;++i) { Elysia::Brain b(new Elysia::SimpleProteinEnvironment); // usleep(10); } //getchar(); return 1; } <commit_msg>Added a function to make generating test neurons easier<commit_after>#include "Platform.hpp" #include "genome.pb.h" #include "CellComponent.hpp" #include "ActivityStats.hpp" #include "Neuron.hpp" #include "Branch.hpp" #include "Synapse.hpp" #include "Base64.hpp" #include "Brain.hpp" #include "SimpleProteinEnvironment.hpp" #include <time.h> namespace Elysia { void testTwoConnectedNeurons() { ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment(); Brain *brain= new Brain(myProteinEnvironment); FILE *dendriteTree=NULL; dendriteTree = fopen("Dendritic_Tree.txt", "w"); std::vector<Neuron *> createdList; int neuronNumber = 2; for(int i=0;i<neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_bounds(); sourcebb->set_minx(i); sourcebb->set_miny(i); sourcebb->set_minz(i); sourcebb->set_maxx(i); sourcebb->set_maxy(i); sourcebb->set_maxz(i); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(1-i); targetbb->set_maxy(1-i); targetbb->set_maxz(2); Vector3f v; v.x = i; v.y = i; v.z = 1; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; n->developSynapse(n->getActivityStats()); size_t parent; parent = 0; n->visualizeTree(dendriteTree, parent); //const Vector3f &location): mNeuronLocation(location){)); } for(int j=0; j<10; j++){ for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; if(j== 0 && i==0){n->activateComponent(*brain,100);} //if(j== 2){brain->inactivateNeuron(n);} n->tick(); //const Vector3f &location): mNeuronLocation(location){)); } brain ->tick(); } fclose(dendriteTree); delete brain; } //Target is axon, Source is dendrite (?) Neuron* placeTestNeuron(Brain* brain, float locx, float locy, float locz, float sx, float sy, float sz, float range){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_bounds(); sourcebb->set_minx(sx-range); sourcebb->set_miny(sy-range); sourcebb->set_minz(1); sourcebb->set_maxx(sx+range); sourcebb->set_maxy(sy+range); sourcebb->set_maxz(1); targetbb->set_minx(locx-range); targetbb->set_miny(locy-range); targetbb->set_minz(1); targetbb->set_maxx(locx+range); targetbb->set_maxy(locy+range); targetbb->set_maxz(1); Vector3f v; v.x = locx; v.y = locy; v.z = 1; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); return n; } void testDevelopment(){ ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment(); Brain *brain= new Brain(myProteinEnvironment); FILE *dendriteTree=NULL; dendriteTree = fopen("Development_Tree.txt", "w"); std::vector<Neuron *> createdList; int neuronNumber = 4; for(int i=0;i<neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_target_region(); sourcebb->set_minx(50+i); sourcebb->set_miny(50+i); sourcebb->set_minz(50+i); sourcebb->set_maxx(150+i); sourcebb->set_maxy(150+i); sourcebb->set_maxz(150+i); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(i+1); targetbb->set_maxy(i+1); targetbb->set_maxz(i+1); Vector3f v; v.x = i; v.y = i; v.z = i; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(int i=100;i<100+neuronNumber;i++){ Genome::Gene gene;//FIXME set source and target regions to match the desired behavior Genome::TemporalBoundingBox *sourcebb=gene.add_bounds(); Genome::TemporalBoundingBox *targetbb=gene.add_target_region(); sourcebb->set_minx(0); sourcebb->set_miny(0); sourcebb->set_minz(0); sourcebb->set_maxx(20); sourcebb->set_maxy(20); sourcebb->set_maxz(20); targetbb->set_minx(i); targetbb->set_miny(i); targetbb->set_minz(i); targetbb->set_maxx(i+1); targetbb->set_maxy(i+1); targetbb->set_maxz(i+1); Vector3f v; v.x = i; v.y = i; v.z = i; Neuron *n; srand(time(NULL)); brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene)); createdList.push_back(n); } for(float i=0;i<2*neuronNumber;i++){ Neuron *n = createdList[i]; n->developSynapse(n->getActivityStats()); size_t parent; parent = 0; n->visualizeTree(dendriteTree, parent); //const Vector3f &location): mNeuronLocation(location){)); } for(int j=0; j<10; j++){ for(float i=0;i<neuronNumber;i++){ Neuron *n = createdList[i]; if(j==0){n->activateComponent(*brain,100);} n->tick(); //const Vector3f &location): mNeuronLocation(location){)); } brain ->tick(); } fclose(dendriteTree); delete brain; } void testResultHelper(const std::vector<std::pair<Elysia::Genome::Effect, float> >&combinedResult, float*grow_leaf_count,float*grow_neuron_count,float*other_count){ using namespace Elysia::Genome; *grow_neuron_count=0; *grow_leaf_count=0; *other_count=0; for (size_t i=0;i<combinedResult.size();++i) { switch(combinedResult[i].first) { case GROW_NEURON: *grow_neuron_count+=combinedResult[i].second; break; case GROW_LEAF: *grow_leaf_count+=combinedResult[i].second; break; default: *other_count+=combinedResult[i].second; break; } } } void testProteinEnvironment() { using namespace Elysia::Genome; Elysia::Genome::Genome twoOverlappingGenes; Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers(); Elysia::Genome::Gene firstGene; Elysia::Genome::Protein firstProtein; firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where firstProtein.set_density(0.125); Elysia::Genome::Protein firstAuxProtein; firstAuxProtein.set_protein_code(GROW_LEAF);//so we see that they are additive firstAuxProtein.set_density(0.25); *firstGene.add_external_proteins()=firstProtein; assert(firstGene.external_proteins(0).protein_code()==GROW_NEURON); *firstGene.add_external_proteins()=firstAuxProtein; assert(firstGene.external_proteins(1).protein_code()==GROW_LEAF); Elysia::Genome::TemporalBoundingBox firstRegion; firstRegion.set_minx(0); firstRegion.set_miny(0); firstRegion.set_minz(0); firstRegion.set_maxx(2); firstRegion.set_maxy(2); firstRegion.set_maxz(2); *firstGene.add_bounds()=firstRegion; Elysia::Genome::TemporalBoundingBox firstTargetRegion; firstTargetRegion.set_minx(5); firstTargetRegion.set_miny(5); firstTargetRegion.set_minz(5); firstTargetRegion.set_maxx(8); firstTargetRegion.set_maxy(8); firstTargetRegion.set_maxz(8); *firstGene.add_target_region()=firstTargetRegion; Elysia::Genome::Gene secondGene; Elysia::Genome::Protein secondProtein; secondProtein.set_protein_code(GROW_LEAF); secondProtein.set_density(0.5); *secondGene.add_external_proteins()=secondProtein; Elysia::Genome::TemporalBoundingBox secondRegion; secondRegion.set_minx(-1); secondRegion.set_miny(-1); secondRegion.set_minz(-1); secondRegion.set_maxx(1); secondRegion.set_maxy(1); secondRegion.set_maxz(1); *secondGene.add_bounds()=secondRegion; Elysia::Genome::TemporalBoundingBox secondTargetRegion; secondTargetRegion.set_minx(-5); secondTargetRegion.set_miny(-5); secondTargetRegion.set_minz(-5); secondTargetRegion.set_maxx(3); secondTargetRegion.set_maxy(3); secondTargetRegion.set_maxz(3); *secondGene.add_target_region()=secondTargetRegion; *father->add_genes()=firstGene; *father->add_genes()=secondGene; ProteinEnvironment * pe=new SimpleProteinEnvironment; pe->initialize(twoOverlappingGenes); std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,0)); //check that firstResult matches expectations std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,0)); //check that secondResult matches expectations std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,0)); float grow_leaf_count=0; float grow_neuron_count=0; float other_count=0; testResultHelper(combinedResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.75); assert(grow_neuron_count==.125); assert(other_count==0); testResultHelper(firstResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.25); assert(grow_neuron_count==.125); assert(other_count==0); testResultHelper(secondResult,&grow_leaf_count,&grow_neuron_count,&other_count); assert(grow_leaf_count==.5); assert(grow_neuron_count==0); assert(other_count==0); //return;//UNCOMMENT TO GET FAILING TEST const Gene * grow_neuron_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0), GROW_NEURON); const Gene * combined_grow_leaf_gene = &pe->retrieveGene(Vector3f(0.5,0.5,0), GROW_LEAF); const Gene * first_grow_leaf_gene = &pe->retrieveGene(Vector3f(1.5,1.5,0), GROW_LEAF); const Gene * second_grow_leaf_gene = &pe->retrieveGene(Vector3f(-0.5,-0.5,0), GROW_LEAF); assert(grow_neuron_gene->target_region(0).minx()==5); assert(combined_grow_leaf_gene->target_region(0).minx()==5||combined_grow_leaf_gene->target_region(0).minx()==-5); assert(first_grow_leaf_gene->target_region(0).minx()==5); assert(second_grow_leaf_gene->target_region(0).minx()==-5); delete pe; } } int runtest(){ //Elysia::testTwoConnectedNeurons(); Elysia::testDevelopment(); Elysia::testProteinEnvironment(); if (0) for (int i=0;i<30000;++i) { Elysia::Brain b(new Elysia::SimpleProteinEnvironment); // usleep(10); } //getchar(); return 1; } <|endoftext|>
<commit_before>// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <core_io.h> #include <core_memusage.h> #include <pubkey.h> #include <primitives/block.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <validation.h> #include <version.h> #include <cassert> #include <string> void initialize() { const static auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); CBlock block; try { int nVersion; ds >> nVersion; ds.SetVersion(nVersion); ds >> block; } catch (const std::ios_base::failure&) { return; } const Consensus::Params& consensus_params = Params().GetConsensus(); BlockValidationState validation_state_pow_and_merkle; const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_pow; const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false); BlockValidationState validation_state_merkle; const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_none; const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false); if (valid_incl_pow_and_merkle) { assert(valid_incl_pow && valid_incl_merkle && valid_incl_none); } else if (valid_incl_merkle || valid_incl_pow) { assert(valid_incl_none); } (void)block.GetHash(); (void)block.ToString(); (void)BlockMerkleRoot(block); if (!block.vtx.empty()) { // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot // when block.vtx.empty(). (void)BlockWitnessMerkleRoot(block); } (void)GetBlockWeight(block); (void)GetWitnessCommitmentIndex(block); (void)RecursiveDynamicUsage(block); } <commit_msg>tests: Fuzz RecursiveDynamicUsage(const std::shared_ptr<X>& p)<commit_after>// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <consensus/validation.h> #include <core_io.h> #include <core_memusage.h> #include <pubkey.h> #include <primitives/block.h> #include <streams.h> #include <test/fuzz/fuzz.h> #include <validation.h> #include <version.h> #include <cassert> #include <memory> #include <string> void initialize() { const static auto verify_handle = MakeUnique<ECCVerifyHandle>(); SelectParams(CBaseChainParams::REGTEST); } void test_one_input(const std::vector<uint8_t>& buffer) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); CBlock block; try { int nVersion; ds >> nVersion; ds.SetVersion(nVersion); ds >> block; } catch (const std::ios_base::failure&) { return; } const Consensus::Params& consensus_params = Params().GetConsensus(); BlockValidationState validation_state_pow_and_merkle; const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_pow; const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false); BlockValidationState validation_state_merkle; const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true); BlockValidationState validation_state_none; const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false); if (valid_incl_pow_and_merkle) { assert(valid_incl_pow && valid_incl_merkle && valid_incl_none); } else if (valid_incl_merkle || valid_incl_pow) { assert(valid_incl_none); } (void)block.GetHash(); (void)block.ToString(); (void)BlockMerkleRoot(block); if (!block.vtx.empty()) { // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot // when block.vtx.empty(). (void)BlockWitnessMerkleRoot(block); } (void)GetBlockWeight(block); (void)GetWitnessCommitmentIndex(block); const size_t raw_memory_size = RecursiveDynamicUsage(block); const size_t raw_memory_size_as_shared_ptr = RecursiveDynamicUsage(std::make_shared<CBlock>(block)); assert(raw_memory_size_as_shared_ptr > raw_memory_size); } <|endoftext|>
<commit_before>// Copyright (c) 2013-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <hash.h> #include <utilstrencodings.h> #include <test/test_bitcoin.h> #include <vector> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(murmurhash3) { #define T(expected, seed, data) BOOST_CHECK_EQUAL(MurmurHash3(seed, ParseHex(data)), expected) // Test MurmurHash3 with various inputs. Of course this is retested in the // bloom filter tests - they would fail if MurmurHash3() had any problems - // but is useful for those trying to implement Bitcoin libraries as a // source of test data for their MurmurHash3() primitive during // development. // // The magic number 0xFBA4C795 comes from CBloomFilter::Hash() T(0x00000000, 0x00000000, ""); T(0x6a396f08, 0xFBA4C795, ""); T(0x81f16f39, 0xffffffff, ""); T(0x514e28b7, 0x00000000, "00"); T(0xea3f0b17, 0xFBA4C795, "00"); T(0xfd6cf10d, 0x00000000, "ff"); T(0x16c6b7ab, 0x00000000, "0011"); T(0x8eb51c3d, 0x00000000, "001122"); T(0xb4471bf8, 0x00000000, "00112233"); T(0xe2301fa8, 0x00000000, "0011223344"); T(0xfc2e4a15, 0x00000000, "001122334455"); T(0xb074502c, 0x00000000, "00112233445566"); T(0x8034d2a0, 0x00000000, "0011223344556677"); T(0xb4698def, 0x00000000, "001122334455667788"); #undef T } /* SipHash-2-4 output with k = 00 01 02 ... and in = (empty string) in = 00 (1 byte) in = 00 01 (2 bytes) in = 00 01 02 (3 bytes) ... in = 00 01 02 ... 3e (63 bytes) from: https://131002.net/siphash/siphash24.c */ uint64_t siphash_4_2_testvec[] = { 0x726fdb47dd0e0e31, 0x74f839c593dc67fd, 0x0d6c8009d9a94f5a, 0x85676696d7fb7e2d, 0xcf2794e0277187b7, 0x18765564cd99a68d, 0xcbc9466e58fee3ce, 0xab0200f58b01d137, 0x93f5f5799a932462, 0x9e0082df0ba9e4b0, 0x7a5dbbc594ddb9f3, 0xf4b32f46226bada7, 0x751e8fbc860ee5fb, 0x14ea5627c0843d90, 0xf723ca908e7af2ee, 0xa129ca6149be45e5, 0x3f2acc7f57c29bdb, 0x699ae9f52cbe4794, 0x4bc1b3f0968dd39c, 0xbb6dc91da77961bd, 0xbed65cf21aa2ee98, 0xd0f2cbb02e3b67c7, 0x93536795e3a33e88, 0xa80c038ccd5ccec8, 0xb8ad50c6f649af94, 0xbce192de8a85b8ea, 0x17d835b85bbb15f3, 0x2f2e6163076bcfad, 0xde4daaaca71dc9a5, 0xa6a2506687956571, 0xad87a3535c49ef28, 0x32d892fad841c342, 0x7127512f72f27cce, 0xa7f32346f95978e3, 0x12e0b01abb051238, 0x15e034d40fa197ae, 0x314dffbe0815a3b4, 0x027990f029623981, 0xcadcd4e59ef40c4d, 0x9abfd8766a33735c, 0x0e3ea96b5304a7d0, 0xad0c42d6fc585992, 0x187306c89bc215a9, 0xd4a60abcf3792b95, 0xf935451de4f21df2, 0xa9538f0419755787, 0xdb9acddff56ca510, 0xd06c98cd5c0975eb, 0xe612a3cb9ecba951, 0xc766e62cfcadaf96, 0xee64435a9752fe72, 0xa192d576b245165a, 0x0a8787bf8ecb74b2, 0x81b3e73d20b49b6f, 0x7fa8220ba3b2ecea, 0x245731c13ca42499, 0xb78dbfaf3a8d83bd, 0xea1ad565322a1a0b, 0x60e61c23a3795013, 0x6606d7e446282b93, 0x6ca4ecb15c5f91e1, 0x9f626da15c9625f3, 0xe51b38608ef25f57, 0x958a324ceb064572 }; BOOST_AUTO_TEST_CASE(siphash) { CSipHasher hasher(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x726fdb47dd0e0e31ull); static const unsigned char t0[1] = {0}; hasher.Write(t0, 1); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x74f839c593dc67fdull); static const unsigned char t1[7] = {1,2,3,4,5,6,7}; hasher.Write(t1, 7); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x93f5f5799a932462ull); hasher.Write(0x0F0E0D0C0B0A0908ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x3f2acc7f57c29bdbull); static const unsigned char t2[2] = {16,17}; hasher.Write(t2, 2); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x4bc1b3f0968dd39cull); static const unsigned char t3[9] = {18,19,20,21,22,23,24,25,26}; hasher.Write(t3, 9); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x2f2e6163076bcfadull); static const unsigned char t4[5] = {27,28,29,30,31}; hasher.Write(t4, 5); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x7127512f72f27cceull); hasher.Write(0x2726252423222120ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x0e3ea96b5304a7d0ull); hasher.Write(0x2F2E2D2C2B2A2928ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0xe612a3cb9ecba951ull); BOOST_CHECK_EQUAL(SipHashUint256(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL, uint256S("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")), 0x7127512f72f27cceull); // Check test vectors from spec, one byte at a time CSipHasher hasher2(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); ++x) { BOOST_CHECK_EQUAL(hasher2.Finalize(), siphash_4_2_testvec[x]); hasher2.Write(&x, 1); } // Check test vectors from spec, eight bytes at a time CSipHasher hasher3(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); x+=8) { BOOST_CHECK_EQUAL(hasher3.Finalize(), siphash_4_2_testvec[x]); hasher3.Write(uint64_t(x)|(uint64_t(x+1)<<8)|(uint64_t(x+2)<<16)|(uint64_t(x+3)<<24)| (uint64_t(x+4)<<32)|(uint64_t(x+5)<<40)|(uint64_t(x+6)<<48)|(uint64_t(x+7)<<56)); } CHashWriter ss(SER_DISK, CLIENT_VERSION); CMutableTransaction tx; // Note these tests were originally written with tx.nVersion=1 // and the test would be affected by default tx version bumps if not fixed. tx.nVersion = 1; ss << tx; BOOST_CHECK_EQUAL(SipHashUint256(1, 2, ss.GetHash()), 0x79751e980c2a0a35ULL); // Check consistency between CSipHasher and SipHashUint256[Extra]. FastRandomContext ctx; for (int i = 0; i < 16; ++i) { uint64_t k1 = ctx.rand64(); uint64_t k2 = ctx.rand64(); uint256 x = InsecureRand256(); uint32_t n = ctx.rand32(); uint8_t nb[4]; WriteLE32(nb, n); CSipHasher sip256(k1, k2); sip256.Write(x.begin(), 32); CSipHasher sip288 = sip256; sip288.Write(nb, 4); BOOST_CHECK_EQUAL(SipHashUint256(k1, k2, x), sip256.Finalize()); BOOST_CHECK_EQUAL(SipHashUint256Extra(k1, k2, x, n), sip288.Finalize()); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fix hash tests<commit_after>// Copyright (c) 2013-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <hash.h> #include <utilstrencodings.h> #include <test/test_bitcoin.h> #include <vector> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(hash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(murmurhash3) { #define T(expected, seed, data) BOOST_CHECK_EQUAL(MurmurHash3(seed, ParseHex(data)), expected) // Test MurmurHash3 with various inputs. Of course this is retested in the // bloom filter tests - they would fail if MurmurHash3() had any problems - // but is useful for those trying to implement Bitcoin libraries as a // source of test data for their MurmurHash3() primitive during // development. // // The magic number 0xFBA4C795 comes from CBloomFilter::Hash() T(0x00000000, 0x00000000, ""); T(0x6a396f08, 0xFBA4C795, ""); T(0x81f16f39, 0xffffffff, ""); T(0x514e28b7, 0x00000000, "00"); T(0xea3f0b17, 0xFBA4C795, "00"); T(0xfd6cf10d, 0x00000000, "ff"); T(0x16c6b7ab, 0x00000000, "0011"); T(0x8eb51c3d, 0x00000000, "001122"); T(0xb4471bf8, 0x00000000, "00112233"); T(0xe2301fa8, 0x00000000, "0011223344"); T(0xfc2e4a15, 0x00000000, "001122334455"); T(0xb074502c, 0x00000000, "00112233445566"); T(0x8034d2a0, 0x00000000, "0011223344556677"); T(0xb4698def, 0x00000000, "001122334455667788"); #undef T } /* SipHash-2-4 output with k = 00 01 02 ... and in = (empty string) in = 00 (1 byte) in = 00 01 (2 bytes) in = 00 01 02 (3 bytes) ... in = 00 01 02 ... 3e (63 bytes) from: https://131002.net/siphash/siphash24.c */ uint64_t siphash_4_2_testvec[] = { 0x726fdb47dd0e0e31, 0x74f839c593dc67fd, 0x0d6c8009d9a94f5a, 0x85676696d7fb7e2d, 0xcf2794e0277187b7, 0x18765564cd99a68d, 0xcbc9466e58fee3ce, 0xab0200f58b01d137, 0x93f5f5799a932462, 0x9e0082df0ba9e4b0, 0x7a5dbbc594ddb9f3, 0xf4b32f46226bada7, 0x751e8fbc860ee5fb, 0x14ea5627c0843d90, 0xf723ca908e7af2ee, 0xa129ca6149be45e5, 0x3f2acc7f57c29bdb, 0x699ae9f52cbe4794, 0x4bc1b3f0968dd39c, 0xbb6dc91da77961bd, 0xbed65cf21aa2ee98, 0xd0f2cbb02e3b67c7, 0x93536795e3a33e88, 0xa80c038ccd5ccec8, 0xb8ad50c6f649af94, 0xbce192de8a85b8ea, 0x17d835b85bbb15f3, 0x2f2e6163076bcfad, 0xde4daaaca71dc9a5, 0xa6a2506687956571, 0xad87a3535c49ef28, 0x32d892fad841c342, 0x7127512f72f27cce, 0xa7f32346f95978e3, 0x12e0b01abb051238, 0x15e034d40fa197ae, 0x314dffbe0815a3b4, 0x027990f029623981, 0xcadcd4e59ef40c4d, 0x9abfd8766a33735c, 0x0e3ea96b5304a7d0, 0xad0c42d6fc585992, 0x187306c89bc215a9, 0xd4a60abcf3792b95, 0xf935451de4f21df2, 0xa9538f0419755787, 0xdb9acddff56ca510, 0xd06c98cd5c0975eb, 0xe612a3cb9ecba951, 0xc766e62cfcadaf96, 0xee64435a9752fe72, 0xa192d576b245165a, 0x0a8787bf8ecb74b2, 0x81b3e73d20b49b6f, 0x7fa8220ba3b2ecea, 0x245731c13ca42499, 0xb78dbfaf3a8d83bd, 0xea1ad565322a1a0b, 0x60e61c23a3795013, 0x6606d7e446282b93, 0x6ca4ecb15c5f91e1, 0x9f626da15c9625f3, 0xe51b38608ef25f57, 0x958a324ceb064572 }; BOOST_AUTO_TEST_CASE(siphash) { CSipHasher hasher(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x726fdb47dd0e0e31ull); static const unsigned char t0[1] = {0}; hasher.Write(t0, 1); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x74f839c593dc67fdull); static const unsigned char t1[7] = {1,2,3,4,5,6,7}; hasher.Write(t1, 7); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x93f5f5799a932462ull); hasher.Write(0x0F0E0D0C0B0A0908ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x3f2acc7f57c29bdbull); static const unsigned char t2[2] = {16,17}; hasher.Write(t2, 2); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x4bc1b3f0968dd39cull); static const unsigned char t3[9] = {18,19,20,21,22,23,24,25,26}; hasher.Write(t3, 9); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x2f2e6163076bcfadull); static const unsigned char t4[5] = {27,28,29,30,31}; hasher.Write(t4, 5); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x7127512f72f27cceull); hasher.Write(0x2726252423222120ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0x0e3ea96b5304a7d0ull); hasher.Write(0x2F2E2D2C2B2A2928ULL); BOOST_CHECK_EQUAL(hasher.Finalize(), 0xe612a3cb9ecba951ull); BOOST_CHECK_EQUAL(SipHashUint256(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL, uint256S("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")), 0x7127512f72f27cceull); // Check test vectors from spec, one byte at a time CSipHasher hasher2(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); ++x) { BOOST_CHECK_EQUAL(hasher2.Finalize(), siphash_4_2_testvec[x]); hasher2.Write(&x, 1); } // Check test vectors from spec, eight bytes at a time CSipHasher hasher3(0x0706050403020100ULL, 0x0F0E0D0C0B0A0908ULL); for (uint8_t x=0; x<ARRAYLEN(siphash_4_2_testvec); x+=8) { BOOST_CHECK_EQUAL(hasher3.Finalize(), siphash_4_2_testvec[x]); hasher3.Write(uint64_t(x)|(uint64_t(x+1)<<8)|(uint64_t(x+2)<<16)|(uint64_t(x+3)<<24)| (uint64_t(x+4)<<32)|(uint64_t(x+5)<<40)|(uint64_t(x+6)<<48)|(uint64_t(x+7)<<56)); } CHashWriter ss(SER_DISK, CLIENT_VERSION); CMutableTransaction tx; // Note these tests were originally written with tx.nVersion=1 // and the test would be affected by default tx version bumps if not fixed. tx.nVersion = 1; tx.nTime = 0; ss << tx; BOOST_CHECK_EQUAL(SipHashUint256(1, 2, ss.GetHash()), 0x1708BAA2A6B3C73ULL); // Check consistency between CSipHasher and SipHashUint256[Extra]. FastRandomContext ctx; for (int i = 0; i < 16; ++i) { uint64_t k1 = ctx.rand64(); uint64_t k2 = ctx.rand64(); uint256 x = InsecureRand256(); uint32_t n = ctx.rand32(); uint8_t nb[4]; WriteLE32(nb, n); CSipHasher sip256(k1, k2); sip256.Write(x.begin(), 32); CSipHasher sip288 = sip256; sip288.Write(nb, 4); BOOST_CHECK_EQUAL(SipHashUint256(k1, k2, x), sip256.Finalize()); BOOST_CHECK_EQUAL(SipHashUint256Extra(k1, k2, x, n), sip288.Finalize()); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before> #include "common_headers.h" #include "all_tests.h" #include "common.h" #include "errors.h" namespace circa { void register_branch_tests(); void register_builtin_function_tests(); void register_list_tests(); void register_parser_tests(); void register_primitive_type_tests(); void register_subroutine_tests(); void register_struct_tests(); void register_tokenizer_tests(); void run_all_tests() { gTestCases.clear(); register_branch_tests(); register_builtin_function_tests(); register_list_tests(); register_parser_tests(); register_primitive_type_tests(); register_subroutine_tests(); register_struct_tests(); register_tokenizer_tests(); std::vector<TestCase>::iterator it; int totalTestCount = (int) gTestCases.size(); int numSuccess = 0; int numFailure = 0; for (it = gTestCases.begin(); it != gTestCases.end(); ++it) { try { it->execute(); numSuccess++; } catch (errors::CircaError &err) { std::cout << "Error white running test case " << it->name << std::endl; std::cout << err.message() << std::endl; numFailure++; } } std::cout << "Ran " << totalTestCount << " tests, " << numSuccess << " success(es) and " << numFailure << " failure(s)." << std::endl; } } <commit_msg>Make test output prettier<commit_after> #include "common_headers.h" #include "all_tests.h" #include "common.h" #include "errors.h" namespace circa { void register_branch_tests(); void register_builtin_function_tests(); void register_list_tests(); void register_parser_tests(); void register_primitive_type_tests(); void register_subroutine_tests(); void register_struct_tests(); void register_tokenizer_tests(); void run_all_tests() { gTestCases.clear(); register_branch_tests(); register_builtin_function_tests(); register_list_tests(); register_parser_tests(); register_primitive_type_tests(); register_subroutine_tests(); register_struct_tests(); register_tokenizer_tests(); std::vector<TestCase>::iterator it; int totalTestCount = (int) gTestCases.size(); int successCount = 0; int failureCount = 0; for (it = gTestCases.begin(); it != gTestCases.end(); ++it) { try { it->execute(); successCount++; } catch (errors::CircaError &err) { std::cout << "Error white running test case " << it->name << std::endl; std::cout << err.message() << std::endl; failureCount++; } } std::string successes = successCount == 1 ? "success" : "sucesses"; std::string failures = failureCount == 1 ? "failure" : "failures"; std::cout << "Ran " << totalTestCount << " tests, " << successCount << " " << successes << " and " << failureCount << " " << failures << "." << std::endl; } } <|endoftext|>
<commit_before>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QtNetwork> #include <QStringList> #include <QSettings> #include "settings-mgr.h" #include "account-mgr.h" #include "seafile-applet.h" #include "api/api-error.h" #include "api/requests.h" #include "login-dialog.h" #include "utils/utils.h" #ifdef HAVE_SHIBBOLETH_SUPPORT #include "shib/shib-login-dialog.h" #endif // HAVE_SHIBBOLETH_SUPPORT namespace { const char *kDefaultServerAddr1 = "https://seacloud.cc"; const char *kUsedServerAddresses = "UsedServerAddresses"; const char *const kPreconfigureServerAddr = "PreconfigureServerAddr"; const char *const kPreconfigureServerAddrOnly = "PreconfigureServerAddrOnly"; const char *const kPreconfigureShibbolethLoginUrl = "PreconfigureShibbolethLoginUrl"; const char *const kSeafileOTPHeader = "X-Seafile-OTP"; QStringList getUsedServerAddresses() { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList retval = settings.value("main").toStringList(); settings.endGroup(); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (!preconfigure_addr.isEmpty() && !retval.contains(preconfigure_addr)) { retval.push_back(preconfigure_addr); } if (!retval.contains(kDefaultServerAddr1)) { retval.push_back(kDefaultServerAddr1); } return retval; } void saveUsedServerAddresses(const QString &new_address) { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList list = settings.value("main").toStringList(); // put the last used address to the front list.removeAll(new_address); list.insert(0, new_address); settings.setValue("main", list); settings.endGroup(); } } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); request_ = NULL; account_info_req_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (seafApplet->readPreconfigureEntry(kPreconfigureServerAddrOnly).toBool() && !preconfigure_addr.isEmpty()) { mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, preconfigure_addr); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); } else { mServerAddr->addItems(getUsedServerAddresses()); mServerAddr->clearEditText(); } mServerAddr->setAutoCompletion(false); QString computerName = seafApplet->settingsManager()->getComputerName(); mComputerName->setText(computerName); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); #ifdef HAVE_SHIBBOLETH_SUPPORT setupShibLoginLink(); #else mShibLoginLink->hide(); #endif } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::setupShibLoginLink() { QString txt = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("Shibboleth Login")); mShibLoginLink->setText(txt); connect(mShibLoginLink, SIGNAL(linkActivated(const QString&)), this, SLOT(loginWithShib())); } #endif // HAVE_SHIBBOLETH_SUPPORT void LoginDialog::initFromAccount(const Account& account) { setWindowTitle(tr("Re-login")); mTitle->setText(tr("Re-login")); mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, account.serverUrl.toString()); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); mUsername->setText(account.username); mPassword->setFocus(Qt::OtherFocusReason); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } saveUsedServerAddresses(url_.toString()); mStatusText->setText(tr("Logging in...")); disableInputs(); if (request_) { request_->deleteLater(); } request_ = new LoginRequest(url_, username_, password_, computer_name_); if (!two_factor_auth_token_.isEmpty()) { request_->setHeader(kSeafileOTPHeader, two_factor_auth_token_); } connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(const ApiError&)), this, SLOT(loginFailed(const ApiError&))); request_->send(); } void LoginDialog::disableInputs() { mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); mComputerName->setEnabled(false); } void LoginDialog::enableInputs() { mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mSubmitBtn->setEnabled(true); mComputerName->setEnabled(true); } void LoginDialog::onNetworkError(const QNetworkReply::NetworkError& error, const QString& error_string) { showWarning(tr("Network Error:\n %1").arg(error_string)); enableInputs(); mStatusText->setText(""); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { const QSslCertificate &cert = reply->sslConfiguration().peerCertificate(); qDebug() << "\n= SslErrors =\n" << dumpSslErrors(errors); qDebug() << "\n= Certificate =\n" << dumpCertificate(cert); if (seafApplet->detailedYesOrNoBox(tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"), dumpSslErrors(errors) + dumpCertificate(cert), this, false)) reply->ignoreSslErrors(); } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->currentText(); QString protocol; QUrl url; if (serverAddr.size() == 0) { showWarning(tr("Please enter the server address")); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } } QString email = mUsername->text(); if (email.size() == 0) { showWarning(tr("Please enter the username")); return false; } if (mPassword->text().size() == 0) { showWarning(tr("Please enter the password")); return false; } QString computer_name = mComputerName->text().trimmed(); if (computer_name.size() == 0) { showWarning(tr("Please enter the computer name")); return false; } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); computer_name_ = mComputerName->text(); seafApplet->settingsManager()->setComputerName(computer_name_); return true; } void LoginDialog::loginSuccess(const QString& token) { if (account_info_req_) { account_info_req_->deleteLater(); } account_info_req_ = new FetchAccountInfoRequest(Account(url_, username_, token)); connect(account_info_req_, SIGNAL(success(const AccountInfo&)), this, SLOT(onFetchAccountInfoSuccess(const AccountInfo&))); connect(account_info_req_, SIGNAL(failed(const ApiError&)), this, SLOT(onFetchAccountInfoFailed(const ApiError&))); account_info_req_->send(); } void LoginDialog::onFetchAccountInfoFailed(const ApiError& error) { loginFailed(error); } void LoginDialog::loginFailed(const ApiError& error) { switch (error.type()) { case ApiError::SSL_ERROR: onSslErrors(error.sslReply(), error.sslErrors()); break; case ApiError::NETWORK_ERROR: onNetworkError(error.networkError(), error.networkErrorString()); break; case ApiError::HTTP_ERROR: onHttpError(error.httpErrorCode()); default: // impossible break; } } void LoginDialog::onFetchAccountInfoSuccess(const AccountInfo& info) { Account account = account_info_req_->account(); // The user may use the username to login, but we need to store the email // to account database account.username = info.email; if (seafApplet->accountManager()->saveAccount(account) < 0) { showWarning(tr("Failed to save current account")); } else { seafApplet->accountManager()->updateAccountInfo(account, info); done(QDialog::Accepted); } } void LoginDialog::onHttpError(int code) { const QNetworkReply* reply = request_->reply(); if (reply->hasRawHeader(kSeafileOTPHeader) && QString(reply->rawHeader(kSeafileOTPHeader)) == "required") { two_factor_auth_token_ = seafApplet->getText( this, tr("Two Factor Authentication"), tr("Enter the two factor authentication token"), QLineEdit::Normal, ""); if (!two_factor_auth_token_.isEmpty()) { doLogin(); return; } } else { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code == 429) { reason = tr("Logging in too frequently, please wait a minute"); } else if (code == 500) { reason = tr("Internal Server Error"); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } showWarning(err_msg); } enableInputs(); mStatusText->setText(""); } void LoginDialog::showWarning(const QString& msg) { seafApplet->warningBox(msg, this); } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::loginWithShib() { bool ok = true; QUrl url; QString serverAddr = seafApplet->readPreconfigureEntry(kPreconfigureShibbolethLoginUrl) .toString() .trimmed(); if (!serverAddr.isEmpty()) { if (QUrl(serverAddr).isValid()) { qWarning("Using preconfigured shibboleth login url: %s\n", toCStr(serverAddr)); } else { qWarning("Invalid preconfigured shibboleth login url: %s\n", toCStr(serverAddr)); serverAddr = ""; } } if (serverAddr.isEmpty()) { // When we reach here, there is no preconfigured shibboleth login url, // or the preconfigured url is invalid. So we ask the user for the url. serverAddr = seafApplet->settingsManager()->getLastShibUrl(); while (ok) { serverAddr = seafApplet->getText(this, tr("Shibboleth Login"), tr("%1 Server Address").arg(getBrand()), QLineEdit::Normal, serverAddr, &ok); serverAddr = serverAddr.trimmed(); // exit when user hits cancel button if (!ok) { return; } if (serverAddr.isEmpty()) { showWarning(tr("Server address must not be empty.").arg(serverAddr)); continue; } if (!serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address. It has to start with 'https://'.").arg(serverAddr)); continue; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); continue; } // exit loop, if everything is okay break; } } seafApplet->settingsManager()->setLastShibUrl(serverAddr); ShibLoginDialog shib_dialog(url, mComputerName->text(), this); if (shib_dialog.exec() == QDialog::Accepted) { accept(); } } #endif // HAVE_SHIBBOLETH_SUPPORT <commit_msg>Improved punctuation. Ref #953.<commit_after>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QtNetwork> #include <QStringList> #include <QSettings> #include "settings-mgr.h" #include "account-mgr.h" #include "seafile-applet.h" #include "api/api-error.h" #include "api/requests.h" #include "login-dialog.h" #include "utils/utils.h" #ifdef HAVE_SHIBBOLETH_SUPPORT #include "shib/shib-login-dialog.h" #endif // HAVE_SHIBBOLETH_SUPPORT namespace { const char *kDefaultServerAddr1 = "https://seacloud.cc"; const char *kUsedServerAddresses = "UsedServerAddresses"; const char *const kPreconfigureServerAddr = "PreconfigureServerAddr"; const char *const kPreconfigureServerAddrOnly = "PreconfigureServerAddrOnly"; const char *const kPreconfigureShibbolethLoginUrl = "PreconfigureShibbolethLoginUrl"; const char *const kSeafileOTPHeader = "X-Seafile-OTP"; QStringList getUsedServerAddresses() { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList retval = settings.value("main").toStringList(); settings.endGroup(); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (!preconfigure_addr.isEmpty() && !retval.contains(preconfigure_addr)) { retval.push_back(preconfigure_addr); } if (!retval.contains(kDefaultServerAddr1)) { retval.push_back(kDefaultServerAddr1); } return retval; } void saveUsedServerAddresses(const QString &new_address) { QSettings settings; settings.beginGroup(kUsedServerAddresses); QStringList list = settings.value("main").toStringList(); // put the last used address to the front list.removeAll(new_address); list.insert(0, new_address); settings.setValue("main", list); settings.endGroup(); } } // namespace LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add an account")); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); request_ = NULL; account_info_req_ = NULL; mStatusText->setText(""); mLogo->setPixmap(QPixmap(":/images/seafile-32.png")); QString preconfigure_addr = seafApplet->readPreconfigureExpandedString(kPreconfigureServerAddr); if (seafApplet->readPreconfigureEntry(kPreconfigureServerAddrOnly).toBool() && !preconfigure_addr.isEmpty()) { mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, preconfigure_addr); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); } else { mServerAddr->addItems(getUsedServerAddresses()); mServerAddr->clearEditText(); } mServerAddr->setAutoCompletion(false); QString computerName = seafApplet->settingsManager()->getComputerName(); mComputerName->setText(computerName); connect(mSubmitBtn, SIGNAL(clicked()), this, SLOT(doLogin())); const QRect screen = QApplication::desktop()->screenGeometry(); move(screen.center() - this->rect().center()); #ifdef HAVE_SHIBBOLETH_SUPPORT setupShibLoginLink(); #else mShibLoginLink->hide(); #endif } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::setupShibLoginLink() { QString txt = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("Shibboleth Login")); mShibLoginLink->setText(txt); connect(mShibLoginLink, SIGNAL(linkActivated(const QString&)), this, SLOT(loginWithShib())); } #endif // HAVE_SHIBBOLETH_SUPPORT void LoginDialog::initFromAccount(const Account& account) { setWindowTitle(tr("Re-login")); mTitle->setText(tr("Re-login")); mServerAddr->setMaxCount(1); mServerAddr->insertItem(0, account.serverUrl.toString()); mServerAddr->setCurrentIndex(0); mServerAddr->setEditable(false); mUsername->setText(account.username); mPassword->setFocus(Qt::OtherFocusReason); } void LoginDialog::doLogin() { if (!validateInputs()) { return; } saveUsedServerAddresses(url_.toString()); mStatusText->setText(tr("Logging in...")); disableInputs(); if (request_) { request_->deleteLater(); } request_ = new LoginRequest(url_, username_, password_, computer_name_); if (!two_factor_auth_token_.isEmpty()) { request_->setHeader(kSeafileOTPHeader, two_factor_auth_token_); } connect(request_, SIGNAL(success(const QString&)), this, SLOT(loginSuccess(const QString&))); connect(request_, SIGNAL(failed(const ApiError&)), this, SLOT(loginFailed(const ApiError&))); request_->send(); } void LoginDialog::disableInputs() { mServerAddr->setEnabled(false); mUsername->setEnabled(false); mPassword->setEnabled(false); mSubmitBtn->setEnabled(false); mComputerName->setEnabled(false); } void LoginDialog::enableInputs() { mServerAddr->setEnabled(true); mUsername->setEnabled(true); mPassword->setEnabled(true); mSubmitBtn->setEnabled(true); mComputerName->setEnabled(true); } void LoginDialog::onNetworkError(const QNetworkReply::NetworkError& error, const QString& error_string) { showWarning(tr("Network Error:\n %1").arg(error_string)); enableInputs(); mStatusText->setText(""); } void LoginDialog::onSslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { const QSslCertificate &cert = reply->sslConfiguration().peerCertificate(); qDebug() << "\n= SslErrors =\n" << dumpSslErrors(errors); qDebug() << "\n= Certificate =\n" << dumpCertificate(cert); if (seafApplet->detailedYesOrNoBox(tr("<b>Warning:</b> The ssl certificate of this server is not trusted, proceed anyway?"), dumpSslErrors(errors) + dumpCertificate(cert), this, false)) reply->ignoreSslErrors(); } bool LoginDialog::validateInputs() { QString serverAddr = mServerAddr->currentText(); QString protocol; QUrl url; if (serverAddr.size() == 0) { showWarning(tr("Please enter the server address")); return false; } else { if (!serverAddr.startsWith("http://") && !serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); return false; } } QString email = mUsername->text(); if (email.size() == 0) { showWarning(tr("Please enter the username")); return false; } if (mPassword->text().size() == 0) { showWarning(tr("Please enter the password")); return false; } QString computer_name = mComputerName->text().trimmed(); if (computer_name.size() == 0) { showWarning(tr("Please enter the computer name")); return false; } url_ = url; username_ = mUsername->text(); password_ = mPassword->text(); computer_name_ = mComputerName->text(); seafApplet->settingsManager()->setComputerName(computer_name_); return true; } void LoginDialog::loginSuccess(const QString& token) { if (account_info_req_) { account_info_req_->deleteLater(); } account_info_req_ = new FetchAccountInfoRequest(Account(url_, username_, token)); connect(account_info_req_, SIGNAL(success(const AccountInfo&)), this, SLOT(onFetchAccountInfoSuccess(const AccountInfo&))); connect(account_info_req_, SIGNAL(failed(const ApiError&)), this, SLOT(onFetchAccountInfoFailed(const ApiError&))); account_info_req_->send(); } void LoginDialog::onFetchAccountInfoFailed(const ApiError& error) { loginFailed(error); } void LoginDialog::loginFailed(const ApiError& error) { switch (error.type()) { case ApiError::SSL_ERROR: onSslErrors(error.sslReply(), error.sslErrors()); break; case ApiError::NETWORK_ERROR: onNetworkError(error.networkError(), error.networkErrorString()); break; case ApiError::HTTP_ERROR: onHttpError(error.httpErrorCode()); default: // impossible break; } } void LoginDialog::onFetchAccountInfoSuccess(const AccountInfo& info) { Account account = account_info_req_->account(); // The user may use the username to login, but we need to store the email // to account database account.username = info.email; if (seafApplet->accountManager()->saveAccount(account) < 0) { showWarning(tr("Failed to save current account")); } else { seafApplet->accountManager()->updateAccountInfo(account, info); done(QDialog::Accepted); } } void LoginDialog::onHttpError(int code) { const QNetworkReply* reply = request_->reply(); if (reply->hasRawHeader(kSeafileOTPHeader) && QString(reply->rawHeader(kSeafileOTPHeader)) == "required") { two_factor_auth_token_ = seafApplet->getText( this, tr("Two Factor Authentication"), tr("Enter the two factor authentication token"), QLineEdit::Normal, ""); if (!two_factor_auth_token_.isEmpty()) { doLogin(); return; } } else { QString err_msg, reason; if (code == 400) { reason = tr("Incorrect email or password"); } else if (code == 429) { reason = tr("Logging in too frequently, please wait a minute"); } else if (code == 500) { reason = tr("Internal Server Error"); } if (reason.length() > 0) { err_msg = tr("Failed to login: %1").arg(reason); } else { err_msg = tr("Failed to login"); } showWarning(err_msg); } enableInputs(); mStatusText->setText(""); } void LoginDialog::showWarning(const QString& msg) { seafApplet->warningBox(msg, this); } #ifdef HAVE_SHIBBOLETH_SUPPORT void LoginDialog::loginWithShib() { bool ok = true; QUrl url; QString serverAddr = seafApplet->readPreconfigureEntry(kPreconfigureShibbolethLoginUrl) .toString() .trimmed(); if (!serverAddr.isEmpty()) { if (QUrl(serverAddr).isValid()) { qWarning("Using preconfigured shibboleth login url: %s\n", toCStr(serverAddr)); } else { qWarning("Invalid preconfigured shibboleth login url: %s\n", toCStr(serverAddr)); serverAddr = ""; } } if (serverAddr.isEmpty()) { // When we reach here, there is no preconfigured shibboleth login url, // or the preconfigured url is invalid. So we ask the user for the url. serverAddr = seafApplet->settingsManager()->getLastShibUrl(); while (ok) { serverAddr = seafApplet->getText(this, tr("Shibboleth Login"), tr("%1 Server Address").arg(getBrand()), QLineEdit::Normal, serverAddr, &ok); serverAddr = serverAddr.trimmed(); // exit when user hits cancel button if (!ok) { return; } if (serverAddr.isEmpty()) { showWarning(tr("Server address must not be empty").arg(serverAddr)); continue; } if (!serverAddr.startsWith("https://")) { showWarning(tr("%1 is not a valid server address. It has to start with 'https://'").arg(serverAddr)); continue; } url = QUrl(serverAddr, QUrl::StrictMode); if (!url.isValid()) { showWarning(tr("%1 is not a valid server address").arg(serverAddr)); continue; } // exit loop, if everything is okay break; } } seafApplet->settingsManager()->setLastShibUrl(serverAddr); ShibLoginDialog shib_dialog(url, mComputerName->text(), this); if (shib_dialog.exec() == QDialog::Accepted) { accept(); } } #endif // HAVE_SHIBBOLETH_SUPPORT <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Syscoin Signed Message:\n"; <commit_msg>back to btc signed message prefix for compatibility<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n"; <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * 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 HOLDER 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. * * \file test_main.hxx * * Include this file into your unittest to define the necessary symbols and * main function. * * @author Balazs Racz * @date 3 Nov 2013 */ #ifdef _UTILS_TEST_MAIN_HXX_ #error Only ever include test_main into the main unittest file. #else #define _UTILS_TEST_MAIN_HXX_ #include "nmranet_config.h" #include <stdio.h> #include <stdarg.h> #include <memory> #include <string> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "os/os.h" //#include "utils/pipe.hxx" #include "nmranet_can.h" #include "executor/Executor.hxx" #include "executor/Service.hxx" namespace testing { /** Conveninence utility to do a printf directly into a C++ string. */ string StringPrintf(const char* format, ...) { static const int kBufSize = 1000; char buffer[kBufSize]; va_list ap; va_start(ap, format); int n = vsnprintf(buffer, kBufSize, format, ap); va_end(ap); HASSERT(n >= 0); if (n < kBufSize) { return string(buffer, n); } string ret(n + 1, 0); va_start(ap, format); n = vsnprintf(&ret[0], ret.size(), format, ap); va_end(ap); HASSERT(n >= 0); ret.resize(n); return ret; } } using testing::StringPrintf; int appl_main(int argc, char* argv[]) { testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } static Executor<1> g_executor("ex_thread", 0, 1024); static Service g_service(&g_executor); /** Blocks the current thread until the main executor has run out of work. * * Use this function in unittest functions to wait for any asynchronous work * you may have scheduled on the main executor. This typically happens before * expectations. Also if you have stack-allocated objects that will schedule * themselves on the main executor, then you must call this function before * ending the scope that will deallocate them -- it is typical to have this as * the last command in a TEST_F. */ void wait_for_main_executor() { ExecutorGuard<decltype(g_executor)> guard(&g_executor); guard.wait_for_notification(); } /* Utility class to block an executor for a while. * * Usage: add an instance of BlockExecutor to the executor you want to block, * then call wait_for_blocked() and later release_block(). */ class BlockExecutor : public Executable { public: virtual void run() { n_.notify(); m_.wait_for_notification(); } /** Blocks the current thread until the BlockExecutor manages to block the executor it was scheduled on. */ void wait_for_blocked() { n_.wait_for_notification(); } /** Releases the executor that was blocked. */ void release_block() { m_.notify(); } private: SyncNotifiable n_; SyncNotifiable m_; }; /** Overrides the value of a variable and restores it to the original value * when destructed. Useful for changing flags for a single test only. * * Usage: * { * ScopedOverride ov(&DATAGRAM_RESPONSE_TIMEOUT_NSEC, 100000); * ... test code assuming new value ... * } * ... now the original value is restored. */ class ScopedOverride { public: template <class T> ScopedOverride(T* variable, T new_value) : holder_(new Holder<T>(variable, new_value)) {} private: class HolderBase { public: virtual ~HolderBase() {} }; template<class T> class Holder : public HolderBase { public: Holder(T* variable, T new_value) : variable_(variable), oldValue_(*variable) { *variable = new_value; } ~Holder() { *variable_ = oldValue_; } private: T* variable_; T oldValue_; }; std::unique_ptr<HolderBase> holder_; }; extern "C" { const char *nmranet_manufacturer = "Stuart W. Baker"; const char *nmranet_hardware_rev = "N/A"; const char *nmranet_software_rev = "0.1"; const size_t main_stack_size = 2560; const size_t ALIAS_POOL_SIZE = 2; const size_t DOWNSTREAM_ALIAS_CACHE_SIZE = 2; const size_t UPSTREAM_ALIAS_CACHE_SIZE = 2; const size_t DATAGRAM_POOL_SIZE = 10; const size_t CAN_RX_BUFFER_SIZE = 1; const size_t CAN_TX_BUFFER_SIZE = 32; const size_t SERIAL_RX_BUFFER_SIZE = 16; const size_t SERIAL_TX_BUFFER_SIZE = 16; const size_t DATAGRAM_THREAD_STACK_SIZE = 512; const size_t CAN_IF_READ_THREAD_STACK_SIZE = 1024; const size_t COMPAT_EVENT_THREAD_STACK_SIZE = 1024; const size_t WRITE_FLOW_THREAD_STACK_SIZE = 1024; } #endif // _UTILS_TEST_MAIN_HXX_ <commit_msg>clag-fpormat test_main. Adds a feature to BlockExecutor that allows easier blocking of the global executor.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * 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. * * 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 HOLDER 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. * * \file test_main.hxx * * Include this file into your unittest to define the necessary symbols and * main function. * * @author Balazs Racz * @date 3 Nov 2013 */ #ifdef _UTILS_TEST_MAIN_HXX_ #error Only ever include test_main into the main unittest file. #else #define _UTILS_TEST_MAIN_HXX_ #include "nmranet_config.h" #include <stdio.h> #include <stdarg.h> #include <memory> #include <string> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "os/os.h" //#include "utils/pipe.hxx" #include "nmranet_can.h" #include "executor/Executor.hxx" #include "executor/Service.hxx" namespace testing { /** Conveninence utility to do a printf directly into a C++ string. */ string StringPrintf(const char *format, ...) { static const int kBufSize = 1000; char buffer[kBufSize]; va_list ap; va_start(ap, format); int n = vsnprintf(buffer, kBufSize, format, ap); va_end(ap); HASSERT(n >= 0); if (n < kBufSize) { return string(buffer, n); } string ret(n + 1, 0); va_start(ap, format); n = vsnprintf(&ret[0], ret.size(), format, ap); va_end(ap); HASSERT(n >= 0); ret.resize(n); return ret; } } using testing::StringPrintf; int appl_main(int argc, char *argv[]) { testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } static Executor<1> g_executor("ex_thread", 0, 1024); static Service g_service(&g_executor); /** Blocks the current thread until the main executor has run out of work. * * Use this function in unittest functions to wait for any asynchronous work * you may have scheduled on the main executor. This typically happens before * expectations. Also if you have stack-allocated objects that will schedule * themselves on the main executor, then you must call this function before * ending the scope that will deallocate them -- it is typical to have this as * the last command in a TEST_F. */ void wait_for_main_executor() { ExecutorGuard<decltype(g_executor)> guard(&g_executor); guard.wait_for_notification(); } /* Utility class to block an executor for a while. * * Usage: add an instance of BlockExecutor to the executor you want to block, * then call wait_for_blocked() and later release_block(). */ class BlockExecutor : public Executable { public: BlockExecutor() { } /** Creates a block against executor e and waits until the block * suceeds. If e==null, then blocks g_executor. */ BlockExecutor(ExecutorBase *e) { if (e) { e->add(this); } else { g_executor.add(this); } wait_for_blocked(); } virtual void run() { n_.notify(); m_.wait_for_notification(); } /** Blocks the current thread until the BlockExecutor manages to block the executor it was scheduled on. */ void wait_for_blocked() { n_.wait_for_notification(); } /** Releases the executor that was blocked. */ void release_block() { m_.notify(); } private: SyncNotifiable n_; SyncNotifiable m_; }; /** Overrides the value of a variable and restores it to the original value * when destructed. Useful for changing flags for a single test only. * * Usage: * { * ScopedOverride ov(&DATAGRAM_RESPONSE_TIMEOUT_NSEC, 100000); * ... test code assuming new value ... * } * ... now the original value is restored. */ class ScopedOverride { public: template <class T> ScopedOverride(T *variable, T new_value) : holder_(new Holder<T>(variable, new_value)) { } private: class HolderBase { public: virtual ~HolderBase() { } }; template <class T> class Holder : public HolderBase { public: Holder(T *variable, T new_value) : variable_(variable) , oldValue_(*variable) { *variable = new_value; } ~Holder() { *variable_ = oldValue_; } private: T *variable_; T oldValue_; }; std::unique_ptr<HolderBase> holder_; }; extern "C" { const char *nmranet_manufacturer = "Stuart W. Baker"; const char *nmranet_hardware_rev = "N/A"; const char *nmranet_software_rev = "0.1"; const size_t main_stack_size = 2560; const size_t ALIAS_POOL_SIZE = 2; const size_t DOWNSTREAM_ALIAS_CACHE_SIZE = 2; const size_t UPSTREAM_ALIAS_CACHE_SIZE = 2; const size_t DATAGRAM_POOL_SIZE = 10; const size_t CAN_RX_BUFFER_SIZE = 1; const size_t CAN_TX_BUFFER_SIZE = 32; const size_t SERIAL_RX_BUFFER_SIZE = 16; const size_t SERIAL_TX_BUFFER_SIZE = 16; const size_t DATAGRAM_THREAD_STACK_SIZE = 512; const size_t CAN_IF_READ_THREAD_STACK_SIZE = 1024; const size_t COMPAT_EVENT_THREAD_STACK_SIZE = 1024; const size_t WRITE_FLOW_THREAD_STACK_SIZE = 1024; } #endif // _UTILS_TEST_MAIN_HXX_ <|endoftext|>
<commit_before>/* * This material contains unpublished, proprietary software of * Entropic Research Laboratory, Inc. Any reproduction, distribution, * or publication of this work must be authorized in writing by Entropic * Research Laboratory, Inc., and must bear the notice: * * "Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. * All rights reserved" * * The copyright notice above does not evidence any actual or intended * publication of this source code. * * Written by: Derek Lin * Checked by: * Revised by: David Talkin * * Brief description: Estimates F0 using normalized cross correlation and * dynamic programming. * */ #include <math.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <limits.h> #include <stdexcept> #include <sstream> #include <vector> #include "f0.h" int debug_level = 0; // ---------------------------------------- // Externs extern "C" { int init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep); int dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par, float **f0p_pt, float **vuvp_pt, float **rms_speech_pt, float **acpkp_pt, int *vecsize, int last_time); } struct f0_params; namespace GetF0 { // EXCEPTIONS #define CREATE_ERROR(_Name, _Base) \ class _Name : public _Base { \ public: \ explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \ }; CREATE_ERROR(RuntimeError, std::runtime_error); CREATE_ERROR(LogicError, std::logic_error); CREATE_ERROR(ParameterError, RuntimeError); CREATE_ERROR(ProcessingError, RuntimeError); CREATE_ERROR(AssertionError, LogicError); #undef CREATE_ERROR #define THROW_ERROR(condition, exception, s) \ do { \ if (condition) { \ std::stringstream ss; \ ss << s; \ throw exception(ss.str()); \ } \ } while (0); class GetF0 { public: typedef double SampleFrequency; typedef int DebugLevel; GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel = 0); void resetParameters(); /// @brief Some consistency checks on parameter values. Throws /// ParameterError if there's something wrong. void checkParameters(); void run(); // ---------------------------------------- // Getters/setters float& paramCandThresh() { return m_par.cand_thresh; } // only correlation peaks above this are considered float& paramLagWeight() { return m_par.lag_weight; } // degree to which shorter lags are weighted float& paramFreqWeight() { return m_par.freq_weight; } // weighting given to F0 trajectory smoothness float& paramTransCost() { return m_par.trans_cost; } // fixed cost for a voicing-state transition float& paramTransAmp() { return m_par.trans_amp; } // amplitude-change-modulated VUV trans. cost float& paramTransSpec() { return m_par.trans_spec; } // spectral-change-modulated VUV trans. cost float& paramVoiceBias() { return m_par.voice_bias; } // fixed bias towards the voiced hypothesis float& paramDoubleCost() { return m_par.double_cost; } // cost for octave F0 jumps float& paramMeanF0() { return m_par.mean_f0; } // talker-specific mean F0 (Hz) float& paramMeanF0Weight() { return m_par.mean_f0_weight; } // weight to be given to deviations from mean F0 float& paramMinF0() { return m_par.min_f0; } // min. F0 to search for (Hz) float& paramMaxF0() { return m_par.max_f0; } // max. F0 to search for (Hz) float& paramFrameStep() { return m_par.frame_step; } // inter-frame-interval (sec) float& paramWindDur() { return m_par.wind_dur; } // duration of correlation window (sec) int & paramNCands() { return m_par.n_cands; } // max. # of F0 cands. to consider at each frame int & paramConditioning() { return m_par.conditioning; } // Specify optional signal pre-conditioning. SampleFrequency &sampleFrequency() { return m_sampleFrequency; }; DebugLevel &debugLevel() { return m_debugLevel; }; protected: /// @brief Provide a `buffer` we can read `num_records` samples /// from, returning how many samples we can read. Returning less /// than requested samples is a termination condition. /// /// `buffer` is not guaranteed to not be written to. (TODO: check to /// see if buffer can be written to.) virtual long read_samples(float **buffer, long num_records) { return 0; } /// @brief Like `read_samples`, but read `step` samples from /// previous buffer. virtual long read_samples_overlap(float **buffer, long num_records, long step) { return 0; } virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech, float *acpkp, int vecsize) { } private: f0_params m_par; SampleFrequency m_sampleFrequency; DebugLevel m_debugLevel; }; GetF0::GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel) : m_sampleFrequency(sampleFrequency), m_debugLevel(debugLevel) { resetParameters(); } void GetF0::resetParameters() { m_par.cand_thresh = 0.3; m_par.lag_weight = 0.3; m_par.freq_weight = 0.02; m_par.trans_cost = 0.005; m_par.trans_amp = 0.5; m_par.trans_spec = 0.5; m_par.voice_bias = 0.0; m_par.double_cost = 0.35; m_par.min_f0 = 50; m_par.max_f0 = 550; m_par.frame_step = 0.01; m_par.wind_dur = 0.0075; m_par.n_cands = 20; m_par.mean_f0 = 200; /* unused */ m_par.mean_f0_weight = 0.0; /* unused */ m_par.conditioning = 0; /*unused */ } void GetF0::run() { int done; long buff_size, actsize; double output_starts, frame_rate; float *f0p, *vuvp, *rms_speech, *acpkp; int i, vecsize; long sdstep = 0; checkParameters(); /*SW: Removed range restricter, but this may be interesting: if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then input range too small*/ output_starts = m_par.wind_dur/2.0; /* Average delay due to loc. of ref. window center. */ frame_rate = 1.0 / m_par.frame_step; /* Initialize variables in get_f0.c; allocate data structures; * determine length and overlap of input frames to read. * * sw: Looks like init_dp_f0 never returns errors via rcode, but put * under assertion. */ THROW_ERROR(init_dp_f0(m_sampleFrequency, &m_par, &buff_size, &sdstep) || buff_size > INT_MAX || sdstep > INT_MAX, AssertionError, "problem in init_dp_f0()."); /*SW: pass sdstep to caller so it knows how much we have to buffer. */ if (debug_level) Fprintf(stderr, "init_dp_f0 returned buff_size %ld, sdstep %ld.\n", buff_size, sdstep); float* fdata = nullptr; actsize = read_samples(&fdata, buff_size); while (true) { done = (actsize < buff_size); THROW_ERROR(dp_f0(fdata, (int)actsize, (int)sdstep, m_sampleFrequency, &m_par, &f0p, &vuvp, &rms_speech, &acpkp, &vecsize, done), ProcessingError, "problem in dp_f0()."); writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize); if (done) break; actsize = read_samples_overlap(&fdata, buff_size, sdstep); } } void GetF0::checkParameters() { std::vector<std::string> errors; if ((m_par.cand_thresh < 0.01) || (m_par.cand_thresh > 0.99)) { errors.push_back("cand_thresh parameter must be between [0.01, 0.99]."); } if ((m_par.wind_dur > .1) || (m_par.wind_dur < .0001)) { errors.push_back("wind_dur parameter must be between [0.0001, 0.1]."); } if ((m_par.n_cands > 100) || (m_par.n_cands < 3)) { errors.push_back("n_cands parameter must be between [3,100]."); } if ((m_par.max_f0 <= m_par.min_f0) || (m_par.max_f0 >= (m_sampleFrequency / 2.0)) || (m_par.min_f0 < (m_sampleFrequency / 10000.0))) { errors.push_back( "min(max)_f0 parameter inconsistent with sampling frequency."); } double dstep = ((double)((int)(0.5 + (m_sampleFrequency * m_par.frame_step)))) / m_sampleFrequency; if (dstep != m_par.frame_step) { if (debug_level) Fprintf(stderr, "Frame step set to %f to exactly match signal sample rate.\n", dstep); m_par.frame_step = dstep; } if ((m_par.frame_step > 0.1) || (m_par.frame_step < (1.0 / m_sampleFrequency))) { errors.push_back( "frame_step parameter must be between [1/sampling rate, " "0.1]."); } if (!errors.empty()) { std::stringstream ss; bool first = true; for (auto &error : errors) { if (!first) ss << " "; ss << error; } THROW_ERROR(true, ParameterError, ss.str()); } } } // namespace GetF0 <commit_msg>Split init and run<commit_after>/* * This material contains unpublished, proprietary software of * Entropic Research Laboratory, Inc. Any reproduction, distribution, * or publication of this work must be authorized in writing by Entropic * Research Laboratory, Inc., and must bear the notice: * * "Copyright (c) 1990-1996 Entropic Research Laboratory, Inc. * All rights reserved" * * The copyright notice above does not evidence any actual or intended * publication of this source code. * * Written by: Derek Lin * Checked by: * Revised by: David Talkin * * Brief description: Estimates F0 using normalized cross correlation and * dynamic programming. * */ #include <math.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #include <limits.h> #include <stdexcept> #include <sstream> #include <vector> #include "f0.h" int debug_level = 0; // ---------------------------------------- // Externs extern "C" { int init_dp_f0(double freq, F0_params *par, long *buffsize, long *sdstep); int dp_f0(float *fdata, int buff_size, int sdstep, double freq, F0_params *par, float **f0p_pt, float **vuvp_pt, float **rms_speech_pt, float **acpkp_pt, int *vecsize, int last_time); } struct f0_params; namespace GetF0 { // EXCEPTIONS #define CREATE_ERROR(_Name, _Base) \ class _Name : public _Base { \ public: \ explicit _Name(const std::string &what_arg) : _Base(what_arg) {} \ }; CREATE_ERROR(RuntimeError, std::runtime_error); CREATE_ERROR(LogicError, std::logic_error); CREATE_ERROR(ParameterError, RuntimeError); CREATE_ERROR(ProcessingError, RuntimeError); #undef CREATE_ERROR #define THROW_ERROR(condition, exception, s) \ do { \ if (condition) { \ std::stringstream ss; \ ss << s; \ throw exception(ss.str()); \ } \ } while (0); class GetF0 { public: typedef double SampleFrequency; typedef int DebugLevel; GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel = 0); void resetParameters(); /// @brief Some consistency checks on parameter values. Throws /// ParameterError if there's something wrong. void checkParameters(); void init(); void run(); // ---------------------------------------- // Getters/setters float& paramCandThresh() { return m_par.cand_thresh; } // only correlation peaks above this are considered float& paramLagWeight() { return m_par.lag_weight; } // degree to which shorter lags are weighted float& paramFreqWeight() { return m_par.freq_weight; } // weighting given to F0 trajectory smoothness float& paramTransCost() { return m_par.trans_cost; } // fixed cost for a voicing-state transition float& paramTransAmp() { return m_par.trans_amp; } // amplitude-change-modulated VUV trans. cost float& paramTransSpec() { return m_par.trans_spec; } // spectral-change-modulated VUV trans. cost float& paramVoiceBias() { return m_par.voice_bias; } // fixed bias towards the voiced hypothesis float& paramDoubleCost() { return m_par.double_cost; } // cost for octave F0 jumps float& paramMeanF0() { return m_par.mean_f0; } // talker-specific mean F0 (Hz) float& paramMeanF0Weight() { return m_par.mean_f0_weight; } // weight to be given to deviations from mean F0 float& paramMinF0() { return m_par.min_f0; } // min. F0 to search for (Hz) float& paramMaxF0() { return m_par.max_f0; } // max. F0 to search for (Hz) float& paramFrameStep() { return m_par.frame_step; } // inter-frame-interval (sec) float& paramWindDur() { return m_par.wind_dur; } // duration of correlation window (sec) int & paramNCands() { return m_par.n_cands; } // max. # of F0 cands. to consider at each frame int & paramConditioning() { return m_par.conditioning; } // Specify optional signal pre-conditioning. SampleFrequency &sampleFrequency() { return m_sampleFrequency; }; DebugLevel &debugLevel() { return m_debugLevel; }; protected: /// @brief Provide a `buffer` we can read `num_records` samples /// from, returning how many samples we can read. Returning less /// than requested samples is a termination condition. /// /// `buffer` is not guaranteed to not be written to. (TODO: check to /// see if buffer can be written to.) virtual long read_samples(float **buffer, long num_records) { return 0; } /// @brief Like `read_samples`, but read `step` samples from /// previous buffer. virtual long read_samples_overlap(float **buffer, long num_records, long step) { return 0; } virtual void writeOutput(float *f0p, float *vuvp, float *rms_speech, float *acpkp, int vecsize) { } private: f0_params m_par; SampleFrequency m_sampleFrequency; DebugLevel m_debugLevel; bool m_initialized; long m_buffSize; long m_sdstep; }; GetF0::GetF0(SampleFrequency sampleFrequency, DebugLevel debugLevel) : m_sampleFrequency(sampleFrequency), m_debugLevel(debugLevel), m_initialized(false), m_buffSize(0), m_sdstep(0) { resetParameters(); } void GetF0::resetParameters() { m_par.cand_thresh = 0.3; m_par.lag_weight = 0.3; m_par.freq_weight = 0.02; m_par.trans_cost = 0.005; m_par.trans_amp = 0.5; m_par.trans_spec = 0.5; m_par.voice_bias = 0.0; m_par.double_cost = 0.35; m_par.min_f0 = 50; m_par.max_f0 = 550; m_par.frame_step = 0.01; m_par.wind_dur = 0.0075; m_par.n_cands = 20; m_par.mean_f0 = 200; /* unused */ m_par.mean_f0_weight = 0.0; /* unused */ m_par.conditioning = 0; /*unused */ } void GetF0::init() { checkParameters(); /*SW: Removed range restricter, but this may be interesting: if (total_samps < ((par->frame_step * 2.0) + par->wind_dur) * sf), then input range too small*/ // double output_starts = m_par.wind_dur/2.0; /* Average delay due to loc. of ref. window center. */ // SW: I think this is the time delay until output actually // starts. In other words, we'll have some dropped frames. // double frame_rate = 1.0 / m_par.frame_step; /* Initialize variables in get_f0.c; allocate data structures; * determine length and overlap of input frames to read. * * sw: Looks like init_dp_f0 never returns errors via rcode, but put * under assertion. */ THROW_ERROR(init_dp_f0(m_sampleFrequency, &m_par, &m_buffSize, &m_sdstep) || m_buffSize > INT_MAX || m_sdstep > INT_MAX, LogicError, "problem in init_dp_f0()."); m_initialized = true; } void GetF0::run() { THROW_ERROR(!m_initialized, LogicError, "Not initialized"); float* fdata = nullptr; float *f0p, *vuvp, *rms_speech, *acpkp; int done; int i, vecsize; long actsize = read_samples(&fdata, m_buffSize); while (true) { done = (actsize < m_buffSize); THROW_ERROR(dp_f0(fdata, (int)actsize, (int)m_sdstep, m_sampleFrequency, &m_par, &f0p, &vuvp, &rms_speech, &acpkp, &vecsize, done), ProcessingError, "problem in dp_f0()."); writeOutput(f0p, vuvp, rms_speech, acpkp, vecsize); if (done) break; actsize = read_samples_overlap(&fdata, m_buffSize, m_sdstep); } } void GetF0::checkParameters() { std::vector<std::string> errors; if ((m_par.cand_thresh < 0.01) || (m_par.cand_thresh > 0.99)) { errors.push_back("cand_thresh parameter must be between [0.01, 0.99]."); } if ((m_par.wind_dur > .1) || (m_par.wind_dur < .0001)) { errors.push_back("wind_dur parameter must be between [0.0001, 0.1]."); } if ((m_par.n_cands > 100) || (m_par.n_cands < 3)) { errors.push_back("n_cands parameter must be between [3,100]."); } if ((m_par.max_f0 <= m_par.min_f0) || (m_par.max_f0 >= (m_sampleFrequency / 2.0)) || (m_par.min_f0 < (m_sampleFrequency / 10000.0))) { errors.push_back( "min(max)_f0 parameter inconsistent with sampling frequency."); } double dstep = ((double)((int)(0.5 + (m_sampleFrequency * m_par.frame_step)))) / m_sampleFrequency; if (dstep != m_par.frame_step) { if (debug_level) Fprintf(stderr, "Frame step set to %f to exactly match signal sample rate.\n", dstep); m_par.frame_step = dstep; } if ((m_par.frame_step > 0.1) || (m_par.frame_step < (1.0 / m_sampleFrequency))) { errors.push_back( "frame_step parameter must be between [1/sampling rate, " "0.1]."); } if (!errors.empty()) { std::stringstream ss; bool first = true; for (auto &error : errors) { if (!first) ss << " "; ss << error; } THROW_ERROR(true, ParameterError, ss.str()); } } } // namespace GetF0 <|endoftext|>
<commit_before>// Copyright 2013 Tanel Lebedev #include "./websocket_client.h" #include <string> #include <sstream> #include "Poco/Exception.h" #include "Poco/InflatingStream.h" #include "Poco/DeflatingStream.h" #include "Poco/Logger.h" #include "Poco/URI.h" #include "Poco/NumberParser.h" #include "Poco/Net/Context.h" #include "Poco/Net/NameValueCollection.h" #include "Poco/Net/HTTPMessage.h" #include "Poco/Net/HTTPBasicCredentials.h" #include "Poco/ScopedLock.h" #include "Poco/Mutex.h" #include "./libjson.h" #include "./version.h" namespace kopsik { const int kWebsocketBufSize = 1024 * 10; const std::string kPong("{\"type\": \"pong\"}"); error WebSocketClient::Start(void *ctx, std::string api_token, WebSocketMessageCallback on_websocket_message) { poco_assert(ctx); poco_assert(!api_token.empty()); poco_assert(on_websocket_message); Poco::Mutex mutex; Poco::Mutex::ScopedLock lock(mutex); ctx_ = ctx; on_websocket_message_ = on_websocket_message; Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("WebSocketClient::Start"); try { const Poco::URI uri(websocket_url_); // FIXME: check certification const Poco::Net::Context::Ptr context(new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH")); if (session_) { delete session_; } session_ = new Poco::Net::HTTPSClientSession(uri.getHost(), uri.getPort(), context); if (req_) { delete req_; } req_ = new Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_GET, "/ws", Poco::Net::HTTPMessage::HTTP_1_1); req_->set("Origin", "https://localhost"); req_->set("User-Agent", kopsik::UserAgent(app_name_, app_version_)); if (res_) { delete res_; } res_ = new Poco::Net::HTTPResponse(); if (ws_) { delete ws_; } ws_ = new Poco::Net::WebSocket(*session_, *req_, *res_); ws_->setBlocking(false); Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("WebSocket connection established."); // Authenticate JSONNODE *c = json_new(JSON_NODE); json_push_back(c, json_new_a("type", "authenticate")); json_push_back(c, json_new_a("api_token", api_token.c_str())); json_char *jc = json_write_formatted(c); std::string payload(jc); json_free(jc); json_delete(c); ws_->sendFrame(payload.data(), static_cast<int>(payload.size()), Poco::Net::WebSocket::FRAME_BINARY); activity_.start(); } catch(const Poco::Exception& exc) { return exc.displayText(); } catch(const std::exception& ex) { return ex.what(); } catch(const std::string& ex) { return ex; } return noError; } std::string WebSocketClient::parseWebSocketMessageType(std::string json) { poco_assert(!json.empty()); std::string type("data"); const char *str = json.c_str(); if (!json_is_valid(str)) { return ""; } JSONNODE *root = json_parse(str); JSONNODE_ITERATOR i = json_begin(root); JSONNODE_ITERATOR e = json_end(root); while (i != e) { json_char *node_name = json_name(*i); if (strcmp(node_name, "type") == 0) { type = std::string(json_as_string(*i)); break; } ++i; } json_delete(root); return type; } std::string WebSocketClient::receiveWebSocketMessage() { char buf[kWebsocketBufSize]; int flags = Poco::Net::WebSocket::FRAME_BINARY; int n = ws_->receiveFrame(buf, kWebsocketBufSize, flags); std::string json; if (n > 0) { json.append(buf, n); } return json; } void WebSocketClient::runActivity() { Poco::Logger &logger = Poco::Logger::get("websocket_client"); Poco::Timespan span(250 * 1000); while (!activity_.isStopped()) { if (!ws_->poll(span, Poco::Net::Socket::SELECT_READ)) { continue; } std::string json = receiveWebSocketMessage(); if (json.empty()) { logger.error("WebSocket peer has shut down or closed the connection"); break; } std::stringstream ss; ss << "WebSocket message: " << json; logger.debug(ss.str()); std::string type = parseWebSocketMessageType(json); if (activity_.isStopped()) { break; } if ("ping" == type) { ws_->sendFrame(kPong.data(), static_cast<int>(kPong.size()), Poco::Net::WebSocket::FRAME_BINARY); continue; } if ("data" == type) { on_websocket_message_(ctx_, json); } } logger.debug("WebSocketClient::runActivity finished"); } void WebSocketClient::Stop() { Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("shutting down"); if (ws_) { ws_->shutdown(); } activity_.stop(); // request stop activity_.wait(); // wait until activity actually stops logger.debug("stopped"); } } // namespace kopsik <commit_msg>Set Websocket client timeouts to 5 seconds<commit_after>// Copyright 2013 Tanel Lebedev #include "./websocket_client.h" #include <string> #include <sstream> #include "Poco/Exception.h" #include "Poco/InflatingStream.h" #include "Poco/DeflatingStream.h" #include "Poco/Logger.h" #include "Poco/URI.h" #include "Poco/NumberParser.h" #include "Poco/Net/Context.h" #include "Poco/Net/NameValueCollection.h" #include "Poco/Net/HTTPMessage.h" #include "Poco/Net/HTTPBasicCredentials.h" #include "Poco/ScopedLock.h" #include "Poco/Mutex.h" #include "./libjson.h" #include "./version.h" namespace kopsik { const int kWebsocketBufSize = 1024 * 10; const std::string kPong("{\"type\": \"pong\"}"); error WebSocketClient::Start(void *ctx, std::string api_token, WebSocketMessageCallback on_websocket_message) { poco_assert(ctx); poco_assert(!api_token.empty()); poco_assert(on_websocket_message); Poco::Mutex mutex; Poco::Mutex::ScopedLock lock(mutex); ctx_ = ctx; on_websocket_message_ = on_websocket_message; Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("WebSocketClient::Start"); try { const Poco::URI uri(websocket_url_); // FIXME: check certification const Poco::Net::Context::Ptr context(new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH")); if (session_) { delete session_; } session_ = new Poco::Net::HTTPSClientSession(uri.getHost(), uri.getPort(), context); if (req_) { delete req_; } req_ = new Poco::Net::HTTPRequest(Poco::Net::HTTPRequest::HTTP_GET, "/ws", Poco::Net::HTTPMessage::HTTP_1_1); req_->set("Origin", "https://localhost"); req_->set("User-Agent", kopsik::UserAgent(app_name_, app_version_)); if (res_) { delete res_; } res_ = new Poco::Net::HTTPResponse(); if (ws_) { delete ws_; } ws_ = new Poco::Net::WebSocket(*session_, *req_, *res_); ws_->setBlocking(false); ws_->setReceiveTimeout(Poco::Timespan(5, 0)); ws_->setSendTimeout(Poco::Timespan(5, 0)); Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("WebSocket connection established."); // Authenticate JSONNODE *c = json_new(JSON_NODE); json_push_back(c, json_new_a("type", "authenticate")); json_push_back(c, json_new_a("api_token", api_token.c_str())); json_char *jc = json_write_formatted(c); std::string payload(jc); json_free(jc); json_delete(c); ws_->sendFrame(payload.data(), static_cast<int>(payload.size()), Poco::Net::WebSocket::FRAME_BINARY); activity_.start(); } catch(const Poco::Exception& exc) { return exc.displayText(); } catch(const std::exception& ex) { return ex.what(); } catch(const std::string& ex) { return ex; } return noError; } std::string WebSocketClient::parseWebSocketMessageType(std::string json) { poco_assert(!json.empty()); std::string type("data"); const char *str = json.c_str(); if (!json_is_valid(str)) { return ""; } JSONNODE *root = json_parse(str); JSONNODE_ITERATOR i = json_begin(root); JSONNODE_ITERATOR e = json_end(root); while (i != e) { json_char *node_name = json_name(*i); if (strcmp(node_name, "type") == 0) { type = std::string(json_as_string(*i)); break; } ++i; } json_delete(root); return type; } std::string WebSocketClient::receiveWebSocketMessage() { char buf[kWebsocketBufSize]; int flags = Poco::Net::WebSocket::FRAME_BINARY; int n = ws_->receiveFrame(buf, kWebsocketBufSize, flags); std::string json; if (n > 0) { json.append(buf, n); } return json; } void WebSocketClient::runActivity() { Poco::Logger &logger = Poco::Logger::get("websocket_client"); Poco::Timespan span(250 * 1000); while (!activity_.isStopped()) { if (!ws_->poll(span, Poco::Net::Socket::SELECT_READ)) { continue; } std::string json = receiveWebSocketMessage(); if (json.empty()) { logger.error("WebSocket peer has shut down or closed the connection"); break; } std::stringstream ss; ss << "WebSocket message: " << json; logger.debug(ss.str()); std::string type = parseWebSocketMessageType(json); if (activity_.isStopped()) { break; } if ("ping" == type) { ws_->sendFrame(kPong.data(), static_cast<int>(kPong.size()), Poco::Net::WebSocket::FRAME_BINARY); continue; } if ("data" == type) { on_websocket_message_(ctx_, json); } } logger.debug("WebSocketClient::runActivity finished"); } void WebSocketClient::Stop() { Poco::Logger &logger = Poco::Logger::get("websocket_client"); logger.debug("shutting down"); if (ws_) { ws_->shutdown(); } activity_.stop(); // request stop activity_.wait(); // wait until activity actually stops logger.debug("stopped"); } } // namespace kopsik <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessn a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/listbox.hpp" #include "guichan/basiccontainer.hpp" #include "guichan/font.hpp" #include "guichan/graphics.hpp" #include "guichan/key.hpp" #include "guichan/listmodel.hpp" #include "guichan/mouseinput.hpp" #include "guichan/selectionlistener.hpp" namespace gcn { ListBox::ListBox() : mSelected(-1), mListModel(NULL), mWrappingEnabled(false) { setWidth(100); setFocusable(true); addMouseListener(this); addKeyListener(this); } ListBox::ListBox(ListModel *listModel) : mSelected(-1), mWrappingEnabled(false) { setWidth(100); setListModel(listModel); setFocusable(true); addMouseListener(this); addKeyListener(this); } void ListBox::draw(Graphics* graphics) { graphics->setColor(getBackgroundColor()); graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight())); if (mListModel == NULL) { return; } graphics->setColor(getForegroundColor()); graphics->setFont(getFont()); // Check the current clip area so we don't draw unnecessary items // that are not visible. const ClipRectangle currentClipArea = graphics->getCurrentClipArea(); int rowHeight = getRowHeight(); // Calculate the number of rows to draw by checking the clip area. // The addition of two makes covers a partial visible row at the top // and a partial visible row at the bottom. int numberOfRows = currentClipArea.height / rowHeight + 2; if (numberOfRows > mListModel->getNumberOfElements()) { numberOfRows = mListModel->getNumberOfElements(); } // Calculate which row to start drawing. If the list box // has a negative y coordinate value we should check if // we should drop rows in the begining of the list as // they might not be visible. A negative y value is very // common if the list box for instance resides in a scroll // area and the user has scrolled the list box downwards. int startRow; if (getY() < 0) { startRow = -1 * (getY() / rowHeight); } else { startRow = 0; } int i; // The y coordinate where we start to draw the text is // simply the y coordinate multiplied with the font height. int y = rowHeight * startRow; for (i = startRow; i < startRow + numberOfRows; ++i) { if (i == mSelected) { graphics->setColor(getSelectionColor()); graphics->fillRectangle(Rectangle(0, y, getWidth(), rowHeight)); graphics->setColor(getForegroundColor()); } // If the row height is greater than the font height we // draw the text with a center vertical alignment. if (rowHeight > getFont()->getHeight()) { graphics->drawText(mListModel->getElementAt(i), 1, y + rowHeight / 2 - getFont()->getHeight() / 2); } else { graphics->drawText(mListModel->getElementAt(i), 1, y); } y += rowHeight; } } void ListBox::logic() { adjustSize(); Rectangle scroll; if (mSelected < 0) { scroll.y = 0; } else { scroll.y = getRowHeight() * mSelected; } scroll.height = getRowHeight(); showPart(scroll); } int ListBox::getSelected() const { return mSelected; } void ListBox::setSelected(int selected) { if (mListModel == NULL) { mSelected = -1; } else { if (selected < 0) { mSelected = -1; } else if (selected >= mListModel->getNumberOfElements()) { mSelected = mListModel->getNumberOfElements() - 1; } else { mSelected = selected; } } distributeValueChangedEvent(); } void ListBox::keyPressed(KeyEvent& keyEvent) { Key key = keyEvent.getKey(); if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) { distributeActionEvent(); keyEvent.consume(); } else if (key.getValue() == Key::UP) { setSelected(mSelected - 1); if (mSelected == -1) { if (mWrappingEnabled) { setSelected(getListModel()->getNumberOfElements() - 1); } else { setSelected(0); } } keyEvent.consume(); } else if (key.getValue() == Key::DOWN) { if (mWrappingEnabled && getSelected() == getListModel()->getNumberOfElements() - 1) { setSelected(0); } else { setSelected(getSelected() + 1); } keyEvent.consume(); } else if (key.getValue() == Key::HOME) { setSelected(0); keyEvent.consume(); } else if (key.getValue() == Key::END) { setSelected(getListModel()->getNumberOfElements() - 1); keyEvent.consume(); } } void ListBox::mousePressed(MouseEvent& mouseEvent) { if (mouseEvent.getButton() == MouseEvent::LEFT) { setSelected(mouseEvent.getY() / getRowHeight()); distributeActionEvent(); } } void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent) { if (isFocused()) { if (getSelected() > 0 ) { setSelected(getSelected() - 1); } mouseEvent.consume(); } } void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent) { if (isFocused()) { setSelected(getSelected() + 1); mouseEvent.consume(); } } void ListBox::mouseDragged(MouseEvent& mouseEvent) { mouseEvent.consume(); } void ListBox::setListModel(ListModel *listModel) { mSelected = -1; mListModel = listModel; adjustSize(); } ListModel* ListBox::getListModel() { return mListModel; } void ListBox::adjustSize() { if (mListModel != NULL) { setHeight(getRowHeight() * mListModel->getNumberOfElements()); } } bool ListBox::isWrappingEnabled() const { return mWrappingEnabled; } void ListBox::setWrappingEnabled(bool wrappingEnabled) { mWrappingEnabled = wrappingEnabled; } void ListBox::addSelectionListener(SelectionListener* selectionListener) { mSelectionListeners.push_back(selectionListener); } void ListBox::removeSelectionListener(SelectionListener* selectionListener) { mSelectionListeners.remove(selectionListener); } void ListBox::distributeValueChangedEvent() { SelectionListenerIterator iter; for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter) { SelectionEvent event(this); (*iter)->valueChanged(event); } } unsigned int ListBox::getRowHeight() const { return getFont()->getHeight(); } } <commit_msg>A bug prevented scroll area from scrolling a list box correctly. It was caused by the fact that list box called Widget::showPart on every logic call to fix it's scroll when a user goes up and down the list which caused the scroll areas scroll to be ignored. The problem has been fixed by only calling Widget::showPart when a new item in the list box has been selected.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessn a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/listbox.hpp" #include "guichan/basiccontainer.hpp" #include "guichan/font.hpp" #include "guichan/graphics.hpp" #include "guichan/key.hpp" #include "guichan/listmodel.hpp" #include "guichan/mouseinput.hpp" #include "guichan/selectionlistener.hpp" namespace gcn { ListBox::ListBox() : mSelected(-1), mListModel(NULL), mWrappingEnabled(false) { setWidth(100); setFocusable(true); addMouseListener(this); addKeyListener(this); } ListBox::ListBox(ListModel *listModel) : mSelected(-1), mWrappingEnabled(false) { setWidth(100); setListModel(listModel); setFocusable(true); addMouseListener(this); addKeyListener(this); } void ListBox::draw(Graphics* graphics) { graphics->setColor(getBackgroundColor()); graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight())); if (mListModel == NULL) { return; } graphics->setColor(getForegroundColor()); graphics->setFont(getFont()); // Check the current clip area so we don't draw unnecessary items // that are not visible. const ClipRectangle currentClipArea = graphics->getCurrentClipArea(); int rowHeight = getRowHeight(); // Calculate the number of rows to draw by checking the clip area. // The addition of two makes covers a partial visible row at the top // and a partial visible row at the bottom. int numberOfRows = currentClipArea.height / rowHeight + 2; if (numberOfRows > mListModel->getNumberOfElements()) { numberOfRows = mListModel->getNumberOfElements(); } // Calculate which row to start drawing. If the list box // has a negative y coordinate value we should check if // we should drop rows in the begining of the list as // they might not be visible. A negative y value is very // common if the list box for instance resides in a scroll // area and the user has scrolled the list box downwards. int startRow; if (getY() < 0) { startRow = -1 * (getY() / rowHeight); } else { startRow = 0; } int i; // The y coordinate where we start to draw the text is // simply the y coordinate multiplied with the font height. int y = rowHeight * startRow; for (i = startRow; i < startRow + numberOfRows; ++i) { if (i == mSelected) { graphics->setColor(getSelectionColor()); graphics->fillRectangle(Rectangle(0, y, getWidth(), rowHeight)); graphics->setColor(getForegroundColor()); } // If the row height is greater than the font height we // draw the text with a center vertical alignment. if (rowHeight > getFont()->getHeight()) { graphics->drawText(mListModel->getElementAt(i), 1, y + rowHeight / 2 - getFont()->getHeight() / 2); } else { graphics->drawText(mListModel->getElementAt(i), 1, y); } y += rowHeight; } } void ListBox::logic() { adjustSize(); } int ListBox::getSelected() const { return mSelected; } void ListBox::setSelected(int selected) { if (mListModel == NULL) { mSelected = -1; } else { if (selected < 0) { mSelected = -1; } else if (selected >= mListModel->getNumberOfElements()) { mSelected = mListModel->getNumberOfElements() - 1; } else { mSelected = selected; } } Rectangle scroll; if (mSelected < 0) { scroll.y = 0; } else { scroll.y = getRowHeight() * mSelected; } scroll.height = getRowHeight(); showPart(scroll); distributeValueChangedEvent(); } void ListBox::keyPressed(KeyEvent& keyEvent) { Key key = keyEvent.getKey(); if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) { distributeActionEvent(); keyEvent.consume(); } else if (key.getValue() == Key::UP) { setSelected(mSelected - 1); if (mSelected == -1) { if (mWrappingEnabled) { setSelected(getListModel()->getNumberOfElements() - 1); } else { setSelected(0); } } keyEvent.consume(); } else if (key.getValue() == Key::DOWN) { if (mWrappingEnabled && getSelected() == getListModel()->getNumberOfElements() - 1) { setSelected(0); } else { setSelected(getSelected() + 1); } keyEvent.consume(); } else if (key.getValue() == Key::HOME) { setSelected(0); keyEvent.consume(); } else if (key.getValue() == Key::END) { setSelected(getListModel()->getNumberOfElements() - 1); keyEvent.consume(); } } void ListBox::mousePressed(MouseEvent& mouseEvent) { if (mouseEvent.getButton() == MouseEvent::LEFT) { setSelected(mouseEvent.getY() / getRowHeight()); distributeActionEvent(); } } void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent) { if (isFocused()) { if (getSelected() > 0 ) { setSelected(getSelected() - 1); } mouseEvent.consume(); } } void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent) { if (isFocused()) { setSelected(getSelected() + 1); mouseEvent.consume(); } } void ListBox::mouseDragged(MouseEvent& mouseEvent) { mouseEvent.consume(); } void ListBox::setListModel(ListModel *listModel) { mSelected = -1; mListModel = listModel; adjustSize(); } ListModel* ListBox::getListModel() { return mListModel; } void ListBox::adjustSize() { if (mListModel != NULL) { setHeight(getRowHeight() * mListModel->getNumberOfElements()); } } bool ListBox::isWrappingEnabled() const { return mWrappingEnabled; } void ListBox::setWrappingEnabled(bool wrappingEnabled) { mWrappingEnabled = wrappingEnabled; } void ListBox::addSelectionListener(SelectionListener* selectionListener) { mSelectionListeners.push_back(selectionListener); } void ListBox::removeSelectionListener(SelectionListener* selectionListener) { mSelectionListeners.remove(selectionListener); } void ListBox::distributeValueChangedEvent() { SelectionListenerIterator iter; for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter) { SelectionEvent event(this); (*iter)->valueChanged(event); } } unsigned int ListBox::getRowHeight() const { return getFont()->getHeight(); } } <|endoftext|>
<commit_before>#include "../World.h" // TODO: not needed? #include "qtopenc2e.h" #include "../Engine.h" #ifdef _WIN32 #include "../SDLBackend.h" #include <windows.h> #endif #include <QApplication> #ifdef _WIN32 #include <windows.h> #endif int main(int argc, char *argv[]) { try { QApplication app(argc, argv); if (!engine.parseCommandLine(argc, argv)) return 1; QtOpenc2e myvat; myvat.show(); return app.exec(); } catch (std::exception &e) { #ifdef _WIN32 MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR); #else std::cerr << "Fatal exception encountered: " << e.what() << "\n"; #endif return 1; } } <commit_msg>Add openc2e version/copyright banner to qtgui main<commit_after>#include "../World.h" // TODO: not needed? #include "qtopenc2e.h" #include "../Engine.h" #ifdef _WIN32 #include "../SDLBackend.h" #include <windows.h> #endif #include <QApplication> #ifdef _WIN32 #include <windows.h> #endif int main(int argc, char *argv[]) { try { std::cout << "openc2e (development build), built " __DATE__ " " __TIME__ "\nCopyright (c) 2004-2008 Alyssa Milburn and others\n\n"; QApplication app(argc, argv); if (!engine.parseCommandLine(argc, argv)) return 1; QtOpenc2e myvat; myvat.show(); return app.exec(); } catch (std::exception &e) { #ifdef _WIN32 MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR); #else std::cerr << "Fatal exception encountered: " << e.what() << "\n"; #endif return 1; } } <|endoftext|>
<commit_before>/* * This file is part of Maliit framework * * * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * Copyright (C) 2012 One Laptop per Child Association * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "windowedsurface.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include "mimdummyinputcontext.h" #endif #include "mimapphostedserverlogic.h" #include <maliit/plugins/abstractwidgetssurface.h> #include <QApplication> #include <QDebug> #include <QDesktopWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsItem> #include <QWidget> #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QtGui/5.0.0/QtGui/qpa/qplatformnativeinterface.h> #include <QVariant> #include <QWindow> #endif #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif using Maliit::Plugins::AbstractSurface; namespace Maliit { namespace Server { class WindowedSurface : public virtual Maliit::Plugins::AbstractSurface { public: WindowedSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent, QWidget *toplevel) : AbstractSurface(), mFactory(factory), mOptions(options), mParent(parent), mToplevel(toplevel), mActive(false), mVisible(false), mRelativePosition() { QWidget *parentWidget = 0; if (parent) { parentWidget = parent->mToplevel.data(); } mToplevel->setParent(parentWidget, static_cast<Qt::WindowFlags>(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint)); mToplevel->setAttribute(Qt::WA_X11DoNotAcceptFocus); mToplevel->setAutoFillBackground(false); mToplevel->setBackgroundRole(QPalette::NoRole); mToplevel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); updateVisibility(); } ~WindowedSurface() { } void show() { mVisible = true; updateVisibility(); } void hide() { mVisible = false; updateVisibility(); } QSize size() const { return mToplevel->size(); } void setSize(const QSize &size) { const QSize& desktopSize = QApplication::desktop()->screenGeometry().size(); if (isWindow()) { // stand-alone Maliit server if (mOptions & PositionCenterBottom) { mToplevel->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size)); } else { mToplevel->resize(size); } } else { // application-hosted Maliit server mToplevel->resize(size); } mFactory->updateInputMethodArea(); } QPoint relativePosition() const { return mRelativePosition; } void setRelativePosition(const QPoint &position) { mRelativePosition = position; QPoint parentPosition(0, 0); if (mParent) { if (isWindow() && !mParent->isWindow()) { parentPosition = mParent->mapToGlobal(QPoint(0, 0)); } else if (!isWindow() && mParent->isWindow()) { // do nothing } else { parentPosition = mParent->mToplevel->pos(); } } mToplevel->move(parentPosition + mRelativePosition); mFactory->updateInputMethodArea(); } QSharedPointer<AbstractSurface> parent() const { return mParent; } QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const { if (!eventSurface) return eventPosition; QSharedPointer<WindowedSurface> windowedSurface = qSharedPointerDynamicCast<WindowedSurface>(eventSurface); if (!windowedSurface) return QPoint(); return -mToplevel->pos() + eventPosition + windowedSurface->mToplevel->pos(); } void setActive(bool active) { mActive = active; updateVisibility(); } void applicationFocusChanged(WId winId) { if (mParent) return; #ifdef Q_WS_X11 XSetTransientForHint(QX11Info::display(), mToplevel->window()->effectiveWinId(), winId); #else Q_UNUSED(winId); #endif } QRegion inputMethodArea() { if (!mToplevel->isVisible()) return QRegion(); return QRegion(mToplevel->geometry()); } private: void updateVisibility() { mToplevel->setVisible(mActive && mVisible); mFactory->updateInputMethodArea(); } protected: bool isWindow() const { return mToplevel->isWindow(); } QPoint mapToGlobal(const QPoint &pos) const { return mToplevel->mapToGlobal(pos); } WindowedSurfaceFactory *mFactory; Options mOptions; QSharedPointer<WindowedSurface> mParent; QScopedPointer<QWidget> mToplevel; bool mActive; bool mVisible; QPoint mRelativePosition; }; class GraphicsView : public QGraphicsView { public: GraphicsView() : QGraphicsView() { setWindowFlags(static_cast<Qt::WindowFlags>(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)); setAttribute(Qt::WA_X11DoNotAcceptFocus); setAutoFillBackground(false); setBackgroundRole(QPalette::NoRole); setBackgroundBrush(Qt::transparent); // This is a workaround for non-compositing window managers. Apparently // setting this attribute while using such WMs may cause garbled // painting of VKB. #ifndef DISABLE_TRANSLUCENT_BACKGROUND_HINT setAttribute(Qt::WA_TranslucentBackground); #endif viewport()->setAutoFillBackground(false); } }; class RootItem : public QGraphicsItem { private: QRectF m_rect; public: explicit RootItem(QGraphicsItem *parent = 0) : QGraphicsItem(parent) , m_rect() { setFlag(QGraphicsItem::ItemHasNoContents); } void setRect(const QRectF &rect) { m_rect = rect; } virtual QRectF boundingRect() const { return m_rect; } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class WindowedGraphicsViewSurface : public WindowedSurface, public Maliit::Plugins::AbstractGraphicsViewSurface { public: WindowedGraphicsViewSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new GraphicsView), AbstractGraphicsViewSurface(), mRoot(0) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) MIMDummyInputContext dummy; #endif QGraphicsView *view = static_cast<QGraphicsView*>(mToplevel.data()); view->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); view->setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); view->setFrameShape(QFrame::NoFrame); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // Calling QGraphicsView::setScene() indirectly calls QWidget::inputContext() on the view. If there isn't // an input context set on the widget, this calls QApplication::inputContext(), which leads to infinite // recursion if surface creation happens during input method creation and QT_IM_MODULE is set (for example // when embedding maliit-server in the application) view->setInputContext(&dummy); #endif QGraphicsScene *scene = new QGraphicsScene(view); view->setScene(scene); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) view->setInputContext(0); #endif } ~WindowedGraphicsViewSurface() {} QGraphicsScene *scene() const { return view()->scene(); } QGraphicsView *view() const { return static_cast<QGraphicsView*>(mToplevel.data()); } void show() { WindowedSurface::show(); const QRect rect(QPoint(), mToplevel->size()); if (not mRoot) { scene()->addItem(mRoot = new RootItem); mRoot->setRect(rect); mRoot->show(); } } void setSize(const QSize &size) { WindowedSurface::setSize(size); view()->setSceneRect(QRect(QPoint(), mToplevel->size())); if (mRoot) { mRoot->setRect(QRect(QPoint(), mToplevel->size())); } } void clear() { mRoot = 0; scene()->clear(); } QGraphicsItem *root() const { return mRoot; } private: RootItem *mRoot; }; class WindowedWidgetSurface : public WindowedSurface, public Maliit::Plugins::AbstractWidgetSurface { public: WindowedWidgetSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new QWidget), AbstractWidgetSurface() {} QWidget* widget() const { return mToplevel.data(); } }; WindowedSurfaceFactory::WindowedSurfaceFactory() : AbstractSurfaceFactory() , surfaces() , mActive(false) { connect(QApplication::desktop(), SIGNAL(resized(int)), this, SLOT(screenResized(int))); } WindowedSurfaceFactory::~WindowedSurfaceFactory() { } QSize WindowedSurfaceFactory::screenSize() const { return QApplication::desktop()->screenGeometry().size(); } bool WindowedSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const { return options & AbstractSurface::TypeGraphicsView; } QSharedPointer<AbstractSurface> WindowedSurfaceFactory::create(AbstractSurface::Options options, const QSharedPointer<AbstractSurface> &parent) { QSharedPointer<WindowedSurface> defaultSurfaceParent(qSharedPointerDynamicCast<WindowedSurface>(parent)); if (options & Maliit::Plugins::AbstractSurface::TypeGraphicsView) { QSharedPointer<WindowedGraphicsViewSurface> newSurface(new WindowedGraphicsViewSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->view(), options); return newSurface; } else if (options & Maliit::Plugins::AbstractSurface::TypeWidget) { QSharedPointer<WindowedWidgetSurface> newSurface(new WindowedWidgetSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->widget(), options); return newSurface; } return QSharedPointer<AbstractSurface>(); } void WindowedSurfaceFactory::activate() { mActive = true; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(true); } } void WindowedSurfaceFactory::deactivate() { mActive = false; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(false); } } void WindowedSurfaceFactory::applicationFocusChanged(WId winId) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->applicationFocusChanged(winId); } } } void WindowedSurfaceFactory::screenResized(int) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->setSize(surface->size()); if (surface->parent()) { surface->setRelativePosition(surface->relativePosition()); } } } Q_EMIT screenSizeChanged(screenSize()); } void WindowedSurfaceFactory::updateInputMethodArea() { if (!mActive) return; QRegion inputMethodArea; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface && !surface->parent()) { inputMethodArea |= surface->inputMethodArea(); } } Q_EMIT inputMethodAreaChanged(inputMethodArea); } } // namespace Server } // namespace Maliit <commit_msg>Fix Qt5 window flags to prevent plugin surface from stealing focus<commit_after>/* * This file is part of Maliit framework * * * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Contact: maliit-discuss@lists.maliit.org * * Copyright (C) 2012 One Laptop per Child Association * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "windowedsurface.h" #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include "mimdummyinputcontext.h" #endif #include "mimapphostedserverlogic.h" #include <maliit/plugins/abstractwidgetssurface.h> #include <QApplication> #include <QDebug> #include <QDesktopWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsItem> #include <QWidget> #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QtGui/5.0.0/QtGui/qpa/qplatformnativeinterface.h> #include <QVariant> #include <QWindow> #endif #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif using Maliit::Plugins::AbstractSurface; namespace Maliit { namespace Server { namespace { const Qt::WindowFlags g_window_flags = #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Qt::WindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint | Qt::WindowDoesNotAcceptFocus); #else Qt::WindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint); #endif } class WindowedSurface : public virtual Maliit::Plugins::AbstractSurface { public: WindowedSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent, QWidget *toplevel) : AbstractSurface(), mFactory(factory), mOptions(options), mParent(parent), mToplevel(toplevel), mActive(false), mVisible(false), mRelativePosition() { QWidget *parentWidget = 0; if (parent) { parentWidget = parent->mToplevel.data(); } mToplevel->setParent(parentWidget, g_window_flags); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) mToplevel->setAttribute(Qt::WA_X11DoNotAcceptFocus); #endif mToplevel->setAutoFillBackground(false); mToplevel->setBackgroundRole(QPalette::NoRole); mToplevel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); updateVisibility(); } ~WindowedSurface() { } void show() { mVisible = true; updateVisibility(); } void hide() { mVisible = false; updateVisibility(); } QSize size() const { return mToplevel->size(); } void setSize(const QSize &size) { const QSize& desktopSize = QApplication::desktop()->screenGeometry().size(); if (isWindow()) { // stand-alone Maliit server if (mOptions & PositionCenterBottom) { mToplevel->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size)); } else { mToplevel->resize(size); } } else { // application-hosted Maliit server mToplevel->resize(size); } mFactory->updateInputMethodArea(); } QPoint relativePosition() const { return mRelativePosition; } void setRelativePosition(const QPoint &position) { mRelativePosition = position; QPoint parentPosition(0, 0); if (mParent) { if (isWindow() && !mParent->isWindow()) { parentPosition = mParent->mapToGlobal(QPoint(0, 0)); } else if (!isWindow() && mParent->isWindow()) { // do nothing } else { parentPosition = mParent->mToplevel->pos(); } } mToplevel->move(parentPosition + mRelativePosition); mFactory->updateInputMethodArea(); } QSharedPointer<AbstractSurface> parent() const { return mParent; } QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const { if (!eventSurface) return eventPosition; QSharedPointer<WindowedSurface> windowedSurface = qSharedPointerDynamicCast<WindowedSurface>(eventSurface); if (!windowedSurface) return QPoint(); return -mToplevel->pos() + eventPosition + windowedSurface->mToplevel->pos(); } void setActive(bool active) { mActive = active; updateVisibility(); } void applicationFocusChanged(WId winId) { if (mParent) return; #ifdef Q_WS_X11 XSetTransientForHint(QX11Info::display(), mToplevel->window()->effectiveWinId(), winId); #else Q_UNUSED(winId); #endif } QRegion inputMethodArea() { if (!mToplevel->isVisible()) return QRegion(); return QRegion(mToplevel->geometry()); } private: void updateVisibility() { mToplevel->setVisible(mActive && mVisible); mFactory->updateInputMethodArea(); } protected: bool isWindow() const { return mToplevel->isWindow(); } QPoint mapToGlobal(const QPoint &pos) const { return mToplevel->mapToGlobal(pos); } WindowedSurfaceFactory *mFactory; Options mOptions; QSharedPointer<WindowedSurface> mParent; QScopedPointer<QWidget> mToplevel; bool mActive; bool mVisible; QPoint mRelativePosition; }; class GraphicsView : public QGraphicsView { public: GraphicsView() : QGraphicsView() { setWindowFlags(g_window_flags); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) setAttribute(Qt::WA_X11DoNotAcceptFocus); #endif setAutoFillBackground(false); setBackgroundRole(QPalette::NoRole); setBackgroundBrush(Qt::transparent); // This is a workaround for non-compositing window managers. Apparently // setting this attribute while using such WMs may cause garbled // painting of VKB. #ifndef DISABLE_TRANSLUCENT_BACKGROUND_HINT setAttribute(Qt::WA_TranslucentBackground); #endif viewport()->setAutoFillBackground(false); } }; class RootItem : public QGraphicsItem { private: QRectF m_rect; public: explicit RootItem(QGraphicsItem *parent = 0) : QGraphicsItem(parent) , m_rect() { setFlag(QGraphicsItem::ItemHasNoContents); } void setRect(const QRectF &rect) { m_rect = rect; } virtual QRectF boundingRect() const { return m_rect; } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class WindowedGraphicsViewSurface : public WindowedSurface, public Maliit::Plugins::AbstractGraphicsViewSurface { public: WindowedGraphicsViewSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new GraphicsView), AbstractGraphicsViewSurface(), mRoot(0) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) MIMDummyInputContext dummy; #endif QGraphicsView *view = static_cast<QGraphicsView*>(mToplevel.data()); view->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); view->setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); view->setFrameShape(QFrame::NoFrame); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // Calling QGraphicsView::setScene() indirectly calls QWidget::inputContext() on the view. If there isn't // an input context set on the widget, this calls QApplication::inputContext(), which leads to infinite // recursion if surface creation happens during input method creation and QT_IM_MODULE is set (for example // when embedding maliit-server in the application) view->setInputContext(&dummy); #endif QGraphicsScene *scene = new QGraphicsScene(view); view->setScene(scene); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) view->setInputContext(0); #endif } ~WindowedGraphicsViewSurface() {} QGraphicsScene *scene() const { return view()->scene(); } QGraphicsView *view() const { return static_cast<QGraphicsView*>(mToplevel.data()); } void show() { WindowedSurface::show(); const QRect rect(QPoint(), mToplevel->size()); if (not mRoot) { scene()->addItem(mRoot = new RootItem); mRoot->setRect(rect); mRoot->show(); } } void setSize(const QSize &size) { WindowedSurface::setSize(size); view()->setSceneRect(QRect(QPoint(), mToplevel->size())); if (mRoot) { mRoot->setRect(QRect(QPoint(), mToplevel->size())); } } void clear() { mRoot = 0; scene()->clear(); } QGraphicsItem *root() const { return mRoot; } private: RootItem *mRoot; }; class WindowedWidgetSurface : public WindowedSurface, public Maliit::Plugins::AbstractWidgetSurface { public: WindowedWidgetSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new QWidget), AbstractWidgetSurface() {} QWidget* widget() const { return mToplevel.data(); } }; WindowedSurfaceFactory::WindowedSurfaceFactory() : AbstractSurfaceFactory() , surfaces() , mActive(false) { connect(QApplication::desktop(), SIGNAL(resized(int)), this, SLOT(screenResized(int))); } WindowedSurfaceFactory::~WindowedSurfaceFactory() { } QSize WindowedSurfaceFactory::screenSize() const { return QApplication::desktop()->screenGeometry().size(); } bool WindowedSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const { return options & AbstractSurface::TypeGraphicsView; } QSharedPointer<AbstractSurface> WindowedSurfaceFactory::create(AbstractSurface::Options options, const QSharedPointer<AbstractSurface> &parent) { QSharedPointer<WindowedSurface> defaultSurfaceParent(qSharedPointerDynamicCast<WindowedSurface>(parent)); if (options & Maliit::Plugins::AbstractSurface::TypeGraphicsView) { QSharedPointer<WindowedGraphicsViewSurface> newSurface(new WindowedGraphicsViewSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->view(), options); return newSurface; } else if (options & Maliit::Plugins::AbstractSurface::TypeWidget) { QSharedPointer<WindowedWidgetSurface> newSurface(new WindowedWidgetSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->widget(), options); return newSurface; } return QSharedPointer<AbstractSurface>(); } void WindowedSurfaceFactory::activate() { mActive = true; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(true); } } void WindowedSurfaceFactory::deactivate() { mActive = false; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(false); } } void WindowedSurfaceFactory::applicationFocusChanged(WId winId) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->applicationFocusChanged(winId); } } } void WindowedSurfaceFactory::screenResized(int) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->setSize(surface->size()); if (surface->parent()) { surface->setRelativePosition(surface->relativePosition()); } } } Q_EMIT screenSizeChanged(screenSize()); } void WindowedSurfaceFactory::updateInputMethodArea() { if (!mActive) return; QRegion inputMethodArea; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface && !surface->parent()) { inputMethodArea |= surface->inputMethodArea(); } } Q_EMIT inputMethodAreaChanged(inputMethodArea); } } // namespace Server } // namespace Maliit <|endoftext|>
<commit_before>/* * This file is part of meego-im-framework * * * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "windowedsurface.h" #include "mimdummyinputcontext.h" #include "mimapphostedserverlogic.h" #include <maliit/plugins/abstractwidgetssurface.h> #include <QApplication> #include <QDebug> #include <QDesktopWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsItem> #include <QWidget> #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QPlatformNativeInterface> #include <QVariant> #include <QWindow> #endif #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif using Maliit::Plugins::AbstractSurface; namespace Maliit { namespace Server { class WindowedSurface : public virtual Maliit::Plugins::AbstractSurface { public: WindowedSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent, QWidget *toplevel) : AbstractSurface(), mFactory(factory), mOptions(options), mParent(parent), mToplevel(toplevel), mActive(false), mVisible(false), mRelativePosition() { QWidget *parentWidget = 0; if (parent) { parentWidget = parent->mToplevel.data(); } mToplevel->setParent(parentWidget, static_cast<Qt::WindowFlags>(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint)); mToplevel->setAttribute(Qt::WA_X11DoNotAcceptFocus); mToplevel->setAutoFillBackground(false); mToplevel->setBackgroundRole(QPalette::NoRole); mToplevel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); updateVisibility(); } ~WindowedSurface() { } void show() { mVisible = true; updateVisibility(); } void hide() { mVisible = false; updateVisibility(); } QSize size() const { return mToplevel->size(); } void setSize(const QSize &size) { const QSize& desktopSize = QApplication::desktop()->screenGeometry().size(); if (mOptions & PositionCenterBottom) { mToplevel->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size)); } else { mToplevel->resize(size); } mFactory->updateInputMethodArea(); } QPoint relativePosition() const { return mRelativePosition; } void setRelativePosition(const QPoint &position) { mRelativePosition = position; QPoint parentPosition(0, 0); if (mParent) { parentPosition = mParent->mToplevel->pos(); } mToplevel->move(parentPosition + mRelativePosition); mFactory->updateInputMethodArea(); } QSharedPointer<AbstractSurface> parent() const { return mParent; } QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const { if (!eventSurface) return eventPosition; QSharedPointer<WindowedSurface> windowedSurface = qSharedPointerDynamicCast<WindowedSurface>(eventSurface); if (!windowedSurface) return QPoint(); return -mToplevel->pos() + eventPosition + windowedSurface->mToplevel->pos(); } void setActive(bool active) { mActive = active; updateVisibility(); } void applicationFocusChanged(WId winId) { if (mParent) return; #ifdef Q_WS_X11 XSetTransientForHint(QX11Info::display(), mToplevel->window()->effectiveWinId(), winId); #else Q_UNUSED(winId); #endif } QRegion inputMethodArea() { if (!mToplevel->isVisible()) return QRegion(); return QRegion(mToplevel->geometry()); } private: void updateVisibility() { mToplevel->setVisible(mActive && mVisible); mFactory->updateInputMethodArea(); } protected: WindowedSurfaceFactory *mFactory; Options mOptions; QSharedPointer<WindowedSurface> mParent; QScopedPointer<QWidget> mToplevel; bool mActive; bool mVisible; QPoint mRelativePosition; }; class GraphicsView : public QGraphicsView { public: GraphicsView() : QGraphicsView() { setWindowFlags(static_cast<Qt::WindowFlags>(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)); setAttribute(Qt::WA_X11DoNotAcceptFocus); setAutoFillBackground(false); setBackgroundRole(QPalette::NoRole); setBackgroundBrush(Qt::transparent); setAttribute(Qt::WA_TranslucentBackground); viewport()->setAutoFillBackground(false); } }; class RootItem : public QGraphicsItem { private: QRectF m_rect; public: explicit RootItem(QGraphicsItem *parent = 0) : QGraphicsItem(parent) , m_rect() { setFlag(QGraphicsItem::ItemHasNoContents); } void setRect(const QRectF &rect) { m_rect = rect; } virtual QRectF boundingRect() const { return m_rect; } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class WindowedGraphicsViewSurface : public WindowedSurface, public Maliit::Plugins::AbstractGraphicsViewSurface { public: WindowedGraphicsViewSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new GraphicsView), AbstractGraphicsViewSurface(), mRoot(0) { MIMDummyInputContext dummy; QGraphicsView *view = static_cast<QGraphicsView*>(mToplevel.data()); view->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); view->setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); view->setFrameShape(QFrame::NoFrame); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Calling QGraphicsView::setScene() indirectly calls QWidget::inputContext() on the view. If there isn't // an input context set on the widget, this calls QApplication::inputContext(), which leads to infinite // recursion if surface creation happens during input method creation and QT_IM_MODULE is set (for example // when embedding maliit-server in the application) view->setInputContext(&dummy); QGraphicsScene *scene = new QGraphicsScene(view); view->setScene(scene); view->setInputContext(0); } ~WindowedGraphicsViewSurface() {} QGraphicsScene *scene() const { return view()->scene(); } QGraphicsView *view() const { return static_cast<QGraphicsView*>(mToplevel.data()); } void show() { WindowedSurface::show(); const QRect rect(QPoint(), mToplevel->size()); if (not mRoot) { scene()->addItem(mRoot = new RootItem); mRoot->setRect(rect); mRoot->show(); } } void setSize(const QSize &size) { WindowedSurface::setSize(size); view()->setSceneRect(QRect(QPoint(), mToplevel->size())); if (mRoot) { mRoot->setRect(QRect(QPoint(), mToplevel->size())); } } void clear() { mRoot = 0; scene()->clear(); } QGraphicsItem *root() const { return mRoot; } private: RootItem *mRoot; }; class WindowedWidgetSurface : public WindowedSurface, public Maliit::Plugins::AbstractWidgetSurface { public: WindowedWidgetSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new QWidget), AbstractWidgetSurface() {} QWidget* widget() const { return mToplevel.data(); } }; WindowedSurfaceFactory::WindowedSurfaceFactory() : AbstractSurfaceFactory() , surfaces() , mActive(false) { connect(QApplication::desktop(), SIGNAL(resized(int)), this, SLOT(screenResized(int))); } WindowedSurfaceFactory::~WindowedSurfaceFactory() { } QSize WindowedSurfaceFactory::screenSize() const { return QApplication::desktop()->screenGeometry().size(); } bool WindowedSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const { return options & AbstractSurface::TypeGraphicsView; } QSharedPointer<AbstractSurface> WindowedSurfaceFactory::create(AbstractSurface::Options options, const QSharedPointer<AbstractSurface> &parent) { QSharedPointer<WindowedSurface> defaultSurfaceParent(qSharedPointerDynamicCast<WindowedSurface>(parent)); if (options & Maliit::Plugins::AbstractSurface::TypeGraphicsView) { QSharedPointer<WindowedGraphicsViewSurface> newSurface(new WindowedGraphicsViewSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->view(), options); return newSurface; } else if (options & Maliit::Plugins::AbstractSurface::TypeWidget) { QSharedPointer<WindowedWidgetSurface> newSurface(new WindowedWidgetSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->widget(), options); return newSurface; } return QSharedPointer<AbstractSurface>(); } void WindowedSurfaceFactory::activate() { mActive = true; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(true); } } void WindowedSurfaceFactory::deactivate() { mActive = false; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(false); } } void WindowedSurfaceFactory::applicationFocusChanged(WId winId) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->applicationFocusChanged(winId); } } } void WindowedSurfaceFactory::screenResized(int) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->setSize(surface->size()); if (surface->parent()) { surface->setRelativePosition(surface->relativePosition()); } } } Q_EMIT screenSizeChanged(screenSize()); } void WindowedSurfaceFactory::updateInputMethodArea() { if (!mActive) return; QRegion inputMethodArea; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface && !surface->parent()) { inputMethodArea |= surface->inputMethodArea(); } } Q_EMIT inputMethodAreaChanged(inputMethodArea); } } // namespace Server } // namespace Maliit <commit_msg>Do not use setGeometry() with screen-based coordinates for non-toplevel windows.<commit_after>/* * This file is part of meego-im-framework * * * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "windowedsurface.h" #include "mimdummyinputcontext.h" #include "mimapphostedserverlogic.h" #include <maliit/plugins/abstractwidgetssurface.h> #include <QApplication> #include <QDebug> #include <QDesktopWidget> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsItem> #include <QWidget> #if QT_VERSION >= 0x050000 #include <QGuiApplication> #include <QPlatformNativeInterface> #include <QVariant> #include <QWindow> #endif #ifdef Q_WS_X11 #include <QX11Info> #include <X11/Xlib.h> #endif using Maliit::Plugins::AbstractSurface; namespace Maliit { namespace Server { class WindowedSurface : public virtual Maliit::Plugins::AbstractSurface { public: WindowedSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent, QWidget *toplevel) : AbstractSurface(), mFactory(factory), mOptions(options), mParent(parent), mToplevel(toplevel), mActive(false), mVisible(false), mRelativePosition() { QWidget *parentWidget = 0; if (parent) { parentWidget = parent->mToplevel.data(); } mToplevel->setParent(parentWidget, static_cast<Qt::WindowFlags>(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint)); mToplevel->setAttribute(Qt::WA_X11DoNotAcceptFocus); mToplevel->setAutoFillBackground(false); mToplevel->setBackgroundRole(QPalette::NoRole); mToplevel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); updateVisibility(); } ~WindowedSurface() { } void show() { mVisible = true; updateVisibility(); } void hide() { mVisible = false; updateVisibility(); } QSize size() const { return mToplevel->size(); } void setSize(const QSize &size) { const QSize& desktopSize = QApplication::desktop()->screenGeometry().size(); if (isWindow()) { // stand-alone Maliit server if (mOptions & PositionCenterBottom) { mToplevel->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size)); } else { mToplevel->resize(size); } } else { // application-hosted Maliit server mToplevel->resize(size); } mFactory->updateInputMethodArea(); } QPoint relativePosition() const { return mRelativePosition; } void setRelativePosition(const QPoint &position) { mRelativePosition = position; QPoint parentPosition(0, 0); if (mParent) { parentPosition = mParent->mToplevel->pos(); } mToplevel->move(parentPosition + mRelativePosition); mFactory->updateInputMethodArea(); } QSharedPointer<AbstractSurface> parent() const { return mParent; } QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const { if (!eventSurface) return eventPosition; QSharedPointer<WindowedSurface> windowedSurface = qSharedPointerDynamicCast<WindowedSurface>(eventSurface); if (!windowedSurface) return QPoint(); return -mToplevel->pos() + eventPosition + windowedSurface->mToplevel->pos(); } void setActive(bool active) { mActive = active; updateVisibility(); } void applicationFocusChanged(WId winId) { if (mParent) return; #ifdef Q_WS_X11 XSetTransientForHint(QX11Info::display(), mToplevel->window()->effectiveWinId(), winId); #else Q_UNUSED(winId); #endif } QRegion inputMethodArea() { if (!mToplevel->isVisible()) return QRegion(); return QRegion(mToplevel->geometry()); } private: void updateVisibility() { mToplevel->setVisible(mActive && mVisible); mFactory->updateInputMethodArea(); } protected: bool isWindow() const { return mToplevel->isWindow(); } WindowedSurfaceFactory *mFactory; Options mOptions; QSharedPointer<WindowedSurface> mParent; QScopedPointer<QWidget> mToplevel; bool mActive; bool mVisible; QPoint mRelativePosition; }; class GraphicsView : public QGraphicsView { public: GraphicsView() : QGraphicsView() { setWindowFlags(static_cast<Qt::WindowFlags>(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)); setAttribute(Qt::WA_X11DoNotAcceptFocus); setAutoFillBackground(false); setBackgroundRole(QPalette::NoRole); setBackgroundBrush(Qt::transparent); setAttribute(Qt::WA_TranslucentBackground); viewport()->setAutoFillBackground(false); } }; class RootItem : public QGraphicsItem { private: QRectF m_rect; public: explicit RootItem(QGraphicsItem *parent = 0) : QGraphicsItem(parent) , m_rect() { setFlag(QGraphicsItem::ItemHasNoContents); } void setRect(const QRectF &rect) { m_rect = rect; } virtual QRectF boundingRect() const { return m_rect; } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class WindowedGraphicsViewSurface : public WindowedSurface, public Maliit::Plugins::AbstractGraphicsViewSurface { public: WindowedGraphicsViewSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new GraphicsView), AbstractGraphicsViewSurface(), mRoot(0) { MIMDummyInputContext dummy; QGraphicsView *view = static_cast<QGraphicsView*>(mToplevel.data()); view->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate); view->setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontSavePainterState); view->setFrameShape(QFrame::NoFrame); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Calling QGraphicsView::setScene() indirectly calls QWidget::inputContext() on the view. If there isn't // an input context set on the widget, this calls QApplication::inputContext(), which leads to infinite // recursion if surface creation happens during input method creation and QT_IM_MODULE is set (for example // when embedding maliit-server in the application) view->setInputContext(&dummy); QGraphicsScene *scene = new QGraphicsScene(view); view->setScene(scene); view->setInputContext(0); } ~WindowedGraphicsViewSurface() {} QGraphicsScene *scene() const { return view()->scene(); } QGraphicsView *view() const { return static_cast<QGraphicsView*>(mToplevel.data()); } void show() { WindowedSurface::show(); const QRect rect(QPoint(), mToplevel->size()); if (not mRoot) { scene()->addItem(mRoot = new RootItem); mRoot->setRect(rect); mRoot->show(); } } void setSize(const QSize &size) { WindowedSurface::setSize(size); view()->setSceneRect(QRect(QPoint(), mToplevel->size())); if (mRoot) { mRoot->setRect(QRect(QPoint(), mToplevel->size())); } } void clear() { mRoot = 0; scene()->clear(); } QGraphicsItem *root() const { return mRoot; } private: RootItem *mRoot; }; class WindowedWidgetSurface : public WindowedSurface, public Maliit::Plugins::AbstractWidgetSurface { public: WindowedWidgetSurface(WindowedSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<WindowedSurface> &parent) : WindowedSurface(factory, options, parent, new QWidget), AbstractWidgetSurface() {} QWidget* widget() const { return mToplevel.data(); } }; WindowedSurfaceFactory::WindowedSurfaceFactory() : AbstractSurfaceFactory() , surfaces() , mActive(false) { connect(QApplication::desktop(), SIGNAL(resized(int)), this, SLOT(screenResized(int))); } WindowedSurfaceFactory::~WindowedSurfaceFactory() { } QSize WindowedSurfaceFactory::screenSize() const { return QApplication::desktop()->screenGeometry().size(); } bool WindowedSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const { return options & AbstractSurface::TypeGraphicsView; } QSharedPointer<AbstractSurface> WindowedSurfaceFactory::create(AbstractSurface::Options options, const QSharedPointer<AbstractSurface> &parent) { QSharedPointer<WindowedSurface> defaultSurfaceParent(qSharedPointerDynamicCast<WindowedSurface>(parent)); if (options & Maliit::Plugins::AbstractSurface::TypeGraphicsView) { QSharedPointer<WindowedGraphicsViewSurface> newSurface(new WindowedGraphicsViewSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->view(), options); return newSurface; } else if (options & Maliit::Plugins::AbstractSurface::TypeWidget) { QSharedPointer<WindowedWidgetSurface> newSurface(new WindowedWidgetSurface(this, options, defaultSurfaceParent)); surfaces.push_back(newSurface); Q_EMIT surfaceWidgetCreated(newSurface->widget(), options); return newSurface; } return QSharedPointer<AbstractSurface>(); } void WindowedSurfaceFactory::activate() { mActive = true; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(true); } } void WindowedSurfaceFactory::deactivate() { mActive = false; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) surface->setActive(false); } } void WindowedSurfaceFactory::applicationFocusChanged(WId winId) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->applicationFocusChanged(winId); } } } void WindowedSurfaceFactory::screenResized(int) { Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface) { surface->setSize(surface->size()); if (surface->parent()) { surface->setRelativePosition(surface->relativePosition()); } } } Q_EMIT screenSizeChanged(screenSize()); } void WindowedSurfaceFactory::updateInputMethodArea() { if (!mActive) return; QRegion inputMethodArea; Q_FOREACH(QWeakPointer<WindowedSurface> weakSurface, surfaces) { QSharedPointer<WindowedSurface> surface = weakSurface.toStrongRef(); if (surface && !surface->parent()) { inputMethodArea |= surface->inputMethodArea(); } } Q_EMIT inputMethodAreaChanged(inputMethodArea); } } // namespace Server } // namespace Maliit <|endoftext|>
<commit_before>#include <boost/algorithm/string.hpp> #include <iostream> using namespace std; string encrypt(const string& plaintext, const string& keyword) { /* Returns the plaintext encrypted using the given keyword and the Vigenere * Cipher (http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher). * * For now, assumes that the length of the plaintext is greater than or equal * to the length of the keyword. */ string keyphrase = "" int reps = plaintext.length() / keyword.length() + 1 for (int i = 0; i < plaintext.length() / { } string plaintext = boost::algorithm::to_upper_copy<string>(plaintext); return plaintext + " " keyword; } <commit_msg>Removed length restriction.<commit_after>#include <boost/algorithm/string.hpp> #include <iostream> using namespace std; string encrypt(const string& plaintext, const string& keyword) { /* Returns the plaintext encrypted using the given keyword and the Vigenere * Cipher (http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher). */ string keyphrase = "" int reps = plaintext.length() / keyword.length() + 1 for (int i = 0; i < plaintext.length() / { } string plaintext = boost::algorithm::to_upper_copy<string>(plaintext); return plaintext + " " keyword; } <|endoftext|>
<commit_before> #include <xmppproxystream.h> #include <xmppproxy.h> #include <logs.h> #include <sys/socket.h> #include <arpa/inet.h> //#include <netinet/in.h> //#include <netdb.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <string.h> using namespace std; /** * Конструктор */ XMPPProxyStream::XMPPProxyStream(XMPPProxy *prx): proxy(prx), AsyncStream(0), ready_read(false), ready_write(false), pair(0), finish_count(0) { tx = rx = rxsec = rxsec_limit = rxsec_switch = 0; client = true; } /** * Конструктор потока XMPP-прокси * * @param prx ссылка на прокси * @param s ссылка на противоположный сокет * @param socket сокет */ XMPPProxyStream::XMPPProxyStream(class XMPPProxy *prx, XMPPProxyStream *s, int socket): proxy(prx), AsyncStream(socket), ready_read(true), ready_write(false), pair(s), finish_count(0) { tx = rx = rxsec = rxsec_limit = rxsec_switch = 0; client = false; } /** * Деструктор */ XMPPProxyStream::~XMPPProxyStream() { } /** * Принять сокет * @param sock принимаемый сокет * @param ip IP сервера к которому надо приконнектисться * @param port порт сервера * @return TRUE - сокет принят, FALSE сокет отклонен */ bool XMPPProxyStream::accept(int sock, const char *ip, int port) { struct sockaddr_in target; // Клиент который к нам приконнектился fd = sock; // Сервер к которому мы коннектимся int server_socket = ::socket(PF_INET, SOCK_STREAM, 0); if ( server_socket <= 0 ) return false; target.sin_family = AF_INET; target.sin_port = htons(port); inet_pton(AF_INET, ip, &(target.sin_addr)); memset(target.sin_zero, '\0', 8); if ( ::connect(server_socket, (struct sockaddr *)&target, sizeof( struct sockaddr )) == 0 ) { fcntl(server_socket, F_SETFL, O_NONBLOCK); this->pair = new XMPPProxyStream(proxy, this, server_socket); ready_read = true; proxy->daemon->addObject(this); proxy->daemon->addObject(this->pair); return true; } ::close(server_socket); // shit! fprintf(stderr, "connect(%s:%d) fault\n", ip, port); ::shutdown(fd, SHUT_RDWR); return false; } /** * Вернуть маску ожидаемых событий */ uint32_t XMPPProxyStream::getEventsMask() { uint32_t mask = EPOLLRDHUP | EPOLLONESHOT | EPOLLHUP | EPOLLERR; if ( ready_read && ((rxsec_limit == 0) || (rxsec <= rxsec_limit)) ) mask |= EPOLLIN; if ( ready_write ) mask |= EPOLLOUT; return mask; } /** * Таймер-функция разблокировки потока * @param data указатель на XMPPProxyStream который надо разблочить */ void XMPPProxyStream::unblock(int wid, void *data) { XMPPProxyStream *stream = static_cast<XMPPProxyStream *>(data); printf("[XMPPProxyStream: %d] unlock stream\n", stream->fd); stream->rxsec = 0; stream->proxy->daemon->modifyObject(stream); stream->release(); } #include <stdlib.h> /** * Событие готовности к чтению * * Вызывается когда в потоке есть данные, * которые можно прочитать без блокирования */ void XMPPProxyStream::onRead() { if ( mutex.lock() ) { int x = random(); ssize_t r = read(pair->buffer, sizeof(pair->buffer)); if ( r > 0 ) { rx += r; pair->len = r; pair->written = 0; //if ( ! pair->writeChunk() ) { ready_read = false; pair->ready_write = true; proxy->daemon->modifyObject(pair); } // проверка ограничений if ( rxsec_limit > 0 ) { time_t tm = time(0); int mask = tm & 1; if ( rxsec_switch != mask ) { rxsec = 0; rxsec_switch = mask; } rxsec += r; if ( rxsec > rxsec_limit ) { printf("[XMPPProxyStream: %d] lock stream, recieved %d bytes per second\n", fd, rxsec); this->lock(); proxy->daemon->setTimer(tm+1, unblock, this); } } } mutex.unlock(); } } /** * Записать кусок * @return TRUE всё записал, FALSE ничего не записал или только часть */ bool XMPPProxyStream::writeChunk() { ssize_t r = write(buffer + written, len - written); if ( r > 0 ) { len -= r; written += r; tx += r; return len == 0; } return false; } /** * Событие готовности к записи * * Вызывается, когда в поток готов принять * данные для записи без блокировки */ void XMPPProxyStream::onWrite() { if ( writeChunk() ) { ready_write = false; if ( pair->mutex.lock() ) { pair->ready_read = true; proxy->daemon->modifyObject(pair); pair->mutex.unlock(); } } } /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ void XMPPProxyStream::onPeerDown() { printf("#%d: [XMPPProxyStream: %d] peer down\n", getWorkerId(), fd); ::shutdown(pair->fd, SHUT_WR); pair = 0; proxy->daemon->removeObject(this); } /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ void XMPPProxyStream::onShutdown() { printf("#%d: [XMPPProxyStream: %d] shutdown\n", getWorkerId(), fd); ::shutdown(pair->fd, SHUT_RDWR); proxy->daemon->removeObject(this); pair = 0; } /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ void XMPPProxyStream::onTerminate() { printf("#%d: [XMPPProxyStream: %d] onTerminate\n", getWorkerId(), fd); ::shutdown(fd, SHUT_RDWR); ::shutdown(pair->fd, SHUT_RDWR); } <commit_msg>XMPPProxy: fix логирование дисконнектов<commit_after> #include <xmppproxystream.h> #include <xmppproxy.h> #include <logs.h> #include <sys/socket.h> #include <arpa/inet.h> //#include <netinet/in.h> //#include <netdb.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <string.h> using namespace std; /** * Конструктор */ XMPPProxyStream::XMPPProxyStream(XMPPProxy *prx): proxy(prx), AsyncStream(0), ready_read(false), ready_write(false), pair(0), finish_count(0) { tx = rx = rxsec = rxsec_limit = rxsec_switch = 0; client = true; } /** * Конструктор потока XMPP-прокси * * @param prx ссылка на прокси * @param s ссылка на противоположный сокет * @param socket сокет */ XMPPProxyStream::XMPPProxyStream(class XMPPProxy *prx, XMPPProxyStream *s, int socket): proxy(prx), AsyncStream(socket), ready_read(true), ready_write(false), pair(s), finish_count(0) { tx = rx = rxsec = rxsec_limit = rxsec_switch = 0; client = false; } /** * Деструктор */ XMPPProxyStream::~XMPPProxyStream() { if ( client ) { fprintf(stdlog, "%s [proxyd] disconnect from: %s, rx: %lld, tx: %lld\n", logtime().c_str(), remoteIP.c_str(), rx, tx); } } /** * Принять сокет * @param sock принимаемый сокет * @param ip IP сервера к которому надо приконнектисться * @param port порт сервера * @return TRUE - сокет принят, FALSE сокет отклонен */ bool XMPPProxyStream::accept(int sock, const char *ip, int port) { struct sockaddr_in target; // Клиент который к нам приконнектился fd = sock; // Сервер к которому мы коннектимся int server_socket = ::socket(PF_INET, SOCK_STREAM, 0); if ( server_socket <= 0 ) return false; target.sin_family = AF_INET; target.sin_port = htons(port); inet_pton(AF_INET, ip, &(target.sin_addr)); memset(target.sin_zero, '\0', 8); if ( ::connect(server_socket, (struct sockaddr *)&target, sizeof( struct sockaddr )) == 0 ) { fcntl(server_socket, F_SETFL, O_NONBLOCK); this->pair = new XMPPProxyStream(proxy, this, server_socket); ready_read = true; proxy->daemon->addObject(this); proxy->daemon->addObject(this->pair); return true; } ::close(server_socket); // shit! fprintf(stdlog, "%s [proxyd] connect(%s:%d) for %s failed\n", logtime().c_str(), ip, port, remoteIP.c_str()); ::shutdown(fd, SHUT_RDWR); return false; } /** * Вернуть маску ожидаемых событий */ uint32_t XMPPProxyStream::getEventsMask() { uint32_t mask = EPOLLRDHUP | EPOLLONESHOT | EPOLLHUP | EPOLLERR; if ( ready_read && ((rxsec_limit == 0) || (rxsec <= rxsec_limit)) ) mask |= EPOLLIN; if ( ready_write ) mask |= EPOLLOUT; return mask; } /** * Таймер-функция разблокировки потока * @param data указатель на XMPPProxyStream который надо разблочить */ void XMPPProxyStream::unblock(int wid, void *data) { XMPPProxyStream *stream = static_cast<XMPPProxyStream *>(data); printf("[XMPPProxyStream: %d] unlock stream\n", stream->fd); stream->rxsec = 0; stream->proxy->daemon->modifyObject(stream); stream->release(); } /** * Событие готовности к чтению * * Вызывается когда в потоке есть данные, * которые можно прочитать без блокирования */ void XMPPProxyStream::onRead() { if ( mutex.lock() ) { ssize_t r = read(pair->buffer, sizeof(pair->buffer)); if ( r > 0 ) { rx += r; pair->len = r; pair->written = 0; //if ( ! pair->writeChunk() ) { ready_read = false; pair->ready_write = true; proxy->daemon->modifyObject(pair); } // проверка ограничений if ( rxsec_limit > 0 ) { time_t tm = time(0); int mask = tm & 1; if ( rxsec_switch != mask ) { rxsec = 0; rxsec_switch = mask; } rxsec += r; if ( rxsec > rxsec_limit ) { printf("[XMPPProxyStream: %d] lock stream, recieved %d bytes per second\n", fd, rxsec); this->lock(); proxy->daemon->setTimer(tm+1, unblock, this); } } } mutex.unlock(); } } /** * Записать кусок * @return TRUE всё записал, FALSE ничего не записал или только часть */ bool XMPPProxyStream::writeChunk() { ssize_t r = write(buffer + written, len - written); if ( r > 0 ) { len -= r; written += r; tx += r; return len == 0; } return false; } /** * Событие готовности к записи * * Вызывается, когда в поток готов принять * данные для записи без блокировки */ void XMPPProxyStream::onWrite() { if ( writeChunk() ) { ready_write = false; if ( pair->mutex.lock() ) { pair->ready_read = true; proxy->daemon->modifyObject(pair); pair->mutex.unlock(); } } } /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ void XMPPProxyStream::onPeerDown() { printf("#%d: [XMPPProxyStream: %d] peer down\n", getWorkerId(), fd); ::shutdown(pair->fd, SHUT_WR); pair = 0; proxy->daemon->removeObject(this); } /** * Пир (peer) закрыл поток. * * Мы уже ничего не можем отправить в ответ, * можем только корректно закрыть соединение с нашей стороны. */ void XMPPProxyStream::onShutdown() { printf("#%d: [XMPPProxyStream: %d] shutdown\n", getWorkerId(), fd); ::shutdown(pair->fd, SHUT_RDWR); proxy->daemon->removeObject(this); pair = 0; } /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ void XMPPProxyStream::onTerminate() { printf("#%d: [XMPPProxyStream: %d] onTerminate\n", getWorkerId(), fd); ::shutdown(fd, SHUT_RDWR); ::shutdown(pair->fd, SHUT_RDWR); } <|endoftext|>
<commit_before>#include "master.hpp" namespace factor { /* Certain special objects in the image are known to the runtime */ void factor_vm::init_objects(image_header* h) { memcpy(special_objects, h->special_objects, sizeof(special_objects)); true_object = h->true_object; bignum_zero = h->bignum_zero; bignum_pos_one = h->bignum_pos_one; bignum_neg_one = h->bignum_neg_one; } void factor_vm::load_data_heap(FILE* file, image_header* h, vm_parameters* p) { p->tenured_size = std::max((h->data_size * 3) / 2, p->tenured_size); init_data_heap(p->young_size, p->aging_size, p->tenured_size); fixnum bytes_read = safe_fread((void*)data->tenured->start, 1, h->data_size, file); if ((cell)bytes_read != h->data_size) { std::cout << "truncated image: " << bytes_read << " bytes read, "; std::cout << h->data_size << " bytes expected\n"; fatal_error("load_data_heap failed", 0); } data->tenured->initial_free_list(h->data_size); } void factor_vm::load_code_heap(FILE* file, image_header* h, vm_parameters* p) { if (h->code_size > p->code_size) fatal_error("Code heap too small to fit image", h->code_size); init_code_heap(p->code_size); if (h->code_size != 0) { size_t bytes_read = safe_fread(code->allocator->first_block(), 1, h->code_size, file); if (bytes_read != h->code_size) { std::cout << "truncated image: " << bytes_read << " bytes read, "; std::cout << h->code_size << " bytes expected\n"; fatal_error("load_code_heap failed", 0); } } code->allocator->initial_free_list(h->code_size); code->initialize_all_blocks_set(); } struct startup_fixup { static const bool translated_code_block_map = true; cell data_offset; cell code_offset; startup_fixup(cell data_offset, cell code_offset) : data_offset(data_offset), code_offset(code_offset) {} object* fixup_data(object* obj) { return (object*)((cell)obj + data_offset); } code_block* fixup_code(code_block* obj) { return (code_block*)((cell)obj + code_offset); } object* translate_data(const object* obj) { return fixup_data((object*)obj); } code_block* translate_code(const code_block* compiled) { return fixup_code((code_block*)compiled); } cell size(const object* obj) { return obj->size(*this); } cell size(code_block* compiled) { return compiled->size(*this); } }; struct start_object_updater { factor_vm* parent; startup_fixup fixup; slot_visitor<startup_fixup> data_visitor; code_block_visitor<startup_fixup> code_visitor; start_object_updater(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup), data_visitor(slot_visitor<startup_fixup>(parent, fixup)), code_visitor(code_block_visitor<startup_fixup>(parent, fixup)) {} void operator()(object* obj, cell size) { parent->data->tenured->starts.record_object_start_offset(obj); data_visitor.visit_slots(obj); switch (obj->type()) { case ALIEN_TYPE: { alien* ptr = (alien*)obj; if (to_boolean(ptr->base)) ptr->update_address(); else ptr->expired = parent->true_object; break; } case DLL_TYPE: { parent->ffi_dlopen((dll*)obj); break; } default: { code_visitor.visit_object_code_block(obj); break; } } } }; void factor_vm::fixup_data(cell data_offset, cell code_offset) { startup_fixup fixup(data_offset, code_offset); slot_visitor<startup_fixup> data_workhorse(this, fixup); data_workhorse.visit_roots(); start_object_updater updater(this, fixup); data->tenured->iterate(updater, fixup); } struct startup_code_block_relocation_visitor { factor_vm* parent; startup_fixup fixup; slot_visitor<startup_fixup> data_visitor; startup_code_block_relocation_visitor(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup), data_visitor(slot_visitor<startup_fixup>(parent, fixup)) {} void operator()(instruction_operand op) { code_block* compiled = op.compiled; cell old_offset = op.rel_offset() + (cell)compiled->entry_point() - fixup.code_offset; switch (op.rel_type()) { case RT_LITERAL: { cell value = op.load_value(old_offset); if (immediate_p(value)) op.store_value(value); else op.store_value( RETAG(fixup.fixup_data(untag<object>(value)), TAG(value))); break; } case RT_ENTRY_POINT: case RT_ENTRY_POINT_PIC: case RT_ENTRY_POINT_PIC_TAIL: case RT_HERE: { cell value = op.load_value(old_offset); cell offset = TAG(value); code_block* compiled = (code_block*)UNTAG(value); op.store_value((cell)fixup.fixup_code(compiled) + offset); break; } case RT_UNTAGGED: break; default: parent->store_external_address(op); break; } } }; struct startup_code_block_updater { factor_vm* parent; startup_fixup fixup; startup_code_block_updater(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup) {} void operator()(code_block* compiled, cell size) { slot_visitor<startup_fixup> data_visitor(parent, fixup); data_visitor.visit_code_block_objects(compiled); startup_code_block_relocation_visitor code_visitor(parent, fixup); compiled->each_instruction_operand(code_visitor); } }; void factor_vm::fixup_code(cell data_offset, cell code_offset) { startup_fixup fixup(data_offset, code_offset); startup_code_block_updater updater(this, fixup); code->allocator->iterate(updater, fixup); } bool factor_vm::read_embedded_image_footer(FILE* file, embedded_image_footer* footer) { safe_fseek(file, -(off_t)sizeof(embedded_image_footer), SEEK_END); safe_fread(footer, (off_t)sizeof(embedded_image_footer), 1, file); return footer->magic == image_magic; } FILE* factor_vm::open_image(vm_parameters* p) { if (p->embedded_image) { FILE* file = OPEN_READ(p->executable_path); if (file == NULL) { std::cout << "Cannot open embedded image" << std::endl; std::cout << strerror(errno) << std::endl; exit(1); } embedded_image_footer footer; if (!read_embedded_image_footer(file, &footer)) { std::cout << "No embedded image" << std::endl; exit(1); } safe_fseek(file, (off_t)footer.image_offset, SEEK_SET); return file; } else return OPEN_READ(p->image_path); } /* Read an image file from disk, only done once during startup */ /* This function also initializes the data and code heaps */ void factor_vm::load_image(vm_parameters* p) { FILE* file = open_image(p); if (file == NULL) { std::cout << "Cannot open image file: " << p->image_path << std::endl; std::cout << strerror(errno) << std::endl; exit(1); } image_header h; if (safe_fread(&h, sizeof(image_header), 1, file) != 1) fatal_error("Cannot read image header", 0); if (h.magic != image_magic) fatal_error("Bad image: magic number check failed", h.magic); if (h.version != image_version) fatal_error("Bad image: version number check failed", h.version); load_data_heap(file, &h, p); load_code_heap(file, &h, p); safe_fclose(file); init_objects(&h); cell data_offset = data->tenured->start - h.data_relocation_base; cell code_offset = code->allocator->start - h.code_relocation_base; fixup_data(data_offset, code_offset); fixup_code(data_offset, code_offset); /* Store image path name */ special_objects[OBJ_IMAGE] = allot_alien(false_object, (cell)p->image_path); } /* Save the current image to disk */ bool factor_vm::save_image(const vm_char* saving_filename, const vm_char* filename) { FILE* file; image_header h; file = OPEN_WRITE(saving_filename); if (file == NULL) { std::cout << "Cannot open image file: " << saving_filename << std::endl; std::cout << strerror(errno) << std::endl; return false; } h.magic = image_magic; h.version = image_version; h.data_relocation_base = data->tenured->start; h.data_size = data->tenured->occupied_space(); h.code_relocation_base = code->allocator->start; h.code_size = code->allocator->occupied_space(); h.true_object = true_object; h.bignum_zero = bignum_zero; h.bignum_pos_one = bignum_pos_one; h.bignum_neg_one = bignum_neg_one; for (cell i = 0; i < special_object_count; i++) h.special_objects[i] = (save_special_p(i) ? special_objects[i] : false_object); bool ok = true; if (safe_fwrite(&h, sizeof(image_header), 1, file) != 1) ok = false; if (safe_fwrite((void*)data->tenured->start, h.data_size, 1, file) != 1) ok = false; if (safe_fwrite(code->allocator->first_block(), h.code_size, 1, file) != 1) ok = false; safe_fclose(file); if (!ok) std::cout << "save-image failed: " << strerror(errno) << std::endl; else move_file(saving_filename, filename); return ok; } void factor_vm::primitive_save_image() { /* do a full GC to push everything into tenured space */ primitive_compact_gc(); data_root<byte_array> path2(ctx->pop(), this); path2.untag_check(this); data_root<byte_array> path1(ctx->pop(), this); path1.untag_check(this); save_image((vm_char*)(path1.untagged() + 1), (vm_char*)(path2.untagged() + 1)); } void factor_vm::primitive_save_image_and_exit() { /* We unbox this before doing anything else. This is the only point where we might throw an error, so we have to throw an error here since later steps destroy the current image. */ data_root<byte_array> path2(ctx->pop(), this); path2.untag_check(this); data_root<byte_array> path1(ctx->pop(), this); path1.untag_check(this); /* strip out special_objects data which is set on startup anyway */ for (cell i = 0; i < special_object_count; i++) if (!save_special_p(i)) special_objects[i] = false_object; gc(collect_compact_op, 0, /* requested size */ false /* discard objects only reachable from stacks */); /* Save the image */ if (save_image((vm_char*)(path1.untagged() + 1), (vm_char*)(path2.untagged() + 1))) exit(0); else exit(1); } bool factor_vm::embedded_image_p() { const vm_char* vm_path = vm_executable_path(); if (!vm_path) return false; FILE* file = OPEN_READ(vm_path); if (!file) return false; embedded_image_footer footer; bool embedded_p = read_embedded_image_footer(file, &footer); fclose(file); return embedded_p; } } <commit_msg>vm/image.cpp: Better error for opening a file for writing.<commit_after>#include "master.hpp" namespace factor { /* Certain special objects in the image are known to the runtime */ void factor_vm::init_objects(image_header* h) { memcpy(special_objects, h->special_objects, sizeof(special_objects)); true_object = h->true_object; bignum_zero = h->bignum_zero; bignum_pos_one = h->bignum_pos_one; bignum_neg_one = h->bignum_neg_one; } void factor_vm::load_data_heap(FILE* file, image_header* h, vm_parameters* p) { p->tenured_size = std::max((h->data_size * 3) / 2, p->tenured_size); init_data_heap(p->young_size, p->aging_size, p->tenured_size); fixnum bytes_read = safe_fread((void*)data->tenured->start, 1, h->data_size, file); if ((cell)bytes_read != h->data_size) { std::cout << "truncated image: " << bytes_read << " bytes read, "; std::cout << h->data_size << " bytes expected\n"; fatal_error("load_data_heap failed", 0); } data->tenured->initial_free_list(h->data_size); } void factor_vm::load_code_heap(FILE* file, image_header* h, vm_parameters* p) { if (h->code_size > p->code_size) fatal_error("Code heap too small to fit image", h->code_size); init_code_heap(p->code_size); if (h->code_size != 0) { size_t bytes_read = safe_fread(code->allocator->first_block(), 1, h->code_size, file); if (bytes_read != h->code_size) { std::cout << "truncated image: " << bytes_read << " bytes read, "; std::cout << h->code_size << " bytes expected\n"; fatal_error("load_code_heap failed", 0); } } code->allocator->initial_free_list(h->code_size); code->initialize_all_blocks_set(); } struct startup_fixup { static const bool translated_code_block_map = true; cell data_offset; cell code_offset; startup_fixup(cell data_offset, cell code_offset) : data_offset(data_offset), code_offset(code_offset) {} object* fixup_data(object* obj) { return (object*)((cell)obj + data_offset); } code_block* fixup_code(code_block* obj) { return (code_block*)((cell)obj + code_offset); } object* translate_data(const object* obj) { return fixup_data((object*)obj); } code_block* translate_code(const code_block* compiled) { return fixup_code((code_block*)compiled); } cell size(const object* obj) { return obj->size(*this); } cell size(code_block* compiled) { return compiled->size(*this); } }; struct start_object_updater { factor_vm* parent; startup_fixup fixup; slot_visitor<startup_fixup> data_visitor; code_block_visitor<startup_fixup> code_visitor; start_object_updater(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup), data_visitor(slot_visitor<startup_fixup>(parent, fixup)), code_visitor(code_block_visitor<startup_fixup>(parent, fixup)) {} void operator()(object* obj, cell size) { parent->data->tenured->starts.record_object_start_offset(obj); data_visitor.visit_slots(obj); switch (obj->type()) { case ALIEN_TYPE: { alien* ptr = (alien*)obj; if (to_boolean(ptr->base)) ptr->update_address(); else ptr->expired = parent->true_object; break; } case DLL_TYPE: { parent->ffi_dlopen((dll*)obj); break; } default: { code_visitor.visit_object_code_block(obj); break; } } } }; void factor_vm::fixup_data(cell data_offset, cell code_offset) { startup_fixup fixup(data_offset, code_offset); slot_visitor<startup_fixup> data_workhorse(this, fixup); data_workhorse.visit_roots(); start_object_updater updater(this, fixup); data->tenured->iterate(updater, fixup); } struct startup_code_block_relocation_visitor { factor_vm* parent; startup_fixup fixup; slot_visitor<startup_fixup> data_visitor; startup_code_block_relocation_visitor(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup), data_visitor(slot_visitor<startup_fixup>(parent, fixup)) {} void operator()(instruction_operand op) { code_block* compiled = op.compiled; cell old_offset = op.rel_offset() + (cell)compiled->entry_point() - fixup.code_offset; switch (op.rel_type()) { case RT_LITERAL: { cell value = op.load_value(old_offset); if (immediate_p(value)) op.store_value(value); else op.store_value( RETAG(fixup.fixup_data(untag<object>(value)), TAG(value))); break; } case RT_ENTRY_POINT: case RT_ENTRY_POINT_PIC: case RT_ENTRY_POINT_PIC_TAIL: case RT_HERE: { cell value = op.load_value(old_offset); cell offset = TAG(value); code_block* compiled = (code_block*)UNTAG(value); op.store_value((cell)fixup.fixup_code(compiled) + offset); break; } case RT_UNTAGGED: break; default: parent->store_external_address(op); break; } } }; struct startup_code_block_updater { factor_vm* parent; startup_fixup fixup; startup_code_block_updater(factor_vm* parent, startup_fixup fixup) : parent(parent), fixup(fixup) {} void operator()(code_block* compiled, cell size) { slot_visitor<startup_fixup> data_visitor(parent, fixup); data_visitor.visit_code_block_objects(compiled); startup_code_block_relocation_visitor code_visitor(parent, fixup); compiled->each_instruction_operand(code_visitor); } }; void factor_vm::fixup_code(cell data_offset, cell code_offset) { startup_fixup fixup(data_offset, code_offset); startup_code_block_updater updater(this, fixup); code->allocator->iterate(updater, fixup); } bool factor_vm::read_embedded_image_footer(FILE* file, embedded_image_footer* footer) { safe_fseek(file, -(off_t)sizeof(embedded_image_footer), SEEK_END); safe_fread(footer, (off_t)sizeof(embedded_image_footer), 1, file); return footer->magic == image_magic; } FILE* factor_vm::open_image(vm_parameters* p) { if (p->embedded_image) { FILE* file = OPEN_READ(p->executable_path); if (file == NULL) { std::cout << "Cannot open embedded image" << std::endl; std::cout << strerror(errno) << std::endl; exit(1); } embedded_image_footer footer; if (!read_embedded_image_footer(file, &footer)) { std::cout << "No embedded image" << std::endl; exit(1); } safe_fseek(file, (off_t)footer.image_offset, SEEK_SET); return file; } else return OPEN_READ(p->image_path); } /* Read an image file from disk, only done once during startup */ /* This function also initializes the data and code heaps */ void factor_vm::load_image(vm_parameters* p) { FILE* file = open_image(p); if (file == NULL) { std::cout << "Cannot open image file: " << p->image_path << std::endl; std::cout << strerror(errno) << std::endl; exit(1); } image_header h; if (safe_fread(&h, sizeof(image_header), 1, file) != 1) fatal_error("Cannot read image header", 0); if (h.magic != image_magic) fatal_error("Bad image: magic number check failed", h.magic); if (h.version != image_version) fatal_error("Bad image: version number check failed", h.version); load_data_heap(file, &h, p); load_code_heap(file, &h, p); safe_fclose(file); init_objects(&h); cell data_offset = data->tenured->start - h.data_relocation_base; cell code_offset = code->allocator->start - h.code_relocation_base; fixup_data(data_offset, code_offset); fixup_code(data_offset, code_offset); /* Store image path name */ special_objects[OBJ_IMAGE] = allot_alien(false_object, (cell)p->image_path); } /* Save the current image to disk */ bool factor_vm::save_image(const vm_char* saving_filename, const vm_char* filename) { FILE* file; image_header h; file = OPEN_WRITE(saving_filename); if (file == NULL) { std::cout << "Cannot open image file for writing: " << saving_filename << std::endl; std::cout << strerror(errno) << std::endl; return false; } h.magic = image_magic; h.version = image_version; h.data_relocation_base = data->tenured->start; h.data_size = data->tenured->occupied_space(); h.code_relocation_base = code->allocator->start; h.code_size = code->allocator->occupied_space(); h.true_object = true_object; h.bignum_zero = bignum_zero; h.bignum_pos_one = bignum_pos_one; h.bignum_neg_one = bignum_neg_one; for (cell i = 0; i < special_object_count; i++) h.special_objects[i] = (save_special_p(i) ? special_objects[i] : false_object); bool ok = true; if (safe_fwrite(&h, sizeof(image_header), 1, file) != 1) ok = false; if (safe_fwrite((void*)data->tenured->start, h.data_size, 1, file) != 1) ok = false; if (safe_fwrite(code->allocator->first_block(), h.code_size, 1, file) != 1) ok = false; safe_fclose(file); if (!ok) std::cout << "save-image failed: " << strerror(errno) << std::endl; else move_file(saving_filename, filename); return ok; } void factor_vm::primitive_save_image() { /* do a full GC to push everything into tenured space */ primitive_compact_gc(); data_root<byte_array> path2(ctx->pop(), this); path2.untag_check(this); data_root<byte_array> path1(ctx->pop(), this); path1.untag_check(this); save_image((vm_char*)(path1.untagged() + 1), (vm_char*)(path2.untagged() + 1)); } void factor_vm::primitive_save_image_and_exit() { /* We unbox this before doing anything else. This is the only point where we might throw an error, so we have to throw an error here since later steps destroy the current image. */ data_root<byte_array> path2(ctx->pop(), this); path2.untag_check(this); data_root<byte_array> path1(ctx->pop(), this); path1.untag_check(this); /* strip out special_objects data which is set on startup anyway */ for (cell i = 0; i < special_object_count; i++) if (!save_special_p(i)) special_objects[i] = false_object; gc(collect_compact_op, 0, /* requested size */ false /* discard objects only reachable from stacks */); /* Save the image */ if (save_image((vm_char*)(path1.untagged() + 1), (vm_char*)(path2.untagged() + 1))) exit(0); else exit(1); } bool factor_vm::embedded_image_p() { const vm_char* vm_path = vm_executable_path(); if (!vm_path) return false; FILE* file = OPEN_READ(vm_path); if (!file) return false; embedded_image_footer footer; bool embedded_p = read_embedded_image_footer(file, &footer); fclose(file); return embedded_p; } } <|endoftext|>
<commit_before>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> // Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4. // Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block. // Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile. #define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128 #define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16 #define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4 // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselves are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS) typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t width_in_pixels; uint32_t height_in_pixels; // num_tiles_per_row * num_pixels_per_tile uint32_t pixels_per_row_of_tiles; // pixels_per_row_of_tiles * num_tile_rows uint32_t pixels_per_slice; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning int32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; int32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { for (uint32_t pixel_y = 0, pixel_y_bits = 0; pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = 0, pixel_x_bits = 0; pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y; uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x; // don't copy pixels outside src rectangle region if (src_y < y || src_y >= y + height) continue; if (src_x < x || src_x >= x + width) continue; uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_row_of_tiles; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { }<commit_msg>allocate per-tile commands<commit_after>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> // Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4. // Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block. // Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile. #define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128 #define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16 #define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4 // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselves are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS) // If there are too many commands and this buffer gets filled up, // then the command buffer for that tile must be flushed. #define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128 typedef struct tile_cmdbuf_t { // start and past-the-end of the allocation for the buffer uint32_t* cmdbuf_start; uint32_t* cmdbuf_end; // the next location where to read and write commands uint32_t* cmdbuf_read; uint32_t* cmdbuf_write; } tile_cmdbuf_t; typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t* tile_cmdpool; tile_cmdbuf_t* tile_cmdbufs; uint32_t width_in_pixels; uint32_t height_in_pixels; // num_tiles_per_row * num_pixels_per_tile uint32_t pixels_per_row_of_tiles; // pixels_per_row_of_tiles * num_tile_rows uint32_t pixels_per_slice; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t width_in_tiles = padded_width_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t height_in_tiles = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t total_num_tiles = width_in_tiles * height_in_tiles; fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t)); assert(fb->tile_cmdpool); fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t)); assert(fb->tile_cmdbufs); for (uint32_t i = 0; i < total_num_tiles; i++) { fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS]; fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS; fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start; fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start; } return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->tile_cmdbufs); free(fb->tile_cmdpool); free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { for (uint32_t pixel_y = 0, pixel_y_bits = 0; pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = 0, pixel_x_bits = 0; pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y; uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x; // don't copy pixels outside src rectangle region if (src_y < y || src_y >= y + height) continue; if (src_x < x || src_x >= x + width) continue; uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_row_of_tiles; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { }<|endoftext|>
<commit_before>/* * Copyright (c) [2004-2015] Novell, Inc. * Copyright (c) 2016 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/RegionImpl.h" namespace storage { InvalidBlockSize::InvalidBlockSize(unsigned int block_size) : Exception(sformat("invalid block size %d", block_size), LogLevel::ERROR) { } DifferentBlockSizes::DifferentBlockSizes(unsigned int seen, unsigned int expected) : Exception(sformat("different block sizes, seen: %d, exception: %d", seen, expected), LogLevel::ERROR) { } NoIntersection::NoIntersection() : Exception("no intersection", LogLevel::WARNING) { } NotInside::NotInside() : Exception("not inside", LogLevel::WARNING) { } Region::Region() : impl(new Impl()) { } Region::Region(unsigned long long start, unsigned long long len, unsigned int block_size) : impl(new Impl(start, len, block_size)) { } Region::Region(const Region& region) : impl(new Impl(region.get_impl())) { } Region::~Region() { } Region& Region::operator=(const Region& region) { *impl = region.get_impl(); return *this; } Region::Impl& Region::get_impl() { return *impl; } const Region::Impl& Region::get_impl() const { return *impl; } bool Region::empty() const { return get_impl().empty(); } unsigned long long Region::get_start() const { return get_impl().get_start(); } unsigned long long Region::get_length() const { return get_impl().get_length(); } unsigned long long Region::get_end() const { return get_impl().get_end(); } void Region::set_start(unsigned long long start) { get_impl().set_start(start); } void Region::set_length(unsigned long long length) { get_impl().set_length(length); } void Region::adjust_start(long long delta) { get_impl().adjust_start(delta); } void Region::adjust_length(long long delta) { get_impl().adjust_length(delta); } unsigned int Region::get_block_size() const { return get_impl().get_block_size(); } void Region::set_block_size(unsigned int block_size) { get_impl().set_block_size(block_size); } unsigned long long Region::to_bytes(unsigned long long blocks) const { return get_impl().to_bytes(blocks); } unsigned long long Region::to_blocks(unsigned long long bytes) const { return get_impl().to_blocks(bytes); } bool Region::operator==(const Region& rhs) const { return get_impl().operator==(rhs.get_impl()); } bool Region::operator!=(const Region& rhs) const { return get_impl().operator!=(rhs.get_impl()); } bool Region::operator<(const Region& rhs) const { return get_impl().operator<(rhs.get_impl()); } bool Region::operator>(const Region& rhs) const { return get_impl().operator>(rhs.get_impl()); } bool Region::operator<=(const Region& rhs) const { return get_impl().operator<=(rhs.get_impl()); } bool Region::operator>=(const Region& rhs) const { return get_impl().operator>=(rhs.get_impl()); } bool Region::inside(const Region& rhs) const { return get_impl().inside(rhs.get_impl()); } bool Region::intersect(const Region& rhs) const { return get_impl().intersect(rhs.get_impl()); } Region Region::intersection(const Region& rhs) const { return get_impl().intersection(rhs.get_impl()); } vector<Region> Region::unused_regions(const vector<Region>& used_regions) const { return get_impl().unused_regions(used_regions); } std::ostream& operator<<(std::ostream& s, const Region& region) { return operator<<(s, region.get_impl()); } bool getChildValue(const xmlNode* node, const char* name, Region& value) { return getChildValue(node, name, value.get_impl()); } void setChildValue(xmlNode* node, const char* name, const Region& value) { setChildValue(node, name, value.get_impl()); } } <commit_msg>- fixed typo<commit_after>/* * Copyright (c) [2004-2015] Novell, Inc. * Copyright (c) 2016 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/RegionImpl.h" namespace storage { InvalidBlockSize::InvalidBlockSize(unsigned int block_size) : Exception(sformat("invalid block size %d", block_size), LogLevel::ERROR) { } DifferentBlockSizes::DifferentBlockSizes(unsigned int seen, unsigned int expected) : Exception(sformat("different block sizes, seen: %d, expected: %d", seen, expected), LogLevel::ERROR) { } NoIntersection::NoIntersection() : Exception("no intersection", LogLevel::WARNING) { } NotInside::NotInside() : Exception("not inside", LogLevel::WARNING) { } Region::Region() : impl(new Impl()) { } Region::Region(unsigned long long start, unsigned long long len, unsigned int block_size) : impl(new Impl(start, len, block_size)) { } Region::Region(const Region& region) : impl(new Impl(region.get_impl())) { } Region::~Region() { } Region& Region::operator=(const Region& region) { *impl = region.get_impl(); return *this; } Region::Impl& Region::get_impl() { return *impl; } const Region::Impl& Region::get_impl() const { return *impl; } bool Region::empty() const { return get_impl().empty(); } unsigned long long Region::get_start() const { return get_impl().get_start(); } unsigned long long Region::get_length() const { return get_impl().get_length(); } unsigned long long Region::get_end() const { return get_impl().get_end(); } void Region::set_start(unsigned long long start) { get_impl().set_start(start); } void Region::set_length(unsigned long long length) { get_impl().set_length(length); } void Region::adjust_start(long long delta) { get_impl().adjust_start(delta); } void Region::adjust_length(long long delta) { get_impl().adjust_length(delta); } unsigned int Region::get_block_size() const { return get_impl().get_block_size(); } void Region::set_block_size(unsigned int block_size) { get_impl().set_block_size(block_size); } unsigned long long Region::to_bytes(unsigned long long blocks) const { return get_impl().to_bytes(blocks); } unsigned long long Region::to_blocks(unsigned long long bytes) const { return get_impl().to_blocks(bytes); } bool Region::operator==(const Region& rhs) const { return get_impl().operator==(rhs.get_impl()); } bool Region::operator!=(const Region& rhs) const { return get_impl().operator!=(rhs.get_impl()); } bool Region::operator<(const Region& rhs) const { return get_impl().operator<(rhs.get_impl()); } bool Region::operator>(const Region& rhs) const { return get_impl().operator>(rhs.get_impl()); } bool Region::operator<=(const Region& rhs) const { return get_impl().operator<=(rhs.get_impl()); } bool Region::operator>=(const Region& rhs) const { return get_impl().operator>=(rhs.get_impl()); } bool Region::inside(const Region& rhs) const { return get_impl().inside(rhs.get_impl()); } bool Region::intersect(const Region& rhs) const { return get_impl().intersect(rhs.get_impl()); } Region Region::intersection(const Region& rhs) const { return get_impl().intersection(rhs.get_impl()); } vector<Region> Region::unused_regions(const vector<Region>& used_regions) const { return get_impl().unused_regions(used_regions); } std::ostream& operator<<(std::ostream& s, const Region& region) { return operator<<(s, region.get_impl()); } bool getChildValue(const xmlNode* node, const char* name, Region& value) { return getChildValue(node, name, value.get_impl()); } void setChildValue(xmlNode* node, const char* name, const Region& value) { setChildValue(node, name, value.get_impl()); } } <|endoftext|>
<commit_before>#include "graphs.h" int main() { int maxOrder = 20; vector< graph > linearGraphs; int currentIndex = 0; for( int currentOrder = 1; currentOrder <= maxOrder; currentOrder++) { currentIndex++; linearGraphs.resize(currentIndex); linearGraphs[currentIndex - 1].NumberSites = currentOrder; linearGraphs[currentIndex - 1].NumberBonds = currentOrder - 1; linearGraphs[currentIndex - 1].AdjacencyList.resize(currentOrder - 1); if (currentOrder > 1) { for ( int currentSite = 0; currentSite < currentOrder - 1; currentSite++) { linearGraphs.at(currentIndex - 1).AdjacencyList.at(currentSite) = make_pair(currentSite, currentSite + 1); } } linearGraphs[currentIndex - 1].Identifier = currentOrder - 1; for ( int currentGraph = 0; currentGraph < currentOrder; currentGraph++) { linearGraphs[currentIndex - 1].SubgraphList.push_back(currentGraph); } } const std::string filename ("lineargraphs.dat"); WriteGraphsToFile( linearGraphs, filename); } void WriteGraphsToFile( vector< graph > & graphList, const std::string file) { ofstream output(file.c_str()); for( unsigned int currentGraph = 0; currentGraph < graphList.size(); currentGraph++) { output<<graphList[currentGraph].Identifier<<endl; output<<graphList[currentGraph].NumberSites<<endl; output<<graphList[currentGraph].NumberBonds<<endl; output<<graphList[currentGraph].LatticeConstant<<endl; for (unsigned int currentBond = 0; currentBond < graphList[currentGraph].AdjacencyList.size(); currentBond++) { output<<"("<<graphList[currentGraph].AdjacencyList[currentBond].first<<","<<graphList[currentGraph].AdjacencyList[currentBond].second<<")"; } output<<endl; for (unsigned int currentSubgraph = 0; currentSubgraph < graphList[currentGraph].SubgraphList.size(); currentSubgraph++) { output<<"("<<graphList[currentGraph].SubgraphList[currentSubgraph]<<")"; } output<<endl; } } void ReadGraphsFromFile( vector< graph > & graphList, string & file) { ifstream input(file.c_str()); vector< string > rawLines; int currentGraph; const int memberCount = 6; while ( !input.eof() ) { rawLines.resize(rawLines.size() + 1); getline(input, rawLines.back()) ; } input.close(); for (unsigned int currentLine = 0; currentLine < rawLines.size(); currentLine++) { currentGraph = currentLine/memberCount; graph tempGraph; unsigned int currentChar = 0; string currentNumber; switch ( currentLine % memberCount ) { case 0 : tempGraph.Identifier = atoi(rawLines.at(currentLine).c_str()); case 1 : tempGraph.NumberSites = atoi(rawLines.at(currentLine).c_str()); break; case 2 : tempGraph.NumberBonds = atoi(rawLines.at(currentLine).c_str()); break; case 3 : tempGraph.LatticeConstant = atoi(rawLines.at(currentLine).c_str()); break; case 4 : while ( currentChar < rawLines.at(currentLine).length() ) { if ( rawLines.at(currentLine)[currentChar] == '(' ) { tempGraph.AdjacencyList.resize( tempGraph.AdjacencyList.size() + 1); } if ( rawLines.at(currentLine)[currentChar] != '(' && rawLines.at(currentLine)[currentChar] != ')' && rawLines.at(currentLine)[currentChar] != ',' && rawLines.at(currentLine)[currentChar] != '\n' ) { currentNumber.push_back(rawLines.at(currentLine)[currentChar]); } if ( rawLines.at(currentLine)[currentChar] == ',' ) { tempGraph.AdjacencyList.back().first = atoi(currentNumber.c_str()); currentNumber.clear(); } if ( rawLines.at(currentLine)[currentChar] == ')' ) { tempGraph.AdjacencyList.back().second = atoi(currentNumber.c_str()); currentNumber.clear(); } } break; case 5 : while ( currentChar < rawLines.at(currentLine).length() ) { if ( rawLines.at(currentLine)[currentChar] == '(' ) { tempGraph.SubgraphList.resize( tempGraph.SubgraphList.size() + 1); } if ( rawLines.at(currentLine)[currentChar] != '(' && rawLines.at(currentLine)[currentChar] != ')' && rawLines.at(currentLine)[currentChar] != '\n' ) { currentNumber.push_back(rawLines.at(currentLine)[currentChar]); } if ( rawLines.at(currentLine)[currentChar] == ')' ) { tempGraph.SubgraphList.back() = atoi(currentNumber.c_str()); currentNumber.clear(); } } break; } graphList.push_back(tempGraph); } } /* std::string getFileContents(const std::string& filename) { std::ifstream file(filename.c_str()); return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); } */ <commit_msg>first 4 graph params printed on same line now<commit_after>#include "graphs.h" int main() { int maxOrder = 20; vector< graph > linearGraphs; int currentIndex = 0; for( int currentOrder = 1; currentOrder <= maxOrder; currentOrder++) { currentIndex++; linearGraphs.resize(currentIndex); linearGraphs[currentIndex - 1].NumberSites = currentOrder; linearGraphs[currentIndex - 1].NumberBonds = currentOrder - 1; linearGraphs[currentIndex - 1].AdjacencyList.resize(currentOrder - 1); if (currentOrder > 1) { for ( int currentSite = 0; currentSite < currentOrder - 1; currentSite++) { linearGraphs.at(currentIndex - 1).AdjacencyList.at(currentSite) = make_pair(currentSite, currentSite + 1); } } linearGraphs[currentIndex - 1].Identifier = currentOrder - 1; for ( int currentGraph = 0; currentGraph < currentOrder; currentGraph++) { linearGraphs[currentIndex - 1].SubgraphList.push_back(currentGraph); } } const std::string filename ("lineargraphs.dat"); WriteGraphsToFile( linearGraphs, filename); } void WriteGraphsToFile( vector< graph > & graphList, const std::string file) { ofstream output(file.c_str()); for( unsigned int currentGraph = 0; currentGraph < graphList.size(); currentGraph++) { output<<graphList[currentGraph].Identifier<<" "; output<<graphList[currentGraph].NumberSites<<" "; output<<graphList[currentGraph].NumberBonds<<" "; output<<graphList[currentGraph].LatticeConstant<<endl; for (unsigned int currentBond = 0; currentBond < graphList[currentGraph].AdjacencyList.size(); currentBond++) { output<<"("<<graphList[currentGraph].AdjacencyList[currentBond].first<<","<<graphList[currentGraph].AdjacencyList[currentBond].second<<")"; } output<<endl; for (unsigned int currentSubgraph = 0; currentSubgraph < graphList[currentGraph].SubgraphList.size(); currentSubgraph++) { output<<"("<<graphList[currentGraph].SubgraphList[currentSubgraph]<<")"; } output<<endl; } } void ReadGraphsFromFile( vector< graph > & graphList, string & file) { ifstream input(file.c_str()); vector< string > rawLines; int currentGraph; const int memberCount = 6; while ( !input.eof() ) { rawLines.resize(rawLines.size() + 1); getline(input, rawLines.back()) ; } input.close(); for (unsigned int currentLine = 0; currentLine < rawLines.size(); currentLine++) { currentGraph = currentLine/memberCount; graph tempGraph; unsigned int currentChar = 0; string currentNumber; switch ( currentLine % memberCount ) { case 0 : tempGraph.Identifier = atoi(rawLines.at(currentLine).c_str()); case 1 : tempGraph.NumberSites = atoi(rawLines.at(currentLine).c_str()); break; case 2 : tempGraph.NumberBonds = atoi(rawLines.at(currentLine).c_str()); break; case 3 : tempGraph.LatticeConstant = atoi(rawLines.at(currentLine).c_str()); break; case 4 : while ( currentChar < rawLines.at(currentLine).length() ) { if ( rawLines.at(currentLine)[currentChar] == '(' ) { tempGraph.AdjacencyList.resize( tempGraph.AdjacencyList.size() + 1); } if ( rawLines.at(currentLine)[currentChar] != '(' && rawLines.at(currentLine)[currentChar] != ')' && rawLines.at(currentLine)[currentChar] != ',' && rawLines.at(currentLine)[currentChar] != '\n' ) { currentNumber.push_back(rawLines.at(currentLine)[currentChar]); } if ( rawLines.at(currentLine)[currentChar] == ',' ) { tempGraph.AdjacencyList.back().first = atoi(currentNumber.c_str()); currentNumber.clear(); } if ( rawLines.at(currentLine)[currentChar] == ')' ) { tempGraph.AdjacencyList.back().second = atoi(currentNumber.c_str()); currentNumber.clear(); } } break; case 5 : while ( currentChar < rawLines.at(currentLine).length() ) { if ( rawLines.at(currentLine)[currentChar] == '(' ) { tempGraph.SubgraphList.resize( tempGraph.SubgraphList.size() + 1); } if ( rawLines.at(currentLine)[currentChar] != '(' && rawLines.at(currentLine)[currentChar] != ')' && rawLines.at(currentLine)[currentChar] != '\n' ) { currentNumber.push_back(rawLines.at(currentLine)[currentChar]); } if ( rawLines.at(currentLine)[currentChar] == ')' ) { tempGraph.SubgraphList.back() = atoi(currentNumber.c_str()); currentNumber.clear(); } } break; } graphList.push_back(tempGraph); } } /* std::string getFileContents(const std::string& filename) { std::ifstream file(filename.c_str()); return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); } */ <|endoftext|>
<commit_before>#ifndef PORTS_H #define PORTS_H #include<vector> #include<boost/scoped_ptr.hpp> #include<boost/shared_ptr.hpp> #include<string> /*abstract class*/ class AsyncPort{ public: // returns true if input is available on the port virtual bool input_available(void) const =0; // size of vector denotes desired number of characters // (call vector::resize() before calling this function) // upon return, vector now contains the actual read // number of bytes virtual void input(std::vector<unsigned char>&) =0; virtual bool output_available(void) const =0; virtual void output(std::vector<unsigned char> const&) =0; virtual bool is_input(void) const =0; virtual bool is_output(void) const =0; virtual ~AsyncPort(){}; }; boost::shared_ptr<AsyncPort> AsyncSTDIN(void); boost::shared_ptr<AsyncPort> AsyncSTDOUT(void); boost::shared_ptr<AsyncPort> AsyncSTDERR(void); #define DECLARE_ASYNC_PORT(T)\ virtual bool input_available(void) const;\ virtual void input(std::vector<unsigned char>&);\ virtual bool output_available(void) const;\ virtual void output(std::vector<unsigned char> const&);\ virtual bool is_input(void) const;\ virtual bool is_output(void) const;\ virtual ~T();\ friend boost::shared_ptr<AsyncPort> AsyncSTDIN(void);\ friend boost::shared_ptr<AsyncPort> AsyncSTDOUT(void);\ friend boost::shared_ptr<AsyncPort> AsyncSTDERR(void); /*include above as friends, we can't be too sure that those functions might, in some random implementation, actually construct a derived concrete class. */ /*---------------------------------------------------------concrete classes*/ class InputFileImplementation; class InputFilePort : public AsyncPort{ private: //Pointer to implementation boost::scoped_ptr<InputFileImplementation> p; InputFilePort(); public: DECLARE_ASYNC_PORT(InputFilePort) explicit InputFilePort(std::string const&); }; class OutputFileImplementation; class OutputFilePort : public AsyncPort{ private: //Pointer to implementation boost::scoped_ptr<OutputFileImplementation> p; OutputFilePort(); public: DECLARE_ASYNC_PORT(OutputFilePort) explicit OutputFilePort(std::string const&); }; /*question: can we do terminal-based i/o that way or no?*/ /*-------------------------------------------sets of AsyncPorts for waiting*/ class AsyncPortSetImplementation; class AsyncPortSet{ private: boost::scoped_ptr<AsyncPortSetImplementation> p; public: void add(boost::shared_ptr<AsyncPort>); void remove(boost::shared_ptr<AsyncPort>); //nonblocking // returns all asynchronous ports that have data // waiting. those ports are automatically removed // from this set. std::vector<boost::shared_ptr<AsyncPort> > check(void); //blocking (if we detect that we're the only running //process) std::vector<boost::shared_ptr<AsyncPort> > wait(void); }; #endif //PORTS_H <commit_msg>ports: Changed output() function<commit_after>#ifndef PORTS_H #define PORTS_H #include<vector> #include<boost/scoped_ptr.hpp> #include<boost/shared_ptr.hpp> #include<string> /*abstract class*/ class AsyncPort{ public: // returns true if input is available on the port virtual bool input_available(void) const =0; // size of vector denotes desired number of characters // (call vector::resize() before calling this function) // upon return, vector now contains the actual read // number of bytes virtual void input(std::vector<unsigned char>&) =0; virtual bool output_available(void) const =0; virtual size_t output(std::vector<unsigned char> const&, size_t off=0) =0; virtual bool is_input(void) const =0; virtual bool is_output(void) const =0; virtual ~AsyncPort(){}; }; boost::shared_ptr<AsyncPort> AsyncSTDIN(void); boost::shared_ptr<AsyncPort> AsyncSTDOUT(void); boost::shared_ptr<AsyncPort> AsyncSTDERR(void); #define DECLARE_ASYNC_PORT(T)\ virtual bool input_available(void) const;\ virtual void input(std::vector<unsigned char>&);\ virtual bool output_available(void) const;\ virtual size_t output(std::vector<unsigned char> const&, size_t off=0 );\ virtual bool is_input(void) const;\ virtual bool is_output(void) const;\ virtual ~T();\ friend boost::shared_ptr<AsyncPort> AsyncSTDIN(void);\ friend boost::shared_ptr<AsyncPort> AsyncSTDOUT(void);\ friend boost::shared_ptr<AsyncPort> AsyncSTDERR(void); /*include above as friends, we can't be too sure that those functions might, in some random implementation, actually construct a derived concrete class. */ /*---------------------------------------------------------concrete classes*/ class InputFileImplementation; class InputFilePort : public AsyncPort{ private: //Pointer to implementation boost::scoped_ptr<InputFileImplementation> p; InputFilePort(); public: DECLARE_ASYNC_PORT(InputFilePort) explicit InputFilePort(std::string const&); }; class OutputFileImplementation; class OutputFilePort : public AsyncPort{ private: //Pointer to implementation boost::scoped_ptr<OutputFileImplementation> p; OutputFilePort(); public: DECLARE_ASYNC_PORT(OutputFilePort) explicit OutputFilePort(std::string const&); }; /*question: can we do terminal-based i/o that way or no?*/ /*-------------------------------------------sets of AsyncPorts for waiting*/ class AsyncPortSetImplementation; class AsyncPortSet{ private: boost::scoped_ptr<AsyncPortSetImplementation> p; public: void add(boost::shared_ptr<AsyncPort>); void remove(boost::shared_ptr<AsyncPort>); //nonblocking // returns all asynchronous ports that have data // waiting. those ports are automatically removed // from this set. std::vector<boost::shared_ptr<AsyncPort> > check(void); //blocking (if we detect that we're the only running //process) std::vector<boost::shared_ptr<AsyncPort> > wait(void); }; #endif //PORTS_H <|endoftext|>
<commit_before>#ifndef C3__FRAMEWORK__HH #define C3__FRAMEWORK__HH #include "C3_Exception.hh" #include "C3_Column.hh" #include "C3_Image.hh" #include "C3_Row.hh" #include "C3_Stack.hh" #include "C3_View.hh" #include "C3_Operator.hh" #include "C3_Reduce.hh" #endif <commit_msg>Added environment.<commit_after>#ifndef C3__FRAMEWORK__HH #define C3__FRAMEWORK__HH #include "C3_Environment.hh" #include "C3_Exception.hh" #include "C3_Column.hh" #include "C3_Image.hh" #include "C3_Row.hh" #include "C3_Stack.hh" #include "C3_View.hh" #include "C3_Operator.hh" #include "C3_Reduce.hh" #endif <|endoftext|>
<commit_before>#include "devicethread.h" #include "usb_commands.h" DeviceThread::DeviceThread() { exit = false; } void DeviceThread::finish() { exit = true; } void DeviceThread::run() { int ret; while(!exit) { if(!board.isConnected()) { ret = board.attachDevice(); if(ret < 0) { //Failed to attach wait(3000); notConnected(); continue; } else connected(); } //Connected, do actual work in this thread... //Update status getBacklightState(); //Process command queue while(!cmd.isEmpty()) { Command_t c = cmd.dequeue(); if(!IS_GET(c.cmd)) board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3); else { uint8_t buf[EP_LEN]; board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3, buf); if(buf[0] == CMD_RESP && buf[1] == CMD_BL_GET_STATE) emit(backlightResponse(buf[2], buf[3])); } } //Wait for some time period. Number chosen at random as prime. wait(635); } } void DeviceThread::enqueue(const Command_t & c) { cmd.enqueue(c); } void DeviceThread::getBacklightState() { Command_t c; c.cmd = CMD_BL_GET_STATE; cmd.enqueue(c); } <commit_msg>Use sleep and emit<commit_after>#include "devicethread.h" #include "usb_commands.h" DeviceThread::DeviceThread() { exit = false; } void DeviceThread::finish() { exit = true; } void DeviceThread::run() { int ret; while(!exit) { if(!board.isConnected()) { ret = board.attachDevice(); if(ret < 0) { //Failed to attach sleep(3000); emit notConnected(); continue; } else emit connected(); } //Connected, do actual work in this thread... //Update status getBacklightState(); //Process command queue while(!cmd.isEmpty()) { Command_t c = cmd.dequeue(); if(!IS_GET(c.cmd)) board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3); else { uint8_t buf[EP_LEN]; board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3, buf); if(buf[0] == CMD_RESP && buf[1] == CMD_BL_GET_STATE) emit(backlightResponse(buf[2], buf[3])); } } //Wait for some time period. Number chosen at random as prime. sleep(635); } } void DeviceThread::enqueue(const Command_t & c) { cmd.enqueue(c); } void DeviceThread::getBacklightState() { Command_t c; c.cmd = CMD_BL_GET_STATE; cmd.enqueue(c); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "apps/seawreck/http_response_parser.hh" #include "core/print.hh" #include "core/reactor.hh" #include "core/app-template.hh" #include "core/future-util.hh" #include "core/distributed.hh" #include "core/semaphore.hh" #include "core/future-util.hh" #include <chrono> template <typename... Args> void http_debug(const char* fmt, Args&&... args) { #if HTTP_DEBUG print(fmt, std::forward<Args>(args)...); #endif } class http_client { private: unsigned _duration; unsigned _conn_per_core; unsigned _reqs_per_conn; std::vector<connected_socket> _sockets; semaphore _conn_connected{0}; semaphore _conn_finished{0}; timer<> _run_timer; bool _timer_based; bool _timer_done{false}; uint64_t _total_reqs{0}; public: http_client(unsigned duration, unsigned total_conn, unsigned reqs_per_conn) : _duration(duration) , _conn_per_core(total_conn / smp::count) , _reqs_per_conn(reqs_per_conn) , _run_timer([this] { _timer_done = true; }) , _timer_based(reqs_per_conn == 0) { } class connection { private: connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; http_response_parser _parser; http_client* _http_client; uint64_t _nr_done{0}; public: connection(connected_socket&& fd, http_client* client) : _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _http_client(client){ } uint64_t nr_done() { return _nr_done; } future<> do_req() { return _write_buf.write("GET / HTTP/1.1\r\nHost: 127.0.0.1:10000\r\n\r\n").then([this] { return _write_buf.flush(); }).then([this] { _parser.init(); return _read_buf.consume(_parser).then([this] { // Read HTTP response header first if (_parser.eof()) { return make_ready_future<>(); } auto _rsp = _parser.get_parsed_response(); auto it = _rsp->_headers.find("Content-Length"); if (it == _rsp->_headers.end()) { print("Error: HTTP response does not contain: Content-Length\n"); return make_ready_future<>(); } auto content_len = std::stoi(it->second); http_debug("Content-Length = %d\n", content_len); // Read HTTP response body return _read_buf.read_exactly(content_len).then([this] (temporary_buffer<char> buf) { _nr_done++; http_debug("%s\n", buf.get()); if (_http_client->done(_nr_done)) { return make_ready_future(); } else { return do_req(); } }); }); }); } }; future<uint64_t> total_reqs() { print("Requests on cpu %2d: %ld\n", engine().cpu_id(), _total_reqs); return make_ready_future<uint64_t>(_total_reqs); } bool done(uint64_t nr_done) { if (_timer_based) { return _timer_done; } else { return nr_done >= _reqs_per_conn; } } future<> connect(ipv4_addr server_addr) { // Establish all the TCP connections first for (unsigned i = 0; i < _conn_per_core; i++) { engine().net().connect(make_ipv4_address(server_addr)).then([this] (connected_socket fd) { _sockets.push_back(std::move(fd)); http_debug("Established connection %6d on cpu %3d\n", _conn_connected.current(), engine().cpu_id()); _conn_connected.signal(); }); } return _conn_connected.wait(_conn_per_core); } future<> run() { // All connected, start HTTP request http_debug("Established all %6d tcp connections on cpu %3d\n", _conn_per_core, engine().cpu_id()); if (_timer_based) { _run_timer.arm(std::chrono::seconds(_duration)); } for (auto&& fd : _sockets) { auto conn = new connection(std::move(fd), this); conn->do_req().rescue([this, conn] (auto get_ex) { http_debug("Finished connection %6d on cpu %3d\n", _conn_finished.current(), engine().cpu_id()); _total_reqs += conn->nr_done(); _conn_finished.signal(); delete conn; try { get_ex(); } catch (std::exception& ex) { print("http request error: %s\n", ex.what()); } }); } // All finished return _conn_finished.wait(_conn_per_core); } future<> stop() { return make_ready_future(); } }; namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("server,s", bpo::value<std::string>()->default_value("192.168.66.100:10000"), "Server address") ("conn,c", bpo::value<unsigned>()->default_value(100), "total connections") ("reqs,r", bpo::value<unsigned>()->default_value(0), "reqs per connection") ("duration,d", bpo::value<unsigned>()->default_value(10), "duration of the test in seconds)"); return app.run(ac, av, [&app] { auto& config = app.configuration(); auto server = config["server"].as<std::string>(); auto reqs_per_conn = config["reqs"].as<unsigned>(); auto total_conn= config["conn"].as<unsigned>(); auto duration = config["duration"].as<unsigned>(); if (total_conn % smp::count != 0) { print("Error: conn needs to be n * cpu_nr\n"); return engine().exit(0); } auto http_clients = new distributed<http_client>; // Start http requests on all the cores auto started = std::chrono::high_resolution_clock::now(); print("========== http_client ============\n"); print("Server: %s\n", server); print("Connections: %u\n", total_conn); print("Requests/connection: %s\n", reqs_per_conn == 0 ? "dynamic (timer based)" : std::to_string(reqs_per_conn)); http_clients->start(std::ref(duration), std::ref(total_conn), std::ref(reqs_per_conn)).then([http_clients, started, server] { return http_clients->invoke_on_all(&http_client::connect, ipv4_addr{server}); }).then([http_clients] { return http_clients->invoke_on_all(&http_client::run); }).then([http_clients] { return http_clients->map_reduce(adder<uint64_t>(), &http_client::total_reqs); }).then([http_clients, started] (auto total_reqs) { // All the http requests are finished auto finished = std::chrono::high_resolution_clock::now(); auto elapsed = finished - started; auto secs = static_cast<double>(elapsed.count() / 1000000000.0); print("Total cpus: %u\n", smp::count); print("Total requests: %u\n", total_reqs); print("Total time: %f\n", secs); print("Requests/sec: %f\n", static_cast<double>(total_reqs) / secs); print("========== done ============\n"); http_clients->stop().then([http_clients] { // FIXME: If we call engine().exit(0) here to exit when // requests are done. The tcp connection will not be closed // properly, becasue we exit too earily and the FIN packets are // not exchanged. delete http_clients; engine().exit(0); }); }); }); } <commit_msg>seawreck: abort on a connection error<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "apps/seawreck/http_response_parser.hh" #include "core/print.hh" #include "core/reactor.hh" #include "core/app-template.hh" #include "core/future-util.hh" #include "core/distributed.hh" #include "core/semaphore.hh" #include "core/future-util.hh" #include <chrono> template <typename... Args> void http_debug(const char* fmt, Args&&... args) { #if HTTP_DEBUG print(fmt, std::forward<Args>(args)...); #endif } class http_client { private: unsigned _duration; unsigned _conn_per_core; unsigned _reqs_per_conn; std::vector<connected_socket> _sockets; semaphore _conn_connected{0}; semaphore _conn_finished{0}; timer<> _run_timer; bool _timer_based; bool _timer_done{false}; uint64_t _total_reqs{0}; public: http_client(unsigned duration, unsigned total_conn, unsigned reqs_per_conn) : _duration(duration) , _conn_per_core(total_conn / smp::count) , _reqs_per_conn(reqs_per_conn) , _run_timer([this] { _timer_done = true; }) , _timer_based(reqs_per_conn == 0) { } class connection { private: connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; http_response_parser _parser; http_client* _http_client; uint64_t _nr_done{0}; public: connection(connected_socket&& fd, http_client* client) : _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) , _http_client(client){ } uint64_t nr_done() { return _nr_done; } future<> do_req() { return _write_buf.write("GET / HTTP/1.1\r\nHost: 127.0.0.1:10000\r\n\r\n").then([this] { return _write_buf.flush(); }).then([this] { _parser.init(); return _read_buf.consume(_parser).then([this] { // Read HTTP response header first if (_parser.eof()) { return make_ready_future<>(); } auto _rsp = _parser.get_parsed_response(); auto it = _rsp->_headers.find("Content-Length"); if (it == _rsp->_headers.end()) { print("Error: HTTP response does not contain: Content-Length\n"); return make_ready_future<>(); } auto content_len = std::stoi(it->second); http_debug("Content-Length = %d\n", content_len); // Read HTTP response body return _read_buf.read_exactly(content_len).then([this] (temporary_buffer<char> buf) { _nr_done++; http_debug("%s\n", buf.get()); if (_http_client->done(_nr_done)) { return make_ready_future(); } else { return do_req(); } }); }); }); } }; future<uint64_t> total_reqs() { print("Requests on cpu %2d: %ld\n", engine().cpu_id(), _total_reqs); return make_ready_future<uint64_t>(_total_reqs); } bool done(uint64_t nr_done) { if (_timer_based) { return _timer_done; } else { return nr_done >= _reqs_per_conn; } } future<> connect(ipv4_addr server_addr) { // Establish all the TCP connections first for (unsigned i = 0; i < _conn_per_core; i++) { engine().net().connect(make_ipv4_address(server_addr)).then([this] (connected_socket fd) { _sockets.push_back(std::move(fd)); http_debug("Established connection %6d on cpu %3d\n", _conn_connected.current(), engine().cpu_id()); _conn_connected.signal(); }).or_terminate(); } return _conn_connected.wait(_conn_per_core); } future<> run() { // All connected, start HTTP request http_debug("Established all %6d tcp connections on cpu %3d\n", _conn_per_core, engine().cpu_id()); if (_timer_based) { _run_timer.arm(std::chrono::seconds(_duration)); } for (auto&& fd : _sockets) { auto conn = new connection(std::move(fd), this); conn->do_req().rescue([this, conn] (auto get_ex) { http_debug("Finished connection %6d on cpu %3d\n", _conn_finished.current(), engine().cpu_id()); _total_reqs += conn->nr_done(); _conn_finished.signal(); delete conn; try { get_ex(); } catch (std::exception& ex) { print("http request error: %s\n", ex.what()); } }); } // All finished return _conn_finished.wait(_conn_per_core); } future<> stop() { return make_ready_future(); } }; namespace bpo = boost::program_options; int main(int ac, char** av) { app_template app; app.add_options() ("server,s", bpo::value<std::string>()->default_value("192.168.66.100:10000"), "Server address") ("conn,c", bpo::value<unsigned>()->default_value(100), "total connections") ("reqs,r", bpo::value<unsigned>()->default_value(0), "reqs per connection") ("duration,d", bpo::value<unsigned>()->default_value(10), "duration of the test in seconds)"); return app.run(ac, av, [&app] { auto& config = app.configuration(); auto server = config["server"].as<std::string>(); auto reqs_per_conn = config["reqs"].as<unsigned>(); auto total_conn= config["conn"].as<unsigned>(); auto duration = config["duration"].as<unsigned>(); if (total_conn % smp::count != 0) { print("Error: conn needs to be n * cpu_nr\n"); return engine().exit(0); } auto http_clients = new distributed<http_client>; // Start http requests on all the cores auto started = std::chrono::high_resolution_clock::now(); print("========== http_client ============\n"); print("Server: %s\n", server); print("Connections: %u\n", total_conn); print("Requests/connection: %s\n", reqs_per_conn == 0 ? "dynamic (timer based)" : std::to_string(reqs_per_conn)); http_clients->start(std::ref(duration), std::ref(total_conn), std::ref(reqs_per_conn)).then([http_clients, started, server] { return http_clients->invoke_on_all(&http_client::connect, ipv4_addr{server}); }).then([http_clients] { return http_clients->invoke_on_all(&http_client::run); }).then([http_clients] { return http_clients->map_reduce(adder<uint64_t>(), &http_client::total_reqs); }).then([http_clients, started] (auto total_reqs) { // All the http requests are finished auto finished = std::chrono::high_resolution_clock::now(); auto elapsed = finished - started; auto secs = static_cast<double>(elapsed.count() / 1000000000.0); print("Total cpus: %u\n", smp::count); print("Total requests: %u\n", total_reqs); print("Total time: %f\n", secs); print("Requests/sec: %f\n", static_cast<double>(total_reqs) / secs); print("========== done ============\n"); http_clients->stop().then([http_clients] { // FIXME: If we call engine().exit(0) here to exit when // requests are done. The tcp connection will not be closed // properly, becasue we exit too earily and the FIN packets are // not exchanged. delete http_clients; engine().exit(0); }); }); }); } <|endoftext|>
<commit_before>// include headers{{{ #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> /*}}}*/ # define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace std; int main() { return 0; } <commit_msg>Update template for c++<commit_after>#include <algorithm> #include <iostream> #include <istream> #include <iterator> #include <queue> #include <set> #include <stack> #include <string> #include <vector> using namespace std; int main() { return 0; } <|endoftext|>
<commit_before>// // Macros // #define Clr(m) memset(m, 0, sizeof(m)) #define Inf(m) memset(m, 0x3f, sizeof(m)) #define Neg(m) memset(m, -1, sizeof(m)) #define InfRange(p,n,t) memset(p, 0x3f, sizeof(t)*(n)) #define For(t,i,c) for(t::iterator i=(c).begin(); i != (c).end(); ++i) #define RFor(t,v,c) for(t::reverse_iterator i=(c).rbegin(); i!=(c).rend(); ++i) // // Fraction // template<typename T> struct Fraction { T p, q; Fraction() : p(0), q(1) {} Fraction(T P) : p(P), q(1) {} Fraction(T P, T Q) : p(P), q(Q) { simplify(); } void simplify() { T g = gcd(p, q); p /= g; q /= g; } Fraction operator+(const Fraction &f) const { return Fraction(p * f.q + q * f.p, q * f.q); } Fraction operator-(const Fraction &f) const { return Fraction(p * f.q - q * f.p, q * f.q); } Fraction operator*(const Fraction &f) const { return Fraction(p * f.p, q * f.q); } Fraction operator/(const Fraction &f) const { return Fraction(p * f.q, q * f.p); } Fraction operator%(int m) const { return Fraction(p % (m*q), q); } Fraction operator-() const { return Fraction(-p, q); } bool operator<(const Fraction &f) const { return p*f.q < q*f.p; } bool operator>(const Fraction &f) const { return p*f.q > q*f.p; } bool operator<=(const Fraction &f) const { return p*f.q <= q*f.p; } bool operator>=(const Fraction &f) const { return p*f.q >= q*f.p; } bool operator==(const Fraction &f) const { return p == f.p && q == f.q; } }; struct Mod2 { int v; Mod2() {} Mod2(int V) : v(V) {} bool operator!=(const Mod2 &x) const { return v != x.v; } Mod2 operator/(const Mod2 &x) const { return Mod2(v); } Mod2 operator*(const Mod2 &x) const { return Mod2(v & x.v); } Mod2 &operator-=(const Mod2 &x) { v ^= x.v; return *this; } }; // // IDA* // struct Board { // heuristics int h() { return 0; } bool is_solution() { return false; } // computes the next child bool next(Board &child, int &dist, int &delta) { return false; } // resets the loop to visit children void reset() { } }; typedef Board NodeT; typedef int DeltaT; // represents a state change, useful to track the path // Depth limited search bool ida_dls(NodeT &node, int depth, int g, int &nxt, stack<DeltaT> &st) { if (g == depth) return node.is_solution(); NodeT child; int dist; DeltaT delta; for (node.reset(); node.next(child, dist, delta);) { int f = g + dist + child.h(); if (f > depth && f < nxt) nxt = f; if (f <= depth && ida_dls(child, depth, g + 1, nxt, st)) { st.push(delta); return true; } } return false; } bool ida_star(NodeT &root, int limit, stack<DeltaT> &st) { for (int depth = root.h(); depth <= limit;) { int next_depth = INF; if (ida_dls(root, depth, 0, next_depth, st)) return true; if (next_depth == INF) return false; depth = next_depth; } return false; } // // Quickselect - for locating the median // struct Data { int v; // value int n; // occurrences int p; // original position of data, to break ties Data(int V, int N, int P) : v(V), n(N), p(P) {} bool operator<(const Data &x) const { if (v != x.v) return v < x.v; if (n != x.n) return n < x.n; return p < x.p; } }; typedef vector<Data> DV; typedef DV::iterator DVi; int select_kth(DVi lo, DVi hi, int k) { if (hi == lo + 1) return lo->v; swap(*(lo + (rand() % (hi - lo))), *(hi - 1)); Data piv = *(hi - 1); DVi x = lo; int lt = 0; for (DVi i = lo, I = hi - 1; i != I; ++i) if (*i < piv) { swap(*i, *x); lt += x->n, ++x; } swap(*x, *(hi - 1)); if (k < lt) return select_kth(lo, x, k); if (k >= lt + x->n) return select_kth(x + 1, hi, k - lt - x->n); return x->v; } // // Basic binary search // template <typename T> int binsearch(const T *a, int lo, int hi, T v) { while (lo < hi) { int mid = (lo + hi) / 2; if (a[mid] == v) return mid; if (a[mid] < v) lo = mid + 1; else hi = mid; } return -1; } template <typename T> int binsearch_upper(const T *a, int lo, int hi, T v) { while (lo < hi) { int mid = (lo + hi) / 2; if (a[mid] <= v) lo = mid + 1; else hi = mid; } return lo; } // // Merge sort - useful for adapting it to sorting-related problems // void merge(IVi lo, IVi hi, IVi mid) { IV x; for (IVi a = lo, b = mid; a < mid || b < hi; ) { if (a >= mid) { x.push_back(*b++); continue; } if (b >= hi) { x.push_back(*a++); continue; } if (*a < *b) { x.push_back(*a++); continue; } x.push_back(*b++); } for (IVi a = lo, b = x.begin(); a < hi; ++a, ++b) *a = *b; } void merge_sort(IVi lo, IVi hi) { if (hi <= lo + 1) return; IVi mid = lo + ((hi - lo) / 2); merge_sort(lo, mid); merge_sort(mid, hi); merge(lo, hi, mid); } // // Misc functions // // returns the position of the last visited in range [0, n-1] int josephus(int n, int k) { if (n == 1) return 0; return (josephus(n-1, k) + k) % n; } // // Stable Marriage Problem // // man[i][j]: woman with priority j for man i int man[MAXN][MAXN]; // woman[i][j]: priority for man j given by woman i int woman[MAXN][MAXN]; // next_for[i]: next priority to consider for man i int next_for[MAXN]; struct Marriage { int w, m; Marriage() {} Marriage(int W, int M): w(W), m(M) {} bool operator<(const Marriage &x) const { return woman[w][m] > woman[x.w][x.m]; } }; // marriage[j]: current marriage for woman j Marriage marriage[MAXN]; // Gale-Shapley algorithm. // pre-cond: Clr(next_for) Neg(marriage) void stable_match(int m) { // if a solution is not guaranteed, add check here to see if maybe there // are no more matches int w = man[m][ next_for[m]++ ]; Marriage cur(w, m); if (marriage[w].m < 0) marriage[w] = cur; else if (marriage[w] < cur) { int mp = marriage[w].m; marriage[w] = cur; stable_match(mp); } else stable_match(m); } <commit_msg>Added histogram area code<commit_after>// // Macros // #define Clr(m) memset(m, 0, sizeof(m)) #define Inf(m) memset(m, 0x3f, sizeof(m)) #define Neg(m) memset(m, -1, sizeof(m)) #define InfRange(p,n,t) memset(p, 0x3f, sizeof(t)*(n)) #define For(t,i,c) for(t::iterator i=(c).begin(); i != (c).end(); ++i) #define RFor(t,v,c) for(t::reverse_iterator i=(c).rbegin(); i!=(c).rend(); ++i) // // Fraction // template<typename T> struct Fraction { T p, q; Fraction() : p(0), q(1) {} Fraction(T P) : p(P), q(1) {} Fraction(T P, T Q) : p(P), q(Q) { simplify(); } void simplify() { T g = gcd(p, q); p /= g; q /= g; } Fraction operator+(const Fraction &f) const { return Fraction(p * f.q + q * f.p, q * f.q); } Fraction operator-(const Fraction &f) const { return Fraction(p * f.q - q * f.p, q * f.q); } Fraction operator*(const Fraction &f) const { return Fraction(p * f.p, q * f.q); } Fraction operator/(const Fraction &f) const { return Fraction(p * f.q, q * f.p); } Fraction operator%(int m) const { return Fraction(p % (m*q), q); } Fraction operator-() const { return Fraction(-p, q); } bool operator<(const Fraction &f) const { return p*f.q < q*f.p; } bool operator>(const Fraction &f) const { return p*f.q > q*f.p; } bool operator<=(const Fraction &f) const { return p*f.q <= q*f.p; } bool operator>=(const Fraction &f) const { return p*f.q >= q*f.p; } bool operator==(const Fraction &f) const { return p == f.p && q == f.q; } }; struct Mod2 { int v; Mod2() {} Mod2(int V) : v(V) {} bool operator!=(const Mod2 &x) const { return v != x.v; } Mod2 operator/(const Mod2 &x) const { return Mod2(v); } Mod2 operator*(const Mod2 &x) const { return Mod2(v & x.v); } Mod2 &operator-=(const Mod2 &x) { v ^= x.v; return *this; } }; // // IDA* // struct Board { // heuristics int h() { return 0; } bool is_solution() { return false; } // computes the next child bool next(Board &child, int &dist, int &delta) { return false; } // resets the loop to visit children void reset() { } }; typedef Board NodeT; typedef int DeltaT; // represents a state change, useful to track the path // Depth limited search bool ida_dls(NodeT &node, int depth, int g, int &nxt, stack<DeltaT> &st) { if (g == depth) return node.is_solution(); NodeT child; int dist; DeltaT delta; for (node.reset(); node.next(child, dist, delta);) { int f = g + dist + child.h(); if (f > depth && f < nxt) nxt = f; if (f <= depth && ida_dls(child, depth, g + 1, nxt, st)) { st.push(delta); return true; } } return false; } bool ida_star(NodeT &root, int limit, stack<DeltaT> &st) { for (int depth = root.h(); depth <= limit;) { int next_depth = INF; if (ida_dls(root, depth, 0, next_depth, st)) return true; if (next_depth == INF) return false; depth = next_depth; } return false; } // // Quickselect - for locating the median // struct Data { int v; // value int n; // occurrences int p; // original position of data, to break ties Data(int V, int N, int P) : v(V), n(N), p(P) {} bool operator<(const Data &x) const { if (v != x.v) return v < x.v; if (n != x.n) return n < x.n; return p < x.p; } }; typedef vector<Data> DV; typedef DV::iterator DVi; int select_kth(DVi lo, DVi hi, int k) { if (hi == lo + 1) return lo->v; swap(*(lo + (rand() % (hi - lo))), *(hi - 1)); Data piv = *(hi - 1); DVi x = lo; int lt = 0; for (DVi i = lo, I = hi - 1; i != I; ++i) if (*i < piv) { swap(*i, *x); lt += x->n, ++x; } swap(*x, *(hi - 1)); if (k < lt) return select_kth(lo, x, k); if (k >= lt + x->n) return select_kth(x + 1, hi, k - lt - x->n); return x->v; } // // Basic binary search // template <typename T> int binsearch(const T *a, int lo, int hi, T v) { while (lo < hi) { int mid = (lo + hi) / 2; if (a[mid] == v) return mid; if (a[mid] < v) lo = mid + 1; else hi = mid; } return -1; } template <typename T> int binsearch_upper(const T *a, int lo, int hi, T v) { while (lo < hi) { int mid = (lo + hi) / 2; if (a[mid] <= v) lo = mid + 1; else hi = mid; } return lo; } // // Merge sort - useful for adapting it to sorting-related problems // void merge(IVi lo, IVi hi, IVi mid) { IV x; for (IVi a = lo, b = mid; a < mid || b < hi; ) { if (a >= mid) { x.push_back(*b++); continue; } if (b >= hi) { x.push_back(*a++); continue; } if (*a < *b) { x.push_back(*a++); continue; } x.push_back(*b++); } for (IVi a = lo, b = x.begin(); a < hi; ++a, ++b) *a = *b; } void merge_sort(IVi lo, IVi hi) { if (hi <= lo + 1) return; IVi mid = lo + ((hi - lo) / 2); merge_sort(lo, mid); merge_sort(mid, hi); merge(lo, hi, mid); } // // Misc functions // // returns the position of the last visited in range [0, n-1] int josephus(int n, int k) { if (n == 1) return 0; return (josephus(n-1, k) + k) % n; } // // Max Area Rectangle in an Histogram // typedef int AreaT; AreaT areas[MAXN]; int stk[MAXN], stk_top; AreaT histo_area(AreaT *h, int n) { stk_top = 0; for (int i = 0; i < n; ++i) { while (stk_top > 0 && h[ stk[stk_top-1] ] >= h[i]) --stk_top; int bound = stk_top > 0 ? stk[stk_top - 1] : -1; areas[i] = i - bound; stk[stk_top++] = i; } stk_top = 0; for (int i = n-1; i >= 0; --i) { while (stk_top > 0 && h[ stk[stk_top-1] ] >= h[i]) --stk_top; int bound = stk_top > 0 ? stk[stk_top - 1] : n; areas[i] += bound - i - 1; stk[stk_top++] = i; } AreaT ans = 0; for (int i = 0; i < n; ++i) if (h[i] > 0 && areas[i]*h[i] > ans) ans = areas[i]*h[i]; return ans; } // // Stable Marriage Problem // // man[i][j]: woman with priority j for man i int man[MAXN][MAXN]; // woman[i][j]: priority for man j given by woman i int woman[MAXN][MAXN]; // next_for[i]: next priority to consider for man i int next_for[MAXN]; struct Marriage { int w, m; Marriage() {} Marriage(int W, int M): w(W), m(M) {} bool operator<(const Marriage &x) const { return woman[w][m] > woman[x.w][x.m]; } }; // marriage[j]: current marriage for woman j Marriage marriage[MAXN]; // Gale-Shapley algorithm. // pre-cond: Clr(next_for) Neg(marriage) void stable_match(int m) { // if a solution is not guaranteed, add check here to see if maybe there // are no more matches int w = man[m][ next_for[m]++ ]; Marriage cur(w, m); if (marriage[w].m < 0) marriage[w] = cur; else if (marriage[w] < cur) { int mp = marriage[w].m; marriage[w] = cur; stable_match(mp); } else stable_match(m); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_CODIM1_HH #define DUNE_GDT_LOCALOPERATOR_CODIM1_HH #include <utility> #include <vector> #include <type_traits> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/densematrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/disable_warnings.hh> # include <dune/geometry/quadraturerules.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/functions/interfaces.hh> #include "../localevaluation/interface.hh" #include "interface.hh" namespace Dune { namespace GDT { namespace LocalOperator { // forward, to be used in the traits template< class QuaternaryEvaluationImp > class Codim1CouplingIntegral; template< class QuaternaryEvaluationImp > class Codim1CouplingIntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim1Interface< typename QuaternaryEvaluationImp::Traits, 4 >, QuaternaryEvaluationImp >::value, "QuaternaryEvaluationImp has to be derived from LocalEvaluation::Codim1Interface< ..., 4 >!"); public: typedef Codim1CouplingIntegral< QuaternaryEvaluationImp > derived_type; typedef LocalEvaluation::Codim1Interface< typename QuaternaryEvaluationImp::Traits, 4 > QuaternaryEvaluationType; }; template< class QuaternaryEvaluationImp > class Codim1CouplingIntegral : public LocalOperator::Codim1CouplingInterface< Codim1CouplingIntegralTraits< QuaternaryEvaluationImp > > { public: typedef Codim1CouplingIntegralTraits< QuaternaryEvaluationImp > Traits; typedef typename Traits::QuaternaryEvaluationType QuaternaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 4; public: template< class... Args > Codim1CouplingIntegral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > Codim1CouplingIntegral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} template< class... Args > Codim1CouplingIntegral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(boost::numeric_cast< size_t >(over_integrate)) {} size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class N, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& entityTestBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& entityAnsatzBase, const Stuff::LocalfunctionSetInterface< N, D, d, R, rT, rCT >& neighborTestBase, const Stuff::LocalfunctionSetInterface< N, D, d, R, rA, rCA >& neighborAnsatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& entityEntityRet, Dune::DynamicMatrix< R >& neighborNeighborRet, Dune::DynamicMatrix< R >& entityNeighborRet, Dune::DynamicMatrix< R >& neighborEntityRet, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { // local inducing function const auto& entity = entityTestBase.entity(); const auto localFunctionsEn = evaluation_.localFunctions(entity); const auto& neighbor = neighborTestBase.entity(); const auto localFunctionsNe = evaluation_.localFunctions(neighbor); // quadrature const size_t integrand_order = evaluation().order(localFunctionsEn, localFunctionsNe, entityTestBase, entityAnsatzBase, neighborTestBase, neighborAnsatzBase) + over_integrate_; assert(integrand_order < std::numeric_limits< int >::max()); const auto& faceQuadrature = QuadratureRules< D, d - 1 >::rule(intersection.type(), int(integrand_order)); // check matrices entityEntityRet *= 0.0; neighborNeighborRet *= 0.0; entityNeighborRet *= 0.0; neighborEntityRet *= 0.0; const size_t rowsEn = entityTestBase.size(); const size_t colsEn = entityAnsatzBase.size(); const size_t rowsNe = neighborTestBase.size(); const size_t colsNe = neighborAnsatzBase.size(); assert(entityEntityRet.rows() >= rowsEn); assert(entityEntityRet.cols() >= colsEn); assert(neighborNeighborRet.rows() >= rowsNe); assert(neighborNeighborRet.cols() >= colsNe); assert(entityNeighborRet.rows() >= rowsEn); assert(entityNeighborRet.cols() >= colsNe); assert(neighborEntityRet.rows() >= rowsEn); assert(neighborEntityRet.cols() >= colsEn); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); Dune::DynamicMatrix< R >& entityEntityVals = tmpLocalMatrices[0]; Dune::DynamicMatrix< R >& neighborNeighborVals = tmpLocalMatrices[1]; Dune::DynamicMatrix< R >& entityNeighborVals = tmpLocalMatrices[2]; Dune::DynamicMatrix< R >& neighborEntityVals = tmpLocalMatrices[3]; // loop over all quadrature points for (auto quadPoint = faceQuadrature.begin(); quadPoint != faceQuadrature.end(); ++quadPoint) { const Dune::FieldVector< D, d - 1 > localPoint = quadPoint->position(); const R integrationFactor = intersection.geometry().integrationElement(localPoint); const R quadratureWeight = quadPoint->weight(); // evaluate local evaluation().evaluate(localFunctionsEn, localFunctionsNe, entityTestBase, entityAnsatzBase, neighborTestBase, neighborAnsatzBase, intersection, localPoint, entityEntityVals, neighborNeighborVals, entityNeighborVals, neighborEntityVals); // compute integral assert(entityEntityVals.rows() >= rowsEn); assert(entityEntityVals.cols() >= colsEn); assert(neighborNeighborVals.rows() >= rowsNe); assert(neighborNeighborVals.cols() >= colsNe); assert(entityNeighborVals.rows() >= rowsEn); assert(entityNeighborVals.cols() >= colsNe); assert(neighborEntityVals.rows() >= rowsEn); assert(neighborEntityVals.cols() >= colsEn); // loop over all entity test basis functions for (size_t ii = 0; ii < rowsEn; ++ii) { auto& entityEntityRetRow = entityEntityRet[ii]; const auto& entityEntityValsRow = entityEntityVals[ii]; auto& entityNeighborRetRow = entityNeighborRet[ii]; const auto& entityNeighborValsRow = entityNeighborVals[ii]; // loop over all entity ansatz basis functions for (size_t jj = 0; jj < colsEn; ++jj) { entityEntityRetRow[jj] += entityEntityValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all entity ansatz basis functions // loop over all neighbor ansatz basis functions for (size_t jj = 0; jj < colsNe; ++jj) { entityNeighborRetRow[jj] += entityNeighborValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all neighbor ansatz basis functions } // loop over all entity test basis functions // loop over all neighbor test basis functions for (size_t ii = 0; ii < rowsNe; ++ii) { auto& neighborNeighborRetRow = neighborNeighborRet[ii]; const auto& neighborNeighborValsRow = neighborNeighborVals[ii]; auto& neighborEntityRetRow = neighborEntityRet[ii]; const auto& neighborEntityValsRow = neighborEntityVals[ii]; // loop over all neighbor ansatz basis functions for (size_t jj = 0; jj < colsNe; ++jj) { neighborNeighborRetRow[jj] += neighborNeighborValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all neighbor ansatz basis functions // loop over all entity ansatz basis functions for (size_t jj = 0; jj < colsEn; ++jj) { neighborEntityRetRow[jj] += neighborEntityValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all entity ansatz basis functions } // loop over all neighbor test basis functions } // loop over all quadrature points } // void apply(...) const private: const QuaternaryEvaluationType& evaluation() const { return evaluation_; } const QuaternaryEvaluationImp evaluation_; const size_t over_integrate_; }; // class Codim1CouplingIntegral // forward, to be used in the traits template< class BinaryEvaluationImp > class Codim1BoundaryIntegral; template< class BinaryEvaluationImp > class Codim1BoundaryIntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim1Interface< typename BinaryEvaluationImp::Traits, 2 >, BinaryEvaluationImp >::value, "BinaryEvaluationImp has to be derived from LocalEvaluation::Codim1Interface< ..., 2 >!"); public: typedef Codim1BoundaryIntegral< BinaryEvaluationImp > derived_type; typedef LocalEvaluation::Codim1Interface< typename BinaryEvaluationImp::Traits, 2 > BinaryEvaluationType; }; template< class BinaryEvaluationImp > class Codim1BoundaryIntegral : public LocalOperator::Codim1BoundaryInterface< Codim1BoundaryIntegralTraits< BinaryEvaluationImp > > { public: typedef Codim1BoundaryIntegralTraits< BinaryEvaluationImp > Traits; typedef typename Traits::BinaryEvaluationType BinaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 1; public: template< class... Args > Codim1BoundaryIntegral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > Codim1BoundaryIntegral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} template< class... Args > Codim1BoundaryIntegral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(boost::numeric_cast< size_t >(over_integrate)) {} size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { // local inducing function const auto& entity = testBase.entity(); const auto localFunctions = evaluation_.localFunctions(entity); // quadrature typedef Dune::QuadratureRules< D, d - 1 > FaceQuadratureRules; typedef Dune::QuadratureRule< D, d - 1 > FaceQuadratureType; const size_t integrand_order = evaluation().order(localFunctions, testBase, ansatzBase) + over_integrate_; assert(integrand_order < std::numeric_limits< int >::max()); const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), int(integrand_order)); // check matrix and tmp storage ret *= 0.0; const size_t rows = testBase.size(); const size_t cols = ansatzBase.size(); assert(ret.rows() >= rows); assert(ret.cols() >= cols); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); Dune::DynamicMatrix< R >& localMatrix = tmpLocalMatrices[0]; // loop over all quadrature points for (auto quadPoint = faceQuadrature.begin(); quadPoint != faceQuadrature.end(); ++quadPoint) { const Dune::FieldVector< D, d - 1 > localPoint = quadPoint->position(); const R integrationFactor = intersection.geometry().integrationElement(localPoint); const R quadratureWeight = quadPoint->weight(); // evaluate local evaluation().evaluate(localFunctions, testBase, ansatzBase, intersection, localPoint, localMatrix); // compute integral assert(localMatrix.rows() >= rows); assert(localMatrix.cols() >= cols); // loop over all test basis functions for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; const auto& localMatrixRow = localMatrix[ii]; // loop over all ansatz basis functions for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] += localMatrixRow[jj] * integrationFactor * quadratureWeight; } // loop over all ansatz basis functions } // loop over all test basis functions } // loop over all quadrature points } // void apply(...) const private: const BinaryEvaluationType& evaluation() const { return evaluation_; } const BinaryEvaluationImp evaluation_; const size_t over_integrate_; }; // class Codim1BoundaryIntegral } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_CODIM1_HH <commit_msg>[localoperator.codim1] modernize<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_LOCALOPERATOR_CODIM1_HH #define DUNE_GDT_LOCALOPERATOR_CODIM1_HH #include <utility> #include <vector> #include <type_traits> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/densematrix.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/functions/interfaces.hh> #include "../localevaluation/interface.hh" #include "interface.hh" namespace Dune { namespace GDT { namespace LocalOperator { // forwards template< class QuaternaryEvaluationImp > class Codim1CouplingIntegral; template< class BinaryEvaluationImp > class Codim1BoundaryIntegral; namespace internal { template< class QuaternaryEvaluationImp > class Codim1CouplingIntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim1Interface< typename QuaternaryEvaluationImp::Traits, 4 >, QuaternaryEvaluationImp >::value, "QuaternaryEvaluationImp has to be derived from LocalEvaluation::Codim1Interface< ..., 4 >!"); public: typedef Codim1CouplingIntegral< QuaternaryEvaluationImp > derived_type; }; template< class BinaryEvaluationImp > class Codim1BoundaryIntegralTraits { static_assert(std::is_base_of< LocalEvaluation::Codim1Interface< typename BinaryEvaluationImp::Traits, 2 >, BinaryEvaluationImp >::value, "BinaryEvaluationImp has to be derived from LocalEvaluation::Codim1Interface< ..., 2 >!"); public: typedef Codim1BoundaryIntegral< BinaryEvaluationImp > derived_type; }; } // namespace internal template< class QuaternaryEvaluationImp > class Codim1CouplingIntegral : public LocalOperator::Codim1CouplingInterface< internal::Codim1CouplingIntegralTraits< QuaternaryEvaluationImp > > { public: typedef internal::Codim1CouplingIntegralTraits< QuaternaryEvaluationImp > Traits; typedef QuaternaryEvaluationImp QuaternaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 4; public: template< class... Args > explicit Codim1CouplingIntegral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > explicit Codim1CouplingIntegral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} template< class... Args > explicit Codim1CouplingIntegral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(boost::numeric_cast< size_t >(over_integrate)) {} size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class N, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& entityTestBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& entityAnsatzBase, const Stuff::LocalfunctionSetInterface< N, D, d, R, rT, rCT >& neighborTestBase, const Stuff::LocalfunctionSetInterface< N, D, d, R, rA, rCA >& neighborAnsatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& entityEntityRet, Dune::DynamicMatrix< R >& neighborNeighborRet, Dune::DynamicMatrix< R >& entityNeighborRet, Dune::DynamicMatrix< R >& neighborEntityRet, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { // local inducing function const auto& entity = entityTestBase.entity(); const auto localFunctionsEn = evaluation_.localFunctions(entity); const auto& neighbor = neighborTestBase.entity(); const auto localFunctionsNe = evaluation_.localFunctions(neighbor); // quadrature const size_t integrand_order = evaluation_.order(localFunctionsEn, localFunctionsNe, entityTestBase, entityAnsatzBase, neighborTestBase, neighborAnsatzBase) + over_integrate_; const auto& faceQuadrature = QuadratureRules< D, d - 1 >::rule(intersection.type(), boost::numeric_cast< int >(integrand_order)); // check matrices entityEntityRet *= 0.0; neighborNeighborRet *= 0.0; entityNeighborRet *= 0.0; neighborEntityRet *= 0.0; const size_t rowsEn = entityTestBase.size(); const size_t colsEn = entityAnsatzBase.size(); const size_t rowsNe = neighborTestBase.size(); const size_t colsNe = neighborAnsatzBase.size(); assert(entityEntityRet.rows() >= rowsEn); assert(entityEntityRet.cols() >= colsEn); assert(neighborNeighborRet.rows() >= rowsNe); assert(neighborNeighborRet.cols() >= colsNe); assert(entityNeighborRet.rows() >= rowsEn); assert(entityNeighborRet.cols() >= colsNe); assert(neighborEntityRet.rows() >= rowsEn); assert(neighborEntityRet.cols() >= colsEn); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); auto& entityEntityVals = tmpLocalMatrices[0]; auto& neighborNeighborVals = tmpLocalMatrices[1]; auto& entityNeighborVals = tmpLocalMatrices[2]; auto& neighborEntityVals = tmpLocalMatrices[3]; // loop over all quadrature points for (auto quadPoint = faceQuadrature.begin(); quadPoint != faceQuadrature.end(); ++quadPoint) { const Dune::FieldVector< D, d - 1 > localPoint = quadPoint->position(); const auto integrationFactor = intersection.geometry().integrationElement(localPoint); const auto quadratureWeight = quadPoint->weight(); // evaluate local evaluation_.evaluate(localFunctionsEn, localFunctionsNe, entityTestBase, entityAnsatzBase, neighborTestBase, neighborAnsatzBase, intersection, localPoint, entityEntityVals, neighborNeighborVals, entityNeighborVals, neighborEntityVals); // compute integral assert(entityEntityVals.rows() >= rowsEn); assert(entityEntityVals.cols() >= colsEn); assert(neighborNeighborVals.rows() >= rowsNe); assert(neighborNeighborVals.cols() >= colsNe); assert(entityNeighborVals.rows() >= rowsEn); assert(entityNeighborVals.cols() >= colsNe); assert(neighborEntityVals.rows() >= rowsEn); assert(neighborEntityVals.cols() >= colsEn); // loop over all entity test basis functions for (size_t ii = 0; ii < rowsEn; ++ii) { auto& entityEntityRetRow = entityEntityRet[ii]; const auto& entityEntityValsRow = entityEntityVals[ii]; auto& entityNeighborRetRow = entityNeighborRet[ii]; const auto& entityNeighborValsRow = entityNeighborVals[ii]; // loop over all entity ansatz basis functions for (size_t jj = 0; jj < colsEn; ++jj) { entityEntityRetRow[jj] += entityEntityValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all entity ansatz basis functions // loop over all neighbor ansatz basis functions for (size_t jj = 0; jj < colsNe; ++jj) { entityNeighborRetRow[jj] += entityNeighborValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all neighbor ansatz basis functions } // loop over all entity test basis functions // loop over all neighbor test basis functions for (size_t ii = 0; ii < rowsNe; ++ii) { auto& neighborNeighborRetRow = neighborNeighborRet[ii]; const auto& neighborNeighborValsRow = neighborNeighborVals[ii]; auto& neighborEntityRetRow = neighborEntityRet[ii]; const auto& neighborEntityValsRow = neighborEntityVals[ii]; // loop over all neighbor ansatz basis functions for (size_t jj = 0; jj < colsNe; ++jj) { neighborNeighborRetRow[jj] += neighborNeighborValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all neighbor ansatz basis functions // loop over all entity ansatz basis functions for (size_t jj = 0; jj < colsEn; ++jj) { neighborEntityRetRow[jj] += neighborEntityValsRow[jj] * integrationFactor * quadratureWeight; } // loop over all entity ansatz basis functions } // loop over all neighbor test basis functions } // loop over all quadrature points } // void apply(...) const private: const QuaternaryEvaluationType evaluation_; const size_t over_integrate_; }; // class Codim1CouplingIntegral template< class BinaryEvaluationImp > class Codim1BoundaryIntegral : public LocalOperator::Codim1BoundaryInterface< internal::Codim1BoundaryIntegralTraits< BinaryEvaluationImp > > { public: typedef internal::Codim1BoundaryIntegralTraits< BinaryEvaluationImp > Traits; typedef BinaryEvaluationImp BinaryEvaluationType; private: static const size_t numTmpObjectsRequired_ = 1; public: template< class... Args > Codim1BoundaryIntegral(Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(0) {} template< class... Args > Codim1BoundaryIntegral(const size_t over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(over_integrate) {} template< class... Args > Codim1BoundaryIntegral(const int over_integrate, Args&& ...args) : evaluation_(std::forward< Args >(args)...) , over_integrate_(boost::numeric_cast< size_t >(over_integrate)) {} size_t numTmpObjectsRequired() const { return numTmpObjectsRequired_; } template< class E, class IntersectionType, class D, int d, class R, int rT, int rCT, int rA, int rCA > void apply(const Stuff::LocalfunctionSetInterface< E, D, d, R, rT, rCT >& testBase, const Stuff::LocalfunctionSetInterface< E, D, d, R, rA, rCA >& ansatzBase, const IntersectionType& intersection, Dune::DynamicMatrix< R >& ret, std::vector< Dune::DynamicMatrix< R > >& tmpLocalMatrices) const { // local inducing function const auto& entity = testBase.entity(); const auto localFunctions = evaluation_.localFunctions(entity); // quadrature typedef Dune::QuadratureRules< D, d - 1 > FaceQuadratureRules; typedef Dune::QuadratureRule< D, d - 1 > FaceQuadratureType; const auto integrand_order = evaluation_.order(localFunctions, testBase, ansatzBase) + over_integrate_; const FaceQuadratureType& faceQuadrature = FaceQuadratureRules::rule(intersection.type(), boost::numeric_cast< int >(integrand_order)); // check matrix and tmp storage ret *= 0.0; const size_t rows = testBase.size(); const size_t cols = ansatzBase.size(); assert(ret.rows() >= rows); assert(ret.cols() >= cols); assert(tmpLocalMatrices.size() >= numTmpObjectsRequired_); Dune::DynamicMatrix< R >& localMatrix = tmpLocalMatrices[0]; // loop over all quadrature points for (auto quadPoint = faceQuadrature.begin(); quadPoint != faceQuadrature.end(); ++quadPoint) { const Dune::FieldVector< D, d - 1 > localPoint = quadPoint->position(); const R integrationFactor = intersection.geometry().integrationElement(localPoint); const R quadratureWeight = quadPoint->weight(); // evaluate local evaluation_.evaluate(localFunctions, testBase, ansatzBase, intersection, localPoint, localMatrix); // compute integral assert(localMatrix.rows() >= rows); assert(localMatrix.cols() >= cols); // loop over all test basis functions for (size_t ii = 0; ii < rows; ++ii) { auto& retRow = ret[ii]; const auto& localMatrixRow = localMatrix[ii]; // loop over all ansatz basis functions for (size_t jj = 0; jj < cols; ++jj) { retRow[jj] += localMatrixRow[jj] * integrationFactor * quadratureWeight; } // loop over all ansatz basis functions } // loop over all test basis functions } // loop over all quadrature points } // void apply(...) const private: const BinaryEvaluationType evaluation_; const size_t over_integrate_; }; // class Codim1BoundaryIntegral } // namespace LocalOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_LOCALOPERATOR_CODIM1_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH #define DUNE_STUFF_GRID_PROVIDER_GMSH_HH // system #include <sstream> #include <type_traits> #include <boost/assign/list_of.hpp> // dune-common #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> // dune-grid #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #ifdef HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/grid/sgrid.hh> //#include <dune/grid/common/mcmgmapper.hh> //#include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/gmshreader.hh> // local #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Gmsh grid provider */ #if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridType = Dune::GridSelector::GridType > #else template< class GridType > #endif class Gmsh : public Interface<GridImp> { public: //! Type of the provided grid. typedef GridImp GridType; //! Dimension of the provided grid. static const unsigned int dim = GridType::dimension; //! Type of the grids coordinates. typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.gmsh static const std::string static_id; Gmsh(const Dune::ParameterTree paramTree) { const std::string filename = paramTree.get("mshfile", "sample.msh"); //read gmshfile grid_ = Dune::shared_ptr<GridType> (GmshReader<GridType>::read(filename)); } virtual std::string id() const { return static_id; } /** \brief Provides access to the created grid. \return Reference to the grid. **/ virtual GridType& grid() { return *grid_; } /** * \brief Provides const access to the created grid. * \return Reference to the grid. **/ virtual const GridType& grid() const { return *grid_; } //! access to shared ptr virtual Dune::shared_ptr<GridType> gridPtr() { return grid_; } //! const access to shared ptr virtual const Dune::shared_ptr< const GridType > gridPtr() const { return grid_; } private: const std::string filename_; Dune::shared_ptr< GridType > grid_; }; // class Gmsh template< typename GridImp > const std::string Gmsh< GridImp >::static_id = "stuff.grid.provider.gmsh"; } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_GMSH_HH <commit_msg>fix nonsense template arg naming<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH #define DUNE_STUFF_GRID_PROVIDER_GMSH_HH // system #include <sstream> #include <type_traits> #include <boost/assign/list_of.hpp> // dune-common #include <dune/common/parametertree.hh> #include <dune/common/shared_ptr.hh> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> // dune-grid #include <dune/grid/utility/structuredgridfactory.hh> #include <dune/grid/yaspgrid.hh> #ifdef HAVE_ALUGRID #include <dune/grid/alugrid.hh> #endif #include <dune/grid/sgrid.hh> //#include <dune/grid/common/mcmgmapper.hh> //#include <dune/grid/io/file/vtk/vtkwriter.hh> #include <dune/grid/io/file/gmshreader.hh> // local #include "interface.hh" namespace Dune { namespace Stuff { namespace Grid { namespace Provider { /** * \brief Gmsh grid provider */ #if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG template< class GridImp = Dune::GridSelector::GridType > #else template< class GridImp > #endif class Gmsh : public Interface<GridImp> { public: //! Type of the provided grid. typedef GridImp GridType; //! Dimension of the provided grid. static const unsigned int dim = GridType::dimension; //! Type of the grids coordinates. typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; //! Unique identifier: \c stuff.grid.provider.gmsh static const std::string static_id; Gmsh(const Dune::ParameterTree paramTree) { const std::string filename = paramTree.get("mshfile", "sample.msh"); //read gmshfile grid_ = Dune::shared_ptr<GridType> (GmshReader<GridType>::read(filename)); } virtual std::string id() const { return static_id; } /** \brief Provides access to the created grid. \return Reference to the grid. **/ virtual GridType& grid() { return *grid_; } /** * \brief Provides const access to the created grid. * \return Reference to the grid. **/ virtual const GridType& grid() const { return *grid_; } //! access to shared ptr virtual Dune::shared_ptr<GridType> gridPtr() { return grid_; } //! const access to shared ptr virtual const Dune::shared_ptr< const GridType > gridPtr() const { return grid_; } private: const std::string filename_; Dune::shared_ptr< GridType > grid_; }; // class Gmsh template< typename GridImp > const std::string Gmsh< GridImp >::static_id = "stuff.grid.provider.gmsh"; } // namespace Provider } // namespace Grid } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_GRID_PROVIDER_GMSH_HH <|endoftext|>
<commit_before>#include "test_common.hh" #if HAVE_DUNE_GRID // system #include <iostream> #include <fstream> #include <utility> // boost #include <boost/filesystem.hpp> // dune-common #include <dune/common/mpihelper.hh> #include <dune/common/parametertreeparser.hh> #include <dune/common/timer.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/grid/provider/cornerpoint.hh> #include <dune/stuff/grid/provider/cube.hh> using namespace Dune::Stuff; const std::string id = "grid_provider"; /** \brief Creates a parameter file if it does not exist. Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary keys and values. \param[in] filename (Relative) path to the file. **/ void ensureParamFile(std::string filename) { // only write param file if there is none if (!boost::filesystem::exists(filename)) { std::ofstream file; file.open(filename); file << "[stuff.grid.provider.cube]" << std::endl; file << "level = 2" << std::endl; file << "visualize.grid = rb_grid_provider_cube_grid" << std::endl; file << "visualize.msGrid = rb_grid_provider_cube_msGrid" << std::endl; file << std::endl; file << "[stuff.grid.provider.cornerpoint]" << std::endl; file << "filename = /dune-stuff/data/grid/johansen_formation.grdecl" << std::endl; // has to be an absolute path file.close(); } // only write param file if there is none } // void ensureParamFile() /** \brief Fills a Dune::ParameterTree given a parameter file or command line arguments. \param[in] argc From \c main() \param[in] argv From \c main() \param[out] paramTree The Dune::ParameterTree that is to be filled. **/ void initParamTree(int argc, char** argv, Dune::ParameterTree& paramTree) { paramTree = Common::ExtendedParameterTree::init(argc, argv, "provider.param"); } template< class GridViewType > int walkGridView(const GridViewType& gridView) { return gridView.size(0); } // void walkGrid(const GridType& grid) /*template< class MDGridType > int walkMDGrid(MDGridType& mdGrid) { int numElements = 0; // loop over all subdomains for (typename MDGridType::SubDomainIndexType subdomainIndex = 0; subdomainIndex <= mdGrid.maxSubDomainIndex; ++subdomainIndex) { // subdomain grid typedef typename MDGridType::SubDomainGrid SDGridType; const SDGridType& sdGrid = mdGrid.subDomain(subdomainIndex); // subdomain grid view typedef typename SDGridType::LeafGridView SDGridViewType; const SDGridViewType& sdGridView = sdGrid.leafView(); // walk the subdomain grid typedef typename SDGridViewType::template Codim<0>::Iterator SDElementIteratorType; typedef typename SDGridViewType::template Codim<0>::Entity SDElementType; for (SDElementIteratorType sdElementIterator = sdGridView.template begin<0>(); sdElementIterator != sdGridView.template end<0>(); ++sdElementIterator) { const SDElementType& sdElement = *sdElementIterator; ++numElements; } // walk the subdomain grid } // loop over all subdomains return numElements; } // void walkMDGrid(const GridType& grid)*/ template< class GridProviderType > void measureTiming(GridProviderType& gridProvider) { Dune::Timer timer; typename GridProviderType::GridType::LeafGridView gridView = gridProvider.grid().leafView(); const int numHostGridElements = walkGridView(gridView); std::cout << " host grid: " << timer.elapsed() << " sec, " << numHostGridElements << " elements" << std::endl; timer.reset(); } /** \brief Main routine. **/ int GNAH(int argc, char** argv) { try { // mpi Dune::MPIHelper::instance(argc, argv); // parameter ensureParamFile(id + ".param"); Common::ExtendedParameterTree paramTree = Common::ExtendedParameterTree::init(argc, argv, id + ".param"); std::ofstream new_param(id + ".param_new"); paramTree.report(new_param); // timer Dune::Timer timer; // unitcube typedef Grid::Provider::Cube< Dune::GridSelector::GridType > CubeProviderType; //this CANNOT work CubeProviderType cubeProvider(paramTree.sub(cubeProvider.id)); CubeProviderType cubeProvider(paramTree.sub("cubeProvider.id")); DUNE_THROW(Dune::InvalidStateException, "cubeProvider dummy init"); cubeProvider.visualize(id); // cornerpoint #ifdef HAVE_DUNE_CORNERPOINT typedef Grid::Provider::Cornerpoint CornerpointGridProviderType; CornerpointGridProviderType cornerpointGridProvider(paramTree); cornerpointGridProvider.visualize(paramTree); #endif // measure timing std::cout << std::endl; measureTiming(cubeProvider); } catch (Dune::Exception& e) { std::cout << e.what() << std::endl; return 1; } return 0; } static const int dim = 2; typedef testing::Types< Dune::YaspGrid< dim > #if HAVE_ALUGRID , Dune::ALUCubeGrid< dim, dim > , Dune::ALUConformGrid< dim, dim > , Dune::ALUSimplexGrid< dim, dim > #endif #if HAVE_ALBERTA , Dune::AlbertaGrid< dim > #endif #if HAVE_UG , Dune::UGGrid< dim > #endif , Dune::SGrid< dim, dim > > GridTypes; template <class GridType> struct CubeTest : public testing::Test{ typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; CubeTest() {} void test_cube(typename GridType::ctype lower, typename GridType::ctype upper, const std::vector<u_int16_t>& elements_per_dimension) { test_cube(CoordinateType(lower), CoordinateType(upper), elements_per_dimension); } void test_cube(const CoordinateType lower, const CoordinateType upper, const std::vector<u_int16_t>& elements_per_dimension) { Grid::Provider::Cube< GridType > cube(lower, upper, elements_per_dimension); EXPECT_GE(cube.grid().size(0), 0); EXPECT_GE(cube.grid().size(1), 0); } }; TYPED_TEST_CASE(CubeTest, GridTypes); TYPED_TEST(CubeTest, All){ std::vector<u_int16_t> f = {1u,2u}; this->test_cube(0,1,f); } TEST(OLD, gnah){ char* gnah[] = {"koko"}; EXPECT_EQ(0, GNAH(1,gnah)); } #endif // #if HAVE_DUNE_GRID int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); Dune::MPIHelper::instance(argc, argv); return RUN_ALL_TESTS(); } <commit_msg>[test.grid_provider] make it work again<commit_after>#include "test_common.hh" #if HAVE_DUNE_GRID #include <iostream> #include <fstream> #include <utility> #include <boost/filesystem.hpp> #include <dune/common/mpihelper.hh> #include <dune/common/parametertree.hh> #include <dune/common/timer.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/grid/provider.hh> using namespace Dune; using namespace Dune::Stuff; const std::string id = "grid_provider"; ParameterTree sampleParamTree() { ParameterTree paramTree; paramTree[id + ".grid"] = "stuff.grid.provider.cube"; paramTree["stuff.grid.provider.cube.lowerLeft"] = "[0.0; 0.0; 0.0]"; paramTree["stuff.grid.provider.cube.upperRight"] = "[1.0; 1.0; 1.0]"; paramTree["stuff.grid.provider.cube.numElements"] = "[1; 1; 1]"; return paramTree; } static const int dim = 2; typedef testing::Types< Dune::YaspGrid< dim > #if HAVE_ALUGRID , Dune::ALUCubeGrid< dim, dim > , Dune::ALUConformGrid< dim, dim > , Dune::ALUSimplexGrid< dim, dim > #endif #if HAVE_ALBERTA , Dune::AlbertaGrid< dim > #endif #if HAVE_UG , Dune::UGGrid< dim > #endif , Dune::SGrid< dim, dim > > GridTypes; template< class GridType > struct CubeTest : public testing::Test { typedef Dune::FieldVector< typename GridType::ctype, dim > CoordinateType; CubeTest() {} void test_cube(const ParameterTree& paramTree) { const Dune::Stuff::Grid::Provider::Interface<>* gridProvider = Dune::Stuff::Grid::Provider::create(paramTree.get(id + ".grid", "stuff.grid.provider.cube"), paramTree); EXPECT_GT(gridProvider->grid()->size(0), 0); EXPECT_GT(gridProvider->grid()->size(1), 0); } }; TYPED_TEST_CASE(CubeTest, GridTypes); TYPED_TEST(CubeTest, All) { ParameterTree paramTree = sampleParamTree(); this->test_cube(paramTree); } #endif // #if HAVE_DUNE_GRID int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); Dune::MPIHelper::instance(argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(h) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { private: bool getNumber(const string &data, int *start, int *num) { if (data[*start] == '#') { *start += 2; // Skip "# ". return false; } for (*num = 0; isdigit(data[*start]); ++(*start)) { *num = *num * 10 + data[*start] - '0'; } ++(*start); // Skip " ". return true; } void deserializeHelper(const string& data, int *start, TreeNode **root) { int num; if (!getNumber(data, start, &num)) { *root = nullptr; } else { *root = new TreeNode(num); deserializeHelper(data, start, &((*root)->left)); deserializeHelper(data, start, &((*root)->right)); } } void serializeHelper(const TreeNode *root, string *prev) { if (!root) { prev->append("# "); } else { stringstream buffer; buffer << root->val << " "; prev->append(buffer.str()); serializeHelper(root->left, prev); serializeHelper(root->right, prev); } } public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { string output; serializeHelper(root, &output); return output; } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { TreeNode *root = nullptr; int start = 0; deserializeHelper(data, &start, &root); return root; } }; <commit_msg>Update binary-tree-serialization.cpp<commit_after>// Time: O(n) // Space: O(h) /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { private: bool getNumber(const string &data, int *start, int *num) { if (data[*start] == '#') { *start += 2; // Skip "# ". return false; } for (*num = 0; isdigit(data[*start]); ++(*start)) { *num = *num * 10 + data[*start] - '0'; } ++(*start); // Skip " ". return true; } void deserializeHelper(const string& data, int *start, TreeNode **root) { int num; if (!getNumber(data, start, &num)) { *root = nullptr; } else { *root = new TreeNode(num); deserializeHelper(data, start, &((*root)->left)); deserializeHelper(data, start, &((*root)->right)); } } void serializeHelper(const TreeNode *root, string *prev) { if (!root) { prev->append("# "); } else { prev->append(to_string(root->val) + " "); serializeHelper(root->left, prev); serializeHelper(root->right, prev); } } public: /** * This method will be invoked first, you should design your own algorithm * to serialize a binary tree which denote by a root node to a string which * can be easily deserialized by your own "deserialize" method later. */ string serialize(TreeNode *root) { string output; serializeHelper(root, &output); return output; } /** * This method will be invoked second, the argument data is what exactly * you serialized at method "serialize", that means the data is not given by * system, it's given by your own serialize method. So the format of data is * designed by yourself, and deserialize it here as you serialize it in * "serialize" method. */ TreeNode *deserialize(string data) { TreeNode *root = nullptr; int start = 0; deserializeHelper(data, &start, &root); return root; } }; <|endoftext|>
<commit_before>/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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 "paddle/fluid/operators/rank_attention_op.h" #include <memory> #include <string> #include <vector> namespace paddle { namespace operators { using Tensor = framework::Tensor; class RankAttentionOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true, platform::errors::InvalidArgument( "Input(X) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("RankOffset"), true, platform::errors::InvalidArgument( "Input(RankOffset) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("RankParam"), true, platform::errors::InvalidArgument( "Input(RankParam) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("InsRank"), true, platform::errors::InvalidArgument( "Output(InsRank) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("InputHelp"), true, platform::errors::InvalidArgument( "Output(InputHelp) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("Out"), true, platform::errors::InvalidArgument( "Output(Out) of RankAttentionOp should not be null.")); auto max_rank = ctx->Attrs().Get<int>("MaxRank"); auto x_dims = ctx->GetInputDim("X"); auto ins_num = x_dims[0]; auto param_dims = ctx->GetInputDim("RankParam"); auto para_col = param_dims[1]; auto rank_offset_dims = ctx->GetInputDim("RankOffset"); auto x_fea_dim = x_dims[1]; auto block_matrix_row = max_rank * x_fea_dim; PADDLE_ENFORCE_EQ((rank_offset_dims[1] - 1) / 2, max_rank, platform::errors::InvalidArgument( "Input(RankOffset) has wrong columns.")); ctx->SetOutputDim("Out", {ins_num, para_col}); ctx->SetOutputDim("InputHelp", {ins_num, block_matrix_row}); ctx->SetOutputDim("InsRank", {ins_num, 1}); ctx->ShareLoD("X", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.device_context()); } }; class RankAttentionGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("X"), true, platform::errors::InvalidArgument("Input(X) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("RankParam"), true, platform::errors::InvalidArgument( "Input(RankParam) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("RankOffset"), true, platform::errors::InvalidArgument( "Input(RankOffset) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("InputHelp"), true, platform::errors::InvalidArgument( "Input(InputHelp) should not be null")); PADDLE_ENFORCE_EQ( ctx->HasInput("InsRank"), true, platform::errors::InvalidArgument("Input(InsRank) should not be null")); ctx->SetOutputDim(framework::GradVarName("RankParam"), ctx->GetInputDim("RankParam")); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("Out")), ctx.device_context()); } }; class RankAttentionOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor) Input tensor of rank_attention_Op operator."); AddInput("RankOffset", "(Tensor) Input tensor of rank_attention_Op operator."); AddInput("RankParam", "(Tensor) Input tensor of rank_attention_Op operator."); AddOutput("InputHelp", "Output tensor of rank_attention_Op operator.") .AsDispensable(); AddOutput("Out", "Output tensor of rank_attention_Op operator."); AddOutput("InsRank", "Output tensor of rank_attention_Op operator.") .AsDispensable(); AddAttr<int>("MaxRank", "(int, default 3) max rank of rank_attention_Op") .SetDefault(3); AddAttr<int>("MaxSize", "(int, default 0) max rank of rank_attention_Op") .SetDefault(0); AddComment(R"DOC( RankAttention Operator. This Op can calculate rank attention between input and rank_param, and rank_param gives the organization of data. Notice: It currently supports GPU device. This Op exists in contrib, which means that it is not shown to the public. )DOC"); } }; template <typename T> class RankAttentionGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("rank_attention_grad"); op->SetInput("X", this->Input("X")); op->SetInput("RankOffset", this->Input("RankOffset")); op->SetInput("RankParam", this->Input("RankParam")); op->SetInput("InputHelp", this->Output("InputHelp")); op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); op->SetInput("InsRank", this->Output("InsRank")); op->SetOutput(framework::GradVarName("RankParam"), this->InputGrad("RankParam")); op->SetAttrMap(this->Attrs()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERER( RankAttentionGradOpNoNeedBufferVarsInference, "X", "RankOffset", "RankParam"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(rank_attention, ops::RankAttentionOp, ops::RankAttentionOpMaker, ops::RankAttentionGradOpMaker<paddle::framework::OpDesc>, ops::RankAttentionGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(rank_attention_grad, ops::RankAttentionGradOp, ops::RankAttentionGradOpNoNeedBufferVarsInference); REGISTER_OP_CPU_KERNEL( rank_attention, ops::RankAttentionKernel<paddle::platform::CPUDeviceContext, float>, ops::RankAttentionKernel<paddle::platform::CPUDeviceContext, double>); <commit_msg>Fix rank_attention op_version, test=op_version (#30006)<commit_after>/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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 "paddle/fluid/operators/rank_attention_op.h" #include <memory> #include <string> #include <vector> #include "paddle/fluid/framework/op_version_registry.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; class RankAttentionOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true, platform::errors::InvalidArgument( "Input(X) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("RankOffset"), true, platform::errors::InvalidArgument( "Input(RankOffset) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("RankParam"), true, platform::errors::InvalidArgument( "Input(RankParam) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("InsRank"), true, platform::errors::InvalidArgument( "Output(InsRank) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("InputHelp"), true, platform::errors::InvalidArgument( "Output(InputHelp) of RankAttentionOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("Out"), true, platform::errors::InvalidArgument( "Output(Out) of RankAttentionOp should not be null.")); auto max_rank = ctx->Attrs().Get<int>("MaxRank"); auto x_dims = ctx->GetInputDim("X"); auto ins_num = x_dims[0]; auto param_dims = ctx->GetInputDim("RankParam"); auto para_col = param_dims[1]; auto rank_offset_dims = ctx->GetInputDim("RankOffset"); auto x_fea_dim = x_dims[1]; auto block_matrix_row = max_rank * x_fea_dim; PADDLE_ENFORCE_EQ((rank_offset_dims[1] - 1) / 2, max_rank, platform::errors::InvalidArgument( "Input(RankOffset) has wrong columns.")); ctx->SetOutputDim("Out", {ins_num, para_col}); ctx->SetOutputDim("InputHelp", {ins_num, block_matrix_row}); ctx->SetOutputDim("InsRank", {ins_num, 1}); ctx->ShareLoD("X", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.device_context()); } }; class RankAttentionGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE_EQ( ctx->HasInput("X"), true, platform::errors::InvalidArgument("Input(X) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("RankParam"), true, platform::errors::InvalidArgument( "Input(RankParam) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("RankOffset"), true, platform::errors::InvalidArgument( "Input(RankOffset) should not be null")); PADDLE_ENFORCE_EQ(ctx->HasInput("InputHelp"), true, platform::errors::InvalidArgument( "Input(InputHelp) should not be null")); PADDLE_ENFORCE_EQ( ctx->HasInput("InsRank"), true, platform::errors::InvalidArgument("Input(InsRank) should not be null")); ctx->SetOutputDim(framework::GradVarName("RankParam"), ctx->GetInputDim("RankParam")); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType( ctx, framework::GradVarName("Out")), ctx.device_context()); } }; class RankAttentionOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor) Input tensor of rank_attention_Op operator."); AddInput("RankOffset", "(Tensor) Input tensor of rank_attention_Op operator."); AddInput("RankParam", "(Tensor) Input tensor of rank_attention_Op operator."); AddOutput("InputHelp", "Output tensor of rank_attention_Op operator.") .AsDispensable(); AddOutput("Out", "Output tensor of rank_attention_Op operator."); AddOutput("InsRank", "Output tensor of rank_attention_Op operator.") .AsDispensable(); AddAttr<int>("MaxRank", "(int, default 3) max rank of rank_attention_Op") .SetDefault(3); AddAttr<int>("MaxSize", "(int, default 0) max rank of rank_attention_Op") .SetDefault(0); AddComment(R"DOC( RankAttention Operator. This Op can calculate rank attention between input and rank_param, and rank_param gives the organization of data. Notice: It currently supports GPU device. This Op exists in contrib, which means that it is not shown to the public. )DOC"); } }; template <typename T> class RankAttentionGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("rank_attention_grad"); op->SetInput("X", this->Input("X")); op->SetInput("RankOffset", this->Input("RankOffset")); op->SetInput("RankParam", this->Input("RankParam")); op->SetInput("InputHelp", this->Output("InputHelp")); op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); op->SetInput("InsRank", this->Output("InsRank")); op->SetOutput(framework::GradVarName("RankParam"), this->InputGrad("RankParam")); op->SetAttrMap(this->Attrs()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERER( RankAttentionGradOpNoNeedBufferVarsInference, "X", "RankOffset", "RankParam"); } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(rank_attention, ops::RankAttentionOp, ops::RankAttentionOpMaker, ops::RankAttentionGradOpMaker<paddle::framework::OpDesc>, ops::RankAttentionGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(rank_attention_grad, ops::RankAttentionGradOp, ops::RankAttentionGradOpNoNeedBufferVarsInference); REGISTER_OP_CPU_KERNEL( rank_attention, ops::RankAttentionKernel<paddle::platform::CPUDeviceContext, float>, ops::RankAttentionKernel<paddle::platform::CPUDeviceContext, double>); REGISTER_OP_VERSION(rank_attention) .AddCheckpoint( R"ROC( Upgrade rank_attention, add 1 outputs [InputHelp] and 1 attribute [MaxSize]. )ROC", paddle::framework::compatible::OpVersionDesc() .NewOutput("InputHelp", "Output tensor of rank_attention_Op operator " "in order to assist calculation in the reverse process.") .NewAttr( "MaxSize", "Forward calculation to set the pre-applied video memory size", 0)); <|endoftext|>
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // #include "port/stack_trace.h" namespace rocksdb { namespace port { #if defined(ROCKSDB_LITE) || !(defined(OS_LINUX) || defined(OS_MACOSX)) // noop void InstallStackTraceHandler() {} void PrintStack(int first_frames_to_skip) {} #else #include <execinfo.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <cxxabi.h> namespace { #ifdef OS_LINUX const char* GetExecutableName() { static char name[1024]; char link[1024]; snprintf(link, sizeof(link), "/proc/%d/exe", getpid()); auto read = readlink(link, name, sizeof(name)); if (-1 == read) { return nullptr; } else { name[read] = 0; return name; } } void PrintStackTraceLine(const char* symbol, void* frame) { static const char* executable = GetExecutableName(); if (symbol) { fprintf(stderr, "%s ", symbol); } if (executable) { // out source to addr2line, for the address translation const int kLineMax = 256; char cmd[kLineMax]; snprintf(cmd, kLineMax, "addr2line %p -e %s -f -C 2>&1", frame, executable); auto f = popen(cmd, "r"); if (f) { char line[kLineMax]; while (fgets(line, sizeof(line), f)) { line[strlen(line) - 1] = 0; // remove newline fprintf(stderr, "%s\t", line); } pclose(f); } } else { fprintf(stderr, " %p", frame); } fprintf(stderr, "\n"); } #elif OS_MACOSX void PrintStackTraceLine(const char* symbol, void* frame) { static int pid = getpid(); // out source to atos, for the address translation const int kLineMax = 256; char cmd[kLineMax]; snprintf(cmd, kLineMax, "xcrun atos %p -p %d 2>&1", frame, pid); auto f = popen(cmd, "r"); if (f) { char line[kLineMax]; while (fgets(line, sizeof(line), f)) { line[strlen(line) - 1] = 0; // remove newline fprintf(stderr, "%s\t", line); } pclose(f); } else if (symbol) { fprintf(stderr, "%s ", symbol); } fprintf(stderr, "\n"); } #endif } // namespace void PrintStack(int first_frames_to_skip) { const int kMaxFrames = 100; void* frames[kMaxFrames]; auto num_frames = backtrace(frames, kMaxFrames); auto symbols = backtrace_symbols(frames, num_frames); for (int i = first_frames_to_skip; i < num_frames; ++i) { fprintf(stderr, "#%-2d ", i - first_frames_to_skip); PrintStackTraceLine((symbols != nullptr) ? symbols[i] : nullptr, frames[i]); } } static void StackTraceHandler(int sig) { // reset to default handler signal(sig, SIG_DFL); fprintf(stderr, "Received signal %d (%s)\n", sig, strsignal(sig)); // skip the top three signal handler related frames PrintStack(3); // re-signal to default handler (so we still get core dump if needed...) raise(sig); } void InstallStackTraceHandler() { // just use the plain old signal as it's simple and sufficient // for this use case signal(SIGILL, StackTraceHandler); signal(SIGSEGV, StackTraceHandler); signal(SIGBUS, StackTraceHandler); signal(SIGABRT, StackTraceHandler); } #endif } // namespace port } // namespace rocksdb <commit_msg>Avoid off-by-one error when using readlink<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // #include "port/stack_trace.h" namespace rocksdb { namespace port { #if defined(ROCKSDB_LITE) || !(defined(OS_LINUX) || defined(OS_MACOSX)) // noop void InstallStackTraceHandler() {} void PrintStack(int first_frames_to_skip) {} #else #include <execinfo.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <cxxabi.h> namespace { #ifdef OS_LINUX const char* GetExecutableName() { static char name[1024]; char link[1024]; snprintf(link, sizeof(link), "/proc/%d/exe", getpid()); auto read = readlink(link, name, sizeof(name) - 1); if (-1 == read) { return nullptr; } else { name[read] = 0; return name; } } void PrintStackTraceLine(const char* symbol, void* frame) { static const char* executable = GetExecutableName(); if (symbol) { fprintf(stderr, "%s ", symbol); } if (executable) { // out source to addr2line, for the address translation const int kLineMax = 256; char cmd[kLineMax]; snprintf(cmd, kLineMax, "addr2line %p -e %s -f -C 2>&1", frame, executable); auto f = popen(cmd, "r"); if (f) { char line[kLineMax]; while (fgets(line, sizeof(line), f)) { line[strlen(line) - 1] = 0; // remove newline fprintf(stderr, "%s\t", line); } pclose(f); } } else { fprintf(stderr, " %p", frame); } fprintf(stderr, "\n"); } #elif OS_MACOSX void PrintStackTraceLine(const char* symbol, void* frame) { static int pid = getpid(); // out source to atos, for the address translation const int kLineMax = 256; char cmd[kLineMax]; snprintf(cmd, kLineMax, "xcrun atos %p -p %d 2>&1", frame, pid); auto f = popen(cmd, "r"); if (f) { char line[kLineMax]; while (fgets(line, sizeof(line), f)) { line[strlen(line) - 1] = 0; // remove newline fprintf(stderr, "%s\t", line); } pclose(f); } else if (symbol) { fprintf(stderr, "%s ", symbol); } fprintf(stderr, "\n"); } #endif } // namespace void PrintStack(int first_frames_to_skip) { const int kMaxFrames = 100; void* frames[kMaxFrames]; auto num_frames = backtrace(frames, kMaxFrames); auto symbols = backtrace_symbols(frames, num_frames); for (int i = first_frames_to_skip; i < num_frames; ++i) { fprintf(stderr, "#%-2d ", i - first_frames_to_skip); PrintStackTraceLine((symbols != nullptr) ? symbols[i] : nullptr, frames[i]); } } static void StackTraceHandler(int sig) { // reset to default handler signal(sig, SIG_DFL); fprintf(stderr, "Received signal %d (%s)\n", sig, strsignal(sig)); // skip the top three signal handler related frames PrintStack(3); // re-signal to default handler (so we still get core dump if needed...) raise(sig); } void InstallStackTraceHandler() { // just use the plain old signal as it's simple and sufficient // for this use case signal(SIGILL, StackTraceHandler); signal(SIGSEGV, StackTraceHandler); signal(SIGBUS, StackTraceHandler); signal(SIGABRT, StackTraceHandler); } #endif } // namespace port } // namespace rocksdb <|endoftext|>
<commit_before>//-*- Mode: C++ -*- // $Id: AliHLTHOMERProxyHandler.cxx $ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Jochen Thaeder <thaeder@kip.uni-heidelberg.de> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTHOMERProxyHandler.cxx @author Jochen Thaeder @date @brief HOMER proxy handler for HomerManger */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #if __GNUC__>= 3 using namespace std; #endif #include "TDOMParser.h" #include "TSocket.h" #include "TSystem.h" // -- -- -- -- -- -- -- #include "AliHLTHOMERProxyHandler.h" // -- -- -- -- -- -- -- ClassImp(AliHLTHOMERProxyHandler) /* * --------------------------------------------------------------------------------- * Constructor / Destructor * --------------------------------------------------------------------------------- */ //################################################################################## AliHLTHOMERProxyHandler::AliHLTHOMERProxyHandler() : fRealm(kHLT), fXmlRpcResponse(""), fSourceList(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } //################################################################################## AliHLTHOMERProxyHandler::~AliHLTHOMERProxyHandler() { // see header file for class documentation } //################################################################################## Int_t AliHLTHOMERProxyHandler::Initialize() { // see header file for class documentation Int_t iResult = 0 ; IdentifyRealm(); return iResult; } /* * --------------------------------------------------------------------------------- * Source List - public * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::FillSourceList(TList *srcList) { // see header file for class documentation Int_t iResult = 0; fSourceList = srcList; iResult = RequestXmlRpcResponse(); if (!iResult) iResult = ProcessXmlRpcResponse(); if (iResult < 0) { HLTError(Form("Filling SourceList failed.")); } return iResult; } /* * --------------------------------------------------------------------------------- * Realms - private * --------------------------------------------------------------------------------- */ //################################################################################## const Char_t *AliHLTHOMERProxyHandler::fgkHOMERProxyNode[] = { "portal-dcs0.internal", "alihlt-dcs0.cern.ch", "alihlt-vobox0.cern.ch", "alihlt-gw0.kip.uni-heidelberg.de", "localhost", "portal-dcs1.internal", "alihlt-dcs1.cern.ch", "alihlt-vobox1.cern.ch", "alihlt-gw1.kip.uni-heidelberg.de", "localhost" }; //################################################################################## void AliHLTHOMERProxyHandler::IdentifyRealm() { // see header file for class documentation TString hostIP(gSystem->GetHostByName(gSystem->HostName()).GetHostAddress()); if ( hostIP.Contains("10.162.") ) fRealm = kHLT; else if ( hostIP.Contains("10.160.") || hostIP.Contains("10.161.") ) fRealm = kACR; else if ( hostIP.Contains("129.206.") ) fRealm = kKIP; else if ( hostIP.Contains("137.138") || hostIP.Contains("128.141") || hostIP.Contains("127.0.") ) fRealm = kGPN; else { fRealm = kLoc; } return; } /* * --------------------------------------------------------------------------------- * Proxy Communication - private * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::RequestXmlRpcResponse() { // see header file for class documentation Int_t iResult = 0; // -- open socket // ---------------- Int_t proxyPort = 19999; TSocket *socket = new TSocket(fgkHOMERProxyNode[fRealm], proxyPort); if ( ! socket->IsValid() ) { HLTWarning(Form("Failed to create socket to %s:%d,",fgkHOMERProxyNode[fRealm], proxyPort)); HLTWarning(Form("trying %s:%d now.", fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort)); socket = new TSocket(fgkHOMERProxyNode[fRealm+kHOMERRealmsMax], proxyPort); if ( ! socket->IsValid() ) { HLTError(Form("Failed to create socket to %s:%d and %s:%d.", fgkHOMERProxyNode[fRealm], proxyPort, fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort)); HLTWarning(Form("trying %s:%d now.", fgkHOMERProxyNode[kLoc],proxyPort)); socket = new TSocket(fgkHOMERProxyNode[kLoc], proxyPort); if ( ! socket->IsValid() ) { HLTError(Form("Failed to create socket to %s:%d , %s:%d and %s:%d.", fgkHOMERProxyNode[fRealm], proxyPort, fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort, fgkHOMERProxyNode[kLoc], proxyPort)); fRealm = -1; return -1; } else { fRealm = kLoc; } } else fRealm = fRealm+kHOMERRealmsMax; } // -- send request // ----------------- Char_t reqMsg[] = "POST / HTTP/1.1\r\n\ User-Agent: curl/7.18.0 (x86_64-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n\ Host: localhost:10000\r\n\ Accept: */*\r\n\ Content-type: text/xml\r\n\ Content-Length: 68\r\n\ \r\n<methodCall><methodName>getTcpDumpServices</methodName></methodCall>\r\n"; iResult = socket->SendRaw( reqMsg, strlen(reqMsg) ); if ( iResult < 1 || iResult != static_cast<Int_t>(strlen(reqMsg))) { HLTError(Form("Error sending! -- send length %d -- msg length %d.", iResult, static_cast<Int_t>(strlen(reqMsg)) )); socket->Close(); return iResult; } // -- receive answer // ------------------- const Int_t bufferSize = 1024; Char_t buffer[bufferSize]; Bool_t isXmlRpc = kFALSE; fXmlRpcResponse = ""; // -- loop for getting full xmlRPC response while(1) { Int_t bufferLength = 0; // -- loop for reading until end of line while (1) { iResult = socket->RecvRaw(&buffer[bufferLength], 1); if ( iResult < 0) { HLTError(Form("Error reading form socket.")); socket->Close(); return iResult; } // -- Checking for end of line if ( buffer[bufferLength] == 10 ) { buffer[bufferLength] = 0; break; } ++bufferLength; } TString bufferString(buffer); // -- Checking for start of XML response if ( bufferString.BeginsWith("<?xml") ) isXmlRpc = kTRUE; // -- Append the xml response if (isXmlRpc) { fXmlRpcResponse.Append(bufferString); } // -- Checking for end of XML response if( ! bufferString.CompareTo("</methodResponse>") ) break; } // -- close socket socket->Close(); return 0; } //################################################################################## Int_t AliHLTHOMERProxyHandler::ProcessXmlRpcResponse() { // see header file for class documentation Int_t iResult = 0; // -- Parse XML RPC Response // --------------------------- TDOMParser xmlParser; xmlParser.SetValidate(kFALSE); HLTDebug(Form("XMLResponse: %s",fXmlRpcResponse.Data())); iResult = xmlParser.ParseBuffer(fXmlRpcResponse.Data(), fXmlRpcResponse.Length()); if ( iResult < 0 ) { HLTError(Form("Parsing buffer with error: %s", xmlParser.GetParseCodeMessage(xmlParser.GetParseCode()) )); return iResult; } TXMLNode * node = xmlParser.GetXMLDocument()->GetRootNode()-> GetChildren()->GetChildren()->GetChildren()->GetChildren(); if ( strcmp( node->GetNodeName(), "string" ) ) { HLTError(Form("No node 'string' in XmlRpcResponse.")); return -1; } // -- Parse Content // ------------------ // -- Get Content TString xmlContent(node->GetText() ); HLTDebug(Form("XMLContent: %s",xmlContent.Data())); iResult = xmlParser.ParseBuffer(xmlContent.Data(), xmlContent.Length()); if ( iResult < 0 ) { HLTError(Form("Parsing buffer with error: %s", xmlParser.GetParseCodeMessage(xmlParser.GetParseCode()) )); return iResult; } if ( !xmlParser.GetXMLDocument()->GetRootNode()->HasChildren() ) { HLTWarning(Form("No Services active.")); return 1; } // -- Loop over all service nodes TXMLNode* serviceNode = xmlParser.GetXMLDocument()->GetRootNode()->GetChildren(); TXMLNode* prevServiceNode = NULL; do { prevServiceNode = serviceNode; // -- Add service to list iResult = AddService( serviceNode->GetChildren() ); if ( iResult > 0 ) { HLTWarning(Form("Incomplete Service not added.")); iResult = 0; } } while ( ( serviceNode = prevServiceNode->GetNextNode() ) && !iResult ); return iResult; } /* * --------------------------------------------------------------------------------- * Source Resolving - private * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::AddService(TXMLNode *innerNode) { // see header file for class documentation Int_t iResult = 0; HLTInfo(Form(">> New service")); TXMLNode* serviceNode = innerNode; // -- Loop over all service properties and // read them from the service tag // ----------------------------------------- TString hostname = ""; Int_t port = 0; TString dataType = ""; TString dataOrigin = ""; TString dataSpecification = ""; TXMLNode* prevInnerNode = NULL; // -- Retrieve hostname and port // ------------------------------- do { prevInnerNode = innerNode; if ( ! strcmp(innerNode->GetNodeName(), "text" ) ) continue; // -- hostname if ( ! strcmp( innerNode->GetNodeName(), "address") ) { HLTInfo(Form(" > %s ++ %s", innerNode->GetNodeName(), innerNode->GetText() )); hostname = innerNode->GetText(); } else if ( ! strcmp( innerNode->GetNodeName(), "port") ) { HLTInfo(Form(" > %s ++ %s", innerNode->GetNodeName(), innerNode->GetText() )); TString portS(innerNode->GetText()); if ( portS.IsDigit() ) port = portS.Atoi(); else { HLTError(Form("Port %s is not a digit.", portS.Data())); iResult = -1; } } } while ( ( innerNode = prevInnerNode->GetNextNode() ) && !iResult ); // -- Change hostame from service with proxy, if outside HLT if ( fRealm != kHLT && fRealm != kHLT+kHOMERRealmsMax ) hostname = fgkHOMERProxyNode[fRealm]; // -- Get Data Specifications from blocks // ---------------------------------------- do { prevInnerNode = serviceNode; if ( strcmp( serviceNode->GetNodeName(), "blocks") ) continue; TXMLNode* blocks = serviceNode->GetChildren(); if ( ! blocks ) { HLTError(Form("No blocks present")); return 1; } TXMLNode* blockNode = blocks->GetNextNode(); TXMLNode* prevBlockNode = NULL; if ( ! blockNode ) { HLTError(Form("No block present in the blocks tag")); return 1; } // -- blocks loop do { prevBlockNode = blockNode; if ( strcmp( blockNode->GetNodeName(), "block") ) continue; TXMLNode *dataNode = blockNode->GetChildren(); TXMLNode *prevDataNode = NULL; if ( ! dataNode ) { HLTError(Form("No data specification tags present in block tag.")); return 1; } // -- data spec loop do { prevDataNode = dataNode; if ( ! strcmp(dataNode->GetNodeName(), "text" ) ) continue; HLTInfo(Form(" %s ++ %s", dataNode->GetNodeName(), dataNode->GetText() )); if ( ! strcmp( dataNode->GetNodeName(), "dataorigin") ) { dataOrigin = dataNode->GetText(); } else if ( ! strcmp( dataNode->GetNodeName(), "datatype") ) { dataType = dataNode->GetText(); } else if ( ! strcmp( dataNode->GetNodeName(), "dataspecification") ) { dataSpecification = dataNode->GetText(); } } while ( ( dataNode = prevDataNode->GetNextNode() ) && !iResult ); // -- data spec loop // -- Check the service properties // --------------------------------- // -- Check for completeness of the source properties if ( hostname.IsNull() || !port || dataOrigin.IsNull() || dataType.IsNull() || dataSpecification.IsNull() ) { HLTWarning(Form("Service provides not all values:\n\thostname\t\t %s\n\tport\t\t\t %d\n\tdataorigin\t\t %s\n\tdatatype\t\t %s\n\tdataspecification\t 0x%08X", hostname.Data(), port, dataOrigin.Data(), dataType.Data(), dataSpecification.Atoi())); return 1; } // -- Create new source // ---------------------- AliHLTHOMERSourceDesc * source = new AliHLTHOMERSourceDesc(); source->SetService( hostname, port, dataOrigin, dataType, dataSpecification ); fSourceList->Add( source ); HLTInfo(Form( "New Source added : %s", source->GetSourceName().Data())); } while ( ( blockNode = prevBlockNode->GetNextNode() ) && !iResult ); // -- blocks loop } while ( ( serviceNode = prevInnerNode->GetNextNode() ) && !iResult ); return iResult; } <commit_msg>added new wireless ip to gpn list<commit_after>//-*- Mode: C++ -*- // $Id: AliHLTHOMERProxyHandler.cxx $ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Jochen Thaeder <thaeder@kip.uni-heidelberg.de> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTHOMERProxyHandler.cxx @author Jochen Thaeder @date @brief HOMER proxy handler for HomerManger */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #if __GNUC__>= 3 using namespace std; #endif #include "TDOMParser.h" #include "TSocket.h" #include "TSystem.h" // -- -- -- -- -- -- -- #include "AliHLTHOMERProxyHandler.h" // -- -- -- -- -- -- -- ClassImp(AliHLTHOMERProxyHandler) /* * --------------------------------------------------------------------------------- * Constructor / Destructor * --------------------------------------------------------------------------------- */ //################################################################################## AliHLTHOMERProxyHandler::AliHLTHOMERProxyHandler() : fRealm(kHLT), fXmlRpcResponse(""), fSourceList(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } //################################################################################## AliHLTHOMERProxyHandler::~AliHLTHOMERProxyHandler() { // see header file for class documentation } //################################################################################## Int_t AliHLTHOMERProxyHandler::Initialize() { // see header file for class documentation Int_t iResult = 0 ; IdentifyRealm(); return iResult; } /* * --------------------------------------------------------------------------------- * Source List - public * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::FillSourceList(TList *srcList) { // see header file for class documentation Int_t iResult = 0; fSourceList = srcList; iResult = RequestXmlRpcResponse(); if (!iResult) iResult = ProcessXmlRpcResponse(); if (iResult < 0) { HLTError(Form("Filling SourceList failed.")); } return iResult; } /* * --------------------------------------------------------------------------------- * Realms - private * --------------------------------------------------------------------------------- */ //################################################################################## const Char_t *AliHLTHOMERProxyHandler::fgkHOMERProxyNode[] = { "portal-dcs0.internal", "alihlt-dcs0.cern.ch", "alihlt-vobox0.cern.ch", "alihlt-gw0.kip.uni-heidelberg.de", "localhost", "portal-dcs1.internal", "alihlt-dcs1.cern.ch", "alihlt-vobox1.cern.ch", "alihlt-gw1.kip.uni-heidelberg.de", "localhost" }; //################################################################################## void AliHLTHOMERProxyHandler::IdentifyRealm() { // see header file for class documentation TString hostIP(gSystem->GetHostByName(gSystem->HostName()).GetHostAddress()); HLTInfo(hostIP.Data()); if ( hostIP.Contains("10.162.") ) fRealm = kHLT; else if ( hostIP.Contains("10.160.") || hostIP.Contains("10.161.") ) fRealm = kACR; else if ( hostIP.Contains("129.206.") ) fRealm = kKIP; else if ( hostIP.Contains("137.138") || hostIP.Contains("128.141") || hostIP.Contains("127.0.") || hostIP.Contains("192.168") ) fRealm = kGPN; else { fRealm = kLoc; } return; } /* * --------------------------------------------------------------------------------- * Proxy Communication - private * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::RequestXmlRpcResponse() { // see header file for class documentation Int_t iResult = 0; // -- open socket // ---------------- Int_t proxyPort = 19999; TSocket *socket = new TSocket(fgkHOMERProxyNode[fRealm], proxyPort); if ( ! socket->IsValid() ) { HLTWarning(Form("Failed to create socket to %s:%d,",fgkHOMERProxyNode[fRealm], proxyPort)); HLTWarning(Form("trying %s:%d now.", fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort)); socket = new TSocket(fgkHOMERProxyNode[fRealm+kHOMERRealmsMax], proxyPort); if ( ! socket->IsValid() ) { HLTError(Form("Failed to create socket to %s:%d and %s:%d.", fgkHOMERProxyNode[fRealm], proxyPort, fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort)); HLTWarning(Form("trying %s:%d now.", fgkHOMERProxyNode[kLoc],proxyPort)); socket = new TSocket(fgkHOMERProxyNode[kLoc], proxyPort); if ( ! socket->IsValid() ) { HLTError(Form("Failed to create socket to %s:%d , %s:%d and %s:%d.", fgkHOMERProxyNode[fRealm], proxyPort, fgkHOMERProxyNode[fRealm+kHOMERRealmsMax],proxyPort, fgkHOMERProxyNode[kLoc], proxyPort)); fRealm = -1; return -1; } else { fRealm = kLoc; } } else fRealm = fRealm+kHOMERRealmsMax; } // -- send request // ----------------- Char_t reqMsg[] = "POST / HTTP/1.1\r\n\ User-Agent: curl/7.18.0 (x86_64-pc-linux-gnu) libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.1\r\n\ Host: localhost:10000\r\n\ Accept: */*\r\n\ Content-type: text/xml\r\n\ Content-Length: 68\r\n\ \r\n<methodCall><methodName>getTcpDumpServices</methodName></methodCall>\r\n"; iResult = socket->SendRaw( reqMsg, strlen(reqMsg) ); if ( iResult < 1 || iResult != static_cast<Int_t>(strlen(reqMsg))) { HLTError(Form("Error sending! -- send length %d -- msg length %d.", iResult, static_cast<Int_t>(strlen(reqMsg)) )); socket->Close(); return iResult; } // -- receive answer // ------------------- const Int_t bufferSize = 1024; Char_t buffer[bufferSize]; Bool_t isXmlRpc = kFALSE; fXmlRpcResponse = ""; // -- loop for getting full xmlRPC response while(1) { Int_t bufferLength = 0; // -- loop for reading until end of line while (1) { iResult = socket->RecvRaw(&buffer[bufferLength], 1); if ( iResult < 0) { HLTError(Form("Error reading form socket.")); socket->Close(); return iResult; } // -- Checking for end of line if ( buffer[bufferLength] == 10 ) { buffer[bufferLength] = 0; break; } ++bufferLength; } TString bufferString(buffer); // -- Checking for start of XML response if ( bufferString.BeginsWith("<?xml") ) isXmlRpc = kTRUE; // -- Append the xml response if (isXmlRpc) { fXmlRpcResponse.Append(bufferString); } // -- Checking for end of XML response if( ! bufferString.CompareTo("</methodResponse>") ) break; } // -- close socket socket->Close(); return 0; } //################################################################################## Int_t AliHLTHOMERProxyHandler::ProcessXmlRpcResponse() { // see header file for class documentation Int_t iResult = 0; // -- Parse XML RPC Response // --------------------------- TDOMParser xmlParser; xmlParser.SetValidate(kFALSE); HLTDebug(Form("XMLResponse: %s",fXmlRpcResponse.Data())); iResult = xmlParser.ParseBuffer(fXmlRpcResponse.Data(), fXmlRpcResponse.Length()); if ( iResult < 0 ) { HLTError(Form("Parsing buffer with error: %s", xmlParser.GetParseCodeMessage(xmlParser.GetParseCode()) )); return iResult; } TXMLNode * node = xmlParser.GetXMLDocument()->GetRootNode()-> GetChildren()->GetChildren()->GetChildren()->GetChildren(); if ( strcmp( node->GetNodeName(), "string" ) ) { HLTError(Form("No node 'string' in XmlRpcResponse.")); return -1; } // -- Parse Content // ------------------ // -- Get Content TString xmlContent(node->GetText() ); HLTDebug(Form("XMLContent: %s",xmlContent.Data())); iResult = xmlParser.ParseBuffer(xmlContent.Data(), xmlContent.Length()); if ( iResult < 0 ) { HLTError(Form("Parsing buffer with error: %s", xmlParser.GetParseCodeMessage(xmlParser.GetParseCode()) )); return iResult; } if ( !xmlParser.GetXMLDocument()->GetRootNode()->HasChildren() ) { HLTWarning(Form("No Services active.")); return 1; } // -- Loop over all service nodes TXMLNode* serviceNode = xmlParser.GetXMLDocument()->GetRootNode()->GetChildren(); TXMLNode* prevServiceNode = NULL; do { prevServiceNode = serviceNode; // -- Add service to list iResult = AddService( serviceNode->GetChildren() ); if ( iResult > 0 ) { HLTWarning(Form("Incomplete Service not added.")); iResult = 0; } } while ( ( serviceNode = prevServiceNode->GetNextNode() ) && !iResult ); return iResult; } /* * --------------------------------------------------------------------------------- * Source Resolving - private * --------------------------------------------------------------------------------- */ //################################################################################## Int_t AliHLTHOMERProxyHandler::AddService(TXMLNode *innerNode) { // see header file for class documentation Int_t iResult = 0; HLTInfo(Form(">> New service")); TXMLNode* serviceNode = innerNode; // -- Loop over all service properties and // read them from the service tag // ----------------------------------------- TString hostname = ""; Int_t port = 0; TString dataType = ""; TString dataOrigin = ""; TString dataSpecification = ""; TXMLNode* prevInnerNode = NULL; // -- Retrieve hostname and port // ------------------------------- do { prevInnerNode = innerNode; if ( ! strcmp(innerNode->GetNodeName(), "text" ) ) continue; // -- hostname if ( ! strcmp( innerNode->GetNodeName(), "address") ) { HLTInfo(Form(" > %s ++ %s", innerNode->GetNodeName(), innerNode->GetText() )); hostname = innerNode->GetText(); } else if ( ! strcmp( innerNode->GetNodeName(), "port") ) { HLTInfo(Form(" > %s ++ %s", innerNode->GetNodeName(), innerNode->GetText() )); TString portS(innerNode->GetText()); if ( portS.IsDigit() ) port = portS.Atoi(); else { HLTError(Form("Port %s is not a digit.", portS.Data())); iResult = -1; } } } while ( ( innerNode = prevInnerNode->GetNextNode() ) && !iResult ); // -- Change hostame from service with proxy, if outside HLT if ( fRealm != kHLT && fRealm != kHLT+kHOMERRealmsMax ) hostname = fgkHOMERProxyNode[fRealm]; // -- Get Data Specifications from blocks // ---------------------------------------- do { prevInnerNode = serviceNode; if ( strcmp( serviceNode->GetNodeName(), "blocks") ) continue; TXMLNode* blocks = serviceNode->GetChildren(); if ( ! blocks ) { HLTError(Form("No blocks present")); return 1; } TXMLNode* blockNode = blocks->GetNextNode(); TXMLNode* prevBlockNode = NULL; if ( ! blockNode ) { HLTError(Form("No block present in the blocks tag")); return 1; } // -- blocks loop do { prevBlockNode = blockNode; if ( strcmp( blockNode->GetNodeName(), "block") ) continue; TXMLNode *dataNode = blockNode->GetChildren(); TXMLNode *prevDataNode = NULL; if ( ! dataNode ) { HLTError(Form("No data specification tags present in block tag.")); return 1; } // -- data spec loop do { prevDataNode = dataNode; if ( ! strcmp(dataNode->GetNodeName(), "text" ) ) continue; HLTInfo(Form(" %s ++ %s", dataNode->GetNodeName(), dataNode->GetText() )); if ( ! strcmp( dataNode->GetNodeName(), "dataorigin") ) { dataOrigin = dataNode->GetText(); } else if ( ! strcmp( dataNode->GetNodeName(), "datatype") ) { dataType = dataNode->GetText(); } else if ( ! strcmp( dataNode->GetNodeName(), "dataspecification") ) { dataSpecification = dataNode->GetText(); } } while ( ( dataNode = prevDataNode->GetNextNode() ) && !iResult ); // -- data spec loop // -- Check the service properties // --------------------------------- // -- Check for completeness of the source properties if ( hostname.IsNull() || !port || dataOrigin.IsNull() || dataType.IsNull() || dataSpecification.IsNull() ) { HLTWarning(Form("Service provides not all values:\n\thostname\t\t %s\n\tport\t\t\t %d\n\tdataorigin\t\t %s\n\tdatatype\t\t %s\n\tdataspecification\t 0x%08X", hostname.Data(), port, dataOrigin.Data(), dataType.Data(), dataSpecification.Atoi())); return 1; } // -- Create new source // ---------------------- AliHLTHOMERSourceDesc * source = new AliHLTHOMERSourceDesc(); source->SetService( hostname, port, dataOrigin, dataType, dataSpecification ); fSourceList->Add( source ); HLTInfo(Form( "New Source added : %s", source->GetSourceName().Data())); } while ( ( blockNode = prevBlockNode->GetNextNode() ) && !iResult ); // -- blocks loop } while ( ( serviceNode = prevInnerNode->GetNextNode() ) && !iResult ); return iResult; } <|endoftext|>