commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
c72b6912649ea85a7f91ef50a4e0a2ec89aab908
Testing/mitkSliceNavigationControllerTest.cpp
Testing/mitkSliceNavigationControllerTest.cpp
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkSliceNavigationController.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include "mitkTimeSlicedGeometry.h" #include <vnl/vnl_quaternion.h> #include <vnl/vnl_quaternion.txx> #include <fstream> bool operator==(const mitk::Geometry3D & left, const mitk::Geometry3D & right) { mitk::BoundingBox::BoundsArrayType leftbounds, rightbounds; leftbounds =left.GetBounds(); rightbounds=right.GetBounds(); unsigned int i; for(i=0;i<6;++i) if(mitk::Equal(leftbounds[i],rightbounds[i])==false) return false; const mitk::Geometry3D::TransformType::MatrixType & leftmatrix = left.GetIndexToWorldTransform()->GetMatrix(); const mitk::Geometry3D::TransformType::MatrixType & rightmatrix = right.GetIndexToWorldTransform()->GetMatrix(); unsigned int j; for(i=0;i<3;++i) { const mitk::Geometry3D::TransformType::MatrixType::ValueType* leftvector = leftmatrix[i]; const mitk::Geometry3D::TransformType::MatrixType::ValueType* rightvector = rightmatrix[i]; for(j=0;j<3;++j) if(mitk::Equal(leftvector[i],rightvector[i])==false) return false; } const mitk::Geometry3D::TransformType::OffsetType & leftoffset = left.GetIndexToWorldTransform()->GetOffset(); const mitk::Geometry3D::TransformType::OffsetType & rightoffset = right.GetIndexToWorldTransform()->GetOffset(); for(i=0;i<3;++i) if(mitk::Equal(leftoffset[i],rightoffset[i])==false) return false; return true; } int compareGeometry(const mitk::Geometry3D & geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { std::cout << "Testing width, height and thickness (in units): "; if((mitk::Equal(geometry.GetExtent(0),width)==false) || (mitk::Equal(geometry.GetExtent(1),height)==false) || (mitk::Equal(geometry.GetExtent(2),numSlices)==false) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing width, height and thickness (in mm): "; if((mitk::Equal(geometry.GetExtentInMM(0),widthInMM)==false) || (mitk::Equal(geometry.GetExtentInMM(1),heightInMM)==false) || (mitk::Equal(geometry.GetExtentInMM(2),thicknessInMM)==false) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing GetAxisVector(): "; std::cout << "dir=0 "; mitk::Vector3D dv; dv=right; dv.Normalize(); dv*=widthInMM; if((mitk::Equal(geometry.GetAxisVector(0), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"; std::cout << ", dir=1 "; dv=bottom; dv.Normalize(); dv*=heightInMM; if((mitk::Equal(geometry.GetAxisVector(1), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"; std::cout << ", dir=2 "; dv=normal; dv.Normalize(); dv*=thicknessInMM; if((mitk::Equal(geometry.GetAxisVector(2), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing offset: "; if((mitk::Equal(geometry.GetCornerPoint(0),cornerpoint0)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; } int testGeometry(const mitk::Geometry3D * geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { int result=EXIT_FAILURE; std::cout << "Comparing GetCornerPoint(0) of Geometry3D with provided cornerpoint0: "; if(mitk::Equal(geometry->GetCornerPoint(0), cornerpoint0)==false) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating and initializing a SliceNavigationController with the Geometry3D: "; mitk::SliceNavigationController::Pointer sliceCtrl = new mitk::SliceNavigationController(); sliceCtrl->SetInputWorldGeometry(geometry); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Transversal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Transversal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; mitk::Point3D transversalcornerpoint0; transversalcornerpoint0 = cornerpoint0+bottom+normal*(numSlices-1); //really -1? result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, height, numSlices, widthInMM, heightInMM, thicknessInMM*numSlices, transversalcornerpoint0, right, bottom*(-1.0), normal*(-1.0)); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Frontal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Frontal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, numSlices, height, widthInMM, thicknessInMM*numSlices, heightInMM, cornerpoint0, right, normal, bottom); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Sagittal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Sagittal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "<<std::endl; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), height, numSlices, width, heightInMM, thicknessInMM*numSlices, widthInMM, cornerpoint0, bottom, normal, right); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; } int mitkSliceNavigationControllerTest(int argc, char* argv[]) { int result=EXIT_FAILURE; std::cout << "Creating and initializing a PlaneGeometry: "; mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; // mitk::FillVector3D(origin, 0, 0, thicknessInMM*0.5); mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.Get_vnl_vector(), bottom.Get_vnl_vector(), &spacing); planegeometry->SetOrigin(origin); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating and initializing a SlicedGeometry3D with the PlaneGeometry: "; mitk::SlicedGeometry3D::Pointer slicedgeometry = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 5; slicedgeometry->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a Geometry3D with the same extent as the SlicedGeometry3D: "; mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry->GetIndexToWorldTransform()); std::cout<<"[PASSED]"<<std::endl; mitk::Point3D cornerpoint0; cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; mitk::BoundingBox::BoundsArrayType bounds = geometry->GetBounds(); mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); transform->SetMatrix(geometry->GetIndexToWorldTransform()->GetMatrix()); mitk::BoundingBox::Pointer boundingbox = geometry->CalculateBoundingBoxRelativeToTransform(transform); geometry->SetBounds(boundingbox->GetBounds()); cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout << "Changing the IndexToWorldTransform of the geometry to a rotated version by SetIndexToWorldTransform() (keep cornerpoint0): "; transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = planegeometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::VnlVector axis(3); mitk::FillVector3D(axis, 1.0, 1.0, 1.0); axis.normalize(); vnl_quaternion<mitk::ScalarType> rotation(axis, 0.123); vnlmatrix = rotation.rotation_matrix_transpose()*vnlmatrix; mitk::Matrix3D matrix; matrix = vnlmatrix; transform->SetMatrix(matrix); transform->SetOffset(cornerpoint0.GetVectorFromOrigin()); right.Set_vnl_vector( rotation.rotation_matrix_transpose()*right.Get_vnl_vector() ); bottom.Set_vnl_vector(rotation.rotation_matrix_transpose()*bottom.Get_vnl_vector()); normal.Set_vnl_vector(rotation.rotation_matrix_transpose()*normal.Get_vnl_vector()); geometry->SetIndexToWorldTransform(transform); std::cout<<"[PASSED]"<<std::endl; cornerpoint0 = geometry->GetCornerPoint(0); result = testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; }
/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkSliceNavigationController.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include "mitkTimeSlicedGeometry.h" #include <vnl/vnl_quaternion.h> #include <vnl/vnl_quaternion.txx> #include <fstream> bool operator==(const mitk::Geometry3D & left, const mitk::Geometry3D & right) { mitk::BoundingBox::BoundsArrayType leftbounds, rightbounds; leftbounds =left.GetBounds(); rightbounds=right.GetBounds(); unsigned int i; for(i=0;i<6;++i) if(mitk::Equal(leftbounds[i],rightbounds[i])==false) return false; const mitk::Geometry3D::TransformType::MatrixType & leftmatrix = left.GetIndexToWorldTransform()->GetMatrix(); const mitk::Geometry3D::TransformType::MatrixType & rightmatrix = right.GetIndexToWorldTransform()->GetMatrix(); unsigned int j; for(i=0;i<3;++i) { const mitk::Geometry3D::TransformType::MatrixType::ValueType* leftvector = leftmatrix[i]; const mitk::Geometry3D::TransformType::MatrixType::ValueType* rightvector = rightmatrix[i]; for(j=0;j<3;++j) if(mitk::Equal(leftvector[i],rightvector[i])==false) return false; } const mitk::Geometry3D::TransformType::OffsetType & leftoffset = left.GetIndexToWorldTransform()->GetOffset(); const mitk::Geometry3D::TransformType::OffsetType & rightoffset = right.GetIndexToWorldTransform()->GetOffset(); for(i=0;i<3;++i) if(mitk::Equal(leftoffset[i],rightoffset[i])==false) return false; return true; } int compareGeometry(const mitk::Geometry3D & geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { std::cout << "Testing width, height and thickness (in units): "; if((mitk::Equal(geometry.GetExtent(0),width)==false) || (mitk::Equal(geometry.GetExtent(1),height)==false) || (mitk::Equal(geometry.GetExtent(2),numSlices)==false) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing width, height and thickness (in mm): "; if((mitk::Equal(geometry.GetExtentInMM(0),widthInMM)==false) || (mitk::Equal(geometry.GetExtentInMM(1),heightInMM)==false) || (mitk::Equal(geometry.GetExtentInMM(2),thicknessInMM)==false) ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing GetAxisVector(): "; std::cout << "dir=0 "; mitk::Vector3D dv; dv=right; dv.Normalize(); dv*=widthInMM; if((mitk::Equal(geometry.GetAxisVector(0), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"; std::cout << ", dir=1 "; dv=bottom; dv.Normalize(); dv*=heightInMM; if((mitk::Equal(geometry.GetAxisVector(1), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"; std::cout << ", dir=2 "; dv=normal; dv.Normalize(); dv*=thicknessInMM; if((mitk::Equal(geometry.GetAxisVector(2), dv)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing offset: "; if((mitk::Equal(geometry.GetCornerPoint(0),cornerpoint0)==false)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; } int testGeometry(const mitk::Geometry3D * geometry, const mitk::ScalarType& width, const mitk::ScalarType& height, const mitk::ScalarType& numSlices, const mitk::ScalarType& widthInMM, const mitk::ScalarType& heightInMM, const mitk::ScalarType& thicknessInMM, const mitk::Point3D& cornerpoint0, const mitk::Vector3D& right, const mitk::Vector3D& bottom, const mitk::Vector3D& normal) { int result=EXIT_FAILURE; std::cout << "Comparing GetCornerPoint(0) of Geometry3D with provided cornerpoint0: "; if(mitk::Equal(geometry->GetCornerPoint(0), cornerpoint0)==false) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating and initializing a SliceNavigationController with the Geometry3D: "; mitk::SliceNavigationController::Pointer sliceCtrl = new mitk::SliceNavigationController(); sliceCtrl->SetInputWorldGeometry(geometry); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Transversal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Transversal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; mitk::Point3D transversalcornerpoint0; transversalcornerpoint0 = cornerpoint0+bottom+normal*(numSlices-1+0.5); //really -1? result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, height, numSlices, widthInMM, heightInMM, thicknessInMM*numSlices, transversalcornerpoint0, right, bottom*(-1.0), normal*(-1.0)); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Frontal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Frontal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; mitk::Point3D frontalcornerpoint0; frontalcornerpoint0 = cornerpoint0+geometry->GetAxisVector(1)*(+0.5/geometry->GetExtent(1)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), width, numSlices, height, widthInMM, thicknessInMM*numSlices, heightInMM, frontalcornerpoint0, right, normal, bottom); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing SetViewDirection(mitk::SliceNavigationController::Sagittal): "; sliceCtrl->SetViewDirection(mitk::SliceNavigationController::Sagittal); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing Update(): "<<std::endl; sliceCtrl->Update(); std::cout<<"[PASSED]"<<std::endl; std::cout << "Testing result of CreatedWorldGeometry(): "; mitk::Point3D sagittalcornerpoint0; sagittalcornerpoint0 = cornerpoint0+geometry->GetAxisVector(0)*(+0.5/geometry->GetExtent(0)); result = compareGeometry(*sliceCtrl->GetCreatedWorldGeometry(), height, numSlices, width, heightInMM, thicknessInMM*numSlices, widthInMM, sagittalcornerpoint0, bottom, normal, right); if(result!=EXIT_SUCCESS) { std::cout<<"[FAILED]"<<std::endl; return result; } std::cout<<"[PASSED]"<<std::endl; return EXIT_SUCCESS; } int mitkSliceNavigationControllerTest(int argc, char* argv[]) { int result=EXIT_FAILURE; std::cout << "Creating and initializing a PlaneGeometry: "; mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, bottom, normal; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.5; // mitk::FillVector3D(origin, 0, 0, thicknessInMM*0.5); mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::Vector3D spacing; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.Get_vnl_vector(), bottom.Get_vnl_vector(), &spacing); planegeometry->SetOrigin(origin); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating and initializing a SlicedGeometry3D with the PlaneGeometry: "; mitk::SlicedGeometry3D::Pointer slicedgeometry = mitk::SlicedGeometry3D::New(); unsigned int numSlices = 5; slicedgeometry->InitializeEvenlySpaced(planegeometry, thicknessInMM, numSlices, false); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a Geometry3D with the same extent as the SlicedGeometry3D: "; mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetBounds(slicedgeometry->GetBounds()); geometry->SetIndexToWorldTransform(slicedgeometry->GetIndexToWorldTransform()); std::cout<<"[PASSED]"<<std::endl; mitk::Point3D cornerpoint0; cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; mitk::BoundingBox::BoundsArrayType bounds = geometry->GetBounds(); mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); transform->SetMatrix(geometry->GetIndexToWorldTransform()->GetMatrix()); mitk::BoundingBox::Pointer boundingbox = geometry->CalculateBoundingBoxRelativeToTransform(transform); geometry->SetBounds(boundingbox->GetBounds()); cornerpoint0 = geometry->GetCornerPoint(0); result=testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout << "Changing the IndexToWorldTransform of the geometry to a rotated version by SetIndexToWorldTransform() (keep cornerpoint0): "; transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = planegeometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::VnlVector axis(3); mitk::FillVector3D(axis, 1.0, 1.0, 1.0); axis.normalize(); vnl_quaternion<mitk::ScalarType> rotation(axis, 0.123); vnlmatrix = rotation.rotation_matrix_transpose()*vnlmatrix; mitk::Matrix3D matrix; matrix = vnlmatrix; transform->SetMatrix(matrix); transform->SetOffset(cornerpoint0.GetVectorFromOrigin()); right.Set_vnl_vector( rotation.rotation_matrix_transpose()*right.Get_vnl_vector() ); bottom.Set_vnl_vector(rotation.rotation_matrix_transpose()*bottom.Get_vnl_vector()); normal.Set_vnl_vector(rotation.rotation_matrix_transpose()*normal.Get_vnl_vector()); geometry->SetIndexToWorldTransform(transform); std::cout<<"[PASSED]"<<std::endl; cornerpoint0 = geometry->GetCornerPoint(0); result = testGeometry(geometry, width, height, numSlices, widthInMM, heightInMM, thicknessInMM, cornerpoint0, right, bottom, normal); if(result!=EXIT_SUCCESS) return result; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; }
test changed according to image alignment fix
CHG: test changed according to image alignment fix
C++
bsd-3-clause
RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,NifTK/MITK,MITK/MITK,iwegner/MITK,MITK/MITK,danielknorr/MITK,nocnokneo/MITK,fmilano/mitk,rfloca/MITK,fmilano/mitk,iwegner/MITK,rfloca/MITK,nocnokneo/MITK,nocnokneo/MITK,danielknorr/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,rfloca/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,fmilano/mitk,RabadanLab/MITKats,danielknorr/MITK,nocnokneo/MITK,RabadanLab/MITKats,rfloca/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,fmilano/mitk,danielknorr/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,NifTK/MITK,danielknorr/MITK,nocnokneo/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,NifTK/MITK,nocnokneo/MITK,nocnokneo/MITK,RabadanLab/MITKats,MITK/MITK,iwegner/MITK,rfloca/MITK,fmilano/mitk,rfloca/MITK,NifTK/MITK,rfloca/MITK,iwegner/MITK,NifTK/MITK
64c41917c16ec70bc66e1f3e8aeb1d9cf02d5862
contrib/libHilbert/include/Hilbert/Algorithm.hpp
contrib/libHilbert/include/Hilbert/Algorithm.hpp
/* * Copyright (C) 2006-2014 Chris Hamilton <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ALGORITHM_HPP_ #define _ALGORITHM_HPP_ #include "Hilbert/Common.hpp" #include "Hilbert/BigBitVec.hpp" #include "Hilbert/GetLocation.hpp" #include "Hilbert/SetLocation.hpp" #include "Hilbert/GetBits.hpp" #include "Hilbert/SetBits.hpp" #include "Hilbert/GrayCodeRank.hpp" #include <string.h> // Templated Hilbert functions. // P - is the class used to represent each dimension // of a multidimensional point. // H - is the class used to represent the point as a Hilbert // index. // I - is the class used to represent interim variables. // Needs to have as many bits as there are dimensions. // // In general, each of P,H,I should be a FixBitVec if they // fit in that fixed precision. Otherwise, use a BigBitVec. // Whatever you use, they must all be of consistent underlying // storage types. // The dimension across which the Hilbert curve travels // principally. // D0 is d + 1, where d is the actual dimension you want to // walk across. // MUST HAVE 0 <= D0 < n #define D0 1 namespace Hilbert { // 'Transforms' a point. template<class I> H_INLINE void transform( const I &e, int d, int n, I &a ) { a ^= e; a.rotr( d, n );//#D d+1, n ); return; } // Inverse 'transforms' a point. template<class I> H_INLINE void transformInv( const I &e, int d, int n, I &a ) { a.rotl( d, n );//#D d+1, n ); a ^= e; return; } // Update for method 1 (GrayCodeInv in the loop) template<class I> H_INLINE void update1( const I &l, const I &t, const I &w, int n, I &e, int &d ) { assert( 0 <= d && d < n ); e = l; e.toggleBit( d ); //#D d == n-1 ? 0 : d+1 ); // Update direction d += 1 + t.fsb(); if ( d >= n ) d -= n; if ( d >= n ) d -= n; assert( 0 <= d && d < n ); if ( ! (w.rack() & 1) ) e.toggleBit( d == 0 ? n-1 : d-1 ); //#D d ); return; } // Update for method 2 (GrayCodeInv out of loop) template<class I> H_INLINE void update2( const I &l, const I &t, const I & /* w */, int n, I &e, int &d ) { assert( 0 <= d && d < n ); e = l; e.toggleBit( d );//#D d == n-1 ? 0 : d+1 ); // Update direction d += 1 + t.fsb(); if ( d >= n ) d -= n; if ( d >= n ) d -= n; assert( 0 <= d && d < n ); return; } template <class P,class H,class I> H_INLINE void _coordsToIndex( const P *p, int m, int n, H &h, int *ds = NULL // #HACK ) { I e(n), l(n), t(n), w(n); int d, i; int ho = m*n; // Initialize e.zero(); d = D0; l.zero(); h.zero(); int r, b; BBV_MODSPLIT(r,b,n-1); FBV_UINT bm = (1<<b); // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // #HACK if ( ds ) ds[i] = d; // Get corner of sub-hypercube where point lies. getLocation<P,I>(p,n,i,l); // Mirror and reflect the location. // t = T_{(e,d)}(l) t = l; transform<I>(e,d,n,t); w = t; if ( i < m-1 ) w.racks()[r] ^= bm; // Concatenate to the index. ho -= n; setBits<H,I>(h,n,ho,w); // Update the entry point and direction. update2<I>(l,t,w,n,e,d); } h.grayCodeInv(); return; } // This is wrapper to the basic Hilbert curve index // calculation function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes h is big enough for the output (n*m bits!) template<class P,class H> H_INLINE void coordsToIndex( const P *p, // [in ] point int m, // [in ] precision of each dimension in bits int n, // [in ] number of dimensions H &h // [out] Hilbert index ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _coordsToIndex<P,H,CFixBitVec>(p,m,n,h); // Otherwise, they must be BigBitVecs. else _coordsToIndex<P,H,CBigBitVec>(p,m,n,h); return; } template <class P,class H,class I> H_INLINE void _indexToCoords( P *p, int m, int n, const H &h ) { I e(n), l(n), t(n), w(n); int d, i, j, ho; // Initialize e.zero(); d = D0; l.zero(); for ( j = 0; j < n; j++ ) p[j].zero(); ho = m*n; // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // Get the Hilbert index bits ho -= n; getBits<H,I>(h,n,ho,w); // t = GrayCode(w) t = w; t.grayCode(); // Reverse the transform // l = T^{-1}_{(e,d)}(t) l = t; transformInv<I>(e,d,n,l); // Distribute these bits // to the coordinates. setLocation<P,I>(p,n,i,l); // Update the entry point and direction. update1<I>(l,t,w,n,e,d); } return; } // This is wrapper to the basic Hilbert curve inverse // index function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes each entry of p is big enough to hold the // appropriate variable. template<class P,class H> H_INLINE void indexToCoords( P *p, // [out] point int m, // [in ] precision of each dimension in bits int n, // [in ] number of dimensions const H &h // [out] Hilbert index ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _indexToCoords<P,H,CFixBitVec>(p,m,n,h); // Otherwise, they must be BigBitVecs. else _indexToCoords<P,H,CBigBitVec>(p,m,n,h); return; } template <class P,class HC,class I> H_INLINE void _coordsToCompactIndex( const P *p, const int *ms, int n, HC &hc, int M = 0, int m = 0 ) { int i, mn; int *ds; // Get total precision and max precision // if not supplied if ( M == 0 || m == 0 ) { M = m = 0; for ( i = 0; i < n; i++ ) { if ( ms[i] > m ) m = ms[i]; M += ms[i]; } } mn = m*n; // If we could avoid allocation altogether (ie: have a // fixed buffer allocated on the stack) then this increases // speed by a bit (4% when n=4, m=20) ds = new int [ m ]; if ( mn > FBV_BITS ) { CBigBitVec h(mn); _coordsToIndex<P,CBigBitVec,I>(p,m,n,h,ds); compactIndex<CBigBitVec,HC>(ms,ds,n,m,h,hc); } else { CFixBitVec h; _coordsToIndex<P,CFixBitVec,I>(p,m,n,h,ds); compactIndex<CFixBitVec,HC>(ms,ds,n,m,h,hc); } delete [] ds; return; } // This is wrapper to the basic Hilbert curve index // calculation function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes h is big enough for the output (n*m bits!) template<class P,class HC> H_INLINE void coordsToCompactIndex( const P *p, // [in ] point const int *ms,// [in ] precision of each dimension in bits int n, // [in ] number of dimensions HC &hc, // [out] Hilbert index int M = 0, int m = 0 ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _coordsToCompactIndex<P,HC,CFixBitVec>(p,ms,n,hc,M,m); // Otherwise, they must be BigBitVecs. else _coordsToCompactIndex<P,HC,CBigBitVec>(p,ms,n,hc,M,m); return; } template <class P,class HC,class I> H_INLINE void _compactIndexToCoords( P *p, const int *ms, int n, const HC &hc, int M = 0, int m = 0 ) { I e(n), l(n), t(n), w(n), r(n), mask(n), ptrn(n); int d, i, j, b; // Get total precision and max precision // if not supplied if ( M == 0 || m == 0 ) { M = m = 0; for ( i = 0; i < n; i++ ) { if ( ms[i] > m ) m = ms[i]; M += ms[i]; } } // Initialize e.zero(); d = D0; l.zero(); for ( j = 0; j < n; j++ ) p[j].zero(); // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // Get the mask and ptrn extractMask<I>(ms,n,d,i,mask,b); ptrn = e; ptrn.rotr(d,n);//#D ptrn.Rotr(d+1,n); // Get the Hilbert index bits M -= b; r.zero(); // GetBits doesn't do this getBits<HC,I>(hc,b,M,r); // w = GrayCodeRankInv(r) // t = GrayCode(w) grayCodeRankInv<I>(mask,ptrn,r,n,b,t,w); // Reverse the transform // l = T^{-1}_{(e,d)}(t) l = t; transformInv<I>(e,d,n,l); // Distribute these bits // to the coordinates. setLocation<P,I>(p,n,i,l); // Update the entry point and direction. update1<I>(l,t,w,n,e,d); } return; } // This is wrapper to the basic Hilbert curve inverse // index function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes each entry of p is big enough to hold the // appropriate variable. template<class P,class HC> H_INLINE void compactIndexToCoords( P *p, // [out] point const int *ms,// [in ] precision of each dimension in bits int n, // [in ] number of dimensions const HC &hc, // [out] Hilbert index int M = 0, int m = 0 ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _compactIndexToCoords<P,HC,CFixBitVec>(p,ms,n,hc,M,m); // Otherwise, they must be BigBitVecs. else _compactIndexToCoords<P,HC,CBigBitVec>(p,ms,n,hc,M,m); return; } } #endif
/* * Copyright (C) 2006-2014 Chris Hamilton <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ALGORITHM_HPP_ #define _ALGORITHM_HPP_ #include "Hilbert/Common.hpp" #include "Hilbert/BigBitVec.hpp" #include "Hilbert/GetLocation.hpp" #include "Hilbert/SetLocation.hpp" #include "Hilbert/GetBits.hpp" #include "Hilbert/SetBits.hpp" #include "Hilbert/GrayCodeRank.hpp" #include <string.h> // Templated Hilbert functions. // P - is the class used to represent each dimension // of a multidimensional point. // H - is the class used to represent the point as a Hilbert // index. // I - is the class used to represent interim variables. // Needs to have as many bits as there are dimensions. // // In general, each of P,H,I should be a FixBitVec if they // fit in that fixed precision. Otherwise, use a BigBitVec. // Whatever you use, they must all be of consistent underlying // storage types. // The dimension across which the Hilbert curve travels // principally. // D0 is d + 1, where d is the actual dimension you want to // walk across. // MUST HAVE 0 <= D0 < n #define D0 1 namespace Hilbert { // 'Transforms' a point. template<class I> H_INLINE void transform( const I &e, int d, int n, I &a ) { a ^= e; a.rotr( d, n );//#D d+1, n ); return; } // Inverse 'transforms' a point. template<class I> H_INLINE void transformInv( const I &e, int d, int n, I &a ) { a.rotl( d, n );//#D d+1, n ); a ^= e; return; } // Update for method 1 (GrayCodeInv in the loop) template<class I> H_INLINE void update1( const I &l, const I &t, const I &w, int n, I &e, int &d ) { assert( 0 <= d && d < n ); e = l; e.toggleBit( d ); //#D d == n-1 ? 0 : d+1 ); // Update direction d += 1 + t.fsb(); if ( d >= n ) d -= n; if ( d >= n ) d -= n; assert( 0 <= d && d < n ); if ( ! (w.rack() & 1) ) e.toggleBit( d == 0 ? n-1 : d-1 ); //#D d ); return; } // Update for method 2 (GrayCodeInv out of loop) template<class I> H_INLINE void update2( const I &l, const I &t, const I & /* w */, int n, I &e, int &d ) { assert( 0 <= d && d < n ); e = l; e.toggleBit( d );//#D d == n-1 ? 0 : d+1 ); // Update direction d += 1 + t.fsb(); if ( d >= n ) d -= n; if ( d >= n ) d -= n; assert( 0 <= d && d < n ); return; } template <class P,class H,class I> H_INLINE void _coordsToIndex( const P *p, int m, int n, H &h, int *ds = NULL // #HACK ) { I e(n), l(n), t(n), w(n); int d, i; int ho = m*n; // Initialize e.zero(); d = D0; l.zero(); h.zero(); int r, b; BBV_MODSPLIT(r,b,n-1); FBV_UINT bm = (1<<b); // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // #HACK if ( ds ) ds[i] = d; // Get corner of sub-hypercube where point lies. getLocation<P,I>(p,n,i,l); // Mirror and reflect the location. // t = T_{(e,d)}(l) t = l; transform<I>(e,d,n,t); w = t; if ( i < m-1 ) w.racks()[r] ^= bm; // Concatenate to the index. ho -= n; setBits<H,I>(h,n,ho,w); // Update the entry point and direction. update2<I>(l,t,w,n,e,d); } h.grayCodeInv(); return; } // This is wrapper to the basic Hilbert curve index // calculation function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes h is big enough for the output (n*m bits!) template<class P,class H> H_INLINE void coordsToIndex( const P *p, // [in ] point int m, // [in ] precision of each dimension in bits int n, // [in ] number of dimensions H &h // [out] Hilbert index ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _coordsToIndex<P,H,CFixBitVec>(p,m,n,h); // Otherwise, they must be BigBitVecs. else _coordsToIndex<P,H,CBigBitVec>(p,m,n,h); return; } template <class P,class H,class I> H_INLINE void _indexToCoords( P *p, int m, int n, const H &h ) { I e(n), l(n), t(n), w(n); int d, i, j, ho; // Initialize e.zero(); d = D0; l.zero(); for ( j = 0; j < n; j++ ) p[j].zero(); ho = m*n; // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // Get the Hilbert index bits ho -= n; getBits<H,I>(h,n,ho,w); // t = GrayCode(w) t = w; t.grayCode(); // Reverse the transform // l = T^{-1}_{(e,d)}(t) l = t; transformInv<I>(e,d,n,l); // Distribute these bits // to the coordinates. setLocation<P,I>(p,n,i,l); // Update the entry point and direction. update1<I>(l,t,w,n,e,d); } return; } // This is wrapper to the basic Hilbert curve inverse // index function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes each entry of p is big enough to hold the // appropriate variable. template<class P,class H> H_INLINE void indexToCoords(P *p, // [out] point int m, // [in ] precision of each dimension in bits int n, // [in ] number of dimensions const H &h) // [in ] Hilbert index { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _indexToCoords<P,H,CFixBitVec>(p,m,n,h); // Otherwise, they must be BigBitVecs. else _indexToCoords<P,H,CBigBitVec>(p,m,n,h); return; } template <class P,class HC,class I> H_INLINE void _coordsToCompactIndex( const P *p, const int *ms, int n, HC &hc, int M = 0, int m = 0 ) { int i, mn; int *ds; // Get total precision and max precision // if not supplied if ( M == 0 || m == 0 ) { M = m = 0; for ( i = 0; i < n; i++ ) { if ( ms[i] > m ) m = ms[i]; M += ms[i]; } } mn = m*n; // If we could avoid allocation altogether (ie: have a // fixed buffer allocated on the stack) then this increases // speed by a bit (4% when n=4, m=20) ds = new int [ m ]; if ( mn > FBV_BITS ) { CBigBitVec h(mn); _coordsToIndex<P,CBigBitVec,I>(p,m,n,h,ds); compactIndex<CBigBitVec,HC>(ms,ds,n,m,h,hc); } else { CFixBitVec h; _coordsToIndex<P,CFixBitVec,I>(p,m,n,h,ds); compactIndex<CFixBitVec,HC>(ms,ds,n,m,h,hc); } delete [] ds; return; } // This is wrapper to the basic Hilbert curve index // calculation function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes h is big enough for the output (n*m bits!) template<class P,class HC> H_INLINE void coordsToCompactIndex( const P *p, // [in ] point const int *ms,// [in ] precision of each dimension in bits int n, // [in ] number of dimensions HC &hc, // [out] Hilbert index int M = 0, int m = 0 ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _coordsToCompactIndex<P,HC,CFixBitVec>(p,ms,n,hc,M,m); // Otherwise, they must be BigBitVecs. else _coordsToCompactIndex<P,HC,CBigBitVec>(p,ms,n,hc,M,m); return; } template <class P,class HC,class I> H_INLINE void _compactIndexToCoords( P *p, const int *ms, int n, const HC &hc, int M = 0, int m = 0 ) { I e(n), l(n), t(n), w(n), r(n), mask(n), ptrn(n); int d, i, j, b; // Get total precision and max precision // if not supplied if ( M == 0 || m == 0 ) { M = m = 0; for ( i = 0; i < n; i++ ) { if ( ms[i] > m ) m = ms[i]; M += ms[i]; } } // Initialize e.zero(); d = D0; l.zero(); for ( j = 0; j < n; j++ ) p[j].zero(); // Work from MSB to LSB for ( i = m-1; i >= 0; i-- ) { // Get the mask and ptrn extractMask<I>(ms,n,d,i,mask,b); ptrn = e; ptrn.rotr(d,n);//#D ptrn.Rotr(d+1,n); // Get the Hilbert index bits M -= b; r.zero(); // GetBits doesn't do this getBits<HC,I>(hc,b,M,r); // w = GrayCodeRankInv(r) // t = GrayCode(w) grayCodeRankInv<I>(mask,ptrn,r,n,b,t,w); // Reverse the transform // l = T^{-1}_{(e,d)}(t) l = t; transformInv<I>(e,d,n,l); // Distribute these bits // to the coordinates. setLocation<P,I>(p,n,i,l); // Update the entry point and direction. update1<I>(l,t,w,n,e,d); } return; } // This is wrapper to the basic Hilbert curve inverse // index function. It will support fixed or // arbitrary precision, templated. Depending on the // number of dimensions, it will use the most efficient // representation for interim variables. // Assumes each entry of p is big enough to hold the // appropriate variable. template<class P,class HC> H_INLINE void compactIndexToCoords( P *p, // [out] point const int *ms,// [in ] precision of each dimension in bits int n, // [in ] number of dimensions const HC &hc, // [out] Hilbert index int M = 0, int m = 0 ) { // Intermediate variables will fit in fixed width? if ( n <= FBV_BITS ) _compactIndexToCoords<P,HC,CFixBitVec>(p,ms,n,hc,M,m); // Otherwise, they must be BigBitVecs. else _compactIndexToCoords<P,HC,CBigBitVec>(p,ms,n,hc,M,m); return; } } #endif
Fix small documentation issue in libHilbert.
Fix small documentation issue in libHilbert.
C++
lgpl-2.1
jiangwen84/libmesh,jwpeterson/libmesh,pbauman/libmesh,friedmud/libmesh,salazardetroya/libmesh,karpeev/libmesh,pbauman/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,karpeev/libmesh,benkirk/libmesh,balborian/libmesh,jiangwen84/libmesh,pbauman/libmesh,aeslaughter/libmesh,friedmud/libmesh,roystgnr/libmesh,balborian/libmesh,svallaghe/libmesh,balborian/libmesh,hrittich/libmesh,cahaynes/libmesh,jwpeterson/libmesh,svallaghe/libmesh,dschwen/libmesh,jiangwen84/libmesh,90jrong/libmesh,dmcdougall/libmesh,friedmud/libmesh,Mbewu/libmesh,pbauman/libmesh,svallaghe/libmesh,friedmud/libmesh,jwpeterson/libmesh,salazardetroya/libmesh,giorgiobornia/libmesh,90jrong/libmesh,libMesh/libmesh,Mbewu/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,friedmud/libmesh,cahaynes/libmesh,permcody/libmesh,dknez/libmesh,coreymbryant/libmesh,karpeev/libmesh,capitalaslash/libmesh,dknez/libmesh,permcody/libmesh,dmcdougall/libmesh,balborian/libmesh,coreymbryant/libmesh,hrittich/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,pbauman/libmesh,jwpeterson/libmesh,90jrong/libmesh,hrittich/libmesh,coreymbryant/libmesh,permcody/libmesh,cahaynes/libmesh,salazardetroya/libmesh,dknez/libmesh,dschwen/libmesh,friedmud/libmesh,roystgnr/libmesh,capitalaslash/libmesh,balborian/libmesh,vikramvgarg/libmesh,jiangwen84/libmesh,dschwen/libmesh,permcody/libmesh,BalticPinguin/libmesh,Mbewu/libmesh,hrittich/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,aeslaughter/libmesh,dmcdougall/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,roystgnr/libmesh,coreymbryant/libmesh,Mbewu/libmesh,90jrong/libmesh,dmcdougall/libmesh,balborian/libmesh,Mbewu/libmesh,svallaghe/libmesh,balborian/libmesh,dmcdougall/libmesh,karpeev/libmesh,dmcdougall/libmesh,dknez/libmesh,benkirk/libmesh,benkirk/libmesh,roystgnr/libmesh,capitalaslash/libmesh,libMesh/libmesh,90jrong/libmesh,permcody/libmesh,salazardetroya/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,giorgiobornia/libmesh,90jrong/libmesh,karpeev/libmesh,cahaynes/libmesh,balborian/libmesh,pbauman/libmesh,giorgiobornia/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,roystgnr/libmesh,aeslaughter/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,Mbewu/libmesh,dknez/libmesh,dknez/libmesh,karpeev/libmesh,dschwen/libmesh,pbauman/libmesh,capitalaslash/libmesh,hrittich/libmesh,cahaynes/libmesh,giorgiobornia/libmesh,svallaghe/libmesh,aeslaughter/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,dknez/libmesh,balborian/libmesh,jiangwen84/libmesh,90jrong/libmesh,cahaynes/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,hrittich/libmesh,Mbewu/libmesh,cahaynes/libmesh,dschwen/libmesh,friedmud/libmesh,pbauman/libmesh,friedmud/libmesh,salazardetroya/libmesh,roystgnr/libmesh,BalticPinguin/libmesh,benkirk/libmesh,benkirk/libmesh,dmcdougall/libmesh,hrittich/libmesh,Mbewu/libmesh,roystgnr/libmesh,svallaghe/libmesh,jiangwen84/libmesh,karpeev/libmesh,aeslaughter/libmesh,permcody/libmesh,BalticPinguin/libmesh,dschwen/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,libMesh/libmesh,benkirk/libmesh,libMesh/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,vikramvgarg/libmesh,dmcdougall/libmesh,pbauman/libmesh,permcody/libmesh,libMesh/libmesh,salazardetroya/libmesh,dschwen/libmesh,jiangwen84/libmesh,aeslaughter/libmesh,capitalaslash/libmesh,dschwen/libmesh,jwpeterson/libmesh,BalticPinguin/libmesh,permcody/libmesh,libMesh/libmesh,aeslaughter/libmesh,jiangwen84/libmesh,giorgiobornia/libmesh,friedmud/libmesh,giorgiobornia/libmesh,benkirk/libmesh,benkirk/libmesh,libMesh/libmesh,BalticPinguin/libmesh,balborian/libmesh,hrittich/libmesh,Mbewu/libmesh,cahaynes/libmesh,90jrong/libmesh,benkirk/libmesh,salazardetroya/libmesh,svallaghe/libmesh,hrittich/libmesh,90jrong/libmesh,libMesh/libmesh,roystgnr/libmesh,salazardetroya/libmesh,svallaghe/libmesh,dknez/libmesh,karpeev/libmesh
8aea252ff4fa2123c91fc0c07df7fdb03a6efda3
src/uoj2254.cpp
src/uoj2254.cpp
#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> //#include <string> #include <stack> #include <queue> using namespace std; typedef char[21] string; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ cin >>temptime>>templv>>temp; } else return 0; }while(temptime<=now); } int pop(){ if(lv4.size()>0){ cout<<lv4.front()<<endl; lv4.pop(); return 4; } if(lv3.size()>0){ cout<<lv3.front()<<endl; lv3.pop(); return 3; } if(lv2.size()>0){ cout<<lv2.front()<<endl; lv2.pop(); return 2; } if(lv1.size()>0){ cout<<lv1.front()<<endl; lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum * 5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }
#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <iostream> //#include <string> #include <stack> #include <queue> using namespace std; typedef char string[21]; queue<string> lv1; queue<string> lv2; queue<string> lv3; queue<string> lv4; string temp; int templv; int temptime=0; int usernum; int users=0; int read(int now){ if(now < temptime || users>usernum) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; case 4: lv4.push(temp);break; } } users++; if(users<=usernum){ cin >>temptime>>templv>>temp; } else return 0; }while(temptime<=now); } int pop(){ if(lv4.size()>0){ cout<<lv4.front()<<endl; lv4.pop(); return 4; } if(lv3.size()>0){ cout<<lv3.front()<<endl; lv3.pop(); return 3; } if(lv2.size()>0){ cout<<lv2.front()<<endl; lv2.pop(); return 2; } if(lv1.size()>0){ cout<<lv1.front()<<endl; lv1.pop(); return 1; } return 0; } int main(int argc, char const *argv[]) { int time; scanf("%d%d",&usernum,&time); for (int i = 0; i < time && i< usernum * 5; ++i) { read(i); //cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl; if(i%5==0) pop(); } //while(pop()){} return 0; }
update uoj2254
update uoj2254
C++
mit
czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj
eb3aac5c25d816759257d0c79568f173f0e056d2
webkit/tools/test_shell/test_shell_main.cc
webkit/tools/test_shell/test_shell_main.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Creates an instance of the test_shell. #include <stdlib.h> // required by _set_abort_behavior #include <windows.h> #include <commctrl.h> #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_util.h" #include "base/gfx/native_theme.h" #include "base/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/resource_util.h" #include "base/stack_container.h" #include "base/stats_table.h" #include "base/string_util.h" #include "base/trace_event.h" #include "breakpad/src/client/windows/handler/exception_handler.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/url_request/url_request_context.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" // This is only set for layout tests. static wchar_t g_currentTestName[MAX_PATH]; namespace { // StatsTable initialization parameters. static wchar_t* kStatsFile = L"testshell"; static int kStatsFileThreads = 20; static int kStatsFileCounters = 200; std::string GetDataResource(HMODULE module, int resource_id) { void* data_ptr; size_t data_size; return base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size) ? std::string(static_cast<char*>(data_ptr), data_size) : std::string(); } // This is called indirectly by the network layer to access resources. std::string NetResourceProvider(int key) { return GetDataResource(::GetModuleHandle(NULL), key); } void SetCurrentTestName(char* path) { char* lastSlash = strrchr(path, '/'); if (lastSlash) { ++lastSlash; } else { lastSlash = path; } wcscpy_s(g_currentTestName, arraysize(g_currentTestName), UTF8ToWide(lastSlash).c_str()); } bool MinidumpCallback(const wchar_t *dumpPath, const wchar_t *minidumpID, void *context, EXCEPTION_POINTERS *exinfo, MDRawAssertionInfo *assertion, bool succeeded) { // Warning: Don't use the heap in this function. It may be corrupted. if (!g_currentTestName[0]) return false; // Try to rename the minidump file to include the crashed test's name. // StackString uses the stack but overflows onto the heap. But we don't // care too much about being completely correct here, since most crashes // will be happening on developers' machines where they have debuggers. StackWString<MAX_PATH*2> origPath; origPath->append(dumpPath); origPath->push_back(file_util::kPathSeparator); origPath->append(minidumpID); origPath->append(L".dmp"); StackWString<MAX_PATH*2> newPath; newPath->append(dumpPath); newPath->push_back(file_util::kPathSeparator); newPath->append(g_currentTestName); newPath->append(L"-"); newPath->append(minidumpID); newPath->append(L".dmp"); // May use the heap, but oh well. If this fails, we'll just have the // original dump file lying around. _wrename(origPath->c_str(), newPath->c_str()); return false; } } // namespace int main(int argc, char* argv[]) { process_util::EnableTerminationOnHeapCorruption(); #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; CommandLine parsed_command_line; if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) MessageBox(NULL, L"attach to me?", L"test_shell", MB_OK); //webkit_glue::SetLayoutTestMode(true); // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = (GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0) || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); TestShell::InitLogging(suppress_error_dialogs); // Suppress abort message in v8 library in debugging mode. // V8 calls abort() when it hits assertion errors. if (suppress_error_dialogs) { _set_abort_behavior(0, _WRITE_ABORT_MSG); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); // Make the selection of network stacks early on before any consumers try to // issue HTTP requests. if (parsed_command_line.HasSwitch(test_shell::kUseNewHttp)) net::HttpNetworkLayer::UseWinHttp(false); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); std::wstring cache_path = parsed_command_line.GetSwitchValue(test_shell::kCacheDir); if (cache_path.empty()) { PathService::Get(base::DIR_EXE, &cache_path); file_util::AppendToPath(&cache_path, L"cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(NetResourceProvider); INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); bool interactive = !layout_test_mode; TestShell::InitializeTestShell(interactive); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. if (!interactive) gfx::NativeTheme::instance()->DisableTheming(); if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str())); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Initialize global strings TestShell::RegisterWindowClass(); // Treat the first loose value as the initial URL to open. std::wstring uri; // Default to a homepage if we're interactive. if (interactive) { PathService::Get(base::DIR_SOURCE_ROOT, &uri); file_util::AppendToPath(&uri, L"webkit"); file_util::AppendToPath(&uri, L"data"); file_util::AppendToPath(&uri, L"test_shell"); file_util::AppendToPath(&uri, L"index.html"); } if (parsed_command_line.GetLooseValueCount() > 0) { CommandLine::LooseValueIterator iter( parsed_command_line.GetLooseValuesBegin()); uri = *iter; } if (parsed_command_line.HasSwitch(test_shell::kCrashDumps)) { std::wstring dir( parsed_command_line.GetSwitchValue(test_shell::kCrashDumps)); new google_breakpad::ExceptionHandler(dir, 0, &MinidumpCallback, 0, true); } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. CommandLine::AppendSwitch(&js_flags, L"expose-gc"); webkit_glue::SetJavaScriptFlags(js_flags); // load and initialize the stats table. StatsTable *table = new StatsTable(kStatsFile, kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(uri, &shell)) { if (record_mode || playback_mode) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); // Tell webkit as well. webkit_glue::SetRecordPlaybackMode(true); } shell->Show(shell->webView(), NEW_WINDOW); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { std::wstring script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); file_util::AppendToPath(&script_path, L"script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { webkit_glue::SetLayoutTestMode(true); // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (uri.length() == 0) { // Watch stdin for URLs. char filenameBuffer[2048]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { char *newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; SetCurrentTestName(filenameBuffer); if (!TestShell::RunFileTest(filenameBuffer, params)) break; } } else { TestShell::RunFileTest(WideToUTF8(uri).c_str(), params); } shell->CallJSGC(); shell->CallJSGC(); if (shell) delete shell; } else { MessageLoop::current()->Run(); } // Flush any remaining messages. This ensures that any accumulated // Task objects get destroyed before we exit, which avoids noise in // purify leak-test results. MessageLoop::current()->RunAllPending(); if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif return 0; }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Creates an instance of the test_shell. #include <stdlib.h> // required by _set_abort_behavior #include <windows.h> #include <commctrl.h> #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_util.h" #include "base/gfx/native_theme.h" #include "base/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/resource_util.h" #include "base/stack_container.h" #include "base/stats_table.h" #include "base/string_util.h" #include "base/trace_event.h" #include "breakpad/src/client/windows/handler/exception_handler.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/url_request/url_request_context.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" // This is only set for layout tests. static wchar_t g_currentTestName[MAX_PATH]; namespace { // StatsTable initialization parameters. static wchar_t* kStatsFile = L"testshell"; static int kStatsFileThreads = 20; static int kStatsFileCounters = 200; std::string GetDataResource(HMODULE module, int resource_id) { void* data_ptr; size_t data_size; return base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size) ? std::string(static_cast<char*>(data_ptr), data_size) : std::string(); } // This is called indirectly by the network layer to access resources. std::string NetResourceProvider(int key) { return GetDataResource(::GetModuleHandle(NULL), key); } void SetCurrentTestName(char* path) { char* lastSlash = strrchr(path, '/'); if (lastSlash) { ++lastSlash; } else { lastSlash = path; } wcscpy_s(g_currentTestName, arraysize(g_currentTestName), UTF8ToWide(lastSlash).c_str()); } bool MinidumpCallback(const wchar_t *dumpPath, const wchar_t *minidumpID, void *context, EXCEPTION_POINTERS *exinfo, MDRawAssertionInfo *assertion, bool succeeded) { // Warning: Don't use the heap in this function. It may be corrupted. if (!g_currentTestName[0]) return false; // Try to rename the minidump file to include the crashed test's name. // StackString uses the stack but overflows onto the heap. But we don't // care too much about being completely correct here, since most crashes // will be happening on developers' machines where they have debuggers. StackWString<MAX_PATH*2> origPath; origPath->append(dumpPath); origPath->push_back(file_util::kPathSeparator); origPath->append(minidumpID); origPath->append(L".dmp"); StackWString<MAX_PATH*2> newPath; newPath->append(dumpPath); newPath->push_back(file_util::kPathSeparator); newPath->append(g_currentTestName); newPath->append(L"-"); newPath->append(minidumpID); newPath->append(L".dmp"); // May use the heap, but oh well. If this fails, we'll just have the // original dump file lying around. _wrename(origPath->c_str(), newPath->c_str()); return false; } } // namespace int main(int argc, char* argv[]) { process_util::EnableTerminationOnHeapCorruption(); #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; CommandLine parsed_command_line; if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) MessageBox(NULL, L"attach to me?", L"test_shell", MB_OK); //webkit_glue::SetLayoutTestMode(true); // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = (GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0) || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); TestShell::InitLogging(suppress_error_dialogs); // Suppress abort message in v8 library in debugging mode. // V8 calls abort() when it hits assertion errors. if (suppress_error_dialogs) { _set_abort_behavior(0, _WRITE_ABORT_MSG); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); // Make the selection of network stacks early on before any consumers try to // issue HTTP requests. if (parsed_command_line.HasSwitch(test_shell::kUseNewHttp)) net::HttpNetworkLayer::UseWinHttp(false); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); std::wstring cache_path = parsed_command_line.GetSwitchValue(test_shell::kCacheDir); if (cache_path.empty()) { PathService::Get(base::DIR_EXE, &cache_path); file_util::AppendToPath(&cache_path, L"cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(NetResourceProvider); INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); bool interactive = !layout_test_mode; TestShell::InitializeTestShell(interactive); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. if (!interactive) gfx::NativeTheme::instance()->DisableTheming(); if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str())); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Initialize global strings TestShell::RegisterWindowClass(); // Treat the first loose value as the initial URL to open. std::wstring uri; // Default to a homepage if we're interactive. if (interactive) { PathService::Get(base::DIR_SOURCE_ROOT, &uri); file_util::AppendToPath(&uri, L"webkit"); file_util::AppendToPath(&uri, L"data"); file_util::AppendToPath(&uri, L"test_shell"); file_util::AppendToPath(&uri, L"index.html"); } if (parsed_command_line.GetLooseValueCount() > 0) { CommandLine::LooseValueIterator iter( parsed_command_line.GetLooseValuesBegin()); uri = *iter; } if (parsed_command_line.HasSwitch(test_shell::kCrashDumps)) { std::wstring dir( parsed_command_line.GetSwitchValue(test_shell::kCrashDumps)); new google_breakpad::ExceptionHandler(dir, 0, &MinidumpCallback, 0, true); } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. CommandLine::AppendSwitch(&js_flags, L"expose-gc"); webkit_glue::SetJavaScriptFlags(js_flags); // load and initialize the stats table. StatsTable *table = new StatsTable(kStatsFile, kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(uri, &shell)) { if (record_mode || playback_mode) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); // Tell webkit as well. webkit_glue::SetRecordPlaybackMode(true); } shell->Show(shell->webView(), NEW_WINDOW); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { std::wstring script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); file_util::AppendToPath(&script_path, L"script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { webkit_glue::SetLayoutTestMode(true); // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (uri.length() == 0) { // Watch stdin for URLs. char filenameBuffer[2048]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { char *newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; SetCurrentTestName(filenameBuffer); if (!TestShell::RunFileTest(filenameBuffer, params)) break; } } else { TestShell::RunFileTest(WideToUTF8(uri).c_str(), params); } shell->CallJSGC(); shell->CallJSGC(); if (shell) delete shell; } else { MessageLoop::current()->Run(); } // Flush any remaining messages. This ensures that any accumulated // Task objects get destroyed before we exit, which avoids noise in // purify leak-test results. MessageLoop::current()->RunAllPending(); if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif return 0; }
Fix indentation. Review URL: http://codereview.chromium.org/5636
Fix indentation. Review URL: http://codereview.chromium.org/5636 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@2816 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
9ac4d6fcbd36fce6dcc9b069bdf248e38aef35fe
webkit/tools/test_shell/test_shell_main.cc
webkit/tools/test_shell/test_shell_main.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stats_table.h" #include "base/sys_info.h" #include "base/trace_event.h" #include "base/utf_string_conversions.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/http/http_cache.h" #include "net/socket/ssl_test_util.h" #include "net/url_request/url_request_context.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/extensions/v8/gc_extension.h" #include "webkit/extensions/v8/heap_profiler_extension.h" #include "webkit/extensions/v8/playback_extension.h" #include "webkit/extensions/v8/profiler_extension.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" #include "webkit/tools/test_shell/test_shell_webkit_init.h" #if defined(OS_WIN) #pragma warning(disable: 4996) #endif static const size_t kPathBufSize = 2048; using WebKit::WebScriptController; namespace { // StatsTable initialization parameters. const char* const kStatsFilePrefix = "testshell_"; int kStatsFileThreads = 20; int kStatsFileCounters = 200; void RemoveSharedMemoryFile(std::string& filename) { // Stats uses SharedMemory under the hood. On posix, this results in a file // on disk. #if defined(OS_POSIX) base::SharedMemory memory; memory.Delete(UTF8ToWide(filename)); #endif } } // namespace int main(int argc, char* argv[]) { base::EnableInProcessStackDumping(); base::EnableTerminationOnHeapCorruption(); // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; TestShellPlatformDelegate::PreflightArgs(&argc, &argv); CommandLine::Init(argc, argv); const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); TestShellPlatformDelegate platform(parsed_command_line); if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) TestShell::ShowStartupDebuggingDialog(); if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) { exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1); } // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = ( base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme); bool classic_theme = parsed_command_line.HasSwitch(test_shell::kClassicTheme); #if defined(OS_WIN) bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) || parsed_command_line.HasSwitch(test_shell::kGenericTheme); #else // Stop compiler warnings about unused variables. ux_theme = ux_theme; #endif bool enable_gp_fault_error_box = false; enable_gp_fault_error_box = parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox); bool allow_external_pages = parsed_command_line.HasSwitch(test_shell::kAllowExternalPages); TestShell::InitLogging(suppress_error_dialogs, layout_test_mode, enable_gp_fault_error_box); // Initialize WebKit for this scope. TestShellWebKitInit test_shell_webkit_init(layout_test_mode); // Suppress abort message in v8 library in debugging mode (but not // actually under a debugger). V8 calls abort() when it hits // assertion errors. if (suppress_error_dialogs) { platform.SuppressErrorReporting(); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; // This is a special mode where JS helps the browser implement // playback/record mode. Generally, in this mode, some functions // of client-side randomness are removed. For example, in // this mode Math.random() and Date.getTime() may not return // values which vary. bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); FilePath cache_path = parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir); // If the cache_path is empty and it's layout_test_mode, leave it empty // so we use an in-memory cache. This makes running multiple test_shells // in parallel less flaky. if (cache_path.empty() && !layout_test_mode) { PathService::Get(base::DIR_EXE, &cache_path); cache_path = cache_path.AppendASCII("cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode, layout_test_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(TestShell::NetResourceProvider); // On Linux and Mac, load the test root certificate. net::TestServerLauncher ssl_util; ssl_util.LoadTestRootCert(); platform.InitializeGUI(); TestShell::InitializeTestShell(layout_test_mode, allow_external_pages); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. #if defined(OS_WIN) TestShellWebTheme::Engine engine; #endif if (classic_theme) platform.SelectUnifiedTheme(); #if defined(OS_WIN) if (generic_theme) test_shell_webkit_init.SetThemeEngine(&engine); #endif if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str()))); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Treat the first loose value as the initial URL to open. GURL starting_url; // Default to a homepage if we're interactive. if (!layout_test_mode) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("webkit"); path = path.AppendASCII("data"); path = path.AppendASCII("test_shell"); path = path.AppendASCII("index.html"); starting_url = net::FilePathToFileURL(path); } std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues(); if (loose_values.size() > 0) { GURL url(WideToUTF16Hack(loose_values[0])); if (url.is_valid()) { starting_url = url; } else { // Treat as a file path starting_url = net::FilePathToFileURL(FilePath::FromWStringHack(loose_values[0])); } } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. js_flags += L" --expose-gc"; webkit_glue::SetJavaScriptFlags(js_flags); // Expose GCController to JavaScript. WebScriptController::registerExtension(extensions_v8::GCExtension::Get()); if (parsed_command_line.HasSwitch(test_shell::kProfiler)) { WebScriptController::registerExtension( extensions_v8::ProfilerExtension::Get()); } if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) { WebScriptController::registerExtension( extensions_v8::HeapProfilerExtension::Get()); } // Load and initialize the stats table. Attempt to construct a somewhat // unique name to isolate separate instances from each other. // truncate the random # to 32 bits for the benefit of Mac OS X, to // avoid tripping over its maximum shared memory segment name length std::string stats_filename = kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL); RemoveSharedMemoryFile(stats_filename); StatsTable *table = new StatsTable(stats_filename, kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(starting_url, &shell)) { if (record_mode || playback_mode) { platform.SetWindowPositionForRecording(shell); WebScriptController::registerExtension( extensions_v8::PlaybackExtension::Get()); } shell->Show(WebKit::WebNavigationPolicyNewWindow); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { FilePath script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); script_path = script_path.AppendASCII("script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (!starting_url.is_valid()) { // Watch stdin for URLs. char filenameBuffer[kPathBufSize]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { // When running layout tests we pass new line separated // tests to TestShell. Each line is a space separated list // of filename, timeout and expected pixel hash. The timeout // and the pixel hash are optional. char* newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; params.test_url = strtok(filenameBuffer, " "); // Set the current path to the directory that contains the test // files. This is because certain test file may use the relative // path. GURL test_url(params.test_url); FilePath test_file_path; net::FileURLToFilePath(test_url, &test_file_path); file_util::SetCurrentDirectory(test_file_path.DirName()); int old_timeout_ms = TestShell::GetLayoutTestTimeout(); char* timeout = strtok(NULL, " "); if (timeout) { TestShell::SetFileTestTimeout(atoi(timeout)); char* pixel_hash = strtok(NULL, " "); if (pixel_hash) params.pixel_hash = pixel_hash; } if (!TestShell::RunFileTest(params)) break; TestShell::SetFileTestTimeout(old_timeout_ms); } } else { // TODO(ojan): Provide a way for run-singly tests to pass // in a hash and then set params.pixel_hash here. params.test_url = WideToUTF8(loose_values[0]); TestShell::RunFileTest(params); } shell->CallJSGC(); shell->CallJSGC(); // When we finish the last test, cleanup the LayoutTestController. // It may have references to not-yet-cleaned up windows. By // cleaning up here we help purify reports. shell->ResetTestController(); // Flush any remaining messages before we kill ourselves. // http://code.google.com/p/chromium/issues/detail?id=9500 MessageLoop::current()->RunAllPending(); } else { MessageLoop::current()->Run(); } if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; RemoveSharedMemoryFile(stats_filename); return 0; }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/at_exit.h" #include "base/basictypes.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/i18n/icu_util.h" #include "base/memory_debug.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/rand_util.h" #include "base/stats_table.h" #include "base/sys_info.h" #include "base/trace_event.h" #include "base/utf_string_conversions.h" #include "net/base/cookie_monster.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/http/http_cache.h" #include "net/socket/ssl_test_util.h" #include "net/url_request/url_request_context.h" #include "third_party/WebKit/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/extensions/v8/gc_extension.h" #include "webkit/extensions/v8/heap_profiler_extension.h" #include "webkit/extensions/v8/playback_extension.h" #include "webkit/extensions/v8/profiler_extension.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" #include "webkit/tools/test_shell/test_shell_request_context.h" #include "webkit/tools/test_shell/test_shell_switches.h" #include "webkit/tools/test_shell/test_shell_webkit_init.h" #if defined(OS_WIN) #pragma warning(disable: 4996) #endif static const size_t kPathBufSize = 2048; using WebKit::WebScriptController; namespace { // StatsTable initialization parameters. const char* const kStatsFilePrefix = "testshell_"; int kStatsFileThreads = 20; int kStatsFileCounters = 200; void RemoveSharedMemoryFile(std::string& filename) { // Stats uses SharedMemory under the hood. On posix, this results in a file // on disk. #if defined(OS_POSIX) base::SharedMemory memory; memory.Delete(UTF8ToWide(filename)); #endif } } // namespace int main(int argc, char* argv[]) { base::EnableInProcessStackDumping(); base::EnableTerminationOnHeapCorruption(); // Some tests may use base::Singleton<>, thus we need to instanciate // the AtExitManager or else we will leak objects. base::AtExitManager at_exit_manager; TestShellPlatformDelegate::PreflightArgs(&argc, &argv); CommandLine::Init(argc, argv); const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); TestShellPlatformDelegate platform(parsed_command_line); if (parsed_command_line.HasSwitch(test_shell::kStartupDialog)) TestShell::ShowStartupDebuggingDialog(); if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) { exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1); } // Allocate a message loop for this thread. Although it is not used // directly, its constructor sets up some necessary state. MessageLoopForUI main_message_loop; bool suppress_error_dialogs = ( base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") || parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) || parsed_command_line.HasSwitch(test_shell::kLayoutTests)); bool layout_test_mode = parsed_command_line.HasSwitch(test_shell::kLayoutTests); bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme); bool classic_theme = parsed_command_line.HasSwitch(test_shell::kClassicTheme); #if defined(OS_WIN) bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) || parsed_command_line.HasSwitch(test_shell::kGenericTheme); #else // Stop compiler warnings about unused variables. ux_theme = ux_theme; #endif bool enable_gp_fault_error_box = false; enable_gp_fault_error_box = parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox); bool allow_external_pages = parsed_command_line.HasSwitch(test_shell::kAllowExternalPages); TestShell::InitLogging(suppress_error_dialogs, layout_test_mode, enable_gp_fault_error_box); // Initialize WebKit for this scope. TestShellWebKitInit test_shell_webkit_init(layout_test_mode); // Suppress abort message in v8 library in debugging mode (but not // actually under a debugger). V8 calls abort() when it hits // assertion errors. if (suppress_error_dialogs) { platform.SuppressErrorReporting(); } if (parsed_command_line.HasSwitch(test_shell::kEnableTracing)) base::TraceLog::StartTracing(); net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL; // This is a special mode where JS helps the browser implement // playback/record mode. Generally, in this mode, some functions // of client-side randomness are removed. For example, in // this mode Math.random() and Date.getTime() may not return // values which vary. bool playback_mode = parsed_command_line.HasSwitch(test_shell::kPlaybackMode); bool record_mode = parsed_command_line.HasSwitch(test_shell::kRecordMode); if (playback_mode) cache_mode = net::HttpCache::PLAYBACK; else if (record_mode) cache_mode = net::HttpCache::RECORD; if (layout_test_mode || parsed_command_line.HasSwitch(test_shell::kEnableFileCookies)) net::CookieMonster::EnableFileScheme(); FilePath cache_path = parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir); // If the cache_path is empty and it's layout_test_mode, leave it empty // so we use an in-memory cache. This makes running multiple test_shells // in parallel less flaky. if (cache_path.empty() && !layout_test_mode) { PathService::Get(base::DIR_EXE, &cache_path); cache_path = cache_path.AppendASCII("cache"); } // Initializing with a default context, which means no on-disk cookie DB, // and no support for directory listings. SimpleResourceLoaderBridge::Init( new TestShellRequestContext(cache_path, cache_mode, layout_test_mode)); // Load ICU data tables icu_util::Initialize(); // Config the network module so it has access to a limited set of resources. net::NetModule::SetResourceProvider(TestShell::NetResourceProvider); // On Linux and Mac, load the test root certificate. net::TestServerLauncher ssl_util; ssl_util.LoadTestRootCert(); platform.InitializeGUI(); TestShell::InitializeTestShell(layout_test_mode, allow_external_pages); if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows)) TestShell::SetAllowScriptsToCloseWindows(); // Disable user themes for layout tests so pixel tests are consistent. #if defined(OS_WIN) TestShellWebTheme::Engine engine; #endif if (classic_theme) platform.SelectUnifiedTheme(); #if defined(OS_WIN) if (generic_theme) test_shell_webkit_init.SetThemeEngine(&engine); #endif if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) { const std::wstring timeout_str = parsed_command_line.GetSwitchValue( test_shell::kTestShellTimeOut); int timeout_ms = static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str()))); if (timeout_ms > 0) TestShell::SetFileTestTimeout(timeout_ms); } // Treat the first loose value as the initial URL to open. GURL starting_url; // Default to a homepage if we're interactive. if (!layout_test_mode) { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("webkit"); path = path.AppendASCII("data"); path = path.AppendASCII("test_shell"); path = path.AppendASCII("index.html"); starting_url = net::FilePathToFileURL(path); } std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues(); if (loose_values.size() > 0) { GURL url(WideToUTF16Hack(loose_values[0])); if (url.is_valid()) { starting_url = url; } else { // Treat as a relative file path. FilePath path = FilePath::FromWStringHack(loose_values[0]); file_util::AbsolutePath(&path); starting_url = net::FilePathToFileURL(path); } } std::wstring js_flags = parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags); // Test shell always exposes the GC. js_flags += L" --expose-gc"; webkit_glue::SetJavaScriptFlags(js_flags); // Expose GCController to JavaScript. WebScriptController::registerExtension(extensions_v8::GCExtension::Get()); if (parsed_command_line.HasSwitch(test_shell::kProfiler)) { WebScriptController::registerExtension( extensions_v8::ProfilerExtension::Get()); } if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) { WebScriptController::registerExtension( extensions_v8::HeapProfilerExtension::Get()); } // Load and initialize the stats table. Attempt to construct a somewhat // unique name to isolate separate instances from each other. // truncate the random # to 32 bits for the benefit of Mac OS X, to // avoid tripping over its maximum shared memory segment name length std::string stats_filename = kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL); RemoveSharedMemoryFile(stats_filename); StatsTable *table = new StatsTable(stats_filename, kStatsFileThreads, kStatsFileCounters); StatsTable::set_current(table); TestShell* shell; if (TestShell::CreateNewWindow(starting_url, &shell)) { if (record_mode || playback_mode) { platform.SetWindowPositionForRecording(shell); WebScriptController::registerExtension( extensions_v8::PlaybackExtension::Get()); } shell->Show(WebKit::WebNavigationPolicyNewWindow); if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable)) shell->DumpStatsTableOnExit(); bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents); if ((record_mode || playback_mode) && !no_events) { FilePath script_path = cache_path; // Create the cache directory in case it doesn't exist. file_util::CreateDirectory(cache_path); script_path = script_path.AppendASCII("script.log"); if (record_mode) base::EventRecorder::current()->StartRecording(script_path); if (playback_mode) base::EventRecorder::current()->StartPlayback(script_path); } if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) { base::MemoryDebug::SetMemoryInUseEnabled(true); // Dump all in use memory at startup base::MemoryDebug::DumpAllMemoryInUse(); } // See if we need to run the tests. if (layout_test_mode) { // Set up for the kind of test requested. TestShell::TestParams params; if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) { // The pixel test flag also gives the image file name to use. params.dump_pixels = true; params.pixel_file_name = parsed_command_line.GetSwitchValue( test_shell::kDumpPixels); if (params.pixel_file_name.size() == 0) { fprintf(stderr, "No file specified for pixel tests"); exit(1); } } if (parsed_command_line.HasSwitch(test_shell::kNoTree)) { params.dump_tree = false; } if (!starting_url.is_valid()) { // Watch stdin for URLs. char filenameBuffer[kPathBufSize]; while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) { // When running layout tests we pass new line separated // tests to TestShell. Each line is a space separated list // of filename, timeout and expected pixel hash. The timeout // and the pixel hash are optional. char* newLine = strchr(filenameBuffer, '\n'); if (newLine) *newLine = '\0'; if (!*filenameBuffer) continue; params.test_url = strtok(filenameBuffer, " "); // Set the current path to the directory that contains the test // files. This is because certain test file may use the relative // path. GURL test_url(params.test_url); FilePath test_file_path; net::FileURLToFilePath(test_url, &test_file_path); file_util::SetCurrentDirectory(test_file_path.DirName()); int old_timeout_ms = TestShell::GetLayoutTestTimeout(); char* timeout = strtok(NULL, " "); if (timeout) { TestShell::SetFileTestTimeout(atoi(timeout)); char* pixel_hash = strtok(NULL, " "); if (pixel_hash) params.pixel_hash = pixel_hash; } if (!TestShell::RunFileTest(params)) break; TestShell::SetFileTestTimeout(old_timeout_ms); } } else { // TODO(ojan): Provide a way for run-singly tests to pass // in a hash and then set params.pixel_hash here. params.test_url = WideToUTF8(loose_values[0]); TestShell::RunFileTest(params); } shell->CallJSGC(); shell->CallJSGC(); // When we finish the last test, cleanup the LayoutTestController. // It may have references to not-yet-cleaned up windows. By // cleaning up here we help purify reports. shell->ResetTestController(); // Flush any remaining messages before we kill ourselves. // http://code.google.com/p/chromium/issues/detail?id=9500 MessageLoop::current()->RunAllPending(); } else { MessageLoop::current()->Run(); } if (record_mode) base::EventRecorder::current()->StopRecording(); if (playback_mode) base::EventRecorder::current()->StopPlayback(); } TestShell::ShutdownTestShell(); TestShell::CleanupLogging(); // Tear down shared StatsTable; prevents unit_tests from leaking it. StatsTable::set_current(NULL); delete table; RemoveSharedMemoryFile(stats_filename); return 0; }
allow relative paths on the command line
test_shell: allow relative paths on the command line This makes "./out/Debug/test_shell path/to/file.html" do the right thing. In theory I should use URLFixerUpper but that's deep inside chrome/browser/; this is simple enough anyway. Review URL: http://codereview.chromium.org/1711024 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@45977 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium
041d5b39749a832524af1bbc005c2b3c528118fa
src/uvw/lib.hpp
src/uvw/lib.hpp
#pragma once #include <utility> #include <memory> #include <string> #include <uv.h> #include "loop.hpp" namespace uvw { namespace details { template<typename T> struct IsFunc: std::false_type { }; template<typename R, typename... A> struct IsFunc<R(A...)>: std::true_type { }; } /** * @brief The SharedLib class. * * `uvw` provides cross platform utilities for loading shared libraries and * retrieving symbols from them, by means of the API offered by libuv. */ class SharedLib final { explicit SharedLib(std::shared_ptr<Loop> ref, std::string filename) noexcept : pLoop{std::move(ref)}, lib{} { opened = (0 == uv_dlopen(filename.data(), &lib)); } public: /** * @brief Creates a new shared library object. * @param loop A pointer to the loop from which the handle generated. * @param filename The filename of the library in UTF8. * @return A pointer to the newly created handle. */ static std::shared_ptr<SharedLib> create(std::shared_ptr<Loop> loop, std::string filename) noexcept { return std::shared_ptr<SharedLib>{new SharedLib{std::move(loop), std::move(filename)}}; } SharedLib(const SharedLib &) = delete; SharedLib(SharedLib &&) = delete; ~SharedLib() noexcept { uv_dlclose(&lib); } SharedLib& operator=(const SharedLib &) = delete; SharedLib& operator=(SharedLib &&) = delete; /** * @brief Checks if the library has been correctly opened. * @return True if the library is opened, false otherwise. */ explicit operator bool() const noexcept { return !opened; } /** * @brief Retrieves a data pointer from a dynamic library. * * `F` shall be a valid function type (as an example, `void(int)`).<br/> * It is legal for a symbol to map to `nullptr`. * * @param name The symbol to be retrieved. * @return A valid function pointer in case of success, `nullptr` otherwise. */ template<typename F> F * sym(std::string name) { static_assert(details::IsFunc<F>::value, "!"); F *func; auto err = uv_dlsym(&lib, name.data(), reinterpret_cast<void**>(&func)); if(err) { func = nullptr; } return func; } /** * @brief Returns the last error message, if any. * @return The last error message, if any. */ const char * error() const noexcept { return uv_dlerror(&lib); } /** * @brief Gets the loop from which the object was originated. * @return A reference to a loop instance. */ Loop& loop() const noexcept { return *pLoop; } private: std::shared_ptr<Loop> pLoop; uv_lib_t lib; bool opened; }; }
#pragma once #include <utility> #include <memory> #include <string> #include <type_traits> #include <uv.h> #include "loop.hpp" namespace uvw { /** * @brief The SharedLib class. * * `uvw` provides cross platform utilities for loading shared libraries and * retrieving symbols from them, by means of the API offered by libuv. */ class SharedLib final { explicit SharedLib(std::shared_ptr<Loop> ref, std::string filename) noexcept : pLoop{std::move(ref)}, lib{} { opened = (0 == uv_dlopen(filename.data(), &lib)); } public: /** * @brief Creates a new shared library object. * @param loop A pointer to the loop from which the handle generated. * @param filename The filename of the library in UTF8. * @return A pointer to the newly created handle. */ static std::shared_ptr<SharedLib> create(std::shared_ptr<Loop> loop, std::string filename) noexcept { return std::shared_ptr<SharedLib>{new SharedLib{std::move(loop), std::move(filename)}}; } SharedLib(const SharedLib &) = delete; SharedLib(SharedLib &&) = delete; ~SharedLib() noexcept { uv_dlclose(&lib); } SharedLib& operator=(const SharedLib &) = delete; SharedLib& operator=(SharedLib &&) = delete; /** * @brief Checks if the library has been correctly opened. * @return True if the library is opened, false otherwise. */ explicit operator bool() const noexcept { return !opened; } /** * @brief Retrieves a data pointer from a dynamic library. * * `F` shall be a valid function type (as an example, `void(int)`).<br/> * It is legal for a symbol to map to `nullptr`. * * @param name The symbol to be retrieved. * @return A valid function pointer in case of success, `nullptr` otherwise. */ template<typename F> F * sym(std::string name) { static_assert(std::is_function<F>::value, "!"); F *func; auto err = uv_dlsym(&lib, name.data(), reinterpret_cast<void**>(&func)); if(err) { func = nullptr; } return func; } /** * @brief Returns the last error message, if any. * @return The last error message, if any. */ const char * error() const noexcept { return uv_dlerror(&lib); } /** * @brief Gets the loop from which the object was originated. * @return A reference to a loop instance. */ Loop& loop() const noexcept { return *pLoop; } private: std::shared_ptr<Loop> pLoop; uv_lib_t lib; bool opened; }; }
Use std::is_function instead of IsFunc
SharedLib: Use std::is_function instead of IsFunc
C++
mit
skypjack/uvw,tusharpm/uvw,tusharpm/uvw,skypjack/uvw,skypjack/uvw,tusharpm/uvw
5dfd4d6c7539b56694429d3b8e90823c4862018c
heron/common/tests/cpp/network/http_server_unittest.cpp
heron/common/tests/cpp/network/http_server_unittest.cpp
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "network/http_server_unittest.h" #include "network/host_unittest.h" #include "gtest/gtest.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "network/network.h" static sp_uint32 nkeys = 0; TestHttpServer::TestHttpServer(EventLoopImpl* eventLoop, NetworkOptions& _options) { server_ = new HTTPServer(eventLoop, _options); server_->InstallCallBack( "/meta", [this](IncomingHTTPRequest* request) { this->HandleMetaRequest(request); }); server_->InstallCallBack("/terminate", [this](IncomingHTTPRequest* request) { this->HandleTerminateRequest(request); }); server_->InstallGenericCallBack( [this](IncomingHTTPRequest* request) { this->HandleGenericRequest(request); }); server_->Start(); } TestHttpServer::~TestHttpServer() { delete server_; } void TestHttpServer::HandleMetaRequest(IncomingHTTPRequest* _request) { if (_request->type() != BaseHTTPRequest::GET) { // We only accept get requests server_->SendErrorReply(_request, 400); return; } std::cerr << "Got a meta request" << std::endl; const HTTPKeyValuePairs& keyvalues = _request->keyvalues(); EXPECT_EQ(nkeys, keyvalues.size()); for (size_t i = 0; i < keyvalues.size(); ++i) { std::ostringstream key, value; key << "key" << i; value << "value" << i; EXPECT_EQ(key.str(), keyvalues[i].first); EXPECT_EQ(value.str(), keyvalues[i].second); } OutgoingHTTPResponse* response = new OutgoingHTTPResponse(_request); response->AddResponse("This is response for meta object\r\n"); server_->SendReply(_request, 200, response); } void TestHttpServer::HandleGenericRequest(IncomingHTTPRequest* _request) { std::cerr << "Got a generic request" << std::endl; const HTTPKeyValuePairs& keyvalues = _request->keyvalues(); for (size_t i = 0; i < keyvalues.size(); ++i) { std::cout << "Key : " << keyvalues[i].first << " " << "Value: " << keyvalues[i].second << " " << std::endl; } server_->SendErrorReply(_request, 404); } void TestHttpServer::HandleTerminateRequest(IncomingHTTPRequest* _request) { server_->getEventLoop()->loopExit(); } void start_http_server(sp_uint32 _port, sp_uint32 _nkeys, int fd) { nkeys = _nkeys; EventLoopImpl ss; // set host, port and packet size NetworkOptions options; options.set_host(LOCALHOST); options.set_port(_port); options.set_max_packet_size(BUFSIZ << 4); // start the server TestHttpServer http_server(&ss, options); // use pipe to block clients before server enters event loop int sent; write(fd, &sent, sizeof(int)); ss.loop(); }
/* * Copyright 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "network/http_server_unittest.h" #include "network/host_unittest.h" #include "gtest/gtest.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "network/network.h" static sp_uint32 nkeys = 0; TestHttpServer::TestHttpServer(EventLoopImpl* eventLoop, NetworkOptions& _options) { server_ = new HTTPServer(eventLoop, _options); server_->InstallCallBack( "/meta", [this](IncomingHTTPRequest* request) { this->HandleMetaRequest(request); }); server_->InstallCallBack("/terminate", [this](IncomingHTTPRequest* request) { this->HandleTerminateRequest(request); }); server_->InstallGenericCallBack( [this](IncomingHTTPRequest* request) { this->HandleGenericRequest(request); }); EXPECT_EQ(SP_OK, server_->Start()); } TestHttpServer::~TestHttpServer() { delete server_; } void TestHttpServer::HandleMetaRequest(IncomingHTTPRequest* _request) { if (_request->type() != BaseHTTPRequest::GET) { // We only accept get requests server_->SendErrorReply(_request, 400); return; } std::cerr << "Got a meta request" << std::endl; const HTTPKeyValuePairs& keyvalues = _request->keyvalues(); EXPECT_EQ(nkeys, keyvalues.size()); for (size_t i = 0; i < keyvalues.size(); ++i) { std::ostringstream key, value; key << "key" << i; value << "value" << i; EXPECT_EQ(key.str(), keyvalues[i].first); EXPECT_EQ(value.str(), keyvalues[i].second); } OutgoingHTTPResponse* response = new OutgoingHTTPResponse(_request); response->AddResponse("This is response for meta object\r\n"); server_->SendReply(_request, 200, response); } void TestHttpServer::HandleGenericRequest(IncomingHTTPRequest* _request) { std::cerr << "Got a generic request" << std::endl; const HTTPKeyValuePairs& keyvalues = _request->keyvalues(); for (size_t i = 0; i < keyvalues.size(); ++i) { std::cout << "Key : " << keyvalues[i].first << " " << "Value: " << keyvalues[i].second << " " << std::endl; } server_->SendErrorReply(_request, 404); } void TestHttpServer::HandleTerminateRequest(IncomingHTTPRequest* _request) { server_->getEventLoop()->loopExit(); } void start_http_server(sp_uint32 _port, sp_uint32 _nkeys, int fd) { nkeys = _nkeys; EventLoopImpl ss; // set host, port and packet size NetworkOptions options; options.set_host(LOCALHOST); options.set_port(_port); options.set_max_packet_size(BUFSIZ << 4); // start the server TestHttpServer http_server(&ss, options); // use pipe to block clients before server enters event loop int sent; write(fd, &sent, sizeof(int)); ss.loop(); }
add checking server starting return (#1984)
add checking server starting return (#1984)
C++
apache-2.0
streamlio/heron,nlu90/heron,tomncooper/heron,tomncooper/heron,mycFelix/heron,ashvina/heron,srkukarni/heron,nlu90/heron,ashvina/heron,mycFelix/heron,twitter/heron,srkukarni/heron,huijunwu/heron,streamlio/heron,srkukarni/heron,srkukarni/heron,huijunwu/heron,srkukarni/heron,lucperkins/heron,nlu90/heron,ashvina/heron,srkukarni/heron,lucperkins/heron,mycFelix/heron,mycFelix/heron,streamlio/heron,nlu90/heron,mycFelix/heron,mycFelix/heron,huijunwu/heron,tomncooper/heron,ashvina/heron,ashvina/heron,ashvina/heron,twitter/heron,twitter/heron,twitter/heron,twitter/heron,twitter/heron,tomncooper/heron,nlu90/heron,twitter/heron,streamlio/heron,lucperkins/heron,ashvina/heron,huijunwu/heron,srkukarni/heron,lucperkins/heron,ashvina/heron,tomncooper/heron,huijunwu/heron,huijunwu/heron,tomncooper/heron,tomncooper/heron,mycFelix/heron,streamlio/heron,streamlio/heron,srkukarni/heron,twitter/heron,huijunwu/heron,huijunwu/heron,ashvina/heron,nlu90/heron,streamlio/heron,nlu90/heron,lucperkins/heron,nlu90/heron,tomncooper/heron,nlu90/heron,lucperkins/heron,tomncooper/heron,lucperkins/heron,lucperkins/heron,streamlio/heron,mycFelix/heron,streamlio/heron,mycFelix/heron
5917ecfb7af44056dc4596041fd7abdce0d949cb
src/tester.cpp
src/tester.cpp
#include <iostream> #include <stdexcept> #include <memory> #include <set> #include <chrono> #include <mutex> #include <thread> #include <atomic> #include <ogdf/basic/Graph.h> #include <ogdf/basic/simple_graph_alg.h> #include <ogdf/basic/graph_generators.h> #include "helpers.h" #include "circuitcocircuit.h" #define BIAS6 63 #define SMALLN 62 #define TOPBIT6 32 using namespace ogdf; using namespace std; /* Graph sources */ /** * Since the default updateOnGraphRetrieval() uses no synchronization * the user might get updates on the number of retrieved graphs more often * than once a second if the extending classes do not implement any lock * (e.g. RandomGraphSource does this) */ class AbstractGraphSource { std::chrono::time_point<std::chrono::system_clock> lastOutputTime; atomic<int> nGraphsRetrieved = ATOMIC_VAR_INIT(0); protected: AbstractGraphSource() { lastOutputTime = std::chrono::system_clock::now(); } void updateOnGraphRetrieval() { ++nGraphsRetrieved; auto now = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::seconds> (now-lastOutputTime).count(); if (diff > 1) { cout << "Graphs retrieved: " << nGraphsRetrieved.load() << endl; lastOutputTime = now; } } public: virtual bool get(Graph &G) = 0; virtual ~AbstractGraphSource() {} }; /** * Reads graphs in nauty's graph6 format from stdin. */ class StdinGraphSource : public AbstractGraphSource { mutex cin_mtx; /* * The following two functions are from the nauty package. * See http://pallini.di.uniroma1.it/ * stringtograph was modified to work with OGDF's Graph class */ /** * Get size of graph out of graph6 or sparse6 string. */ static int graphsize(char *s) { char *p; int n; if (s[0] == ':') p = s+1; else p = s; n = *p++ - BIAS6; if (n > SMALLN) { n = *p++ - BIAS6; n = (n << 6) | (*p++ - BIAS6); n = (n << 6) | (*p++ - BIAS6); } return n; } /** * Convert string in graph6 format to graph. */ static void stringtograph(char *s, Graph &G) { int n = graphsize(s), x = 0; char *p = s + 1; if (n > SMALLN) p += 3; vector<node> vertices(n); for(int i = 0; i < n; ++i) { vertices[i] = G.newNode(i); } int k = 1; for (int j = 1; j < n; ++j) { for (int i = 0; i < j; ++i) { if (--k == 0) { k = 6; x = *(p++) - BIAS6; } if (x & TOPBIT6) { G.newEdge(vertices[i], vertices[j]); } x <<= 1; } } } public: /** * Locks cin! */ bool get(Graph &G) { string s; unique_lock<mutex> lock(cin_mtx); bool r = getline(cin, s); updateOnGraphRetrieval(); lock.unlock(); if (r) { char *cp = (char*) s.c_str(); stringtograph(cp, G); } return r; } }; class RandomGraphSource : public AbstractGraphSource { int nodes, minEdges, maxEdges; public: RandomGraphSource(int nodes, int minE, int maxE) : nodes(nodes), minEdges(minE), maxEdges(maxE) {} /** * OGDF's solution is probably biased, * (see http://stackoverflow.com/a/14618505/247532) but we don't care * since other solutions are way slower */ bool get(Graph &G) { int edges = randomNumber(minEdges, maxEdges); randomSimpleGraph(G, nodes, edges); List<edge> added; makeConnected(G, added); updateOnGraphRetrieval(); return true; } }; /* Test runner */ class TestRunner { unique_ptr<AbstractGraphSource> graphs; protected: mutex errorOutputMutex; bool errorFound = false; int minComponents, maxComponents, cutSizeBound; void reportProblem(const Graph &G, const set<set<int>> &AmB, const set<set<int>> &BmA) { unique_lock<mutex> lock(errorOutputMutex, defer_lock); if (errorFound || !lock.try_lock()) { // Somebody is already reporting a problem return; } errorFound = true; cout << "\nmincuts / bf:" << endl; for (const set<int> &c : AmB) { cout << c << endl; } cout << "bf / mincuts:" << endl; for (const set<int> &c : BmA) { cout << c << endl; } ofstream fGraph("tmp/tester_in.csv"); if (!fGraph.is_open()) { cerr << "tmp/tester_in.csv could not be opened" << endl; exit(3); } graph2csv(G, fGraph); cout << "Input graph written to tmp/tester_in.csv" << endl; } bool testGraph(Graph &G) { // run circuitcocircuit and bfc List<bond> bonds; CircuitCocircuit alg(G, cutSizeBound); for (int i = minComponents; i <= maxComponents; ++i) { alg.run(i, bonds); } List<List<edge>> bf_bonds; bruteforceGraphBonds(G, cutSizeBound, minComponents, maxComponents, bf_bonds); set<set<int>> A, B, AmB, BmA; for(const bond &b : bonds) { set<int> si; for (edge e : b.edges) si.insert(e->index()); A.insert(si); } for(const List<edge> &le : bf_bonds) { set<int> si; for (edge e : le) si.insert(e->index()); B.insert(si); } set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(AmB, AmB.end())); set_difference(B.begin(), B.end(), A.begin(), A.end(), inserter(BmA, BmA.end())); if (AmB.empty() && BmA.empty()) { return true; } else { reportProblem(G, AmB, BmA); return false; } } public: TestRunner(int minC, int maxC, int cutSizeB, unique_ptr<AbstractGraphSource> graphs) : graphs(move(graphs)), minComponents(minC), maxComponents(maxC), cutSizeBound(cutSizeB) { } virtual void run() final { while(!errorFound) { Graph G; // Exhausted input? if (!graphs->get(G)) { break; } // Problem found on G? if (!testGraph(G)) { break; } } } }; /* --- */ void printUsage(char *name) { cerr << "Usage:\t" << name << " <cut size bound> <# of components> " \ << "\n\t\t[-r, --randomized <# of nodes> <min>-<max edges>] [-tN]\n\n"; cerr << "\tThis program tests CircuitCocircuit implementation.\n" \ << "\tExpects graphs in nauty's graph6 format on stdin.\n\n" \ << "\tFirst two arguments are used for any graph being tested.\n" \ << "\t<# of components> can be exact or range (e.g. 2-3)\n" \ << "\t-r generate random graphs (won't use stdin input)\n" \ << "\t<max edges> is not strict (if the random graph is " \ << "disconnected\n\t\tthen we add edges to connect it)\n" \ << "\t-tN use N threads (by default N == 2)\n"; } int main(int argc, char *argv[]) { if (argc < 3 || argc == 5 || argc > 7) { printUsage(argv[0]); exit(1); } // Number of components and cut size bound settings int minComponents, maxComponents, cutSizeBound; try { cutSizeBound = stoi(argv[1]); // # of components string secondArg(argv[2]); size_t hyphenPos = secondArg.find('-'); if (hyphenPos == string::npos) { minComponents = maxComponents = stoi(argv[2]); } else { minComponents = stoi(secondArg.substr(0, hyphenPos)); maxComponents = stoi(secondArg.substr(hyphenPos + 1)); } if (maxComponents < minComponents) { throw invalid_argument("max components < min components"); } } catch(invalid_argument &_) { // stoi failed printUsage(argv[0]); exit(2); } // Graph source settings unique_ptr<AbstractGraphSource> source; if (argc == 3 || (argv[3] != string("-r") && argv[3] != string("--randomized"))) { source = unique_ptr<StdinGraphSource>(new StdinGraphSource()); } else { // Configure randomized testing int nodes, minEdges, maxEdges; try { size_t hyphenPos; // # of nodes nodes = stoi(argv[4]); // min-max edges string fifthArg(argv[5]); hyphenPos = fifthArg.find('-'); if (hyphenPos == string::npos) { throw invalid_argument("Number of edges is not range."); } minEdges = stoi(fifthArg.substr(0, hyphenPos)); maxEdges = stoi(fifthArg.substr(hyphenPos + 1)); if (maxEdges < minEdges) { throw invalid_argument("max edges < min edges"); } } catch(invalid_argument &_) { // stoi failed printUsage(argv[0]); exit(2); } source = unique_ptr<RandomGraphSource>(new RandomGraphSource(nodes, minEdges, maxEdges)); } // Parallelization settings int nThreads = 2; string lastArg(argv[argc - 1]); if (lastArg.substr(0, 2) == "-t") { nThreads = stoi(lastArg.substr(2)); } // Run tester in parallel try { TestRunner testrunner(minComponents, maxComponents, cutSizeBound, move(source)); vector<thread> threads(nThreads); for (int i = 0; i < nThreads; ++i) { threads[i] = thread(&TestRunner::run, ref(testrunner)); } for (int i = 0; i < nThreads; ++i) { threads[i].join(); } } catch (const exception& e) { cerr << e.what() << endl; exit(3); } return 0; }
#include <iostream> #include <stdexcept> #include <memory> #include <set> #include <chrono> #include <mutex> #include <thread> #include <atomic> #include <ogdf/basic/Graph.h> #include <ogdf/basic/simple_graph_alg.h> #include <ogdf/basic/graph_generators.h> #include "helpers.h" #include "circuitcocircuit.h" #define BIAS6 63 #define SMALLN 62 #define TOPBIT6 32 using namespace ogdf; using namespace std; /* Graph sources */ /** * Since the default updateOnGraphRetrieval() uses no synchronization * the user might get updates on the number of retrieved graphs more often * than once a second if the extending classes do not implement any lock * (e.g. RandomGraphSource does this) */ class AbstractGraphSource { std::chrono::time_point<std::chrono::system_clock> lastOutputTime; atomic<int> nGraphsRetrieved = ATOMIC_VAR_INIT(0); protected: AbstractGraphSource() { lastOutputTime = std::chrono::system_clock::now(); } void updateOnGraphRetrieval() { ++nGraphsRetrieved; auto now = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::seconds> (now-lastOutputTime).count(); if (diff > 1) { cout << "Graphs retrieved: " << nGraphsRetrieved.load() << endl; lastOutputTime = now; } } public: virtual bool get(Graph &G) = 0; virtual ~AbstractGraphSource() {} }; /** * Reads graphs in nauty's graph6 format from stdin. */ class StdinGraphSource : public AbstractGraphSource { mutex cin_mtx; /* * The following two functions are from the nauty package. * See http://pallini.di.uniroma1.it/ * stringtograph was modified to work with OGDF's Graph class */ /** * Get size of graph out of graph6 or sparse6 string. */ static int graphsize(char *s) { char *p; int n; if (s[0] == ':') p = s+1; else p = s; n = *p++ - BIAS6; if (n > SMALLN) { n = *p++ - BIAS6; n = (n << 6) | (*p++ - BIAS6); n = (n << 6) | (*p++ - BIAS6); } return n; } /** * Convert string in graph6 format to graph. */ static void stringtograph(char *s, Graph &G) { int n = graphsize(s), x = 0; char *p = s + 1; if (n > SMALLN) p += 3; vector<node> vertices(n); for(int i = 0; i < n; ++i) { vertices[i] = G.newNode(i); } int k = 1; for (int j = 1; j < n; ++j) { for (int i = 0; i < j; ++i) { if (--k == 0) { k = 6; x = *(p++) - BIAS6; } if (x & TOPBIT6) { G.newEdge(vertices[i], vertices[j]); } x <<= 1; } } } public: /** * Locks cin! */ bool get(Graph &G) { string s; unique_lock<mutex> lock(cin_mtx); bool r = getline(cin, s); updateOnGraphRetrieval(); lock.unlock(); if (r) { char *cp = (char*) s.c_str(); stringtograph(cp, G); } return r; } }; class RandomGraphSource : public AbstractGraphSource { int nodes, minEdges, maxEdges; public: RandomGraphSource(int nodes, int minE, int maxE) : nodes(nodes), minEdges(minE), maxEdges(maxE) { srand (time(NULL)); // OGDF uses rand() } /** * OGDF's solution is probably biased, * (see http://stackoverflow.com/a/14618505/247532) but we don't care * since other solutions are way slower */ bool get(Graph &G) { int edges = randomNumber(minEdges, maxEdges); randomSimpleGraph(G, nodes, edges); List<edge> added; makeConnected(G, added); updateOnGraphRetrieval(); return true; } }; /* Test runner */ class TestRunner { unique_ptr<AbstractGraphSource> graphs; protected: mutex errorOutputMutex; bool errorFound = false; int minComponents, maxComponents, cutSizeBound; void reportProblem(const Graph &G, const set<set<int>> &AmB, const set<set<int>> &BmA) { unique_lock<mutex> lock(errorOutputMutex, defer_lock); if (errorFound || !lock.try_lock()) { // Somebody is already reporting a problem return; } errorFound = true; cout << "\nmincuts / bf:" << endl; for (const set<int> &c : AmB) { cout << c << endl; } cout << "bf / mincuts:" << endl; for (const set<int> &c : BmA) { cout << c << endl; } ofstream fGraph("tmp/tester_in.csv"); if (!fGraph.is_open()) { cerr << "tmp/tester_in.csv could not be opened" << endl; exit(3); } graph2csv(G, fGraph); cout << "Input graph written to tmp/tester_in.csv" << endl; } bool testGraph(Graph &G) { // run circuitcocircuit and bfc List<bond> bonds; CircuitCocircuit alg(G, cutSizeBound); for (int i = minComponents; i <= maxComponents; ++i) { alg.run(i, bonds); } List<List<edge>> bf_bonds; bruteforceGraphBonds(G, cutSizeBound, minComponents, maxComponents, bf_bonds); set<set<int>> A, B, AmB, BmA; for(const bond &b : bonds) { set<int> si; for (edge e : b.edges) si.insert(e->index()); A.insert(si); } for(const List<edge> &le : bf_bonds) { set<int> si; for (edge e : le) si.insert(e->index()); B.insert(si); } set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(AmB, AmB.end())); set_difference(B.begin(), B.end(), A.begin(), A.end(), inserter(BmA, BmA.end())); if (AmB.empty() && BmA.empty()) { return true; } else { reportProblem(G, AmB, BmA); return false; } } public: TestRunner(int minC, int maxC, int cutSizeB, unique_ptr<AbstractGraphSource> graphs) : graphs(move(graphs)), minComponents(minC), maxComponents(maxC), cutSizeBound(cutSizeB) { } virtual void run() final { while(!errorFound) { Graph G; // Exhausted input? if (!graphs->get(G)) { break; } // Problem found on G? if (!testGraph(G)) { break; } } } }; /* --- */ void printUsage(char *name) { cerr << "Usage:\t" << name << " <cut size bound> <# of components> " \ << "\n\t\t[-r, --randomized <# of nodes> <min>-<max edges>] [-tN]\n\n"; cerr << "\tThis program tests CircuitCocircuit implementation.\n" \ << "\tExpects graphs in nauty's graph6 format on stdin.\n\n" \ << "\tFirst two arguments are used for any graph being tested.\n" \ << "\t<# of components> can be exact or range (e.g. 2-3)\n" \ << "\t-r generate random graphs (won't use stdin input)\n" \ << "\t<max edges> is not strict (if the random graph is " \ << "disconnected\n\t\tthen we add edges to connect it)\n" \ << "\t-tN use N threads (by default N == 2)\n"; } int main(int argc, char *argv[]) { if (argc < 3 || argc == 5 || argc > 7) { printUsage(argv[0]); exit(1); } // Number of components and cut size bound settings int minComponents, maxComponents, cutSizeBound; try { cutSizeBound = stoi(argv[1]); // # of components string secondArg(argv[2]); size_t hyphenPos = secondArg.find('-'); if (hyphenPos == string::npos) { minComponents = maxComponents = stoi(argv[2]); } else { minComponents = stoi(secondArg.substr(0, hyphenPos)); maxComponents = stoi(secondArg.substr(hyphenPos + 1)); } if (maxComponents < minComponents) { throw invalid_argument("max components < min components"); } } catch(invalid_argument &_) { // stoi failed printUsage(argv[0]); exit(2); } // Graph source settings unique_ptr<AbstractGraphSource> source; if (argc == 3 || (argv[3] != string("-r") && argv[3] != string("--randomized"))) { source = unique_ptr<StdinGraphSource>(new StdinGraphSource()); } else { // Configure randomized testing int nodes, minEdges, maxEdges; try { size_t hyphenPos; // # of nodes nodes = stoi(argv[4]); // min-max edges string fifthArg(argv[5]); hyphenPos = fifthArg.find('-'); if (hyphenPos == string::npos) { throw invalid_argument("Number of edges is not range."); } minEdges = stoi(fifthArg.substr(0, hyphenPos)); maxEdges = stoi(fifthArg.substr(hyphenPos + 1)); if (maxEdges < minEdges) { throw invalid_argument("max edges < min edges"); } } catch(invalid_argument &_) { // stoi failed printUsage(argv[0]); exit(2); } source = unique_ptr<RandomGraphSource>(new RandomGraphSource(nodes, minEdges, maxEdges)); } // Parallelization settings int nThreads = 2; string lastArg(argv[argc - 1]); if (lastArg.substr(0, 2) == "-t") { nThreads = stoi(lastArg.substr(2)); } // Run tester in parallel try { TestRunner testrunner(minComponents, maxComponents, cutSizeBound, move(source)); vector<thread> threads(nThreads); for (int i = 0; i < nThreads; ++i) { threads[i] = thread(&TestRunner::run, ref(testrunner)); } for (int i = 0; i < nThreads; ++i) { threads[i].join(); } } catch (const exception& e) { cerr << e.what() << endl; exit(3); } return 0; }
Set random seed for OGDF's randomSimpleGraph
Tester: Set random seed for OGDF's randomSimpleGraph
C++
mit
OndrejSlamecka/mincuts
e86f59c3b562786ff6d5fbc19ac5234d019f7577
src/Application/SkyXHydrax/EC_SkyX.cpp
src/Application/SkyXHydrax/EC_SkyX.cpp
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_SkyX.cpp * @brief A sky component using SkyX, http://www.ogre3d.org/tikiwiki/SkyX */ #define OGRE_INTEROP #include "DebugOperatorNew.h" #include "EC_SkyX.h" #include "Scene.h" #include "Framework.h" #include "FrameAPI.h" #include "OgreWorld.h" #include "Renderer.h" #include "EC_Camera.h" #include "Entity.h" #include "LoggingFunctions.h" #include "Math/MathFunc.h" #include "Profiler.h" #include "Color.h" #include <Ogre.h> #include <SkyX.h> #include "MemoryLeakCheck.h" /// @cond PRIVATE struct EC_SkyXImpl { // Ambient and sun diffuse color copied from EC_EnvironmentLight EC_SkyXImpl() : skyX(0), sunlight(0), cloudLayer(0), sunColor(0.639f,0.639f,0.639f), ambientColor(0.364f, 0.364f, 0.364f, 1.f) {} ~EC_SkyXImpl() { if (skyX) { skyX->remove(); if (sunlight && skyX->getSceneManager()) skyX->getSceneManager()->destroyLight(sunlight); } sunlight = 0; SAFE_DELETE(skyX) } SkyX::SkyX *skyX; SkyX::CloudLayer *cloudLayer; ///< Currently just one cloud layer used. Ogre::Light *sunlight; Color sunColor; Color ambientColor; }; /// @endcond EC_SkyX::EC_SkyX(Scene* scene) : IComponent(scene), volumetricClouds(this, "Volumetric clouds", false), timeMultiplier(this, "Time multiplier", 0.0f), time(this, "Time", float3(14.f, 7.5f, 20.5f)), weather(this, "Weather (volumetric clouds only)", float2(1.f, 1.f)), // windSpeed(this, "Wind speed (volumetric clouds only)", 800.f), windDirection(this, "Wind direction", 0.0f), impl(0) { OgreWorldPtr w = scene->GetWorld<OgreWorld>(); if (!w) { LogError("EC_SkyX: no OgreWorld available. Cannot be created."); return; } connect(w->GetRenderer(), SIGNAL(MainCameraChanged(Entity *)), SLOT(OnActiveCameraChanged(Entity *))); connect(this, SIGNAL(ParentEntitySet()), SLOT(Create())); } EC_SkyX::~EC_SkyX() { SAFE_DELETE(impl); } float3 EC_SkyX::SunPosition() const { if (impl->skyX) return impl->skyX->getAtmosphereManager()->getSunPosition(); return float3(); } void EC_SkyX::Create() { SAFE_DELETE(impl); try { if (!ParentScene()) { LogError("EC_SkyX: no parent scene. Cannot be created."); return; } OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>(); assert(w); if (!w->GetRenderer() || !w->GetRenderer()->MainCamera()) return; // Can't create SkyX just yet, no main camera set. Ogre::SceneManager *sm = w->GetSceneManager(); impl = new EC_SkyXImpl(); // Create Sky Entity *mainCamera = w->GetRenderer()->MainCamera(); if (!mainCamera) { LogError("Cannot create SkyX: No main camera set!"); return; } impl->skyX = new SkyX::SkyX(sm, mainCamera->GetComponent<EC_Camera>()->GetCamera()); impl->skyX->create(); // A little change to default atmosphere settings. SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions(); atOpt.RayleighMultiplier = 0.0045f; impl->skyX->getAtmosphereManager()->setOptions(atOpt); UpdateAttribute(&volumetricClouds); UpdateAttribute(&timeMultiplier); UpdateAttribute(&time); connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection); connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection); CreateSunlight(); } catch(Ogre::Exception &e) { // Currently if we try to create more than one SkyX component we end up here due to Ogre internal name collision. LogError("Could not create EC_SkyX: " + std::string(e.what())); } } void EC_SkyX::CreateSunlight() { if (impl) { OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>(); Ogre::SceneManager *sm = w->GetSceneManager(); sm->setAmbientLight(impl->ambientColor); impl->sunlight = sm->createLight(w->GetRenderer()->GetUniqueObjectName("SkyXSunlight")); impl->sunlight->setType(Ogre::Light::LT_DIRECTIONAL); impl->sunlight->setDiffuseColour(impl->sunColor); impl->sunlight->setSpecularColour(0.f,0.f,0.f); impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection()); impl->sunlight->setCastShadows(true); } } void EC_SkyX::OnActiveCameraChanged(Entity *newActiveCamera) { if (!newActiveCamera) { SAFE_DELETE(impl); return; } // If we haven't yet initialized, do a full init. if (!impl) Create(); else // Otherwise, update the camera to an existing initialized SkyX instance. if (impl && impl->skyX) impl->skyX->setCamera(newActiveCamera->GetComponent<EC_Camera>()->GetCamera()); } void EC_SkyX::UpdateAttribute(IAttribute *attr) { if (!impl->skyX) return; if (attr == &volumetricClouds) { if (volumetricClouds.Get()) { impl->skyX->getCloudsManager()->removeAll(); impl->skyX->getVCloudsManager()->create(); } else { impl->skyX->getVCloudsManager()->remove(); impl->skyX->getCloudsManager()->removeAll(); impl->cloudLayer = impl->skyX->getCloudsManager()->add(SkyX::CloudLayer::Options()); } } else if (attr == &timeMultiplier) { impl->skyX->setTimeMultiplier((Ogre::Real)timeMultiplier.Get()); } else if (attr == &time) { SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions(); atOpt.Time = time.Get(); impl->skyX->getAtmosphereManager()->setOptions(atOpt); } else if (attr == &weather) { // Clamp value to [0.0, 1.0], otherwise crashes occur. float2 w = Clamp(weather.Get(), 0.f, 1.f); if (volumetricClouds.Get()) impl->skyX->getVCloudsManager()->getVClouds()->setWheater(w.x, w.y, 2); weather.Set(w, AttributeChange::Disconnected); } /* else if (attr == &windSpeed) { if (volumetricClouds.Get()) impl->skyX->getVCloudsManager()->setWindSpeed(windSpeed.Get()); } */ else if (attr == &windDirection) { if (volumetricClouds.Get()) { impl->skyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Radian(DegToRad(windDirection.Get()))); } else { SkyX::CloudLayer::Options options = impl->cloudLayer->getOptions(); Ogre::Radian r1(Ogre::Degree(windDirection.Get())), r2(Ogre::Degree(windDirection.Get())); options.WindDirection = Ogre::Vector2(Ogre::Math::Cos(r1), Ogre::Math::Sin(r2)); impl->skyX->getCloudsManager()->removeAll(); impl->skyX->getCloudsManager()->add(options); } } } void EC_SkyX::Update(float frameTime) { if (impl && impl->skyX) { PROFILE(EC_SkyX_Update); if (impl->sunlight) impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection()); impl->skyX->update(frameTime); // Do not replicate constant time attribute updates as SkyX internals are authoritative for it. time.Set(impl->skyX->getAtmosphereManager()->getOptions().Time, AttributeChange::LocalOnly); } }
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_SkyX.cpp * @brief A sky component using SkyX, http://www.ogre3d.org/tikiwiki/SkyX */ #define OGRE_INTEROP #include "DebugOperatorNew.h" #include "EC_SkyX.h" #include "Scene.h" #include "Framework.h" #include "FrameAPI.h" #include "OgreWorld.h" #include "Renderer.h" #include "EC_Camera.h" #include "Entity.h" #include "LoggingFunctions.h" #include "Math/MathFunc.h" #include "Profiler.h" #include "Color.h" #include <Ogre.h> #include <SkyX.h> #include "MemoryLeakCheck.h" /// @cond PRIVATE struct EC_SkyXImpl { EC_SkyXImpl() : skyX(0), sunlight(0), cloudLayer(0) {} ~EC_SkyXImpl() { if (skyX) { skyX->remove(); Ogre::SceneManager *sm = skyX->getSceneManager(); if (sm) { if (sunlight) sm->destroyLight(sunlight); sm->setAmbientLight(originalAmbientColor); } } sunlight = 0; SAFE_DELETE(skyX) } operator bool () const { return skyX != 0; } SkyX::SkyX *skyX; SkyX::CloudLayer *cloudLayer; ///< Currently just one cloud layer used. Ogre::Light *sunlight; Color originalAmbientColor; }; /// @endcond EC_SkyX::EC_SkyX(Scene* scene) : IComponent(scene), volumetricClouds(this, "Volumetric clouds", false), timeMultiplier(this, "Time multiplier", 0.0f), time(this, "Time", float3(14.f, 7.5f, 20.5f)), weather(this, "Weather (volumetric clouds only)", float2(1.f, 1.f)), // windSpeed(this, "Wind speed (volumetric clouds only)", 800.f), windDirection(this, "Wind direction", 0.0f), impl(0) { OgreWorldPtr w = scene->GetWorld<OgreWorld>(); if (!w) { LogError("EC_SkyX: no OgreWorld available. Cannot be created."); return; } connect(w->GetRenderer(), SIGNAL(MainCameraChanged(Entity *)), SLOT(OnActiveCameraChanged(Entity *))); connect(this, SIGNAL(ParentEntitySet()), SLOT(Create())); } EC_SkyX::~EC_SkyX() { SAFE_DELETE(impl); } float3 EC_SkyX::SunPosition() const { if (impl) return impl->skyX->getAtmosphereManager()->getSunPosition(); return float3(); } void EC_SkyX::Create() { SAFE_DELETE(impl); try { if (!ParentScene()) { LogError("EC_SkyX: no parent scene. Cannot be created."); return; } OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>(); assert(w); if (!w->GetRenderer() || !w->GetRenderer()->MainCamera()) return; // Can't create SkyX just yet, no main camera set. Ogre::SceneManager *sm = w->GetSceneManager(); Entity *mainCamera = w->GetRenderer()->MainCamera(); if (!mainCamera) { LogError("Cannot create SkyX: No main camera set!"); return; } impl = new EC_SkyXImpl(); impl->skyX = new SkyX::SkyX(sm, mainCamera->GetComponent<EC_Camera>()->GetCamera()); impl->skyX->create(); // A little change to default atmosphere settings. SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions(); atOpt.RayleighMultiplier = 0.0045f; impl->skyX->getAtmosphereManager()->setOptions(atOpt); UpdateAttribute(&volumetricClouds); UpdateAttribute(&timeMultiplier); UpdateAttribute(&time); connect(framework->Frame(), SIGNAL(PostFrameUpdate(float)), SLOT(Update(float)), Qt::UniqueConnection); connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(UpdateAttribute(IAttribute*)), Qt::UniqueConnection); CreateSunlight(); } catch(Ogre::Exception &e) { // Currently if we try to create more than one SkyX component we end up here due to Ogre internal name collision. LogError("Could not create EC_SkyX: " + std::string(e.what())); } } void EC_SkyX::CreateSunlight() { if (impl) { // Ambient and sun diffuse color copied from EC_EnvironmentLight OgreWorldPtr w = ParentScene()->GetWorld<OgreWorld>(); Ogre::SceneManager *sm = w->GetSceneManager(); impl->originalAmbientColor = sm->getAmbientLight(); sm->setAmbientLight(Color(0.364f, 0.364f, 0.364f, 1.f)); impl->sunlight = sm->createLight(w->GetRenderer()->GetUniqueObjectName("SkyXSunlight")); impl->sunlight->setType(Ogre::Light::LT_DIRECTIONAL); impl->sunlight->setDiffuseColour(Color(0.639f,0.639f,0.639f)); impl->sunlight->setSpecularColour(0.f,0.f,0.f); impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection()); impl->sunlight->setCastShadows(true); } } void EC_SkyX::OnActiveCameraChanged(Entity *newActiveCamera) { if (!newActiveCamera) { SAFE_DELETE(impl); return; } // If we haven't yet initialized, do a full init. if (!impl) Create(); else // Otherwise, update the camera to an existing initialized SkyX instance. if (impl) impl->skyX->setCamera(newActiveCamera->GetComponent<EC_Camera>()->GetCamera()); } void EC_SkyX::UpdateAttribute(IAttribute *attr) { if (!impl) return; if (attr == &volumetricClouds) { if (volumetricClouds.Get()) { impl->skyX->getCloudsManager()->removeAll(); impl->skyX->getVCloudsManager()->create(); } else { impl->skyX->getVCloudsManager()->remove(); impl->skyX->getCloudsManager()->removeAll(); impl->cloudLayer = impl->skyX->getCloudsManager()->add(SkyX::CloudLayer::Options()); } } else if (attr == &timeMultiplier) { impl->skyX->setTimeMultiplier((Ogre::Real)timeMultiplier.Get()); } else if (attr == &time) { SkyX::AtmosphereManager::Options atOpt = impl->skyX->getAtmosphereManager()->getOptions(); atOpt.Time = time.Get(); impl->skyX->getAtmosphereManager()->setOptions(atOpt); } else if (attr == &weather) { // Clamp value to [0.0, 1.0], otherwise crashes occur. float2 w = Clamp(weather.Get(), 0.f, 1.f); if (volumetricClouds.Get()) impl->skyX->getVCloudsManager()->getVClouds()->setWheater(w.x, w.y, 2); weather.Set(w, AttributeChange::Disconnected); } /* else if (attr == &windSpeed) { if (volumetricClouds.Get()) impl->skyX->getVCloudsManager()->setWindSpeed(windSpeed.Get()); } */ else if (attr == &windDirection) { if (volumetricClouds.Get()) { impl->skyX->getVCloudsManager()->getVClouds()->setWindDirection(Ogre::Radian(DegToRad(windDirection.Get()))); } else { SkyX::CloudLayer::Options options = impl->cloudLayer->getOptions(); Ogre::Radian r1(Ogre::Degree(windDirection.Get())), r2(Ogre::Degree(windDirection.Get())); options.WindDirection = Ogre::Vector2(Ogre::Math::Cos(r1), Ogre::Math::Sin(r2)); impl->skyX->getCloudsManager()->removeAll(); impl->skyX->getCloudsManager()->add(options); } } } void EC_SkyX::Update(float frameTime) { if (impl) { PROFILE(EC_SkyX_Update); if (impl->sunlight) impl->sunlight->setDirection(impl->skyX->getAtmosphereManager()->getSunDirection()); impl->skyX->update(frameTime); // Do not replicate constant time attribute updates as SkyX internals are authoritative for it. time.Set(impl->skyX->getAtmosphereManager()->getOptions().Time, AttributeChange::LocalOnly); } }
Add operator bool to EC_SkyXImpl so that instead of e.g. "if (impl && impl->skyX)" we can just write "if (impl)". Also, restore the original Ogre scene manager ambient color when EC_SkyX is deleted.
EC_SkyX: Add operator bool to EC_SkyXImpl so that instead of e.g. "if (impl && impl->skyX)" we can just write "if (impl)". Also, restore the original Ogre scene manager ambient color when EC_SkyX is deleted.
C++
apache-2.0
BogusCurry/tundra,pharos3d/tundra,realXtend/tundra,jesterKing/naali,pharos3d/tundra,realXtend/tundra,BogusCurry/tundra,realXtend/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,jesterKing/naali,realXtend/tundra,jesterKing/naali,pharos3d/tundra,jesterKing/naali,pharos3d/tundra,realXtend/tundra,BogusCurry/tundra,BogusCurry/tundra,AlphaStaxLLC/tundra,jesterKing/naali,BogusCurry/tundra,jesterKing/naali,pharos3d/tundra,BogusCurry/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,realXtend/tundra,jesterKing/naali,AlphaStaxLLC/tundra
2ad923b5ca826939ce7847cdfed209fb9e9daef4
src/tstock.cxx
src/tstock.cxx
/* * Connection pooling for the translation server. * * author: Max Kellermann <[email protected]> */ #include "tstock.hxx" #include "TranslateHandler.hxx" #include "translate_client.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "stock/GetHandler.hxx" #include "lease.hxx" #include "pool.hxx" #include "gerrno.h" #include "net/AllocatedSocketAddress.hxx" #include "net/SocketDescriptor.hxx" #include "event/Event.hxx" #include "event/Callback.hxx" #include <daemon/log.h> #include <string.h> #include <errno.h> class TranslateConnection final : public HeapStockItem { SocketDescriptor s; Event event; public: explicit TranslateConnection(CreateStockItem c) :HeapStockItem(c) {} ~TranslateConnection() override { if (s.IsDefined()) event.Delete(); } private: bool CreateAndConnect(SocketAddress address) { assert(!s.IsDefined()); return s.Create(AF_LOCAL, SOCK_STREAM, 0) && s.Connect(address); } public: void CreateAndConnectAndFinish(SocketAddress address) { if (CreateAndConnect(address)) { event.Set(s.Get(), EV_READ, MakeSimpleEventCallback(TranslateConnection, EventCallback), this); InvokeCreateSuccess(); } else { auto error = new_error_errno(); if (s.IsDefined()) s.Close(); InvokeCreateError(error); } } int GetSocket() { return s.Get(); } private: void EventCallback() { char buffer; ssize_t nbytes = recv(s.Get(), &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle translation server connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data in idle translation server connection\n"); InvokeIdleDisconnect(); pool_commit(); } public: /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { event.Add(); return true; } }; static void tstock_create(gcc_unused void *ctx, CreateStockItem c, void *info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { const auto &address = *(const AllocatedSocketAddress *)info; auto *connection = new TranslateConnection(c); connection->CreateAndConnectAndFinish(address); } static constexpr StockClass tstock_class = { .create = tstock_create, }; class TranslateStock { EventLoop &event_loop; Stock stock; AllocatedSocketAddress address; public: TranslateStock(EventLoop &_event_loop, const char *path, unsigned limit) :event_loop(_event_loop), stock(event_loop, tstock_class, nullptr, "translation", limit, 8) { address.SetLocal(path); } EventLoop &GetEventLoop() { return event_loop; } void Get(struct pool &pool, StockGetHandler &handler, struct async_operation_ref &async_ref) { stock.Get(pool, &address, handler, async_ref); } void Put(StockItem &item, bool destroy) { stock.Put(item, destroy); } }; class TranslateStockRequest final : public StockGetHandler, Lease { struct pool &pool; TranslateStock &stock; TranslateConnection *item; const TranslateRequest &request; const TranslateHandler &handler; void *handler_ctx; struct async_operation_ref &async_ref; public: TranslateStockRequest(TranslateStock &_stock, struct pool &_pool, const TranslateRequest &_request, const TranslateHandler &_handler, void *_ctx, struct async_operation_ref &_async_ref) :pool(_pool), stock(_stock), request(_request), handler(_handler), handler_ctx(_ctx), async_ref(_async_ref) {} /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock.Put(*item, !reuse); } }; /* * stock callback * */ void TranslateStockRequest::OnStockItemReady(StockItem &_item) { item = &(TranslateConnection &)_item; translate(pool, stock.GetEventLoop(), item->GetSocket(), *this, request, handler, handler_ctx, async_ref); } void TranslateStockRequest::OnStockItemError(GError *error) { handler.error(error, handler_ctx); } /* * constructor * */ TranslateStock * tstock_new(EventLoop &event_loop, const char *socket_path, unsigned limit) { return new TranslateStock(event_loop, socket_path, limit); } void tstock_free(TranslateStock *stock) { delete stock; } void tstock_translate(TranslateStock &stock, struct pool &pool, const TranslateRequest &request, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request, handler, ctx, async_ref); stock.Get(pool, *r, async_ref); }
/* * Connection pooling for the translation server. * * author: Max Kellermann <[email protected]> */ #include "tstock.hxx" #include "TranslateHandler.hxx" #include "translate_client.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "stock/GetHandler.hxx" #include "lease.hxx" #include "pool.hxx" #include "gerrno.h" #include "net/AllocatedSocketAddress.hxx" #include "net/SocketDescriptor.hxx" #include "event/SocketEvent.hxx" #include <daemon/log.h> #include <string.h> #include <errno.h> class TranslateConnection final : public HeapStockItem { SocketDescriptor s; SocketEvent event; public: explicit TranslateConnection(CreateStockItem c) :HeapStockItem(c), event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)) {} ~TranslateConnection() override { if (s.IsDefined()) event.Delete(); } private: bool CreateAndConnect(SocketAddress address) { assert(!s.IsDefined()); return s.Create(AF_LOCAL, SOCK_STREAM, 0) && s.Connect(address); } public: void CreateAndConnectAndFinish(SocketAddress address) { if (CreateAndConnect(address)) { event.Set(s.Get(), EV_READ); InvokeCreateSuccess(); } else { auto error = new_error_errno(); if (s.IsDefined()) s.Close(); InvokeCreateError(error); } } int GetSocket() { return s.Get(); } private: void EventCallback(gcc_unused short events) { char buffer; ssize_t nbytes = recv(s.Get(), &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle translation server connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data in idle translation server connection\n"); InvokeIdleDisconnect(); pool_commit(); } public: /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { event.Add(); return true; } }; static void tstock_create(gcc_unused void *ctx, CreateStockItem c, void *info, gcc_unused struct pool &caller_pool, gcc_unused struct async_operation_ref &async_ref) { const auto &address = *(const AllocatedSocketAddress *)info; auto *connection = new TranslateConnection(c); connection->CreateAndConnectAndFinish(address); } static constexpr StockClass tstock_class = { .create = tstock_create, }; class TranslateStock { EventLoop &event_loop; Stock stock; AllocatedSocketAddress address; public: TranslateStock(EventLoop &_event_loop, const char *path, unsigned limit) :event_loop(_event_loop), stock(event_loop, tstock_class, nullptr, "translation", limit, 8) { address.SetLocal(path); } EventLoop &GetEventLoop() { return event_loop; } void Get(struct pool &pool, StockGetHandler &handler, struct async_operation_ref &async_ref) { stock.Get(pool, &address, handler, async_ref); } void Put(StockItem &item, bool destroy) { stock.Put(item, destroy); } }; class TranslateStockRequest final : public StockGetHandler, Lease { struct pool &pool; TranslateStock &stock; TranslateConnection *item; const TranslateRequest &request; const TranslateHandler &handler; void *handler_ctx; struct async_operation_ref &async_ref; public: TranslateStockRequest(TranslateStock &_stock, struct pool &_pool, const TranslateRequest &_request, const TranslateHandler &_handler, void *_ctx, struct async_operation_ref &_async_ref) :pool(_pool), stock(_stock), request(_request), handler(_handler), handler_ctx(_ctx), async_ref(_async_ref) {} /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock.Put(*item, !reuse); } }; /* * stock callback * */ void TranslateStockRequest::OnStockItemReady(StockItem &_item) { item = &(TranslateConnection &)_item; translate(pool, stock.GetEventLoop(), item->GetSocket(), *this, request, handler, handler_ctx, async_ref); } void TranslateStockRequest::OnStockItemError(GError *error) { handler.error(error, handler_ctx); } /* * constructor * */ TranslateStock * tstock_new(EventLoop &event_loop, const char *socket_path, unsigned limit) { return new TranslateStock(event_loop, socket_path, limit); } void tstock_free(TranslateStock *stock) { delete stock; } void tstock_translate(TranslateStock &stock, struct pool &pool, const TranslateRequest &request, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto r = NewFromPool<TranslateStockRequest>(pool, stock, pool, request, handler, ctx, async_ref); stock.Get(pool, *r, async_ref); }
use class SocketEvent
tstock: use class SocketEvent
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
ec4c6f8546882e212f0ea6764d454b75978fe478
graf3d/eve7/inc/ROOT/REveDataSimpleProxyBuilderTemplate.hxx
graf3d/eve7/inc/ROOT/REveDataSimpleProxyBuilderTemplate.hxx
#ifndef ROOT7_REveDataProxySimpleBuilderTemplate #define ROOT7_REveDataProxySimpleBuilderTemplate #include <ROOT/REveDataSimpleProxyBuilder.hxx> namespace ROOT { namespace Experimental { template <typename T> class REveDataSimpleProxyBuilderTemplate : public REveDataSimpleProxyBuilder { public: REveDataSimpleProxyBuilderTemplate() : REveDataSimpleProxyBuilder("GL") { } protected: using REveDataSimpleProxyBuilder::Build; virtual void Build(const void *iData, int index, REveElement *itemHolder, const REveViewContext *context) { if(iData) { Build(*reinterpret_cast<const T*> (iData), index, itemHolder, context); } } using REveDataSimpleProxyBuilder::BuildViewType; virtual void BuildViewType(const void *iData, int index, REveElement *itemHolder, std::string viewType, const REveViewContext *context) { if(iData) { BuildViewType(*reinterpret_cast<const T*> (iData), index, itemHolder, viewType, context); } } virtual void Build(const T &/*iData*/, int index, REveElement */*itemHolder*/, const REveViewContext */*context*/) { throw std::runtime_error("virtual Build(const T&, int, REveElement&, const REveViewContext*) not implemented by inherited class."); } virtual void BuildViewType(const T &/*iData*/, int index, REveElement */*itemHolder*/, std::string /*viewType*/, const REveViewContext */*context*/) { throw std::runtime_error("virtual BuildViewType(const T&, int, REveElement&, const REveViewContext*) not implemented by inherited class."); } private: REveDataSimpleProxyBuilderTemplate(const REveDataSimpleProxyBuilderTemplate&); // stop default const REveDataSimpleProxyBuilderTemplate& operator=(const REveDataSimpleProxyBuilderTemplate&); // stop default }; } // namespace Experimental } // namespace ROOT #endif
#ifndef ROOT7_REveDataProxySimpleBuilderTemplate #define ROOT7_REveDataProxySimpleBuilderTemplate #include <ROOT/REveDataSimpleProxyBuilder.hxx> namespace ROOT { namespace Experimental { template <typename T> class REveDataSimpleProxyBuilderTemplate : public REveDataSimpleProxyBuilder { public: REveDataSimpleProxyBuilderTemplate() : REveDataSimpleProxyBuilder("GL") { } protected: void Build(const void *iData, int index, REveElement *itemHolder, const REveViewContext *context) override { if(iData) { Build(*reinterpret_cast<const T*> (iData), index, itemHolder, context); } } void Build(const T & /*iData*/, int /*index*/, REveElement */*itemHolder*/, const REveViewContext */*context*/) override { throw std::runtime_error("virtual Build(const T&, int, REveElement&, const REveViewContext*) not implemented by inherited class."); } void BuildViewType(const void *iData, int index, REveElement *itemHolder, std::string viewType, const REveViewContext *context) override { if(iData) { BuildViewType(*reinterpret_cast<const T*> (iData), index, itemHolder, viewType, context); } } void BuildViewType(const T &/*iData*/, int /*index*/, REveElement */*itemHolder*/, std::string /*viewType*/, const REveViewContext */*context*/) override { throw std::runtime_error("virtual BuildViewType(const T&, int, REveElement&, const REveViewContext*) not implemented by inherited class."); } private: REveDataSimpleProxyBuilderTemplate(const REveDataSimpleProxyBuilderTemplate&); // stop default const REveDataSimpleProxyBuilderTemplate& operator=(const REveDataSimpleProxyBuilderTemplate&); // stop default }; } // namespace Experimental } // namespace ROOT #endif
fix compiler warning, use override instead of virtual
[eve7] fix compiler warning, use override instead of virtual
C++
lgpl-2.1
karies/root,olifre/root,olifre/root,root-mirror/root,olifre/root,karies/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,olifre/root,karies/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,karies/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,karies/root
86298aec81cc10f2500d6730c92b3db9be3c5043
src/vector.hpp
src/vector.hpp
/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE A small class to carry a Vector data structure */ #pragma once #include <cmath> #include <iostream> namespace sim { struct Vector { double x, y, z, t; double norm_sq() const { return x * x + y * y + z * z; } double norm() const { return std::sqrt(norm_sq()); } Vector normed() const { return Vector(*this) / norm(); } Vector operator+(const Vector& rhs) const { return Vector{ x + rhs.x, y + rhs.y, z + rhs.z }; } Vector operator-(const Vector& rhs) const { return Vector{ x - rhs.x, y - rhs.y, z - rhs.z }; } Vector operator/(const double rhs) const { return Vector{ x / rhs, y / rhs, z / rhs }; } Vector& operator+=(const Vector& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } }; inline double dot(const Vector& u, const Vector& v) { return u.x * v.x + u.y * v.y + u.z * v.z; } inline Vector operator*(const Vector& u, const Vector& v) { return { u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x }; } inline Vector cross(const Vector& u, const Vector& v) { return u * v; } inline Vector operator*(double lhs, const Vector& rhs) { return { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; } inline Vector operator*(const Vector& lhs, double rhs) { return { rhs * lhs.x, rhs * lhs.y, rhs * lhs.z }; } inline Vector rotate(const Vector& v, Vector k, double th) // Rotate v about k by th // https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula { k = k / k.norm(); return v * std::cos(th) + cross(k, v) * std::sin(th) + k * dot(k, v) * (1 - std::cos(th)); } inline std::ostream& operator<<(std::ostream& os, const Vector& v) { os << v.x << ", " << v.y << ", " << v.z; return os; } struct LatLon { float lat, lon; // LatLon( float _lat, float _lon ) { lat = _lat; lon = _lon; } }; inline std::ostream& operator<<(std::ostream& os, const LatLon& ll) { os << ll.lat << ", " << ll.lon; return os; } } // namespace sim
/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE A small class to carry a Vector data structure */ #pragma once #include <cmath> #include <iostream> namespace sim { struct Vector { double x, y, z; double norm_sq() const { return x * x + y * y + z * z; } double norm() const { return std::sqrt(norm_sq()); } Vector normed() const { return Vector(*this) / norm(); } Vector operator+(const Vector& rhs) const { return Vector{ x + rhs.x, y + rhs.y, z + rhs.z }; } Vector operator-(const Vector& rhs) const { return Vector{ x - rhs.x, y - rhs.y, z - rhs.z }; } Vector operator/(const double rhs) const { return Vector{ x / rhs, y / rhs, z / rhs }; } Vector& operator+=(const Vector& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } }; inline double dot(const Vector& u, const Vector& v) { return u.x * v.x + u.y * v.y + u.z * v.z; } inline Vector operator*(const Vector& u, const Vector& v) { return { u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x }; } inline Vector cross(const Vector& u, const Vector& v) { return u * v; } inline Vector operator*(double lhs, const Vector& rhs) { return { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; } inline Vector operator*(const Vector& lhs, double rhs) { return { rhs * lhs.x, rhs * lhs.y, rhs * lhs.z }; } inline Vector rotate(const Vector& v, Vector k, double th) // Rotate v about k by th // https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula { k = k / k.norm(); return v * std::cos(th) + cross(k, v) * std::sin(th) + k * dot(k, v) * (1 - std::cos(th)); } inline std::ostream& operator<<(std::ostream& os, const Vector& v) { os << v.x << ", " << v.y << ", " << v.z; return os; } struct LatLon { float lat, lon; // LatLon( float _lat, float _lon ) { lat = _lat; lon = _lon; } }; inline std::ostream& operator<<(std::ostream& os, const LatLon& ll) { os << ll.lat << ", " << ll.lon; return os; } } // namespace sim
Remove t from Vector
Remove t from Vector This will now go in body state
C++
mit
kghose/groho
6e407d0274068a3fdbad4b81e264754c8ddf3e49
courier/serialization/pybind.cc
courier/serialization/pybind.cc
// Copyright 2020 DeepMind Technologies Limited. // // 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 <pybind11/pybind11.h> #include <pybind11/pytypes.h> #include "courier/platform/status_macros.h" #include "courier/platform/tensor_conversion.h" #include "courier/serialization/py_serialize.h" #include "pybind11_abseil/absl_casters.h" #include "pybind11_abseil/status_casters.h" namespace courier { namespace { namespace py = pybind11; absl::StatusOr<py::bytes> SerializeToString(const py::handle& handle) { PyObject* object = handle.ptr(); auto result = SerializePyObjectToString(object); if (!result.ok()) { return result.status(); } return py::bytes(result.value()); } py::object DeserializeFromString(const std::string& str) { auto result = DeserializePyObjectFromString(str); py::object object = py::reinterpret_steal<py::object>(result.value()); return object; } absl::StatusOr<SerializedObject> SerializeToProto(const py::handle& handle) { PyObject* object = handle.ptr(); auto result = SerializePyObject(object); if (!result.ok()) { return result.status(); } return result.value(); } absl::StatusOr<py::object> DeserializeFromProto( const SerializedObject& buffer) { COURIER_ASSIGN_OR_RETURN(auto tensor_lookup, CreateTensorLookup(buffer)); COURIER_ASSIGN_OR_RETURN(auto result, DeserializePyObjectUnsafe(buffer, tensor_lookup)); return py::reinterpret_steal<py::object>(result); } PYBIND11_MODULE(pybind, m) { py::google::ImportStatusModule(); m.def("SerializeToString", &SerializeToString, "Serializes Object to a string"); m.def("DeserializeFromString", &DeserializeFromString, "Deserializes object from a string"); m.def("SerializeToProto", &SerializeToProto, "Serializes object to a proto"); m.def("DeserializeFromProto", &DeserializeFromProto, "Deserializes object from a proto"); } } // namespace } // namespace courier
// Copyright 2020 DeepMind Technologies Limited. // // 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 <pybind11/pybind11.h> #include <pybind11/pytypes.h> #include "courier/platform/status_macros.h" #include "courier/platform/tensor_conversion.h" #include "courier/serialization/py_serialize.h" #include "pybind11_abseil/absl_casters.h" #include "pybind11_abseil/status_casters.h" namespace courier { namespace { namespace py = pybind11; absl::StatusOr<py::bytes> SerializeToString(const py::handle& handle) { PyObject* object = handle.ptr(); COURIER_ASSIGN_OR_RETURN(auto result, SerializePyObjectToString(object)); return py::bytes(result); } absl::StatusOr<py::object> DeserializeFromString(const std::string& str) { COURIER_ASSIGN_OR_RETURN(auto result, DeserializePyObjectFromString(str)); py::object object = py::reinterpret_steal<py::object>(result); return object; } absl::StatusOr<SerializedObject> SerializeToProto(const py::handle& handle) { PyObject* object = handle.ptr(); return SerializePyObject(object); } absl::StatusOr<py::object> DeserializeFromProto( const SerializedObject& buffer) { COURIER_ASSIGN_OR_RETURN(auto tensor_lookup, CreateTensorLookup(buffer)); COURIER_ASSIGN_OR_RETURN(auto result, DeserializePyObjectUnsafe(buffer, tensor_lookup)); return py::reinterpret_steal<py::object>(result); } PYBIND11_MODULE(pybind, m) { py::google::ImportStatusModule(); m.def("SerializeToString", &SerializeToString, "Serializes Object to a string"); m.def("DeserializeFromString", &DeserializeFromString, "Deserializes object from a string"); m.def("SerializeToProto", &SerializeToProto, "Serializes object to a proto"); m.def("DeserializeFromProto", &DeserializeFromProto, "Deserializes object from a proto"); } } // namespace } // namespace courier
Use Courier macros in pybind.
Use Courier macros in pybind. PiperOrigin-RevId: 425835248 Change-Id: Ieea4a3137c81bf8af56fa445140d039222a6e30c
C++
apache-2.0
deepmind/launchpad,deepmind/launchpad,deepmind/launchpad,deepmind/launchpad
10d2adf012d4462d30654da4b40b115fe2b5b4ee
cpp/Classes/HelloWorldScene.cpp
cpp/Classes/HelloWorldScene.cpp
#include "HelloWorldScene.h" #include "ui/CocosGUI.h" #include "cocostudio/CocoStudio.h" #include "PluginGoogleAnalytics/PluginGoogleAnalytics.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } FileUtils::getInstance()->addSearchPath("res"); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto rootNode = CSLoader::createNode("MainScene.csb"); addChild(rootNode); auto btnEvent = rootNode->getChildByName<ui::Button*>("btnEvent"); btnEvent->addClickEventListener(CC_CALLBACK_1(HelloWorld::onEvent, this)); auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); return true; } void HelloWorld::onEvent(cocos2d::Ref* sender) { sdkbox::PluginGoogleAnalytics::logEvent("Test", "Click", "", 1); } void HelloWorld::menuCloseCallback(Ref* pSender) { Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
#include "HelloWorldScene.h" #include "ui/CocosGUI.h" #include "cocostudio/CocoStudio.h" #include "PluginGoogleAnalytics/PluginGoogleAnalytics.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } FileUtils::getInstance()->addSearchPath("res"); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto rootNode = CSLoader::createNode("MainScene.csb"); addChild(rootNode); auto btnEvent = rootNode->getChildByName<ui::Button*>("btnEvent"); btnEvent->addClickEventListener(CC_CALLBACK_1(HelloWorld::onEvent, this)); auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); return true; } void HelloWorld::onEvent(cocos2d::Ref* sender) { sdkbox::PluginGoogleAnalytics::logEvent("Test", "Click", "", 1); sdkbox::PluginGoogleAnalytics::dispatchHits(); } void HelloWorld::menuCloseCallback(Ref* pSender) { Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
test google analytics
test google analytics
C++
mit
wanghuan1115/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,wanghuan1115/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample,tinybearc/sdkbox-ga-sample
0414489e739b9949834a3f24c3a494e6b291b465
daemon/src/Salamandre-daemon/ServerBroadcast.cpp
daemon/src/Salamandre-daemon/ServerBroadcast.cpp
#include <Salamandre-daemon/ServerBroadcast.hpp> #include <Salamandre-daemon/ServerFunctions.hpp> #include <Socket/FuncWrapper.hpp> #include <Salamandre-stats/stats.hpp> #include <chrono> namespace salamandre { ServerBroadcast::ServerBroadcast(int port,int server_port): port(port), server_port(server_port), run(false), sock_listen(ntw::Socket::Dommaine::IP,ntw::Socket::Type::UDP,IPPROTO_UDP), sock_send(ntw::Socket::Dommaine::IP,ntw::Socket::UDP,IPPROTO_UDP) { sock_listen.connect("0.0.0.0",port); sock_listen.setReusable(true); sock_listen.bind(); sock_send.connect(port); sock_send.setBroadcast(true); sock_send.connect("255.255.255.255",port); } void ServerBroadcast::init() { stats::Stats::init(); } void ServerBroadcast::close() { stats::Stats::close(); } void ServerBroadcast::start() { run = true; this->thread[0] = std::thread(&ServerBroadcast::start_listener,this); this->thread[1] = std::thread(&ServerBroadcast::start_sender,this); } void ServerBroadcast::wait() { this->thread[0].join(); this->thread[1].join(); } void ServerBroadcast::sendThisIsMyInfo() { sock_send<<(int)salamandre::srv::thisIsMyInfos <<server_port; sock_send.send(sock_listen); sock_send.clear(); } void ServerBroadcast::sendILostMyData(int id_medecin,int id_patient,std::string filename) { sock_send<<(int)salamandre::srv::iLostMyData <<id_medecin <<id_patient <<filename <<server_port; std::cout<<"Send:"<<sock_send<<std::endl; sock_send.send(sock_listen); sock_send.clear(); } void ServerBroadcast::start_listener() { while(this->run) { sock_listen.clear(); ntw::SocketSerialized from(ntw::Socket::Dommaine::IP,ntw::Socket::Type::UDP); from.connect(port); sock_listen.receive(from); std::cout<<sock_listen<<std::endl; int id; sock_listen>>id; std::cout<<"Recv id "<<id<<std::endl; switch(id) { case salamandre::srv::func::thisIsMyInfos : { int port; sock_listen>>port; funcThisIsMyInfos(from,port); }break; case salamandre::srv::func::iLostMyData : { int id_medecin,id_patient,port; std::string filename; sock_listen>>id_medecin>>id_patient>>filename>>port; funcILostMyData(from,id_medecin,id_patient,filename,port); }break; default: ///\todo WTF are you doing? break; } } } void ServerBroadcast::start_sender() { const std::chrono::seconds duration(30); const std::chrono::milliseconds step(500); std::chrono::milliseconds elapsed_time(0); sendThisIsMyInfo(); while(this->run) { if (elapsed_time > duration) { sendThisIsMyInfo(); elapsed_time = std::chrono::milliseconds(0); } std::this_thread::sleep_for(step); elapsed_time += step; } } void ServerBroadcast::stop() { run = false; sock_listen.shutdown(); } void ServerBroadcast::funcThisIsMyInfos(ntw::SocketSerialized& from,int port) { std::cout<<"Recv info from:"<<from.getIp()<<", Port"<<port<<std::endl; ///\todo TODO check if this is me stats::Stats::add_node(from.getIp(),port); } void ServerBroadcast::funcILostMyData(ntw::SocketSerialized& from,int id_medecin,int id_patient,std::string filename,int port) { std::cout<<"funcILostMyData from:"<<from.getIp()<<" id_medecin:"<<id_medecin<<" id_patient:"<<id_patient<<" filename:"<<filename<<" port:"<<port<<std::endl; std::thread t(salamandre::srv::funcILostMyData,id_medecin,id_patient,filename,port,from.getIp()); t.detach(); } }
#include <Salamandre-daemon/ServerBroadcast.hpp> #include <Salamandre-daemon/ServerFunctions.hpp> #include <Socket/FuncWrapper.hpp> #include <Salamandre-stats/stats.hpp> #include <chrono> namespace salamandre { ServerBroadcast::ServerBroadcast(int port,int server_port): port(port), server_port(server_port), run(false), sock_listen(ntw::Socket::Dommaine::IP,ntw::Socket::Type::UDP,IPPROTO_UDP), sock_send(ntw::Socket::Dommaine::IP,ntw::Socket::UDP,IPPROTO_UDP) { sock_listen.connect("0.0.0.0",port); sock_listen.setReusable(true); sock_listen.bind(); sock_send.connect(port); sock_send.setBroadcast(true); sock_send.connect("255.255.255.255",port); } void ServerBroadcast::init() { stats::Stats::init(); } void ServerBroadcast::close() { stats::Stats::close(); } void ServerBroadcast::start() { run = true; this->thread[0] = std::thread(&ServerBroadcast::start_listener,this); this->thread[1] = std::thread(&ServerBroadcast::start_sender,this); } void ServerBroadcast::wait() { this->thread[0].join(); this->thread[1].join(); } void ServerBroadcast::sendThisIsMyInfo() { sock_send<<(int)salamandre::srv::thisIsMyInfos <<server_port; sock_send.send(sock_listen); sock_send.clear(); } void ServerBroadcast::sendILostMyData(int id_medecin,int id_patient,std::string filename) { sock_send<<(int)salamandre::srv::iLostMyData <<id_medecin <<id_patient <<filename <<server_port; std::cout<<"Send:"<<sock_send<<std::endl; sock_send.send(sock_listen); sock_send.clear(); } void ServerBroadcast::start_listener() { while(this->run) { sock_listen.clear(); ntw::SocketSerialized from(ntw::Socket::Dommaine::IP,ntw::Socket::Type::UDP); from.connect(port); sock_listen.receive(from); int id; sock_listen>>id; std::cout<<"Recv id "<<id<<std::endl; switch(id) { case salamandre::srv::func::thisIsMyInfos : { int port; sock_listen>>port; funcThisIsMyInfos(from,port); }break; case salamandre::srv::func::iLostMyData : { int id_medecin,id_patient,port; std::string filename; sock_listen>>id_medecin>>id_patient>>filename>>port; funcILostMyData(from,id_medecin,id_patient,filename,port); }break; default: ///\todo WTF are you doing? break; } } } void ServerBroadcast::start_sender() { const std::chrono::seconds duration(30); const std::chrono::milliseconds step(500); std::chrono::milliseconds elapsed_time(0); sendThisIsMyInfo(); while(this->run) { if (elapsed_time > duration) { sendThisIsMyInfo(); elapsed_time = std::chrono::milliseconds(0); } std::this_thread::sleep_for(step); elapsed_time += step; } } void ServerBroadcast::stop() { run = false; sock_listen.shutdown(); } void ServerBroadcast::funcThisIsMyInfos(ntw::SocketSerialized& from,int port) { std::cout<<"Recv info from:"<<from.getIp()<<", Port"<<port<<std::endl; ///\todo TODO check if this is me stats::Stats::add_node(from.getIp(),port); } void ServerBroadcast::funcILostMyData(ntw::SocketSerialized& from,int id_medecin,int id_patient,std::string filename,int port) { std::cout<<"funcILostMyData from:"<<from.getIp()<<" id_medecin:"<<id_medecin<<" id_patient:"<<id_patient<<" filename:"<<filename<<" port:"<<port<<std::endl; std::thread t(salamandre::srv::funcILostMyData,id_medecin,id_patient,filename,port,from.getIp()); t.detach(); } }
remove debug print
remove debug print
C++
bsd-2-clause
Krozark/Salamandre,Krozark/Salamandre
453ab8783895dda2880976840818b81cc08f2111
include/fl/model/observation/robust_feature_obsrv_model.hpp
include/fl/model/observation/robust_feature_obsrv_model.hpp
/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file robust_feature_obsrv_model.hpp * \date August 2015 * \author Jan Issac ([email protected]) */ #pragma once #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/util/types.hpp> #include <fl/util/descriptor.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/observation/interface/observation_density.hpp> #include <fl/model/observation/interface/observation_function.hpp> namespace fl { namespace internal { enum RobustFeatureDimension { RobustFeatureDimExt = 2 }; } /** * \ingroup observation_models * * \brief Represents an observation function or model which takes an arbitrary * observation model (one that implements an ObservationFunction & a * an ObservationDensity) as an argument and maps it into a feature space * used by the RobustGaussianFilter. */ template <typename ObsrvModel> class RobustFeatureObsrvModel : public ObservationFunction< /* Obsrv type of the size SizeOf<ObsrvModel::Obsrv> + 2 */ typename VariateOfSize< JoinSizes< SizeOf<typename ObsrvModel::Obsrv>::Value, internal::RobustFeatureDimExt >::Value >::Type, typename ObsrvModel::State, typename ObsrvModel::Noise>, public Descriptor { private: typedef RobustFeatureObsrvModel<ObsrvModel> This; public: /** * \brief \a InputObsrv type which is the same as * ObsrvModel::Obsrv. \a InputObsrv is mapped into the feature space. * The resulting type is \a Obsrv. */ typedef typename ObsrvModel::Obsrv InputObsrv; /** * \brief \a Obsrv (\f$y_t\f$) type which is a variate of the size * SizeOf<InputObsrv> + 2. \a Obsrv reside in the feature space. */ typedef typename VariateOfSize< JoinSizes< SizeOf<typename ObsrvModel::Obsrv>::Value, internal::RobustFeatureDimExt >::Value >::Type Obsrv; /** * \brief \a State (\f$x_t\f$) type which is the same as ObsrvModel::State */ typedef typename ObsrvModel::State State; /** * \brief \a Noise (\f$x_t\f$) type which is the same as ObsrvModel::Noise */ typedef typename ObsrvModel::Noise Noise; public: /** * \brief Constructs a robust feature observation model for the robust * gaussian filter * * \param obsrv_model Reference to the source observation model * * \note This model takes only a reference of to an existing lvalue of the * source model */ explicit RobustFeatureObsrvModel(ObsrvModel& obsrv_model) : obsrv_model_(obsrv_model), body_gaussian_(obsrv_model.obsrv_dimension()) { } /** * \brief Overridable default destructor */ virtual ~RobustFeatureObsrvModel() { } /** * \brief observation Returns a feature mapped observation */ Obsrv observation(const State& state, const Noise& noise) const override { auto input_obsrv = obsrv_model_.observation(state, noise); Obsrv y = feature_obsrv(input_obsrv); return y; // RVO } /** * \brief Computes the robust feature given an input feature fron the * source observation model */ virtual Obsrv feature_obsrv(const InputObsrv& input_obsrv) const { auto y = Obsrv(obsrv_dimension()); auto weight = obsrv_model_.weight_threshold(); auto prob_y = body_gaussian_.probability(input_obsrv); auto prob_tail = obsrv_model_ .tail_model() .probability(input_obsrv, mean_state_); auto normalizer = 1.0 / ((1.0 - weight) * prob_y + weight * prob_tail); if(weight == 0) { y(0) = 0.0; if (internal::RobustFeatureDimExt == 2) y(1) = 1.0; y.bottomRows(obsrv_model_.obsrv_dimension()) = input_obsrv; } else if( !std::isfinite(1.0 / (weight * prob_tail)) ) { std::cout << "prob_tail is too small: " << prob_tail << " weight: " << weight << " input_obsrv: " << input_obsrv.transpose() << " normalizer: " << normalizer << std::endl; exit(-1); } else if(std::isfinite(normalizer)) { y(0) = weight * prob_tail; if (internal::RobustFeatureDimExt == 2) y(1) = (1.0 - weight) * prob_y; y.bottomRows(obsrv_model_.obsrv_dimension()) = (1.0 - weight) * prob_y * input_obsrv; y *= normalizer; } else // if the normalizer is not finite, we assume that the { std::cout << "normalizer in robust feature is not finite " << " weight: " << weight << " input_obsrv: " << input_obsrv.transpose() << " normalizer: " << normalizer << std::endl; exit(-1); } return y; } /** * \brief Sets the feature function \a mean_state; * \param mean_state \f$ \mu_x \f$ * * \todo PAPER REF */ virtual void mean_state(const State& mean_state) { mean_state_ = mean_state; } /** * \brief Sets the feature function body moments * \param body_gaussian \f${\cal N}(y_t\mid \mu_{y}, \Sigma_{yy})\f$ * * \todo PAPER REF */ virtual void body_moments( const typename FirstMomentOf<InputObsrv>::Type& mean_obsrv, const typename SecondMomentOf<InputObsrv>::Type& cov_obsrv) { body_gaussian_.mean(mean_obsrv); body_gaussian_.covariance(cov_obsrv); } /** * \brief Returns the dimension of the \a Obsrv which is dim(\a Obsrv) + 2 */ int obsrv_dimension() const override { return obsrv_model_.obsrv_dimension() + internal::RobustFeatureDimExt; } int noise_dimension() const override { return obsrv_model_.noise_dimension(); } int state_dimension() const override { return obsrv_model_.state_dimension(); } ObsrvModel& embedded_obsrv_model() { return obsrv_model_; } const ObsrvModel& embedded_obsrv_model() const { return obsrv_model_; } virtual int id() const { return obsrv_model_.id(); } virtual void id(int new_id) { obsrv_model_.id(new_id); } virtual std::string name() const { return "RobustFeatureObsrvModel<" + this->list_arguments(embedded_obsrv_model().name()) + ">"; } virtual std::string description() const { return "Robust feature observation model with " + this->list_descriptions(embedded_obsrv_model().description()); } protected: /** \cond internal */ /** * \brief Reference to the ource observation model */ ObsrvModel& obsrv_model_; /** * \brief \f${\cal N}(y_t\mid \mu_{y}, \Sigma_{yy})\f$ */ Gaussian<InputObsrv> body_gaussian_; /** * \brief \f$\mu_x\f$ */ State mean_state_; /* \endcond */ }; }
/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file robust_feature_obsrv_model.hpp * \date August 2015 * \author Jan Issac ([email protected]) */ #pragma once #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/util/types.hpp> #include <fl/util/descriptor.hpp> #include <fl/distribution/gaussian.hpp> #include <fl/model/observation/interface/observation_density.hpp> #include <fl/model/observation/interface/observation_function.hpp> namespace fl { namespace internal { enum RobustFeatureDimension { RobustFeatureDimExt = 2 }; } /** * \ingroup observation_models * * \brief Represents an observation function or model which takes an arbitrary * observation model (one that implements an ObservationFunction & a * an ObservationDensity) as an argument and maps it into a feature space * used by the RobustGaussianFilter. */ template <typename ObsrvModel> class RobustFeatureObsrvModel : public ObservationFunction< /* Obsrv type of the size SizeOf<ObsrvModel::Obsrv> + 2 */ typename VariateOfSize< JoinSizes< SizeOf<typename ObsrvModel::Obsrv>::Value, internal::RobustFeatureDimExt >::Value >::Type, typename ObsrvModel::State, typename ObsrvModel::Noise>, public Descriptor { private: typedef RobustFeatureObsrvModel<ObsrvModel> This; public: /** * \brief \a InputObsrv type which is the same as * ObsrvModel::Obsrv. \a InputObsrv is mapped into the feature space. * The resulting type is \a Obsrv. */ typedef typename ObsrvModel::Obsrv InputObsrv; /** * \brief \a Obsrv (\f$y_t\f$) type which is a variate of the size * SizeOf<InputObsrv> + 2. \a Obsrv reside in the feature space. */ typedef typename VariateOfSize< JoinSizes< SizeOf<typename ObsrvModel::Obsrv>::Value, internal::RobustFeatureDimExt >::Value >::Type Obsrv; /** * \brief \a State (\f$x_t\f$) type which is the same as ObsrvModel::State */ typedef typename ObsrvModel::State State; /** * \brief \a Noise (\f$x_t\f$) type which is the same as ObsrvModel::Noise */ typedef typename ObsrvModel::Noise Noise; public: /** * \brief Constructs a robust feature observation model for the robust * gaussian filter * * \param obsrv_model Reference to the source observation model * * \note This model takes only a reference of to an existing lvalue of the * source model */ explicit RobustFeatureObsrvModel(ObsrvModel& obsrv_model) : obsrv_model_(obsrv_model), body_gaussian_(obsrv_model.obsrv_dimension()) { } /** * \brief Overridable default destructor */ virtual ~RobustFeatureObsrvModel() { } /** * \brief observation Returns a feature mapped observation */ Obsrv observation(const State& state, const Noise& noise) const override { auto input_obsrv = obsrv_model_.observation(state, noise); Obsrv y = feature_obsrv(input_obsrv); return y; // RVO } /** * \brief Computes the robust feature given an input feature fron the * source observation model */ virtual Obsrv feature_obsrv(const InputObsrv& input_obsrv) const { auto y = Obsrv(obsrv_dimension()); //! \todo BG changes if(!std::isfinite(input_obsrv(0))) return y; auto weight = obsrv_model_.weight_threshold(); auto prob_y = body_gaussian_.probability(input_obsrv); auto prob_tail = obsrv_model_ .tail_model() .probability(input_obsrv, mean_state_); auto normalizer = 1.0 / ((1.0 - weight) * prob_y + weight * prob_tail); if(weight == 0) { y(0) = 0.0; if (internal::RobustFeatureDimExt == 2) y(1) = 1.0; y.bottomRows(obsrv_model_.obsrv_dimension()) = input_obsrv; } else if( !std::isfinite(1.0 / (weight * prob_tail)) ) { std::cout << "prob_tail is too small: " << prob_tail << " weight: " << weight << " input_obsrv: " << input_obsrv.transpose() << " normalizer: " << normalizer << std::endl; exit(-1); } else if(std::isfinite(normalizer)) { y(0) = weight * prob_tail; if (internal::RobustFeatureDimExt == 2) y(1) = (1.0 - weight) * prob_y; y.bottomRows(obsrv_model_.obsrv_dimension()) = (1.0 - weight) * prob_y * input_obsrv; y *= normalizer; } else // if the normalizer is not finite, we assume that the { std::cout << "normalizer in robust feature is not finite " << " weight: " << weight << " input_obsrv: " << input_obsrv.transpose() << " normalizer: " << normalizer << std::endl; exit(-1); } return y; } /** * \brief Sets the feature function \a mean_state; * \param mean_state \f$ \mu_x \f$ * * \todo PAPER REF */ virtual void mean_state(const State& mean_state) { mean_state_ = mean_state; } /** * \brief Sets the feature function body moments * \param body_gaussian \f${\cal N}(y_t\mid \mu_{y}, \Sigma_{yy})\f$ * * \todo PAPER REF */ virtual void body_moments( const typename FirstMomentOf<InputObsrv>::Type& mean_obsrv, const typename SecondMomentOf<InputObsrv>::Type& cov_obsrv) { body_gaussian_.mean(mean_obsrv); body_gaussian_.covariance(cov_obsrv); } /** * \brief Returns the dimension of the \a Obsrv which is dim(\a Obsrv) + 2 */ int obsrv_dimension() const override { return obsrv_model_.obsrv_dimension() + internal::RobustFeatureDimExt; } int noise_dimension() const override { return obsrv_model_.noise_dimension(); } int state_dimension() const override { return obsrv_model_.state_dimension(); } ObsrvModel& embedded_obsrv_model() { return obsrv_model_; } const ObsrvModel& embedded_obsrv_model() const { return obsrv_model_; } virtual int id() const { return obsrv_model_.id(); } virtual void id(int new_id) { obsrv_model_.id(new_id); } virtual std::string name() const { return "RobustFeatureObsrvModel<" + this->list_arguments(embedded_obsrv_model().name()) + ">"; } virtual std::string description() const { return "Robust feature observation model with " + this->list_descriptions(embedded_obsrv_model().description()); } public: /** \cond internal */ /** * \brief Reference to the ource observation model */ ObsrvModel& obsrv_model_; /** * \brief \f${\cal N}(y_t\mid \mu_{y}, \Sigma_{yy})\f$ */ Gaussian<InputObsrv> body_gaussian_; /** * \brief \f$\mu_x\f$ */ State mean_state_; /* \endcond */ }; }
Return inf feature if input obsrv was inf
Return inf feature if input obsrv was inf
C++
mit
filtering-library/fl,SimonEbner/fl
0a9bb39299bca7771e3e5706c5110ed76a0359ab
libraries/blockchain/include/bts/blockchain/checkpoints.hpp
libraries/blockchain/include/bts/blockchain/checkpoints.hpp
#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) }, { 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) }, { 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) }, { 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) }, { 304000, bts::blockchain::block_id_type( "714cefe31d07f02705fe925647ad38604774d1a5" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain
#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) }, { 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) }, { 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) }, { 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) }, { 348800, bts::blockchain::block_id_type( "04a21330a0bc78fdd9dcc05e8bda153e2b8e35af" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain
Update checkpoint
Update checkpoint
C++
unlicense
camponez/bitshares,camponez/bitshares,bitshares/bitshares-0.x,frrp/bitshares,bitshares/bitshares,FollowMyVote/bitshares,jakeporter/Bitshares,jakeporter/Bitshares,RemitaBit/Remitabit,frrp/bitshares,bitshares/bitshares-0.x,jakeporter/Bitshares,RemitaBit/Remitabit,camponez/bitshares,frrp/bitshares,camponez/bitshares,camponez/bitshares,bitshares/bitshares-0.x,bitshares/bitshares-0.x,jakeporter/Bitshares,FollowMyVote/bitshares,jakeporter/Bitshares,FollowMyVote/bitshares,bitshares/devshares,FollowMyVote/bitshares,frrp/bitshares,RemitaBit/Remitabit,bitshares/bitshares,camponez/bitshares,bitshares/bitshares,frrp/bitshares,jakeporter/Bitshares,bitshares/devshares,bitshares/bitshares-0.x,bitshares/devshares,frrp/bitshares,bitshares/bitshares-0.x,RemitaBit/Remitabit,RemitaBit/Remitabit,bitshares/bitshares,FollowMyVote/bitshares,bitshares/bitshares,bitshares/devshares,RemitaBit/Remitabit,bitshares/devshares,bitshares/devshares,FollowMyVote/bitshares,bitshares/bitshares
6f27c3da0e9b5e14440d2129c43835f0344211f7
moses-cmd/src/Main.cpp
moses-cmd/src/Main.cpp
// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (c) 2006 University of Edinburgh All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Edinburgh 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. ***********************************************************************/ // example file on how to use moses library #ifdef WIN32 // Include Visual Leak Detector //#include <vld.h> #endif #include <fstream> #include "Main.h" #include "LatticePath.h" #include "FactorCollection.h" #include "Manager.h" #include "Phrase.h" #include "Util.h" #include "LatticePathList.h" #include "Timer.h" #include "IOCommandLine.h" #include "IOFile.h" #include "Sentence.h" #include "ConfusionNet.h" #include "TranslationAnalysis.h" #if HAVE_CONFIG_H #include "config.h" #else // those not using autoconf have to build MySQL support for now # define USE_MYSQL 1 #endif using namespace std; Timer timer; bool readInput(InputOutput *inputOutput, int inputType, InputType*& source) { delete source; source=inputOutput->GetInput((inputType ? static_cast<InputType*>(new ConfusionNet) : static_cast<InputType*>(new Sentence(Input)))); return (source ? true : false); } int main(int argc, char* argv[]) { // Welcome message TRACE_ERR( "Moses (built on " << __DATE__ << ")" << endl ); TRACE_ERR( "a beam search decoder for phrase-based statistical machine translation models" << endl ); TRACE_ERR( "written by Hieu Hoang, with contributions by Nicola Bertoldi, Ondrej Bojar," << endl << "Chris Callison-Burch, Alexandra Constantin, Brooke Cowan, Chris Dyer, Marcello" << endl << "Federico, Evan Herbst, Philipp Koehn, Christine Moran, Wade Shen, Richard Zens." << endl); TRACE_ERR( "(c) 2006 University of Edinburgh, Scotland" << endl ); TRACE_ERR( "command: " ); for(int i=0;i<argc;++i) TRACE_ERR( argv[i]<<" " ); TRACE_ERR(endl); // load data structures timer.start(); StaticData staticData; if (!staticData.LoadParameters(argc, argv)) return EXIT_FAILURE; // set up read/writing class InputOutput *inputOutput = GetInputOutput(staticData); // check on weights vector<float> weights = staticData.GetAllWeights(); IFVERBOSE(2) { std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager(); std::cerr << "The global weight vector looks like this:"; for (size_t j=0; j<weights.size(); j++) { std::cerr << " " << weights[j]; } std::cerr << "\n"; } // every score must have a weight! check that here: if(weights.size() != staticData.GetScoreIndexManager().GetTotalNumberOfScores()) { std::cerr << "ERROR: " << staticData.GetScoreIndexManager().GetTotalNumberOfScores() << " score components, but " << weights.size() << " weights defined" << std::endl; return EXIT_FAILURE; } if (inputOutput == NULL) return EXIT_FAILURE; // read each sentence & decode InputType *source=0; size_t lineCount = 0; while(readInput(inputOutput,staticData.GetInputType(),source)) { // note: source is only valid within this while loop! ResetUserTime(); VERBOSE(2,"\nTRANSLATING(" << ++lineCount << "): " << *source); staticData.InitializeBeforeSentenceProcessing(*source); Manager manager(*source, staticData); manager.ProcessSentence(); inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(), staticData.GetReportSegmentation(), staticData.GetReportAllFactors() ); // n-best size_t nBestSize = staticData.GetNBestSize(); if (nBestSize > 0) { VERBOSE(2,"WRITING " << nBestSize << " TRANSLATION ALTERNATIVES TO " << staticData.GetNBestFilePath() << endl); LatticePathList nBestList; manager.CalcNBest(nBestSize, nBestList,staticData.OnlyDistinctNBest()); inputOutput->SetNBest(nBestList, source->GetTranslationId()); RemoveAllInColl(nBestList); } if (staticData.IsDetailedTranslationReportingEnabled()) { TranslationAnalysis::PrintTranslationAnalysis(std::cerr, manager.GetBestHypothesis()); } IFVERBOSE(2) { PrintUserTime(std::cerr, "Sentence Decoding Time:"); } manager.CalcDecoderStatistics(staticData); staticData.CleanUpAfterSentenceProcessing(); } delete inputOutput; timer.check("End."); return EXIT_SUCCESS; } InputOutput *GetInputOutput(StaticData &staticData) { InputOutput *inputOutput; const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder() ,&outputFactorOrder = staticData.GetOutputFactorOrder(); FactorMask inputFactorUsed(inputFactorOrder); // io if (staticData.GetIOMethod() == IOMethodFile) { VERBOSE(2,"IO from File" << endl); string inputFileHash; list< Phrase > inputPhraseList; string filePath = staticData.GetParam("input-file")[0]; VERBOSE(2,"About to create ioFile" << endl); IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed , staticData.GetFactorCollection() , staticData.GetNBestSize() , staticData.GetNBestFilePath() , filePath); if(staticData.GetInputType()) { TRACE_ERR("Do not read input phrases for confusion net translation\n"); } else { VERBOSE(2,"About to GetInputPhrase\n"); ioFile->GetInputPhrase(inputPhraseList); } VERBOSE(2,"After GetInputPhrase" << endl); inputOutput = ioFile; inputFileHash = GetMD5Hash(filePath); VERBOSE(2,"About to LoadPhraseTables" << endl); staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList); ioFile->ResetSentenceId(); } else { VERBOSE(1,"IO from STDOUT/STDIN" << endl); inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed , staticData.GetFactorCollection() , staticData.GetNBestSize() , staticData.GetNBestFilePath()); staticData.LoadPhraseTables(); } staticData.LoadMapping(); timer.check("Created input-output object"); return inputOutput; }
// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (c) 2006 University of Edinburgh All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Edinburgh 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. ***********************************************************************/ // example file on how to use moses library #ifdef WIN32 // Include Visual Leak Detector #include <vld.h> #endif #include <fstream> #include "Main.h" #include "LatticePath.h" #include "FactorCollection.h" #include "Manager.h" #include "Phrase.h" #include "Util.h" #include "LatticePathList.h" #include "Timer.h" #include "IOCommandLine.h" #include "IOFile.h" #include "Sentence.h" #include "ConfusionNet.h" #include "TranslationAnalysis.h" #if HAVE_CONFIG_H #include "config.h" #else // those not using autoconf have to build MySQL support for now # define USE_MYSQL 1 #endif using namespace std; Timer timer; bool readInput(InputOutput *inputOutput, int inputType, InputType*& source) { delete source; source=inputOutput->GetInput((inputType ? static_cast<InputType*>(new ConfusionNet) : static_cast<InputType*>(new Sentence(Input)))); return (source ? true : false); } int main(int argc, char* argv[]) { // Welcome message TRACE_ERR( "Moses (built on " << __DATE__ << ")" << endl ); TRACE_ERR( "a beam search decoder for phrase-based statistical machine translation models" << endl ); TRACE_ERR( "written by Hieu Hoang, with contributions by Nicola Bertoldi, Ondrej Bojar," << endl << "Chris Callison-Burch, Alexandra Constantin, Brooke Cowan, Chris Dyer, Marcello" << endl << "Federico, Evan Herbst, Philipp Koehn, Christine Moran, Wade Shen, Richard Zens." << endl); TRACE_ERR( "(c) 2006 University of Edinburgh, Scotland" << endl ); TRACE_ERR( "command: " ); for(int i=0;i<argc;++i) TRACE_ERR( argv[i]<<" " ); TRACE_ERR(endl); // load data structures timer.start(); StaticData staticData; if (!staticData.LoadParameters(argc, argv)) return EXIT_FAILURE; // set up read/writing class InputOutput *inputOutput = GetInputOutput(staticData); // check on weights vector<float> weights = staticData.GetAllWeights(); IFVERBOSE(2) { std::cerr << "The score component vector looks like this:\n" << staticData.GetScoreIndexManager(); std::cerr << "The global weight vector looks like this:"; for (size_t j=0; j<weights.size(); j++) { std::cerr << " " << weights[j]; } std::cerr << "\n"; } // every score must have a weight! check that here: if(weights.size() != staticData.GetScoreIndexManager().GetTotalNumberOfScores()) { std::cerr << "ERROR: " << staticData.GetScoreIndexManager().GetTotalNumberOfScores() << " score components, but " << weights.size() << " weights defined" << std::endl; return EXIT_FAILURE; } if (inputOutput == NULL) return EXIT_FAILURE; // read each sentence & decode InputType *source=0; size_t lineCount = 0; while(readInput(inputOutput,staticData.GetInputType(),source)) { // note: source is only valid within this while loop! ResetUserTime(); VERBOSE(2,"\nTRANSLATING(" << ++lineCount << "): " << *source); staticData.InitializeBeforeSentenceProcessing(*source); Manager manager(*source, staticData); manager.ProcessSentence(); inputOutput->SetOutput(manager.GetBestHypothesis(), source->GetTranslationId(), staticData.GetReportSegmentation(), staticData.GetReportAllFactors() ); // n-best size_t nBestSize = staticData.GetNBestSize(); if (nBestSize > 0) { VERBOSE(2,"WRITING " << nBestSize << " TRANSLATION ALTERNATIVES TO " << staticData.GetNBestFilePath() << endl); LatticePathList nBestList; manager.CalcNBest(nBestSize, nBestList,staticData.OnlyDistinctNBest()); inputOutput->SetNBest(nBestList, source->GetTranslationId()); RemoveAllInColl(nBestList); } if (staticData.IsDetailedTranslationReportingEnabled()) { TranslationAnalysis::PrintTranslationAnalysis(std::cerr, manager.GetBestHypothesis()); } IFVERBOSE(2) { PrintUserTime(std::cerr, "Sentence Decoding Time:"); } manager.CalcDecoderStatistics(staticData); staticData.CleanUpAfterSentenceProcessing(); } delete inputOutput; timer.check("End."); return EXIT_SUCCESS; } InputOutput *GetInputOutput(StaticData &staticData) { InputOutput *inputOutput; const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder() ,&outputFactorOrder = staticData.GetOutputFactorOrder(); FactorMask inputFactorUsed(inputFactorOrder); // io if (staticData.GetIOMethod() == IOMethodFile) { VERBOSE(2,"IO from File" << endl); string inputFileHash; list< Phrase > inputPhraseList; string filePath = staticData.GetParam("input-file")[0]; VERBOSE(2,"About to create ioFile" << endl); IOFile *ioFile = new IOFile(inputFactorOrder, outputFactorOrder, inputFactorUsed , staticData.GetFactorCollection() , staticData.GetNBestSize() , staticData.GetNBestFilePath() , filePath); if(staticData.GetInputType()) { TRACE_ERR("Do not read input phrases for confusion net translation\n"); } else { VERBOSE(2,"About to GetInputPhrase\n"); ioFile->GetInputPhrase(inputPhraseList); } VERBOSE(2,"After GetInputPhrase" << endl); inputOutput = ioFile; inputFileHash = GetMD5Hash(filePath); VERBOSE(2,"About to LoadPhraseTables" << endl); staticData.LoadPhraseTables(true, inputFileHash, inputPhraseList); ioFile->ResetSentenceId(); } else { VERBOSE(1,"IO from STDOUT/STDIN" << endl); inputOutput = new IOCommandLine(inputFactorOrder, outputFactorOrder, inputFactorUsed , staticData.GetFactorCollection() , staticData.GetNBestSize() , staticData.GetNBestFilePath()); staticData.LoadPhraseTables(); } staticData.LoadMapping(); timer.check("Created input-output object"); return inputOutput; }
put back Visual Leak Detector for Win32 build
put back Visual Leak Detector for Win32 build git-svn-id: f5d636078e73450abf2183305c5e43efec2a5605@807 1f5c12ca-751b-0410-a591-d2e778427230
C++
lgpl-2.1
pjwilliams/mosesdecoder,emjotde/mosesdecoder_nmt,KonceptGeek/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,hychyc07/mosesdecoder,hychyc07/mosesdecoder,alvations/mosesdecoder,emjotde/mosesdecoder_nmt,pjwilliams/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,emjotde/mosesdecoder_nmt,moses-smt/mosesdecoder,pjwilliams/mosesdecoder,alvations/mosesdecoder,hychyc07/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,hychyc07/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,hychyc07/mosesdecoder,pjwilliams/mosesdecoder,tofula/mosesdecoder,emjotde/mosesdecoder_nmt,emjotde/mosesdecoder_nmt,hychyc07/mosesdecoder,emjotde/mosesdecoder_nmt,pjwilliams/mosesdecoder,hychyc07/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,hychyc07/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,pjwilliams/mosesdecoder,emjotde/mosesdecoder_nmt,KonceptGeek/mosesdecoder,alvations/mosesdecoder,hychyc07/mosesdecoder,alvations/mosesdecoder,alvations/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,emjotde/mosesdecoder_nmt,tofula/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,pjwilliams/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,pjwilliams/mosesdecoder,KonceptGeek/mosesdecoder,KonceptGeek/mosesdecoder,alvations/mosesdecoder,KonceptGeek/mosesdecoder,tofula/mosesdecoder,emjotde/mosesdecoder_nmt,hychyc07/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,pjwilliams/mosesdecoder,tofula/mosesdecoder,tofula/mosesdecoder,KonceptGeek/mosesdecoder,moses-smt/mosesdecoder,KonceptGeek/mosesdecoder,pjwilliams/mosesdecoder,emjotde/mosesdecoder_nmt
d90691fde2fc72b9e67089c591c830c05d90eaa7
lib/Simulation.cpp
lib/Simulation.cpp
// Simulation.cpp // // Implementation of the simulation objects // // Oliver W. Laslett (2015) // [email protected] // #include<Simulation.hpp> // ----- CONSTRUCTOR ----- Simulation::Simulation( const ParticleCluster g, const ad_vec init_state, const double stepsize, const unsigned int n, const double temp, const array_d field ) : geom( g ) , h( boost::extents[3] ) , stability( geom.computeStability( temp ) ) { setTimeStep( stepsize ); setSimLength( n ); setState( init_state ); setTemp( temp ); setField( field ); equilibrium_rng.seed(1001); } // ----- Setter methods ----- void Simulation::setSimLength( const unsigned int n ) { N=n; } void Simulation::setTimeStep( const double h ) { dt=h; } void Simulation::setField( const array_d field ) { h = field; } void Simulation::setTemp( const double t ) { if( t < 0 ) throw std::invalid_argument("Temperature T must be greater than" " zero."); T = t; } void Simulation::setState( const ad_vec s ) { size_t dim1=geom.getNParticles(), dim2=3; if( ( s.size() != dim1 ) or ( s[0].shape()[0] != dim2 ) ) throw std::invalid_argument( "State of the system must be (Nx2)" " - where N is the number of " "particles" ); state = s; } // ----- Getter methods ----- double Simulation::getTimeStep() const { return dt; } unsigned int Simulation::getSimLength() const { return N; } const ad_vec& Simulation::getState() const { return state; } double Simulation::getTemp() const { return T; } array_d Simulation::getField() const { return h; } ParticleCluster Simulation::getGeometry() const { return geom; } // ----- COMPUTE ARRHENIUS RATES ----- // determines the energy barriers and then the transition rate matrix_d // from the exponential Neel-Arrhenius law matrix_d Simulation::arrheniusMatrix_D() const { throw "NOT IMPLEMENTED"; } matrix_d Simulation::computeEnergyBarriers() const { throw "NOT IMPLMENTED"; } // Run the simulation - currently an integration of the Langevin // dynamics without field int Simulation::runFull() { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // Get the initial condition of the particle array_d init( boost::extents[3] ); for( array_d::index i=0; i!=3; ++i ) init[i] = state[0][i]; // Initialise the integrator and its RNG mt19937 rng2( 301 ); auto inte = Heun<double>( llg, init, 0.0, dtau, rng2 ); // store the solutions here matrix_d sols( boost::extents[N][3] ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // temporary state vector array_d state_temp( boost::extents[3] ); // Step the integrator and store the result at each step for( array_d::index n=0; n!=N; ++n ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); // renormalise the solution double norm = sqrt( currentState[0]*currentState[0] + currentState[1]*currentState[1] + currentState[2]*currentState[2] ); for( bidx k=0; k!=3; ++k ) state_temp[k] = currentState[k] / norm; inte.setState( state_temp ); // store the solutions for( array_d::index i=0; i!=3; ++i ) sols[n][i] = currentState[i]; } // Write the results to the hardrive boostToFile( sols, "llg.mag" ); return 1; // everything was fine } // Run the simulation // this runs the system N times and stores the final state // these states are then saved to the hard drive int Simulation::runEnsemble( unsigned int Nruns ) { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // Get the initial condition of the particle array_d init( boost::extents[3] ); for( array_d::index i=0; i!=3; ++i ) init[i] = state[0][i]; // Initialise the integrator and its RNG mt19937 rng( 301 ); auto inte = Heun<double>( llg, init, 0.0, dtau, rng ); // store the solutions here matrix_d sols( boost::extents[Nruns][3] ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // Run the integrator a number of times for( bidx m=0; m!=Nruns; ++m ) { // Reset the itegrator inte.reset(); // Step the integrator and store the result at each step for( array_d::index n=0; n!=N; ++n ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); } // for each time step // Store the final state of the system for( bidx i=0; i!=3; ++i ) sols[m][i] = currentState[i]; } // Write the results to the hardrive boostToFile( sols, "ensemble.mag" ); return 1; // everything was fine } // Computes the first passage time for a single particle in the absence of an // external field int Simulation::runFPT( const int N_ensemble, const bool alignup ) { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // each simulation in the ensemble has its own RNG // generate seeds here mt19937 seed_rng( 8888 ); std::vector<int> seeds; seeds.reserve( N_ensemble ); boost::uniform_int<> int_dist; for( auto &i : seeds ) i = int_dist( seed_rng ); // store the fpt for each run array_d fpt( extents[N_ensemble] ); // run for every simulation in the ensemble #pragma omp parallel for for( bidx i=0; i<N_ensemble; ++i ) { // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // The initial condition of the particle is determined by the flag // if align up is true, then particle is initially such that mz=1 array_d init( boost::extents[3] ); if( alignup ) { init[0] = 0; init[1] = 0; init[2] = 1; } // if it is false then the initial condition is drawn from the // equilibrium initial condition else init = equilibriumState(); // Initialise the integrator and its RNG mt19937 heun_rng( seeds[i] ); auto inte = Heun<double>( llg, init, 0.0, dtau, heun_rng ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // Step the integrator until switch occurs // then store the time while( 1 ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); // check the end condition if( currentState[2] < 0 ) break; } // store the time fpt[i] = inte.getTime(); } // Write the results to the hardrive boostToFile( fpt, "llg.fpt" ); return 1; // everything was fine } // returns a random state from the equilibrium distribution array_d Simulation::equilibriumState() { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // define the pdf auto pdf = [&p, this]( double theta ) { return sin( theta) * exp( -p.getK()*p.getV()*pow( sin( theta ), 2 ) / ( Constants::KB * T ) ); }; // find the max array_d angles( extents[10000] ); for( bidx i=0; i!=10000; ++i ) angles[i] = i * M_PI_2 / 10000; double max = 0.0; for( auto &t : angles ) if( pdf( t ) > max) max = pdf( t ); // use uniform distribution as the candidate density // with M 10% higher that the max of target dist static boost::random::uniform_real_distribution<> gen_candidate( 0,M_PI ); static boost::random::uniform_real_distribution<> gen_check( 0,1 ); double M = 1.1 * max; // Rejection rate algorithm double candidate = 0; while( 1 ) { candidate = gen_candidate( equilibrium_rng ); double acceptance = pdf( candidate ) / M; double check = gen_check( equilibrium_rng ); if( acceptance > check ) break; } array_d init_state( extents[3] ); init_state[0] = 0; init_state[1] = 0; init_state[2] = cos( candidate ); return init_state; }
// Simulation.cpp // // Implementation of the simulation objects // // Oliver W. Laslett (2015) // [email protected] // #include<Simulation.hpp> // ----- CONSTRUCTOR ----- Simulation::Simulation( const ParticleCluster g, const ad_vec init_state, const double stepsize, const unsigned int n, const double temp, const array_d field ) : geom( g ) , h( boost::extents[3] ) , stability( geom.computeStability( temp ) ) { setTimeStep( stepsize ); setSimLength( n ); setState( init_state ); setTemp( temp ); setField( field ); equilibrium_rng.seed(1001); } // ----- Setter methods ----- void Simulation::setSimLength( const unsigned int n ) { N=n; } void Simulation::setTimeStep( const double h ) { dt=h; } void Simulation::setField( const array_d field ) { h = field; } void Simulation::setTemp( const double t ) { if( t < 0 ) throw std::invalid_argument("Temperature T must be greater than" " zero."); T = t; } void Simulation::setState( const ad_vec s ) { size_t dim1=geom.getNParticles(), dim2=3; if( ( s.size() != dim1 ) or ( s[0].shape()[0] != dim2 ) ) throw std::invalid_argument( "State of the system must be (Nx2)" " - where N is the number of " "particles" ); state = s; } // ----- Getter methods ----- double Simulation::getTimeStep() const { return dt; } unsigned int Simulation::getSimLength() const { return N; } const ad_vec& Simulation::getState() const { return state; } double Simulation::getTemp() const { return T; } array_d Simulation::getField() const { return h; } ParticleCluster Simulation::getGeometry() const { return geom; } // ----- COMPUTE ARRHENIUS RATES ----- // determines the energy barriers and then the transition rate matrix_d // from the exponential Neel-Arrhenius law matrix_d Simulation::arrheniusMatrix_D() const { throw "NOT IMPLEMENTED"; } matrix_d Simulation::computeEnergyBarriers() const { throw "NOT IMPLMENTED"; } // Run the simulation - currently an integration of the Langevin // dynamics without field int Simulation::runFull() { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // Get the initial condition of the particle array_d init( boost::extents[3] ); for( array_d::index i=0; i!=3; ++i ) init[i] = state[0][i]; // Initialise the integrator and its RNG mt19937 rng2( 301 ); auto inte = Heun<double>( llg, init, 0.0, dtau, rng2 ); // store the solutions here matrix_d sols( boost::extents[N][3] ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // temporary state vector array_d state_temp( boost::extents[3] ); // Step the integrator and store the result at each step for( array_d::index n=0; n!=N; ++n ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); // renormalise the solution double norm = sqrt( currentState[0]*currentState[0] + currentState[1]*currentState[1] + currentState[2]*currentState[2] ); for( bidx k=0; k!=3; ++k ) state_temp[k] = currentState[k] / norm; inte.setState( state_temp ); // store the solutions for( array_d::index i=0; i!=3; ++i ) sols[n][i] = currentState[i]; } // Write the results to the hardrive boostToFile( sols, "llg.mag" ); return 1; // everything was fine } // Run the simulation // this runs the system N times and stores the final state // these states are then saved to the hard drive int Simulation::runEnsemble( unsigned int Nruns ) { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // Get the initial condition of the particle array_d init( boost::extents[3] ); for( array_d::index i=0; i!=3; ++i ) init[i] = state[0][i]; // Initialise the integrator and its RNG mt19937 rng( 301 ); auto inte = Heun<double>( llg, init, 0.0, dtau, rng ); // store the solutions here matrix_d sols( boost::extents[Nruns][3] ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // Run the integrator a number of times for( bidx m=0; m!=Nruns; ++m ) { // Reset the itegrator inte.reset(); // Step the integrator and store the result at each step for( array_d::index n=0; n!=N; ++n ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); } // for each time step // Store the final state of the system for( bidx i=0; i!=3; ++i ) sols[m][i] = currentState[i]; } // Write the results to the hardrive boostToFile( sols, "ensemble.mag" ); return 1; // everything was fine } // Computes the first passage time for a single particle in the absence of an // external field int Simulation::runFPT( const int N_ensemble, const bool alignup ) { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // The thermal field intensity for reduced simulation double therm_strength{std::sqrt( p.getAlpha() * Constants::KB * T / ( p.getK() * p.getV() * ( 1 + std::pow( p.getAlpha(),2 ) ) ) ) }; // Compute the reduced time for the simulation double Hk{ 2 * p.getK() / ( Constants::MU0 * p.getMs() ) }; double t_factor{ Constants::GYROMAG * Constants::MU0 * Hk / ( 1+pow( p.getAlpha(), 2 ) ) }; double dtau = dt * t_factor; // compute the reduced external field array_d happ( extents[3] ); for( bidx i=0; i!=3; ++i ) happ[i] = h[i]/Hk; // each simulation in the ensemble has its own RNG // generate seeds here mt19937 seed_rng( 8888 ); std::vector<int> seeds; seeds.reserve( N_ensemble ); boost::uniform_int<> int_dist; for( auto &i : seeds ) i = int_dist( seed_rng ); // store the fpt for each run array_d fpt( extents[N_ensemble] ); // run for every simulation in the ensemble #pragma omp parallel for schedule(dynamic, 1) for( bidx i=0; i<N_ensemble; ++i ) { // Set up an LLG equation for the particle // finite temperature with the reduced field StocLLG<double> llg( therm_strength, p.getAlpha(), happ[0], happ[1], happ[2] ); // The initial condition of the particle is determined by the flag // if align up is true, then particle is initially such that mz=1 array_d init( boost::extents[3] ); if( alignup ) { init[0] = 0; init[1] = 0; init[2] = 1; } // if it is false then the initial condition is drawn from the // equilibrium initial condition else init = equilibriumState(); // Initialise the integrator and its RNG mt19937 heun_rng( seeds[i] ); auto inte = Heun<double>( llg, init, 0.0, dtau, heun_rng ); // reference to the current state and the field const array_d& currentState = inte.getState(); array_d& currentField = llg.getReducedFieldRef(); // Step the integrator until switch occurs // then store the time while( 1 ) { // first compute the field due to the anisotropy // and put that in the field vector p.computeAnisotropyField( currentField, currentState ); // then add the reduced external field for( bidx j=0; j!=3; ++j ) currentField[j] += happ[j]; // step the integrator inte.step(); // check the end condition if( currentState[2] < 0 ) break; } // store the time fpt[i] = inte.getTime(); } // Write the results to the hardrive boostToFile( fpt, "llg.fpt" ); return 1; // everything was fine } // returns a random state from the equilibrium distribution array_d Simulation::equilibriumState() { // Currently only runs a single particle if( geom.getNParticles() != 1 ) throw "Simulation only runs for a single particle."; // Get the particle info Particle p = geom.getParticle( 0 ); // define the pdf auto pdf = [&p, this]( double theta ) { return sin( theta) * exp( -p.getK()*p.getV()*pow( sin( theta ), 2 ) / ( Constants::KB * T ) ); }; // find the max array_d angles( extents[10000] ); for( bidx i=0; i!=10000; ++i ) angles[i] = i * M_PI_2 / 10000; double max = 0.0; for( auto &t : angles ) if( pdf( t ) > max) max = pdf( t ); // use uniform distribution as the candidate density // with M 10% higher that the max of target dist static boost::random::uniform_real_distribution<> gen_candidate( 0,M_PI ); static boost::random::uniform_real_distribution<> gen_check( 0,1 ); double M = 1.1 * max; // Rejection rate algorithm double candidate = 0; while( 1 ) { candidate = gen_candidate( equilibrium_rng ); double acceptance = pdf( candidate ) / M; double check = gen_check( equilibrium_rng ); if( acceptance > check ) break; } array_d init_state( extents[3] ); init_state[0] = 0; init_state[1] = 0; init_state[2] = cos( candidate ); return init_state; }
use dynamic scheduling for fpt calcs
use dynamic scheduling for fpt calcs
C++
bsd-2-clause
owlas/maggie
4ce8a20c7fdc0f23a5f83c7d2d8980d8e4203375
examples/flash_spi_program/flash_spi_program.cpp
examples/flash_spi_program/flash_spi_program.cpp
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/flash/spi.h" #include "config/sdcard.h" #include "config/usart.h" #include "config/filesystem.h" #include "memory/scoped_ptr.h" #include <vector> #include <string> using namespace stm32plus; /** * This example programs a SPI flash device from files stored on an SD card and outputs * progress messages to a USART terminal. This programmer only requires the standard SPI * commands so it uses the 'StandardSpiFlashDevice' template. Other templates are available * that mixin commands specific to those devices. * * The SD card must contain an "index.txt" file in the "/spiflash" folder. "/spiflash/index.txt" * contains one line per file to flash The line is of the form: * * <filename>=<start-address-in-flash-in-decimal> * * For example: * * /spiflash/graphic1.bin=0 * /spiflash/graphic2.bin=16384 * /spiflash/assets/line.bin=24576 * * Whitespace is not permitted anywhere on the text lines. It is important that each address * is a multiple of the device page size (usually 256 bytes). If it's not then you will get * data corruption. A chip-erase command is used to wipe the device before * programming. * * An example "spiflash" directory is included with this example that can be copied to * the root of your SD card. See the related 'flash_spi_reader' example for a demo that * reads back the example graphic files and displays them on an LCD. * * The default peripherals for this demo are SPI2, USART1, Winbond W25Q16DW 16Mbit flash. All * of these are customisable by you. The device identification code reported by the W25Q16DW * should be "ef6015". * * The pinout for SPI2 is: * * NSS = PB12 * SCK = PB13 * MISO = PB14 * MOSI = PB15 * * Compatible MCU: * STM32F1 * STM32F4 * * Tested on devices: * STM32F103ZET6 * STM32F407VGT6 */ class FlashSpiProgram { // these are the peripherals we will use typedef Spi2<> MySpi; typedef Usart1<> MyUsart; typedef spiflash::StandardSpiFlashDevice<MySpi> MyFlash; // declare the peripheral pointers MyUsart *_usart; MySpi *_spi; MyFlash *_flash; SdioDmaSdCard *_sdcard; FileSystem *_fs; UsartPollingOutputStream *_usartStream; // declare the program variables struct FlashEntry { char *filename; uint32_t length; uint32_t offset; }; std::vector<FlashEntry> _flashEntries; public: void run() { // initialise the USART _usart=new MyUsart(57600); _usartStream=new UsartPollingOutputStream(*_usart); status("Initialising SD card."); // initialise the SD card _sdcard=new SdioDmaSdCard; if(errorProvider.hasError()) error("SD card could not be initialised"); // initialise the filesystem on the card NullTimeProvider timeProvider; if(!FileSystem::getInstance(*_sdcard,timeProvider,_fs)) error("The file system on the SD card could not be initialised"); // Initialise the SPI peripheral in master mode. The SPI speed is bus/4 // Make sure that this is not too fast for your device. MySpi::Parameters spiParams; spiParams.spi_mode=SPI_Mode_Master; spiParams.spi_baudRatePrescaler=SPI_BaudRatePrescaler_4; spiParams.spi_cpol=SPI_CPOL_Low; spiParams.spi_cpha=SPI_CPHA_1Edge; _spi=new MySpi(spiParams); // initialise the flash device _flash=new MyFlash(*_spi); // show the device identifier showDeviceIdentifier(); // read the index file readIndexFile(); // erase the flash device eraseFlash(); // write each file for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++) writeFile(*it); // verify each file for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++) verifyFile(*it); // done status("Success"); for(;;); } /* * Show the flash device id */ void showDeviceIdentifier() { uint8_t id[3]; char output[7]; if(!_flash->readJedecId(id,sizeof(id))) error("Unable to read the flash id code"); StringUtil::toHex(id,sizeof(id),output); output[sizeof(output)-1]='\0'; *_usartStream << "Flash id = " << output << "\r\n"; } /* * Erase the entire device */ void eraseFlash() { status("Erasing the entire flash device"); if(!_flash->writeEnable()) error("Unable to enable write access"); if(!_flash->chipErase()) error("Unable to execute the erase command"); if(!_flash->waitForIdle()) error("Failed to wait for the flash device to be idle"); status("Erase completed"); } /* * Write the file to the flash device */ void writeFile(const FlashEntry& fe) { uint8_t page[MyFlash::PAGE_SIZE]; scoped_ptr<File> file; uint32_t remaining,actuallyRead,address; *_usartStream << "Programming " << fe.filename << "\r\n"; if(!_fs->openFile(fe.filename,file.address())) error("Failed to open file"); address=fe.offset; for(remaining=fe.length;remaining;remaining-=actuallyRead) { // read a page from the file if(!file->read(page,sizeof(page),actuallyRead)) error("Failed to read from file"); // cannot hit EOF here if(!actuallyRead) error("Unexpected end of file"); // wait for the device to go idle if(!_flash->waitForIdle()) error("Failed to wait for the device to become idle"); // enable writing if(!_flash->writeEnable()) error("Unable to enable write access"); if(!_flash->waitForIdle()) error("Failed to wait for the device to become idle"); // program the page if(!_flash->pageProgram(address,page,actuallyRead)) error("Failed to program the page"); // update for next address+=actuallyRead; } } /* * Verify the file just written to the device */ void verifyFile(const FlashEntry& fe) { uint8_t filePage[MyFlash::PAGE_SIZE],flashPage[MyFlash::PAGE_SIZE]; scoped_ptr<File> file; uint32_t remaining,actuallyRead,address; *_usartStream << "Verifying " << fe.filename << "\r\n"; if(!_fs->openFile(fe.filename,file.address())) error("Failed to open file"); address=fe.offset; for(remaining=fe.length;remaining;remaining-=actuallyRead) { // read a page from the file if(!file->read(filePage,sizeof(filePage),actuallyRead)) error("Failed to read from file"); // cannot hit EOF here if(!actuallyRead) error("Unexpected end of file"); // read the page from the flash device if(!_flash->fastRead(address,flashPage,actuallyRead)) error("Failed to read from the flash device"); // compare it if(memcmp(filePage,flashPage,actuallyRead)!=0) error("Verify error: programming failed"); // update for next address+=actuallyRead; } } /* * Read index.txt */ void readIndexFile() { scoped_ptr<File> file; char line[200],*ptr; status("Reading index file."); // open the file if(!_fs->openFile("/spiflash/index.txt",file.address())) error("Cannot open /index.txt"); // attach a reader and read each line FileReader reader(*file); while(reader.available()) { scoped_ptr<File> dataFile; // read line if(!reader.readLine(line,sizeof(line))) error("Failed to read line from file"); // search for the = separator and break the text line at it if((ptr=strchr(line,'='))==nullptr) error("Badly formatted index.txt line - cannot find = symbol"); *ptr='\0'; // ensure this file can be opened if(!_fs->openFile(line,dataFile.address())) error("Cannot open data file"); FlashEntry fe; fe.filename=strdup(line); fe.offset=atoi(ptr+1); fe.length=dataFile->getLength(); _flashEntries.push_back(fe); *_usartStream << "Parsed " << fe.filename << " offset " << StringUtil::Ascii(fe.offset) << " length " << StringUtil::Ascii(fe.length) << "\r\n"; } *_usartStream << "Finished reading index, " << StringUtil::Ascii(_flashEntries.size()) << ", entries read\r\n"; } /* * Unrecoverable error */ void error(const char *text) { status(text); for(;;); } /* * Write a status string to the usart */ void status(const char *text) { *_usartStream << text << "\r\n"; } }; /* * Main entry point */ int main() { MillisecondTimer::initialise(); FlashSpiProgram test; test.run(); // not reached return 0; }
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/flash/spi.h" #include "config/sdcard.h" #include "config/usart.h" #include "config/crc.h" #include "config/filesystem.h" #include "memory/scoped_ptr.h" #include <vector> #include <string> using namespace stm32plus; /** * This example programs a SPI flash device from files stored on an SD card and outputs * progress messages to a USART terminal. This programmer only requires the standard SPI * commands so it uses the 'StandardSpiFlashDevice' template. Other templates are available * that mixin commands specific to those devices. * * The SD card must contain an "index.txt" file in the "/spiflash" folder. "/spiflash/index.txt" * contains one line per file to flash The line is of the form: * * <filename>=<start-address-in-flash-in-decimal> * * For example: * * /spiflash/graphic1.bin=0 * /spiflash/graphic2.bin=16384 * /spiflash/assets/line.bin=24576 * * Whitespace is not permitted anywhere on the text lines. It is important that each address * is a multiple of the device page size (usually 256 bytes). If it's not then you will get * data corruption. A chip-erase command is used to wipe the device before * programming. * * An example "spiflash" directory is included with this example that can be copied to * the root of your SD card. See the related 'flash_spi_reader' example for a demo that * reads back the example graphic files and displays them on an LCD. * * The default peripherals for this demo are SPI2, USART1, Winbond W25Q16DW 16Mbit flash. All * of these are customisable by you. The device identification code reported by the W25Q16DW * should be "ef6015". * * The pinout for SPI2 is: * * NSS = PB12 * SCK = PB13 * MISO = PB14 * MOSI = PB15 * * Compatible MCU: * STM32F1 * STM32F4 * * Tested on devices: * STM32F103ZET6 * STM32F407VGT6 */ class FlashSpiProgram { // these are the peripherals we will use typedef Spi2<> MySpi; typedef Usart1<> MyUsart; typedef spiflash::StandardSpiFlashDevice<MySpi> MyFlash; // declare the peripheral pointers MyUsart *_usart; MySpi *_spi; MyFlash *_flash; SdioDmaSdCard *_sdcard; FileSystem *_fs; UsartPollingOutputStream *_usartStream; // declare the program variables struct FlashEntry { char *filename; uint32_t length; uint32_t offset; }; std::vector<FlashEntry> _flashEntries; public: void run() { // initialise the USART _usart=new MyUsart(57600); _usartStream=new UsartPollingOutputStream(*_usart); status("Initialising SD card."); // initialise the SD card _sdcard=new SdioDmaSdCard; if(errorProvider.hasError()) error("SD card could not be initialised"); // initialise the filesystem on the card NullTimeProvider timeProvider; if(!FileSystem::getInstance(*_sdcard,timeProvider,_fs)) error("The file system on the SD card could not be initialised"); // Initialise the SPI peripheral in master mode. The SPI speed is bus/4 // Make sure that this is not too fast for your device. MySpi::Parameters spiParams; spiParams.spi_mode=SPI_Mode_Master; spiParams.spi_baudRatePrescaler=SPI_BaudRatePrescaler_4; spiParams.spi_cpol=SPI_CPOL_Low; spiParams.spi_cpha=SPI_CPHA_1Edge; _spi=new MySpi(spiParams); // initialise the flash device _flash=new MyFlash(*_spi); // show the device identifier showDeviceIdentifier(); // read the index file readIndexFile(); // erase the flash device eraseFlash(); // write each file for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++) writeFile(*it); // verify each file for(auto it=_flashEntries.begin();it!=_flashEntries.end();it++) verifyFile(*it); // done status("Success"); for(;;); } /* * Show the flash device id */ void showDeviceIdentifier() { uint8_t id[3]; char output[7]; if(!_flash->readJedecId(id,sizeof(id))) error("Unable to read the flash id code"); StringUtil::toHex(id,sizeof(id),output); output[sizeof(output)-1]='\0'; *_usartStream << "Flash id = " << output << "\r\n"; } /* * Erase the entire device */ void eraseFlash() { status("Erasing the entire flash device"); if(!_flash->writeEnable()) error("Unable to enable write access"); if(!_flash->chipErase()) error("Unable to execute the erase command"); if(!_flash->waitForIdle()) error("Failed to wait for the flash device to be idle"); status("Erase completed"); } /* * Write the file to the flash device */ void writeFile(const FlashEntry& fe) { uint8_t page[MyFlash::PAGE_SIZE]; scoped_ptr<File> file; uint32_t i,remaining,actuallyRead,address; CrcBigEndian::Parameters params; CrcBigEndian crc(params); *_usartStream << "Programming " << fe.filename << "\r\n"; if(!_fs->openFile(fe.filename,file.address())) error("Failed to open file"); address=fe.offset; for(remaining=fe.length;remaining;remaining-=actuallyRead) { // read a page from the file if(!file->read(page,sizeof(page),actuallyRead)) error("Failed to read from file"); // cannot hit EOF here if(!actuallyRead) error("Unexpected end of file"); // wait for the device to go idle if(!_flash->waitForIdle()) error("Failed to wait for the device to become idle"); // enable writing if(!_flash->writeEnable()) error("Unable to enable write access"); if(!_flash->waitForIdle()) error("Failed to wait for the device to become idle"); // program the page if(!_flash->pageProgram(address,page,actuallyRead)) error("Failed to program the page"); // add to CRC for(i=0;i<actuallyRead;i++) crc.addNewData(page[i]); // update for next address+=actuallyRead; } *_usartStream << "Programmed " << fe.filename << " OK. CRC = " << StringUtil::Ascii(crc.finish()) << "\r\n"; } /* * Verify the file just written to the device */ void verifyFile(const FlashEntry& fe) { uint8_t filePage[MyFlash::PAGE_SIZE],flashPage[MyFlash::PAGE_SIZE]; scoped_ptr<File> file; uint32_t i,remaining,actuallyRead,address; CrcBigEndian::Parameters params; CrcBigEndian crc(params); *_usartStream << "Verifying " << fe.filename << "\r\n"; if(!_fs->openFile(fe.filename,file.address())) error("Failed to open file"); address=fe.offset; for(remaining=fe.length;remaining;remaining-=actuallyRead) { // read a page from the file if(!file->read(filePage,sizeof(filePage),actuallyRead)) error("Failed to read from file"); // cannot hit EOF here if(!actuallyRead) error("Unexpected end of file"); // read the page from the flash device if(!_flash->fastRead(address,flashPage,actuallyRead)) error("Failed to read from the flash device"); // compare it if(memcmp(filePage,flashPage,actuallyRead)!=0) error("Verify error: programming failed"); // add to CRC for(i=0;i<actuallyRead;i++) crc.addNewData(flashPage[i]); // update for next address+=actuallyRead; } *_usartStream << "Verified " << fe.filename << " OK. CRC = " << StringUtil::Ascii(crc.finish()) << "\r\n"; } /* * Read index.txt */ void readIndexFile() { scoped_ptr<File> file; char line[200],*ptr; status("Reading index file."); // open the file if(!_fs->openFile("/spiflash/index.txt",file.address())) error("Cannot open /index.txt"); // attach a reader and read each line FileReader reader(*file); while(reader.available()) { scoped_ptr<File> dataFile; // read line if(!reader.readLine(line,sizeof(line))) error("Failed to read line from file"); // search for the = separator and break the text line at it if((ptr=strchr(line,'='))==nullptr) error("Badly formatted index.txt line - cannot find = symbol"); *ptr='\0'; // ensure this file can be opened if(!_fs->openFile(line,dataFile.address())) error("Cannot open data file"); FlashEntry fe; fe.filename=strdup(line); fe.offset=atoi(ptr+1); fe.length=dataFile->getLength(); _flashEntries.push_back(fe); *_usartStream << "Parsed " << fe.filename << " offset " << StringUtil::Ascii(fe.offset) << " length " << StringUtil::Ascii(fe.length) << "\r\n"; } *_usartStream << "Finished reading index, " << StringUtil::Ascii(_flashEntries.size()) << ", entries read\r\n"; } /* * Unrecoverable error */ void error(const char *text) { status(text); for(;;); } /* * Write a status string to the usart */ void status(const char *text) { *_usartStream << text << "\r\n"; } }; /* * Main entry point */ int main() { MillisecondTimer::initialise(); FlashSpiProgram test; test.run(); // not reached return 0; }
add CRC to flash programming output
add CRC to flash programming output
C++
bsd-3-clause
trigrass2/stm32plus,ThanhVic/stm32plus,trigrass2/stm32plus,tokoro10g/stm32plus,phynex/stm32plus,lcbowling/stm32plus,trigrass2/stm32plus,lcbowling/stm32plus,lcbowling/stm32plus,ThanhVic/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,tokoro10g/stm32plus,trigrass2/stm32plus,phynex/stm32plus,spiralray/stm32plus,ThanhVic/stm32plus,lcbowling/stm32plus,punkkeks/stm32plus,lcbowling/stm32plus,punkkeks/stm32plus,trigrass2/stm32plus,punkkeks/stm32plus,spiralray/stm32plus,tokoro10g/stm32plus,tokoro10g/stm32plus,spiralray/stm32plus,phynex/stm32plus,ThanhVic/stm32plus,punkkeks/stm32plus,punkkeks/stm32plus,spiralray/stm32plus,lcbowling/stm32plus,tokoro10g/stm32plus,phynex/stm32plus,spiralray/stm32plus,phynex/stm32plus,phynex/stm32plus,ThanhVic/stm32plus,trigrass2/stm32plus,spiralray/stm32plus,ThanhVic/stm32plus,ThanhVic/stm32plus,trigrass2/stm32plus,spiralray/stm32plus,punkkeks/stm32plus,punkkeks/stm32plus,phynex/stm32plus,tokoro10g/stm32plus
9437f2c005b40f84eb074749114062cfbc456e98
lib/dag_select.hpp
lib/dag_select.hpp
/* * Copyright (c) 2011 Daisuke Okanohara * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above Copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above Copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the authors nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. */ #ifndef DAG_SELECT_HPP_ #define DAG_SELECT_HPP_ #include "dag_vector.hpp" #include "bit_vector.hpp" namespace dag{ class dag_select{ public: dag_select() { clear(); } dag_select(uint64_t low_width) { clear(); low_width_ = low_width; mask_ = (low_width_ == BLOCK_SIZE) ? 0xFFFFFFFFFFFFFFFF : (1 << low_width_) - 1; } dag_select(uint64_t one_num, uint64_t all_num){ clear(); if (one_num == 0) return; uint64_t dist = all_num / one_num; for (low_width_ = 0; dist >> low_width_; ++low_width_) {} mask_ = (low_width_ == BLOCK_SIZE) ? 0xFFFFFFFFFFFFFFFF : (1 << low_width_) - 1; } ~dag_select(){ } void clear(){ high_one_.clear(); high_zero_.clear(); low_.clear(); size_ = 0; low_width_ = BLOCK_SIZE; prev_val_ = 0; run_ones_ = 0; } void push_back(uint64_t val){ ++size_; uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : val >> low_width_; uint64_t prev_high = (low_width_ == BLOCK_SIZE) ? 0 : prev_val_ >> low_width_; uint64_t dist = high - prev_high; high_one_.push_back(dist); high_bv_.push_back(1LLU << dist, dist+1); // write 00..01 if (dist > 0){ high_zero_.push_back(run_ones_); run_ones_ = 0; } for (uint64_t i = 1; i < dist; ++i){ high_zero_.push_back(0); } ++run_ones_; prev_val_ = val; low_.push_back(val & mask_, low_width_); } uint64_t select(uint64_t rank) const{ uint64_t rank1 = rank + 1; uint64_t high = high_one_.prefix_sum(rank1); uint64_t low = low_.get_bits(rank * low_width_, low_width_); return (high << low_width_) + low; } uint64_t get_bit(uint64_t pos) const{ uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : pos >> low_width_; uint64_t low = pos & mask_; uint64_t low_pos = high_zero_.prefix_sum(high); uint64_t cur_rank = low_pos + high; for (; cur_rank < high_bv_.size(); cur_rank++, low_pos++){ if (!high_bv_.get_bit(cur_rank)) { break; } uint64_t cur_low = low_.get_bits(low_pos * low_width_, low_width_); if (cur_low >= low){ if (cur_low == low){ return 1; } else { return 0; } } } return 0; } uint64_t rank(uint64_t pos) const{ uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : pos >> low_width_; uint64_t low = pos & mask_; uint64_t low_pos = high_zero_.prefix_sum(high); uint64_t cur_rank = low_pos + high; for (; cur_rank < high_bv_.size(); cur_rank++, low_pos++){ if (!high_bv_.get_bit(cur_rank)) { break; } uint64_t cur_low = low_.get_bits(low_pos * low_width_, low_width_); if (cur_low >= low){ break; } } return cur_rank; } uint64_t size() const { return size_; } uint64_t low_width() const { return low_width_; } void compress(){ uint64_t size = high_one_.size(); uint64_t total_sum = high_one_.sum(); uint64_t dist = total_sum / size; uint64_t new_low_width = 0; for (new_low_width = 0; dist >> new_low_width; ++new_low_width) {} if (new_low_width == low_width_) return; dag_select new_dag_select(new_low_width); dag_vector::const_iterator old_it = high_one_.begin(); uint64_t high = 0; for (uint64_t i = 0; i < size_; ++i, ++old_it){ high += *old_it; uint64_t low = low_.get_bits(i * low_width_, low_width_); uint64_t val = (high << low_width_) + low; new_dag_select.push_back(val); } swap(new_dag_select); } uint64_t get_alloc_byte_num() const{ std::cout << "high_zero_num:" << high_one_.sum() << " high_one_num:" << high_zero_.sum() << " low_width_:" << low_width_ << std::endl; std::cout << "high_one_:" << high_one_.get_alloc_byte_num() << " " << high_one_.height() << std::endl; std::cout << "high_zero_:" << high_zero_.get_alloc_byte_num() << " " << high_zero_.height() << std::endl; std::cout << "low_:" << low_.get_alloc_byte_num() << std::endl; std::cout << "high_bv_:" << high_bv_.get_alloc_byte_num() << std::endl; return high_one_.get_alloc_byte_num() + high_zero_.get_alloc_byte_num() + low_.get_alloc_byte_num() + high_bv_.get_alloc_byte_num() + sizeof(uint64_t) * 3; } void swap(dag_select& ds){ high_one_.swap(ds.high_one_); high_zero_.swap(ds.high_zero_); low_.swap(ds.low_); std::swap(size_, ds.size_); std::swap(low_width_, ds.low_width_); std::swap(prev_val_, ds.prev_val_); std::swap(run_ones_, ds.run_ones_); std::swap(mask_, ds.mask_); } class const_iterator : public std::iterator<std::random_access_iterator_tag, uint64_t, size_t> { public: const_iterator(const dag_select& ds) : low_(ds.low_), high_bv_(ds.high_bv_), pos_(0), high_pos_(0), high_prefix_val_(0), size_(ds.size()), low_width_(ds.low_width()){ advance(); } const_iterator(const dag_select& ds, uint64_t) : low_(ds.low_), high_bv_(ds.high_bv_), pos_(ds.size()), high_pos_(high_bv_.size()), high_prefix_val_(0), size_(ds.size()), low_width_(ds.low_width()){ } const_iterator& operator++(){ ++pos_; advance(); return *this; } const_iterator operator++(int){ const_iterator tmp(*this); ++*this; return tmp; } /* const_iterator& operator--(){ --dvit_; --pos_; high_ -= *dvit_; return *this; } const_iterator operator--(int){ const_iterator tmp(*this); --*this; return tmp; } */ size_t operator-(const const_iterator& it) const{ return pos_ - it.pos_; } bool operator==(const const_iterator& it) const{ return pos_ == it.pos_; } bool operator!=(const const_iterator& it) const{ return !(*this == it); } uint64_t operator*() const { return (high_prefix_val_ << low_width_) + low_.get_bits(pos_ * low_width_, low_width_); } private: void advance(){ for (;;++high_prefix_val_){ if (high_bv_.get_bit(high_pos_++)){ break; } } } const bit_vector& low_; const bit_vector& high_bv_; uint64_t pos_; uint64_t high_pos_; uint64_t high_prefix_val_; uint64_t size_; const uint64_t low_width_; }; const_iterator begin() const{ return const_iterator(*this); } const_iterator end() const{ return const_iterator(*this, size_); } private: static const uint64_t BLOCK_SIZE = 64; dag_vector high_one_; dag_vector high_zero_; bit_vector high_bv_; bit_vector low_; uint64_t size_; uint64_t low_width_; uint64_t prev_val_; uint64_t run_ones_; uint64_t mask_; }; } #endif // DAG_SELECT_HPP_
/* * Copyright (c) 2011 Daisuke Okanohara * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above Copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above Copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the authors nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. */ #ifndef DAG_SELECT_HPP_ #define DAG_SELECT_HPP_ #include "dag_vector.hpp" #include "bit_vector.hpp" namespace dag{ class dag_select{ public: dag_select() { clear(); } dag_select(uint64_t low_width) { clear(); low_width_ = low_width; mask_ = (low_width_ == BLOCK_SIZE) ? 0xFFFFFFFFFFFFFFFF : (1 << low_width_) - 1; } dag_select(uint64_t one_num, uint64_t all_num){ clear(); if (one_num == 0) return; uint64_t dist = all_num / one_num; for (low_width_ = 0; dist >> low_width_; ++low_width_) {} mask_ = (low_width_ == BLOCK_SIZE) ? 0xFFFFFFFFFFFFFFFF : (1 << low_width_) - 1; } ~dag_select(){ } void clear(){ high_one_.clear(); high_zero_.clear(); low_.clear(); size_ = 0; low_width_ = BLOCK_SIZE; prev_val_ = 0; run_ones_ = 0; } void push_back(uint64_t val){ ++size_; uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : val >> low_width_; uint64_t prev_high = (low_width_ == BLOCK_SIZE) ? 0 : prev_val_ >> low_width_; uint64_t dist = high - prev_high; high_one_.push_back(dist); high_bv_.push_back(1LLU << dist, dist+1); // write 00..01 if (dist > 0){ high_zero_.push_back(run_ones_); run_ones_ = 0; } for (uint64_t i = 1; i < dist; ++i){ high_zero_.push_back(0); } ++run_ones_; prev_val_ = val; low_.push_back(val & mask_, low_width_); } uint64_t select(uint64_t rank) const{ uint64_t rank1 = rank + 1; uint64_t high = high_one_.prefix_sum(rank1); uint64_t low = low_.get_bits(rank * low_width_, low_width_); return (high << low_width_) + low; } uint64_t get_bit(uint64_t pos) const{ uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : pos >> low_width_; uint64_t low = pos & mask_; uint64_t low_pos = high_zero_.prefix_sum(high); uint64_t cur_rank = low_pos + high; for (; cur_rank < high_bv_.size(); cur_rank++, low_pos++){ if (!high_bv_.get_bit(cur_rank)) { break; } uint64_t cur_low = low_.get_bits(low_pos * low_width_, low_width_); if (cur_low >= low){ if (cur_low == low){ return 1; } else { return 0; } } } return 0; } uint64_t rank(uint64_t pos) const{ uint64_t high = (low_width_ == BLOCK_SIZE) ? 0 : pos >> low_width_; uint64_t low = pos & mask_; uint64_t low_pos = high_zero_.prefix_sum(high); uint64_t cur_rank = low_pos + high; for (; cur_rank < high_bv_.size(); cur_rank++, low_pos++){ if (!high_bv_.get_bit(cur_rank)) { break; } uint64_t cur_low = low_.get_bits(low_pos * low_width_, low_width_); if (cur_low >= low){ break; } } return cur_rank; } uint64_t size() const { return size_; } uint64_t low_width() const { return low_width_; } void compress(){ uint64_t size = high_one_.size(); uint64_t total_sum = high_one_.sum(); uint64_t dist = total_sum / size; uint64_t new_low_width = 0; for (new_low_width = 0; dist >> new_low_width; ++new_low_width) {} if (new_low_width == low_width_) return; dag_select new_dag_select(new_low_width); dag_vector::const_iterator old_it = high_one_.begin(); uint64_t high = 0; for (uint64_t i = 0; i < size_; ++i, ++old_it){ high += *old_it; uint64_t low = low_.get_bits(i * low_width_, low_width_); uint64_t val = (high << low_width_) + low; new_dag_select.push_back(val); } swap(new_dag_select); } uint64_t get_alloc_byte_num() const{ return high_one_.get_alloc_byte_num() + high_zero_.get_alloc_byte_num() + low_.get_alloc_byte_num() + high_bv_.get_alloc_byte_num() + sizeof(uint64_t) * 3; } void swap(dag_select& ds){ high_one_.swap(ds.high_one_); high_zero_.swap(ds.high_zero_); low_.swap(ds.low_); std::swap(size_, ds.size_); std::swap(low_width_, ds.low_width_); std::swap(prev_val_, ds.prev_val_); std::swap(run_ones_, ds.run_ones_); std::swap(mask_, ds.mask_); } class const_iterator : public std::iterator<std::random_access_iterator_tag, uint64_t, size_t> { public: const_iterator(const dag_select& ds) : low_(ds.low_), high_bv_(ds.high_bv_), pos_(0), high_pos_(0), high_prefix_val_(0), size_(ds.size()), low_width_(ds.low_width()){ advance(); } const_iterator(const dag_select& ds, uint64_t) : low_(ds.low_), high_bv_(ds.high_bv_), pos_(ds.size()), high_pos_(high_bv_.size()), high_prefix_val_(0), size_(ds.size()), low_width_(ds.low_width()){ } const_iterator& operator++(){ ++pos_; advance(); return *this; } const_iterator operator++(int){ const_iterator tmp(*this); ++*this; return tmp; } /* const_iterator& operator--(){ --dvit_; --pos_; high_ -= *dvit_; return *this; } const_iterator operator--(int){ const_iterator tmp(*this); --*this; return tmp; } */ size_t operator-(const const_iterator& it) const{ return pos_ - it.pos_; } bool operator==(const const_iterator& it) const{ return pos_ == it.pos_; } bool operator!=(const const_iterator& it) const{ return !(*this == it); } uint64_t operator*() const { return (high_prefix_val_ << low_width_) + low_.get_bits(pos_ * low_width_, low_width_); } private: void advance(){ for (;;++high_prefix_val_){ if (high_bv_.get_bit(high_pos_++)){ break; } } } const bit_vector& low_; const bit_vector& high_bv_; uint64_t pos_; uint64_t high_pos_; uint64_t high_prefix_val_; uint64_t size_; const uint64_t low_width_; }; const_iterator begin() const{ return const_iterator(*this); } const_iterator end() const{ return const_iterator(*this, size_); } private: static const uint64_t BLOCK_SIZE = 64; dag_vector high_one_; dag_vector high_zero_; bit_vector high_bv_; bit_vector low_; uint64_t size_; uint64_t low_width_; uint64_t prev_val_; uint64_t run_ones_; uint64_t mask_; }; } #endif // DAG_SELECT_HPP_
remove debug message
remove debug message
C++
bsd-3-clause
pfi/dag_vector
9de27d2a7d97c7cbfc9e376757af3d97573de7f5
network_simulation.hpp
network_simulation.hpp
#ifndef __NETWORK_SIMULATION_HPP__ #define __NETWORK_SIMULATION_HPP__ #include "bwpathfinder.hpp" #include "libsimfw/simfw.hpp" #include "libsimfw/timer.hpp" #include <map> namespace bwpathfinder { typedef simfw::TimeInPS Time; class NetworkSimulation : public simfw::Simulation<Time> { struct Flit { PathPtr owner; size_t hops; NodePtr lastNode; Flit(PathPtr path) : owner(path), hops(0), lastNode(path->src) { } NodePtr nextNode() { if (arrived()) return owner->dst; assert(hops < owner->path.size()); LinkPtr currLink = owner->path[hops]; // printf("nextNode src %p dst %p curr (%p %p)\n", // owner->src.get(), owner->dst.get(), currLink->a.get(), currLink->b.get()); if (currLink->a == lastNode) return currLink->b; else if (currLink->b == lastNode) return currLink->a; else assert(false && "Invalid lastNode, currLink association"); } void advanceHop() { lastNode = nextNode(); hops += 1; } bool arrived() { return lastNode == owner->dst; } }; class SimulatedLink; class SimulatedNode : public simfw::InputPort<Time, Flit*> { std::map<uint64_t, SimulatedLink*> outPorts; public: NodePtr node; std::map<PathPtr, uint64_t> flits_seen; SimulatedNode(NetworkSimulation* sim, NodePtr node) : simfw::InputPort<Time, Flit*>(sim), node(node) { } void notifyLink(NodePtr toNode, SimulatedLink* link) { outPorts[toNode->id] = link; } void inject(Time time, Flit* f, SimulatedLink* from) { f->advanceHop(); flits_seen[f->owner] += 1; if (f->arrived()) { // We've arrived! delete f; } else { NodePtr next = f->nextNode(); outPorts[next->id]->inject(time, f, from); } } }; class SimulatedLink : public simfw::InputPort<Time, Flit*> { LinkPtr link; size_t max_in_flight; Time latency; size_t bufferedItems; size_t roundRobinIndex; std::map<SimulatedLink*, std::deque<Flit*> > buffers; std::set<Flit*> inFlight; SimulatedNode* nodeA; SimulatedNode* nodeB; public: SimulatedLink(NetworkSimulation* sim, LinkPtr link) : simfw::InputPort<Time, Flit*>(sim), link(link), bufferedItems(0), roundRobinIndex(0) { float max_iff = link->bandwidth * link->latency / sim->flit_size_in_bytes; this->max_in_flight = round(max_iff); if (this->max_in_flight < 1) { printf("Config violation: max in flight (%f) < 1!\n", max_iff); printf("\tbw: %e latency: %e flit_size: %lu bytes\n", link->bandwidth, link->latency, sim->flit_size_in_bytes); assert(false); } this->latency = link->latency; this->nodeA = sim->getNode(link->a); this->nodeB = sim->getNode(link->b); assert(nodeA != NULL); assert(nodeB != NULL); } ~SimulatedLink() { for (auto flit : inFlight) { delete flit; } for (auto& buffer : buffers) { for (auto flit : buffer.second) { delete flit; } } } void inject(Time time, Flit* f, SimulatedLink* last) { if (inFlight.size() >= max_in_flight) { buffers[last].push_back(f); bufferedItems += 1; } else { inFlight.insert(f); this->deliverIn(latency, f); } } virtual void recieve(Time time, Flit* f) { inFlight.erase(f); if (bufferedItems > 0) { // Find next to send according to RR policy auto iter = buffers.begin(); for (size_t i=0; i<roundRobinIndex; i++) { iter++; } const size_t num_buffers = buffers.size(); // if (num_buffers > 1) // printf("[%p] bi: %lu, num_buffers: %lu\n", this, bufferedItems, num_buffers); for (size_t i=0; i<num_buffers; i++) { if (!iter->second.empty()) { Flit* inj_flit = iter->second.front(); iter->second.pop_front(); inFlight.insert(inj_flit); this->deliverIn(latency, inj_flit); roundRobinIndex = (i + roundRobinIndex + 1) % num_buffers; // if (num_buffers > 1) // printf("rrI: %lu\n", roundRobinIndex); bufferedItems -= 1; break; } else { iter++; if (iter == buffers.end()) iter = buffers.begin(); } } } NodePtr next = f->nextNode(); // printf("next: %p a %p b %p\n", // next.get(), nodeA->node.get(), nodeB->node.get()); // printf("link : %p %p\n", link->a.get(), link->b.get()); if (next == nodeA->node) nodeA->inject(time, f, this); else if (next == nodeB->node) nodeB->inject(time, f, this); else assert(false && "Invalid route found!"); } }; class InjectionPort : public simfw::Timer<Time> { PathPtr path; SimulatedLink* link; public: InjectionPort(NetworkSimulation* sim, Time period, PathPtr path, SimulatedLink* link) : simfw::Timer<Time>(sim, period), path(path), link(link) { } protected: virtual bool ding(uint64_t i) { link->inject(simulation->now(), new Flit(path), NULL); // printf("Injecting flit %lf %lu\n", simulation->now().seconds(), i); return true; } }; NetworkPtr network; size_t flit_size_in_bytes; Time longestPeriod; Time slowestClock; size_t longestPath; std::map<PathPtr, InjectionPort*, smart_ptr_less_than> injectionPorts; std::map<NodePtr, SimulatedNode*, smart_ptr_less_than> simulatedNodes; std::map<LinkPtr, SimulatedLink*, smart_ptr_less_than> simulatedLinks; public: NetworkSimulation(NetworkPtr network) { this->network = network; this->flit_size_in_bytes = network->flit_size_in_bytes; slowestClock = 0.0; for(auto node : network->nodes) { simulatedNodes.insert(std::make_pair(node, new SimulatedNode(this, node))); if (slowestClock < node->latency) slowestClock = node->latency; } for(auto link: network->links) { if (slowestClock < link->latency) slowestClock = link->latency; simulatedLinks.insert(std::make_pair(link, new SimulatedLink(this, link))); SimulatedLink* slink = simulatedLinks.find(link)->second; SimulatedNode* n; n = getNode(link->a); assert(n != NULL); n->notifyLink(link->b, slink); n = getNode(link->b); assert(n != NULL); n->notifyLink(link->a, slink); } Time largestPeriod = 0.0; this->longestPath = 0; for (auto path: network->paths){ Time period = 1.0 / (path->requested_bw / flit_size_in_bytes); if (largestPeriod < period) largestPeriod = period; if (path->path.size() > longestPath) longestPath = path->path.size(); LinkPtr vlink = network->findLink(path->src, NodePtr()); assert(vlink != LinkPtr()); auto flink = simulatedLinks.find(vlink); assert(flink != simulatedLinks.end()); SimulatedLink* slink = flink->second; injectionPorts.insert(std::make_pair(path, new InjectionPort(this, period, path, slink))); } this->longestPeriod = largestPeriod; } ~NetworkSimulation() { for (auto pr : injectionPorts) { delete pr.second; } for (auto pr : simulatedNodes) { delete pr.second; } for (auto pr : simulatedLinks) { delete pr.second; } } SimulatedNode* getNode(NodePtr n) { auto fnode = simulatedNodes.find(n); if (fnode == simulatedNodes.end()) return NULL; return fnode->second; } void simulate() { // Simulate N of the slowest packet injections this->goUntil(longestPeriod.seconds() * 500.0 + 10 * longestPath * slowestClock.seconds()); } void setDeliveredBandwidths() { float runtime = this->now().seconds(); for (auto path: this->network->paths) { SimulatedNode* dst = this->getNode(path->dst); assert(dst != NULL); uint64_t recvd_flits = dst->flits_seen[path]; uint64_t bytes_recvd = recvd_flits * this->flit_size_in_bytes; path->delivered_bw = ((float)bytes_recvd) / runtime; } } }; } #endif // __NETWORK_SIMULATION_HPP__
#ifndef __NETWORK_SIMULATION_HPP__ #define __NETWORK_SIMULATION_HPP__ #include "bwpathfinder.hpp" #include "libsimfw/simfw.hpp" #include "libsimfw/timer.hpp" #include <map> namespace bwpathfinder { typedef simfw::TimeInPS Time; class NetworkSimulation : public simfw::Simulation<Time> { struct Flit { PathPtr owner; size_t hops; NodePtr lastNode; Flit(PathPtr path) : owner(path), hops(0), lastNode(path->src) { } NodePtr nextNode() { if (arrived()) return owner->dst; assert(hops < owner->path.size()); LinkPtr currLink = owner->path[hops]; // printf("nextNode src %p dst %p curr (%p %p)\n", // owner->src.get(), owner->dst.get(), currLink->a.get(), currLink->b.get()); if (currLink->a == lastNode) return currLink->b; else if (currLink->b == lastNode) return currLink->a; else assert(false && "Invalid lastNode, currLink association"); } void advanceHop() { lastNode = nextNode(); hops += 1; } bool arrived() { return lastNode == owner->dst; } }; class SimulatedLink; class SimulatedNode : public simfw::InputPort<Time, Flit*> { std::map<uint64_t, SimulatedLink*> outPorts; public: NodePtr node; std::map<PathPtr, uint64_t> flits_seen; SimulatedNode(NetworkSimulation* sim, NodePtr node) : simfw::InputPort<Time, Flit*>(sim), node(node) { } void notifyLink(NodePtr toNode, SimulatedLink* link) { outPorts[toNode->id] = link; } void inject(Time time, Flit* f, SimulatedLink* from) { f->advanceHop(); flits_seen[f->owner] += 1; if (f->arrived()) { // We've arrived! delete f; } else { NodePtr next = f->nextNode(); outPorts[next->id]->inject(time, f, from); } } }; class SimulatedLink : public simfw::InputPort<Time, Flit*> { LinkPtr link; size_t max_in_flight; Time latency; size_t bufferedItems; size_t roundRobinIndex; std::map<SimulatedLink*, std::deque<Flit*> > buffers; std::set<Flit*> inFlight; SimulatedNode* nodeA; SimulatedNode* nodeB; public: SimulatedLink(NetworkSimulation* sim, LinkPtr link) : simfw::InputPort<Time, Flit*>(sim), link(link), bufferedItems(0), roundRobinIndex(0) { float max_iff = link->bandwidth * link->latency / sim->flit_size_in_bytes; this->max_in_flight = round(max_iff); if (this->max_in_flight < 1) { printf("Config violation: max in flight (%f) < 1!\n", max_iff); printf("\tbw: %e latency: %e flit_size: %lu bytes\n", link->bandwidth, link->latency, sim->flit_size_in_bytes); assert(false); } this->latency = link->latency; this->nodeA = sim->getNode(link->a); this->nodeB = sim->getNode(link->b); assert(nodeA != NULL); assert(nodeB != NULL); } ~SimulatedLink() { for (auto flit : inFlight) { delete flit; } for (auto& buffer : buffers) { for (auto flit : buffer.second) { delete flit; } } } void inject(Time time, Flit* f, SimulatedLink* last) { if (inFlight.size() >= max_in_flight) { buffers[last].push_back(f); bufferedItems += 1; } else { inFlight.insert(f); this->deliverIn(latency, f); } } virtual void recieve(Time time, Flit* f) { inFlight.erase(f); if (bufferedItems > 0) { // Find next to send according to RR policy auto iter = buffers.begin(); for (size_t i=0; i<roundRobinIndex; i++) { iter++; } const size_t num_buffers = buffers.size(); // if (num_buffers > 1) // printf("[%p] bi: %lu, num_buffers: %lu\n", this, bufferedItems, num_buffers); for (size_t i=0; i<num_buffers; i++) { if (!iter->second.empty()) { Flit* inj_flit = iter->second.front(); iter->second.pop_front(); inFlight.insert(inj_flit); this->deliverIn(latency, inj_flit); roundRobinIndex = (i + roundRobinIndex + 1) % num_buffers; // if (num_buffers > 1) // printf("rrI: %lu\n", roundRobinIndex); bufferedItems -= 1; break; } else { iter++; if (iter == buffers.end()) iter = buffers.begin(); } } } NodePtr next = f->nextNode(); // printf("next: %p a %p b %p\n", // next.get(), nodeA->node.get(), nodeB->node.get()); // printf("link : %p %p\n", link->a.get(), link->b.get()); if (next == nodeA->node) nodeA->inject(time, f, this); else if (next == nodeB->node) nodeB->inject(time, f, this); else assert(false && "Invalid route found!"); } }; class InjectionPort : public simfw::Timer<Time> { PathPtr path; SimulatedLink* link; public: InjectionPort(NetworkSimulation* sim, Time period, PathPtr path, SimulatedLink* link) : simfw::Timer<Time>(sim, period), path(path), link(link) { } protected: virtual bool ding(uint64_t i) { link->inject(simulation->now(), new Flit(path), NULL); // printf("Injecting flit %lf %lu\n", simulation->now().seconds(), i); return true; } }; NetworkPtr network; size_t flit_size_in_bytes; Time longestPeriod; Time slowestClock; size_t longestPath; std::map<PathPtr, InjectionPort*, smart_ptr_less_than> injectionPorts; std::map<NodePtr, SimulatedNode*, smart_ptr_less_than> simulatedNodes; std::map<LinkPtr, SimulatedLink*, smart_ptr_less_than> simulatedLinks; public: NetworkSimulation(NetworkPtr network) { this->network = network; this->flit_size_in_bytes = network->flit_size_in_bytes; slowestClock = 0.0; for(auto node : network->nodes) { simulatedNodes.insert(std::make_pair(node, new SimulatedNode(this, node))); if (slowestClock < node->latency) slowestClock = node->latency; } for(auto link: network->links) { if (slowestClock < link->latency) slowestClock = link->latency; simulatedLinks.insert(std::make_pair(link, new SimulatedLink(this, link))); SimulatedLink* slink = simulatedLinks.find(link)->second; SimulatedNode* n; n = getNode(link->a); assert(n != NULL); n->notifyLink(link->b, slink); n = getNode(link->b); assert(n != NULL); n->notifyLink(link->a, slink); } Time largestPeriod = 0.0; this->longestPath = 0; for (auto path: network->paths){ Time period = 1.0 / (path->requested_bw / flit_size_in_bytes); if (largestPeriod < period) largestPeriod = period; if (path->path.size() > longestPath) longestPath = path->path.size(); LinkPtr vlink = network->findLink(path->src, NodePtr()); assert(vlink != LinkPtr()); auto flink = simulatedLinks.find(vlink); assert(flink != simulatedLinks.end()); SimulatedLink* slink = flink->second; injectionPorts.insert(std::make_pair(path, new InjectionPort(this, period, path, slink))); } this->longestPeriod = largestPeriod; } ~NetworkSimulation() { for (auto pr : injectionPorts) { delete pr.second; } for (auto pr : simulatedNodes) { delete pr.second; } for (auto pr : simulatedLinks) { delete pr.second; } } SimulatedNode* getNode(NodePtr n) { auto fnode = simulatedNodes.find(n); if (fnode == simulatedNodes.end()) return NULL; return fnode->second; } void simulate() { // Simulate N of the slowest packet injections this->goUntil(longestPeriod.seconds() * 10.0 + 10 * longestPath * slowestClock.seconds()); } void setDeliveredBandwidths() { float runtime = this->now().seconds(); for (auto path: this->network->paths) { SimulatedNode* dst = this->getNode(path->dst); assert(dst != NULL); uint64_t recvd_flits = dst->flits_seen[path]; uint64_t bytes_recvd = recvd_flits * this->flit_size_in_bytes; path->delivered_bw = ((float)bytes_recvd) / runtime; } } }; } #endif // __NETWORK_SIMULATION_HPP__
Reduce network simulation time
Reduce network simulation time
C++
mit
castl/libbwpathfinder,castl/libbwpathfinder
92d57f1151a661458365dbfdf746d78add8aa147
lib/file_utils.cpp
lib/file_utils.cpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <minizinc/file_utils.hh> #include <minizinc/config.hh> #ifdef HAS_PIDPATH #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libproc.h> #include <unistd.h> #elif defined(HAS_GETMODULEFILENAME) || defined(HAS_GETFILEATTRIBUTES) #include <windows.h> #else #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> namespace MiniZinc { namespace FileUtils { #ifdef HAS_PIDPATH std::string progpath(void) { pid_t pid = getpid(); char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath (pid, path, sizeof(path)); if ( ret <= 0 ) { return ""; } else { std::string p(path); size_t slash = p.find_last_of("/"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #elif defined(HAS_GETMODULEFILENAME) std::string progpath(void) { char path[MAX_PATH]; int ret = GetModuleFileName(NULL, path, MAX_PATH); if ( ret <= 0 ) { return ""; } else { std::string p(path); size_t slash = p.find_last_of("/\\"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #else std::string progpath(void) { const int bufsz = 2000; char path[bufsz+1]; ssize_t sz = readlink("/proc/self/exe", path, bufsz); if ( sz < 0 ) { return ""; } else { path[sz] = '\0'; std::string p(path); size_t slash = p.find_last_of("/"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #endif bool file_exists(const std::string& filename) { #if defined(HAS_GETFILEATTRIBUTES) DWORD dwAttrib = GetFileAttributes(filename.c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat info; return stat(filename.c_str(), &info)==0 && (info.st_mode & S_IFREG); #endif } bool directory_exists(const std::string& dirname) { #if defined(HAS_GETFILEATTRIBUTES) DWORD dwAttrib = GetFileAttributes(dirname.c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat info; return stat(dirname.c_str(), &info)==0 && (info.st_mode & S_IFDIR); #endif } std::string file_path(const std::string& filename) { #ifdef _MSC_VER LPSTR lpBuffer, lpFilePart; DWORD nBufferLength = GetFullPathName(filename.c_str(), 0,0,&lpFilePart); if (!(lpBuffer = (LPTSTR)LocalAlloc(LMEM_FIXED, sizeof(TCHAR) * nBufferLength))) return 0; std::string ret; if (!GetFullPathName(lpFileName, nBufferLength, lpBuffer, &lpFilePart)) { ret = ""; } else { ret = std::string(lpBuffer); } LocalFree(lpBuffer); return ret; #else char* rp = realpath(filename.c_str(), NULL); std::string rp_s(rp); free(rp); return rp_s; #endif } }}
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <[email protected]> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <minizinc/file_utils.hh> #include <minizinc/config.hh> #ifdef HAS_PIDPATH #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libproc.h> #include <unistd.h> #elif defined(HAS_GETMODULEFILENAME) || defined(HAS_GETFILEATTRIBUTES) #include <windows.h> #else #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> namespace MiniZinc { namespace FileUtils { #ifdef HAS_PIDPATH std::string progpath(void) { pid_t pid = getpid(); char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath (pid, path, sizeof(path)); if ( ret <= 0 ) { return ""; } else { std::string p(path); size_t slash = p.find_last_of("/"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #elif defined(HAS_GETMODULEFILENAME) std::string progpath(void) { char path[MAX_PATH]; int ret = GetModuleFileName(NULL, path, MAX_PATH); if ( ret <= 0 ) { return ""; } else { std::string p(path); size_t slash = p.find_last_of("/\\"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #else std::string progpath(void) { const int bufsz = 2000; char path[bufsz+1]; ssize_t sz = readlink("/proc/self/exe", path, bufsz); if ( sz < 0 ) { return ""; } else { path[sz] = '\0'; std::string p(path); size_t slash = p.find_last_of("/"); if (slash != std::string::npos) { p = p.substr(0,slash); } return p; } } #endif bool file_exists(const std::string& filename) { #if defined(HAS_GETFILEATTRIBUTES) DWORD dwAttrib = GetFileAttributes(filename.c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat info; return stat(filename.c_str(), &info)==0 && (info.st_mode & S_IFREG); #endif } bool directory_exists(const std::string& dirname) { #if defined(HAS_GETFILEATTRIBUTES) DWORD dwAttrib = GetFileAttributes(dirname.c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat info; return stat(dirname.c_str(), &info)==0 && (info.st_mode & S_IFDIR); #endif } std::string file_path(const std::string& filename) { #ifdef _MSC_VER LPSTR lpBuffer, lpFilePart; DWORD nBufferLength = GetFullPathName(filename.c_str(), 0,0,&lpFilePart); if (!(lpBuffer = (LPTSTR)LocalAlloc(LMEM_FIXED, sizeof(TCHAR) * nBufferLength))) return 0; std::string ret; if (!GetFullPathName(filename.c_str(), nBufferLength, lpBuffer, &lpFilePart)) { ret = ""; } else { ret = std::string(lpBuffer); } LocalFree(lpBuffer); return ret; #else char* rp = realpath(filename.c_str(), NULL); std::string rp_s(rp); free(rp); return rp_s; #endif } }}
Fix for msvc
Fix for msvc
C++
mpl-2.0
jjdekker/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc,tias/libminizinc,tias/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc
ec6e38f3e74dc24ee885a88ac16429c810ea4398
stereo_test.cpp
stereo_test.cpp
#include <iostream> #include <sstream> #include <vector> #include <algorithm> #include <thread> #include <iomanip> #include <chrono> #include "nxtcam.h" #include "stereo_config.h" #include "delta_robot_args.h" using namespace ev3dev; using namespace std; static cl::group motor_control("Motor control"); static cl::arg<mode_type> regulation_mode( "on", cl::name("regulation-mode"), cl::desc("One of: 'on', 'off'."), motor_control); static cl::arg<int> pulses_per_second( 700, cl::name("pulses-per-second"), cl::desc("Pulses/second for when --regulation-on is specified."), motor_control); static cl::arg<int> duty_cycle( 100, cl::name("duty-cycle"), cl::desc("Duty cycle for when --regulation-on is not specified."), motor_control); static cl::arg<int> ramp( 0, cl::name("ramp"), cl::desc("Ramp time, in ms."), motor_control); static delta_robot_args delta_geometry("", "Delta robot geometry"); static stereo_config stereo; static cl::arg<float> sample_rate( 30.0f, cl::name("sample-rate"), cl::desc("Frequency of camera observation samples, in Hz.")); static cl::arg<float> scale( 0.5f, cl::name("scale"), cl::desc("Ratio of robot movement to object movement.")); int main(int argc, const char **argv) { cl::parse(argv[0], argc - 1, argv + 1); // Reduce clutter of insignificant digits. cout << fixed << showpoint << setprecision(3); cerr << fixed << showpoint << setprecision(3); nxtcam nxtcam0(stereo.cam0.port); nxtcam nxtcam1(stereo.cam1.port); cout << "Cameras:" << endl; cout << nxtcam0.device_id() << " " << nxtcam0.version() << " (" << nxtcam0.vendor_id() << ")" << endl; cout << nxtcam1.device_id() << " " << nxtcam1.version() << " (" << nxtcam1.vendor_id() << ")" << endl; thread nxtcam_init_thread([&] () { nxtcam0.track_objects(); nxtcam1.track_objects(); cout << "Tracking objects..." << endl; }); // Initialize the delta robot. delta_robot delta(delta_geometry.geometry()); if (scale > 0.0f) { delta.init(); // Bask in the glory of the calibration result for a moment. this_thread::sleep_for(chrono::milliseconds(500)); // Set the motor parameters. delta.set_regulation_mode(regulation_mode); delta.set_pulses_per_second_setpoint(pulses_per_second); delta.set_duty_cycle_setpoint(duty_cycle); delta.set_ramp_up(ramp); delta.set_ramp_down(ramp); } nxtcam_init_thread.join(); pair<vector3f, float> volume = delta.get_volume(); cameraf cam0, cam1; tie(cam0, cam1) = stereo.cameras(); float baseline = abs(cam1.x - cam0.x); if (baseline < 1e-6f) throw runtime_error("camera baseline is zero"); vector3f b = unit(cam1.x - cam0.x); // t will increment in regular intervals of T. typedef chrono::high_resolution_clock clock; auto t = clock::now(); chrono::microseconds T(static_cast<int>(1e6f/sample_rate + 0.5f)); vector3f origin(0.0f, 0.0f, 0.0f); string eraser; while (true) { nxtcam::blob_list blobs0 = nxtcam0.blobs(); nxtcam::blob_list blobs1 = nxtcam1.blobs(); if (blobs0.size() == 1 && blobs1.size() == 1) { const nxtcam::blob &b0 = blobs0.front(); const nxtcam::blob &b1 = blobs1.front(); vector3f x0 = cam0.sensor_to_projection(b0.center(), 1.0f) - cam0.x; vector3f x1 = cam1.sensor_to_projection(b1.center(), 1.0f) - cam1.x; // z is determined by the stereo disparity. float z = baseline/(dot(x0, b) - dot(x1, b)); // Move the points from the focal plane to the (parallel) plane containing z and add the camera origins. x0 = x0*z + cam0.x; x1 = x1*z + cam1.x; vector3f x = (x0 + x1)/2; stringstream ss; ss << fixed << showpoint << setprecision(3); ss << "x=" << x << ", ||x0 - x1||=" << abs(x0 - x1); string msg = ss.str(); if (msg.length() > eraser.length()) eraser = string(msg.length(), ' '); cout << msg << string(eraser.size() - msg.size(), ' '); if (scale > 0.0f) { // The object moved outside the volume. Move the origin s.t. the volume contains x. x = x*scale - origin; if (x.z < volume.first.z) { origin.z -= volume.first.z - x.z; x.z = volume.first.z; } float r = abs(x - volume.first); if (r >= volume.second) { vector3f shift = unit(x - volume.first)*(r - volume.second); origin += shift; x -= shift; } try { // Move to the position. delta.run_to(x); } catch(runtime_error &) { origin = x; } } } else { cout << eraser; } cout << "\r"; cout.flush(); t += T; this_thread::sleep_until(t); } return 0; }
#include <iostream> #include <sstream> #include <vector> #include <algorithm> #include <thread> #include <iomanip> #include <chrono> #include "nxtcam.h" #include "stereo_config.h" #include "delta_robot_args.h" using namespace ev3dev; using namespace std; static cl::group motor_control("Motor control"); static cl::arg<mode_type> regulation_mode( "on", cl::name("regulation-mode"), cl::desc("One of: 'on', 'off'."), motor_control); static cl::arg<int> pulses_per_second( 700, cl::name("pulses-per-second"), cl::desc("Pulses/second for when --regulation-on is specified."), motor_control); static cl::arg<int> duty_cycle( 100, cl::name("duty-cycle"), cl::desc("Duty cycle for when --regulation-on is not specified."), motor_control); static cl::arg<int> ramp( 0, cl::name("ramp"), cl::desc("Ramp time, in ms."), motor_control); static delta_robot_args delta_geometry("", "Delta robot geometry"); static stereo_config stereo; static cl::arg<float> sample_rate( 30.0f, cl::name("sample-rate"), cl::desc("Frequency of camera observation samples, in Hz.")); static cl::arg<float> scale( 1.0f, cl::name("scale"), cl::desc("Ratio of robot movement to object movement.")); int main(int argc, const char **argv) { cl::parse(argv[0], argc - 1, argv + 1); // Reduce clutter of insignificant digits. cout << fixed << showpoint << setprecision(3); cerr << fixed << showpoint << setprecision(3); nxtcam nxtcam0(stereo.cam0.port); nxtcam nxtcam1(stereo.cam1.port); cout << "Cameras:" << endl; cout << nxtcam0.device_id() << " " << nxtcam0.version() << " (" << nxtcam0.vendor_id() << ")" << endl; cout << nxtcam1.device_id() << " " << nxtcam1.version() << " (" << nxtcam1.vendor_id() << ")" << endl; thread nxtcam_init_thread([&] () { nxtcam0.track_objects(); nxtcam1.track_objects(); cout << "Tracking objects..." << endl; }); // Initialize the delta robot. delta_robot delta(delta_geometry.geometry()); if (scale > 0.0f) { delta.init(); // Bask in the glory of the calibration result for a moment. this_thread::sleep_for(chrono::milliseconds(500)); // Set the motor parameters. delta.set_regulation_mode(regulation_mode); delta.set_pulses_per_second_setpoint(pulses_per_second); delta.set_duty_cycle_setpoint(duty_cycle); delta.set_ramp_up(ramp); delta.set_ramp_down(ramp); } nxtcam_init_thread.join(); pair<vector3f, float> volume = delta.get_volume(); cameraf cam0, cam1; tie(cam0, cam1) = stereo.cameras(); float baseline = abs(cam1.x - cam0.x); if (baseline < 1e-6f) throw runtime_error("camera baseline is zero"); vector3f b = unit(cam1.x - cam0.x); // t will increment in regular intervals of T. typedef chrono::high_resolution_clock clock; auto t = clock::now(); chrono::microseconds T(static_cast<int>(1e6f/sample_rate + 0.5f)); vector3f origin(0.0f, 0.0f, 0.0f); string eraser; while (true) { nxtcam::blob_list blobs0 = nxtcam0.blobs(); nxtcam::blob_list blobs1 = nxtcam1.blobs(); if (blobs0.size() == 1 && blobs1.size() == 1) { const nxtcam::blob &b0 = blobs0.front(); const nxtcam::blob &b1 = blobs1.front(); vector3f x0 = cam0.sensor_to_projection(b0.center(), 1.0f) - cam0.x; vector3f x1 = cam1.sensor_to_projection(b1.center(), 1.0f) - cam1.x; // z is determined by the stereo disparity. float z = baseline/(dot(x0, b) - dot(x1, b)); // Move the points from the focal plane to the (parallel) plane containing z and add the camera origins. x0 = x0*z + cam0.x; x1 = x1*z + cam1.x; vector3f x = (x0 + x1)/2; stringstream ss; ss << fixed << showpoint << setprecision(3); ss << "x=" << x << ", ||x0 - x1||=" << abs(x0 - x1); string msg = ss.str(); if (msg.length() > eraser.length()) eraser = string(msg.length(), ' '); cout << msg << string(eraser.size() - msg.size(), ' '); if (origin == 0.0f) origin = x*scale - volume.first; x = x*scale - origin; if (scale > 0.0f) { try { // Move to the position. delta.run_to(x); } catch(runtime_error &) { } } } else { cout << eraser; } cout << "\r"; cout.flush(); t += T; this_thread::sleep_until(t); } return 0; }
Use first observed 3D position as the origin
Use first observed 3D position as the origin
C++
apache-2.0
dsharlet/DeltaCatch
fb64f052dcf269ad30926f86114b324952e2b7db
SDK/src/NDK/LuaBinding_SDK.cpp
SDK/src/NDK/LuaBinding_SDK.cpp
// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/LuaBinding.hpp> #include <NDK/LuaAPI.hpp> namespace Ndk { /*! * \brief Binds SDK module to Lua */ void LuaBinding::BindSDK() { /*********************************** Ndk::Application **********************************/ #ifndef NDK_SERVER //application.SetMethod("AddWindow", &Application::AddWindow); application.BindMethod("EnableConsole", &Application::EnableConsole); application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter); application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled); application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); #endif application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int { instance.Push(application->AddWorld().CreateHandle()); return 1; }); application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); application.BindMethod("Quit", &Application::Quit); /*********************************** Ndk::Console **********************************/ #ifndef NDK_SERVER consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* { return handle->GetObject(); }); consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); consoleClass.BindMethod("Clear", &Console::Clear); consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); consoleClass.BindMethod("GetHistory", &Console::GetHistory); consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); consoleClass.BindMethod("GetInput", &Console::GetInput); consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); consoleClass.BindMethod("GetSize", &Console::GetSize); consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); consoleClass.BindMethod("IsVisible", &Console::IsVisible); consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); //consoleClass.SetMethod("SendEvent", &Console::SendEvent); consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); consoleClass.BindMethod("SetSize", &Console::SetSize); consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); consoleClass.BindMethod("Show", &Console::Show, true); #endif /*********************************** Ndk::Entity **********************************/ entityClass.BindMethod("Enable", &Entity::Enable, true); entityClass.BindMethod("GetId", &Entity::GetId); entityClass.BindMethod("GetWorld", &Entity::GetWorld); entityClass.BindMethod("Kill", &Entity::Kill); entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); entityClass.BindMethod("IsValid", &Entity::IsValid); entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entityClass.BindMethod("__tostring", &EntityHandle::ToString); entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->adder(instance, handle); }); entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->getter(instance, handle->GetComponent(binding->index)); }); entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); handle->RemoveComponent(binding->index); return 0; }); /*********************************** Ndk::NodeComponent **********************************/ nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); }); /*********************************** Ndk::VelocityComponent **********************************/ velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); if (std::strcmp(member, "Linear") == 0) { lua.Push(instance->linearVelocity); return true; } return false; }); velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); int argIndex = 2; if (std::strcmp(member, "Linear") == 0) { instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex); return true; } return false; }); /*********************************** Ndk::World **********************************/ worldClass.BindMethod("CreateEntity", &World::CreateEntity); worldClass.BindMethod("CreateEntities", &World::CreateEntities); worldClass.BindMethod("Clear", &World::Clear); #ifndef NDK_SERVER /*********************************** Ndk::GraphicsComponent **********************************/ graphicsComponent.BindMethod("Attach", &GraphicsComponent::Attach, 0); #endif // Components functions m_componentBinding.resize(BaseComponent::GetMaxComponentIndex()); BindComponent<NodeComponent>("Node"); BindComponent<VelocityComponent>("Velocity"); #ifndef NDK_SERVER BindComponent<GraphicsComponent>("Graphics"); #endif } /*! * \brief Registers the classes that will be used by the Lua instance * * \param instance Lua instance that will interact with the SDK classes */ void LuaBinding::RegisterSDK(Nz::LuaInstance& instance) { // Classes application.Register(instance); entityClass.Register(instance); nodeComponent.Register(instance); velocityComponent.Register(instance); worldClass.Register(instance); #ifndef NDK_SERVER consoleClass.Register(instance); graphicsComponent.Register(instance); #endif // Enums // ComponentType (fake enumeration to expose component indexes) instance.PushTable(0, m_componentBinding.size()); { for (const ComponentBinding& entry : m_componentBinding) { if (entry.name.IsEmpty()) continue; instance.PushField(entry.name, entry.index); } } instance.SetGlobal("ComponentType"); } /*! * \brief Gets the index of the component * \return A pointer to the binding linked to a component * * \param instance Lua instance that will interact with the component * \param argIndex Index of the component */ LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) { switch (instance.GetType(argIndex)) { case Nz::LuaType_Number: { ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex); if (componentIndex > m_componentBinding.size()) { instance.Error("Invalid component index"); return nullptr; } ComponentBinding& binding = m_componentBinding[componentIndex]; if (binding.name.IsEmpty()) { instance.Error("Invalid component index"); return nullptr; } return &binding; } case Nz::LuaType_String: { const char* key = instance.CheckString(argIndex); auto it = m_componentBindingByName.find(key); if (it == m_componentBindingByName.end()) { instance.Error("Invalid component name"); return nullptr; } return &m_componentBinding[it->second]; } } instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); return nullptr; } }
// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/LuaBinding.hpp> #include <NDK/LuaAPI.hpp> namespace Ndk { /*! * \brief Binds SDK module to Lua */ void LuaBinding::BindSDK() { /*********************************** Ndk::Application **********************************/ #ifndef NDK_SERVER //application.SetMethod("AddWindow", &Application::AddWindow); application.BindMethod("EnableConsole", &Application::EnableConsole); application.BindMethod("EnableFPSCounter", &Application::EnableFPSCounter); application.BindMethod("IsConsoleEnabled", &Application::IsConsoleEnabled); application.BindMethod("IsFPSCounterEnabled", &Application::IsFPSCounterEnabled); #endif application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int { instance.Push(application->AddWorld().CreateHandle()); return 1; }); application.BindMethod("GetUpdateTime", &Application::GetUpdateTime); application.BindMethod("Quit", &Application::Quit); /*********************************** Ndk::Console **********************************/ #ifndef NDK_SERVER consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node* { return handle->GetObject(); }); consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White); consoleClass.BindMethod("Clear", &Console::Clear); consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize); consoleClass.BindMethod("GetHistory", &Console::GetHistory); consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground); consoleClass.BindMethod("GetInput", &Console::GetInput); consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground); consoleClass.BindMethod("GetSize", &Console::GetSize); consoleClass.BindMethod("GetTextFont", &Console::GetTextFont); consoleClass.BindMethod("IsVisible", &Console::IsVisible); consoleClass.BindMethod("SendCharacter", &Console::SendCharacter); //consoleClass.SetMethod("SendEvent", &Console::SendEvent); consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize); consoleClass.BindMethod("SetSize", &Console::SetSize); consoleClass.BindMethod("SetTextFont", &Console::SetTextFont); consoleClass.BindMethod("Show", &Console::Show, true); #endif /*********************************** Ndk::Entity **********************************/ entityClass.BindMethod("Enable", &Entity::Enable, true); entityClass.BindMethod("GetId", &Entity::GetId); entityClass.BindMethod("GetWorld", &Entity::GetWorld); entityClass.BindMethod("Kill", &Entity::Kill); entityClass.BindMethod("IsEnabled", &Entity::IsEnabled); entityClass.BindMethod("IsValid", &Entity::IsValid); entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents); entityClass.BindMethod("__tostring", &EntityHandle::ToString); entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->adder(instance, handle); }); entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); return binding->getter(instance, handle->GetComponent(binding->index)); }); entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int { ComponentBinding* binding = QueryComponentIndex(instance); handle->RemoveComponent(binding->index); return 0; }); /*********************************** Ndk::NodeComponent **********************************/ nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node* { return handle->GetObject(); }); /*********************************** Ndk::VelocityComponent **********************************/ velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); if (std::strcmp(member, "Linear") == 0) { lua.Push(instance->linearVelocity); return true; } return false; }); velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance) { std::size_t length; const char* member = lua.CheckString(1, &length); int argIndex = 2; if (std::strcmp(member, "Linear") == 0) { instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex); return true; } return false; }); /*********************************** Ndk::World **********************************/ worldClass.BindMethod("CreateEntity", &World::CreateEntity); worldClass.BindMethod("CreateEntities", &World::CreateEntities); worldClass.BindMethod("Clear", &World::Clear); #ifndef NDK_SERVER /*********************************** Ndk::GraphicsComponent **********************************/ graphicsComponent.BindMethod("Attach", (void(Ndk::GraphicsComponent::*)(Nz::InstancedRenderableRef, int)) &GraphicsComponent::Attach, 0); #endif // Components functions m_componentBinding.resize(BaseComponent::GetMaxComponentIndex()); BindComponent<NodeComponent>("Node"); BindComponent<VelocityComponent>("Velocity"); #ifndef NDK_SERVER BindComponent<GraphicsComponent>("Graphics"); #endif } /*! * \brief Registers the classes that will be used by the Lua instance * * \param instance Lua instance that will interact with the SDK classes */ void LuaBinding::RegisterSDK(Nz::LuaInstance& instance) { // Classes application.Register(instance); entityClass.Register(instance); nodeComponent.Register(instance); velocityComponent.Register(instance); worldClass.Register(instance); #ifndef NDK_SERVER consoleClass.Register(instance); graphicsComponent.Register(instance); #endif // Enums // ComponentType (fake enumeration to expose component indexes) instance.PushTable(0, m_componentBinding.size()); { for (const ComponentBinding& entry : m_componentBinding) { if (entry.name.IsEmpty()) continue; instance.PushField(entry.name, entry.index); } } instance.SetGlobal("ComponentType"); } /*! * \brief Gets the index of the component * \return A pointer to the binding linked to a component * * \param instance Lua instance that will interact with the component * \param argIndex Index of the component */ LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex) { switch (instance.GetType(argIndex)) { case Nz::LuaType_Number: { ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex); if (componentIndex > m_componentBinding.size()) { instance.Error("Invalid component index"); return nullptr; } ComponentBinding& binding = m_componentBinding[componentIndex]; if (binding.name.IsEmpty()) { instance.Error("Invalid component index"); return nullptr; } return &binding; } case Nz::LuaType_String: { const char* key = instance.CheckString(argIndex); auto it = m_componentBindingByName.find(key); if (it == m_componentBindingByName.end()) { instance.Error("Invalid component name"); return nullptr; } return &m_componentBinding[it->second]; } } instance.Error("Invalid component index at #" + Nz::String::Number(argIndex)); return nullptr; } }
Fix compilation
SDK/Binding: Fix compilation Former-commit-id: 16a69ef5de792f9093fc27ddafaa8e5677d9f66d [formerly 72c2eca09f8e48b414956056cbf16b40cd96b2e5] [formerly a73d622403c9a746ac5f39b3d45178bb21006a17 [formerly 095a0737f1aa42b7d4ba9e09fd897c5ab173b75b]] Former-commit-id: 0373630192183dd80d1250d6132ae676be0b7267 [formerly 4eee844b3dcec8789cd990f6f42fe9ac2e57c3fe] Former-commit-id: b50dd40211e104f15eba529b434c74e9151bb78e
C++
mit
DigitalPulseSoftware/NazaraEngine
e65087fde73d21894d26dcb92849e1104a152368
ojgl/examples/Main.cpp
ojgl/examples/Main.cpp
#include "EmbeddedResources.h" #include "FreeCameraController.h" #include "TextRenderer.hpp" #include "demo/Demo.h" #include "demos/DodensTriumf.h" #include "demos/Edison2021.h" #include "demos/Eldur.h" #include "demos/InnerSystemLab.h" #include "demos/QED.h" #include "demos/Template.h" #include "render/GLState.h" #include "render/Popup.h" #include "render/Texture.h" #include "render/Window.h" #include "utility/Log.h" #include "utility/Macros.h" #include "utility/OJstd.h" #include "utility/ShaderReader.h" #ifdef RENDERDOC #include "renderdoc_app.h" #include <windows.h> RENDERDOC_API_1_1_2* renderdocApi = nullptr; #endif using namespace ojgl; enum class DemoType { DodensTriumf, Eldur, InnerSystemLab, QED, Template, Edison2021 }; ojstd::shared_ptr<Demo> getDemo(DemoType type) { switch (type) { case DemoType::Eldur: return ojstd::make_shared<Eldur>(); case DemoType::QED: return ojstd::make_shared<QED>(); case DemoType::DodensTriumf: return ojstd::make_shared<DodensTriumf>(); case DemoType::InnerSystemLab: return ojstd::make_shared<InnerSystemLab>(); case DemoType::Template: return ojstd::make_shared<Template>(); case DemoType::Edison2021: return ojstd::make_shared<Edison2021>(); } _ASSERTE(false); return nullptr; } int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) { #ifdef RENDERDOC if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) { pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI"); const int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&renderdocApi); _ASSERTE(ret == 1); } #endif popup::Data popupData = popup::show(); /*popupData.width = 1280; popupData.height = 720; popupData.full = false;*/ const Vector2i windowSize(popupData.width, popupData.height); const bool fullScreen = popupData.full; const bool showCursor = !fullScreen; ShaderReader::setBasePath("examples/shaders/"); for (const auto& [content, path] : resources::shaders) ShaderReader::preLoad(path, content); const auto demo = getDemo(DemoType::Edison2021); Window window(windowSize, demo->getTitle(), fullScreen, showCursor); TextRenderer::instance().setHDC(window.hdcBackend()); GLState glState(window, *demo); while (!glState.end() && !window.isClosePressed()) { Timer timer; timer.start(); #ifdef _DEBUG FreeCameraController::instance().update(window); bool captureFrame = false; #endif window.getMessages(); for (auto key : window.getPressedKeys()) { switch (key) { case Window::KEY_ESCAPE: return 0; #ifdef _DEBUG case Window::KEY_LEFT: glState.changeTime(Duration::milliseconds(-5000)); break; case Window::KEY_RIGHT: glState.changeTime(Duration::milliseconds(5000)); break; case Window::KEY_SPACE: glState.togglePause(); break; case Window::KEY_R: glState.restart(); break; case Window::KEY_UP: glState.nextScene(); break; case Window::KEY_DOWN: glState.previousScene(); break; case Window::KEY_P: captureFrame = true; break; case Window::KEY_C: const FreeCameraController& c = FreeCameraController::instance(); LOG_INFO("Camera: (" << c.position.x << ", " << c.position.y << ", " << c.position.z << ")" << ", [" << c.heading << ", " << c.elevation << "]"); break; #endif } } #ifdef RENDERDOC if (renderdocApi && captureFrame) { renderdocApi->StartFrameCapture(nullptr, nullptr); } #endif glState.update(); #ifdef RENDERDOC if (renderdocApi && captureFrame) { renderdocApi->EndFrameCapture(nullptr, nullptr); } #endif timer.end(); #ifdef _DEBUG ojstd::string debugTitle("Frame time: "); debugTitle.append(ojstd::to_string(timer.elapsed().toMilliseconds<long>())); debugTitle.append(" ms"); window.setTitle(debugTitle); #endif } } extern "C" int _tmain(int argc, char** argv) { return main(argc, argv); }
#include "EmbeddedResources.h" #include "FreeCameraController.h" #include "TextRenderer.hpp" #include "demo/Demo.h" #include "demos/DodensTriumf.h" #include "demos/Edison2021.h" #include "demos/Eldur.h" #include "demos/InnerSystemLab.h" #include "demos/QED.h" #include "demos/Template.h" #include "render/GLState.h" #include "render/Popup.h" #include "render/Texture.h" #include "render/Window.h" #include "utility/Log.h" #include "utility/Macros.h" #include "utility/OJstd.h" #include "utility/ShaderReader.h" #ifdef RENDERDOC #include "renderdoc_app.h" #include <windows.h> RENDERDOC_API_1_1_2* renderdocApi = nullptr; #endif using namespace ojgl; enum class DemoType { DodensTriumf, Eldur, InnerSystemLab, QED, Template, Edison2021 }; ojstd::shared_ptr<Demo> getDemo(DemoType type) { switch (type) { case DemoType::Eldur: return ojstd::make_shared<Eldur>(); case DemoType::QED: return ojstd::make_shared<QED>(); case DemoType::DodensTriumf: return ojstd::make_shared<DodensTriumf>(); case DemoType::InnerSystemLab: return ojstd::make_shared<InnerSystemLab>(); case DemoType::Template: return ojstd::make_shared<Template>(); case DemoType::Edison2021: return ojstd::make_shared<Edison2021>(); } _ASSERTE(false); return nullptr; } int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) { #ifdef RENDERDOC if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) { pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI"); const int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&renderdocApi); _ASSERTE(ret == 1); } #endif popup::Data popupData = popup::show(); const Vector2i windowSize(popupData.width, popupData.height); const bool fullScreen = popupData.full; const bool showCursor = !fullScreen; ShaderReader::setBasePath("examples/shaders/"); for (const auto& [content, path] : resources::shaders) ShaderReader::preLoad(path, content); const auto demo = getDemo(DemoType::Edison2021); Window window(windowSize, demo->getTitle(), fullScreen, showCursor); TextRenderer::instance().setHDC(window.hdcBackend()); GLState glState(window, *demo); while (!glState.end() && !window.isClosePressed()) { Timer timer; timer.start(); #ifdef _DEBUG FreeCameraController::instance().update(window); bool captureFrame = false; #endif window.getMessages(); for (auto key : window.getPressedKeys()) { switch (key) { case Window::KEY_ESCAPE: return 0; #ifdef _DEBUG case Window::KEY_LEFT: glState.changeTime(Duration::milliseconds(-5000)); break; case Window::KEY_RIGHT: glState.changeTime(Duration::milliseconds(5000)); break; case Window::KEY_SPACE: glState.togglePause(); break; case Window::KEY_R: glState.restart(); break; case Window::KEY_UP: glState.nextScene(); break; case Window::KEY_DOWN: glState.previousScene(); break; case Window::KEY_P: captureFrame = true; break; case Window::KEY_C: const FreeCameraController& c = FreeCameraController::instance(); LOG_INFO("Camera: (" << c.position.x << ", " << c.position.y << ", " << c.position.z << ")" << ", [" << c.heading << ", " << c.elevation << "]"); break; #endif } } #ifdef RENDERDOC if (renderdocApi && captureFrame) { renderdocApi->StartFrameCapture(nullptr, nullptr); } #endif glState.update(); #ifdef RENDERDOC if (renderdocApi && captureFrame) { renderdocApi->EndFrameCapture(nullptr, nullptr); } #endif timer.end(); #ifdef _DEBUG ojstd::string debugTitle("Frame time: "); debugTitle.append(ojstd::to_string(timer.elapsed().toMilliseconds<long>())); debugTitle.append(" ms"); window.setTitle(debugTitle); #endif } } extern "C" int _tmain(int argc, char** argv) { return main(argc, argv); }
Remove hardcoded popup data
Remove hardcoded popup data
C++
mit
nordstroem/OJGL,nordstroem/OJGL
8efb78e1c2b2087fb28d9b2bdb4665b7cd38a004
xchainer/array_device_test.cc
xchainer/array_device_test.cc
#include "xchainer/array.h" #include <cassert> #include <initializer_list> #include <string> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" #include "xchainer/memory.h" namespace xchainer { namespace { template <typename T> void ExpectDataEqual(const T* expected_data, const Array& actual) { #ifdef XCHAINER_ENABLE_CUDA if (actual.device() == MakeDevice("cuda")) { cuda::CheckError(cudaDeviceSynchronize()); } #endif // XCHAINER_ENABLE_CUDA auto total_size = actual.shape().total_size(); const T* actual_data = static_cast<const T*>(actual.data().get()); for (decltype(total_size) i = 0; i < total_size; i++) { EXPECT_EQ(expected_data[i], actual_data[i]) << "where i is " << i; } } template <typename T> void ExpectDataEqual(T expected, const Array& actual) { #ifdef XCHAINER_ENABLE_CUDA if (actual.device() == MakeDevice("cuda")) { cuda::CheckError(cudaDeviceSynchronize()); } #endif // XCHAINER_ENABLE_CUDA auto total_size = actual.shape().total_size(); const T* actual_data = static_cast<const T*>(actual.data().get()); for (decltype(total_size) i = 0; i < total_size; i++) { if (std::isnan(expected)) { EXPECT_TRUE(std::isnan(actual_data[i])) << "where i is " << i; } else { EXPECT_EQ(expected, actual_data[i]) << "where i is " << i; } } } void ExpectDataEqual(const Array& x, Dtype dtype, Scalar scalar) { VisitDtype(dtype, [&x, &scalar](auto pt) { using T = typename decltype(pt)::type; return ExpectDataEqual<T>(static_cast<T>(scalar), x); }); } // Check that Array data exists on the specified device void ExpectDataExistsOnDevice(const Device& expected_device, const Array& array) { // Check device of data pointee if (expected_device == MakeDevice("cpu")) { EXPECT_FALSE(internal::IsPointerCudaMemory(array.data().get())); } else if (expected_device == MakeDevice("cuda")) { EXPECT_TRUE(internal::IsPointerCudaMemory(array.data().get())); } else { FAIL() << "invalid device"; } } // Common criteria for FromBuffer, Empty, Full, Ones, Zeros, etc. void CheckCommonMembers(const Array& x, const Shape& shape, Dtype dtype, const Device& device) { EXPECT_NE(nullptr, x.data()); EXPECT_EQ(shape, x.shape()); EXPECT_EQ(shape.ndim(), x.ndim()); EXPECT_EQ(shape.total_size(), x.total_size()); EXPECT_EQ(dtype, x.dtype()); EXPECT_EQ(device, x.device()); EXPECT_TRUE(x.is_contiguous()); EXPECT_EQ(0, x.offset()); ExpectDataExistsOnDevice(device, x); } template <typename T> void CheckFromBufferMembers(const Array& x, const Shape& shape, Dtype dtype, std::shared_ptr<T> data, const Device& device) { CheckCommonMembers(x, shape, dtype, device); EXPECT_EQ(int64_t{sizeof(T)}, x.element_bytes()); EXPECT_EQ(shape.total_size() * int64_t{sizeof(T)}, x.total_bytes()); ExpectDataEqual<T>(data.get(), x); } // Common criteria for EmptyLike, FullLike, OnesLike, ZerosLike, etc. void CheckCommonLikeMembers(const Array& x, const Array& x_orig, const Device& device) { EXPECT_NE(nullptr, x.data()); EXPECT_EQ(x_orig.shape(), x.shape()); EXPECT_EQ(x_orig.dtype(), x.dtype()); EXPECT_EQ(device, x.device()); EXPECT_TRUE(x.is_contiguous()); EXPECT_EQ(0, x.offset()); ExpectDataExistsOnDevice(device, x); } class ArrayDeviceTest : public ::testing::TestWithParam<::testing::tuple<nonstd::optional<std::string>, std::string>> { protected: void SetUp() override { // Device scope is optional since we want to test device specified Array creation where no current device is set nonstd::optional<std::string> device_scope_name = ::testing::get<0>(GetParam()); std::string device_name = ::testing::get<1>(GetParam()); // Enter device scope if (device_scope_name) { device_scope_ = std::make_unique<DeviceScope>(device_scope_name.value()); } // Create the device in which Arrays will be explicitly created device_ = MakeDevice(device_name); } void TearDown() override { // Exit device scope if it was entered if (device_scope_) { device_scope_.reset(); } } template <typename T> void CheckFromBuffer(const Shape& shape, Dtype dtype, std::initializer_list<T> raw_data) { assert(shape.total_size() == static_cast<int64_t>(raw_data.size())); auto device_scope = std::make_unique<DeviceScope>(device_); std::shared_ptr<T> data = std::make_unique<T[]>(shape.total_size()); std::copy(raw_data.begin(), raw_data.end(), data.get()); { Array x = Array::FromBuffer(shape, dtype, data); CheckFromBufferMembers(x, shape, dtype, data, device_); } { const Array x = Array::FromBuffer(shape, dtype, data); CheckFromBufferMembers(x, shape, dtype, data, device_); } } void CheckEmpty(const Shape& shape, Dtype dtype) { Array x = Array::Empty(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); } void CheckFullWithGivenDtype(const Shape& shape, Scalar scalar, Dtype dtype) { Array x = Array::Full(shape, scalar, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, scalar); } void CheckFullWithScalarDtype(const Shape& shape, Scalar scalar) { Array x = Array::Full(shape, scalar, device_); CheckCommonMembers(x, shape, scalar.dtype(), device_); ExpectDataEqual(x, scalar.dtype(), scalar); } void CheckZeros(const Shape& shape, Dtype dtype) { Array x = Array::Zeros(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, 0); } void CheckOnes(const Shape& shape, Dtype dtype) { Array x = Array::Ones(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, 1); } void CheckEmptyLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::EmptyLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); } void CheckFullLike(const Shape& shape, Scalar scalar, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::FullLike(x_orig, scalar, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, scalar); } void CheckZerosLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::ZerosLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, 0); } void CheckOnesLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::OnesLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, 1); } private: std::unique_ptr<DeviceScope> device_scope_; Device device_; }; TEST_P(ArrayDeviceTest, FromBuffer) { CheckFromBuffer({2, 3}, Dtype::kFloat32, {0.f, 1.f, 2.f, 3.f, 4.f, 5.f}); } TEST_P(ArrayDeviceTest, Empty) { CheckEmpty({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullWithGivenDtype) { CheckFullWithGivenDtype({2, 3}, float{2.f}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullWithScalarDtype) { CheckFullWithScalarDtype({2, 3}, float{2.f}); } TEST_P(ArrayDeviceTest, Ones) { CheckOnes({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, Zeros) { CheckZeros({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, EmptyLike) { CheckEmptyLike({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullLike) { CheckFullLike({2, 3}, float{2.f}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, ZerosLike) { CheckZerosLike({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, OnesLike) { CheckOnesLike({2, 3}, Dtype::kFloat32); } #ifdef XCHAINER_ENABLE_CUDA // Native and CUDA device combinations const auto parameters = ::testing::Combine(::testing::Values(nonstd::nullopt, nonstd::optional<std::string>(std::string("cpu")), nonstd::optional<std::string>(std::string("cuda"))), ::testing::Values(std::string("cpu"), std::string("cuda"))); #else // Native device only const auto parameters = ::testing::Combine(::testing::Values(nonstd::nullopt, nonstd::optional<std::string>(std::string("cpu"))), ::testing::Values(std::string("cpu"))); #endif // XCHAINER_ENABLE_CUDA INSTANTIATE_TEST_CASE_P(ForEachDevicePair, ArrayDeviceTest, parameters); } // namespace } // namespace xchainer
#include "xchainer/array.h" #include <cassert> #include <initializer_list> #include <string> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/device.h" #include "xchainer/memory.h" namespace xchainer { namespace { template <typename T> void ExpectDataEqual(const T* expected_data, const Array& actual) { #ifdef XCHAINER_ENABLE_CUDA if (actual.device() == MakeDevice("cuda")) { cuda::CheckError(cudaDeviceSynchronize()); } #endif // XCHAINER_ENABLE_CUDA auto total_size = actual.shape().total_size(); const T* actual_data = static_cast<const T*>(actual.data().get()); for (decltype(total_size) i = 0; i < total_size; i++) { EXPECT_EQ(expected_data[i], actual_data[i]) << "where i is " << i; } } template <typename T> void ExpectDataEqual(T expected, const Array& actual) { #ifdef XCHAINER_ENABLE_CUDA if (actual.device() == MakeDevice("cuda")) { cuda::CheckError(cudaDeviceSynchronize()); } #endif // XCHAINER_ENABLE_CUDA auto total_size = actual.shape().total_size(); const T* actual_data = static_cast<const T*>(actual.data().get()); for (decltype(total_size) i = 0; i < total_size; i++) { if (std::isnan(expected)) { EXPECT_TRUE(std::isnan(actual_data[i])) << "where i is " << i; } else { EXPECT_EQ(expected, actual_data[i]) << "where i is " << i; } } } void ExpectDataEqual(const Array& x, Dtype dtype, Scalar scalar) { VisitDtype(dtype, [&x, &scalar](auto pt) { using T = typename decltype(pt)::type; return ExpectDataEqual<T>(static_cast<T>(scalar), x); }); } // Check that Array data exists on the specified device void ExpectDataExistsOnDevice(const Device& expected_device, const Array& array) { // Check device of data pointee if (expected_device == MakeDevice("cpu")) { EXPECT_FALSE(internal::IsPointerCudaMemory(array.data().get())); } else if (expected_device == MakeDevice("cuda")) { EXPECT_TRUE(internal::IsPointerCudaMemory(array.data().get())); } else { FAIL() << "invalid device"; } } // Common criteria for FromBuffer, Empty, Full, Ones, Zeros, etc. void CheckCommonMembers(const Array& x, const Shape& shape, Dtype dtype, const Device& device) { EXPECT_NE(nullptr, x.data()); EXPECT_EQ(shape, x.shape()); EXPECT_EQ(shape.ndim(), x.ndim()); EXPECT_EQ(shape.total_size(), x.total_size()); EXPECT_EQ(dtype, x.dtype()); EXPECT_EQ(device, x.device()); EXPECT_TRUE(x.is_contiguous()); EXPECT_EQ(0, x.offset()); ExpectDataExistsOnDevice(device, x); } // Common criteria for EmptyLike, FullLike, OnesLike, ZerosLike, etc. void CheckCommonLikeMembers(const Array& x, const Array& x_orig, const Device& device) { EXPECT_NE(nullptr, x.data()); EXPECT_EQ(x_orig.shape(), x.shape()); EXPECT_EQ(x_orig.dtype(), x.dtype()); EXPECT_EQ(device, x.device()); EXPECT_TRUE(x.is_contiguous()); EXPECT_EQ(0, x.offset()); ExpectDataExistsOnDevice(device, x); } class ArrayDeviceTest : public ::testing::TestWithParam<::testing::tuple<nonstd::optional<std::string>, std::string>> { protected: void SetUp() override { // Device scope is optional since we want to test device specified Array creation where no current device is set nonstd::optional<std::string> device_scope_name = ::testing::get<0>(GetParam()); std::string device_name = ::testing::get<1>(GetParam()); // Enter device scope if (device_scope_name) { device_scope_ = std::make_unique<DeviceScope>(device_scope_name.value()); } // Create the device in which Arrays will be explicitly created device_ = MakeDevice(device_name); } void TearDown() override { // Exit device scope if it was entered if (device_scope_) { device_scope_.reset(); } } template <typename T> void CheckFromBuffer(const Shape& shape, Dtype dtype, std::initializer_list<T> raw_data) { assert(shape.total_size() == static_cast<int64_t>(raw_data.size())); auto device_scope = std::make_unique<DeviceScope>(device_); std::shared_ptr<T> data = std::make_unique<T[]>(shape.total_size()); std::copy(raw_data.begin(), raw_data.end(), data.get()); { Array x = Array::FromBuffer(shape, dtype, data); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual<T>(data.get(), x); EXPECT_EQ(int64_t{sizeof(T)}, x.element_bytes()); EXPECT_EQ(shape.total_size() * int64_t{sizeof(T)}, x.total_bytes()); } { const Array x = Array::FromBuffer(shape, dtype, data); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual<T>(data.get(), x); EXPECT_EQ(int64_t{sizeof(T)}, x.element_bytes()); EXPECT_EQ(shape.total_size() * int64_t{sizeof(T)}, x.total_bytes()); } } void CheckEmpty(const Shape& shape, Dtype dtype) { Array x = Array::Empty(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); } void CheckFullWithGivenDtype(const Shape& shape, Scalar scalar, Dtype dtype) { Array x = Array::Full(shape, scalar, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, scalar); } void CheckFullWithScalarDtype(const Shape& shape, Scalar scalar) { Array x = Array::Full(shape, scalar, device_); CheckCommonMembers(x, shape, scalar.dtype(), device_); ExpectDataEqual(x, scalar.dtype(), scalar); } void CheckZeros(const Shape& shape, Dtype dtype) { Array x = Array::Zeros(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, 0); } void CheckOnes(const Shape& shape, Dtype dtype) { Array x = Array::Ones(shape, dtype, device_); CheckCommonMembers(x, shape, dtype, device_); ExpectDataEqual(x, dtype, 1); } void CheckEmptyLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::EmptyLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); } void CheckFullLike(const Shape& shape, Scalar scalar, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::FullLike(x_orig, scalar, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, scalar); } void CheckZerosLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::ZerosLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, 0); } void CheckOnesLike(const Shape& shape, Dtype dtype) { Array x_orig = Array::Empty(shape, dtype, device_); Array x = Array::OnesLike(x_orig, device_); CheckCommonLikeMembers(x, x_orig, device_); ExpectDataEqual(x, dtype, 1); } private: std::unique_ptr<DeviceScope> device_scope_; Device device_; }; TEST_P(ArrayDeviceTest, FromBuffer) { CheckFromBuffer({2, 3}, Dtype::kFloat32, {0.f, 1.f, 2.f, 3.f, 4.f, 5.f}); } TEST_P(ArrayDeviceTest, Empty) { CheckEmpty({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullWithGivenDtype) { CheckFullWithGivenDtype({2, 3}, float{2.f}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullWithScalarDtype) { CheckFullWithScalarDtype({2, 3}, float{2.f}); } TEST_P(ArrayDeviceTest, Ones) { CheckOnes({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, Zeros) { CheckZeros({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, EmptyLike) { CheckEmptyLike({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, FullLike) { CheckFullLike({2, 3}, float{2.f}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, ZerosLike) { CheckZerosLike({2, 3}, Dtype::kFloat32); } TEST_P(ArrayDeviceTest, OnesLike) { CheckOnesLike({2, 3}, Dtype::kFloat32); } #ifdef XCHAINER_ENABLE_CUDA // Native and CUDA device combinations const auto parameters = ::testing::Combine(::testing::Values(nonstd::nullopt, nonstd::optional<std::string>(std::string("cpu")), nonstd::optional<std::string>(std::string("cuda"))), ::testing::Values(std::string("cpu"), std::string("cuda"))); #else // Native device only const auto parameters = ::testing::Combine(::testing::Values(nonstd::nullopt, nonstd::optional<std::string>(std::string("cpu"))), ::testing::Values(std::string("cpu"))); #endif // XCHAINER_ENABLE_CUDA INSTANTIATE_TEST_CASE_P(ForEachDevicePair, ArrayDeviceTest, parameters); } // namespace } // namespace xchainer
Remove sparely used function
Remove sparely used function
C++
mit
okuta/chainer,okuta/chainer,niboshi/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,tkerola/chainer,keisuke-umezawa/chainer,pfnet/chainer,niboshi/chainer,wkentaro/chainer,keisuke-umezawa/chainer,ktnyt/chainer,hvy/chainer,chainer/chainer,chainer/chainer,hvy/chainer,hvy/chainer,wkentaro/chainer,keisuke-umezawa/chainer,ktnyt/chainer,chainer/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,okuta/chainer,niboshi/chainer,jnishi/chainer,jnishi/chainer,jnishi/chainer,wkentaro/chainer
cf98d9c2884c3847047796b4b8930c2214839488
lib/src/control.cc
lib/src/control.cc
#include <algorithm> #include <chrono> #include "control.h" #include "bvs/archutils.h" using BVS::Control; using BVS::SystemFlag; Control::Control(ModuleDataMap& modules, BVS& bvs, Info& info) : modules(modules), bvs(bvs), info(info), logger{"Control"}, activePools{0}, pools{}, flag{SystemFlag::PAUSE}, barrier{}, masterLock{barrier.attachParty()}, controlThread{}, round{0}, shutdownRequested{false}, shutdownRound{0} { pools["master"] = std::make_shared<PoolData>("master", ControlFlag::WAIT); } Control& Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(3, "master -> FORKED!"); controlThread = std::thread{&Control::masterController, this, false}; return *this; } else { nameThisThread("masterControl"); // startup sync barrier.notify(); barrier.enqueue(masterLock, [&](){ return activePools.load()==0; }); activePools.store(0); } std::chrono::time_point<std::chrono::high_resolution_clock> timer = std::chrono::high_resolution_clock::now(); while (flag!=SystemFlag::QUIT) { // round sync barrier.enqueue(masterLock, [&](){ return activePools.load()==0; }); info.lastRoundDuration = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer); timer = std::chrono::high_resolution_clock::now(); switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: if (!controlThread.joinable()) return *this; LOG(3, "PAUSE..."); barrier.enqueue(masterLock, [&](){ return flag!=SystemFlag::PAUSE; }); timer = std::chrono::high_resolution_clock::now(); break; case SystemFlag::RUN: case SystemFlag::STEP: LOG(2, "ROUND: " << round); info.round = round++; for (auto& module: modules) { if (module.second->status!=Status::OK) checkModuleStatus(module.second); module.second->flag = ControlFlag::RUN; } for (auto& pool: pools) pool.second->flag = ControlFlag::RUN; activePools.fetch_add(pools.size()-1); //exclude "master" pool barrier.notify(); for (auto& it: pools["master"]->modules) moduleController(*(it.get())); if (flag==SystemFlag::STEP) flag = SystemFlag::PAUSE; LOG(3, "WAIT FOR THREADS AND POOLS!"); break; case SystemFlag::STEP_BACK: break; } if (shutdownRequested && round==shutdownRound) flag = SystemFlag::QUIT; if (!controlThread.joinable() && flag!=SystemFlag::RUN) return *this; } for (auto& pool: pools) pool.second->flag = ControlFlag::QUIT; if (shutdownRequested && round==shutdownRound) bvs.shutdownHandler(); return *this; } Control& Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "FLAG: " << (int)controlFlag); flag = controlFlag; if (controlThread.joinable()) barrier.notify(); else masterController(false); if (controlFlag==SystemFlag::QUIT) { if (controlThread.joinable() && std::this_thread::get_id()!=controlThread.get_id()) { LOG(3, "JOIN MASTER CONTROLLER!"); controlThread.join(); } } return *this; } SystemFlag Control::queryActiveFlag() { return flag; } Control& Control::startModule(std::string id) { auto data = modules[id]; if (data->poolName.empty()) data->poolName = "master"; LOG(3, id << " -> POOL(" << data->poolName << ")"); if (pools.find(data->poolName)==pools.end()) { pools[data->poolName] = std::make_shared<PoolData>(data->poolName, ControlFlag::WAIT); pools[data->poolName]->thread = std::thread{&Control::poolController, this, pools[data->poolName]}; activePools.fetch_add(1); waitUntilInactive(id); pools[data->poolName]->modules.push_back(modules[id]); } else { pools[data->poolName]->modules.push_back(modules[id]); } return *this; } Control& Control::stopModule(std::string id) { // search for pool if (modules.find(id)==modules.end()) return *this; auto poolName = modules[id]->poolName; if (pools.find(poolName)==pools.end()) return *this; auto pool = pools[poolName]; // stop pool auto flag = pool->flag; pool->flag = ControlFlag::WAIT; waitUntilInactive(id); // remove module from pool modules auto& poolModules = pools[poolName]->modules; if (!poolModules.empty()) poolModules.erase(std::remove_if (poolModules.begin(), poolModules.end(), [&](std::shared_ptr<ModuleData> data) { return data->id==id; })); pool->flag = flag; barrier.notify(); return *this; } Control& Control::waitUntilInactive(const std::string& id) { while (isActive(id)) { std::this_thread::sleep_for(std::chrono::milliseconds{100}); barrier.notify(); } return *this; } bool Control::isActive(const std::string& id) { if (!modules[id]->poolName.empty()) { if (modules.find(id)==modules.end()) return false; if (pools.find(modules[id]->poolName)==pools.end()) return false; if (pools[modules[id]->poolName]->flag!=ControlFlag::WAIT) return true; else return false; } return false; } Control& Control::moduleController(ModuleData& data) { std::chrono::time_point<std::chrono::high_resolution_clock> modTimer = std::chrono::high_resolution_clock::now(); switch (data.flag) { case ControlFlag::QUIT: break; case ControlFlag::WAIT: break; case ControlFlag::RUN: data.status = data.module->execute(); data.flag = ControlFlag::WAIT; break; } info.moduleDurations[data.id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - modTimer); return *this; } Control& Control::poolController(std::shared_ptr<PoolData> data) { nameThisThread(("["+data->poolName+"]").c_str()); LOG(3, "POOL(" << data->poolName << ") STARTED!"); std::unique_lock<std::mutex> threadLock{barrier.attachParty()}; std::chrono::time_point<std::chrono::high_resolution_clock> poolTimer = std::chrono::high_resolution_clock::now(); while (bool(data->flag) && !data->modules.empty()) { poolTimer = std::chrono::high_resolution_clock::now(); for (auto& module: data->modules) moduleController(*(module.get())); data->flag = ControlFlag::WAIT; activePools.fetch_sub(1); info.poolDurations[data->poolName] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - poolTimer); LOG(3, "POOL(" << data->poolName << ") WAIT!"); barrier.enqueue(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; }); } pools.erase(pools.find(data->poolName)); LOG(3, "POOL(" << data->poolName << ") QUITTING!"); return *this; } Control& Control::checkModuleStatus(std::shared_ptr<ModuleData> data) { switch (data->status) { case Status::OK: break; case Status::NOINPUT: break; case Status::FAIL: break; case Status::WAIT: break; case Status::DONE: bvs.unloadModule(data->id); break; case Status::SHUTDOWN: if (!shutdownRequested) { LOG(1, "SHUTDOWN REQUEST BY '" << data->id << "', SHUTTING DOWN IN '" << modules.size() << "' ROUNDS!"); shutdownRequested = true; shutdownRound = round + modules.size(); } break; } return *this; }
#include <algorithm> #include <chrono> #include "control.h" #include "bvs/archutils.h" using BVS::Control; using BVS::SystemFlag; Control::Control(ModuleDataMap& modules, BVS& bvs, Info& info) : modules(modules), bvs(bvs), info(info), logger{"Control"}, activePools{0}, pools{}, flag{SystemFlag::PAUSE}, barrier{}, masterLock{barrier.attachParty()}, controlThread{}, round{0}, shutdownRequested{false}, shutdownRound{0} { pools["master"] = std::make_shared<PoolData>("master", ControlFlag::WAIT); } Control& Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(3, "master -> FORKED!"); controlThread = std::thread{&Control::masterController, this, false}; return *this; } else { nameThisThread("masterControl"); // startup sync barrier.notify(); barrier.enqueue(masterLock, [&](){ return activePools.load()==0; }); activePools.store(0); } std::chrono::time_point<std::chrono::high_resolution_clock> timer = std::chrono::high_resolution_clock::now(); while (flag!=SystemFlag::QUIT) { // round sync barrier.enqueue(masterLock, [&](){ return activePools.load()==0; }); info.lastRoundDuration = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer); timer = std::chrono::high_resolution_clock::now(); switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: if (!controlThread.joinable()) return *this; LOG(3, "PAUSE..."); barrier.enqueue(masterLock, [&](){ return flag!=SystemFlag::PAUSE; }); timer = std::chrono::high_resolution_clock::now(); break; case SystemFlag::RUN: case SystemFlag::STEP: LOG(2, "ROUND: " << round); info.round = round++; for (auto& module: modules) { if (module.second->status!=Status::OK) checkModuleStatus(module.second); module.second->flag = ControlFlag::RUN; } for (auto& pool: pools) pool.second->flag = ControlFlag::RUN; activePools.fetch_add(pools.size()-1); //exclude "master" pool barrier.notify(); for (auto& it: pools["master"]->modules) moduleController(*(it.get())); info.poolDurations["master"] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer); if (flag==SystemFlag::STEP) flag = SystemFlag::PAUSE; LOG(3, "WAIT FOR THREADS AND POOLS!"); break; case SystemFlag::STEP_BACK: break; } if (shutdownRequested && round==shutdownRound) flag = SystemFlag::QUIT; if (!controlThread.joinable() && flag!=SystemFlag::RUN) return *this; } for (auto& pool: pools) pool.second->flag = ControlFlag::QUIT; if (shutdownRequested && round==shutdownRound) bvs.shutdownHandler(); return *this; } Control& Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "FLAG: " << (int)controlFlag); flag = controlFlag; if (controlThread.joinable()) barrier.notify(); else masterController(false); if (controlFlag==SystemFlag::QUIT) { if (controlThread.joinable() && std::this_thread::get_id()!=controlThread.get_id()) { LOG(3, "JOIN MASTER CONTROLLER!"); controlThread.join(); } } return *this; } SystemFlag Control::queryActiveFlag() { return flag; } Control& Control::startModule(std::string id) { auto data = modules[id]; if (data->poolName.empty()) data->poolName = "master"; LOG(3, id << " -> POOL(" << data->poolName << ")"); if (pools.find(data->poolName)==pools.end()) { pools[data->poolName] = std::make_shared<PoolData>(data->poolName, ControlFlag::WAIT); pools[data->poolName]->thread = std::thread{&Control::poolController, this, pools[data->poolName]}; activePools.fetch_add(1); waitUntilInactive(id); pools[data->poolName]->modules.push_back(modules[id]); } else { pools[data->poolName]->modules.push_back(modules[id]); } return *this; } Control& Control::stopModule(std::string id) { // search for pool if (modules.find(id)==modules.end()) return *this; auto poolName = modules[id]->poolName; if (pools.find(poolName)==pools.end()) return *this; auto pool = pools[poolName]; // stop pool auto flag = pool->flag; pool->flag = ControlFlag::WAIT; waitUntilInactive(id); // remove module from pool modules auto& poolModules = pools[poolName]->modules; if (!poolModules.empty()) poolModules.erase(std::remove_if (poolModules.begin(), poolModules.end(), [&](std::shared_ptr<ModuleData> data) { return data->id==id; })); pool->flag = flag; barrier.notify(); return *this; } Control& Control::waitUntilInactive(const std::string& id) { while (isActive(id)) { std::this_thread::sleep_for(std::chrono::milliseconds{100}); barrier.notify(); } return *this; } bool Control::isActive(const std::string& id) { if (!modules[id]->poolName.empty()) { if (modules.find(id)==modules.end()) return false; if (pools.find(modules[id]->poolName)==pools.end()) return false; if (pools[modules[id]->poolName]->flag!=ControlFlag::WAIT) return true; else return false; } return false; } Control& Control::moduleController(ModuleData& data) { std::chrono::time_point<std::chrono::high_resolution_clock> modTimer = std::chrono::high_resolution_clock::now(); switch (data.flag) { case ControlFlag::QUIT: break; case ControlFlag::WAIT: break; case ControlFlag::RUN: data.status = data.module->execute(); data.flag = ControlFlag::WAIT; break; } info.moduleDurations[data.id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - modTimer); return *this; } Control& Control::poolController(std::shared_ptr<PoolData> data) { nameThisThread(("["+data->poolName+"]").c_str()); LOG(3, "POOL(" << data->poolName << ") STARTED!"); std::unique_lock<std::mutex> threadLock{barrier.attachParty()}; std::chrono::time_point<std::chrono::high_resolution_clock> poolTimer = std::chrono::high_resolution_clock::now(); while (bool(data->flag) && !data->modules.empty()) { poolTimer = std::chrono::high_resolution_clock::now(); for (auto& module: data->modules) moduleController(*(module.get())); data->flag = ControlFlag::WAIT; activePools.fetch_sub(1); info.poolDurations[data->poolName] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - poolTimer); LOG(3, "POOL(" << data->poolName << ") WAIT!"); barrier.enqueue(threadLock, [&](){ return data->flag!=ControlFlag::WAIT; }); } pools.erase(pools.find(data->poolName)); LOG(3, "POOL(" << data->poolName << ") QUITTING!"); return *this; } Control& Control::checkModuleStatus(std::shared_ptr<ModuleData> data) { switch (data->status) { case Status::OK: break; case Status::NOINPUT: break; case Status::FAIL: break; case Status::WAIT: break; case Status::DONE: bvs.unloadModule(data->id); break; case Status::SHUTDOWN: if (!shutdownRequested) { LOG(1, "SHUTDOWN REQUEST BY '" << data->id << "', SHUTTING DOWN IN '" << modules.size() << "' ROUNDS!"); shutdownRequested = true; shutdownRound = round + modules.size(); } break; } return *this; }
add master pool time to info.PoolDurations
control: add master pool time to info.PoolDurations
C++
mit
nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs
29908116a79b8f7b8fe744a3cfd31f9605dae28e
lib/src/control.cc
lib/src/control.cc
#include "control.h" #include<chrono> std::atomic<int> BVS::Control::runningThreads; int BVS::Control::threadedModules = 0; BVS::Control::Control() : flag(SystemFlag::PAUSE) , logger("Control") , masterMutex() , masterLock(masterMutex) , masterCond() , threadMutex() , threadCond() , controlThread() , round(0) { } BVS::Control& BVS::Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(2, "Master controller forking, now running in dedicated thread!"); //create thread with this function and this object controlThread = std::thread(&Control::masterController, this, false); return *this; } // wait until all started threads have reached their control loop masterCond.notify_one(); masterCond.wait(masterLock, [&](){ return threadedModules == runningThreads.load(); }); runningThreads.store(0); // main loop, repeat until SystemFlag::QUIT is set while (flag != SystemFlag::QUIT) { // wait until all threads are synchronized masterCond.wait_for(masterLock, std::chrono::milliseconds(10), [&](){ return runningThreads.load() == 0; }); // act on system flag switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: // if not running inside own thread, return if (!controlThread.joinable()) return *this; LOG(3, "Pausing..."); masterCond.wait(masterLock, [&](){ return flag != SystemFlag::PAUSE; }); LOG(3, "Continuing..."); break; case SystemFlag::RUN: case SystemFlag::STEP: LOG(3, "Starting next round, notifying threads and executing modules!"); LOG(2, "ROUND: " << round++); // set RUN flag for all modules and signal threads for (auto& it: Loader::modules) { it.second->flag = ModuleFlag::RUN; if (it.second->asThread) runningThreads.fetch_add(1); } threadCond.notify_all(); // iterate through modules executed by master for (auto& it: Loader::masterModules) { moduleController(*(it.get())); } if (flag == SystemFlag::STEP) flag = SystemFlag::PAUSE; break; case SystemFlag::STEP_BACK: break; } LOG(3, "Waiting for threads to finish!"); // return if not control thread if (!controlThread.joinable() && flag != SystemFlag::RUN) return *this; } return *this; } BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "Control() called with flag: " << (int)controlFlag); flag = controlFlag; // check if controlThread is running and notify it, otherwise call control function each time if (controlThread.joinable()) { LOG(3, "Control() notifying master!"); masterCond.notify_one(); } else { LOG(3, "Control() calling master control directly!"); masterController(false); } // on quitting, wait for control thread if necessary if (controlFlag == SystemFlag::QUIT) { if (controlThread.joinable()) { LOG(2, "Waiting for master control thread to join!"); controlThread.join(); } } return *this; } BVS::Control& BVS::Control::moduleController(ModuleData& data) { switch (data.flag) { case ModuleFlag::QUIT: break; case ModuleFlag::WAIT: break; case ModuleFlag::RUN: // call execution functions data.status = data.module->execute(); // reset module flag data.flag = ModuleFlag::WAIT; break; } return *this; } BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data) { // acquire lock needed for conditional variable std::unique_lock<std::mutex> threadLock(threadMutex); // tell system that thread has started runningThreads.fetch_add(1); while (bool(data->flag)) { // wait for master to announce next round LOG(3, data->id << " Waiting for next round!"); masterCond.notify_one(); threadCond.wait(threadLock, [&](){ return data->flag != ModuleFlag::WAIT; }); // call module control moduleController(*(data.get())); // tell master that thread has finished this round runningThreads.fetch_sub(1); } return *this; }
#include "control.h" #include<chrono> std::atomic<int> BVS::Control::runningThreads; int BVS::Control::threadedModules = 0; BVS::Control::Control() : flag(SystemFlag::PAUSE) , logger("Control") , masterMutex() , masterLock(masterMutex) , masterCond() , threadMutex() , threadCond() , controlThread() , round(0) { runningThreads.store(0); } BVS::Control& BVS::Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(2, "Master controller forking, now running in dedicated thread!"); //create thread with this function and this object controlThread = std::thread(&Control::masterController, this, false); return *this; } // wait until all started threads have reached their control loop masterCond.notify_one(); masterCond.wait(masterLock, [&](){ return threadedModules == runningThreads.load(); }); runningThreads.store(0); // main loop, repeat until SystemFlag::QUIT is set while (flag != SystemFlag::QUIT) { // wait until all threads are synchronized masterCond.wait(masterLock, [&](){ return runningThreads.load() == 0; }); //masterCond.wait_for(masterLock, std::chrono::milliseconds(10), [&](){ return runningThreads.load() == 0; }); // act on system flag switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: // if not running inside own thread, return if (!controlThread.joinable()) return *this; LOG(3, "Pausing..."); masterCond.wait(masterLock, [&](){ return flag != SystemFlag::PAUSE; }); LOG(3, "Continuing..."); break; case SystemFlag::RUN: case SystemFlag::STEP: LOG(3, "Starting next round, notifying threads and executing modules!"); LOG(2, "ROUND: " << round++); // set RUN flag for all modules and signal threads for (auto& it: Loader::modules) { it.second->flag = ModuleFlag::RUN; if (it.second->asThread) runningThreads.fetch_add(1, std::memory_order_seq_cst); } threadCond.notify_all(); // iterate through modules executed by master for (auto& it: Loader::masterModules) { moduleController(*(it.get())); } if (flag == SystemFlag::STEP) flag = SystemFlag::PAUSE; break; case SystemFlag::STEP_BACK: break; } LOG(3, "Waiting for threads to finish!"); // return if not control thread if (!controlThread.joinable() && flag != SystemFlag::RUN) return *this; } return *this; } BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "Control() called with flag: " << (int)controlFlag); flag = controlFlag; // check if controlThread is running and notify it, otherwise call control function each time if (controlThread.joinable()) { LOG(3, "Control() notifying master!"); masterCond.notify_one(); } else { LOG(3, "Control() calling master control directly!"); masterController(false); } // on quitting, wait for control thread if necessary if (controlFlag == SystemFlag::QUIT) { if (controlThread.joinable()) { LOG(2, "Waiting for master control thread to join!"); controlThread.join(); } } return *this; } BVS::Control& BVS::Control::moduleController(ModuleData& data) { switch (data.flag) { case ModuleFlag::QUIT: break; case ModuleFlag::WAIT: break; case ModuleFlag::RUN: // call execution functions data.status = data.module->execute(); // reset module flag data.flag = ModuleFlag::WAIT; break; } return *this; } BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data) { // acquire lock needed for conditional variable std::unique_lock<std::mutex> threadLock(threadMutex); // tell system that thread has started runningThreads.fetch_add(1, std::memory_order_seq_cst); while (bool(data->flag)) { // wait for master to announce next round LOG(3, data->id << " Waiting for next round!"); masterCond.notify_one(); threadCond.wait(threadLock, [&](){ return data->flag != ModuleFlag::WAIT; }); // call module control moduleController(*(data.get())); // tell master that thread has finished this round runningThreads.fetch_sub(1, std::memory_order_seq_cst); } return *this; }
fix weird run behaviour
control: fix weird run behaviour
C++
mit
nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs,nilsonholger/bvs
c7ecc12efc81c9c00e61961387d27447fdef3769
libipc/control.cpp
libipc/control.cpp
//===-- control.cpp -------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Control-related operations for registered sockets // //===----------------------------------------------------------------------===// #include "ipcopt.h" #include "debug.h" #include "ipcd.h" #include "ipcreg_internal.h" #include "real.h" #include "string.h" #include <algorithm> #include <fcntl.h> int do_ipc_shutdown(int sockfd, int how) { ipc_info &i = getInfo(getEP(sockfd)); assert(i.state != STATE_INVALID); int ret = __real_shutdown(sockfd, how); // Do similar shutdown operation on local fd, if exists: if (i.state == STATE_OPTIMIZED) { assert(i.localfd); int localret = __real_shutdown(i.localfd, how); assert(localret == ret); // We don't handle mismatch yet } return ret; } int do_ipc_poll(struct pollfd fds[], nfds_t nfds, int timeout) { // For now, replace registered fd's with optimized versions const nfds_t MAX_POLL_FDS = 128; struct pollfd newfds[MAX_POLL_FDS]; assert(nfds < MAX_POLL_FDS); memcpy(newfds, fds, sizeof(fds[0]) * nfds); for (nfds_t i = 0; i < nfds; ++i) { int fd = newfds[i].fd; if (!is_optimized_socket_safe(fd)) continue; newfds[i].fd = getInfo(getEP(fd)).localfd; } int ret = __real_poll(newfds, nfds, timeout); // Copy 'revents' back out from newfds, // as written by 'poll': for (nfds_t i = 0; i < nfds; ++i) { fds[i].revents = newfds[i].revents; } return ret; } fd_set *copy_if_needed(fd_set *src, fd_set *copy, int &nfds) { // Portable way to find fd's contained in the fd_set // More intrusive implementation would be much more efficient! int maxfd = std::min<int>(FD_SETSIZE, TABLE_SIZE); // NULL sets are easy :) if (src == NULL) return src; bool need_copy = false; int fds_found = 0; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, src)) continue; ++fds_found; if (!is_optimized_socket_safe(fd)) continue; need_copy = true; } if (!need_copy) return src; FD_ZERO(copy); // Make second pass, copying into 'copy' // either original fd or the localfd for optimized connections. fds_found = 0; int orig_nfds = nfds; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, src)) continue; ++fds_found; if (!is_optimized_socket_safe(fd)) { assert(!FD_ISSET(fd, copy)); FD_SET(fd, copy); } else { int localfd = getInfo(getEP(fd)).localfd; assert(!FD_ISSET(fd, copy)); FD_SET(localfd, copy); // 'nfds' needs to be value of largest fd plus 1 nfds = std::max(localfd+1, nfds); } } if (false) { if (nfds != orig_nfds) ipclog("In handling call to (p)select(), increased nfds: %d -> %d\n", orig_nfds, nfds); } return copy; } void select__copy_to_output(fd_set *out, fd_set*givenout, int nfds) { // If they're the same, output was already written to givenout if (out == givenout) return; int maxfd = std::min<int>(FD_SETSIZE, TABLE_SIZE); // For each fd set in 'givenout', check if // it or its optimized local version were set // by select in the given 'out' set. int fds_found = 0; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, givenout)) continue; ++fds_found; int equiv_fd = fd; if (is_optimized_socket_safe(fd)) equiv_fd = getInfo(getEP(fd)).localfd; // If the equivalent (local if exists) fd // was not marked by select(), clear it here as well: if (!FD_ISSET(equiv_fd, out)) FD_CLR(fd, givenout); } } int do_ipc_pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, const struct timespec *timeout, const sigset_t *sigmask) { assert(nfds >= 0); fd_set rcopy, wcopy, ecopy; fd_set *r = copy_if_needed(readfds, &rcopy, nfds); fd_set *w = copy_if_needed(writefds, &wcopy, nfds); fd_set *e = copy_if_needed(errorfds, &ecopy, nfds); int ret = __real_pselect(nfds, r, w, e, timeout, sigmask); select__copy_to_output(r, readfds, nfds); select__copy_to_output(w, writefds, nfds); select__copy_to_output(e, errorfds, nfds); return ret; } int do_ipc_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) { assert(nfds >= 0); fd_set rcopy, wcopy, ecopy; fd_set *r = copy_if_needed(readfds, &rcopy, nfds); fd_set *w = copy_if_needed(writefds, &wcopy, nfds); fd_set *e = copy_if_needed(errorfds, &ecopy, nfds); int ret = __real_select(nfds, r, w, e, timeout); select__copy_to_output(r, readfds, nfds); select__copy_to_output(w, writefds, nfds); select__copy_to_output(e, errorfds, nfds); return ret; } void set_local_nonblocking(int fd, bool nonblocking) { ipc_info & i = getInfo(getEP(fd)); assert(i.state == STATE_OPTIMIZED); assert(i.localfd); int flags = __real_fcntl(i.localfd, F_GETFL, /* kludge*/ 0); assert(flags >= 0); if (nonblocking) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; int ret = __real_fcntl_int(i.localfd, F_SETFL, flags); assert(ret != -1); } int do_ipc_fcntl(int fd, int cmd, void *arg) { int ret = __real_fcntl(fd, cmd, arg); if (ret == -1) { // Ignore erroneous fcntl commands return ret; } int iarg = (int)(uintptr_t)arg; // XXX: Desired casting behavior? switch (cmd) { case F_SETFD: // Setting fd options set_cloexec(fd, (iarg & FD_CLOEXEC) != 0); break; case F_SETFL: { // Setting description/endpoint options bool non_blocking = (iarg & O_NONBLOCK) != 0; set_nonblocking(fd, non_blocking); if (is_optimized_socket_safe(fd)) { // Ensure localfd has same non-blocking features set_local_nonblocking(fd, non_blocking); } break; } default: // Ignore for now. break; } return ret; } int do_ipc_setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len) { int ret = __real_setsockopt(socket, level, option_name, option_value, option_len); // TODO: ... what options do we care about? return ret; }
//===-- control.cpp -------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Control-related operations for registered sockets // //===----------------------------------------------------------------------===// #include "ipcopt.h" #include "debug.h" #include "ipcd.h" #include "ipcreg_internal.h" #include "real.h" #include <algorithm> #include <fcntl.h> #include <string.h> int do_ipc_shutdown(int sockfd, int how) { ipc_info &i = getInfo(getEP(sockfd)); assert(i.state != STATE_INVALID); int ret = __real_shutdown(sockfd, how); // Do similar shutdown operation on local fd, if exists: if (i.state == STATE_OPTIMIZED) { assert(i.localfd); int localret = __real_shutdown(i.localfd, how); if (localret == 0 && ret == -1) { ipclog("shutdown(%d, %d) error, local succeeded\n", sockfd, how); } } return ret; } int do_ipc_poll(struct pollfd fds[], nfds_t nfds, int timeout) { // For now, replace registered fd's with optimized versions const nfds_t MAX_POLL_FDS = 128; struct pollfd newfds[MAX_POLL_FDS]; assert(nfds < MAX_POLL_FDS); memcpy(newfds, fds, sizeof(fds[0]) * nfds); for (nfds_t i = 0; i < nfds; ++i) { int fd = newfds[i].fd; if (!is_optimized_socket_safe(fd)) continue; newfds[i].fd = getInfo(getEP(fd)).localfd; } int ret = __real_poll(newfds, nfds, timeout); // Copy 'revents' back out from newfds, // as written by 'poll': for (nfds_t i = 0; i < nfds; ++i) { fds[i].revents = newfds[i].revents; } return ret; } fd_set *copy_if_needed(fd_set *src, fd_set *copy, int &nfds) { // Portable way to find fd's contained in the fd_set // More intrusive implementation would be much more efficient! int maxfd = std::min<int>(FD_SETSIZE, TABLE_SIZE); // NULL sets are easy :) if (src == NULL) return src; bool need_copy = false; int fds_found = 0; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, src)) continue; ++fds_found; if (!is_optimized_socket_safe(fd)) continue; need_copy = true; } if (!need_copy) return src; FD_ZERO(copy); // Make second pass, copying into 'copy' // either original fd or the localfd for optimized connections. fds_found = 0; int orig_nfds = nfds; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, src)) continue; ++fds_found; if (!is_optimized_socket_safe(fd)) { assert(!FD_ISSET(fd, copy)); FD_SET(fd, copy); } else { int localfd = getInfo(getEP(fd)).localfd; assert(!FD_ISSET(fd, copy)); FD_SET(localfd, copy); // 'nfds' needs to be value of largest fd plus 1 nfds = std::max(localfd+1, nfds); } } if (false) { if (nfds != orig_nfds) ipclog("In handling call to (p)select(), increased nfds: %d -> %d\n", orig_nfds, nfds); } return copy; } void select__copy_to_output(fd_set *out, fd_set*givenout, int nfds) { // If they're the same, output was already written to givenout if (out == givenout) return; int maxfd = std::min<int>(FD_SETSIZE, TABLE_SIZE); // For each fd set in 'givenout', check if // it or its optimized local version were set // by select in the given 'out' set. int fds_found = 0; for (int fd = 0; fd < maxfd && fds_found < nfds; ++fd) { if (!FD_ISSET(fd, givenout)) continue; ++fds_found; int equiv_fd = fd; if (is_optimized_socket_safe(fd)) equiv_fd = getInfo(getEP(fd)).localfd; // If the equivalent (local if exists) fd // was not marked by select(), clear it here as well: if (!FD_ISSET(equiv_fd, out)) FD_CLR(fd, givenout); } } int do_ipc_pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, const struct timespec *timeout, const sigset_t *sigmask) { assert(nfds >= 0); fd_set rcopy, wcopy, ecopy; fd_set *r = copy_if_needed(readfds, &rcopy, nfds); fd_set *w = copy_if_needed(writefds, &wcopy, nfds); fd_set *e = copy_if_needed(errorfds, &ecopy, nfds); int ret = __real_pselect(nfds, r, w, e, timeout, sigmask); select__copy_to_output(r, readfds, nfds); select__copy_to_output(w, writefds, nfds); select__copy_to_output(e, errorfds, nfds); return ret; } int do_ipc_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) { assert(nfds >= 0); fd_set rcopy, wcopy, ecopy; fd_set *r = copy_if_needed(readfds, &rcopy, nfds); fd_set *w = copy_if_needed(writefds, &wcopy, nfds); fd_set *e = copy_if_needed(errorfds, &ecopy, nfds); int ret = __real_select(nfds, r, w, e, timeout); select__copy_to_output(r, readfds, nfds); select__copy_to_output(w, writefds, nfds); select__copy_to_output(e, errorfds, nfds); return ret; } void set_local_nonblocking(int fd, bool nonblocking) { ipc_info & i = getInfo(getEP(fd)); assert(i.state == STATE_OPTIMIZED); assert(i.localfd); int flags = __real_fcntl(i.localfd, F_GETFL, /* kludge*/ 0); assert(flags >= 0); if (nonblocking) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; int ret = __real_fcntl_int(i.localfd, F_SETFL, flags); assert(ret != -1); } int do_ipc_fcntl(int fd, int cmd, void *arg) { int ret = __real_fcntl(fd, cmd, arg); if (ret == -1) { // Ignore erroneous fcntl commands return ret; } int iarg = (int)(uintptr_t)arg; // XXX: Desired casting behavior? switch (cmd) { case F_SETFD: // Setting fd options set_cloexec(fd, (iarg & FD_CLOEXEC) != 0); break; case F_SETFL: { // Setting description/endpoint options bool non_blocking = (iarg & O_NONBLOCK) != 0; set_nonblocking(fd, non_blocking); if (is_optimized_socket_safe(fd)) { // Ensure localfd has same non-blocking features set_local_nonblocking(fd, non_blocking); } break; } default: // Ignore for now. break; } return ret; } int do_ipc_setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len) { int ret = __real_setsockopt(socket, level, option_name, option_value, option_len); // TODO: ... what options do we care about? return ret; }
allow shutdown return value mismatch
allow shutdown return value mismatch
C++
isc
dtzWill/ipcopter,dtzWill/ipcopter,dtzWill/ipcopter,dtzWill/ipcopter,dtzWill/ipcopter,dtzWill/ipcopter
cb7959c31e3936d05ec1eafb4be54cedec0a9b11
C/plugins/north/omf/plugin.cpp
C/plugins/north/omf/plugin.cpp
/* * FogLAMP OMF north plugin. * * Copyright (c) 2018 Dianomic Systems * * Released under the Apache 2.0 Licence * * Author: Massimiliano Pinto */ #include <plugin_api.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string> #include <logger.h> #include <plugin_exception.h> #include <iostream> #include <omf.h> #include <simple_https.h> #include <config_category.h> #include <storage_client.h> using namespace std; /** * The OMF plugin interface */ extern "C" { /** * The C API plugin information structure */ static PLUGIN_INFORMATION info = { "OMF", // Name "1.0.0", // Version 0, // Flags PLUGIN_TYPE_NORTH, // Type "1.0.0" // Interface version }; /** * Plugin specific default configuration */ static const string plugin_default_config = "\"URL\": { " "\"description\": \"The URL of the PI Connector to send data to\", " "\"type\": \"string\", " "\"default\": \"https://pi-server:5460/ingress/messages\" }, " "\"producerToken\": { " "\"description\": \"The producer token that represents this FogLAMP stream\", " "\"type\": \"string\", \"default\": \"omf_north_0001\" }, " "\"OMFHttpTimeout\": { " "\"description\": \"Timeout in seconds for the HTTP operations with the OMF PI Connector Relay\", " "\"type\": \"integer\", \"default\": \"10\" }, " "\"OMFMaxRetry\": { " "\"description\": \"Max number of retries for the communication with the OMF PI Connector Relay\", " "\"type\": \"integer\", \"default\": \"3\" }, " "\"OMFRetrySleepTime\": { " "\"description\": \"Seconds between each retry for the communication with the OMF PI Connector Relay, " "NOTE : the time is doubled at each attempt.\", \"type\": \"integer\", \"default\": \"1\" }, " "\"StaticData\": { " "\"description\": \"Static data to include in each sensor reading sent to OMF.\", " "\"type\": \"string\", \"default\": \"Location: Palo Alto, Company: Dianomic\" }, " "\"applyFilter\": { " "\"description\": \"Whether to apply filter before processing the data\", " "\"type\": \"boolean\", \"default\": \"False\" }, " "\"filterRule\": { " "\"description\": \"JQ formatted filter to apply (applicable if applyFilter is True)\", " "\"type\": \"string\", \"default\": \".[]\" }"; static const string omf_types_default_config = "\"type-id\": { " "\"description\": \"Identify sensor and measurement types\", " "\"type\": \"integer\", \"default\": \"0002\" }"; static const map<const string, const string> plugin_configuration = { { "OMF_TYPES", omf_types_default_config }, { "PLUGIN", plugin_default_config }, }; /** * Historian PI Server connector info */ typedef struct { SimpleHttps *sender; // HTTPS connection OMF *omf; // OMF data protocol } CONNECTOR_INFO; static CONNECTOR_INFO connector_info; static StorageClient* storage; /** * Return the information about this plugin */ PLUGIN_INFORMATION *plugin_info() { return &info; } /** * Return default plugin configuration: * plugin specific and types_id */ const map<const string, const string>& plugin_config() { return plugin_configuration; } /** * Initialise the plugin with configuration. * * This funcion is called to get the plugin handle. */ PLUGIN_HANDLE plugin_init(map<string, string>&& configData) { /** * Handle the OMF parameters here */ ConfigCategory configCategory("cfg", configData["GLOBAL_CONFIGURATION"]); string url = configCategory.getValue("URL"); unsigned int timeout = atoi(configCategory.getValue("OMFHttpTimeout").c_str()); string producerToken = configCategory.getValue("producerToken"); /** * Handle the OMF_TYPES parameters here */ ConfigCategory configTypes("types", configData["OMF_TYPES"]); string typesId = configTypes.getValue("type-id"); /** * Extract host, port, path from URL */ size_t findProtocol = url.find_first_of(":"); string protocol = url.substr(0,findProtocol); string tmpUrl = url.substr(findProtocol + 3); size_t findPort = tmpUrl.find_first_of(":"); string hostName = tmpUrl.substr(0, findPort); size_t findPath = tmpUrl.find_first_of("/"); string port = tmpUrl.substr(findPort + 1 , findPath - findPort -1); string path = tmpUrl.substr(findPath); /** * Allocate the HTTPS handler for "Hostname : port" * connect_timeout and request_timeout. * Default is no timeout at all */ string hostAndPort(hostName + ":" + port); connector_info.sender = new SimpleHttps(hostAndPort, timeout, timeout); // Allocate the OMF data protocol connector_info.omf = new OMF(*connector_info.sender, path, typesId, producerToken); Logger::getLogger()->info("OMF plugin configured: URL=%s, " "producerToken=%s, OMF_types_id=%s", url.c_str(), producerToken.c_str(), typesId.c_str()); // TODO: return a more useful data structure for pluin handle string* handle = new string("Init done"); return (PLUGIN_HANDLE)handle; } /** * Send Readings data to historian server */ uint32_t plugin_send(const PLUGIN_HANDLE handle, const vector<Reading *> readings) { return connector_info.omf->sendToServer(readings); } /** * Shutdown the plugin * * Delete allocated data * * @param handle The plugin handle */ void plugin_shutdown(PLUGIN_HANDLE handle) { // Delete connector data delete connector_info.sender; delete connector_info.omf; // Delete the handle string* data = (string *)handle; delete data; } // End of extern "C" };
/* * FogLAMP OMF north plugin. * * Copyright (c) 2018 Dianomic Systems * * Released under the Apache 2.0 Licence * * Author: Massimiliano Pinto */ #include <plugin_api.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string> #include <logger.h> #include <plugin_exception.h> #include <iostream> #include <omf.h> #include <simple_https.h> #include <config_category.h> #include <storage_client.h> using namespace std; /** * Plugin specific default configuration */ #define PLUGIN_DEFAULT_CONFIG "\"URL\": { " \ "\"description\": \"The URL of the PI Connector to send data to\", " \ "\"type\": \"string\", " \ "\"default\": \"https://pi-server:5460/ingress/messages\" }, " \ "\"producerToken\": { " \ "\"description\": \"The producer token that represents this FogLAMP stream\", " \ "\"type\": \"string\", \"default\": \"omf_north_0001\" }, " \ "\"OMFHttpTimeout\": { " \ "\"description\": \"Timeout in seconds for the HTTP operations with the OMF PI Connector Relay\", " \ "\"type\": \"integer\", \"default\": \"10\" }, " \ "\"OMFMaxRetry\": { " \ "\"description\": \"Max number of retries for the communication with the OMF PI Connector Relay\", " \ "\"type\": \"integer\", \"default\": \"3\" }, " \ "\"OMFRetrySleepTime\": { " \ "\"description\": \"Seconds between each retry for the communication with the OMF PI Connector Relay, " \ "NOTE : the time is doubled at each attempt.\", \"type\": \"integer\", \"default\": \"1\" }, " \ "\"StaticData\": { " \ "\"description\": \"Static data to include in each sensor reading sent to OMF.\", " \ "\"type\": \"string\", \"default\": \"Location: Palo Alto, Company: Dianomic\" }, " \ "\"applyFilter\": { " \ "\"description\": \"Whether to apply filter before processing the data\", " \ "\"type\": \"boolean\", \"default\": \"False\" }, " \ "\"filterRule\": { " \ "\"description\": \"JQ formatted filter to apply (applicable if applyFilter is True)\", " \ "\"type\": \"string\", \"default\": \".[]\" }" /** * The OMF plugin interface */ extern "C" { /** * The C API plugin information structure */ static PLUGIN_INFORMATION info = { "OMF", // Name "1.0.0", // Version 0, // Flags PLUGIN_TYPE_NORTH, // Type "1.0.0", // Interface version PLUGIN_DEFAULT_CONFIG // Configuration }; static const string omf_types_default_config = "\"type-id\": { " "\"description\": \"Identify sensor and measurement types\", " "\"type\": \"integer\", \"default\": \"0002\" }"; static const map<const string, const string> plugin_configuration = { { "OMF_TYPES", omf_types_default_config }, { "PLUGIN", string(PLUGIN_DEFAULT_CONFIG) }, }; /** * Historian PI Server connector info */ typedef struct { SimpleHttps *sender; // HTTPS connection OMF *omf; // OMF data protocol } CONNECTOR_INFO; static CONNECTOR_INFO connector_info; static StorageClient* storage; /** * Return the information about this plugin */ PLUGIN_INFORMATION *plugin_info() { return &info; } /** * Return default plugin configuration: * plugin specific and types_id */ const map<const string, const string>& plugin_config() { return plugin_configuration; } /** * Initialise the plugin with configuration. * * This funcion is called to get the plugin handle. */ PLUGIN_HANDLE plugin_init(map<string, string>&& configData) { /** * Handle the OMF parameters here */ ConfigCategory configCategory("cfg", configData["GLOBAL_CONFIGURATION"]); string url = configCategory.getValue("URL"); unsigned int timeout = atoi(configCategory.getValue("OMFHttpTimeout").c_str()); string producerToken = configCategory.getValue("producerToken"); /** * Handle the OMF_TYPES parameters here */ ConfigCategory configTypes("types", configData["OMF_TYPES"]); string typesId = configTypes.getValue("type-id"); /** * Extract host, port, path from URL */ size_t findProtocol = url.find_first_of(":"); string protocol = url.substr(0,findProtocol); string tmpUrl = url.substr(findProtocol + 3); size_t findPort = tmpUrl.find_first_of(":"); string hostName = tmpUrl.substr(0, findPort); size_t findPath = tmpUrl.find_first_of("/"); string port = tmpUrl.substr(findPort + 1 , findPath - findPort -1); string path = tmpUrl.substr(findPath); /** * Allocate the HTTPS handler for "Hostname : port" * connect_timeout and request_timeout. * Default is no timeout at all */ string hostAndPort(hostName + ":" + port); connector_info.sender = new SimpleHttps(hostAndPort, timeout, timeout); // Allocate the OMF data protocol connector_info.omf = new OMF(*connector_info.sender, path, typesId, producerToken); Logger::getLogger()->info("OMF plugin configured: URL=%s, " "producerToken=%s, OMF_types_id=%s", url.c_str(), producerToken.c_str(), typesId.c_str()); // TODO: return a more useful data structure for pluin handle string* handle = new string("Init done"); return (PLUGIN_HANDLE)handle; } /** * Send Readings data to historian server */ uint32_t plugin_send(const PLUGIN_HANDLE handle, const vector<Reading *> readings) { return connector_info.omf->sendToServer(readings); } /** * Shutdown the plugin * * Delete allocated data * * @param handle The plugin handle */ void plugin_shutdown(PLUGIN_HANDLE handle) { // Delete connector data delete connector_info.sender; delete connector_info.omf; // Delete the handle string* data = (string *)handle; delete data; } // End of extern "C" };
Update plugin_api info in OMF C++ plugin (#950)
FOGL-1580: Update plugin_api info in OMF C++ plugin (#950) Use new plugin_api info config in OMF C++ plugin
C++
apache-2.0
foglamp/FogLAMP,foglamp/FogLAMP,foglamp/FogLAMP,foglamp/FogLAMP
ef36e712af209226e56a666a4f30867e854753c0
tests/error.cc
tests/error.cc
#include <yamail/resource_pool/error.hpp> #include <gtest/gtest.h> #include <limits> namespace { using namespace testing; using namespace yamail::resource_pool; using namespace yamail::resource_pool::error; using boost::system::error_code; struct error_test : Test {}; TEST(error_test, make_no_error_and_check_message) { const error_code error = make_error_code(code(ok)); EXPECT_EQ(error.message(), "no error"); } TEST(error_test, make_get_resource_timeout_error_and_check_message) { const error_code error = make_error_code(get_resource_timeout); EXPECT_EQ(error.message(), "get resource timeout"); } TEST(error_test, make_request_queue_overflow_error_and_check_message) { const error_code error = make_error_code(request_queue_overflow); EXPECT_EQ(error.message(), "request queue overflow"); } TEST(error_test, make_disabled_error_and_check_message) { const error_code error = make_error_code(disabled); EXPECT_EQ(error.message(), "resource pool is disabled"); } TEST(error_test, make_out_of_range_error_and_check_message) { const error_code error = make_error_code(code(std::numeric_limits<int>::max())); EXPECT_THROW(error.message(), std::logic_error); } TEST(error_test, make_no_error_and_category_name) { const error_code error = make_error_code(code(ok)); EXPECT_EQ(error.category().name(), "yamail::resource_pool::error::detail::category"); } }
#include <yamail/resource_pool/error.hpp> #include <gtest/gtest.h> #include <limits> namespace { using namespace testing; using namespace yamail::resource_pool; using namespace yamail::resource_pool::error; using boost::system::error_code; struct error_test : Test {}; TEST(error_test, make_no_error_and_check_message) { const error_code error = make_error_code(code(ok)); EXPECT_EQ(error.message(), "no error"); } TEST(error_test, make_get_resource_timeout_error_and_check_message) { const error_code error = make_error_code(get_resource_timeout); EXPECT_EQ(error.message(), "get resource timeout"); } TEST(error_test, make_request_queue_overflow_error_and_check_message) { const error_code error = make_error_code(request_queue_overflow); EXPECT_EQ(error.message(), "request queue overflow"); } TEST(error_test, make_disabled_error_and_check_message) { const error_code error = make_error_code(disabled); EXPECT_EQ(error.message(), "resource pool is disabled"); } TEST(error_test, make_out_of_range_error_and_check_message) { const error_code error = make_error_code(code(std::numeric_limits<int>::max())); EXPECT_THROW(error.message(), std::logic_error); } TEST(error_test, make_no_error_and_category_name) { const error_code error = make_error_code(code(ok)); EXPECT_STREQ(error.category().name(), "yamail::resource_pool::error::detail::category"); } }
Fix raw strings compare
Fix raw strings compare Change-Id: I196e14ce1ad60468745720db371277b4efc5e0d4
C++
mit
elsid/resource_pool,elsid/resource_pool,elsid/resource_pool
40f3b9b0234c958e0bf710c1da21675548b769d0
tests/init.cpp
tests/init.cpp
#include "catch.hpp" #include <iostream> #include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isALessThanB(char A, char B, bool is_capital) { std::string alphabet; if (is_capital) { alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; } else { alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; } size_t A_i; size_t B_i; for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == A) { A_i = i; } if (alphabet[i] == B) { B_i = i; } } return A_i < B_i; } bool isANotMoreThanB(person A, person B) { for (size_t i = 0; i < A.surname.length(); i++) { char A_char = A.surname[i]; char B_char = (i < B.surname.length()) ? B.surname[i] : ' '; if (isALessThanB(A.surname[i], B.surname[i], i == 0)) { return true; } else { if (A.surname[i] != B.surname[i]) { return false; } } } return true; } SCENARIO("Sort", "[s]") { //setlocale(LC_ALL, "ru_RU.utf8"); std::ifstream ru("russian_letters.txt"); for (size_t i = 0; i < 6; i++) { std::string str; ru >> str; russian_letters[i] = str[0]; } ru.close(); size_t n_persons = 2001; size_t RAM_amount = 10000; std::string names_file_name = "names.txt"; std::string surnames_file_name = "surnames.txt"; std::string database_file_name = "database.txt"; std::string output_file_name = "sorted_database.txt"; { Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); //database_sorter.sortDatabase(); size_t result = clock() - start; std::cout << result << std::endl; system("pause"); } for (size_t i = 0; i < 0; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; REQUIRE(letterI(str[0], true) == 1); }
#include "catch.hpp" #include <iostream> #include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isALessThanB(char A, char B, bool is_capital) { std::string alphabet; if (is_capital) { alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; } else { alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; } size_t A_i; size_t B_i; for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == A) { A_i = i; } if (alphabet[i] == B) { B_i = i; } } return A_i < B_i; } bool isANotMoreThanB(person A, person B) { for (size_t i = 0; i < A.surname.length(); i++) { char A_char = A.surname[i]; char B_char = (i < B.surname.length()) ? B.surname[i] : ' '; if (isALessThanB(A.surname[i], B.surname[i], i == 0)) { return true; } else { if (A.surname[i] != B.surname[i]) { return false; } } } return true; } SCENARIO("Sort", "[s]") { //setlocale(LC_ALL, "ru_RU.utf8"); std::ifstream ru("russian_letters.txt"); for (size_t i = 0; i < 6; i++) { std::string str; ru >> str; russian_letters[i] = str[0]; } ru.close(); size_t n_persons = 2001; size_t RAM_amount = 10000; std::string names_file_name = "names.txt"; std::string surnames_file_name = "surnames.txt"; std::string database_file_name = "database.txt"; std::string output_file_name = "sorted_database.txt"; { Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); //database_sorter.sortDatabase(); size_t result = clock() - start; std::cout << result << std::endl; system("pause"); } for (size_t i = 0; i < 0; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; REQUIRE(letterI(str[0], true) == 1); REQUIRE(letterI(str[1], true) == 2); REQUIRE(letterI(str[2], true) == 3); REQUIRE(letterI(str[3], true) == 4); REQUIRE(letterI(str[4], true) == 5); }
Update init.cpp
Update init.cpp
C++
mit
ArtemKokorinStudent/External-sort
6e155dae2455ac196bd59b120bc2be0357d144e7
tests/init.cpp
tests/init.cpp
#include <stack.hpp> #include <catch.hpp> SCENARIO("init", "[init]") { stack<int> A; REQUIRE(A.count() == 0); } SCENARIO("Push", "[push]") { stack<int> A; A.push(1); A.push(2); REQUIRE(A.count() == 2); } SCENARIO("Pop", "[pop]") { stack<int> A; A.push(1); A.push(2); A.pop(); REQUIRE(A.count() == 1); } SCENARIO("oper=", "[oper]"){ stack<int> A; stack<int> B; A.push(1); A.push(2); B.push(3); REQUIRE(A.count() == 2); B = A; REQUIRE(A.count() == 3); }
#include <stack.hpp> #include <catch.hpp> SCENARIO("init", "[init]") { stack<int> A; REQUIRE(A.count() == 0); } SCENARIO("Push", "[push]") { stack<int> A; A.push(1); A.push(2); REQUIRE(A.count() == 2); } SCENARIO("Pop", "[pop]") { stack<int> A; A.push(1); A.push(2); A.pop(); REQUIRE(A.count() == 1); } SCENARIO("oper=", "[oper]"){ stack<int> A; stack<int> B; A.push(1); A.push(2); B.push(3); REQUIRE(A.count() == 2); B = A; REQUIRE(B.count() == 3); }
Update init.cpp
Update init.cpp
C++
mit
rtv22/stack
9c201e33969be9e67029eeb8067b78c3387259d6
tests/main.cpp
tests/main.cpp
//Copyright (c) 2015 Ultimaker B.V. //UltiScanTastic is released under the terms of the AGPLv3 or higher. #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> /*! * \brief Runs the test cases. */ int main(int argc,char** argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); //return runner.run("",false); bool success = runner.run("", false); return success ? 0 : 1; }
//Copyright (c) 2015 Ultimaker B.V. //UltiScanTastic is released under the terms of the AGPLv3 or higher. #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> /*! * \brief Runs the test cases. */ int main(int argc,char** argv) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool success = runner.run("", false); return success ? 0 : 1; }
Remove old try for return code
Remove old try for return code Directly returning the boolean didn't work.
C++
agpl-3.0
pratikshashroff/pcura,Ultimaker/CuraEngine,totalretribution/CuraEngine,markwal/CuraEngine,Ultimaker/CuraEngine,ROBO3D/CuraEngine,ROBO3D/CuraEngine,totalretribution/CuraEngine,ROBO3D/CuraEngine,alephobjects/CuraEngine,pratikshashroff/pcura,totalretribution/CuraEngine,markwal/CuraEngine,pratikshashroff/pcura,alephobjects/CuraEngine,alephobjects/CuraEngine,markwal/CuraEngine
431e00d8d5626ef816732592eb46ef4c17a4196a
src/main.cpp
src/main.cpp
#include "slk.h" #include "txt.h" #include "ini.h" #include "tonumber.h" #include "mdxopt.h" #include "real.h" namespace w3x { static bool is_string(std::string_view& s) { bool r = false; if (!s.empty() && s.front() == '"') { s.remove_prefix(1); r = true; } if (!s.empty() && s.back() == '"') { s.remove_suffix(1); r = true; } return r; } int parse_slk(lua_State* L) { slk l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } for (size_t y = 0; y < l.maxy; ++y) { is_string(l.col[y]); } lua_createtable(L, 0, l.maxy); for (size_t y = 1; y < l.maxy; ++y) { if (l.col[y].empty()) { continue; } lua_pushlstring(L, l.col[y].data(), l.col[y].size()); lua_createtable(L, 0, l.maxx); for (size_t x = 1; x < l.maxx; ++x) { if (l.row[x].empty()) { continue; } lua_pushlstring(L, l.row[x].data(), l.row[x].size()); auto& data = l.data[x][y]; if (is_string(data)) { lua_pushlstring(L, data.data(), data.size()); } else if (!data.empty()) { lua_pushlstring(L, data.data(), data.size()); if (!lua_stringtonumber(L, lua_tostring(L, -1))) { lua_pushinteger(L, 0); } lua_remove(L, -2); } else { lua_pushnil(L); } lua_rawset(L, -3); } lua_rawset(L, -3); } return 1; } int parse_txt(lua_State* L) { txt l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (lua_gettop(L) < 3) { lua_newtable(L); } if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } return 1; } int parse_ini(lua_State* L) { ini l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } return 1; } int tonumber(lua_State* L) { number l(L, luaL_checkstring(L, 1)); l.parse(); return 1; } int mdxopt(lua_State* L) { size_t len = 0; const char* buf = luaL_checklstring(L, 1, &len); char* newbuf = (char*)lua_newuserdata(L, len); memcpy(newbuf, buf, len); mdx::opt(newbuf, len); lua_pushlstring(L, newbuf, len); return 1; } float str2float(const char* z) { for (bool ok = false; !ok;) { switch (*z) { case '\0': case '\n': case '\r': return 0.f; case '\t': case ' ': z++; break; default: ok = true; break; } } errno = 0; float f = strtof(z, NULL); if (errno == ERANGE && (f == HUGE_VALF || f == -HUGE_VALF)) { return 0.f; } return f; } int float2bin(lua_State* L) { size_t len = 0; const char* str = luaL_checklstring(L, 1, &len); char tmp[64] = { 0 }; if (len > 63) len = 63; memcpy(tmp, str, len); float f = str2float(tmp); real_t r = to_real(f); lua_pushlstring(L, (char*)&r, 4); return 1; } int bin2float(lua_State* L) { size_t len = 0; const char* str = luaL_checklstring(L, 1, &len); if (len != 4) { return luaL_error(L, "float bin size must be 4."); } float f = from_real(*(real_t*)str); char tmp[64]; int tmplen = sprintf_s(tmp, "%f", f); while (tmplen > 0 && tmp[tmplen - 1] == '0') { tmplen--; } lua_pushlstring(L, tmp, tmplen); return 1; } } extern "C" __declspec(dllexport) int luaopen_w3xparser(lua_State* L) { static luaL_Reg l[] = { { "slk", w3x::parse_slk }, { "txt", w3x::parse_txt }, { "ini", w3x::parse_ini }, { "tonumber", w3x::tonumber }, { "mdxopt", w3x::mdxopt }, { "float2bin", w3x::float2bin }, { "bin2float", w3x::bin2float }, { NULL, NULL }, }; luaL_newlib(L, l); return 1; }
#include "slk.h" #include "txt.h" #include "ini.h" #include "tonumber.h" #include "mdxopt.h" #include "real.h" namespace w3x { static bool is_string(std::string_view& s) { bool r = false; if (!s.empty() && s.front() == '"') { s.remove_prefix(1); r = true; } if (!s.empty() && s.back() == '"') { s.remove_suffix(1); r = true; } return r; } int parse_slk(lua_State* L) { slk l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } for (size_t y = 0; y < l.maxy; ++y) { is_string(l.col[y]); } lua_createtable(L, 0, l.maxy); for (size_t y = 1; y < l.maxy; ++y) { if (l.col[y].empty()) { continue; } lua_pushlstring(L, l.col[y].data(), l.col[y].size()); lua_createtable(L, 0, l.maxx); for (size_t x = 1; x < l.maxx; ++x) { if (l.row[x].empty()) { continue; } lua_pushlstring(L, l.row[x].data(), l.row[x].size()); auto& data = l.data[x][y]; if (!data.empty()) { lua_pushlstring(L, data.data(), data.size()); } else { lua_pushnil(L); } lua_rawset(L, -3); } lua_rawset(L, -3); } return 1; } int parse_txt(lua_State* L) { txt l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (lua_gettop(L) < 3) { lua_newtable(L); } if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } return 1; } int parse_ini(lua_State* L) { ini l(L, luaL_checkstring(L, 1)); const char* file = luaL_optstring(L, 2, "..."); if (!l.parse()) { return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1)); } return 1; } int tonumber(lua_State* L) { number l(L, luaL_checkstring(L, 1)); l.parse(); return 1; } int mdxopt(lua_State* L) { size_t len = 0; const char* buf = luaL_checklstring(L, 1, &len); char* newbuf = (char*)lua_newuserdata(L, len); memcpy(newbuf, buf, len); mdx::opt(newbuf, len); lua_pushlstring(L, newbuf, len); return 1; } float str2float(const char* z) { for (bool ok = false; !ok;) { switch (*z) { case '\0': case '\n': case '\r': return 0.f; case '\t': case ' ': z++; break; default: ok = true; break; } } errno = 0; float f = strtof(z, NULL); if (errno == ERANGE && (f == HUGE_VALF || f == -HUGE_VALF)) { return 0.f; } return f; } int float2bin(lua_State* L) { size_t len = 0; const char* str = luaL_checklstring(L, 1, &len); char tmp[64] = { 0 }; if (len > 63) len = 63; memcpy(tmp, str, len); float f = str2float(tmp); real_t r = to_real(f); lua_pushlstring(L, (char*)&r, 4); return 1; } int bin2float(lua_State* L) { size_t len = 0; const char* str = luaL_checklstring(L, 1, &len); if (len != 4) { return luaL_error(L, "float bin size must be 4."); } float f = from_real(*(real_t*)str); char tmp[64]; int tmplen = sprintf_s(tmp, "%f", f); while (tmplen > 0 && tmp[tmplen - 1] == '0') { tmplen--; } lua_pushlstring(L, tmp, tmplen); return 1; } } extern "C" __declspec(dllexport) int luaopen_w3xparser(lua_State* L) { static luaL_Reg l[] = { { "slk", w3x::parse_slk }, { "txt", w3x::parse_txt }, { "ini", w3x::parse_ini }, { "tonumber", w3x::tonumber }, { "mdxopt", w3x::mdxopt }, { "float2bin", w3x::float2bin }, { "bin2float", w3x::bin2float }, { NULL, NULL }, }; luaL_newlib(L, l); return 1; }
Update main.cpp
Update main.cpp
C++
apache-2.0
actboy168/w3xparser,actboy168/w3xparser
05183c2de0078d493ffde531ac3fb7f53e2df621
src/main.cpp
src/main.cpp
// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <time.h> #include <semaphore.h> #include <algorithm> #include <math.h> #include <sqlite3.h> #include <assert.h> #include <set> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> #include "clangomp.h" #include "States.h" #include "System.h" #include "Utilities.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; void simulate_and_print(Constants constants, int iterations, OutputType type, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations") ("help","Show help message") ("verbose,v", "Show extensive debugging info") ("output,o", opt::value<int>(), "Output style.") ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; /*! The delta used here is NOT, at this point, the delta used in the paper. This is the ratio of ones to zeroes in the bit stream. Probably worth changing the name, but calculating this at runtime is just an invitation for bugs. */ constants.delta = .5; constants.epsilon = .7; constants.tau = 1; int dimension = 50; #pragma omp parallel for private(constants) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); simulate_and_print(constants, iterations, output_style,verbose); } } void simulate_and_print(Constants constants, int iterations, OutputType type, bool verbose) { /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(); currentSystem->constants = constants; currentSystem->nbits = BIT_STREAM_LENGTH; evolveSystem(currentSystem, localRNG); histogram[currentSystem->endingBitString]++; delete currentSystem; } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(); currentSystem->constants = constants; currentSystem->nbits = BIT_STREAM_LENGTH; evolveSystem(currentSystem, localRNG); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; } delete [] p_prime; delete [] p; #pragma omp critical { if(type==CommaSeparated) { static int once = 0; if (!once) { std::cout<<"delta,epsilon,avg,max_surprise\n"; once=1; } std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl; } if(type==PrettyPrint) { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } if (type==Mathematica) { assert(0); } } gsl_rng_free(localRNG); }
// // main.cpp // thermaleraser // // Created by Mark Larus on 9/8/12. // Copyright (c) 2012 Kenyon College. All rights reserved. // #include <iostream> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf.h> #include <time.h> #include <semaphore.h> #include <algorithm> #include <math.h> #include <sqlite3.h> #include <assert.h> #include <set> #include <boost/program_options.hpp> #include <boost/timer/timer.hpp> #define timer timer_class #include <boost/progress.hpp> #undef timer #include "clangomp.h" #include "States.h" #include "System.h" #include "Utilities.h" #define print(x) std::cout<<#x <<": " <<x<<std::endl; namespace opt = boost::program_options; enum OutputType { CommaSeparated, PrettyPrint, Mathematica, NoOutput }; void simulate_and_print(Constants constants, int iterations, OutputType type, bool verbose = false); int main(int argc, char * argv[]) { /*! Initialize options list. */ bool verbose = false; const int default_iterations = 1<<16; opt::options_description desc("Allowed options"); desc.add_options() ("iterations,n",opt::value<int>(), "Number of iterations") ("help","Show help message") ("verbose,v", "Show extensive debugging info") ("output,o", opt::value<int>(), "Output style.") ("benchmark", "Test evaluation speed") ; opt::variables_map vmap; opt::store(opt::parse_command_line(argc,argv,desc),vmap); opt::notify(vmap); if (vmap.count("help")) { std::cout << desc << "\n"; return 1; } verbose = vmap.count("verbose"); int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations; if (verbose) { print(iterations); #pragma omp parallel #pragma omp single print(omp_get_num_threads()); } OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated; /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is represented by an object with pointers to the next states and the bit-flip states. */ setupStates(); Constants constants; /*! The delta used here is NOT, at this point, the delta used in the paper. This is the ratio of ones to zeroes in the bit stream. Probably worth changing the name, but calculating this at runtime is just an invitation for bugs. */ constants.delta = .5; constants.epsilon = .7; constants.tau = 1; int dimension = 50; if(vmap.count("benchmark")) { std::cout<<"Benchmarking speed.\n"; int benchmark_size = 1000; boost::timer::cpu_timer timer; boost::progress_display display(benchmark_size); timer.start(); int tickmarks; #pragma omp parallel for private(constants) for (int k=0; k<benchmark_size; k++) { simulate_and_print(constants,iterations,NoOutput,false); ++display; } timer.stop(); double speed_factor; double time_elapsed = timer.elapsed().wall; print(benchmark_size); print(timer.format(3,"%ws")); print(benchmark_size/time_elapsed); exit(0); } #pragma omp parallel for private(constants) for (int k=dimension*dimension; k>=0; k--) { constants.epsilon = (k % dimension)/(double)(dimension); constants.delta = .5 + .5*(k / dimension)/(double)(dimension); simulate_and_print(constants, iterations, output_style,verbose); } } void simulate_and_print(Constants constants, int iterations, OutputType type, bool verbose) { /*! Use this to change the length of the tape. */ const int BIT_STREAM_LENGTH = 8; int first_pass_iterations = iterations; int *histogram = new int[1<<BIT_STREAM_LENGTH]; std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0); long double *p = new long double[1<<BIT_STREAM_LENGTH]; long double *p_prime = new long double[1<<BIT_STREAM_LENGTH]; long double sum = 0; const long double beta = log((1+constants.epsilon)/(1-constants.epsilon)); long double max_surprise = 0; long double min_surprise = LONG_MAX; gsl_rng *localRNG = GSLRandomNumberGenerator(); for (int k=0; k<first_pass_iterations; ++k) { System *currentSystem = new System(); currentSystem->constants = constants; currentSystem->nbits = BIT_STREAM_LENGTH; evolveSystem(currentSystem, localRNG); histogram[currentSystem->endingBitString]++; delete currentSystem; } for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) { int setBits = bitCount(k,BIT_STREAM_LENGTH); p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits); p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations); } delete [] histogram; for(int k=0; k<iterations; k++) { System *currentSystem = new System(); currentSystem->constants = constants; currentSystem->nbits = BIT_STREAM_LENGTH; evolveSystem(currentSystem, localRNG); long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString]; max_surprise = surprise > max_surprise ? surprise : max_surprise; min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise; sum = sum + surprise; delete currentSystem; } delete [] p_prime; delete [] p; #pragma omp critical { if(type==CommaSeparated) { static int once = 0; if (!once) { std::cout<<"delta,epsilon,avg,max_surprise\n"; once=1; } std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl; } if(type==PrettyPrint) { print(beta); print(constants.delta); print(constants.epsilon); print(sum/iterations); print(max_surprise); print(sum); std::cout<<std::endl; } if (type==Mathematica) { assert(0); } } gsl_rng_free(localRNG); }
Add --benchmark flag
Add --benchmark flag
C++
mit
marblar/demon,marblar/demon,marblar/demon,marblar/demon
f32e9a7bb4b121a03ee0c8e900682db876252357
src/test.cpp
src/test.cpp
/* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <iostream> #include <string> #include <vector> #include <regex> #include <assert.h> #include "column_types.h" #include "redis.h" #include "md5.h" #include "index.h" #define REDISHOST "127.0.0.1" #define REDISPORT 6379 using namespace std; /** Test to ensure that redis keys are correctly returned */ void testRedisSet() { RedisHandler r; r.connect(); r.write("foo", "bar"); } /** Test to ensure that redis keys are correctly returned */ void testRedisGet() { RedisHandler r; r.connect(); cout << endl << "VALUE FOR KEY foo" << endl; cout << r.read("foo") << endl << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisKeys() { RedisHandler r; std::vector<std::string> vec; r.connect(); vec = r.keys("*"); cout << "KEY LIST FOR *" << endl; for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) { cout << *it << endl; } cout << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisIO() { RedisHandler r; std::vector<string>* vec; std::string outTrue, outFalse = ""; r.connect(); r.write("test_key", "test value"); outTrue = r.read("test_key"); assert(std::strcmp(outTrue.c_str(), "test value") == 0); r.deleteKey("test_key"); assert(!r.exists("test_key")); } /** Test to ensure that md5 hashing works */ void testMd5Hashing() { cout << endl << "md5 of 'mykey': " << md5("mykey") << endl; } /** Test to ensure that md5 hashing works */ void testRegexForTypes() { IntegerColumn ic; FloatColumn fc; assert(ic.validate("1981")); assert(fc.validate("5.2")); cout << "Passed regex tests." << endl; } /** Test to ensure that md5 hashing works */ void testOrderPairAlphaNumeric() { IndexHandler ih; assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0); cout << "Passed orderPairAlphaNumeric tests." << endl; } /** * Test to ensure that relation entities are encoded properly */ void testJSONEntityEncoding() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent = new vector<std::pair<ColumnBase*, std::string>>; fields_ent->push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields ih.writeEntity("test", fields_ent); // Create the entity ih.fetchEntity("test", json); // Fetch the entity representation cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl; // Assert that entity as read matches definition assert(std::strcmp(json["entity"].asCString(), "test") == 0 && std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 && json["fields"]["fields_count"].asInt() == 1 ); ih.removeEntity("test"); // Remove the entity } /** * Test to ensure that relation fields are encoded properly */ void testJSONRelationEncoding() { IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_1 = new vector<std::pair<ColumnBase*, std::string>>; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_2 = new vector<std::pair<ColumnBase*, std::string>>; std::vector<std::pair<std::string, std::string>>* fields_rel_1 = new vector<std::pair<std::string, std::string>>; std::vector<std::pair<std::string, std::string>>* fields_rel_2 = new vector<std::pair<std::string, std::string>>; // Popualate fields fields_ent_1->push_back(std::make_pair(getColumnType("integer"), "a")); fields_ent_2->push_back(std::make_pair(getColumnType("string"), "b")); fields_rel_1->push_back(std::make_pair("a", "1")); fields_rel_2->push_back(std::make_pair("b", "hello")); // Create entities ih.writeEntity("test_1", fields_ent_1); ih.writeEntity("test_2", fields_ent_1); // Create relation in redis ih.writeRelation("test_1", "test_2", fields_rel_1, fields_rel_2); // Fetch the entity representation ret = ih.fetchRelationPrefix("test_1", "test_2"); cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl; // Assert that entity as read matches definition assert( std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 && std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 && std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 && std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 && ret[0]["fields_left"]["fields_count"].asInt() == 1 && ret[0]["fields_right"]["fields_count"].asInt() == 1 ); ih.removeEntity("test_1"); // Remove the entity ih.removeEntity("test_2"); // Remove the entity ih.removeRelation("test_1", "test_2", fields_rel_1, fields_rel_2); // Remove the relation } int main() { cout << "-- TESTS BEGIN --" << endl << endl; // testRedisSet(); // testRedisGet(); // testRedisKeys(); // md5Hashing(); // testRedisIO(); // testRegexForTypes(); // testOrderPairAlphaNumeric(); testJSONEntityEncoding(); testJSONRelationEncoding(); cout << endl << "-- TESTS END --" << endl; return 0; }
/* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <iostream> #include <string> #include <vector> #include <regex> #include <assert.h> #include "column_types.h" #include "redis.h" #include "md5.h" #include "index.h" #define REDISHOST "127.0.0.1" #define REDISPORT 6379 using namespace std; /** Test to ensure that redis keys are correctly returned */ void testRedisSet() { RedisHandler r; r.connect(); r.write("foo", "bar"); } /** Test to ensure that redis keys are correctly returned */ void testRedisGet() { RedisHandler r; r.connect(); cout << endl << "VALUE FOR KEY foo" << endl; cout << r.read("foo") << endl << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisKeys() { RedisHandler r; std::vector<std::string> vec; r.connect(); vec = r.keys("*"); cout << "KEY LIST FOR *" << endl; for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) { cout << *it << endl; } cout << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisIO() { RedisHandler r; std::vector<string>* vec; std::string outTrue, outFalse = ""; r.connect(); r.write("test_key", "test value"); outTrue = r.read("test_key"); assert(std::strcmp(outTrue.c_str(), "test value") == 0); r.deleteKey("test_key"); assert(!r.exists("test_key")); } /** Test to ensure that md5 hashing works */ void testMd5Hashing() { cout << endl << "md5 of 'mykey': " << md5("mykey") << endl; } /** Test to ensure that md5 hashing works */ void testRegexForTypes() { IntegerColumn ic; FloatColumn fc; assert(ic.validate("1981")); assert(fc.validate("5.2")); cout << "Passed regex tests." << endl; } /** Test to ensure that md5 hashing works */ void testOrderPairAlphaNumeric() { IndexHandler ih; assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0); cout << "Passed orderPairAlphaNumeric tests." << endl; } /** * Test to ensure that relation entities are encoded properly */ void testJSONEntityEncoding() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent = new vector<std::pair<ColumnBase*, std::string>>; fields_ent->push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields ih.writeEntity("test", fields_ent); // Create the entity ih.fetchEntity("test", json); // Fetch the entity representation cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl; // Assert that entity as read matches definition assert(std::strcmp(json["entity"].asCString(), "test") == 0 && std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 && json["fields"]["fields_count"].asInt() == 1 ); ih.removeEntity("test"); // Remove the entity } /** * Test to ensure that relation fields are encoded properly */ void testJSONRelationEncoding() { IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_1 = new vector<std::pair<ColumnBase*, std::string>>; std::vector<std::pair<ColumnBase*, std::string>>* fields_ent_2 = new vector<std::pair<ColumnBase*, std::string>>; std::vector<std::pair<std::string, std::string>>* fields_rel_1 = new vector<std::pair<std::string, std::string>>; std::vector<std::pair<std::string, std::string>>* fields_rel_2 = new vector<std::pair<std::string, std::string>>; // Popualate fields fields_ent_1->push_back(std::make_pair(getColumnType("integer"), "a")); fields_ent_2->push_back(std::make_pair(getColumnType("string"), "b")); fields_rel_1->push_back(std::make_pair("a", "1")); fields_rel_2->push_back(std::make_pair("b", "hello")); // Create entities ih.writeEntity("test_1", fields_ent_1); ih.writeEntity("test_2", fields_ent_1); // Create relation in redis ih.writeRelation("test_1", "test_2", fields_rel_1, fields_rel_2); // Fetch the entity representation ret = ih.fetchRelationPrefix("test_1", "test_2"); cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl; // Assert that entity as read matches definition assert( std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 && std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 && std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 && std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 && ret[0]["fields_left"]["fields_count"].asInt() == 1 && ret[0]["fields_right"]["fields_count"].asInt() == 1 ); ih.removeEntity("test_1"); // Remove the entity ih.removeEntity("test_2"); // Remove the entity ih.removeRelation("test_1", "test_2", fields_rel_1, fields_rel_2); // Remove the relation } /** * Tests that parseEntityAssignField correctly flags invalid assignments to integer fields */ void testFieldAssignTypeMismatchInteger() { // TODO - implement } /** * Tests that parseEntityAssignField correctly flags invalid assignments to float fields */ void testFieldAssignTypeMismatchFloat() { // TODO - implement } /** * Tests that parseEntityAssignField correctly flags invalid assignments to string fields */ void testFieldAssignTypeMismatchString() { // TODO - implement } int main() { cout << "-- TESTS BEGIN --" << endl << endl; // testRedisSet(); // testRedisGet(); // testRedisKeys(); // md5Hashing(); // testRedisIO(); // testRegexForTypes(); // testOrderPairAlphaNumeric(); testJSONEntityEncoding(); testJSONRelationEncoding(); cout << endl << "-- TESTS END --" << endl; return 0; }
test stubs for field assignment type mismatches
test stubs for field assignment type mismatches
C++
apache-2.0
rfaulkner/databayes,rfaulkner/databayes,rfaulkner/databayes,rfaulkner/databayes,rfaulkner/databayes
02bddef3bd889b08d291797c47208640138f7635
Sprite.cpp
Sprite.cpp
#include "Sprite.h" Sprite::Sprite() : Node() { // Image m_sprite_path = ""; // Collision Body m_body = new Body; } Sprite::Sprite(std::string p_sprite_path) : Sprite() { // Image m_sprite_path = p_sprite_path; } Sprite::~Sprite() {} void Sprite::setPosition(Vec2<double> p_position) { Node::setPosition(p_position); std::vector<Vec2<double> >::iterator it = m_body->start(); for(;it != m_body->end(); it++) { if((*it).x > m_body->getCenter().x) (*it).x -= m_body->getCenter().x; else (*it).x = m_body->getCenter().x - (*it).x; if((*it).y > m_body->getCenter().y) (*it).y -= m_body->getCenter().y; else (*it).y = m_body->getCenter().y - (*it).y; (*it) = (*it) + p_position; } m_body->calculateCenter(); } void Sprite::moveBy(Vec2<double> p_mov) { Node::moveBy(p_mov); std::vector<Vec2<double> >::iterator it = m_body->start(); for(;it != m_body->end(); it++) (*it) += p_mov; m_body->calculateCenter(); } std::string Sprite::getSpritePath() { return m_sprite_path; } void Sprite::setCollisionBody(Body* p_body) { m_body = p_body; } Body* Sprite::getCollisionBody() { return m_body; } bool Sprite::inRangeWith(Sprite* that) { return m_body->inRangeWith(that->getCollisionBody()); } bool Sprite::collidesWith(Sprite* that) { return this->collidesWith(that); }
#include "Sprite.h" Sprite::Sprite() : Node() { // Image m_sprite_path = ""; // Collision Body m_body = new Body; } Sprite::Sprite(std::string p_sprite_path) : Sprite() { // Image m_sprite_path = p_sprite_path; } Sprite::~Sprite() {} void Sprite::setPosition(Vec2<double> p_position) { Node::setPosition(p_position); std::vector<Vec2<double> >::iterator it = m_body->start(); for(;it != m_body->end(); it++) { if((*it).x > m_body->getCenter().x) (*it).x -= m_body->getCenter().x; else (*it).x = m_body->getCenter().x - (*it).x; if((*it).y > m_body->getCenter().y) (*it).y -= m_body->getCenter().y; else (*it).y = m_body->getCenter().y - (*it).y; (*it) = (*it) + p_position; } m_body->calculateCenter(); } void Sprite::moveBy(Vec2<double> p_mov) { Node::moveBy(p_mov); std::vector<Vec2<double> >::iterator it = m_body->start(); for(;it != m_body->end(); it++) (*it) += p_mov; m_body->calculateCenter(); } std::string Sprite::getSpritePath() { return m_sprite_path; } void Sprite::setCollisionBody(Body* p_body) { m_body = p_body; } Body* Sprite::getCollisionBody() { return m_body; } bool Sprite::inRangeWith(Sprite* that) { return m_body->inRangeWith(that->getCollisionBody()); } bool Sprite::collidesWith(Sprite* that) { return this->m_body->collidesWith(that->m_body); }
Remove infinite loop from collides_with(Sprite*)
Remove infinite loop from collides_with(Sprite*)
C++
mit
maksym-gryb/SDL_Wrapper,maksym-gryb/SDL_Wrapper
de3f454c27c4598961583b2ac86b67a159478ee6
editor/plugins/skeleton_2d_editor_plugin.cpp
editor/plugins/skeleton_2d_editor_plugin.cpp
/*************************************************************************/ /* skeleton_2d_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "skeleton_2d_editor_plugin.h" #include "canvas_item_editor_plugin.h" #include "scene/2d/mesh_instance_2d.h" #include "scene/gui/box_container.h" #include "thirdparty/misc/clipper.hpp" void Skeleton2DEditor::_node_removed(Node *p_node) { if (p_node == node) { node = nullptr; options->hide(); } } void Skeleton2DEditor::edit(Skeleton2D *p_sprite) { node = p_sprite; } void Skeleton2DEditor::_menu_option(int p_option) { if (!node) { return; } switch (p_option) { case MENU_OPTION_MAKE_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered_minsize(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Create Rest Pose from Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_rest", bone->get_transform()); ur->add_undo_method(bone, "set_rest", bone->get_rest()); } ur->commit_action(); } break; case MENU_OPTION_SET_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered_minsize(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Set Rest Pose to Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_transform", bone->get_rest()); ur->add_undo_method(bone, "set_transform", bone->get_transform()); } ur->commit_action(); } break; } } void Skeleton2DEditor::_bind_methods() { ClassDB::bind_method("_menu_option", &Skeleton2DEditor::_menu_option); } Skeleton2DEditor::Skeleton2DEditor() { options = memnew(MenuButton); CanvasItemEditor::get_singleton()->add_control_to_menu_panel(options); options->set_text(TTR("Skeleton2D")); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Skeleton2D", "EditorIcons")); options->get_popup()->add_item(TTR("Make Rest Pose (From Bones)"), MENU_OPTION_MAKE_REST); options->get_popup()->add_separator(); options->get_popup()->add_item(TTR("Set Bones to Rest Pose"), MENU_OPTION_SET_REST); options->set_switch_on_hover(true); options->get_popup()->connect("id_pressed", this, "_menu_option"); err_dialog = memnew(AcceptDialog); add_child(err_dialog); } void Skeleton2DEditorPlugin::edit(Object *p_object) { sprite_editor->edit(Object::cast_to<Skeleton2D>(p_object)); } bool Skeleton2DEditorPlugin::handles(Object *p_object) const { return p_object->is_class("Skeleton2D"); } void Skeleton2DEditorPlugin::make_visible(bool p_visible) { if (p_visible) { sprite_editor->options->show(); } else { sprite_editor->options->hide(); sprite_editor->edit(nullptr); } } Skeleton2DEditorPlugin::Skeleton2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Skeleton2DEditor); editor->get_viewport()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); } Skeleton2DEditorPlugin::~Skeleton2DEditorPlugin() { }
/*************************************************************************/ /* skeleton_2d_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "skeleton_2d_editor_plugin.h" #include "canvas_item_editor_plugin.h" #include "scene/2d/mesh_instance_2d.h" #include "scene/gui/box_container.h" #include "thirdparty/misc/clipper.hpp" void Skeleton2DEditor::_node_removed(Node *p_node) { if (p_node == node) { node = nullptr; options->hide(); } } void Skeleton2DEditor::edit(Skeleton2D *p_sprite) { node = p_sprite; } void Skeleton2DEditor::_menu_option(int p_option) { if (!node) { return; } switch (p_option) { case MENU_OPTION_MAKE_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered_minsize(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Create Rest Pose from Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_rest", bone->get_transform()); ur->add_undo_method(bone, "set_rest", bone->get_rest()); } ur->commit_action(); } break; case MENU_OPTION_SET_REST: { if (node->get_bone_count() == 0) { err_dialog->set_text(TTR("This skeleton has no bones, create some children Bone2D nodes.")); err_dialog->popup_centered_minsize(); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Set Rest Pose to Bones")); for (int i = 0; i < node->get_bone_count(); i++) { Bone2D *bone = node->get_bone(i); ur->add_do_method(bone, "set_transform", bone->get_rest()); ur->add_undo_method(bone, "set_transform", bone->get_transform()); } ur->commit_action(); } break; } } void Skeleton2DEditor::_bind_methods() { ClassDB::bind_method("_menu_option", &Skeleton2DEditor::_menu_option); } Skeleton2DEditor::Skeleton2DEditor() { options = memnew(MenuButton); CanvasItemEditor::get_singleton()->add_control_to_menu_panel(options); options->set_text(TTR("Skeleton2D")); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("Skeleton2D", "EditorIcons")); options->get_popup()->add_item(TTR("Reset to Rest Pose"), MENU_OPTION_MAKE_REST); options->get_popup()->add_separator(); // Use the "Overwrite" word to highlight that this is a destructive operation. options->get_popup()->add_item(TTR("Overwrite Rest Pose"), MENU_OPTION_SET_REST); options->set_switch_on_hover(true); options->get_popup()->connect("id_pressed", this, "_menu_option"); err_dialog = memnew(AcceptDialog); add_child(err_dialog); } void Skeleton2DEditorPlugin::edit(Object *p_object) { sprite_editor->edit(Object::cast_to<Skeleton2D>(p_object)); } bool Skeleton2DEditorPlugin::handles(Object *p_object) const { return p_object->is_class("Skeleton2D"); } void Skeleton2DEditorPlugin::make_visible(bool p_visible) { if (p_visible) { sprite_editor->options->show(); } else { sprite_editor->options->hide(); sprite_editor->edit(nullptr); } } Skeleton2DEditorPlugin::Skeleton2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Skeleton2DEditor); editor->get_viewport()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); } Skeleton2DEditorPlugin::~Skeleton2DEditorPlugin() { }
Tweak skeleton editor texts "Make Rest Pose" and "Set Bones to Rest Pose"
Tweak skeleton editor texts "Make Rest Pose" and "Set Bones to Rest Pose" The new terms are more descriptive of each button's actual function. (cherry picked from commit 16cfb97ca20ae04dc1d3a87dcc24cec5bb38266c)
C++
mit
ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot,ex/godot
c9abaaa923ea2a92fb504dbc3c7f32fef4020387
vm/llvm/inline.hpp
vm/llvm/inline.hpp
#include "llvm/jit_operations.hpp" #include "llvm/access_memory.hpp" #include "builtin/access_variable.hpp" #include "builtin/iseq.hpp" namespace rubinius { class Inliner { JITOperations& ops_; InlineCache* cache_; int count_; BasicBlock* after_; public: Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after) : ops_(ops) , cache_(cache) , count_(count) , after_(after) {} Value* recv() { return ops_.stack_back(count_); } Value* arg(int which) { return ops_.stack_back(count_ - which); } void consider() { executor callee = cache_->method->execute; if(callee == Primitives::tuple_at && count_ == 1) { call_tuple_at(); } else if(callee == Primitives::tuple_put && count_ == 2) { call_tuple_put(); // If the cache has only ever had one class, inline! } else if(cache_->classes_seen() == 1) { AccessManagedMemory memguard(ops_.state()); Executable* meth = cache_->method; if(AccessVariable* acc = try_as<AccessVariable>(meth)) { if(acc->write()->true_p()) { inline_ivar_write(cache_->tracked_class(0), acc); } else { inline_ivar_access(cache_->tracked_class(0), acc); } } else if(CompiledMethod* cm = try_as<CompiledMethod>(meth)) { if(detect_trivial_method(cm->backend_method_)) { inline_trivial_method(cache_->tracked_class(0), cm); } } } } bool detect_trivial_method(VMMethod* vmm) { opcode* stream = vmm->opcodes; size_t size_max = 2; if(stream[0] == InstructionSequence::insn_push_int) { size_max++; } else { return false; } if(vmm->total == size_max && count_ == 0 && vmm->required_args == vmm->total_args && vmm->total_args == 0) return true; return false; } void inline_trivial_method(Class* klass, CompiledMethod* cm) { cm->add_inliner(ops_.vmmethod()); VMMethod* vmm = cm->backend_method_; Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); Value* val = 0; ///// if(vmm->opcodes[0] == InstructionSequence::insn_push_int) { val = ops_.constant(Fixnum::from(vmm->opcodes[1])); } ///// assert(val); ops_.stack_set_top(val); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void inline_ivar_write(Class* klass, AccessVariable* acc) { if(count_ != 1) return; /* std::cout << "Inlining writer to '" << ops_.state()->symbol_cstr(acc->name()) << "' on " << ops_.state()->symbol_cstr(klass->name()) << " in " << "#" << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name()) << "\n"; */ acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* val = ops_.stack_top(); Value* self = ops_.stack_back(1); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ops_.set_object_slot(self, offset, val); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), self, ops_.constant(acc->name()), val }; sig2.call("rbx_set_table_ivar", call_args2, 4, "ivar", ops_.current_block()); } ops_.stack_remove(1); ops_.stack_set_top(val); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void inline_ivar_access(Class* klass, AccessVariable* acc) { if(count_ != 0) return; /* std::cout << "Inlining accessor to '" << ops_.state()->symbol_cstr(acc->name()) << "' on " << ops_.state()->symbol_cstr(klass->name()) << " in " << "#" << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name()) << "\n"; */ acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); Value* ivar = 0; if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ivar = ops_.get_object_slot(self, offset); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), self, ops_.constant(acc->name()) }; ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar", ops_.current_block()); } ops_.stack_set_top(ivar); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void call_tuple_at() { Value* rec = recv(); // bool is_tuple = recv->flags & mask; Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_at"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); // Check that index is not over the end of the Tuple Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); ops_.stack_remove(2); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.stack_push(ops_.create_load(gep, "tuple_at")); ops_.create_branch(after_); ops_.set_block(is_other); } void call_tuple_put() { Value* rec = recv(); Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_put"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); Value* value = arg(1); ops_.stack_remove(3); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.create_store(value, gep); ops_.write_barrier(tup, value); ops_.stack_push(value); ops_.create_branch(after_); ops_.set_block(is_other); } }; }
#include "llvm/jit_operations.hpp" #include "llvm/access_memory.hpp" #include "builtin/access_variable.hpp" #include "builtin/iseq.hpp" namespace rubinius { class Inliner { JITOperations& ops_; InlineCache* cache_; int count_; BasicBlock* after_; public: Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after) : ops_(ops) , cache_(cache) , count_(count) , after_(after) {} Value* recv() { return ops_.stack_back(count_); } Value* arg(int which) { return ops_.stack_back(count_ - which); } void consider() { executor callee = cache_->method->execute; if(callee == Primitives::tuple_at && count_ == 1) { call_tuple_at(); } else if(callee == Primitives::tuple_put && count_ == 2) { call_tuple_put(); // If the cache has only ever had one class, inline! } else if(cache_->classes_seen() == 1) { AccessManagedMemory memguard(ops_.state()); Executable* meth = cache_->method; if(AccessVariable* acc = try_as<AccessVariable>(meth)) { if(acc->write()->true_p()) { inline_ivar_write(cache_->tracked_class(0), acc); } else { inline_ivar_access(cache_->tracked_class(0), acc); } } else if(CompiledMethod* cm = try_as<CompiledMethod>(meth)) { if(detect_trivial_method(cm)) { inline_trivial_method(cache_->tracked_class(0), cm); } } } } bool detect_trivial_method(CompiledMethod* cm) { VMMethod* vmm = cm->backend_method_; opcode* stream = vmm->opcodes; size_t size_max = 2; if(stream[0] == InstructionSequence::insn_push_int) { size_max++; } else if(stream[0] == InstructionSequence::insn_push_literal) { if(kind_of<Symbol>(cm->literals()->at(stream[1]))) { size_max++; } else { return false; } } else { return false; } if(vmm->total == size_max && count_ == 0 && vmm->required_args == vmm->total_args && vmm->total_args == 0) return true; return false; } void inline_trivial_method(Class* klass, CompiledMethod* cm) { cm->add_inliner(ops_.vmmethod()); VMMethod* vmm = cm->backend_method_; Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); Value* val = 0; ///// opcode* stream = vmm->opcodes; if(stream[0] == InstructionSequence::insn_push_int) { val = ops_.constant(Fixnum::from(stream[1])); } else if(stream[0] == InstructionSequence::insn_push_literal) { Symbol* sym = try_as<Symbol>(cm->literals()->at(stream[1])); assert(sym); val = ops_.constant(sym); } else { assert(0 && "Trivial detection is broken!"); } ///// assert(val); ops_.stack_set_top(val); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void inline_ivar_write(Class* klass, AccessVariable* acc) { if(count_ != 1) return; /* std::cout << "Inlining writer to '" << ops_.state()->symbol_cstr(acc->name()) << "' on " << ops_.state()->symbol_cstr(klass->name()) << " in " << "#" << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name()) << "\n"; */ acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* val = ops_.stack_top(); Value* self = ops_.stack_back(1); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ops_.set_object_slot(self, offset, val); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), self, ops_.constant(acc->name()), val }; sig2.call("rbx_set_table_ivar", call_args2, 4, "ivar", ops_.current_block()); } ops_.stack_remove(1); ops_.stack_set_top(val); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void inline_ivar_access(Class* klass, AccessVariable* acc) { if(count_ != 0) return; /* std::cout << "Inlining accessor to '" << ops_.state()->symbol_cstr(acc->name()) << "' on " << ops_.state()->symbol_cstr(klass->name()) << " in " << "#" << ops_.state()->symbol_cstr(ops_.vmmethod()->original->name()) << "\n"; */ acc->add_inliner(ops_.vmmethod()); ops_.state()->add_accessor_inlined(); Value* self = ops_.stack_top(); BasicBlock* use_send = ops_.new_block("use_send"); ops_.check_reference_class(self, klass->class_id(), use_send); // Figure out if we should use the table ivar lookup or // the slot ivar lookup. TypeInfo* ti = klass->type_info(); TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index()); Value* ivar = 0; if(it != ti->slots.end()) { int offset = ti->slot_locations[it->second]; ivar = ops_.get_object_slot(self, offset); } else { Signature sig2(ops_.state(), "Object"); sig2 << "VM"; sig2 << "Object"; sig2 << "Object"; Value* call_args2[] = { ops_.vm(), self, ops_.constant(acc->name()) }; ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar", ops_.current_block()); } ops_.stack_set_top(ivar); ops_.create_branch(after_); ops_.set_block(use_send); after_->moveAfter(use_send); } void call_tuple_at() { Value* rec = recv(); // bool is_tuple = recv->flags & mask; Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_at"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); // Check that index is not over the end of the Tuple Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); ops_.stack_remove(2); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.stack_push(ops_.create_load(gep, "tuple_at")); ops_.create_branch(after_); ops_.set_block(is_other); } void call_tuple_put() { Value* rec = recv(); Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type); BasicBlock* is_tuple = ops_.new_block("is_tuple"); BasicBlock* access = ops_.new_block("tuple_put"); BasicBlock* is_other = ops_.new_block("is_other"); ops_.create_conditional_branch(is_tuple, is_other, cmp); ops_.set_block(is_tuple); Value* index_val = arg(0); Value* fix_cmp = ops_.check_if_fixnum(index_val); Value* tup = ops_.upcast(rec, "Tuple"); Value* index = ops_.tag_strip32(index_val); Value* full_size = ops_.get_tuple_size(tup); Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds"); // Combine fix_cmp and size_cmp to validate entry into access code Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp"); ops_.create_conditional_branch(access, is_other, access_cmp); ops_.set_block(access); Value* value = arg(1); ops_.stack_remove(3); Value* idx[] = { ConstantInt::get(Type::Int32Ty, 0), ConstantInt::get(Type::Int32Ty, offset::tuple_field), index }; Value* gep = ops_.create_gep(tup, idx, 3, "field_pos"); ops_.create_store(value, gep); ops_.write_barrier(tup, value); ops_.stack_push(value); ops_.create_branch(after_); ops_.set_block(is_other); } }; }
Add inlining of methods just returning symbols
Add inlining of methods just returning symbols
C++
mpl-2.0
jsyeo/rubinius,Wirachmat/rubinius,jsyeo/rubinius,pH14/rubinius,ngpestelos/rubinius,ngpestelos/rubinius,pH14/rubinius,lgierth/rubinius,mlarraz/rubinius,dblock/rubinius,travis-repos/rubinius,Wirachmat/rubinius,ngpestelos/rubinius,heftig/rubinius,kachick/rubinius,pH14/rubinius,heftig/rubinius,jemc/rubinius,digitalextremist/rubinius,sferik/rubinius,slawosz/rubinius,mlarraz/rubinius,Azizou/rubinius,kachick/rubinius,heftig/rubinius,ngpestelos/rubinius,heftig/rubinius,kachick/rubinius,ngpestelos/rubinius,kachick/rubinius,kachick/rubinius,ruipserra/rubinius,lgierth/rubinius,dblock/rubinius,ngpestelos/rubinius,digitalextremist/rubinius,dblock/rubinius,sferik/rubinius,sferik/rubinius,Wirachmat/rubinius,Azizou/rubinius,slawosz/rubinius,sferik/rubinius,ruipserra/rubinius,jsyeo/rubinius,travis-repos/rubinius,kachick/rubinius,ruipserra/rubinius,lgierth/rubinius,jemc/rubinius,jemc/rubinius,heftig/rubinius,digitalextremist/rubinius,slawosz/rubinius,jemc/rubinius,pH14/rubinius,heftig/rubinius,mlarraz/rubinius,travis-repos/rubinius,pH14/rubinius,sferik/rubinius,slawosz/rubinius,Azizou/rubinius,jemc/rubinius,mlarraz/rubinius,benlovell/rubinius,ruipserra/rubinius,jemc/rubinius,lgierth/rubinius,ruipserra/rubinius,digitalextremist/rubinius,digitalextremist/rubinius,Wirachmat/rubinius,slawosz/rubinius,travis-repos/rubinius,travis-repos/rubinius,dblock/rubinius,slawosz/rubinius,mlarraz/rubinius,kachick/rubinius,jsyeo/rubinius,sferik/rubinius,travis-repos/rubinius,mlarraz/rubinius,Wirachmat/rubinius,Azizou/rubinius,pH14/rubinius,ruipserra/rubinius,digitalextremist/rubinius,Azizou/rubinius,dblock/rubinius,sferik/rubinius,dblock/rubinius,jemc/rubinius,ngpestelos/rubinius,travis-repos/rubinius,heftig/rubinius,benlovell/rubinius,ruipserra/rubinius,Azizou/rubinius,benlovell/rubinius,dblock/rubinius,benlovell/rubinius,mlarraz/rubinius,jsyeo/rubinius,Wirachmat/rubinius,Wirachmat/rubinius,Azizou/rubinius,jsyeo/rubinius,slawosz/rubinius,benlovell/rubinius,benlovell/rubinius,lgierth/rubinius,digitalextremist/rubinius,kachick/rubinius,pH14/rubinius,benlovell/rubinius,jsyeo/rubinius,lgierth/rubinius,lgierth/rubinius
1c56f6a9bb14a6a2fcd23823db5b02407c308a00
vm/llvm/passes.cpp
vm/llvm/passes.cpp
#ifdef ENABLE_LLVM #include "llvm/passes.hpp" #include <llvm/Attributes.h> #include <llvm/BasicBlock.h> #include <llvm/Function.h> #include <llvm/Instructions.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Support/CallSite.h> #include <llvm/ADT/APInt.h> #include <llvm/Constants.h> #include <llvm/Module.h> #include <llvm/Intrinsics.h> #include <llvm/Analysis/SparsePropagation.h> #include <llvm/Analysis/AliasAnalysis.h> #include <llvm/Support/raw_ostream.h> #include <iostream> namespace { using namespace llvm; class GuardEliminator : public FunctionPass { Type* float_type_; public: static char ID; GuardEliminator() : FunctionPass(ID) {} virtual bool doInitialization(Module& mod) { float_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Float")); return false; } virtual bool runOnFunction(Function& f) { bool changed = false; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { ICmpInst* icmp = dyn_cast<ICmpInst>(inst); if(icmp == NULL) continue; if(BinaryOperator* bin = dyn_cast<BinaryOperator>(icmp->getOperand(0))) { if(bin->getOpcode() != Instruction::And) continue; if(PtrToIntInst* p2i = dyn_cast<PtrToIntInst>(bin->getOperand(0))) { if(p2i->getOperand(0)->getType() == float_type_) { icmp->replaceAllUsesWith(ConstantInt::getTrue(f.getContext())); changed = true; continue; } } } else if(LoadInst* load = dyn_cast<LoadInst>(icmp->getOperand(0))) { if(GetElementPtrInst* gep1 = dyn_cast<GetElementPtrInst>(load->getOperand(0))) { if(LoadInst* load2 = dyn_cast<LoadInst>(gep1->getOperand(0))) { if(GetElementPtrInst* gep2 = dyn_cast<GetElementPtrInst>(load2->getOperand(0))) { if(gep2->getOperand(0)->getType() == float_type_) { icmp->replaceAllUsesWith(ConstantInt::getTrue(f.getContext())); changed = true; continue; } } } } } } } return changed; } }; char GuardEliminator::ID = 0; class AllocationEliminator : public FunctionPass { Function* float_alloc_; public: static char ID; AllocationEliminator() : FunctionPass(ID) , float_alloc_(0) {} virtual bool doInitialization(Module& mod) { float_alloc_ = mod.getFunction("rbx_float_allocate"); return false; } bool gep_used(GetElementPtrInst* gep) { for(Value::use_iterator u = gep->use_begin(); u != gep->use_end(); u++) { llvm::outs() << "gep user: " << *(*u) << "\n"; if(!dyn_cast<StoreInst>(*u)) return true; } return false; } void erase_gep_users(GetElementPtrInst* gep) { for(Value::use_iterator u = gep->use_begin(); u != gep->use_end(); /* nothing */) { if(Instruction* inst = dyn_cast<Instruction>(*u)) { u++; inst->eraseFromParent(); } else { u++; assert(0); } } } virtual bool runOnFunction(Function& f) { std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { CallInst* call = dyn_cast<CallInst>(inst); if(!call) continue; Function* func = call->getCalledFunction(); if(func && func->getName() == "rbx_float_allocate") { llvm::outs() << "here2!\n"; bool use = false; for(Value::use_iterator u = call->use_begin(); u != call->use_end(); u++) { llvm::outs() << "float user: " << *(*u) << "\n"; if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(*u)) { if(gep_used(gep)) { use = true; break; } } else { use = true; break; } } if(!use) { to_remove.push_back(call); } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { CallInst* call = *i; for(Value::use_iterator u = call->use_begin(); u != call->use_end(); /* nothing */) { if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(*u)) { llvm::outs() << "erasing: " << *gep << "\n"; erase_gep_users(gep); u++; gep->eraseFromParent(); } else { assert(0); } } call->eraseFromParent(); } return !to_remove.empty(); } }; char AllocationEliminator::ID = 0; class OverflowConstantFolder : public FunctionPass { public: static char ID; OverflowConstantFolder() : FunctionPass(ID) {} bool try_to_fold_addition(LLVMContext& ctx, CallInst* call) { CallSite cs(call); Value* lhs = cs.getArgument(0); Value* rhs = cs.getArgument(1); bool changed = false; if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) { if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) { const APInt& lval = lc->getValue(); const APInt& rval = rc->getValue(); APInt zero(lval.getBitWidth(), 0, true); APInt res = lval + rval; ConstantInt* overflow = ConstantInt::getFalse(ctx); if(lval.sgt(zero) && res.slt(rval)) { overflow = ConstantInt::getTrue(ctx); } else if(rval.sgt(zero) && res.slt(lval)) { overflow = ConstantInt::getTrue(ctx); } // Now, update the extracts for(Value::use_iterator i = call->use_begin(); i != call->use_end(); /* nothing */) { if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) { Value* result = 0; ExtractValueInst::idx_iterator idx = extract->idx_begin(); if(*idx == 0) { result = ConstantInt::get(ctx, res); } else if(*idx == 1) { result = overflow; } else { llvm::outs() << "unknown index on sadd.overflow extract\n"; } if(result) { extract->replaceAllUsesWith(result); result->takeName(extract); // I uses the element itself to find the next, so we have // to increment before we remove it. i++; extract->eraseFromParent(); continue; } } i++; } changed = true; } } return changed; } virtual bool runOnFunction(Function& f) { bool changed = false; std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { CallInst *call = dyn_cast<CallInst>(inst); if(call == NULL) continue; // This may miss inlining indirect calls that become // direct after inlining something else. Function *called_function = call->getCalledFunction(); if(!called_function) continue; if(called_function->getIntrinsicID() == Intrinsic::sadd_with_overflow) { if(try_to_fold_addition(f.getContext(), call)) { if(call->use_empty()) { to_remove.push_back(call); changed = true; } } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { (*i)->eraseFromParent(); } return changed; } }; // The address of this variable identifies the pass. See // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode. char OverflowConstantFolder::ID = 0; class RubiniusAliasAnalysis : public FunctionPass, public AliasAnalysis { Type* class_type_; Type* object_type_; Type* args_type_; Type* float_type_; public: static char ID; RubiniusAliasAnalysis() : FunctionPass(ID) , class_type_(0) {} virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const { usage.setPreservesAll(); AliasAnalysis::getAnalysisUsage(usage); } virtual bool doInitialization(Module& mod) { class_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Class")); object_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Object")); args_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Arguments")); float_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Float")); return false; } virtual bool runOnFunction(Function& func) { InitializeAliasAnalysis(this); return false; } virtual void* getAdjustedAnalysisPointer(const void* PI) { if(PI == &AliasAnalysis::ID) { return (AliasAnalysis*)this; } return this; } virtual AliasAnalysis::AliasResult alias(const Location &LocA, const Location &LocB) { // Indicate that tagged fixnums can't alias anything. if(const IntToPtrInst* ip = dyn_cast<IntToPtrInst>(LocA.Ptr)) { if(ip->getType() == object_type_) { if(const ConstantInt* ci = dyn_cast<ConstantInt>(ip->getOperand(0))) { const APInt& cv = ci->getValue(); APInt one(cv.getBitWidth(), 1); if(cv.And(one) == one) return NoAlias; } } } return AliasAnalysis::alias(LocA, LocB); } virtual AliasAnalysis::ModRefResult getModRefInfo(ImmutableCallSite cs, const Location &Loc) { if(const Function* func = cs.getCalledFunction()) { if(func->getName() == "rbx_float_allocate") { return NoModRef; } } return AliasAnalysis::getModRefInfo(cs, Loc); } // This method only exists to appease -Woverloaded-virtual. It's dumb // that it won't allow us to overload only one of the signatures for // getModRefInfo. virtual AliasAnalysis::ModRefResult getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) { return AliasAnalysis::getModRefInfo(CS1, CS2); } virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal = false) { LLVMContext& ctx = Loc.Ptr->getContext(); if(const GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(Loc.Ptr)) { if(gep->getPointerOperand()->getType() == class_type_) { // Indicate that the class_id field is constant if(gep->getNumIndices() == 2 && gep->getOperand(1) == ConstantInt::get(Type::getInt32Ty(ctx), 0) && gep->getOperand(2) == ConstantInt::get(Type::getInt32Ty(ctx), 3)) { return true; } // Indicate that pointers to classes are constant } else if(gep->getType() == PointerType::getUnqual(class_type_)) { return true; // Indicate that all fields within Arguments are constant } else if(gep->getPointerOperand()->getType() == args_type_) { return true; } else if(gep->getPointerOperand()->getType() == float_type_) { return true; } } else if(const BitCastInst* bc = dyn_cast<BitCastInst>(Loc.Ptr)) { if(bc->getType() == PointerType::getUnqual(Type::getDoubleTy(ctx))) { return true; } } return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); } }; char RubiniusAliasAnalysis::ID = 0; static RegisterPass<RubiniusAliasAnalysis> RubiniusAliasAnalysis_info("rbx-aa", "Rubinius-specific Alias Analysis", false, true); static RegisterAnalysisGroup<AliasAnalysis, false> RubiniusAliasAnalysis_ag(RubiniusAliasAnalysis_info); /* class TypeGuardRemoval : public FunctionPass { public: static char ID; TypeGuardRemoval() : FunctionPass(&ID) {} class Driver : public AbstractLatticeFunction { virtual LatticeVal ComputeInstructionState( Instructions &I, SparseSolver& SS) { if(ICmpInst* ic = dyn_cast<ICmpInst>(&I)) { if(LoadInst* lc = dyn_cast<LoadInst>(ic->getOperand(0))) { if(GetElementPtrInst* gepc = dyn_cast<GetElementPtrInst>(lc->getPointerOperand())) { } } } }; virtual bool runOnFunction(Function& f) { return true; } }; char TypeGuardRemoval::ID = 0; */ } // anonymous namespace namespace rubinius { llvm::FunctionPass* create_overflow_folding_pass() { return new OverflowConstantFolder(); } llvm::FunctionPass* create_rubinius_alias_analysis() { return new RubiniusAliasAnalysis(); } llvm::FunctionPass* create_guard_eliminator_pass() { return new GuardEliminator(); } llvm::FunctionPass* create_allocation_eliminator_pass() { return new AllocationEliminator(); } } #endif
#ifdef ENABLE_LLVM #include "llvm/passes.hpp" #include <llvm/Attributes.h> #include <llvm/BasicBlock.h> #include <llvm/Function.h> #include <llvm/Instructions.h> #include <llvm/Constants.h> #include <llvm/Module.h> #include <llvm/Intrinsics.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Support/CallSite.h> #include <llvm/ADT/APInt.h> #include <llvm/Analysis/SparsePropagation.h> #include <llvm/Analysis/AliasAnalysis.h> #include <llvm/Support/raw_ostream.h> #include <iostream> namespace { using namespace llvm; class GuardEliminator : public FunctionPass { Type* float_type_; public: static char ID; GuardEliminator() : FunctionPass(ID) {} virtual bool doInitialization(Module& mod) { float_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Float")); return false; } virtual bool runOnFunction(Function& f) { bool changed = false; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { ICmpInst* icmp = dyn_cast<ICmpInst>(inst); if(icmp == NULL) continue; if(BinaryOperator* bin = dyn_cast<BinaryOperator>(icmp->getOperand(0))) { if(bin->getOpcode() != Instruction::And) continue; if(PtrToIntInst* p2i = dyn_cast<PtrToIntInst>(bin->getOperand(0))) { if(p2i->getOperand(0)->getType() == float_type_) { icmp->replaceAllUsesWith(ConstantInt::getTrue(f.getContext())); changed = true; continue; } } } else if(LoadInst* load = dyn_cast<LoadInst>(icmp->getOperand(0))) { if(GetElementPtrInst* gep1 = dyn_cast<GetElementPtrInst>(load->getOperand(0))) { if(LoadInst* load2 = dyn_cast<LoadInst>(gep1->getOperand(0))) { if(GetElementPtrInst* gep2 = dyn_cast<GetElementPtrInst>(load2->getOperand(0))) { if(gep2->getOperand(0)->getType() == float_type_) { icmp->replaceAllUsesWith(ConstantInt::getTrue(f.getContext())); changed = true; continue; } } } } } } } return changed; } }; char GuardEliminator::ID = 0; class AllocationEliminator : public FunctionPass { Function* float_alloc_; public: static char ID; AllocationEliminator() : FunctionPass(ID) , float_alloc_(0) {} virtual bool doInitialization(Module& mod) { float_alloc_ = mod.getFunction("rbx_float_allocate"); return false; } bool gep_used(GetElementPtrInst* gep) { for(Value::use_iterator u = gep->use_begin(); u != gep->use_end(); u++) { llvm::outs() << "gep user: " << *(*u) << "\n"; if(!dyn_cast<StoreInst>(*u)) return true; } return false; } void erase_gep_users(GetElementPtrInst* gep) { for(Value::use_iterator u = gep->use_begin(); u != gep->use_end(); /* nothing */) { if(Instruction* inst = dyn_cast<Instruction>(*u)) { u++; inst->eraseFromParent(); } else { u++; assert(0); } } } virtual bool runOnFunction(Function& f) { std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { CallInst* call = dyn_cast<CallInst>(inst); if(!call) continue; Function* func = call->getCalledFunction(); if(func && func->getName() == "rbx_float_allocate") { llvm::outs() << "here2!\n"; bool use = false; for(Value::use_iterator u = call->use_begin(); u != call->use_end(); u++) { llvm::outs() << "float user: " << *(*u) << "\n"; if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(*u)) { if(gep_used(gep)) { use = true; break; } } else { use = true; break; } } if(!use) { to_remove.push_back(call); } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { CallInst* call = *i; for(Value::use_iterator u = call->use_begin(); u != call->use_end(); /* nothing */) { if(GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(*u)) { llvm::outs() << "erasing: " << *gep << "\n"; erase_gep_users(gep); u++; gep->eraseFromParent(); } else { assert(0); } } call->eraseFromParent(); } return !to_remove.empty(); } }; char AllocationEliminator::ID = 0; class OverflowConstantFolder : public FunctionPass { public: static char ID; OverflowConstantFolder() : FunctionPass(ID) {} bool try_to_fold_addition(LLVMContext& ctx, CallInst* call) { CallSite cs(call); Value* lhs = cs.getArgument(0); Value* rhs = cs.getArgument(1); bool changed = false; if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) { if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) { const APInt& lval = lc->getValue(); const APInt& rval = rc->getValue(); APInt zero(lval.getBitWidth(), 0, true); APInt res = lval + rval; ConstantInt* overflow = ConstantInt::getFalse(ctx); if(lval.sgt(zero) && res.slt(rval)) { overflow = ConstantInt::getTrue(ctx); } else if(rval.sgt(zero) && res.slt(lval)) { overflow = ConstantInt::getTrue(ctx); } // Now, update the extracts for(Value::use_iterator i = call->use_begin(); i != call->use_end(); /* nothing */) { if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) { Value* result = 0; ExtractValueInst::idx_iterator idx = extract->idx_begin(); if(*idx == 0) { result = ConstantInt::get(ctx, res); } else if(*idx == 1) { result = overflow; } else { llvm::outs() << "unknown index on sadd.overflow extract\n"; } if(result) { extract->replaceAllUsesWith(result); result->takeName(extract); // I uses the element itself to find the next, so we have // to increment before we remove it. i++; extract->eraseFromParent(); continue; } } i++; } changed = true; } } return changed; } virtual bool runOnFunction(Function& f) { bool changed = false; std::vector<CallInst*> to_remove; for(Function::iterator bb = f.begin(), e = f.end(); bb != e; ++bb) { for(BasicBlock::iterator inst = bb->begin(); inst != bb->end(); ++inst) { CallInst *call = dyn_cast<CallInst>(inst); if(call == NULL) continue; // This may miss inlining indirect calls that become // direct after inlining something else. Function *called_function = call->getCalledFunction(); if(!called_function) continue; if(called_function->getIntrinsicID() == Intrinsic::sadd_with_overflow) { if(try_to_fold_addition(f.getContext(), call)) { if(call->use_empty()) { to_remove.push_back(call); changed = true; } } } } } for(std::vector<CallInst*>::iterator i = to_remove.begin(); i != to_remove.end(); ++i) { (*i)->eraseFromParent(); } return changed; } }; // The address of this variable identifies the pass. See // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode. char OverflowConstantFolder::ID = 0; class RubiniusAliasAnalysis : public FunctionPass, public AliasAnalysis { Type* class_type_; Type* object_type_; Type* args_type_; Type* float_type_; public: static char ID; RubiniusAliasAnalysis() : FunctionPass(ID) , class_type_(0) {} virtual void getAnalysisUsage(llvm::AnalysisUsage& usage) const { usage.setPreservesAll(); AliasAnalysis::getAnalysisUsage(usage); } virtual bool doInitialization(Module& mod) { class_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Class")); object_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Object")); args_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Arguments")); float_type_ = PointerType::getUnqual( mod.getTypeByName("struct.rubinius::Float")); return false; } virtual bool runOnFunction(Function& func) { InitializeAliasAnalysis(this); return false; } virtual void* getAdjustedAnalysisPointer(const void* PI) { if(PI == &AliasAnalysis::ID) { return (AliasAnalysis*)this; } return this; } virtual AliasAnalysis::AliasResult alias(const Location &LocA, const Location &LocB) { // Indicate that tagged fixnums can't alias anything. if(const IntToPtrInst* ip = dyn_cast<IntToPtrInst>(LocA.Ptr)) { if(ip->getType() == object_type_) { if(const ConstantInt* ci = dyn_cast<ConstantInt>(ip->getOperand(0))) { const APInt& cv = ci->getValue(); APInt one(cv.getBitWidth(), 1); if(cv.And(one) == one) return NoAlias; } } } return AliasAnalysis::alias(LocA, LocB); } virtual AliasAnalysis::ModRefResult getModRefInfo(ImmutableCallSite cs, const Location &Loc) { if(const Function* func = cs.getCalledFunction()) { if(func->getName() == "rbx_float_allocate") { return NoModRef; } } return AliasAnalysis::getModRefInfo(cs, Loc); } // This method only exists to appease -Woverloaded-virtual. It's dumb // that it won't allow us to overload only one of the signatures for // getModRefInfo. virtual AliasAnalysis::ModRefResult getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) { return AliasAnalysis::getModRefInfo(CS1, CS2); } virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal = false) { LLVMContext& ctx = Loc.Ptr->getContext(); if(const GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(Loc.Ptr)) { if(gep->getPointerOperand()->getType() == class_type_) { // Indicate that the class_id field is constant if(gep->getNumIndices() == 2 && gep->getOperand(1) == ConstantInt::get(Type::getInt32Ty(ctx), 0) && gep->getOperand(2) == ConstantInt::get(Type::getInt32Ty(ctx), 3)) { return true; } // Indicate that pointers to classes are constant } else if(gep->getType() == PointerType::getUnqual(class_type_)) { return true; // Indicate that all fields within Arguments are constant } else if(gep->getPointerOperand()->getType() == args_type_) { return true; } else if(gep->getPointerOperand()->getType() == float_type_) { return true; } } else if(const BitCastInst* bc = dyn_cast<BitCastInst>(Loc.Ptr)) { if(bc->getType() == PointerType::getUnqual(Type::getDoubleTy(ctx))) { return true; } } return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal); } }; char RubiniusAliasAnalysis::ID = 0; static RegisterPass<RubiniusAliasAnalysis> RubiniusAliasAnalysis_info("rbx-aa", "Rubinius-specific Alias Analysis", false, true); static RegisterAnalysisGroup<AliasAnalysis, false> RubiniusAliasAnalysis_ag(RubiniusAliasAnalysis_info); /* class TypeGuardRemoval : public FunctionPass { public: static char ID; TypeGuardRemoval() : FunctionPass(&ID) {} class Driver : public AbstractLatticeFunction { virtual LatticeVal ComputeInstructionState( Instructions &I, SparseSolver& SS) { if(ICmpInst* ic = dyn_cast<ICmpInst>(&I)) { if(LoadInst* lc = dyn_cast<LoadInst>(ic->getOperand(0))) { if(GetElementPtrInst* gepc = dyn_cast<GetElementPtrInst>(lc->getPointerOperand())) { } } } }; virtual bool runOnFunction(Function& f) { return true; } }; char TypeGuardRemoval::ID = 0; */ } // anonymous namespace namespace rubinius { llvm::FunctionPass* create_overflow_folding_pass() { return new OverflowConstantFolder(); } llvm::FunctionPass* create_rubinius_alias_analysis() { return new RubiniusAliasAnalysis(); } llvm::FunctionPass* create_guard_eliminator_pass() { return new GuardEliminator(); } llvm::FunctionPass* create_allocation_eliminator_pass() { return new AllocationEliminator(); } } #endif
Sort LLVM includes for coming LLVM 3.3 support
Sort LLVM includes for coming LLVM 3.3 support
C++
mpl-2.0
jemc/rubinius,jsyeo/rubinius,pH14/rubinius,jemc/rubinius,mlarraz/rubinius,ngpestelos/rubinius,jsyeo/rubinius,heftig/rubinius,digitalextremist/rubinius,jemc/rubinius,mlarraz/rubinius,kachick/rubinius,ngpestelos/rubinius,sferik/rubinius,dblock/rubinius,benlovell/rubinius,mlarraz/rubinius,jemc/rubinius,pH14/rubinius,benlovell/rubinius,heftig/rubinius,pH14/rubinius,kachick/rubinius,jemc/rubinius,Wirachmat/rubinius,digitalextremist/rubinius,ngpestelos/rubinius,heftig/rubinius,sferik/rubinius,digitalextremist/rubinius,ngpestelos/rubinius,benlovell/rubinius,Azizou/rubinius,digitalextremist/rubinius,benlovell/rubinius,Wirachmat/rubinius,Azizou/rubinius,jsyeo/rubinius,ngpestelos/rubinius,jsyeo/rubinius,jemc/rubinius,sferik/rubinius,mlarraz/rubinius,Azizou/rubinius,digitalextremist/rubinius,heftig/rubinius,kachick/rubinius,Azizou/rubinius,jsyeo/rubinius,ruipserra/rubinius,ruipserra/rubinius,sferik/rubinius,Azizou/rubinius,ruipserra/rubinius,Azizou/rubinius,Wirachmat/rubinius,pH14/rubinius,kachick/rubinius,dblock/rubinius,pH14/rubinius,dblock/rubinius,Wirachmat/rubinius,Azizou/rubinius,ngpestelos/rubinius,ruipserra/rubinius,pH14/rubinius,jsyeo/rubinius,mlarraz/rubinius,ngpestelos/rubinius,ruipserra/rubinius,dblock/rubinius,mlarraz/rubinius,dblock/rubinius,heftig/rubinius,kachick/rubinius,mlarraz/rubinius,benlovell/rubinius,benlovell/rubinius,kachick/rubinius,dblock/rubinius,digitalextremist/rubinius,Wirachmat/rubinius,jsyeo/rubinius,pH14/rubinius,heftig/rubinius,Wirachmat/rubinius,jemc/rubinius,sferik/rubinius,benlovell/rubinius,dblock/rubinius,ruipserra/rubinius,Wirachmat/rubinius,sferik/rubinius,kachick/rubinius,heftig/rubinius,sferik/rubinius,kachick/rubinius,digitalextremist/rubinius,ruipserra/rubinius
2d69985dcedf1fd0a5119616bd1d642e2decec68
Graphs/Traverse/dfs.cpp
Graphs/Traverse/dfs.cpp
#include <bits/stdc++.h> #define NUM_NODES 8 using namespace std; vector < int > g[NUM_NODES]; int vis[NUM_NODES]; enum {WHITE, GRAY, BLACK}; /* * o -> origin */ void dfs(int o){ vis [o] = GRAY; //semi-visited for (int i = 0; i < g[o].size(); i++){ int v = g[o][i]; if (vis[v] == WHITE) dfs(v); // visit neighbors } cout << o << endl; vis[o] = BLACK; //visited; } int main(){ g[0].push_back(1); g[0].push_back(2); g[0].push_back(3); g[1].push_back(4); g[1].push_back(5); g[2].push_back(6); g[3].push_back(7); dfs(0); return 0; }
#include <bits/stdc++.h> #define NUM_NODES 20 using namespace std; vector < int > g[NUM_NODES]; int vis[NUM_NODES]; enum {WHITE, GRAY, BLACK}; /* * o -> origin */ void dfs(int o){ vis [o] = GRAY; //semi-visited for (int i = 0; i < g[o].size(); i++){ int v = g[o][i]; if (vis[v] == GRAY) cout << "There is a cycle. to " << o << endl; if (vis[v] == WHITE) dfs(v); // visit neighbors } cout << o << endl; vis[o] = BLACK; //visited; } int main(){ g[0].push_back(1); g[0].push_back(2); g[0].push_back(3); g[1].push_back(4); g[1].push_back(5); g[2].push_back(6); g[3].push_back(7); g[4].push_back(0); g[6].push_back(0); dfs(0); return 0; }
Implement awesome form to detect cycles in a graph.
Implement awesome form to detect cycles in a graph.
C++
mit
xdanielsb/Marathon-book,xdanielsb/Marathon-book,xdanielsb/Marathon-book,xdanielsb/Marathon-book,xdanielsb/Marathon-book
feeef079eb1cd577a5eca763eef9c2c514a56e03
IO/vtkGlobFileNames.cxx
IO/vtkGlobFileNames.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkGlobFileNames.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkGlobFileNames.h" #include "vtkStringArray.h" #include "vtkDebugLeaks.h" #include <vtksys/Glob.hxx> #include <vtkstd/string> #include <vtkstd/vector> #include <vtkstd/algorithm> vtkCxxRevisionMacro(vtkGlobFileNames, "1.2"); //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkGlobFileNames); //---------------------------------------------------------------------------- vtkGlobFileNames* vtkGlobFileNames::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkGlobFileNames"); #endif return new vtkGlobFileNames; } //---------------------------------------------------------------------------- vtkGlobFileNames::vtkGlobFileNames() { this->Pattern = 0; this->Recurse = 0; this->FileNames = vtkStringArray::New(); } //---------------------------------------------------------------------------- vtkGlobFileNames::~vtkGlobFileNames() { if (this->Pattern) { delete [] this->Pattern; } this->FileNames->Delete(); this->FileNames = 0; } //---------------------------------------------------------------------------- void vtkGlobFileNames::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Pattern: " << this->GetPattern() << "\n"; os << indent << "Recurse: " << (this->GetRecurse() ? "On\n" : "Off\n"); os << indent << "FileNames: (" << this->GetFileNames() << ")\n"; indent = indent.GetNextIndent(); for(int i = 0; i < this->FileNames->GetNumberOfValues(); i++) { os << indent << this->FileNames->GetValue(i) << "\n"; } } //---------------------------------------------------------------------------- void vtkGlobFileNames::Reset() { this->FileNames->Reset(); } //---------------------------------------------------------------------------- int vtkGlobFileNames::AddFileNames(const char* pattern) { this->SetPattern(pattern); vtksys::Glob glob; if (this->Recurse) { glob.RecurseOn(); } else { glob.RecurseOff(); } if (!this->Pattern) { vtkErrorMacro(<< "FindFileNames: pattern string is null."); return 0; } if (!glob.FindFiles(vtkstd::string(this->Pattern))) { vtkErrorMacro(<< "FindFileNames: Glob action failed for \"" << this->Pattern << "\""); return 0; } // copy the filenames from glob vtkstd::vector<vtkstd::string> files = glob.GetFiles(); // sort them lexicographically vtkstd::sort(files.begin(), files.end()); // add them onto the list of filenames for ( vtkstd::vector<vtkstd::string>::const_iterator iter = files.begin(); iter != files.end(); iter++) { this->FileNames->InsertNextValue(iter->c_str()); } return 1; } //---------------------------------------------------------------------------- const char* vtkGlobFileNames::GetNthFileName(int index) { if(index >= this->FileNames->GetNumberOfValues() || index < 0) { vtkErrorMacro( << "Bad index for GetFileName on vtkGlobFileNames\n"); return 0; } return this->FileNames->GetValue(index).c_str(); } //---------------------------------------------------------------------------- int vtkGlobFileNames::GetNumberOfFileNames() { return this->FileNames->GetNumberOfValues(); }
/*========================================================================= Program: Visualization Toolkit Module: vtkGlobFileNames.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkGlobFileNames.h" #include "vtkStringArray.h" #include "vtkDebugLeaks.h" #include <vtksys/Glob.hxx> #include <vtkstd/string> #include <vtkstd/vector> #include <vtkstd/algorithm> vtkCxxRevisionMacro(vtkGlobFileNames, "1.3"); //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkGlobFileNames); //---------------------------------------------------------------------------- vtkGlobFileNames* vtkGlobFileNames::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkGlobFileNames"); #endif return new vtkGlobFileNames; } //---------------------------------------------------------------------------- vtkGlobFileNames::vtkGlobFileNames() { this->Pattern = 0; this->Recurse = 0; this->FileNames = vtkStringArray::New(); } //---------------------------------------------------------------------------- vtkGlobFileNames::~vtkGlobFileNames() { if (this->Pattern) { delete [] this->Pattern; } this->FileNames->Delete(); this->FileNames = 0; } //---------------------------------------------------------------------------- void vtkGlobFileNames::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Pattern: " << (this->GetPattern() ? this->GetPattern() : " none") << "\n"; os << indent << "Recurse: " << (this->GetRecurse() ? "On\n" : "Off\n"); os << indent << "FileNames: (" << this->GetFileNames() << ")\n"; indent = indent.GetNextIndent(); for(int i = 0; i < this->FileNames->GetNumberOfValues(); i++) { os << indent << this->FileNames->GetValue(i) << "\n"; } } //---------------------------------------------------------------------------- void vtkGlobFileNames::Reset() { this->FileNames->Reset(); } //---------------------------------------------------------------------------- int vtkGlobFileNames::AddFileNames(const char* pattern) { this->SetPattern(pattern); vtksys::Glob glob; if (this->Recurse) { glob.RecurseOn(); } else { glob.RecurseOff(); } if (!this->Pattern) { vtkErrorMacro(<< "FindFileNames: pattern string is null."); return 0; } if (!glob.FindFiles(vtkstd::string(this->Pattern))) { vtkErrorMacro(<< "FindFileNames: Glob action failed for \"" << this->Pattern << "\""); return 0; } // copy the filenames from glob vtkstd::vector<vtkstd::string> files = glob.GetFiles(); // sort them lexicographically vtkstd::sort(files.begin(), files.end()); // add them onto the list of filenames for ( vtkstd::vector<vtkstd::string>::const_iterator iter = files.begin(); iter != files.end(); iter++) { this->FileNames->InsertNextValue(iter->c_str()); } return 1; } //---------------------------------------------------------------------------- const char* vtkGlobFileNames::GetNthFileName(int index) { if(index >= this->FileNames->GetNumberOfValues() || index < 0) { vtkErrorMacro( << "Bad index for GetFileName on vtkGlobFileNames\n"); return 0; } return this->FileNames->GetValue(index).c_str(); } //---------------------------------------------------------------------------- int vtkGlobFileNames::GetNumberOfFileNames() { return this->FileNames->GetNumberOfValues(); }
fix bad printself
BUG: fix bad printself
C++
bsd-3-clause
aashish24/VTK-old,naucoin/VTKSlicerWidgets,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,msmolens/VTK,candy7393/VTK,SimVascular/VTK,collects/VTK,biddisco/VTK,daviddoria/PointGraphsPhase1,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,cjh1/VTK,mspark93/VTK,candy7393/VTK,biddisco/VTK,demarle/VTK,johnkit/vtk-dev,gram526/VTK,jmerkow/VTK,mspark93/VTK,msmolens/VTK,mspark93/VTK,spthaolt/VTK,keithroe/vtkoptix,candy7393/VTK,jeffbaumes/jeffbaumes-vtk,aashish24/VTK-old,daviddoria/PointGraphsPhase1,cjh1/VTK,jmerkow/VTK,hendradarwin/VTK,keithroe/vtkoptix,aashish24/VTK-old,johnkit/vtk-dev,mspark93/VTK,Wuteyan/VTK,msmolens/VTK,sumedhasingla/VTK,aashish24/VTK-old,sumedhasingla/VTK,naucoin/VTKSlicerWidgets,Wuteyan/VTK,daviddoria/PointGraphsPhase1,biddisco/VTK,SimVascular/VTK,sankhesh/VTK,demarle/VTK,biddisco/VTK,msmolens/VTK,ashray/VTK-EVM,jmerkow/VTK,candy7393/VTK,sumedhasingla/VTK,mspark93/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,aashish24/VTK-old,biddisco/VTK,cjh1/VTK,SimVascular/VTK,naucoin/VTKSlicerWidgets,collects/VTK,hendradarwin/VTK,gram526/VTK,gram526/VTK,spthaolt/VTK,biddisco/VTK,arnaudgelas/VTK,sumedhasingla/VTK,SimVascular/VTK,arnaudgelas/VTK,collects/VTK,naucoin/VTKSlicerWidgets,berendkleinhaneveld/VTK,demarle/VTK,keithroe/vtkoptix,candy7393/VTK,johnkit/vtk-dev,cjh1/VTK,berendkleinhaneveld/VTK,naucoin/VTKSlicerWidgets,sankhesh/VTK,ashray/VTK-EVM,msmolens/VTK,hendradarwin/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,spthaolt/VTK,naucoin/VTKSlicerWidgets,ashray/VTK-EVM,SimVascular/VTK,ashray/VTK-EVM,sumedhasingla/VTK,johnkit/vtk-dev,sankhesh/VTK,candy7393/VTK,demarle/VTK,gram526/VTK,sumedhasingla/VTK,demarle/VTK,msmolens/VTK,spthaolt/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,keithroe/vtkoptix,spthaolt/VTK,Wuteyan/VTK,sumedhasingla/VTK,mspark93/VTK,demarle/VTK,candy7393/VTK,msmolens/VTK,berendkleinhaneveld/VTK,keithroe/vtkoptix,collects/VTK,Wuteyan/VTK,demarle/VTK,berendkleinhaneveld/VTK,biddisco/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,collects/VTK,SimVascular/VTK,arnaudgelas/VTK,arnaudgelas/VTK,arnaudgelas/VTK,gram526/VTK,Wuteyan/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,spthaolt/VTK,jmerkow/VTK,gram526/VTK,sumedhasingla/VTK,sankhesh/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,gram526/VTK,hendradarwin/VTK,candy7393/VTK,ashray/VTK-EVM,SimVascular/VTK,cjh1/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,arnaudgelas/VTK,johnkit/vtk-dev,msmolens/VTK,ashray/VTK-EVM,hendradarwin/VTK,cjh1/VTK,ashray/VTK-EVM,sankhesh/VTK,demarle/VTK,sankhesh/VTK,gram526/VTK,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,hendradarwin/VTK,mspark93/VTK,mspark93/VTK,jmerkow/VTK,collects/VTK,keithroe/vtkoptix,spthaolt/VTK,keithroe/vtkoptix,hendradarwin/VTK,SimVascular/VTK
e46aa6772e1e4a605c0feea89c12b0d27c5869a4
src/Nazara/Graphics/AbstractViewer.cpp
src/Nazara/Graphics/AbstractViewer.cpp
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { /*! * \ingroup graphics * \class Nz::AbstractViewer * \brief Graphics class that represents the viewer for our scene * * \remark This class is abstract */ AbstractViewer::~AbstractViewer() = default; Vector3f AbstractViewer::Project(const Nz::Vector3f& worldPosition) const { Vector4f pos4D(worldPosition, 1.f); pos4D = GetViewMatrix() * pos4D; pos4D = GetProjectionMatrix() * pos4D; pos4D /= pos4D.w; Rectf viewport = Rectf(GetViewport()); Nz::Vector3f screenPosition(pos4D.x * 0.5f + 0.5f, -pos4D.y * 0.5f + 0.5f, pos4D.z * 0.5f + 0.5f); screenPosition.x = screenPosition.x * viewport.width + viewport.x; screenPosition.y = screenPosition.y * viewport.height + viewport.y; return screenPosition; } Vector3f AbstractViewer::Unproject(const Nz::Vector3f& screenPos) const { Rectf viewport = Rectf(GetViewport()); Nz::Vector4f normalizedPosition; normalizedPosition.x = (screenPos.x - viewport.x) / viewport.width * 2.f - 1.f; normalizedPosition.y = (screenPos.y - viewport.y) / viewport.height * 2.f - 1.f; normalizedPosition.z = screenPos.z * 2.f - 1.f; normalizedPosition.w = 1.f; Nz::Matrix4f invMatrix = GetViewMatrix() * GetProjectionMatrix(); invMatrix.Inverse(); Nz::Vector4f worldPos = invMatrix * normalizedPosition; worldPos /= worldPos.w; return Nz::Vector3f(worldPos.x, worldPos.y, worldPos.z); } }
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Graphics/Debug.hpp> namespace Nz { /*! * \ingroup graphics * \class Nz::AbstractViewer * \brief Graphics class that represents the viewer for our scene * * \remark This class is abstract */ AbstractViewer::~AbstractViewer() = default; Vector3f AbstractViewer::Project(const Nz::Vector3f& worldPosition) const { Vector4f pos4D(worldPosition, 1.f); pos4D = GetViewMatrix() * pos4D; pos4D = GetProjectionMatrix() * pos4D; pos4D /= pos4D.w; Rectf viewport = Rectf(GetViewport()); Nz::Vector3f screenPosition(pos4D.x * 0.5f + 0.5f, -pos4D.y * 0.5f + 0.5f, pos4D.z * 0.5f + 0.5f); screenPosition.x = screenPosition.x * viewport.width + viewport.x; screenPosition.y = screenPosition.y * viewport.height + viewport.y; return screenPosition; } Vector3f AbstractViewer::Unproject(const Nz::Vector3f& screenPos) const { Rectf viewport = Rectf(GetViewport()); Nz::Vector4f normalizedPosition; normalizedPosition.x = (screenPos.x - viewport.x) / viewport.width * 2.f - 1.f; normalizedPosition.y = (screenPos.y - viewport.y) / viewport.height * 2.f - 1.f; normalizedPosition.z = screenPos.z * 2.f - 1.f; normalizedPosition.w = 1.f; normalizedPosition.y = -normalizedPosition.y; Nz::Matrix4f invMatrix = GetViewMatrix() * GetProjectionMatrix(); invMatrix.Inverse(); Nz::Vector4f worldPos = invMatrix * normalizedPosition; worldPos /= worldPos.w; return Nz::Vector3f(worldPos.x, worldPos.y, worldPos.z); } }
Fix Unproject code
Graphics/AbstractViewer: Fix Unproject code
C++
mit
DigitalPulseSoftware/NazaraEngine
58b788f9e87318b9d69cdec1bf3f5077f541c42d
aaudio/echo/src/main/cpp/echo_audio_engine.cc
aaudio/echo/src/main/cpp/echo_audio_engine.cc
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <climits> #include <assert.h> #include "echo_audio_engine.h" /** * Every time the playback stream requires data this method will be called. * * @param stream the audio stream which is requesting data, this is the playStream_ object * @param userData the context in which the function is being called, in this case it will be the * EchoAudioEngine instance * @param audioData an empty buffer into which we can write our audio data * @param numFrames the number of audio frames which are required * @return Either AAUDIO_CALLBACK_RESULT_CONTINUE if the stream should continue requesting data * or AAUDIO_CALLBACK_RESULT_STOP if the stream should stop. * * @see EchoAudioEngine#dataCallback */ aaudio_data_callback_result_t dataCallback(AAudioStream *stream, void *userData, void *audioData, int32_t numFrames) { assert(userData && audioData); EchoAudioEngine *audioEngine = reinterpret_cast<EchoAudioEngine *>(userData); return audioEngine->dataCallback(stream, audioData, numFrames); } /** * If there is an error with a stream this function will be called. A common example of an error * is when an audio device (such as headphones) is disconnected. In this case you should not * restart the stream within the callback, instead use a separate thread to perform the stream * recreation and restart. * * @param stream the stream with the error * @param userData the context in which the function is being called, in this case it will be the * EchoAudioEngine instance * @param error the error which occured, a human readable string can be obtained using * AAudio_convertResultToText(error); * * @see EchoAudioEngine#errorCallback */ void errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error) { assert(userData); EchoAudioEngine *audioEngine = reinterpret_cast<EchoAudioEngine *>(userData); audioEngine->errorCallback(stream, error); } EchoAudioEngine::EchoAudioEngine() { sampleChannels_ = AUDIO_SAMPLE_CHANNELS; sampleFormat_ = AAUDIO_FORMAT_PCM_I16; bitsPerSample_ = SampleFormatToBpp(sampleFormat_); audioEffect_ = new AudioEffect(); } EchoAudioEngine::~EchoAudioEngine() { closeStream(recordingStream_); closeStream(playStream_); } void EchoAudioEngine::setRecordingDeviceId(int32_t deviceId) { recordingDeviceId_ = deviceId; } void EchoAudioEngine::setPlaybackDeviceId(int32_t deviceId) { playbackDeviceId_ = deviceId; } void EchoAudioEngine::setEchoOn(bool isEchoOn) { if (isEchoOn != isEchoOn_) { isEchoOn_ = isEchoOn; if (isEchoOn) { startStreams(); } else { stopStreams(); } } } void EchoAudioEngine::startStreams() { // Note: The order of stream creation is important. We create the playback stream first, // then use properties from the playback stream (e.g. sample rate) to create the // recording stream. By matching the properties we should get the lowest latency path createPlaybackStream(); createRecordingStream(); // Now start the recording stream so that we can read from it during the playback dataCallback if (recordingStream_ != nullptr && playStream_ != nullptr) { startStream(recordingStream_); startStream(playStream_); playStreamUnderrunCount_ = AAudioStream_getXRunCount(playStream_); } else { LOGE("Failed to create recording and/or playback stream"); } } /** * Stops and closes the playback and recording streams */ void EchoAudioEngine::stopStreams() { if (recordingStream_ != nullptr) { stopStream(recordingStream_); closeStream(recordingStream_); recordingStream_ = nullptr; } if (playStream_ != nullptr) { stopStream(playStream_); closeStream(playStream_); playStream_ = nullptr; } } /** * Creates a stream builder which can be used to construct streams * @return a new stream builder object */ AAudioStreamBuilder *EchoAudioEngine::createStreamBuilder() { AAudioStreamBuilder *builder = nullptr; aaudio_result_t result = AAudio_createStreamBuilder(&builder); if (result != AAUDIO_OK && !builder) { LOGE("Error creating stream builder: %s", AAudio_convertResultToText(result)); } return builder; } /** * Creates an audio stream for recording. The audio device used will depend on recordingDeviceId_. * If the value is set to AAUDIO_UNSPECIFIED then the default recording device will be used. */ void EchoAudioEngine::createRecordingStream() { // To create a stream we use a stream builder. This allows us to specify all the parameters // for the stream prior to opening it AAudioStreamBuilder *builder = createStreamBuilder(); if (builder != nullptr) { setupRecordingStreamParameters(builder); // Now that the parameters are set up we can open the stream aaudio_result_t result = AAudioStreamBuilder_openStream(builder, &recordingStream_); if (result == AAUDIO_OK && recordingStream_ != nullptr) { // Check that the stream format matches what we requested if (sampleFormat_ != AAudioStream_getFormat(recordingStream_)) { LOGW("Recording stream format doesn't match what was requested (format: %d). " "Higher latency expected.", sampleFormat_); } PrintAudioStreamInfo(recordingStream_); } else { LOGE("Failed to create recording stream. Error: %s", AAudio_convertResultToText(result)); } AAudioStreamBuilder_delete(builder); } else { LOGE("Unable to obtain an AAudioStreamBuilder object"); } } /** * Creates an audio stream for playback. The audio device used will depend on playbackDeviceId_. * If the value is set to AAUDIO_UNSPECIFIED then the default playback device will be used. */ void EchoAudioEngine::createPlaybackStream() { AAudioStreamBuilder *builder = createStreamBuilder(); if (builder != nullptr) { setupPlaybackStreamParameters(builder); aaudio_result_t result = AAudioStreamBuilder_openStream(builder, &playStream_); if (result == AAUDIO_OK && playStream_ != nullptr) { // check that we got PCM_I16 format if (sampleFormat_ != AAudioStream_getFormat(playStream_)) { LOGW("Playback stream sample format is not PCM_I16, higher latency expected"); } sampleRate_ = AAudioStream_getSampleRate(playStream_); framesPerBurst_ = AAudioStream_getFramesPerBurst(playStream_); defaultBufSizeInFrames_ = AAudioStream_getBufferSizeInFrames(playStream_); // Set the buffer size to the burst size - this will give us the minimum possible latency AAudioStream_setBufferSizeInFrames(playStream_, framesPerBurst_); bufSizeInFrames_ = framesPerBurst_; PrintAudioStreamInfo(playStream_); } else { LOGE("Failed to create playback stream. Error: %s", AAudio_convertResultToText(result)); } AAudioStreamBuilder_delete(builder); } else { LOGE("Unable to obtain an AAudioStreamBuilder object"); } } /** * Sets the stream parameters which are specific to recording, including the sample rate which * is determined from the playback stream. * @param builder The recording stream builder */ void EchoAudioEngine::setupRecordingStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setDeviceId(builder, recordingDeviceId_); AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_INPUT); AAudioStreamBuilder_setSampleRate(builder, sampleRate_); setupCommonStreamParameters(builder); } /** * Sets the stream parameters which are specific to playback, including device id and the * dataCallback function, which must be set for low latency playback. * @param builder The playback stream builder */ void EchoAudioEngine::setupPlaybackStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setDeviceId(builder, playbackDeviceId_); AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT); // The :: here indicates that the function is in the global namespace // i.e. *not* EchoAudioEngine::dataCallback, but dataCallback defined at the top of this class AAudioStreamBuilder_setDataCallback(builder, ::dataCallback, this); setupCommonStreamParameters(builder); } /** * Set the stream parameters which are common to both recording and playback streams. * @param builder The playback or recording stream builder */ void EchoAudioEngine::setupCommonStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setFormat(builder, sampleFormat_); AAudioStreamBuilder_setChannelCount(builder, sampleChannels_); // We request EXCLUSIVE mode since this will give us the lowest possible latency. // If EXCLUSIVE mode isn't available the builder will fall back to SHARED mode. AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE); AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setErrorCallback(builder, ::errorCallback, this); } void EchoAudioEngine::startStream(AAudioStream *stream) { aaudio_result_t result = AAudioStream_requestStart(stream); if (result != AAUDIO_OK) { LOGE("Error starting stream. %s", AAudio_convertResultToText(result)); } } void EchoAudioEngine::stopStream(AAudioStream *stream) { if (stream != nullptr) { aaudio_result_t result = AAudioStream_requestStop(stream); if (result != AAUDIO_OK) { LOGE("Error stopping stream. %s", AAudio_convertResultToText(result)); } } } /** * Close the stream. After the stream is closed it is deleted and subesequent AAudioStream_* calls * will return an error. AAudioStream_close() also checks and waits for any outstanding dataCallback * calls to complete before closing the stream. This means the application does not need to add * synchronization between the dataCallback function and the thread calling AAudioStream_close() * [the closing thread is the UI thread in this sample]. * @param stream the stream to close */ void EchoAudioEngine::closeStream(AAudioStream *stream) { if (stream != nullptr) { aaudio_result_t result = AAudioStream_close(stream); if (result != AAUDIO_OK) { LOGE("Error closing stream. %s", AAudio_convertResultToText(result)); } } } /** * @see the C method dataCallback at the top of this file */ aaudio_data_callback_result_t EchoAudioEngine::dataCallback(AAudioStream *stream, void *audioData, int32_t numFrames) { if (isEchoOn_) { // Tuning the buffer size for low latency... int32_t underRun = AAudioStream_getXRunCount(playStream_); if (underRun > playStreamUnderrunCount_) { /* Underrun happened since last callback: * try to increase the buffer size. */ playStreamUnderrunCount_ = underRun; aaudio_result_t actSize = AAudioStream_setBufferSizeInFrames( stream, bufSizeInFrames_ + framesPerBurst_); if (actSize > 0) { bufSizeInFrames_ = actSize; } else { LOGE("***** Output stream buffer tuning error: %s", AAudio_convertResultToText(actSize)); } } int32_t samplesPerFrame = sampleChannels_; // frameCount could be // < 0 : error code // >= 0 : actual value read from stream aaudio_result_t frameCount = 0; if (recordingStream_ != nullptr) { // If this is the first data callback we want to drain the recording buffer so we're getting // the most up to date data if (isFirstDataCallback_) { drainRecordingStream(audioData, numFrames); isFirstDataCallback_ = false; } frameCount = AAudioStream_read(recordingStream_, audioData, numFrames, static_cast<int64_t>(0)); audioEffect_->process(static_cast<int16_t *>(audioData), samplesPerFrame, frameCount); if (frameCount < 0) { LOGE("****AAudioStream_read() returns %s", AAudio_convertResultToText(frameCount)); frameCount = 0; // continue to play silent audio } } /** * If there's not enough audio data from input stream, fill the rest of buffer with * 0 (silence) and continue to loop */ numFrames -= frameCount; if (numFrames > 0) { memset(static_cast<int16_t *>(audioData) + frameCount * samplesPerFrame, 0, sizeof(int16_t) * numFrames * samplesPerFrame); } return AAUDIO_CALLBACK_RESULT_CONTINUE; } else { return AAUDIO_CALLBACK_RESULT_STOP; } } /** * Drain the recording stream of any existing data by reading from it until it's empty. This is * usually run to clear out any stale data before performing an actual read operation, thereby * obtaining the most recently recorded data and the best possbile recording latency. * * @param audioData A buffer which the existing data can be read into * @param numFrames The number of frames to read in a single read operation, this is typically the * size of `audioData`. */ void EchoAudioEngine::drainRecordingStream(void *audioData, int32_t numFrames) { aaudio_result_t clearedFrames = 0; do { clearedFrames = AAudioStream_read(recordingStream_, audioData, numFrames, 0); } while (clearedFrames > 0); } /** * See the C method errorCallback at the top of this file */ void EchoAudioEngine::errorCallback(AAudioStream *stream, aaudio_result_t error) { LOGI("errorCallback has result: %s", AAudio_convertResultToText(error)); aaudio_stream_state_t streamState = AAudioStream_getState(stream); if (streamState == AAUDIO_STREAM_STATE_DISCONNECTED) { // Handle stream restart on a separate thread std::function<void(void)> restartStreams = std::bind(&EchoAudioEngine::restartStreams, this); streamRestartThread_ = new std::thread(restartStreams); } } /** * Restart the streams. During the restart operation subsequent calls to this method will output * a warning. */ void EchoAudioEngine::restartStreams() { LOGI("Restarting streams"); if (restartingLock_.try_lock()) { stopStreams(); startStreams(); restartingLock_.unlock(); } else { LOGW("Restart stream operation already in progress - ignoring this request"); // We were unable to obtain the restarting lock which means the restart operation is currently // active. This is probably because we received successive "stream disconnected" events. // Internal issue b/63087953 } }
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <climits> #include <assert.h> #include "echo_audio_engine.h" /** * Every time the playback stream requires data this method will be called. * * @param stream the audio stream which is requesting data, this is the playStream_ object * @param userData the context in which the function is being called, in this case it will be the * EchoAudioEngine instance * @param audioData an empty buffer into which we can write our audio data * @param numFrames the number of audio frames which are required * @return Either AAUDIO_CALLBACK_RESULT_CONTINUE if the stream should continue requesting data * or AAUDIO_CALLBACK_RESULT_STOP if the stream should stop. * * @see EchoAudioEngine#dataCallback */ aaudio_data_callback_result_t dataCallback(AAudioStream *stream, void *userData, void *audioData, int32_t numFrames) { assert(userData && audioData); EchoAudioEngine *audioEngine = reinterpret_cast<EchoAudioEngine *>(userData); return audioEngine->dataCallback(stream, audioData, numFrames); } /** * If there is an error with a stream this function will be called. A common example of an error * is when an audio device (such as headphones) is disconnected. In this case you should not * restart the stream within the callback, instead use a separate thread to perform the stream * recreation and restart. * * @param stream the stream with the error * @param userData the context in which the function is being called, in this case it will be the * EchoAudioEngine instance * @param error the error which occured, a human readable string can be obtained using * AAudio_convertResultToText(error); * * @see EchoAudioEngine#errorCallback */ void errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error) { assert(userData); EchoAudioEngine *audioEngine = reinterpret_cast<EchoAudioEngine *>(userData); audioEngine->errorCallback(stream, error); } EchoAudioEngine::EchoAudioEngine() { sampleChannels_ = AUDIO_SAMPLE_CHANNELS; sampleFormat_ = AAUDIO_FORMAT_PCM_I16; bitsPerSample_ = SampleFormatToBpp(sampleFormat_); audioEffect_ = new AudioEffect(); } EchoAudioEngine::~EchoAudioEngine() { closeStream(recordingStream_); closeStream(playStream_); delete audioEffect_; } void EchoAudioEngine::setRecordingDeviceId(int32_t deviceId) { recordingDeviceId_ = deviceId; } void EchoAudioEngine::setPlaybackDeviceId(int32_t deviceId) { playbackDeviceId_ = deviceId; } void EchoAudioEngine::setEchoOn(bool isEchoOn) { if (isEchoOn != isEchoOn_) { isEchoOn_ = isEchoOn; if (isEchoOn) { startStreams(); } else { stopStreams(); } } } void EchoAudioEngine::startStreams() { // Note: The order of stream creation is important. We create the playback stream first, // then use properties from the playback stream (e.g. sample rate) to create the // recording stream. By matching the properties we should get the lowest latency path createPlaybackStream(); createRecordingStream(); // Now start the recording stream so that we can read from it during the playback dataCallback if (recordingStream_ != nullptr && playStream_ != nullptr) { startStream(recordingStream_); startStream(playStream_); playStreamUnderrunCount_ = AAudioStream_getXRunCount(playStream_); } else { LOGE("Failed to create recording and/or playback stream"); } } /** * Stops and closes the playback and recording streams */ void EchoAudioEngine::stopStreams() { if (recordingStream_ != nullptr) { stopStream(recordingStream_); closeStream(recordingStream_); recordingStream_ = nullptr; } if (playStream_ != nullptr) { stopStream(playStream_); closeStream(playStream_); playStream_ = nullptr; } } /** * Creates a stream builder which can be used to construct streams * @return a new stream builder object */ AAudioStreamBuilder *EchoAudioEngine::createStreamBuilder() { AAudioStreamBuilder *builder = nullptr; aaudio_result_t result = AAudio_createStreamBuilder(&builder); if (result != AAUDIO_OK && !builder) { LOGE("Error creating stream builder: %s", AAudio_convertResultToText(result)); } return builder; } /** * Creates an audio stream for recording. The audio device used will depend on recordingDeviceId_. * If the value is set to AAUDIO_UNSPECIFIED then the default recording device will be used. */ void EchoAudioEngine::createRecordingStream() { // To create a stream we use a stream builder. This allows us to specify all the parameters // for the stream prior to opening it AAudioStreamBuilder *builder = createStreamBuilder(); if (builder != nullptr) { setupRecordingStreamParameters(builder); // Now that the parameters are set up we can open the stream aaudio_result_t result = AAudioStreamBuilder_openStream(builder, &recordingStream_); if (result == AAUDIO_OK && recordingStream_ != nullptr) { // Check that the stream format matches what we requested if (sampleFormat_ != AAudioStream_getFormat(recordingStream_)) { LOGW("Recording stream format doesn't match what was requested (format: %d). " "Higher latency expected.", sampleFormat_); } PrintAudioStreamInfo(recordingStream_); } else { LOGE("Failed to create recording stream. Error: %s", AAudio_convertResultToText(result)); } AAudioStreamBuilder_delete(builder); } else { LOGE("Unable to obtain an AAudioStreamBuilder object"); } } /** * Creates an audio stream for playback. The audio device used will depend on playbackDeviceId_. * If the value is set to AAUDIO_UNSPECIFIED then the default playback device will be used. */ void EchoAudioEngine::createPlaybackStream() { AAudioStreamBuilder *builder = createStreamBuilder(); if (builder != nullptr) { setupPlaybackStreamParameters(builder); aaudio_result_t result = AAudioStreamBuilder_openStream(builder, &playStream_); if (result == AAUDIO_OK && playStream_ != nullptr) { // check that we got PCM_I16 format if (sampleFormat_ != AAudioStream_getFormat(playStream_)) { LOGW("Playback stream sample format is not PCM_I16, higher latency expected"); } sampleRate_ = AAudioStream_getSampleRate(playStream_); framesPerBurst_ = AAudioStream_getFramesPerBurst(playStream_); defaultBufSizeInFrames_ = AAudioStream_getBufferSizeInFrames(playStream_); // Set the buffer size to the burst size - this will give us the minimum possible latency AAudioStream_setBufferSizeInFrames(playStream_, framesPerBurst_); bufSizeInFrames_ = framesPerBurst_; PrintAudioStreamInfo(playStream_); } else { LOGE("Failed to create playback stream. Error: %s", AAudio_convertResultToText(result)); } AAudioStreamBuilder_delete(builder); } else { LOGE("Unable to obtain an AAudioStreamBuilder object"); } } /** * Sets the stream parameters which are specific to recording, including the sample rate which * is determined from the playback stream. * @param builder The recording stream builder */ void EchoAudioEngine::setupRecordingStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setDeviceId(builder, recordingDeviceId_); AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_INPUT); AAudioStreamBuilder_setSampleRate(builder, sampleRate_); setupCommonStreamParameters(builder); } /** * Sets the stream parameters which are specific to playback, including device id and the * dataCallback function, which must be set for low latency playback. * @param builder The playback stream builder */ void EchoAudioEngine::setupPlaybackStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setDeviceId(builder, playbackDeviceId_); AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT); // The :: here indicates that the function is in the global namespace // i.e. *not* EchoAudioEngine::dataCallback, but dataCallback defined at the top of this class AAudioStreamBuilder_setDataCallback(builder, ::dataCallback, this); setupCommonStreamParameters(builder); } /** * Set the stream parameters which are common to both recording and playback streams. * @param builder The playback or recording stream builder */ void EchoAudioEngine::setupCommonStreamParameters(AAudioStreamBuilder *builder) { AAudioStreamBuilder_setFormat(builder, sampleFormat_); AAudioStreamBuilder_setChannelCount(builder, sampleChannels_); // We request EXCLUSIVE mode since this will give us the lowest possible latency. // If EXCLUSIVE mode isn't available the builder will fall back to SHARED mode. AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE); AAudioStreamBuilder_setPerformanceMode(builder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setErrorCallback(builder, ::errorCallback, this); } void EchoAudioEngine::startStream(AAudioStream *stream) { aaudio_result_t result = AAudioStream_requestStart(stream); if (result != AAUDIO_OK) { LOGE("Error starting stream. %s", AAudio_convertResultToText(result)); } } void EchoAudioEngine::stopStream(AAudioStream *stream) { if (stream != nullptr) { aaudio_result_t result = AAudioStream_requestStop(stream); if (result != AAUDIO_OK) { LOGE("Error stopping stream. %s", AAudio_convertResultToText(result)); } } } /** * Close the stream. After the stream is closed it is deleted and subesequent AAudioStream_* calls * will return an error. AAudioStream_close() also checks and waits for any outstanding dataCallback * calls to complete before closing the stream. This means the application does not need to add * synchronization between the dataCallback function and the thread calling AAudioStream_close() * [the closing thread is the UI thread in this sample]. * @param stream the stream to close */ void EchoAudioEngine::closeStream(AAudioStream *stream) { if (stream != nullptr) { aaudio_result_t result = AAudioStream_close(stream); if (result != AAUDIO_OK) { LOGE("Error closing stream. %s", AAudio_convertResultToText(result)); } } } /** * @see the C method dataCallback at the top of this file */ aaudio_data_callback_result_t EchoAudioEngine::dataCallback(AAudioStream *stream, void *audioData, int32_t numFrames) { if (isEchoOn_) { // Tuning the buffer size for low latency... int32_t underRun = AAudioStream_getXRunCount(playStream_); if (underRun > playStreamUnderrunCount_) { /* Underrun happened since last callback: * try to increase the buffer size. */ playStreamUnderrunCount_ = underRun; aaudio_result_t actSize = AAudioStream_setBufferSizeInFrames( stream, bufSizeInFrames_ + framesPerBurst_); if (actSize > 0) { bufSizeInFrames_ = actSize; } else { LOGE("***** Output stream buffer tuning error: %s", AAudio_convertResultToText(actSize)); } } int32_t samplesPerFrame = sampleChannels_; // frameCount could be // < 0 : error code // >= 0 : actual value read from stream aaudio_result_t frameCount = 0; if (recordingStream_ != nullptr) { // If this is the first data callback we want to drain the recording buffer so we're getting // the most up to date data if (isFirstDataCallback_) { drainRecordingStream(audioData, numFrames); isFirstDataCallback_ = false; } frameCount = AAudioStream_read(recordingStream_, audioData, numFrames, static_cast<int64_t>(0)); audioEffect_->process(static_cast<int16_t *>(audioData), samplesPerFrame, frameCount); if (frameCount < 0) { LOGE("****AAudioStream_read() returns %s", AAudio_convertResultToText(frameCount)); frameCount = 0; // continue to play silent audio } } /** * If there's not enough audio data from input stream, fill the rest of buffer with * 0 (silence) and continue to loop */ numFrames -= frameCount; if (numFrames > 0) { memset(static_cast<int16_t *>(audioData) + frameCount * samplesPerFrame, 0, sizeof(int16_t) * numFrames * samplesPerFrame); } return AAUDIO_CALLBACK_RESULT_CONTINUE; } else { return AAUDIO_CALLBACK_RESULT_STOP; } } /** * Drain the recording stream of any existing data by reading from it until it's empty. This is * usually run to clear out any stale data before performing an actual read operation, thereby * obtaining the most recently recorded data and the best possbile recording latency. * * @param audioData A buffer which the existing data can be read into * @param numFrames The number of frames to read in a single read operation, this is typically the * size of `audioData`. */ void EchoAudioEngine::drainRecordingStream(void *audioData, int32_t numFrames) { aaudio_result_t clearedFrames = 0; do { clearedFrames = AAudioStream_read(recordingStream_, audioData, numFrames, 0); } while (clearedFrames > 0); } /** * See the C method errorCallback at the top of this file */ void EchoAudioEngine::errorCallback(AAudioStream *stream, aaudio_result_t error) { LOGI("errorCallback has result: %s", AAudio_convertResultToText(error)); aaudio_stream_state_t streamState = AAudioStream_getState(stream); if (streamState == AAUDIO_STREAM_STATE_DISCONNECTED) { // Handle stream restart on a separate thread std::function<void(void)> restartStreams = std::bind(&EchoAudioEngine::restartStreams, this); streamRestartThread_ = new std::thread(restartStreams); } } /** * Restart the streams. During the restart operation subsequent calls to this method will output * a warning. */ void EchoAudioEngine::restartStreams() { LOGI("Restarting streams"); if (restartingLock_.try_lock()) { stopStreams(); startStreams(); restartingLock_.unlock(); } else { LOGW("Restart stream operation already in progress - ignoring this request"); // We were unable to obtain the restarting lock which means the restart operation is currently // active. This is probably because we received successive "stream disconnected" events. // Internal issue b/63087953 } }
Fix memory leak. Close #71
Fix memory leak. Close #71
C++
apache-2.0
googlearchive/android-audio-high-performance,googlearchive/android-audio-high-performance,googlearchive/android-audio-high-performance
eb0dcb6ddfe6c44904803db1a2b6e556b9d5b49e
Sieve-of-Eratosthenes/main.cpp
Sieve-of-Eratosthenes/main.cpp
#include <iostream> #include <cassert> #include <cmath> using namespace std; int main ( int argc, char *argv[] ) { assert ( argc == 2 ); unsigned long maxnumber = atol(argv[1]); // Create the sieve end initialize all numbers as prime (true) bool *numbers = new bool[maxnumber+1]; for ( unsigned long n = 0; n<=maxnumber; ++n ) numbers[n] = true; // Set 0 and 1 as not-prime numbers[0] = false; numbers[1] = false; // Lets count the found primes unsigned long count = 0; for ( unsigned long n = 2; n<=maxnumber; ++n ) { if ( numbers[n] ) { // We found a new prime cout << n << " " << endl; // Count it ++count; // Delete all multiples for ( unsigned long m = 2*n; m<=maxnumber; m+=n ) numbers[m] = false; } } cout << endl; cout << "We found " << count << " primes." << endl; delete [] numbers; return 0; }
#include <iostream> #include <cassert> #include <cmath> using namespace std; int main ( int argc, char *argv[] ) { unsigned long maxnumber = 0; if ( 2 == argc ) maxnumber = atol(argv[1]); else { cout << "Enter the highest number to test: "; cin >> maxnumber; } // Create the sieve end initialize all numbers as prime (true) bool *numbers = new bool[maxnumber+1]; for ( unsigned long n = 0; n<=maxnumber; ++n ) numbers[n] = true; // Set 0 and 1 as not-prime numbers[0] = false; numbers[1] = false; // Lets count the found primes unsigned long count = 0; for ( unsigned long n = 2; n<=maxnumber; ++n ) { if ( numbers[n] ) { // We found a new prime cout << n << " " << endl; // Count it ++count; // Delete all multiples for ( unsigned long m = 2*n; m<=maxnumber; m+=n ) numbers[m] = false; } } cout << endl; cout << "We found " << count << " primes." << endl; delete [] numbers; return 0; }
Read max number either from command line argument or ask user.
Sieve-of-Eratosthenes: Read max number either from command line argument or ask user.
C++
mit
Shadouw/CPPToyProblems
9ae80f9c1c371b1ead12a86e136b17e8a5385b7f
src/cbang/socket/SocketDefaultImpl.cpp
src/cbang/socket/SocketDefaultImpl.cpp
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "SocketDefaultImpl.h" #include "Socket.h" #include "SocketSet.h" #include "SocketDebugger.h" #include <cbang/os/SystemUtilities.h> #include <cbang/os/SysError.h> #include <cbang/time/Timer.h> #include <cbang/log/Logger.h> #include <cbang/Exception.h> #include <cbang/String.h> #ifdef _WIN32 #include "Winsock.h" typedef int socklen_t; // Unix socket length #define MSG_DONTWAIT 0 #define MSG_NOSIGNAL 0 #define SHUT_RDWR 2 #ifndef EINPROGRESS #define EINPROGRESS WSAEWOULDBLOCK #endif #else // _WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 // WinSock invalid socket #define SOCKET_ERROR -1 // Basic WinSock error #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #endif #include <errno.h> #include <time.h> #include <string.h> using namespace std; using namespace cb; SocketDefaultImpl::SocketDefaultImpl(Socket *parent) : SocketImpl(parent), socket(INVALID_SOCKET), blocking(true), connected(false) { Socket::initialize(); } bool SocketDefaultImpl::isOpen() const {return socket != INVALID_SOCKET;} void SocketDefaultImpl::open() { if (isOpen()) THROW("Socket already open"); if ((socket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) THROW("Failed to create socket"); } void SocketDefaultImpl::setReuseAddr(bool reuse) { if (!isOpen()) open(); #ifdef _WIN32 BOOL opt = reuse; #else int opt = reuse; #endif SysError::clear(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt))) THROW("Failed to set reuse addr: " << SysError()); } void SocketDefaultImpl::setBlocking(bool blocking) { if (!isOpen()) open(); #ifdef _WIN32 u_long on = blocking ? 0 : 1; ioctlsocket((socket_t)socket, FIONBIO, &on); #else int opts = fcntl(socket, F_GETFL); if (opts >= 0) { if (blocking) opts &= ~O_NONBLOCK; else opts |= O_NONBLOCK; fcntl(socket, F_SETFL, opts); } #endif this->blocking = blocking; } void SocketDefaultImpl::setKeepAlive(bool keepAlive) { if (!isOpen()) open(); #ifdef _WIN32 BOOL opt = keepAlive; #else int opt = keepAlive; #endif SysError::clear(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, sizeof(opt))) THROW("Failed to set socket keep alive: " << SysError()); } void SocketDefaultImpl::setSendBuffer(int size) { if (!isOpen()) open(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) THROW("Could not set send buffer to " << size << ": " << SysError()); } void SocketDefaultImpl::setReceiveBuffer(int size) { if (!isOpen()) open(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))) THROW("Could not set receive buffer to " << size << ": " << SysError()); } void SocketDefaultImpl::setSendTimeout(double timeout) { if (!isOpen()) open(); #ifdef _WIN32 DWORD t = 1000 * timeout; // ms #else struct timeval t = Timer::toTimeVal(timeout); #endif if (setsockopt((socket_t)socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t))) THROW("Could not set send timeout to " << timeout << ": " << SysError()); } void SocketDefaultImpl::setReceiveTimeout(double timeout) { if (!isOpen()) open(); #ifdef _WIN32 DWORD t = 1000 * timeout; // ms #else struct timeval t = Timer::toTimeVal(timeout); #endif if (setsockopt((socket_t)socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t))) THROW("Could not set receive timeout to " << timeout << ": " << SysError()); } void SocketDefaultImpl::bind(const IPAddress &ip) { if (!isOpen()) open(); struct sockaddr_in addr; memset((void *)&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(ip.getPort()); addr.sin_addr.s_addr = htonl((unsigned)ip ? (unsigned)ip : INADDR_ANY); SysError::clear(); if (::bind((socket_t)socket, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) THROW("Could not bind socket to " << ip << ": " << SysError()); } void SocketDefaultImpl::listen(int backlog) { if (!isOpen()) open(); SysError::clear(); if (::listen((socket_t)socket, backlog == -1 ? SOMAXCONN : backlog) == SOCKET_ERROR) THROW("listen failed"); #ifndef _WIN32 fcntl(socket, F_SETFD, FD_CLOEXEC); #endif } SmartPointer<Socket> SocketDefaultImpl::accept(IPAddress *ip) { if (!isOpen()) open(); SmartPointer<Socket> a = createSocket(); SocketDefaultImpl *aSock = dynamic_cast<SocketDefaultImpl *>(a->getImpl()); struct sockaddr_in addr; socklen_t len = sizeof(addr); if ((aSock->socket = ::accept((socket_t)socket, (struct sockaddr *)&addr, &len)) != INVALID_SOCKET) { IPAddress inAddr = ntohl(addr.sin_addr.s_addr); inAddr.setPort(ntohs(addr.sin_port)); if (ip) *ip = inAddr; aSock->connected = true; aSock->capture(inAddr, true); aSock->setBlocking(blocking); LOG_DEBUG(5, "accept() new connection"); return a; } return 0; } void SocketDefaultImpl::connect(const IPAddress &ip) { if (!isOpen()) open(); LOG_INFO(3, "Connecting to " << ip); try { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons((short)ip.getPort()); sin.sin_addr.s_addr = htonl(ip); SysError::clear(); if (::connect((socket_t)socket, (struct sockaddr *)&sin, sizeof(sin)) == -1) if (SysError::get() != EINPROGRESS) THROW("Failed to connect to " << ip << ": " << SysError()); connected = true; capture(ip, false); } catch (const Exception &e) { close(); throw; } } streamsize SocketDefaultImpl::write(const char *data, streamsize length, unsigned flags) { if (!isOpen()) THROW("Socket not open"); if (!length) return 0; int f = MSG_NOSIGNAL; if (flags & Socket::NONBLOCKING) f |= MSG_DONTWAIT; SysError::clear(); streamsize ret = send((socket_t)socket, data, length, f); int err = SysError::get(); LOG_DEBUG(5, "send() = " << ret << " of " << length); if (ret < 0) { #ifdef _WIN32 // NOTE: send() can return -1 even when there is no error if (!err || err == WSAEWOULDBLOCK || err == WSAENOBUFS) return 0; #else if (err == EAGAIN) return 0; #endif THROW("Send error: " << err << ": " << SysError(err)); } if (!out.isNull()) out->write(data, ret); // Capture return ret; } streamsize SocketDefaultImpl::read(char *data, streamsize length, unsigned flags) { if (!isOpen()) THROW("Socket not open"); if (!length) return 0; int f = MSG_NOSIGNAL; if (flags & Socket::NONBLOCKING) f |= MSG_DONTWAIT; if (flags & Socket::PEEK) f |= MSG_PEEK; SysError::clear(); streamsize ret = recv((socket_t)socket, data, length, f); int err = SysError::get(); LOG_DEBUG(5, "recv() = " << ret << " of " << length); if (!ret) return -1; // Orderly shutdown if (ret < 0) { #ifdef _WIN32 // NOTE: Windows can return -1 even when there is no error if (!err || err == WSAEWOULDBLOCK || err == WSAETIMEDOUT) return 0; #else if (err == ECONNRESET) return -1; if (err == EAGAIN || err == EWOULDBLOCK) return 0; #endif THROW("Receive error: " << err << ": " << SysError(err)); } if (!in.isNull()) in->write(data, ret); // Capture return ret; } void SocketDefaultImpl::close() { if (!isOpen()) return; // If socket was connected call shutdown() if (connected) { shutdown(socket, SHUT_RDWR); connected = false; } #ifdef _WIN32 closesocket((SOCKET)socket); #else ::close(socket); #endif in = out = 0; // Flush capture socket = INVALID_SOCKET; } void SocketDefaultImpl::set(socket_t socket) { close(); this->socket = socket; } socket_t SocketDefaultImpl::adopt() { socket_t s = socket; in = out = 0; // Flush capture socket = INVALID_SOCKET; connected = false; return s; } void SocketDefaultImpl::capture(const IPAddress &addr, bool incoming) { SocketDebugger &debugger = SocketDebugger::instance(); if (!debugger.getCapture()) return; const string &dir = debugger.getCaptureDirectory(); SystemUtilities::ensureDirectory(dir); uint64_t id = debugger.getNextConnectionID(); string prefix = dir + "/" + String(id) + "-" + (incoming ? "in" : "out") + "-" + addr.toString() + "-"; #ifdef _WIN32 prefix = String::replace(prefix, ':', '-'); #endif string request = prefix + "request.dat"; string response = prefix + "response.dat"; in = SystemUtilities::open(incoming ? request : response, ios::out | ios::trunc); out = SystemUtilities::open(incoming ? response : request, ios::out | ios::trunc); }
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "SocketDefaultImpl.h" #include "Socket.h" #include "SocketSet.h" #include "SocketDebugger.h" #include <cbang/os/SystemUtilities.h> #include <cbang/os/SysError.h> #include <cbang/time/Timer.h> #include <cbang/log/Logger.h> #include <cbang/Exception.h> #include <cbang/String.h> #ifdef _WIN32 #include "Winsock.h" typedef int socklen_t; // Unix socket length #define MSG_DONTWAIT 0 #define MSG_NOSIGNAL 0 #define SHUT_RDWR 2 #define SOCKET_INPROGRESS WSAEWOULDBLOCK #else // _WIN32 #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 // WinSock invalid socket #define SOCKET_ERROR -1 // Basic WinSock error #define SOCKET_INPROGRESS EINPROGRESS #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif #endif #include <errno.h> #include <time.h> #include <string.h> using namespace std; using namespace cb; SocketDefaultImpl::SocketDefaultImpl(Socket *parent) : SocketImpl(parent), socket(INVALID_SOCKET), blocking(true), connected(false) { Socket::initialize(); } bool SocketDefaultImpl::isOpen() const {return socket != INVALID_SOCKET;} void SocketDefaultImpl::open() { if (isOpen()) THROW("Socket already open"); if ((socket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) THROW("Failed to create socket"); } void SocketDefaultImpl::setReuseAddr(bool reuse) { if (!isOpen()) open(); #ifdef _WIN32 BOOL opt = reuse; #else int opt = reuse; #endif SysError::clear(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt))) THROW("Failed to set reuse addr: " << SysError()); } void SocketDefaultImpl::setBlocking(bool blocking) { if (!isOpen()) open(); #ifdef _WIN32 u_long on = blocking ? 0 : 1; ioctlsocket((socket_t)socket, FIONBIO, &on); #else int opts = fcntl(socket, F_GETFL); if (opts >= 0) { if (blocking) opts &= ~O_NONBLOCK; else opts |= O_NONBLOCK; fcntl(socket, F_SETFL, opts); } #endif this->blocking = blocking; } void SocketDefaultImpl::setKeepAlive(bool keepAlive) { if (!isOpen()) open(); #ifdef _WIN32 BOOL opt = keepAlive; #else int opt = keepAlive; #endif SysError::clear(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt, sizeof(opt))) THROW("Failed to set socket keep alive: " << SysError()); } void SocketDefaultImpl::setSendBuffer(int size) { if (!isOpen()) open(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_SNDBUF, (char *)&size, sizeof(size))) THROW("Could not set send buffer to " << size << ": " << SysError()); } void SocketDefaultImpl::setReceiveBuffer(int size) { if (!isOpen()) open(); if (setsockopt((socket_t)socket, SOL_SOCKET, SO_RCVBUF, (char *)&size, sizeof(size))) THROW("Could not set receive buffer to " << size << ": " << SysError()); } void SocketDefaultImpl::setSendTimeout(double timeout) { if (!isOpen()) open(); #ifdef _WIN32 DWORD t = 1000 * timeout; // ms #else struct timeval t = Timer::toTimeVal(timeout); #endif if (setsockopt((socket_t)socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&t, sizeof(t))) THROW("Could not set send timeout to " << timeout << ": " << SysError()); } void SocketDefaultImpl::setReceiveTimeout(double timeout) { if (!isOpen()) open(); #ifdef _WIN32 DWORD t = 1000 * timeout; // ms #else struct timeval t = Timer::toTimeVal(timeout); #endif if (setsockopt((socket_t)socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&t, sizeof(t))) THROW("Could not set receive timeout to " << timeout << ": " << SysError()); } void SocketDefaultImpl::bind(const IPAddress &ip) { if (!isOpen()) open(); struct sockaddr_in addr; memset((void *)&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(ip.getPort()); addr.sin_addr.s_addr = htonl((unsigned)ip ? (unsigned)ip : INADDR_ANY); SysError::clear(); if (::bind((socket_t)socket, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) THROW("Could not bind socket to " << ip << ": " << SysError()); } void SocketDefaultImpl::listen(int backlog) { if (!isOpen()) open(); SysError::clear(); if (::listen((socket_t)socket, backlog == -1 ? SOMAXCONN : backlog) == SOCKET_ERROR) THROW("listen failed"); #ifndef _WIN32 fcntl(socket, F_SETFD, FD_CLOEXEC); #endif } SmartPointer<Socket> SocketDefaultImpl::accept(IPAddress *ip) { if (!isOpen()) open(); SmartPointer<Socket> a = createSocket(); SocketDefaultImpl *aSock = dynamic_cast<SocketDefaultImpl *>(a->getImpl()); struct sockaddr_in addr; socklen_t len = sizeof(addr); if ((aSock->socket = ::accept((socket_t)socket, (struct sockaddr *)&addr, &len)) != INVALID_SOCKET) { IPAddress inAddr = ntohl(addr.sin_addr.s_addr); inAddr.setPort(ntohs(addr.sin_port)); if (ip) *ip = inAddr; aSock->connected = true; aSock->capture(inAddr, true); aSock->setBlocking(blocking); LOG_DEBUG(5, "accept() new connection"); return a; } return 0; } void SocketDefaultImpl::connect(const IPAddress &ip) { if (!isOpen()) open(); LOG_INFO(3, "Connecting to " << ip); try { struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons((short)ip.getPort()); sin.sin_addr.s_addr = htonl(ip); SysError::clear(); if (::connect((socket_t)socket, (struct sockaddr *)&sin, sizeof(sin)) == -1) if (SysError::get() != SOCKET_INPROGRESS) THROW("Failed to connect to " << ip << ": " << SysError()); connected = true; capture(ip, false); } catch (const Exception &e) { close(); throw; } } streamsize SocketDefaultImpl::write(const char *data, streamsize length, unsigned flags) { if (!isOpen()) THROW("Socket not open"); if (!length) return 0; int f = MSG_NOSIGNAL; if (flags & Socket::NONBLOCKING) f |= MSG_DONTWAIT; SysError::clear(); streamsize ret = send((socket_t)socket, data, length, f); int err = SysError::get(); LOG_DEBUG(5, "send() = " << ret << " of " << length); if (ret < 0) { #ifdef _WIN32 // NOTE: send() can return -1 even when there is no error if (!err || err == WSAEWOULDBLOCK || err == WSAENOBUFS) return 0; #else if (err == EAGAIN) return 0; #endif THROW("Send error: " << err << ": " << SysError(err)); } if (!out.isNull()) out->write(data, ret); // Capture return ret; } streamsize SocketDefaultImpl::read(char *data, streamsize length, unsigned flags) { if (!isOpen()) THROW("Socket not open"); if (!length) return 0; int f = MSG_NOSIGNAL; if (flags & Socket::NONBLOCKING) f |= MSG_DONTWAIT; if (flags & Socket::PEEK) f |= MSG_PEEK; SysError::clear(); streamsize ret = recv((socket_t)socket, data, length, f); int err = SysError::get(); LOG_DEBUG(5, "recv() = " << ret << " of " << length); if (!ret) return -1; // Orderly shutdown if (ret < 0) { #ifdef _WIN32 // NOTE: Windows can return -1 even when there is no error if (!err || err == WSAEWOULDBLOCK || err == WSAETIMEDOUT) return 0; #else if (err == ECONNRESET) return -1; if (err == EAGAIN || err == EWOULDBLOCK) return 0; #endif THROW("Receive error: " << err << ": " << SysError(err)); } if (!in.isNull()) in->write(data, ret); // Capture return ret; } void SocketDefaultImpl::close() { if (!isOpen()) return; // If socket was connected call shutdown() if (connected) { shutdown(socket, SHUT_RDWR); connected = false; } #ifdef _WIN32 closesocket((SOCKET)socket); #else ::close(socket); #endif in = out = 0; // Flush capture socket = INVALID_SOCKET; } void SocketDefaultImpl::set(socket_t socket) { close(); this->socket = socket; } socket_t SocketDefaultImpl::adopt() { socket_t s = socket; in = out = 0; // Flush capture socket = INVALID_SOCKET; connected = false; return s; } void SocketDefaultImpl::capture(const IPAddress &addr, bool incoming) { SocketDebugger &debugger = SocketDebugger::instance(); if (!debugger.getCapture()) return; const string &dir = debugger.getCaptureDirectory(); SystemUtilities::ensureDirectory(dir); uint64_t id = debugger.getNextConnectionID(); string prefix = dir + "/" + String(id) + "-" + (incoming ? "in" : "out") + "-" + addr.toString() + "-"; #ifdef _WIN32 prefix = String::replace(prefix, ':', '-'); #endif string request = prefix + "request.dat"; string response = prefix + "response.dat"; in = SystemUtilities::open(incoming ? request : response, ios::out | ios::trunc); out = SystemUtilities::open(incoming ? response : request, ios::out | ios::trunc); }
Fix Windows non-blocking connect problem
Fix Windows non-blocking connect problem
C++
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
5348f1acc5f66f19612d1b24d44ed431f7a5992e
chrome/browser/chromeos/login/screen_locker_browsertest.cc
chrome/browser/chromeos/login/screen_locker_browsertest.cc
// Copyright (c) 2011 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/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/browser/automation/ui_controls.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/cros/mock_input_method_library.h" #include "chrome/browser/chromeos/cros/mock_screen_lock_library.h" #include "chrome/browser/chromeos/login/mock_authenticator.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/screen_locker_tester.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/controls/textfield/textfield.h" #include "views/window/window_gtk.h" namespace { // An object that wait for lock state and fullscreen state. class Waiter : public NotificationObserver { public: explicit Waiter(Browser* browser) : browser_(browser), running_(false) { registrar_.Add(this, NotificationType::SCREEN_LOCK_STATE_CHANGED, NotificationService::AllSources()); handler_id_ = g_signal_connect( G_OBJECT(browser_->window()->GetNativeHandle()), "window-state-event", G_CALLBACK(OnWindowStateEventThunk), this); } ~Waiter() { g_signal_handler_disconnect( G_OBJECT(browser_->window()->GetNativeHandle()), handler_id_); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED); if (running_) MessageLoop::current()->Quit(); } // Wait until the two conditions are met. void Wait(bool locker_state, bool fullscreen) { running_ = true; scoped_ptr<chromeos::test::ScreenLockerTester> tester(chromeos::ScreenLocker::GetTester()); while (tester->IsLocked() != locker_state || browser_->window()->IsFullscreen() != fullscreen) { ui_test_utils::RunMessageLoop(); } // Make sure all pending tasks are executed. ui_test_utils::RunAllPendingInMessageLoop(); running_ = false; } CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent, GdkEventWindowState*); private: Browser* browser_; gulong handler_id_; NotificationRegistrar registrar_; // Are we currently running the message loop? bool running_; DISALLOW_COPY_AND_ASSIGN(Waiter); }; gboolean Waiter::OnWindowStateEvent(GtkWidget* widget, GdkEventWindowState* event) { MessageLoop::current()->Quit(); return false; } } // namespace namespace chromeos { class ScreenLockerTest : public CrosInProcessBrowserTest { public: ScreenLockerTest() : mock_screen_lock_library_(NULL), mock_input_method_library_(NULL) { } protected: MockScreenLockLibrary *mock_screen_lock_library_; MockInputMethodLibrary *mock_input_method_library_; // Test the no password mode with different unlock scheme given by // |unlock| function. void TestNoPassword(void (unlock)(views::Widget*)) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->OffTheRecordUserLoggedIn(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); EXPECT_TRUE(tester->IsLocked()); tester->InjectMockAuthenticator("", ""); unlock(tester->GetWidget()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from PowerManager (via SessionManager). ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void LockScreenWithUser(test::ScreenLockerTester* tester, const std::string& user) { UserManager::Get()->UserLoggedIn(user); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); if (!tester->IsLocked()) { ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); } EXPECT_TRUE(tester->IsLocked()); } private: virtual void SetUpInProcessBrowserTestFixture() { cros_mock_->InitStatusAreaMocks(); cros_mock_->InitMockScreenLockLibrary(); mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library(); mock_input_method_library_ = cros_mock_->mock_input_method_library(); EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted()) .Times(1) .RetiresOnSaturation(); // Expectations for the status are on the screen lock window. cros_mock_->SetStatusAreaMocksExpectations(); // Expectations for the status area on the browser window. cros_mock_->SetStatusAreaMocksExpectations(); } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kLoginProfile, "user"); command_line->AppendSwitch(switches::kNoFirstRun); } DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest); }; IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) { EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods()) .Times(1) .WillRepeatedly((testing::Return(0))) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->UserLoggedIn("user"); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); // Test to make sure that the widget is actually appearing and is of // reasonable size, preventing a regression of // http://code.google.com/p/chromium-os/issues/detail?id=5987 gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds(); EXPECT_GT(lock_bounds.width(), 10); EXPECT_GT(lock_bounds.height(), 10); tester->InjectMockAuthenticator("user", "pass"); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("fail"); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); // Successful authentication simply send a unlock request to PowerManager. EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from PowerManager (via SessionManager). // TODO(oshima): Find out better way to handle this in mock. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); { Waiter waiter(browser()); browser()->ToggleFullscreenMode(); waiter.Wait(false /* not locked */, true /* full screen */); EXPECT_TRUE(browser()->window()->IsFullscreen()); EXPECT_FALSE(tester->IsLocked()); } { Waiter waiter(browser()); UserManager::Get()->UserLoggedIn("user"); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); waiter.Wait(true /* locked */, false /* full screen */); EXPECT_FALSE(browser()->window()->IsFullscreen()); EXPECT_TRUE(tester->IsLocked()); } tester->InjectMockAuthenticator("user", "pass"); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void MouseMove(views::Widget* widget) { ui_controls::SendMouseMove(10, 10); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) { TestNoPassword(MouseMove); } void MouseClick(views::Widget* widget) { ui_controls::SendMouseClick(ui_controls::RIGHT); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseClick) { TestNoPassword(MouseClick); } void KeyPress(views::Widget* widget) { ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()), ui::VKEY_SPACE, false, false, false, false); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) { TestNoPassword(KeyPress); } // See http://crbug.com/78764. IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(2) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), "user"); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); // Calling Show again simply send LockCompleted signal. ScreenLocker::Show(); EXPECT_TRUE(tester->IsLocked()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } // See http://crbug.com/78764. IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), "user"); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); tester->SetPassword("password"); EXPECT_EQ("password", tester->GetPassword()); // Escape clears the password. ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()), ui::VKEY_ESCAPE, false, false, false, false); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_EQ("", tester->GetPassword()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } } // namespace chromeos
// Copyright (c) 2011 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/command_line.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "chrome/browser/automation/ui_controls.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/cros/mock_input_method_library.h" #include "chrome/browser/chromeos/cros/mock_screen_lock_library.h" #include "chrome/browser/chromeos/login/mock_authenticator.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/screen_locker_tester.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/browser_dialogs.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/controls/textfield/textfield.h" #include "views/window/window_gtk.h" namespace { // An object that wait for lock state and fullscreen state. class Waiter : public NotificationObserver { public: explicit Waiter(Browser* browser) : browser_(browser), running_(false) { registrar_.Add(this, NotificationType::SCREEN_LOCK_STATE_CHANGED, NotificationService::AllSources()); handler_id_ = g_signal_connect( G_OBJECT(browser_->window()->GetNativeHandle()), "window-state-event", G_CALLBACK(OnWindowStateEventThunk), this); } ~Waiter() { g_signal_handler_disconnect( G_OBJECT(browser_->window()->GetNativeHandle()), handler_id_); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED); if (running_) MessageLoop::current()->Quit(); } // Wait until the two conditions are met. void Wait(bool locker_state, bool fullscreen) { running_ = true; scoped_ptr<chromeos::test::ScreenLockerTester> tester(chromeos::ScreenLocker::GetTester()); while (tester->IsLocked() != locker_state || browser_->window()->IsFullscreen() != fullscreen) { ui_test_utils::RunMessageLoop(); } // Make sure all pending tasks are executed. ui_test_utils::RunAllPendingInMessageLoop(); running_ = false; } CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent, GdkEventWindowState*); private: Browser* browser_; gulong handler_id_; NotificationRegistrar registrar_; // Are we currently running the message loop? bool running_; DISALLOW_COPY_AND_ASSIGN(Waiter); }; gboolean Waiter::OnWindowStateEvent(GtkWidget* widget, GdkEventWindowState* event) { MessageLoop::current()->Quit(); return false; } } // namespace namespace chromeos { class ScreenLockerTest : public CrosInProcessBrowserTest { public: ScreenLockerTest() : mock_screen_lock_library_(NULL), mock_input_method_library_(NULL) { } protected: MockScreenLockLibrary *mock_screen_lock_library_; MockInputMethodLibrary *mock_input_method_library_; // Test the no password mode with different unlock scheme given by // |unlock| function. void TestNoPassword(void (unlock)(views::Widget*)) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->OffTheRecordUserLoggedIn(); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); EXPECT_TRUE(tester->IsLocked()); tester->InjectMockAuthenticator("", ""); unlock(tester->GetWidget()); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from PowerManager (via SessionManager). ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void LockScreenWithUser(test::ScreenLockerTester* tester, const std::string& user) { UserManager::Get()->UserLoggedIn(user); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); if (!tester->IsLocked()) { ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); } EXPECT_TRUE(tester->IsLocked()); } private: virtual void SetUpInProcessBrowserTestFixture() { cros_mock_->InitStatusAreaMocks(); cros_mock_->InitMockScreenLockLibrary(); mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library(); mock_input_method_library_ = cros_mock_->mock_input_method_library(); EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted()) .Times(1) .RetiresOnSaturation(); // Expectations for the status are on the screen lock window. cros_mock_->SetStatusAreaMocksExpectations(); // Expectations for the status area on the browser window. cros_mock_->SetStatusAreaMocksExpectations(); } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitchASCII(switches::kLoginProfile, "user"); command_line->AppendSwitch(switches::kNoFirstRun); } DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest); }; IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) { EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods()) .Times(1) .WillRepeatedly((testing::Return(0))) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); UserManager::Get()->UserLoggedIn("user"); ScreenLocker::Show(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); tester->EmulateWindowManagerReady(); if (!chromeos::ScreenLocker::GetTester()->IsLocked()) ui_test_utils::WaitForNotification( NotificationType::SCREEN_LOCK_STATE_CHANGED); // Test to make sure that the widget is actually appearing and is of // reasonable size, preventing a regression of // http://code.google.com/p/chromium-os/issues/detail?id=5987 gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds(); EXPECT_GT(lock_bounds.width(), 10); EXPECT_GT(lock_bounds.height(), 10); tester->InjectMockAuthenticator("user", "pass"); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("fail"); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_TRUE(tester->IsLocked()); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); // Successful authentication simply send a unlock request to PowerManager. EXPECT_TRUE(tester->IsLocked()); // Emulate LockScreen request from PowerManager (via SessionManager). // TODO(oshima): Find out better way to handle this in mock. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested()) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); { Waiter waiter(browser()); browser()->ToggleFullscreenMode(); waiter.Wait(false /* not locked */, true /* full screen */); EXPECT_TRUE(browser()->window()->IsFullscreen()); EXPECT_FALSE(tester->IsLocked()); } { Waiter waiter(browser()); UserManager::Get()->UserLoggedIn("user"); ScreenLocker::Show(); tester->EmulateWindowManagerReady(); waiter.Wait(true /* locked */, false /* full screen */); EXPECT_FALSE(browser()->window()->IsFullscreen()); EXPECT_TRUE(tester->IsLocked()); } tester->InjectMockAuthenticator("user", "pass"); tester->EnterPassword("pass"); ui_test_utils::RunAllPendingInMessageLoop(); ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } void MouseMove(views::Widget* widget) { ui_controls::SendMouseMove(10, 10); } // Crashes on chromeos. http://crbug.com/79164 IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) { TestNoPassword(MouseMove); } void MouseClick(views::Widget* widget) { ui_controls::SendMouseClick(ui_controls::RIGHT); } // Crashes on chromeos. http://crbug.com/79164 IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseClick) { TestNoPassword(MouseClick); } void KeyPress(views::Widget* widget) { ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()), ui::VKEY_SPACE, false, false, false, false); } // Crashes on chromeos. http://crbug.com/79164 IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) { TestNoPassword(KeyPress); } // See http://crbug.com/78764. IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(2) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), "user"); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); // Calling Show again simply send LockCompleted signal. ScreenLocker::Show(); EXPECT_TRUE(tester->IsLocked()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } // See http://crbug.com/78764. IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) { EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted()) .Times(1) .RetiresOnSaturation(); scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester()); LockScreenWithUser(tester.get(), "user"); // Ensure there's a profile or this test crashes. ProfileManager::GetDefaultProfile(); tester->SetPassword("password"); EXPECT_EQ("password", tester->GetPassword()); // Escape clears the password. ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()), ui::VKEY_ESCAPE, false, false, false, false); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_EQ("", tester->GetPassword()); // Close the locker to match expectations. ScreenLocker::Hide(); ui_test_utils::RunAllPendingInMessageLoop(); EXPECT_FALSE(tester->IsLocked()); } } // namespace chromeos
Add documentation for why tests are disabled per http://www.chromium.org/developers/tree-sheriffs/sheriff-details-chromium/handling-a-failing-test
Add documentation for why tests are disabled per http://www.chromium.org/developers/tree-sheriffs/sheriff-details-chromium/handling-a-failing-test BUG=79164 TEST=none Review URL: http://codereview.chromium.org/6825077 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@81264 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
17c3fa1402696861f2f1b238c4987a94310b85d2
chrome/browser/ui/panels/panel_browser_view_browsertest.cc
chrome/browser/ui/panels/panel_browser_view_browsertest.cc
// Copyright (c) 2011 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/command_line.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_browser_frame_view.h" #include "chrome/browser/ui/panels/panel_browser_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/in_process_browser_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/controls/button/image_button.h" #include "views/controls/button/menu_button.h" #include "views/controls/label.h" #include "views/controls/menu/menu_2.h" class PanelBrowserViewTest : public InProcessBrowserTest { public: PanelBrowserViewTest() : InProcessBrowserTest() { } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitch(switches::kEnablePanels); } protected: PanelBrowserView* CreatePanelBrowserView(const std::string& panel_name) { Browser* panel_browser = Browser::CreateForApp(Browser::TYPE_PANEL, panel_name, gfx::Size(), browser()->profile()); panel_browser->window()->Show(); return static_cast<PanelBrowserView*>( static_cast<Panel*>(panel_browser->window())->browser_window()); } void ValidateOptionsMenuItems( ui::SimpleMenuModel* options_menu_contents, size_t count, int* ids) { ASSERT_TRUE(options_menu_contents); EXPECT_EQ(static_cast<int>(count), options_menu_contents->GetItemCount()); for (size_t i = 0; i < count; ++i) { if (ids[i] == -1) { EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, options_menu_contents->GetTypeAt(i)); } else { EXPECT_EQ(ids[i] , options_menu_contents->GetCommandIdAt(i)); } } } void ValidateDragging(PanelBrowserView* browser_view, int delta_x, int delta_y, int expected_delta_x_after_release) { gfx::Rect bounds_before_press = browser_view->panel()->GetRestoredBounds(); views::MouseEvent pressed(ui::ET_MOUSE_PRESSED, bounds_before_press.x(), bounds_before_press.y(), ui::EF_LEFT_BUTTON_DOWN); browser_view->OnTitleBarMousePressed(pressed); gfx::Rect bounds_after_press = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press, bounds_after_press); // If both delta_x and delta_y are 0, we perform no dragging. if (delta_x || delta_y) { views::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, bounds_before_press.x() + delta_x, bounds_before_press.y() + delta_y, ui::EF_LEFT_BUTTON_DOWN); browser_view->OnTitleBarMouseDragged(dragged); gfx::Rect bounds_after_drag = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press.x() + delta_x, bounds_after_drag.x()); EXPECT_EQ(bounds_before_press.y(), bounds_after_drag.y()); EXPECT_EQ(bounds_before_press.width(), bounds_after_drag.width()); EXPECT_EQ(bounds_before_press.height(), bounds_after_drag.height()); } views::MouseEvent released(ui::ET_MOUSE_RELEASED, 0, 0, 0); browser_view->OnTitleBarMouseReleased(released); gfx::Rect bounds_after_release = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press.x() + expected_delta_x_after_release, bounds_after_release.x()); EXPECT_EQ(bounds_before_press.y(), bounds_after_release.y()); EXPECT_EQ(bounds_before_press.width(), bounds_after_release.width()); EXPECT_EQ(bounds_before_press.height(), bounds_after_release.height()); } }; // Panel is not supported for Linux view yet. #if !defined(OS_LINUX) || !defined(TOOLKIT_VIEWS) IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, CreatePanel) { PanelBrowserFrameView* frame_view = CreatePanelBrowserView("PanelTest")->GetFrameView(); // We should have icon, text, options button and close button. EXPECT_EQ(4, frame_view->child_count()); EXPECT_TRUE(frame_view->Contains(frame_view->title_icon_)); EXPECT_TRUE(frame_view->Contains(frame_view->title_label_)); EXPECT_TRUE(frame_view->Contains(frame_view->options_button_)); EXPECT_TRUE(frame_view->Contains(frame_view->close_button_)); // These controls should be visible. EXPECT_TRUE(frame_view->title_icon_->IsVisible()); EXPECT_TRUE(frame_view->title_label_->IsVisible()); EXPECT_TRUE(frame_view->options_button_->IsVisible()); EXPECT_TRUE(frame_view->close_button_->IsVisible()); // Validate their layouts. int title_bar_height = frame_view->NonClientTopBorderHeight() - frame_view->NonClientBorderThickness(); EXPECT_GT(frame_view->title_icon_->width(), 0); EXPECT_GT(frame_view->title_icon_->height(), 0); EXPECT_LT(frame_view->title_icon_->height(), title_bar_height); EXPECT_GT(frame_view->title_label_->width(), 0); EXPECT_GT(frame_view->title_label_->height(), 0); EXPECT_LT(frame_view->title_label_->height(), title_bar_height); EXPECT_GT(frame_view->options_button_->width(), 0); EXPECT_GT(frame_view->options_button_->height(), 0); EXPECT_LT(frame_view->options_button_->height(), title_bar_height); EXPECT_GT(frame_view->close_button_->width(), 0); EXPECT_GT(frame_view->close_button_->height(), 0); EXPECT_LT(frame_view->close_button_->height(), title_bar_height); EXPECT_LT(frame_view->title_icon_->x() + frame_view->title_icon_->width(), frame_view->title_label_->x()); EXPECT_LT(frame_view->title_label_->x() + frame_view->title_label_->width(), frame_view->options_button_->x()); EXPECT_LT( frame_view->options_button_->x() + frame_view->options_button_->width(), frame_view->close_button_->x()); // Validate that the controls should be updated when the activation state is // changed. frame_view->UpdateControlStyles(PanelBrowserFrameView::PAINT_AS_ACTIVE); SkColor title_label_color1 = frame_view->title_label_->GetColor(); frame_view->UpdateControlStyles(PanelBrowserFrameView::PAINT_AS_INACTIVE); SkColor title_label_color2 = frame_view->title_label_->GetColor(); EXPECT_NE(title_label_color1, title_label_color2); } IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, CreateOrUpdateOptionsMenu) { int single_panel_menu[] = { PanelBrowserFrameView::COMMAND_ABOUT }; size_t single_panel_menu_count = arraysize(single_panel_menu); int multi_panel_menu_for_minimize[] = { PanelBrowserFrameView::COMMAND_MINIMIZE_ALL, PanelBrowserFrameView::COMMAND_CLOSE_ALL, -1, // Separator PanelBrowserFrameView::COMMAND_ABOUT }; size_t multi_panel_menu_for_minimize_count = arraysize(multi_panel_menu_for_minimize); int multi_panel_menu_for_restore[] = { PanelBrowserFrameView::COMMAND_RESTORE_ALL, PanelBrowserFrameView::COMMAND_CLOSE_ALL, -1, // Separator PanelBrowserFrameView::COMMAND_ABOUT }; size_t multi_panel_menu_for_restore_count = arraysize(multi_panel_menu_for_restore); // With only one panel, we should only have 1 menu item: "About this panel". PanelBrowserFrameView* frame_view1 = CreatePanelBrowserView("PanelTest1")->GetFrameView(); frame_view1->CreateOrUpdateOptionsMenu(); ASSERT_TRUE(frame_view1->options_menu_.get()); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), single_panel_menu_count, single_panel_menu); // With another panel, we should have 4 menu items, including separator. PanelBrowserFrameView* frame_view2 = CreatePanelBrowserView("PanelTest2")->GetFrameView(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); // When we minimize one panel, "Minimize all" remains intact. frame_view1->browser_view_->panel_->Minimize(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); // When we minimize the remaining panel, "Minimize all" should become // "Restore all". frame_view2->browser_view_->panel_->Minimize(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), multi_panel_menu_for_restore_count, multi_panel_menu_for_restore); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_restore_count, multi_panel_menu_for_restore); // When we close one panel, we should be back to have only 1 menu item. frame_view1->browser_view_->panel_->Close(); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), single_panel_menu_count, single_panel_menu); } IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, TitleBarMouseEvent) { // Tests dragging a panel in single-panel environment. // We should get back to the original position after the dragging is ended. PanelBrowserView* browser_view1 = CreatePanelBrowserView("PanelTest1"); ValidateDragging(browser_view1, -500, -5, 0); // Tests dragging a panel with small delta in two-panel environment. // We should get back to the original position after the dragging is ended. PanelBrowserView* browser_view2 = CreatePanelBrowserView("PanelTest2"); ValidateDragging(browser_view1, -5, -5, 0); // Tests dragging a panel with big delta in two-panel environment. // We should move to the new position after the dragging is ended. ValidateDragging( browser_view1, -(browser_view2->panel()->GetRestoredBounds().width() / 2 + 5), -5, browser_view2->panel()->GetRestoredBounds().x() - browser_view1->panel()->GetRestoredBounds().x()); // Tests that no dragging is involved. ValidateDragging(browser_view1, 0, 0, 0); browser_view1->Close(); EXPECT_FALSE(browser_view1->panel()); browser_view2->Close(); EXPECT_FALSE(browser_view2->panel()); } #endif
// Copyright (c) 2011 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/command_line.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_browser_frame_view.h" #include "chrome/browser/ui/panels/panel_browser_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/in_process_browser_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/controls/button/image_button.h" #include "views/controls/button/menu_button.h" #include "views/controls/label.h" #include "views/controls/menu/menu_2.h" class PanelBrowserViewTest : public InProcessBrowserTest { public: PanelBrowserViewTest() : InProcessBrowserTest() { } virtual void SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitch(switches::kEnablePanels); } protected: PanelBrowserView* CreatePanelBrowserView(const std::string& panel_name) { Browser* panel_browser = Browser::CreateForApp(Browser::TYPE_PANEL, panel_name, gfx::Size(), browser()->profile()); panel_browser->window()->Show(); return static_cast<PanelBrowserView*>( static_cast<Panel*>(panel_browser->window())->browser_window()); } void ValidateOptionsMenuItems( ui::SimpleMenuModel* options_menu_contents, size_t count, int* ids) { ASSERT_TRUE(options_menu_contents); EXPECT_EQ(static_cast<int>(count), options_menu_contents->GetItemCount()); for (size_t i = 0; i < count; ++i) { if (ids[i] == -1) { EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, options_menu_contents->GetTypeAt(i)); } else { EXPECT_EQ(ids[i] , options_menu_contents->GetCommandIdAt(i)); } } } void ValidateDragging(PanelBrowserView* browser_view, int delta_x, int delta_y, int expected_delta_x_after_release) { gfx::Rect bounds_before_press = browser_view->panel()->GetRestoredBounds(); views::MouseEvent pressed(ui::ET_MOUSE_PRESSED, bounds_before_press.x(), bounds_before_press.y(), ui::EF_LEFT_BUTTON_DOWN); browser_view->OnTitleBarMousePressed(pressed); gfx::Rect bounds_after_press = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press, bounds_after_press); // If both delta_x and delta_y are 0, we perform no dragging. if (delta_x || delta_y) { views::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, bounds_before_press.x() + delta_x, bounds_before_press.y() + delta_y, ui::EF_LEFT_BUTTON_DOWN); browser_view->OnTitleBarMouseDragged(dragged); gfx::Rect bounds_after_drag = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press.x() + delta_x, bounds_after_drag.x()); EXPECT_EQ(bounds_before_press.y(), bounds_after_drag.y()); EXPECT_EQ(bounds_before_press.width(), bounds_after_drag.width()); EXPECT_EQ(bounds_before_press.height(), bounds_after_drag.height()); } views::MouseEvent released(ui::ET_MOUSE_RELEASED, 0, 0, 0); browser_view->OnTitleBarMouseReleased(released); gfx::Rect bounds_after_release = browser_view->panel()->GetRestoredBounds(); EXPECT_EQ(bounds_before_press.x() + expected_delta_x_after_release, bounds_after_release.x()); EXPECT_EQ(bounds_before_press.y(), bounds_after_release.y()); EXPECT_EQ(bounds_before_press.width(), bounds_after_release.width()); EXPECT_EQ(bounds_before_press.height(), bounds_after_release.height()); } }; // Panel is not supported for Linux view yet. #if !defined(OS_LINUX) || !defined(TOOLKIT_VIEWS) IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, CreatePanel) { PanelBrowserFrameView* frame_view = CreatePanelBrowserView("PanelTest")->GetFrameView(); // We should have icon, text, options button and close button. EXPECT_EQ(4, frame_view->child_count()); EXPECT_TRUE(frame_view->Contains(frame_view->title_icon_)); EXPECT_TRUE(frame_view->Contains(frame_view->title_label_)); EXPECT_TRUE(frame_view->Contains(frame_view->options_button_)); EXPECT_TRUE(frame_view->Contains(frame_view->close_button_)); // These controls should be visible. EXPECT_TRUE(frame_view->title_icon_->IsVisible()); EXPECT_TRUE(frame_view->title_label_->IsVisible()); EXPECT_TRUE(frame_view->options_button_->IsVisible()); EXPECT_TRUE(frame_view->close_button_->IsVisible()); // Validate their layouts. int title_bar_height = frame_view->NonClientTopBorderHeight() - frame_view->NonClientBorderThickness(); EXPECT_GT(frame_view->title_icon_->width(), 0); EXPECT_GT(frame_view->title_icon_->height(), 0); EXPECT_LT(frame_view->title_icon_->height(), title_bar_height); EXPECT_GT(frame_view->title_label_->width(), 0); EXPECT_GT(frame_view->title_label_->height(), 0); EXPECT_LT(frame_view->title_label_->height(), title_bar_height); EXPECT_GT(frame_view->options_button_->width(), 0); EXPECT_GT(frame_view->options_button_->height(), 0); EXPECT_LT(frame_view->options_button_->height(), title_bar_height); EXPECT_GT(frame_view->close_button_->width(), 0); EXPECT_GT(frame_view->close_button_->height(), 0); EXPECT_LT(frame_view->close_button_->height(), title_bar_height); EXPECT_LT(frame_view->title_icon_->x() + frame_view->title_icon_->width(), frame_view->title_label_->x()); EXPECT_LT(frame_view->title_label_->x() + frame_view->title_label_->width(), frame_view->options_button_->x()); EXPECT_LT( frame_view->options_button_->x() + frame_view->options_button_->width(), frame_view->close_button_->x()); // Validate that the controls should be updated when the activation state is // changed. frame_view->UpdateControlStyles(PanelBrowserFrameView::PAINT_AS_ACTIVE); SkColor title_label_color1 = frame_view->title_label_->GetColor(); frame_view->UpdateControlStyles(PanelBrowserFrameView::PAINT_AS_INACTIVE); SkColor title_label_color2 = frame_view->title_label_->GetColor(); EXPECT_NE(title_label_color1, title_label_color2); } IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, CreateOrUpdateOptionsMenu) { int single_panel_menu[] = { PanelBrowserFrameView::COMMAND_ABOUT }; size_t single_panel_menu_count = arraysize(single_panel_menu); int multi_panel_menu_for_minimize[] = { PanelBrowserFrameView::COMMAND_MINIMIZE_ALL, PanelBrowserFrameView::COMMAND_CLOSE_ALL, -1, // Separator PanelBrowserFrameView::COMMAND_ABOUT }; size_t multi_panel_menu_for_minimize_count = arraysize(multi_panel_menu_for_minimize); int multi_panel_menu_for_restore[] = { PanelBrowserFrameView::COMMAND_RESTORE_ALL, PanelBrowserFrameView::COMMAND_CLOSE_ALL, -1, // Separator PanelBrowserFrameView::COMMAND_ABOUT }; size_t multi_panel_menu_for_restore_count = arraysize(multi_panel_menu_for_restore); // With only one panel, we should only have 1 menu item: "About this panel". PanelBrowserFrameView* frame_view1 = CreatePanelBrowserView("PanelTest1")->GetFrameView(); frame_view1->CreateOrUpdateOptionsMenu(); ASSERT_TRUE(frame_view1->options_menu_.get()); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), single_panel_menu_count, single_panel_menu); // With another panel, we should have 4 menu items, including separator. PanelBrowserFrameView* frame_view2 = CreatePanelBrowserView("PanelTest2")->GetFrameView(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); // When we minimize one panel, "Minimize all" remains intact. frame_view1->browser_view_->panel_->Minimize(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_minimize_count, multi_panel_menu_for_minimize); // When we minimize the remaining panel, "Minimize all" should become // "Restore all". frame_view2->browser_view_->panel_->Minimize(); frame_view1->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view1->options_menu_contents_.get(), multi_panel_menu_for_restore_count, multi_panel_menu_for_restore); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), multi_panel_menu_for_restore_count, multi_panel_menu_for_restore); // When we close one panel, we should be back to have only 1 menu item. frame_view1->browser_view_->panel_->Close(); frame_view2->CreateOrUpdateOptionsMenu(); ValidateOptionsMenuItems(frame_view2->options_menu_contents_.get(), single_panel_menu_count, single_panel_menu); } IN_PROC_BROWSER_TEST_F(PanelBrowserViewTest, DISABLED_TitleBarMouseEvent) { // Tests dragging a panel in single-panel environment. // We should get back to the original position after the dragging is ended. PanelBrowserView* browser_view1 = CreatePanelBrowserView("PanelTest1"); ValidateDragging(browser_view1, -500, -5, 0); // Tests dragging a panel with small delta in two-panel environment. // We should get back to the original position after the dragging is ended. PanelBrowserView* browser_view2 = CreatePanelBrowserView("PanelTest2"); ValidateDragging(browser_view1, -5, -5, 0); // Tests dragging a panel with big delta in two-panel environment. // We should move to the new position after the dragging is ended. ValidateDragging( browser_view1, -(browser_view2->panel()->GetRestoredBounds().width() / 2 + 5), -5, browser_view2->panel()->GetRestoredBounds().x() - browser_view1->panel()->GetRestoredBounds().x()); // Tests that no dragging is involved. ValidateDragging(browser_view1, 0, 0, 0); browser_view1->Close(); EXPECT_FALSE(browser_view1->panel()); browser_view2->Close(); EXPECT_FALSE(browser_view2->panel()); } #endif
Disable PanelBrowserViewTest.TitleBarMouseEvent for further investigation.
Disable PanelBrowserViewTest.TitleBarMouseEvent for further investigation. BUG=none TEST=none TBR=jennb Review URL: http://codereview.chromium.org/7013010 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85062 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium
edd208d91fb821425a269a791f59a13198f0fc83
modules/skottie/src/animator/VectorKeyframeAnimator.cpp
modules/skottie/src/animator/VectorKeyframeAnimator.cpp
/* * Copyright 2020 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/animator/VectorKeyframeAnimator.h" #include "include/core/SkTypes.h" #include "include/private/SkNx.h" #include "modules/skottie/src/SkottieJson.h" #include "modules/skottie/src/SkottieValue.h" #include "modules/skottie/src/animator/Animator.h" #include "src/core/SkSafeMath.h" #include <algorithm> #include <cstring> namespace skottie { // Parses an array of exact size. static bool parse_array(const skjson::ArrayValue* ja, float* a, size_t count) { if (!ja || ja->size() != count) { return false; } for (size_t i = 0; i < count; ++i) { if (!Parse((*ja)[i], a + i)) { return false; } } return true; } VectorValue::operator SkV3() const { // best effort to turn this into a 3D point return SkV3 { this->size() > 0 ? (*this)[0] : 0, this->size() > 1 ? (*this)[1] : 0, this->size() > 2 ? (*this)[2] : 0, }; } VectorValue::operator SkColor() const { // best effort to turn this into a color const auto r = this->size() > 0 ? (*this)[0] : 0, g = this->size() > 1 ? (*this)[1] : 0, b = this->size() > 2 ? (*this)[2] : 0, a = this->size() > 3 ? (*this)[3] : 1; return SkColorSetARGB(SkScalarRoundToInt(SkTPin(a, 0.0f, 1.0f) * 255), SkScalarRoundToInt(SkTPin(r, 0.0f, 1.0f) * 255), SkScalarRoundToInt(SkTPin(g, 0.0f, 1.0f) * 255), SkScalarRoundToInt(SkTPin(b, 0.0f, 1.0f) * 255)); } VectorValue::operator SkColor4f() const { // best effort to turn a vector into a color const auto r = this->size() > 0 ? SkTPin((*this)[0], 0.0f, 1.0f) : 0, g = this->size() > 1 ? SkTPin((*this)[1], 0.0f, 1.0f) : 0, b = this->size() > 2 ? SkTPin((*this)[2], 0.0f, 1.0f) : 0, a = this->size() > 3 ? SkTPin((*this)[3], 0.0f, 1.0f) : 1; return { r, g, b, a }; } namespace internal { namespace { // Vector specialization - stores float vector values (of same length) in consolidated/contiguous // storage. Keyframe records hold the storage offset for each value: // // fStorage: [ vec0 ][ vec1 ] ... [ vecN ] // <- vec_len -> <- vec_len -> <- vec_len -> // // ^ ^ ^ // fKFs[]: .idx .idx ... .idx // class VectorKeyframeAnimator final : public KeyframeAnimator { public: VectorKeyframeAnimator(std::vector<Keyframe> kfs, std::vector<SkCubicMap> cms, std::vector<float> storage, size_t vec_len, std::vector<float>* target_value) : INHERITED(std::move(kfs), std::move(cms)) , fStorage(std::move(storage)) , fVecLen(vec_len) , fTarget(target_value) { // Resize the target value appropriately. fTarget->resize(fVecLen); } private: StateChanged onSeek(float t) override { const auto& lerp_info = this->getLERPInfo(t); SkASSERT(lerp_info.vrec0.idx + fVecLen <= fStorage.size()); SkASSERT(lerp_info.vrec1.idx + fVecLen <= fStorage.size()); SkASSERT(fTarget->size() == fVecLen); const auto* v0 = fStorage.data() + lerp_info.vrec0.idx; const auto* v1 = fStorage.data() + lerp_info.vrec1.idx; auto* dst = fTarget->data(); if (lerp_info.isConstant()) { if (std::memcmp(dst, v0, fVecLen * sizeof(float))) { std::copy(v0, v0 + fVecLen, dst); return true; } return false; } size_t count = fVecLen; bool changed = false; while (count >= 4) { const auto old_val = Sk4f::Load(dst), new_val = Lerp(Sk4f::Load(v0), Sk4f::Load(v1), lerp_info.weight); changed |= (new_val != old_val).anyTrue(); new_val.store(dst); v0 += 4; v1 += 4; dst += 4; count -= 4; } while (count-- > 0) { const auto new_val = Lerp(*v0++, *v1++, lerp_info.weight); changed |= (new_val != *dst); *dst++ = new_val; } return changed; } const std::vector<float> fStorage; const size_t fVecLen; std::vector<float>* fTarget; using INHERITED = KeyframeAnimator; }; } // namespace VectorKeyframeAnimatorBuilder::VectorKeyframeAnimatorBuilder(std::vector<float>* target, VectorLenParser parse_len, VectorDataParser parse_data) : fParseLen(parse_len) , fParseData(parse_data) , fTarget(target) {} sk_sp<KeyframeAnimator> VectorKeyframeAnimatorBuilder::make(const AnimationBuilder& abuilder, const skjson::ArrayValue& jkfs) { SkASSERT(jkfs.size() > 0); // peek at the first keyframe value to find our vector length const skjson::ObjectValue* jkf0 = jkfs[0]; if (!jkf0 || !fParseLen((*jkf0)["s"], &fVecLen)) { return nullptr; } SkSafeMath safe; // total elements: vector length x number vectors const auto total_size = safe.mul(fVecLen, jkfs.size()); // we must be able to store all offsets in Keyframe::Value::idx (uint32_t) if (!safe || !SkTFitsIn<uint32_t>(total_size)) { return nullptr; } fStorage.resize(total_size); if (!this->parseKeyframes(abuilder, jkfs)) { return nullptr; } // parseKFValue() might have stored fewer vectors thanks to tail-deduping. SkASSERT(fCurrentVec <= jkfs.size()); fStorage.resize(fCurrentVec * fVecLen); fStorage.shrink_to_fit(); return sk_sp<VectorKeyframeAnimator>( new VectorKeyframeAnimator(std::move(fKFs), std::move(fCMs), std::move(fStorage), fVecLen, fTarget)); } bool VectorKeyframeAnimatorBuilder::parseValue(const AnimationBuilder&, const skjson::Value& jv) const { size_t vec_len; if (!this->fParseLen(jv, &vec_len)) { return false; } fTarget->resize(vec_len); return fParseData(jv, vec_len, fTarget->data()); } bool VectorKeyframeAnimatorBuilder::parseKFValue(const AnimationBuilder&, const skjson::ObjectValue&, const skjson::Value& jv, Keyframe::Value* kfv) { auto offset = fCurrentVec * fVecLen; SkASSERT(offset + fVecLen <= fStorage.size()); if (!fParseData(jv, fVecLen, fStorage.data() + offset)) { return false; } SkASSERT(!fCurrentVec || offset >= fVecLen); // compare with previous vector value if (fCurrentVec > 0 && !memcmp(fStorage.data() + offset, fStorage.data() + offset - fVecLen, fVecLen * sizeof(float))) { // repeating value -> use prev offset (dedupe) offset -= fVecLen; } else { // new value -> advance the current index fCurrentVec += 1; } // Keyframes record the storage-offset for a given vector value. kfv->idx = SkToU32(offset); return true; } template <> bool AnimatablePropertyContainer::bind<VectorValue>(const AnimationBuilder& abuilder, const skjson::ObjectValue* jprop, VectorValue* v) { if (!jprop) { return false; } if (!ParseDefault<bool>((*jprop)["s"], false)) { // Regular (static or keyframed) vector value. VectorKeyframeAnimatorBuilder builder( v, // Len parser. [](const skjson::Value& jv, size_t* len) -> bool { if (const skjson::ArrayValue* ja = jv) { *len = ja->size(); return true; } return false; }, // Data parser. [](const skjson::Value& jv, size_t len, float* data) { return parse_array(jv, data, len); }); return this->bindImpl(abuilder, jprop, builder); } // Separate-dimensions vector value: each component is animated independently. *v = { 0, 0, 0 }; return this->bind(abuilder, (*jprop)["x"], v->data() + 0) | this->bind(abuilder, (*jprop)["y"], v->data() + 1) | this->bind(abuilder, (*jprop)["z"], v->data() + 2); } } // namespace internal } // namespace skottie
/* * Copyright 2020 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/animator/VectorKeyframeAnimator.h" #include "include/core/SkTypes.h" #include "include/private/SkNx.h" #include "modules/skottie/src/SkottieJson.h" #include "modules/skottie/src/SkottieValue.h" #include "modules/skottie/src/animator/Animator.h" #include "src/core/SkSafeMath.h" #include <algorithm> #include <cstring> namespace skottie { // Parses an array of exact size. static bool parse_array(const skjson::ArrayValue* ja, float* a, size_t count) { if (!ja || ja->size() != count) { return false; } for (size_t i = 0; i < count; ++i) { if (!Parse((*ja)[i], a + i)) { return false; } } return true; } VectorValue::operator SkV3() const { // best effort to turn this into a 3D point return SkV3 { this->size() > 0 ? (*this)[0] : 0, this->size() > 1 ? (*this)[1] : 0, this->size() > 2 ? (*this)[2] : 0, }; } VectorValue::operator SkColor() const { return static_cast<SkColor4f>(*this).toSkColor(); } VectorValue::operator SkColor4f() const { // best effort to turn a vector into a color const auto r = this->size() > 0 ? SkTPin((*this)[0], 0.0f, 1.0f) : 0, g = this->size() > 1 ? SkTPin((*this)[1], 0.0f, 1.0f) : 0, b = this->size() > 2 ? SkTPin((*this)[2], 0.0f, 1.0f) : 0, a = this->size() > 3 ? SkTPin((*this)[3], 0.0f, 1.0f) : 1; return { r, g, b, a }; } namespace internal { namespace { // Vector specialization - stores float vector values (of same length) in consolidated/contiguous // storage. Keyframe records hold the storage offset for each value: // // fStorage: [ vec0 ][ vec1 ] ... [ vecN ] // <- vec_len -> <- vec_len -> <- vec_len -> // // ^ ^ ^ // fKFs[]: .idx .idx ... .idx // class VectorKeyframeAnimator final : public KeyframeAnimator { public: VectorKeyframeAnimator(std::vector<Keyframe> kfs, std::vector<SkCubicMap> cms, std::vector<float> storage, size_t vec_len, std::vector<float>* target_value) : INHERITED(std::move(kfs), std::move(cms)) , fStorage(std::move(storage)) , fVecLen(vec_len) , fTarget(target_value) { // Resize the target value appropriately. fTarget->resize(fVecLen); } private: StateChanged onSeek(float t) override { const auto& lerp_info = this->getLERPInfo(t); SkASSERT(lerp_info.vrec0.idx + fVecLen <= fStorage.size()); SkASSERT(lerp_info.vrec1.idx + fVecLen <= fStorage.size()); SkASSERT(fTarget->size() == fVecLen); const auto* v0 = fStorage.data() + lerp_info.vrec0.idx; const auto* v1 = fStorage.data() + lerp_info.vrec1.idx; auto* dst = fTarget->data(); if (lerp_info.isConstant()) { if (std::memcmp(dst, v0, fVecLen * sizeof(float))) { std::copy(v0, v0 + fVecLen, dst); return true; } return false; } size_t count = fVecLen; bool changed = false; while (count >= 4) { const auto old_val = Sk4f::Load(dst), new_val = Lerp(Sk4f::Load(v0), Sk4f::Load(v1), lerp_info.weight); changed |= (new_val != old_val).anyTrue(); new_val.store(dst); v0 += 4; v1 += 4; dst += 4; count -= 4; } while (count-- > 0) { const auto new_val = Lerp(*v0++, *v1++, lerp_info.weight); changed |= (new_val != *dst); *dst++ = new_val; } return changed; } const std::vector<float> fStorage; const size_t fVecLen; std::vector<float>* fTarget; using INHERITED = KeyframeAnimator; }; } // namespace VectorKeyframeAnimatorBuilder::VectorKeyframeAnimatorBuilder(std::vector<float>* target, VectorLenParser parse_len, VectorDataParser parse_data) : fParseLen(parse_len) , fParseData(parse_data) , fTarget(target) {} sk_sp<KeyframeAnimator> VectorKeyframeAnimatorBuilder::make(const AnimationBuilder& abuilder, const skjson::ArrayValue& jkfs) { SkASSERT(jkfs.size() > 0); // peek at the first keyframe value to find our vector length const skjson::ObjectValue* jkf0 = jkfs[0]; if (!jkf0 || !fParseLen((*jkf0)["s"], &fVecLen)) { return nullptr; } SkSafeMath safe; // total elements: vector length x number vectors const auto total_size = safe.mul(fVecLen, jkfs.size()); // we must be able to store all offsets in Keyframe::Value::idx (uint32_t) if (!safe || !SkTFitsIn<uint32_t>(total_size)) { return nullptr; } fStorage.resize(total_size); if (!this->parseKeyframes(abuilder, jkfs)) { return nullptr; } // parseKFValue() might have stored fewer vectors thanks to tail-deduping. SkASSERT(fCurrentVec <= jkfs.size()); fStorage.resize(fCurrentVec * fVecLen); fStorage.shrink_to_fit(); return sk_sp<VectorKeyframeAnimator>( new VectorKeyframeAnimator(std::move(fKFs), std::move(fCMs), std::move(fStorage), fVecLen, fTarget)); } bool VectorKeyframeAnimatorBuilder::parseValue(const AnimationBuilder&, const skjson::Value& jv) const { size_t vec_len; if (!this->fParseLen(jv, &vec_len)) { return false; } fTarget->resize(vec_len); return fParseData(jv, vec_len, fTarget->data()); } bool VectorKeyframeAnimatorBuilder::parseKFValue(const AnimationBuilder&, const skjson::ObjectValue&, const skjson::Value& jv, Keyframe::Value* kfv) { auto offset = fCurrentVec * fVecLen; SkASSERT(offset + fVecLen <= fStorage.size()); if (!fParseData(jv, fVecLen, fStorage.data() + offset)) { return false; } SkASSERT(!fCurrentVec || offset >= fVecLen); // compare with previous vector value if (fCurrentVec > 0 && !memcmp(fStorage.data() + offset, fStorage.data() + offset - fVecLen, fVecLen * sizeof(float))) { // repeating value -> use prev offset (dedupe) offset -= fVecLen; } else { // new value -> advance the current index fCurrentVec += 1; } // Keyframes record the storage-offset for a given vector value. kfv->idx = SkToU32(offset); return true; } template <> bool AnimatablePropertyContainer::bind<VectorValue>(const AnimationBuilder& abuilder, const skjson::ObjectValue* jprop, VectorValue* v) { if (!jprop) { return false; } if (!ParseDefault<bool>((*jprop)["s"], false)) { // Regular (static or keyframed) vector value. VectorKeyframeAnimatorBuilder builder( v, // Len parser. [](const skjson::Value& jv, size_t* len) -> bool { if (const skjson::ArrayValue* ja = jv) { *len = ja->size(); return true; } return false; }, // Data parser. [](const skjson::Value& jv, size_t len, float* data) { return parse_array(jv, data, len); }); return this->bindImpl(abuilder, jprop, builder); } // Separate-dimensions vector value: each component is animated independently. *v = { 0, 0, 0 }; return this->bind(abuilder, (*jprop)["x"], v->data() + 0) | this->bind(abuilder, (*jprop)["y"], v->data() + 1) | this->bind(abuilder, (*jprop)["z"], v->data() + 2); } } // namespace internal } // namespace skottie
Simplify SkColor conversion
[skottie] Simplify SkColor conversion Use the SkColor4f helper. TBR= Change-Id: Iefbbfb1c20a298c8a221f279f9c5b086613c91eb Reviewed-on: https://skia-review.googlesource.com/c/skia/+/296858 Reviewed-by: Florin Malita <[email protected]> Commit-Queue: Florin Malita <[email protected]> Commit-Queue: Florin Malita <[email protected]>
C++
bsd-3-clause
google/skia,google/skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia
16b34270208a277e7dc9d437a7e557c471a1e390
modules/stickychan.cpp
modules/stickychan.cpp
/* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. * * 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 <no/nomodule.h> #include <no/nochannel.h> #include <no/nonetwork.h> #include <no/nowebsocket.h> #include <no/nowebsession.h> class NoStickyChan : public NoModule { public: MODCONSTRUCTOR(NoStickyChan) { AddHelpCommand(); AddCommand("Stick", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnStickCommand), "<#channel> [key]", "Sticks a channel"); AddCommand("Unstick", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnUnstickCommand), "<#channel>", "Unsticks a channel"); AddCommand("List", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnListCommand), "", "Lists sticky channels"); } bool OnLoad(const NoString& sArgs, NoString& sMessage) override; ModRet OnUserPart(NoString& sChannel, NoString& sMessage) override { for (NoStringMap::iterator it = BeginNV(); it != EndNV(); ++it) { if (sChannel.equals(it->first)) { NoChannel* pChan = GetNetwork()->FindChan(sChannel); if (pChan) { pChan->joinUser(); return HALT; } } } return CONTINUE; } virtual void OnMode(const NoNick& pOpNick, NoChannel& Channel, char uMode, const NoString& sArg, bool bAdded, bool bNoChange) override { if (uMode == NoChannel::M_Key) { if (bAdded) { // We ignore channel key "*" because of some broken nets. if (sArg != "*") { SetNV(Channel.getName(), sArg, true); } } else { SetNV(Channel.getName(), "", true); } } } void OnStickCommand(const NoString& sCommand) { NoString sChannel = No::token(sCommand, 1).toLower(); if (sChannel.empty()) { PutModule("Usage: Stick <#channel> [key]"); return; } SetNV(sChannel, No::token(sCommand, 2), true); PutModule("Stuck " + sChannel); } void OnUnstickCommand(const NoString& sCommand) { NoString sChannel = No::token(sCommand, 1); if (sChannel.empty()) { PutModule("Usage: Unstick <#channel>"); return; } DelNV(sChannel, true); PutModule("Unstuck " + sChannel); } void OnListCommand(const NoString& sCommand) { int i = 1; for (NoStringMap::iterator it = BeginNV(); it != EndNV(); ++it, i++) { if (it->second.empty()) PutModule(NoString(i) + ": " + it->first); else PutModule(NoString(i) + ": " + it->first + " (" + it->second + ")"); } PutModule(" -- End of List"); } void RunJob() { NoNetwork* pNetwork = GetNetwork(); if (!pNetwork->GetIRCSock()) return; for (NoStringMap::iterator it = BeginNV(); it != EndNV(); ++it) { NoChannel* pChan = pNetwork->FindChan(it->first); if (!pChan) { pChan = new NoChannel(it->first, pNetwork, true); if (!it->second.empty()) pChan->setKey(it->second); if (!pNetwork->AddChan(pChan)) { /* AddChan() deleted that channel */ PutModule("Could not join [" + it->first + "] (# prefix missing?)"); continue; } } if (!pChan->isOn() && pNetwork->IsIRCConnected()) { PutModule("Joining [" + pChan->getName() + "]"); PutIRC("JOIN " + pChan->getName() + (pChan->getKey().empty() ? "" : " " + pChan->getKey())); } } } NoString GetWebMenuTitle() override { return "Sticky Chans"; } bool OnWebRequest(NoWebSocket& WebSock, const NoString& sPageName, NoTemplate& Tmpl) override { if (sPageName == "index") { bool bSubmitted = (WebSock.GetParam("submitted").toInt() != 0); const std::vector<NoChannel*>& Channels = GetNetwork()->GetChans(); for (uint c = 0; c < Channels.size(); c++) { const NoString sChan = Channels[c]->getName(); bool bStick = FindNV(sChan) != EndNV(); if (bSubmitted) { bool bNewStick = WebSock.GetParam("stick_" + sChan).toBool(); if (bNewStick && !bStick) SetNV(sChan, ""); // no password support for now unless chansaver is active too else if (!bNewStick && bStick) { NoStringMap::iterator it = FindNV(sChan); if (it != EndNV()) DelNV(it); } bStick = bNewStick; } NoTemplate& Row = Tmpl.AddRow("ChannelLoop"); Row["Name"] = sChan; Row["Sticky"] = NoString(bStick); } if (bSubmitted) { WebSock.GetSession()->AddSuccess("Changes have been saved!"); } return true; } return false; } bool OnEmbeddedWebRequest(NoWebSocket& WebSock, const NoString& sPageName, NoTemplate& Tmpl) override { if (sPageName == "webadmin/channel") { NoString sChan = Tmpl["ChanName"]; bool bStick = FindNV(sChan) != EndNV(); if (Tmpl["WebadminAction"].equals("display")) { Tmpl["Sticky"] = NoString(bStick); } else if (WebSock.GetParam("embed_stickychan_presented").toBool()) { bool bNewStick = WebSock.GetParam("embed_stickychan_sticky").toBool(); if (bNewStick && !bStick) { SetNV(sChan, ""); // no password support for now unless chansaver is active too WebSock.GetSession()->AddSuccess("Channel become sticky!"); } else if (!bNewStick && bStick) { DelNV(sChan); WebSock.GetSession()->AddSuccess("Channel stopped being sticky!"); } } return true; } return false; } }; static void RunTimer(NoModule* pModule, NoTimer* pTimer) { ((NoStickyChan*)pModule)->RunJob(); } bool NoStickyChan::OnLoad(const NoString& sArgs, NoString& sMessage) { NoStringVector vsChans = sArgs.split(",", No::SkipEmptyParts); NoStringVector::iterator it; for (it = vsChans.begin(); it != vsChans.end(); ++it) { NoString sChan = No::token(*it, 0); NoString sKey = No::tokens(*it, 1); SetNV(sChan, sKey); } // Since we now have these channels added, clear the argument list SetArgs(""); AddTimer(RunTimer, "StickyChanTimer", 15); return (true); } template <> void no_moduleInfo<NoStickyChan>(NoModuleInfo& Info) { Info.SetWikiPage("stickychan"); Info.SetHasArgs(true); Info.SetArgsHelpText("List of channels, separated by comma."); } NETWORKMODULEDEFS(NoStickyChan, "configless sticky chans, keeps you there very stickily even")
/* * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details. * * 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 <no/nomodule.h> #include <no/nochannel.h> #include <no/nonetwork.h> #include <no/nowebsocket.h> #include <no/nowebsession.h> class NoStickyChan : public NoModule { public: MODCONSTRUCTOR(NoStickyChan) { AddHelpCommand(); AddCommand("Stick", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnStickCommand), "<#channel> [key]", "Sticks a channel"); AddCommand("Unstick", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnUnstickCommand), "<#channel>", "Unsticks a channel"); AddCommand("List", static_cast<NoModuleCommand::ModCmdFunc>(&NoStickyChan::OnListCommand), "", "Lists sticky channels"); } bool OnLoad(const NoString& sArgs, NoString& sMessage) override; ModRet OnUserPart(NoString& sChannel, NoString& sMessage) override { for (NoStringMap::iterator it = BeginNV(); it != EndNV(); ++it) { if (sChannel.equals(it->first)) { NoChannel* pChan = GetNetwork()->FindChan(sChannel); if (pChan) { pChan->joinUser(); return HALT; } } } return CONTINUE; } virtual void OnMode(const NoNick& pOpNick, NoChannel& Channel, char uMode, const NoString& sArg, bool bAdded, bool bNoChange) override { if (uMode == NoChannel::M_Key) { if (bAdded) { // We ignore channel key "*" because of some broken nets. if (sArg != "*") { SetNV(Channel.getName(), sArg, true); } } else { SetNV(Channel.getName(), "", true); } } } void OnStickCommand(const NoString& sCommand) { NoString sChannel = No::token(sCommand, 1).toLower(); if (sChannel.empty()) { PutModule("Usage: Stick <#channel> [key]"); return; } SetNV(sChannel, No::token(sCommand, 2), true); PutModule("Stuck " + sChannel); } void OnUnstickCommand(const NoString& sCommand) { NoString sChannel = No::token(sCommand, 1); if (sChannel.empty()) { PutModule("Usage: Unstick <#channel>"); return; } DelNV(sChannel, true); PutModule("Unstuck " + sChannel); } void OnListCommand(const NoString& sCommand) { int i = 1; for (NoStringMap::iterator it = BeginNV(); it != EndNV(); ++it, i++) { if (it->second.empty()) PutModule(NoString(i) + ": " + it->first); else PutModule(NoString(i) + ": " + it->first + " (" + it->second + ")"); } PutModule(" -- End of List"); } NoString GetWebMenuTitle() override { return "Sticky Chans"; } bool OnWebRequest(NoWebSocket& WebSock, const NoString& sPageName, NoTemplate& Tmpl) override { if (sPageName == "index") { bool bSubmitted = (WebSock.GetParam("submitted").toInt() != 0); const std::vector<NoChannel*>& Channels = GetNetwork()->GetChans(); for (uint c = 0; c < Channels.size(); c++) { const NoString sChan = Channels[c]->getName(); bool bStick = FindNV(sChan) != EndNV(); if (bSubmitted) { bool bNewStick = WebSock.GetParam("stick_" + sChan).toBool(); if (bNewStick && !bStick) SetNV(sChan, ""); // no password support for now unless chansaver is active too else if (!bNewStick && bStick) { NoStringMap::iterator it = FindNV(sChan); if (it != EndNV()) DelNV(it); } bStick = bNewStick; } NoTemplate& Row = Tmpl.AddRow("ChannelLoop"); Row["Name"] = sChan; Row["Sticky"] = NoString(bStick); } if (bSubmitted) { WebSock.GetSession()->AddSuccess("Changes have been saved!"); } return true; } return false; } bool OnEmbeddedWebRequest(NoWebSocket& WebSock, const NoString& sPageName, NoTemplate& Tmpl) override { if (sPageName == "webadmin/channel") { NoString sChan = Tmpl["ChanName"]; bool bStick = FindNV(sChan) != EndNV(); if (Tmpl["WebadminAction"].equals("display")) { Tmpl["Sticky"] = NoString(bStick); } else if (WebSock.GetParam("embed_stickychan_presented").toBool()) { bool bNewStick = WebSock.GetParam("embed_stickychan_sticky").toBool(); if (bNewStick && !bStick) { SetNV(sChan, ""); // no password support for now unless chansaver is active too WebSock.GetSession()->AddSuccess("Channel become sticky!"); } else if (!bNewStick && bStick) { DelNV(sChan); WebSock.GetSession()->AddSuccess("Channel stopped being sticky!"); } } return true; } return false; } }; class NoStickyTimer : public NoTimer { public: NoStickyTimer(NoModule* module) : NoTimer(module, 15, 0, "StickyChanTimer", "") { } protected: void RunJob() override { NoModule* mod = module(); if (!mod) return; NoNetwork* pNetwork = mod->GetNetwork(); if (!pNetwork->GetIRCSock()) return; for (NoStringMap::iterator it = mod->BeginNV(); it != mod->EndNV(); ++it) { NoChannel* pChan = pNetwork->FindChan(it->first); if (!pChan) { pChan = new NoChannel(it->first, pNetwork, true); if (!it->second.empty()) pChan->setKey(it->second); if (!pNetwork->AddChan(pChan)) { /* AddChan() deleted that channel */ mod->PutModule("Could not join [" + it->first + "] (# prefix missing?)"); continue; } } if (!pChan->isOn() && pNetwork->IsIRCConnected()) { mod->PutModule("Joining [" + pChan->getName() + "]"); mod->PutIRC("JOIN " + pChan->getName() + (pChan->getKey().empty() ? "" : " " + pChan->getKey())); } } } }; bool NoStickyChan::OnLoad(const NoString& sArgs, NoString& sMessage) { NoStringVector vsChans = sArgs.split(",", No::SkipEmptyParts); NoStringVector::iterator it; for (it = vsChans.begin(); it != vsChans.end(); ++it) { NoString sChan = No::token(*it, 0); NoString sKey = No::tokens(*it, 1); SetNV(sChan, sKey); } // Since we now have these channels added, clear the argument list SetArgs(""); AddTimer(new NoStickyTimer(this)); return (true); } template <> void no_moduleInfo<NoStickyChan>(NoModuleInfo& Info) { Info.SetWikiPage("stickychan"); Info.SetHasArgs(true); Info.SetArgsHelpText("List of channels, separated by comma."); } NETWORKMODULEDEFS(NoStickyChan, "configless sticky chans, keeps you there very stickily even")
Kill NoTimer::Callback - it was used it one place...
Kill NoTimer::Callback - it was used it one place...
C++
apache-2.0
Kriechi/nobnc,Kriechi/nobnc,Kriechi/nobnc
49e58da5b12e6fb26b4279fc443d7165cc64e115
peerconnection/samples/client/peer_connection_client.cc
peerconnection/samples/client/peer_connection_client.cc
/* * Copyright (c) 2011 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 "peerconnection/samples/client/peer_connection_client.h" #include "peerconnection/samples/client/defaults.h" #include "talk/base/nethelpers.h" #include "talk/base/logging.h" #include "talk/base/stringutils.h" #ifdef WIN32 #include "talk/base/win32socketserver.h" #endif using talk_base::sprintfn; namespace { // This is our magical hangup signal. const char kByeMessage[] = "BYE"; talk_base::AsyncSocket* CreateClientSocket() { #ifdef WIN32 return new talk_base::Win32Socket(); #elif defined(POSIX) talk_base::Thread* thread = talk_base::Thread::Current(); ASSERT(thread != NULL); return thread->socketserver()->CreateAsyncSocket(SOCK_STREAM); #else #error Platform not supported. #endif } } PeerConnectionClient::PeerConnectionClient() : callback_(NULL), control_socket_(CreateClientSocket()), hanging_get_(CreateClientSocket()), state_(NOT_CONNECTED), my_id_(-1) { control_socket_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); hanging_get_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); control_socket_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnConnect); hanging_get_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnHangingGetConnect); control_socket_->SignalReadEvent.connect(this, &PeerConnectionClient::OnRead); hanging_get_->SignalReadEvent.connect(this, &PeerConnectionClient::OnHangingGetRead); } PeerConnectionClient::~PeerConnectionClient() { } int PeerConnectionClient::id() const { return my_id_; } bool PeerConnectionClient::is_connected() const { return my_id_ != -1; } const Peers& PeerConnectionClient::peers() const { return peers_; } void PeerConnectionClient::RegisterObserver( PeerConnectionClientObserver* callback) { ASSERT(!callback_); callback_ = callback; } bool PeerConnectionClient::Connect(const std::string& server, int port, const std::string& client_name) { ASSERT(!server.empty()); ASSERT(!client_name.empty()); if (state_ != NOT_CONNECTED) { LOG(WARNING) << "The client must not be connected before you can call Connect()"; return false; } if (server.empty() || client_name.empty()) return false; if (port <= 0) port = kDefaultServerPort; server_address_.SetIP(server); server_address_.SetPort(port); if (server_address_.IsUnresolved()) { int errcode = 0; hostent* h = talk_base::SafeGetHostByName( server_address_.IPAsString().c_str(), &errcode); if (!h) { LOG(LS_ERROR) << "Failed to resolve host name: " << server_address_.IPAsString(); return false; } else { server_address_.SetResolvedIP( ntohl(*reinterpret_cast<uint32*>(h->h_addr_list[0]))); talk_base::FreeHostEnt(h); } } char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name.c_str()); onconnect_data_ = buffer; bool ret = ConnectControlSocket(); if (ret) state_ = SIGNING_IN; return ret; } bool PeerConnectionClient::SendToPeer(int peer_id, const std::string& message) { if (state_ != CONNECTED) return false; ASSERT(is_connected()); ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED); if (!is_connected() || peer_id == -1) return false; char headers[1024]; sprintfn(headers, sizeof(headers), "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n" "Content-Length: %i\r\n" "Content-Type: text/plain\r\n" "\r\n", my_id_, peer_id, message.length()); onconnect_data_ = headers; onconnect_data_ += message; return ConnectControlSocket(); } bool PeerConnectionClient::SendHangUp(int peer_id) { return SendToPeer(peer_id, kByeMessage); } bool PeerConnectionClient::IsSendingMessage() { return state_ == CONNECTED && control_socket_->GetState() != talk_base::Socket::CS_CLOSED; } bool PeerConnectionClient::SignOut() { if (state_ == NOT_CONNECTED || state_ == SIGNING_OUT) return true; if (hanging_get_->GetState() != talk_base::Socket::CS_CLOSED) hanging_get_->Close(); if (control_socket_->GetState() == talk_base::Socket::CS_CLOSED) { state_ = SIGNING_OUT; if (my_id_ != -1) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); onconnect_data_ = buffer; return ConnectControlSocket(); } else { // Can occur if the app is closed before we finish connecting. return true; } } else { state_ = SIGNING_OUT_WAITING; } return true; } void PeerConnectionClient::Close() { control_socket_->Close(); hanging_get_->Close(); onconnect_data_.clear(); peers_.clear(); my_id_ = -1; state_ = NOT_CONNECTED; } bool PeerConnectionClient::ConnectControlSocket() { ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED); int err = control_socket_->Connect(server_address_); if (err == SOCKET_ERROR) { Close(); return false; } return true; } void PeerConnectionClient::OnConnect(talk_base::AsyncSocket* socket) { ASSERT(!onconnect_data_.empty()); size_t sent = socket->Send(onconnect_data_.c_str(), onconnect_data_.length()); ASSERT(sent == onconnect_data_.length()); onconnect_data_.clear(); } void PeerConnectionClient::OnHangingGetConnect(talk_base::AsyncSocket* socket) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); int len = strlen(buffer); int sent = socket->Send(buffer, len); ASSERT(sent == len); } void PeerConnectionClient::OnMessageFromPeer(int peer_id, const std::string& message) { if (message.length() == (sizeof(kByeMessage) - 1) && message.compare(kByeMessage) == 0) { callback_->OnPeerDisconnected(peer_id); } else { callback_->OnMessageFromPeer(peer_id, message); } } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, size_t* value) { ASSERT(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { *value = atoi(&data[found + strlen(header_pattern)]); return true; } return false; } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, std::string* value) { ASSERT(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { size_t begin = found + strlen(header_pattern); size_t end = data.find("\r\n", begin); if (end == std::string::npos) end = eoh; value->assign(data.substr(begin, end - begin)); return true; } return false; } bool PeerConnectionClient::ReadIntoBuffer(talk_base::AsyncSocket* socket, std::string* data, size_t* content_length) { LOG(INFO) << __FUNCTION__; char buffer[0xffff]; do { int bytes = socket->Recv(buffer, sizeof(buffer)); if (bytes <= 0) break; data->append(buffer, bytes); } while (true); bool ret = false; size_t i = data->find("\r\n\r\n"); if (i != std::string::npos) { LOG(INFO) << "Headers received"; if (GetHeaderValue(*data, i, "\r\nContent-Length: ", content_length)) { LOG(INFO) << "Expecting " << *content_length << " bytes."; size_t total_response_size = (i + 4) + *content_length; if (data->length() >= total_response_size) { ret = true; std::string should_close; const char kConnection[] = "\r\nConnection: "; if (GetHeaderValue(*data, i, kConnection, &should_close) && should_close.compare("close") == 0) { socket->Close(); } } else { // We haven't received everything. Just continue to accept data. } } else { LOG(LS_ERROR) << "No content length field specified by the server."; } } return ret; } void PeerConnectionClient::OnRead(talk_base::AsyncSocket* socket) { LOG(INFO) << __FUNCTION__; size_t content_length = 0; if (ReadIntoBuffer(socket, &control_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(control_data_, content_length, &peer_id, &eoh); if (ok) { if (my_id_ == -1) { // First response. Let's store our server assigned ID. ASSERT(state_ == SIGNING_IN); my_id_ = peer_id; ASSERT(my_id_ != -1); // The body of the response will be a list of already connected peers. if (content_length) { size_t pos = eoh + 4; while (pos < control_data_.size()) { size_t eol = control_data_.find('\n', pos); if (eol == std::string::npos) break; int id = 0; std::string name; bool connected; if (ParseEntry(control_data_.substr(pos, eol - pos), &name, &id, &connected) && id != my_id_) { peers_[id] = name; callback_->OnPeerConnected(id, name); } pos = eol + 1; } } ASSERT(is_connected()); callback_->OnSignedIn(); } else if (state_ == SIGNING_OUT) { Close(); callback_->OnDisconnected(); } else if (state_ == SIGNING_OUT_WAITING) { SignOut(); } } control_data_.clear(); if (state_ == SIGNING_IN) { ASSERT(hanging_get_->GetState() == talk_base::Socket::CS_CLOSED); state_ = CONNECTED; hanging_get_->Connect(server_address_); } } } void PeerConnectionClient::OnHangingGetRead(talk_base::AsyncSocket* socket) { LOG(INFO) << __FUNCTION__; size_t content_length = 0; if (ReadIntoBuffer(socket, &notification_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(notification_data_, content_length, &peer_id, &eoh); if (ok) { // Store the position where the body begins. size_t pos = eoh + 4; if (my_id_ == static_cast<int>(peer_id)) { // A notification about a new member or a member that just // disconnected. int id = 0; std::string name; bool connected = false; if (ParseEntry(notification_data_.substr(pos), &name, &id, &connected)) { if (connected) { peers_[id] = name; callback_->OnPeerConnected(id, name); } else { peers_.erase(id); callback_->OnPeerDisconnected(id); } } } else { OnMessageFromPeer(peer_id, notification_data_.substr(pos)); } } notification_data_.clear(); } if (hanging_get_->GetState() == talk_base::Socket::CS_CLOSED && state_ == CONNECTED) { hanging_get_->Connect(server_address_); } } bool PeerConnectionClient::ParseEntry(const std::string& entry, std::string* name, int* id, bool* connected) { ASSERT(name != NULL); ASSERT(id != NULL); ASSERT(connected != NULL); ASSERT(!entry.empty()); *connected = false; size_t separator = entry.find(','); if (separator != std::string::npos) { *id = atoi(&entry[separator + 1]); name->assign(entry.substr(0, separator)); separator = entry.find(',', separator + 1); if (separator != std::string::npos) { *connected = atoi(&entry[separator + 1]) ? true : false; } } return !name->empty(); } int PeerConnectionClient::GetResponseStatus(const std::string& response) { int status = -1; size_t pos = response.find(' '); if (pos != std::string::npos) status = atoi(&response[pos + 1]); return status; } bool PeerConnectionClient::ParseServerResponse(const std::string& response, size_t content_length, size_t* peer_id, size_t* eoh) { LOG(INFO) << response; int status = GetResponseStatus(response.c_str()); if (status != 200) { LOG(LS_ERROR) << "Received error from server"; Close(); callback_->OnDisconnected(); return false; } *eoh = response.find("\r\n\r\n"); ASSERT(*eoh != std::string::npos); if (*eoh == std::string::npos) return false; *peer_id = -1; // See comment in peer_channel.cc for why we use the Pragma header and // not e.g. "X-Peer-Id". GetHeaderValue(response, *eoh, "\r\nPragma: ", peer_id); return true; } void PeerConnectionClient::OnClose(talk_base::AsyncSocket* socket, int err) { LOG(INFO) << __FUNCTION__; socket->Close(); #ifdef WIN32 if (err != WSAECONNREFUSED) { #else if (err != ECONNREFUSED) { #endif if (socket == hanging_get_.get()) { if (state_ == CONNECTED) { LOG(INFO) << "Issuing a new hanging get"; hanging_get_->Close(); hanging_get_->Connect(server_address_); } } else { callback_->OnMessageSent(err); } } else { // Failed to connect to the server. Close(); callback_->OnDisconnected(); } }
/* * Copyright (c) 2011 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 "peerconnection/samples/client/peer_connection_client.h" #include "peerconnection/samples/client/defaults.h" #include "talk/base/common.h" #include "talk/base/nethelpers.h" #include "talk/base/logging.h" #include "talk/base/stringutils.h" #ifdef WIN32 #include "talk/base/win32socketserver.h" #endif using talk_base::sprintfn; namespace { // This is our magical hangup signal. const char kByeMessage[] = "BYE"; talk_base::AsyncSocket* CreateClientSocket() { #ifdef WIN32 return new talk_base::Win32Socket(); #elif defined(POSIX) talk_base::Thread* thread = talk_base::Thread::Current(); ASSERT(thread != NULL); return thread->socketserver()->CreateAsyncSocket(SOCK_STREAM); #else #error Platform not supported. #endif } } PeerConnectionClient::PeerConnectionClient() : callback_(NULL), control_socket_(CreateClientSocket()), hanging_get_(CreateClientSocket()), state_(NOT_CONNECTED), my_id_(-1) { control_socket_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); hanging_get_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); control_socket_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnConnect); hanging_get_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnHangingGetConnect); control_socket_->SignalReadEvent.connect(this, &PeerConnectionClient::OnRead); hanging_get_->SignalReadEvent.connect(this, &PeerConnectionClient::OnHangingGetRead); } PeerConnectionClient::~PeerConnectionClient() { } int PeerConnectionClient::id() const { return my_id_; } bool PeerConnectionClient::is_connected() const { return my_id_ != -1; } const Peers& PeerConnectionClient::peers() const { return peers_; } void PeerConnectionClient::RegisterObserver( PeerConnectionClientObserver* callback) { ASSERT(!callback_); callback_ = callback; } bool PeerConnectionClient::Connect(const std::string& server, int port, const std::string& client_name) { ASSERT(!server.empty()); ASSERT(!client_name.empty()); if (state_ != NOT_CONNECTED) { LOG(WARNING) << "The client must not be connected before you can call Connect()"; return false; } if (server.empty() || client_name.empty()) return false; if (port <= 0) port = kDefaultServerPort; server_address_.SetIP(server); server_address_.SetPort(port); if (server_address_.IsUnresolved()) { int errcode = 0; hostent* h = talk_base::SafeGetHostByName( server_address_.IPAsString().c_str(), &errcode); if (!h) { LOG(LS_ERROR) << "Failed to resolve host name: " << server_address_.IPAsString(); return false; } else { server_address_.SetResolvedIP( ntohl(*reinterpret_cast<uint32*>(h->h_addr_list[0]))); talk_base::FreeHostEnt(h); } } char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name.c_str()); onconnect_data_ = buffer; bool ret = ConnectControlSocket(); if (ret) state_ = SIGNING_IN; return ret; } bool PeerConnectionClient::SendToPeer(int peer_id, const std::string& message) { if (state_ != CONNECTED) return false; ASSERT(is_connected()); ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED); if (!is_connected() || peer_id == -1) return false; char headers[1024]; sprintfn(headers, sizeof(headers), "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n" "Content-Length: %i\r\n" "Content-Type: text/plain\r\n" "\r\n", my_id_, peer_id, message.length()); onconnect_data_ = headers; onconnect_data_ += message; return ConnectControlSocket(); } bool PeerConnectionClient::SendHangUp(int peer_id) { return SendToPeer(peer_id, kByeMessage); } bool PeerConnectionClient::IsSendingMessage() { return state_ == CONNECTED && control_socket_->GetState() != talk_base::Socket::CS_CLOSED; } bool PeerConnectionClient::SignOut() { if (state_ == NOT_CONNECTED || state_ == SIGNING_OUT) return true; if (hanging_get_->GetState() != talk_base::Socket::CS_CLOSED) hanging_get_->Close(); if (control_socket_->GetState() == talk_base::Socket::CS_CLOSED) { state_ = SIGNING_OUT; if (my_id_ != -1) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); onconnect_data_ = buffer; return ConnectControlSocket(); } else { // Can occur if the app is closed before we finish connecting. return true; } } else { state_ = SIGNING_OUT_WAITING; } return true; } void PeerConnectionClient::Close() { control_socket_->Close(); hanging_get_->Close(); onconnect_data_.clear(); peers_.clear(); my_id_ = -1; state_ = NOT_CONNECTED; } bool PeerConnectionClient::ConnectControlSocket() { ASSERT(control_socket_->GetState() == talk_base::Socket::CS_CLOSED); int err = control_socket_->Connect(server_address_); if (err == SOCKET_ERROR) { Close(); return false; } return true; } void PeerConnectionClient::OnConnect(talk_base::AsyncSocket* socket) { ASSERT(!onconnect_data_.empty()); size_t sent = socket->Send(onconnect_data_.c_str(), onconnect_data_.length()); ASSERT(sent == onconnect_data_.length()); UNUSED(sent); onconnect_data_.clear(); } void PeerConnectionClient::OnHangingGetConnect(talk_base::AsyncSocket* socket) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); int len = strlen(buffer); int sent = socket->Send(buffer, len); ASSERT(sent == len); UNUSED2(sent, len); } void PeerConnectionClient::OnMessageFromPeer(int peer_id, const std::string& message) { if (message.length() == (sizeof(kByeMessage) - 1) && message.compare(kByeMessage) == 0) { callback_->OnPeerDisconnected(peer_id); } else { callback_->OnMessageFromPeer(peer_id, message); } } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, size_t* value) { ASSERT(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { *value = atoi(&data[found + strlen(header_pattern)]); return true; } return false; } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, std::string* value) { ASSERT(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { size_t begin = found + strlen(header_pattern); size_t end = data.find("\r\n", begin); if (end == std::string::npos) end = eoh; value->assign(data.substr(begin, end - begin)); return true; } return false; } bool PeerConnectionClient::ReadIntoBuffer(talk_base::AsyncSocket* socket, std::string* data, size_t* content_length) { LOG(INFO) << __FUNCTION__; char buffer[0xffff]; do { int bytes = socket->Recv(buffer, sizeof(buffer)); if (bytes <= 0) break; data->append(buffer, bytes); } while (true); bool ret = false; size_t i = data->find("\r\n\r\n"); if (i != std::string::npos) { LOG(INFO) << "Headers received"; if (GetHeaderValue(*data, i, "\r\nContent-Length: ", content_length)) { LOG(INFO) << "Expecting " << *content_length << " bytes."; size_t total_response_size = (i + 4) + *content_length; if (data->length() >= total_response_size) { ret = true; std::string should_close; const char kConnection[] = "\r\nConnection: "; if (GetHeaderValue(*data, i, kConnection, &should_close) && should_close.compare("close") == 0) { socket->Close(); } } else { // We haven't received everything. Just continue to accept data. } } else { LOG(LS_ERROR) << "No content length field specified by the server."; } } return ret; } void PeerConnectionClient::OnRead(talk_base::AsyncSocket* socket) { LOG(INFO) << __FUNCTION__; size_t content_length = 0; if (ReadIntoBuffer(socket, &control_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(control_data_, content_length, &peer_id, &eoh); if (ok) { if (my_id_ == -1) { // First response. Let's store our server assigned ID. ASSERT(state_ == SIGNING_IN); my_id_ = peer_id; ASSERT(my_id_ != -1); // The body of the response will be a list of already connected peers. if (content_length) { size_t pos = eoh + 4; while (pos < control_data_.size()) { size_t eol = control_data_.find('\n', pos); if (eol == std::string::npos) break; int id = 0; std::string name; bool connected; if (ParseEntry(control_data_.substr(pos, eol - pos), &name, &id, &connected) && id != my_id_) { peers_[id] = name; callback_->OnPeerConnected(id, name); } pos = eol + 1; } } ASSERT(is_connected()); callback_->OnSignedIn(); } else if (state_ == SIGNING_OUT) { Close(); callback_->OnDisconnected(); } else if (state_ == SIGNING_OUT_WAITING) { SignOut(); } } control_data_.clear(); if (state_ == SIGNING_IN) { ASSERT(hanging_get_->GetState() == talk_base::Socket::CS_CLOSED); state_ = CONNECTED; hanging_get_->Connect(server_address_); } } } void PeerConnectionClient::OnHangingGetRead(talk_base::AsyncSocket* socket) { LOG(INFO) << __FUNCTION__; size_t content_length = 0; if (ReadIntoBuffer(socket, &notification_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(notification_data_, content_length, &peer_id, &eoh); if (ok) { // Store the position where the body begins. size_t pos = eoh + 4; if (my_id_ == static_cast<int>(peer_id)) { // A notification about a new member or a member that just // disconnected. int id = 0; std::string name; bool connected = false; if (ParseEntry(notification_data_.substr(pos), &name, &id, &connected)) { if (connected) { peers_[id] = name; callback_->OnPeerConnected(id, name); } else { peers_.erase(id); callback_->OnPeerDisconnected(id); } } } else { OnMessageFromPeer(peer_id, notification_data_.substr(pos)); } } notification_data_.clear(); } if (hanging_get_->GetState() == talk_base::Socket::CS_CLOSED && state_ == CONNECTED) { hanging_get_->Connect(server_address_); } } bool PeerConnectionClient::ParseEntry(const std::string& entry, std::string* name, int* id, bool* connected) { ASSERT(name != NULL); ASSERT(id != NULL); ASSERT(connected != NULL); ASSERT(!entry.empty()); *connected = false; size_t separator = entry.find(','); if (separator != std::string::npos) { *id = atoi(&entry[separator + 1]); name->assign(entry.substr(0, separator)); separator = entry.find(',', separator + 1); if (separator != std::string::npos) { *connected = atoi(&entry[separator + 1]) ? true : false; } } return !name->empty(); } int PeerConnectionClient::GetResponseStatus(const std::string& response) { int status = -1; size_t pos = response.find(' '); if (pos != std::string::npos) status = atoi(&response[pos + 1]); return status; } bool PeerConnectionClient::ParseServerResponse(const std::string& response, size_t content_length, size_t* peer_id, size_t* eoh) { LOG(INFO) << response; int status = GetResponseStatus(response.c_str()); if (status != 200) { LOG(LS_ERROR) << "Received error from server"; Close(); callback_->OnDisconnected(); return false; } *eoh = response.find("\r\n\r\n"); ASSERT(*eoh != std::string::npos); if (*eoh == std::string::npos) return false; *peer_id = -1; // See comment in peer_channel.cc for why we use the Pragma header and // not e.g. "X-Peer-Id". GetHeaderValue(response, *eoh, "\r\nPragma: ", peer_id); return true; } void PeerConnectionClient::OnClose(talk_base::AsyncSocket* socket, int err) { LOG(INFO) << __FUNCTION__; socket->Close(); #ifdef WIN32 if (err != WSAECONNREFUSED) { #else if (err != ECONNREFUSED) { #endif if (socket == hanging_get_.get()) { if (state_ == CONNECTED) { LOG(INFO) << "Issuing a new hanging get"; hanging_get_->Close(); hanging_get_->Connect(server_address_); } } else { callback_->OnMessageSent(err); } } else { // Failed to connect to the server. Close(); callback_->OnDisconnected(); } }
Fix release mode "unused variable" warnings in peerconnection. Review URL: http://webrtc-codereview.appspot.com/133010
Fix release mode "unused variable" warnings in peerconnection. Review URL: http://webrtc-codereview.appspot.com/133010 git-svn-id: 917f5d3ca488f358c4d40eaec14422cf392ccec9@510 4adac7df-926f-26a2-2b94-8c16560cd09d
C++
bsd-3-clause
mwgoldsmith/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,mwgoldsmith/libilbc,mwgoldsmith/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/libilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,mwgoldsmith/ilbc,TimothyGu/libilbc
cc80f9eb4a3a58caf1050aadb578a09280e68ce0
Testing/Code/Algorithms/itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx
Testing/Code/Algorithms/itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx
/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkImageRegionIterator.h" #include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h" #include "vnl/vnl_math.h" #include <iostream> int main() { //------------------------------------------------------------ // Create two simple images // Two Gaussians with one translated (7,3) pixels from another //------------------------------------------------------------ //Allocate Images typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; enum { ImageDimension = ReferenceType::ImageDimension }; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); // Fill images with a 2D gaussian typedef itk::ImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::ImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; // Set the displacement itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) ); ++ti; } //----------------------------------------------------------- // Set up a the registrator //----------------------------------------------------------- typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration< ReferenceType,TargetType> RegistrationType; RegistrationType::Pointer registrationMethod = RegistrationType::New(); // connect the images registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); // set the transformation centers RegistrationType::PointType transCenter; for( unsigned int j = 0; j < 2; j++ ) { transCenter[j] = double(size[j]) / 2; } registrationMethod->SetTargetTransformationCenter( transCenter ); registrationMethod->SetReferenceTransformationCenter( transCenter ); // set optimization related parameters registrationMethod->SetNumberOfIterations( 500 ); registrationMethod->SetLearningRate( 0.2 ); // // only allow translation - since the metric will allow any // rotation without penalty as image is circular // RegistrationType::ParametersType weights; for( unsigned int j = 0; j < 4; j++ ) { weights[j] = 0.0; } for( unsigned int j=4; j < 6; j++ ) { weights[j] = 1.0; } registrationMethod->SetScalingWeights( weights ); // set metric related parameters registrationMethod->GetMetric()->SetTargetStandardDeviation( 20.0 ); registrationMethod->GetMetric()->SetReferenceStandardDeviation( 20.0 ); registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 ); // start registration registrationMethod->StartRegistration(); // get the results RegistrationType::ParametersType solution = registrationMethod->GetParameters(); std::cout << "Solution is: " << solution << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[6] = { 1, 0, 0, 1, -7, -3 }; for( unsigned int j = 0; j < 4; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.01 ) pass = false; } for( unsigned int j = 4; j < 6; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.5 ) pass = false; } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; }
/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkImageRegionIterator.h" #include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h" #include "vnl/vnl_math.h" #include <iostream> int main() { //------------------------------------------------------------ // Create two simple images // Two Gaussians with one translated (7,3) pixels from another //------------------------------------------------------------ //Allocate Images typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; enum { ImageDimension = ReferenceType::ImageDimension }; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); // Fill images with a 2D gaussian typedef itk::ImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::ImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; // Set the displacement itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) ); ++ti; } //----------------------------------------------------------- // Set up a the registrator //----------------------------------------------------------- typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration< ReferenceType,TargetType> RegistrationType; RegistrationType::Pointer registrationMethod = RegistrationType::New(); // connect the images registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); // set the transformation centers RegistrationType::PointType transCenter; for( unsigned int j = 0; j < 2; j++ ) { transCenter[j] = double(size[j]) / 2; } registrationMethod->SetTargetTransformationCenter( transCenter ); registrationMethod->SetReferenceTransformationCenter( transCenter ); // set optimization related parameters registrationMethod->SetNumberOfIterations( 500 ); registrationMethod->SetLearningRate( 0.2 ); // // only allow translation - since the metric will allow any // rotation without penalty as image is circular // RegistrationType::ParametersType weights; for( unsigned int j = 0; j < 4; j++ ) { weights[j] = 0.0; } for( unsigned int j=4; j < 6; j++ ) { weights[j] = 1.0; } registrationMethod->SetScalingWeights( weights ); // set metric related parameters registrationMethod->GetMetric()->SetTargetStandardDeviation( 20.0 ); registrationMethod->GetMetric()->SetReferenceStandardDeviation( 20.0 ); registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 ); // start registration registrationMethod->StartRegistration(); // get the results RegistrationType::ParametersType solution = registrationMethod->GetParameters(); std::cout << "Solution is: " << solution << std::endl; // // check results to see if it is within range // bool pass = true; double trueParameters[6] = { 1, 0, 0, 1, -7, -3 }; for( unsigned int j = 0; j < 4; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 ) pass = false; } for( unsigned int j = 4; j < 6; j++ ) { if( vnl_math_abs( solution[j] - trueParameters[j] ) > 1.0 ) pass = false; } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; }
make success range larger to allow test to pass for all platforms
FIX: make success range larger to allow test to pass for all platforms
C++
apache-2.0
fuentesdt/InsightToolkit-dev,blowekamp/ITK,ajjl/ITK,jmerkow/ITK,fedral/ITK,biotrump/ITK,GEHC-Surgery/ITK,daviddoria/itkHoughTransform,LucasGandel/ITK,hendradarwin/ITK,atsnyder/ITK,Kitware/ITK,daviddoria/itkHoughTransform,hinerm/ITK,spinicist/ITK,PlutoniumHeart/ITK,stnava/ITK,daviddoria/itkHoughTransform,atsnyder/ITK,vfonov/ITK,paulnovo/ITK,richardbeare/ITK,CapeDrew/DITK,stnava/ITK,rhgong/itk-with-dom,itkvideo/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,rhgong/itk-with-dom,fedral/ITK,rhgong/itk-with-dom,malaterre/ITK,spinicist/ITK,GEHC-Surgery/ITK,paulnovo/ITK,biotrump/ITK,eile/ITK,fuentesdt/InsightToolkit-dev,jmerkow/ITK,blowekamp/ITK,Kitware/ITK,PlutoniumHeart/ITK,paulnovo/ITK,PlutoniumHeart/ITK,daviddoria/itkHoughTransform,stnava/ITK,hinerm/ITK,wkjeong/ITK,thewtex/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,BlueBrain/ITK,malaterre/ITK,paulnovo/ITK,jcfr/ITK,biotrump/ITK,BRAINSia/ITK,heimdali/ITK,jcfr/ITK,Kitware/ITK,stnava/ITK,daviddoria/itkHoughTransform,jmerkow/ITK,CapeDrew/DCMTK-ITK,zachary-williamson/ITK,blowekamp/ITK,thewtex/ITK,atsnyder/ITK,biotrump/ITK,cpatrick/ITK-RemoteIO,itkvideo/ITK,hjmjohnson/ITK,Kitware/ITK,richardbeare/ITK,biotrump/ITK,stnava/ITK,hinerm/ITK,BlueBrain/ITK,hinerm/ITK,fedral/ITK,hendradarwin/ITK,LucasGandel/ITK,zachary-williamson/ITK,itkvideo/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,ajjl/ITK,itkvideo/ITK,fbudin69500/ITK,LucasGandel/ITK,atsnyder/ITK,BRAINSia/ITK,GEHC-Surgery/ITK,rhgong/itk-with-dom,rhgong/itk-with-dom,ajjl/ITK,eile/ITK,msmolens/ITK,BRAINSia/ITK,BRAINSia/ITK,jcfr/ITK,msmolens/ITK,blowekamp/ITK,malaterre/ITK,BlueBrain/ITK,paulnovo/ITK,GEHC-Surgery/ITK,fbudin69500/ITK,fedral/ITK,blowekamp/ITK,msmolens/ITK,cpatrick/ITK-RemoteIO,cpatrick/ITK-RemoteIO,fuentesdt/InsightToolkit-dev,vfonov/ITK,rhgong/itk-with-dom,hjmjohnson/ITK,jmerkow/ITK,fuentesdt/InsightToolkit-dev,thewtex/ITK,Kitware/ITK,zachary-williamson/ITK,ajjl/ITK,fbudin69500/ITK,LucHermitte/ITK,biotrump/ITK,vfonov/ITK,GEHC-Surgery/ITK,ajjl/ITK,richardbeare/ITK,jcfr/ITK,spinicist/ITK,hendradarwin/ITK,GEHC-Surgery/ITK,hinerm/ITK,jcfr/ITK,InsightSoftwareConsortium/ITK,paulnovo/ITK,zachary-williamson/ITK,CapeDrew/DITK,BRAINSia/ITK,PlutoniumHeart/ITK,CapeDrew/DCMTK-ITK,daviddoria/itkHoughTransform,InsightSoftwareConsortium/ITK,jmerkow/ITK,cpatrick/ITK-RemoteIO,wkjeong/ITK,biotrump/ITK,LucHermitte/ITK,eile/ITK,LucasGandel/ITK,malaterre/ITK,malaterre/ITK,fbudin69500/ITK,blowekamp/ITK,CapeDrew/DCMTK-ITK,hjmjohnson/ITK,hendradarwin/ITK,hjmjohnson/ITK,heimdali/ITK,Kitware/ITK,thewtex/ITK,zachary-williamson/ITK,hinerm/ITK,PlutoniumHeart/ITK,CapeDrew/DITK,spinicist/ITK,zachary-williamson/ITK,vfonov/ITK,heimdali/ITK,daviddoria/itkHoughTransform,InsightSoftwareConsortium/ITK,rhgong/itk-with-dom,stnava/ITK,hinerm/ITK,CapeDrew/DCMTK-ITK,wkjeong/ITK,cpatrick/ITK-RemoteIO,blowekamp/ITK,heimdali/ITK,CapeDrew/DITK,LucasGandel/ITK,hjmjohnson/ITK,heimdali/ITK,wkjeong/ITK,spinicist/ITK,jcfr/ITK,msmolens/ITK,fedral/ITK,BlueBrain/ITK,fedral/ITK,heimdali/ITK,spinicist/ITK,fbudin69500/ITK,GEHC-Surgery/ITK,malaterre/ITK,vfonov/ITK,cpatrick/ITK-RemoteIO,eile/ITK,hinerm/ITK,PlutoniumHeart/ITK,hendradarwin/ITK,CapeDrew/DCMTK-ITK,daviddoria/itkHoughTransform,LucHermitte/ITK,daviddoria/itkHoughTransform,hjmjohnson/ITK,paulnovo/ITK,GEHC-Surgery/ITK,fbudin69500/ITK,blowekamp/ITK,LucasGandel/ITK,LucHermitte/ITK,zachary-williamson/ITK,fbudin69500/ITK,fedral/ITK,thewtex/ITK,msmolens/ITK,fedral/ITK,malaterre/ITK,BlueBrain/ITK,eile/ITK,BlueBrain/ITK,atsnyder/ITK,LucHermitte/ITK,jmerkow/ITK,spinicist/ITK,richardbeare/ITK,CapeDrew/DITK,jcfr/ITK,msmolens/ITK,BRAINSia/ITK,hinerm/ITK,atsnyder/ITK,hendradarwin/ITK,CapeDrew/DITK,wkjeong/ITK,richardbeare/ITK,heimdali/ITK,CapeDrew/DITK,LucHermitte/ITK,hendradarwin/ITK,itkvideo/ITK,atsnyder/ITK,zachary-williamson/ITK,ajjl/ITK,LucHermitte/ITK,jmerkow/ITK,itkvideo/ITK,BlueBrain/ITK,ajjl/ITK,CapeDrew/DCMTK-ITK,spinicist/ITK,wkjeong/ITK,itkvideo/ITK,malaterre/ITK,LucHermitte/ITK,PlutoniumHeart/ITK,stnava/ITK,hendradarwin/ITK,PlutoniumHeart/ITK,fuentesdt/InsightToolkit-dev,zachary-williamson/ITK,CapeDrew/DITK,fbudin69500/ITK,jcfr/ITK,malaterre/ITK,jmerkow/ITK,stnava/ITK,eile/ITK,atsnyder/ITK,CapeDrew/DCMTK-ITK,fuentesdt/InsightToolkit-dev,vfonov/ITK,eile/ITK,eile/ITK,paulnovo/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,cpatrick/ITK-RemoteIO,BlueBrain/ITK,wkjeong/ITK,thewtex/ITK,biotrump/ITK,richardbeare/ITK,richardbeare/ITK,msmolens/ITK,wkjeong/ITK,hjmjohnson/ITK,vfonov/ITK,ajjl/ITK,InsightSoftwareConsortium/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DITK,fuentesdt/InsightToolkit-dev,LucasGandel/ITK,itkvideo/ITK,spinicist/ITK,eile/ITK,atsnyder/ITK,itkvideo/ITK,heimdali/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,stnava/ITK,msmolens/ITK,CapeDrew/DCMTK-ITK
4c6931f3cb0a0e10f9798dcdacc2ab57a36a22bf
translator.cpp
translator.cpp
/****************************************************************************** * Copyright (C) 2016 Kitsune Ral <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "translator.h" #include "analyzer.h" #include "printer.h" #include "yaml.h" #include <QtCore/QDir> #include <regex> using namespace std; void addTypeAttributes(TypeUsage& typeUsage, const YamlMap& attributesMap) { for (const auto& attr: attributesMap) { auto attrName = attr.first.as<string>(); if (attrName == "type") continue; switch (attr.second.Type()) { case YAML::NodeType::Null: typeUsage.attributes.emplace(move(attrName), string{}); break; case YAML::NodeType::Scalar: typeUsage.attributes.emplace(move(attrName), attr.second.as<string>()); break; case YAML::NodeType::Sequence: if (const auto& seq = attr.second.asSequence()) typeUsage.lists.emplace(move(attrName), seq.asStrings()); break; default: throw YamlException(attr.second, "Malformed attribute"); } } } TypeUsage parseTargetType(const YamlNode& yamlTypeNode) { using YAML::NodeType; if (yamlTypeNode.Type() == NodeType::Null) return {}; if (yamlTypeNode.Type() == NodeType::Scalar) return TypeUsage(yamlTypeNode.as<string>()); const auto yamlTypeMap = yamlTypeNode.asMap(); TypeUsage typeUsage { yamlTypeMap["type"].as<string>("") }; addTypeAttributes(typeUsage, yamlTypeMap); return typeUsage; } TypeUsage parseTargetType(const YamlNode& yamlTypeNode, const YamlMap& commonAttributesYaml) { auto tu = parseTargetType(yamlTypeNode); addTypeAttributes(tu, commonAttributesYaml); return tu; } template <typename FnT> void parseEntries(const YamlSequence& entriesYaml, FnT inserter, const YamlMap& commonAttributesYaml = {}) { for (const YamlMap typesBlockYaml: entriesYaml) { switch (typesBlockYaml.size()) { case 0: throw YamlException(typesBlockYaml, "Empty type entry"); case 1: { const auto& typeYaml = typesBlockYaml.front(); inserter(typeYaml.first.as<string>(), typeYaml.second, commonAttributesYaml); break; } case 2: if (typesBlockYaml["+on"] && typesBlockYaml["+set"]) { parseEntries(typesBlockYaml.get("+on").asSequence(), inserter, typesBlockYaml.get("+set").asMap()); break; } // FALLTHROUGH default: throw YamlException(typesBlockYaml, "Too many entries in the map, check indentation"); } } } pair_vector_t<TypeUsage> parseTypeEntry(const YamlNode& targetTypeYaml, const YamlMap& commonAttributesYaml = {}) { switch (targetTypeYaml.Type()) { case YAML::NodeType::Scalar: // Use a type with no regard to format case YAML::NodeType::Map: // Same, with attributes for the target type { return { { string(), parseTargetType(targetTypeYaml, commonAttributesYaml) } }; } case YAML::NodeType::Sequence: // A list of formats for the type { pair_vector_t<TypeUsage> targetTypes; parseEntries(targetTypeYaml.asSequence(), [&targetTypes](string formatName, const YamlNode& formatYaml, const YamlMap& commonAttrsYaml) { if (formatName.empty()) formatName = "/"; // Empty format means all formats else if (formatName.size() > 1 && formatName.front() == '/' && formatName.back() == '/') { formatName.pop_back(); } targetTypes.emplace_back(move(formatName), parseTargetType(formatYaml, commonAttrsYaml)); }, commonAttributesYaml); return targetTypes; } default: throw YamlException(targetTypeYaml, "Malformed type entry"); } } pair_vector_t<string> loadStringMap(const YamlMap& yaml) { pair_vector_t<string> stringMap; for (const auto& subst: yaml) { auto pattern = subst.first.as<string>(); if (Q_UNLIKELY(pattern.empty())) clog << subst.first.location() << ": warning: empty pattern in substitutions, skipping" << endl; else if (Q_UNLIKELY(pattern.size() > 1 && pattern.front() != '/' && pattern.back() == '/')) clog << subst.first.location() << ": warning: invalid regular expression, skipping" << endl << "(use a regex with \\/ to match strings beginning with /)"; else { if (pattern.front() == '/' && pattern.back() == '/') pattern.pop_back(); stringMap.emplace_back(pattern, subst.second.as<string>()); } } return stringMap; } Translator::Translator(const QString& configFilePath, QString outputDirPath) : _outputDirPath(outputDirPath.endsWith('/') ? move(outputDirPath) : outputDirPath + '/') { auto cfp = configFilePath.toStdString(); cout << "Using config file at " << cfp << endl; const auto configY = YamlMap::loadFromFile(cfp); const auto& analyzerYaml = configY["analyzer"].asMap(); _substitutions = loadStringMap(analyzerYaml["subst"].asMap()); _identifiers = loadStringMap(analyzerYaml["identifiers"].asMap()); parseEntries(analyzerYaml["types"].asSequence(), [this](const string& name, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { _typesMap.emplace_back(name, parseTypeEntry(typeYaml, commonAttrsYaml)); }); Printer::context_type env; using namespace kainjow::mustache; const auto& mustacheYaml = configY["mustache"].asMap(); const auto& envYaml = mustacheYaml["constants"].asMap(); for (const auto& p: envYaml) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) { env.set(pName, p.second.as<string>()); continue; } const auto pDefinition = p.second.asMap().front(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } const auto& partialsYaml = mustacheYaml["partials"].asMap(); for (const auto& p: partialsYaml) { env.set(p.first.as<string>(), partial { [s = p.second.as<string>()] { return s; } }); } vector<string> outputFiles; const auto& templatesYaml = mustacheYaml["templates"].asSequence(); for (const auto& f: templatesYaml) outputFiles.emplace_back(f.as<string>()); QString configDir = QFileInfo(configFilePath).dir().path(); if (!configDir.isEmpty()) configDir += '/'; _printer = std::make_unique<Printer>( move(env), outputFiles, configDir.toStdString(), _outputDirPath.toStdString(), mustacheYaml["outFilesList"].as<string>("")); } Translator::~Translator() = default; TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, const string& baseName) const { for (const auto& swTypePair: _typesMap) if (swTypePair.first == swaggerType) for (const auto& swFormatPair: swTypePair.second) { const auto& swFormat = swFormatPair.first; if (swFormat == swaggerFormat || (!swFormat.empty() && swFormat.front() == '/' && regex_search(swaggerFormat, regex(++swFormat.begin(), swFormat.end())))) { // FIXME (#22): The below is a source of great inefficiency. // TypeUsage should become a handle to an instance of // a newly-made TypeDefinition type that would own all // the stuff TypeUsage now has, except innerTypes auto tu = swFormatPair.second; // Fallback chain: baseName, swaggerFormat, swaggerType tu.baseName = baseName.empty() ? swaggerFormat.empty() ? swaggerType : swaggerFormat : baseName; return tu; } } return {}; } string Translator::mapIdentifier(const string& baseName, const string& scope) const { auto scopedName = scope; scopedName.append(1, '/').append(baseName); for (const auto& entry: _identifiers) { const auto& pattn = entry.first; if (!pattn.empty() && pattn.front() == '/') return regex_replace(scopedName, regex(++pattn.begin(), pattn.end()), entry.second); if (pattn == baseName || pattn == scopedName) return entry.second; } return baseName; } Model Translator::processFile(string filePath, string baseDirPath, InOut inOut, bool skipTrivial) const { auto m = Analyzer(move(filePath), move(baseDirPath), *this) .loadModel(_substitutions, inOut); if (m.empty() || (m.trivial() && skipTrivial)) return m; QDir d { _outputDirPath + m.fileDir.c_str() }; if (!d.exists() && !d.mkpath(".")) throw Exception { "Cannot create output directory" }; m.dstFiles = _printer->print(m); return m; }
/****************************************************************************** * Copyright (C) 2016 Kitsune Ral <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "translator.h" #include "analyzer.h" #include "printer.h" #include "yaml.h" #include <QtCore/QDir> #include <regex> using namespace std; void addTypeAttributes(TypeUsage& typeUsage, const YamlMap& attributesMap) { for (const auto& attr: attributesMap) { auto attrName = attr.first.as<string>(); if (attrName == "type") continue; switch (attr.second.Type()) { case YAML::NodeType::Null: typeUsage.attributes.emplace(move(attrName), string{}); break; case YAML::NodeType::Scalar: typeUsage.attributes.emplace(move(attrName), attr.second.as<string>()); break; case YAML::NodeType::Sequence: if (const auto& seq = attr.second.asSequence()) typeUsage.lists.emplace(move(attrName), seq.asStrings()); break; default: throw YamlException(attr.second, "Malformed attribute"); } } } TypeUsage parseTargetType(const YamlNode& yamlTypeNode) { using YAML::NodeType; if (yamlTypeNode.Type() == NodeType::Null) return {}; if (yamlTypeNode.Type() == NodeType::Scalar) return TypeUsage(yamlTypeNode.as<string>()); const auto yamlTypeMap = yamlTypeNode.asMap(); TypeUsage typeUsage { yamlTypeMap["type"].as<string>("") }; addTypeAttributes(typeUsage, yamlTypeMap); return typeUsage; } TypeUsage parseTargetType(const YamlNode& yamlTypeNode, const YamlMap& commonAttributesYaml) { auto tu = parseTargetType(yamlTypeNode); addTypeAttributes(tu, commonAttributesYaml); return tu; } template <typename FnT> void parseEntries(const YamlSequence& entriesYaml, FnT inserter, const YamlMap& commonAttributesYaml = {}) { for (const YamlMap typesBlockYaml: entriesYaml) { switch (typesBlockYaml.size()) { case 0: throw YamlException(typesBlockYaml, "Empty type entry"); case 1: { const auto& typeYaml = typesBlockYaml.front(); inserter(typeYaml.first.as<string>(), typeYaml.second, commonAttributesYaml); break; } case 2: if (typesBlockYaml["+on"] && typesBlockYaml["+set"]) { parseEntries(typesBlockYaml.get("+on").asSequence(), inserter, typesBlockYaml.get("+set").asMap()); break; } // FALLTHROUGH default: throw YamlException(typesBlockYaml, "Too many entries in the map, check indentation"); } } } pair_vector_t<TypeUsage> parseTypeEntry(const YamlNode& targetTypeYaml, const YamlMap& commonAttributesYaml = {}) { switch (targetTypeYaml.Type()) { case YAML::NodeType::Scalar: // Use a type with no regard to format case YAML::NodeType::Map: // Same, with attributes for the target type { return { { string(), parseTargetType(targetTypeYaml, commonAttributesYaml) } }; } case YAML::NodeType::Sequence: // A list of formats for the type { pair_vector_t<TypeUsage> targetTypes; parseEntries(targetTypeYaml.asSequence(), [&targetTypes](string formatName, const YamlNode& formatYaml, const YamlMap& commonAttrsYaml) { if (formatName.empty()) formatName = "/"; // Empty format means all formats else if (formatName.size() > 1 && formatName.front() == '/' && formatName.back() == '/') { formatName.pop_back(); } targetTypes.emplace_back(move(formatName), parseTargetType(formatYaml, commonAttrsYaml)); }, commonAttributesYaml); return targetTypes; } default: throw YamlException(targetTypeYaml, "Malformed type entry"); } } pair_vector_t<string> loadStringMap(const YamlMap& yaml) { pair_vector_t<string> stringMap; for (const auto& subst: yaml) { auto pattern = subst.first.as<string>(); if (Q_UNLIKELY(pattern.empty())) clog << subst.first.location() << ": warning: empty pattern in substitutions, skipping" << endl; else if (Q_UNLIKELY(pattern.size() > 1 && pattern.front() != '/' && pattern.back() == '/')) clog << subst.first.location() << ": warning: invalid regular expression, skipping" << endl << "(use a regex with \\/ to match strings beginning with /)"; else { if (pattern.front() == '/' && pattern.back() == '/') pattern.pop_back(); stringMap.emplace_back(pattern, subst.second.as<string>()); } } return stringMap; } Translator::Translator(const QString& configFilePath, QString outputDirPath) : _outputDirPath(outputDirPath.endsWith('/') ? move(outputDirPath) : outputDirPath + '/') { auto cfp = configFilePath.toStdString(); cout << "Using config file at " << cfp << endl; const auto configY = YamlMap::loadFromFile(cfp); const auto& analyzerYaml = configY["analyzer"].asMap(); _substitutions = loadStringMap(analyzerYaml["subst"].asMap()); _identifiers = loadStringMap(analyzerYaml["identifiers"].asMap()); parseEntries(analyzerYaml["types"].asSequence(), [this](const string& name, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { _typesMap.emplace_back(name, parseTypeEntry(typeYaml, commonAttrsYaml)); }); Printer::context_type env; using namespace kainjow::mustache; const auto& mustacheYaml = configY["mustache"].asMap(); const auto& envYaml = mustacheYaml["constants"].asMap(); for (const auto& p: envYaml) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) { env.set(pName, p.second.as<string>()); continue; } const auto pDefinition = p.second.asMap().front(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } const auto& partialsYaml = mustacheYaml["partials"].asMap(); for (const auto& p: partialsYaml) { env.set(p.first.as<string>(), partial { [s = p.second.as<string>()] { return s; } }); } vector<string> outputFiles; const auto& templatesYaml = mustacheYaml["templates"].asSequence(); for (const auto& f: templatesYaml) outputFiles.emplace_back(f.as<string>()); QString configDir = QFileInfo(configFilePath).dir().path(); if (!configDir.isEmpty()) configDir += '/'; _printer = std::make_unique<Printer>( move(env), outputFiles, configDir.toStdString(), _outputDirPath.toStdString(), mustacheYaml["outFilesList"].as<string>("")); } Translator::~Translator() = default; TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, const string& baseName) const { TypeUsage tu; for (const auto& swTypePair: _typesMap) if (swTypePair.first == swaggerType) for (const auto& swFormatPair: swTypePair.second) { const auto& swFormat = swFormatPair.first; if (swFormat == swaggerFormat || (!swFormat.empty() && swFormat.front() == '/' && regex_search(swaggerFormat, regex(++swFormat.begin(), swFormat.end())))) { // FIXME (#22): a source of great inefficiency. // TypeUsage should become a handle to an instance of // a newly-made TypeDefinition type that would own all // the stuff TypeUsage now has, except innerTypes tu = swFormatPair.second; goto conclusion; } } conclusion: // Fallback chain: baseName, swaggerFormat, swaggerType tu.baseName = baseName.empty() ? swaggerFormat.empty() ? swaggerType : swaggerFormat : baseName; return tu; } string Translator::mapIdentifier(const string& baseName, const string& scope) const { auto scopedName = scope; scopedName.append(1, '/').append(baseName); for (const auto& entry: _identifiers) { const auto& pattn = entry.first; if (!pattn.empty() && pattn.front() == '/') return regex_replace(scopedName, regex(++pattn.begin(), pattn.end()), entry.second); if (pattn == baseName || pattn == scopedName) return entry.second; } return baseName; } Model Translator::processFile(string filePath, string baseDirPath, InOut inOut, bool skipTrivial) const { auto m = Analyzer(move(filePath), move(baseDirPath), *this) .loadModel(_substitutions, inOut); if (m.empty() || (m.trivial() && skipTrivial)) return m; QDir d { _outputDirPath + m.fileDir.c_str() }; if (!d.exists() && !d.mkpath(".")) throw Exception { "Cannot create output directory" }; m.dstFiles = _printer->print(m); return m; }
make sure baseName is filled even in empty types
Translator::mapType(): make sure baseName is filled even in empty types
C++
agpl-3.0
KitsuneRal/matrix-csapi-generator
3647031a27da9cfef1353166149c76e8ab58de5b
filter/source/odfflatxml/OdfFlatXml.cxx
filter/source/odfflatxml/OdfFlatXml.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Peter Jentsch <[email protected]> * * Portions created by the Initial Developer are Copyright (C) 2011 the * Initial Developer. All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include <cppuhelper/factory.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/implbase3.hxx> #include <cppuhelper/implbase.hxx> #include <sax/tools/documenthandleradapter.hxx> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Type.hxx> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/xml/XImportFilter.hpp> #include <com/sun/star/xml/XExportFilter.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <com/sun/star/xml/sax/SAXException.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <registration.hxx> using namespace ::rtl; using namespace ::cppu; using namespace ::osl; using namespace ::sax; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; namespace filter { namespace odfflatxml { /* * OdfFlatXml export and imports ODF flat XML documents by plugging a pass-through * filter implementation into XmlFilterAdaptor. */ class OdfFlatXml : public WeakImplHelper3<XImportFilter, XExportFilter, DocumentHandlerAdapter> { private: Reference< XMultiServiceFactory > m_rServiceFactory; public: OdfFlatXml(const Reference<XMultiServiceFactory> &r) : m_rServiceFactory(r) { } // XImportFilter virtual sal_Bool SAL_CALL importer(const Sequence< PropertyValue >& sourceData, const Reference< XDocumentHandler >& docHandler, const Sequence< OUString >& userData) throw (IllegalArgumentException, RuntimeException); // XExportFilter virtual sal_Bool SAL_CALL exporter( const Sequence< PropertyValue >& sourceData, const Sequence< OUString >& userData) throw (IllegalArgumentException, RuntimeException); // UNO component helper methods static OUString impl_getImplementationName(); static Sequence< OUString > impl_getSupportedServiceNames(); static Reference< XInterface > impl_createInstance(const Reference< XMultiServiceFactory >& fact); }; } } using namespace ::filter::odfflatxml; sal_Bool OdfFlatXml::importer( const Sequence< PropertyValue >& sourceData, const Reference< XDocumentHandler >& docHandler, const Sequence< OUString >& /* userData */) throw (IllegalArgumentException, RuntimeException) { // Read InputStream to read from and an URL used for the system id // of the InputSource we create from the given sourceData sequence Reference<XInputStream> inputStream; OUString paramName; OUString url; sal_Int32 paramCount = sourceData.getLength(); for (sal_Int32 paramIdx = 0; paramIdx < paramCount; paramIdx++) { paramName = sourceData[paramIdx].Name; if (paramName.equalsAscii("InputStream")) sourceData[paramIdx].Value >>= inputStream; else if (paramName.equalsAscii("URL")) sourceData[paramIdx].Value >>= url; } OSL_ASSERT(inputStream.is()); if (!inputStream.is()) return sal_False; OUString SAX_PARSER_SERVICE( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser")); Reference<XParser> saxParser(m_rServiceFactory->createInstance( SAX_PARSER_SERVICE), UNO_QUERY); OSL_ASSERT(saxParser.is()); if (!saxParser.is()) return sal_False; InputSource inputSource; inputSource.sSystemId = url; inputSource.sPublicId = url; inputSource.aInputStream = inputStream; saxParser->setDocumentHandler(docHandler); try { saxParser->parseStream(inputSource); } catch (Exception &exc) { OString msg = OUStringToOString(exc.Message, RTL_TEXTENCODING_ASCII_US); OSL_FAIL(msg); return sal_False; } return sal_True; } sal_Bool OdfFlatXml::exporter(const Sequence< PropertyValue >& sourceData, const Sequence< OUString >& /*msUserData*/) throw (IllegalArgumentException, RuntimeException) { OUString paramName; OUString targetURL; Reference<XOutputStream> outputStream; // Read output stream and target URL from the parameters given in sourceData. sal_Int32 paramCount = sourceData.getLength(); for (sal_Int32 paramIdx = 0; paramIdx < paramCount; paramIdx++) { paramName = sourceData[paramIdx].Name; if (paramName.equalsAscii("OutputStream")) sourceData[paramIdx].Value >>= outputStream; else if (paramName.equalsAscii("URL")) sourceData[paramIdx].Value >>= targetURL; } if (!getDelegate().is()) { OUString SAX_WRITER_SERVICE(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer")); Reference< XDocumentHandler > saxWriter(m_rServiceFactory->createInstance(SAX_WRITER_SERVICE), UNO_QUERY); setDelegate(saxWriter); if (!getDelegate().is()) return sal_False; } // get data source interface ... Reference<XActiveDataSource> dataSource(getDelegate(), UNO_QUERY); OSL_ASSERT(dataSource.is()); if (!dataSource.is()) return sal_False; OSL_ASSERT(outputStream.is()); if (!outputStream.is()) return sal_False; dataSource->setOutputStream(outputStream); return sal_True; } OUString OdfFlatXml::impl_getImplementationName() { return OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.filter.OdfFlatXml")); } Sequence< OUString > OdfFlatXml::impl_getSupportedServiceNames() { Sequence< OUString > lServiceNames(2); lServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.ImportFilter" )); lServiceNames[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.ExportFilter" )); return lServiceNames; } Reference< XInterface > SAL_CALL OdfFlatXml::impl_createInstance(const Reference< XMultiServiceFactory >& fact) { return Reference<XInterface> ((OWeakObject *) new OdfFlatXml(fact)); } _COMPHELPER_COMPONENT_GETIMPLEMENTATIONENVIRONMENT // extern "C" component_writeInfo() _COMPHELPER_COMPONENT_WRITEINFO ( _COMPHELPER_COMPONENTINFO( OdfFlatXml, OdfFlatXml::impl_getImplementationName(), OdfFlatXml::impl_getSupportedServiceNames()) ) // extern "C" component_getFactory() _COMPHELPER_COMPONENT_GETFACTORY ( {}, _COMPHELPER_ONEINSTANCEFACTORY( OdfFlatXml::impl_getImplementationName(), OdfFlatXml::impl_getSupportedServiceNames(), OdfFlatXml::impl_createInstance) ) /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Peter Jentsch <[email protected]> * * Portions created by the Initial Developer are Copyright (C) 2011 the * Initial Developer. All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_filter.hxx" #include <cppuhelper/factory.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/implbase3.hxx> #include <cppuhelper/implbase.hxx> #include <sax/tools/documenthandleradapter.hxx> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Type.hxx> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/xml/XImportFilter.hpp> #include <com/sun/star/xml/XExportFilter.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <com/sun/star/xml/sax/SAXException.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <registration.hxx> using namespace ::rtl; using namespace ::cppu; using namespace ::osl; using namespace ::sax; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::xml; using namespace ::com::sun::star::xml::sax; namespace filter { namespace odfflatxml { /* * OdfFlatXml export and imports ODF flat XML documents by plugging a pass-through * filter implementation into XmlFilterAdaptor. */ class OdfFlatXml : public WeakImplHelper3<XImportFilter, XExportFilter, DocumentHandlerAdapter> { private: Reference< XMultiServiceFactory > m_rServiceFactory; public: OdfFlatXml(const Reference<XMultiServiceFactory> &r) : m_rServiceFactory(r) { } // XImportFilter virtual sal_Bool SAL_CALL importer(const Sequence< PropertyValue >& sourceData, const Reference< XDocumentHandler >& docHandler, const Sequence< OUString >& userData) throw (IllegalArgumentException, RuntimeException); // XExportFilter virtual sal_Bool SAL_CALL exporter( const Sequence< PropertyValue >& sourceData, const Sequence< OUString >& userData) throw (IllegalArgumentException, RuntimeException); // UNO component helper methods static OUString impl_getImplementationName(); static Sequence< OUString > impl_getSupportedServiceNames(); static Reference< XInterface > impl_createInstance(const Reference< XMultiServiceFactory >& fact); }; } } using namespace ::filter::odfflatxml; sal_Bool OdfFlatXml::importer( const Sequence< PropertyValue >& sourceData, const Reference< XDocumentHandler >& docHandler, const Sequence< OUString >& /* userData */) throw (IllegalArgumentException, RuntimeException) { // Read InputStream to read from and an URL used for the system id // of the InputSource we create from the given sourceData sequence Reference<XInputStream> inputStream; OUString paramName; OUString url; sal_Int32 paramCount = sourceData.getLength(); for (sal_Int32 paramIdx = 0; paramIdx < paramCount; paramIdx++) { paramName = sourceData[paramIdx].Name; if (paramName.equalsAscii("InputStream")) sourceData[paramIdx].Value >>= inputStream; else if (paramName.equalsAscii("URL")) sourceData[paramIdx].Value >>= url; } OSL_ASSERT(inputStream.is()); if (!inputStream.is()) return sal_False; OUString SAX_PARSER_SERVICE( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser")); Reference<XParser> saxParser(m_rServiceFactory->createInstance( SAX_PARSER_SERVICE), UNO_QUERY); OSL_ASSERT(saxParser.is()); if (!saxParser.is()) return sal_False; InputSource inputSource; inputSource.sSystemId = url; inputSource.sPublicId = url; inputSource.aInputStream = inputStream; saxParser->setDocumentHandler(docHandler); try { saxParser->parseStream(inputSource); } catch (Exception &exc) { OString msg = OUStringToOString(exc.Message, RTL_TEXTENCODING_ASCII_US); OSL_FAIL(msg.getStr()); return sal_False; } return sal_True; } sal_Bool OdfFlatXml::exporter(const Sequence< PropertyValue >& sourceData, const Sequence< OUString >& /*msUserData*/) throw (IllegalArgumentException, RuntimeException) { OUString paramName; OUString targetURL; Reference<XOutputStream> outputStream; // Read output stream and target URL from the parameters given in sourceData. sal_Int32 paramCount = sourceData.getLength(); for (sal_Int32 paramIdx = 0; paramIdx < paramCount; paramIdx++) { paramName = sourceData[paramIdx].Name; if (paramName.equalsAscii("OutputStream")) sourceData[paramIdx].Value >>= outputStream; else if (paramName.equalsAscii("URL")) sourceData[paramIdx].Value >>= targetURL; } if (!getDelegate().is()) { OUString SAX_WRITER_SERVICE(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer")); Reference< XDocumentHandler > saxWriter(m_rServiceFactory->createInstance(SAX_WRITER_SERVICE), UNO_QUERY); setDelegate(saxWriter); if (!getDelegate().is()) return sal_False; } // get data source interface ... Reference<XActiveDataSource> dataSource(getDelegate(), UNO_QUERY); OSL_ASSERT(dataSource.is()); if (!dataSource.is()) return sal_False; OSL_ASSERT(outputStream.is()); if (!outputStream.is()) return sal_False; dataSource->setOutputStream(outputStream); return sal_True; } OUString OdfFlatXml::impl_getImplementationName() { return OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.filter.OdfFlatXml")); } Sequence< OUString > OdfFlatXml::impl_getSupportedServiceNames() { Sequence< OUString > lServiceNames(2); lServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.ImportFilter" )); lServiceNames[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.ExportFilter" )); return lServiceNames; } Reference< XInterface > SAL_CALL OdfFlatXml::impl_createInstance(const Reference< XMultiServiceFactory >& fact) { return Reference<XInterface> ((OWeakObject *) new OdfFlatXml(fact)); } _COMPHELPER_COMPONENT_GETIMPLEMENTATIONENVIRONMENT // extern "C" component_writeInfo() _COMPHELPER_COMPONENT_WRITEINFO ( _COMPHELPER_COMPONENTINFO( OdfFlatXml, OdfFlatXml::impl_getImplementationName(), OdfFlatXml::impl_getSupportedServiceNames()) ) // extern "C" component_getFactory() _COMPHELPER_COMPONENT_GETFACTORY ( {}, _COMPHELPER_ONEINSTANCEFACTORY( OdfFlatXml::impl_getImplementationName(), OdfFlatXml::impl_getSupportedServiceNames(), OdfFlatXml::impl_createInstance) ) /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Use getStr() on OString
Use getStr() on OString
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
64f036b4965a0338d5ff7e30cd673982d993848d
folly/wangle/acceptor/TransportInfo.cpp
folly/wangle/acceptor/TransportInfo.cpp
/* * Copyright (c) 2015, 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 <folly/wangle/acceptor/TransportInfo.h> #include <sys/socket.h> #include <sys/types.h> #include <folly/io/async/AsyncSocket.h> using std::chrono::microseconds; using std::map; using std::string; namespace folly { bool TransportInfo::initWithSocket(const AsyncSocket* sock) { #if defined(__linux__) || defined(__FreeBSD__) if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { tcpinfoErrno = errno; return false; } rtt = microseconds(tcpinfo.tcpi_rtt); /* The ratio of packet retransmission (rtx) is a good indicator of network * bandwidth condition. Unfortunately, the number of segmentOut is not * available in current tcpinfo. To workaround this limitation, totalBytes * and MSS are used to estimate it. */ if (tcpinfo.tcpi_total_retrans == 0) { rtx = 0; } else if (tcpinfo.tcpi_total_retrans > 0 && tcpinfo.tcpi_snd_mss > 0 && totalBytes > 0) { // numSegmentOut is the underestimation of the number of tcp packets sent double numSegmentOut = double(totalBytes) / tcpinfo.tcpi_snd_mss; // so rtx is the overestimation of actual packet retransmission rate rtx = tcpinfo.tcpi_total_retrans / numSegmentOut; } else { rtx = -1; } validTcpinfo = true; #else tcpinfoErrno = EINVAL; rtt = microseconds(-1); rtx = -1; #endif return true; } int64_t TransportInfo::readRTT(const AsyncSocket* sock) { #if defined(__linux__) || defined(__FreeBSD__) struct tcp_info tcpinfo; if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { return -1; } return tcpinfo.tcpi_rtt; #else return -1; #endif } #if defined(__linux__) || defined(__FreeBSD__) bool TransportInfo::readTcpInfo(struct tcp_info* tcpinfo, const AsyncSocket* sock) { socklen_t len = sizeof(struct tcp_info); if (!sock) { return false; } if (getsockopt(sock->getFd(), IPPROTO_TCP, TCP_INFO, (void*) tcpinfo, &len) < 0) { VLOG(4) << "Error calling getsockopt(): " << strerror(errno); return false; } return true; } #endif } // folly
/* * Copyright (c) 2015, 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 <folly/wangle/acceptor/TransportInfo.h> #include <sys/socket.h> #include <sys/types.h> #include <folly/io/async/AsyncSocket.h> using std::chrono::microseconds; using std::map; using std::string; namespace folly { bool TransportInfo::initWithSocket(const AsyncSocket* sock) { #if defined(__linux__) || defined(__FreeBSD__) if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { tcpinfoErrno = errno; return false; } rtt = microseconds(tcpinfo.tcpi_rtt); /* The ratio of packet retransmission (rtx) is a good indicator of network * bandwidth condition. Unfortunately, the number of segmentOut is not * available in current tcpinfo. To workaround this limitation, totalBytes * and MSS are used to estimate it. */ #if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 17 if (tcpinfo.tcpi_total_retrans == 0) { rtx = 0; } else if (tcpinfo.tcpi_total_retrans > 0 && tcpinfo.tcpi_snd_mss > 0 && totalBytes > 0) { // numSegmentOut is the underestimation of the number of tcp packets sent double numSegmentOut = double(totalBytes) / tcpinfo.tcpi_snd_mss; // so rtx is the overestimation of actual packet retransmission rate rtx = tcpinfo.tcpi_total_retrans / numSegmentOut; } else { rtx = -1; } #else rtx = -1; #endif // __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 17 validTcpinfo = true; #else tcpinfoErrno = EINVAL; rtt = microseconds(-1); rtx = -1; #endif return true; } int64_t TransportInfo::readRTT(const AsyncSocket* sock) { #if defined(__linux__) || defined(__FreeBSD__) struct tcp_info tcpinfo; if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { return -1; } return tcpinfo.tcpi_rtt; #else return -1; #endif } #if defined(__linux__) || defined(__FreeBSD__) bool TransportInfo::readTcpInfo(struct tcp_info* tcpinfo, const AsyncSocket* sock) { socklen_t len = sizeof(struct tcp_info); if (!sock) { return false; } if (getsockopt(sock->getFd(), IPPROTO_TCP, TCP_INFO, (void*) tcpinfo, &len) < 0) { VLOG(4) << "Error calling getsockopt(): " << strerror(errno); return false; } return true; } #endif } // folly
fix the compling error caused by tcpinfo of low version
fix the compling error caused by tcpinfo of low version Summary: my D2097198 break the project relying on old glibc Test Plan: compling Reviewed By: [email protected] Subscribers: trunkagent, fugalh, folly-diffs@, jsedgwick, yfeldblum, chalfant FB internal diff: D2135297 Tasks: 7283522 Signature: t1:2135297:1433791259:8b82b8d9b16da32be54c0dff1214fa20c94840e2
C++
apache-2.0
constantine001/folly,Eagle-X/folly,constantine001/folly,kernelim/folly,upsoft/folly,yangjin-unique/folly,cole14/folly,CJstar/folly,SeanRBurton/folly,gavioto/folly,gaoyingie/folly,constantine001/folly,juniway/folly,bobegir/folly,CJstar/folly,shaobz/folly,bsampath/folly,shaobz/folly,constantine001/folly,guker/folly,fw1121/folly,SeanRBurton/folly,stonegithubs/folly,project-zerus/folly,PPC64/folly,bowlofstew/folly,clearlylin/folly,stonegithubs/folly,brunomorishita/folly,bikong2/folly,cole14/folly,Hincoin/folly,zhiweicai/folly,mqeizi/folly,gaoyingie/folly,Eagle-X/folly,sakishum/folly,lifei/folly,project-zerus/folly,chjp2046/folly,colemancda/folly,xzmagic/folly,upsoft/folly,clearlylin/folly,floxard/folly,yangjin-unique/folly,yangjin-unique/folly,renyinew/folly,clearlylin/folly,reddit/folly,tempbottle/folly,sonnyhu/folly,bobegir/folly,brunomorishita/folly,raphaelamorim/folly,Orvid/folly,shaobz/folly,fw1121/folly,renyinew/folly,guker/folly,bowlofstew/folly,doctaweeks/folly,rklabs/folly,shaobz/folly,alexst07/folly,raphaelamorim/folly,floxard/folly,renyinew/folly,yangjin-unique/folly,doctaweeks/folly,bobegir/folly,gavioto/folly,PoisonBOx/folly,clearlylin/folly,nickhen/folly,sonnyhu/folly,Orvid/folly,arg0/folly,brunomorishita/folly,lifei/folly,nickhen/folly,fw1121/folly,wildinto/folly,sakishum/folly,colemancda/folly,SeanRBurton/folly,sonnyhu/folly,bobegir/folly,KSreeHarsha/folly,charsyam/folly,mqeizi/folly,upsoft/folly,bobegir/folly,project-zerus/folly,CJstar/folly,kernelim/folly,arg0/folly,leolujuyi/folly,clearlylin/folly,KSreeHarsha/folly,tomhughes/folly,loversInJapan/folly,Hincoin/folly,tomhughes/folly,alexst07/folly,juniway/folly,zhiweicai/folly,Hincoin/folly,KSreeHarsha/folly,theiver9827/folly,tomhughes/folly,hongliangzhao/folly,Eagle-X/folly,arg0/folly,chjp2046/folly,PPC64/folly,alexst07/folly,SammyK/folly,reddit/folly,theiver9827/folly,project-zerus/folly,lifei/folly,xzmagic/folly,brunomorishita/folly,upsoft/folly,bowlofstew/folly,PoisonBOx/folly,doctaweeks/folly,bikong2/folly,SeanRBurton/folly,Hincoin/folly,bsampath/folly,charsyam/folly,tomhughes/folly,leolujuyi/folly,hongliangzhao/folly,alexst07/folly,guker/folly,PoisonBOx/folly,alexst07/folly,facebook/folly,theiver9827/folly,floxard/folly,xzmagic/folly,colemancda/folly,facebook/folly,gavioto/folly,nickhen/folly,gavioto/folly,juniway/folly,CJstar/folly,sakishum/folly,lifei/folly,gaoyingie/folly,sakishum/folly,PoisonBOx/folly,zhiweicai/folly,bsampath/folly,Orvid/folly,shaobz/folly,loversInJapan/folly,rklabs/folly,arg0/folly,fw1121/folly,chjp2046/folly,stonegithubs/folly,charsyam/folly,rklabs/folly,cole14/folly,xzmagic/folly,chjp2046/folly,colemancda/folly,SeanRBurton/folly,kernelim/folly,renyinew/folly,theiver9827/folly,juniway/folly,brunomorishita/folly,mqeizi/folly,KSreeHarsha/folly,mqeizi/folly,wildinto/folly,bowlofstew/folly,rklabs/folly,constantine001/folly,guker/folly,chjp2046/folly,tempbottle/folly,sonnyhu/folly,gaoyingie/folly,loversInJapan/folly,gaoyingie/folly,hongliangzhao/folly,SammyK/folly,floxard/folly,bsampath/folly,PPC64/folly,nickhen/folly,zhiweicai/folly,bowlofstew/folly,fw1121/folly,bikong2/folly,hongliangzhao/folly,wildinto/folly,hongliangzhao/folly,facebook/folly,juniway/folly,sonnyhu/folly,cole14/folly,yangjin-unique/folly,sakishum/folly,raphaelamorim/folly,CJstar/folly,arg0/folly,loversInJapan/folly,floxard/folly,kernelim/folly,kernelim/folly,PoisonBOx/folly,SammyK/folly,facebook/folly,lifei/folly,bikong2/folly,stonegithubs/folly,stonegithubs/folly,tomhughes/folly,wildinto/folly,rklabs/folly,upsoft/folly,Eagle-X/folly,mqeizi/folly,loversInJapan/folly,reddit/folly,guker/folly,doctaweeks/folly,colemancda/folly,facebook/folly,wildinto/folly,charsyam/folly,zhiweicai/folly,SammyK/folly,KSreeHarsha/folly,tempbottle/folly,reddit/folly,leolujuyi/folly,project-zerus/folly,raphaelamorim/folly,Orvid/folly,bsampath/folly,doctaweeks/folly,Orvid/folly,reddit/folly,gavioto/folly,bikong2/folly,renyinew/folly,PPC64/folly,leolujuyi/folly,cole14/folly,tempbottle/folly,raphaelamorim/folly,tempbottle/folly,Hincoin/folly,nickhen/folly,theiver9827/folly,PPC64/folly,leolujuyi/folly,SammyK/folly,Eagle-X/folly,xzmagic/folly
4f06bd3a3e57038cb1dc4adcb83642d4ae559909
InputCurveNode.C
InputCurveNode.C
#include <maya/MFnNumericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MDataHandle.h> #include <maya/MPointArray.h> #include <maya/MFnNurbsCurve.h> #include "InputCurveNode.h" #include "MayaTypeID.h" #include "hapiutil.h" #include "util.h" #include <cassert> MString InputCurveNode::typeName = "houdiniInputCurve"; MTypeId InputCurveNode::typeId = MayaTypeID_HoudiniInputCurveNode; MObject InputCurveNode::inputCurve; MObject InputCurveNode::outputNodeId; void* InputCurveNode::creator() { InputCurveNode* ret = new InputCurveNode(); return ret; } MStatus InputCurveNode::initialize() { MFnNumericAttribute nAttr; MFnTypedAttribute tAttr; InputCurveNode::inputCurve = tAttr.create( "inputCurve", "inputCurve", MFnData::kNurbsCurve ); tAttr.setDisconnectBehavior(MFnAttribute::kDelete); tAttr.setArray(true); addAttribute(InputCurveNode::inputCurve); InputCurveNode::outputNodeId = nAttr.create( "outputNodeId", "outputNodeId", MFnNumericData::kInt ); nAttr.setStorable(false); nAttr.setWritable(false); addAttribute(InputCurveNode::outputNodeId); attributeAffects(InputCurveNode::inputCurve, InputCurveNode::outputNodeId); return MS::kSuccess; } InputCurveNode::InputCurveNode() : myNodeId(-1) { } InputCurveNode::~InputCurveNode() { if(!Util::theHAPISession.get()) return; if ( myNodeId > 0 ) { CHECK_HAPI(HAPI_DeleteNode( Util::theHAPISession.get(), myNodeId )); } } MStatus InputCurveNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; if ( plug != InputCurveNode::outputNodeId ) { return MPxNode::compute(plug, data); } if ( myNodeId < 0 ) { Util::PythonInterpreterLock pythonInterpreterLock; CHECK_HAPI(HAPI_CreateInputNode( Util::theHAPISession.get(), &myNodeId, NULL )); if ( !Util::statusCheckLoop() ) { DISPLAY_ERROR( MString("Unexpected error when creating input asset.") ); } // Meta data MDataHandle metaDataHandle = data.outputValue(InputCurveNode::outputNodeId); metaDataHandle.setInt(myNodeId); } MPlug inputCurveArrayPlug(thisMObject(), InputCurveNode::inputCurve); const int nInputCurves = inputCurveArrayPlug.numElements(); if ( nInputCurves <= 0 ) { data.setClean(plug); return MStatus::kSuccess; } HAPI_CurveInfo curveInfo = HAPI_CurveInfo_Create(); curveInfo.curveType = HAPI_CURVETYPE_NURBS; curveInfo.isRational = false; std::vector<float> cvP, cvPw; std::vector<int> cvCounts; std::vector<float> knots; std::vector<int> orders; std::vector<std::string> names; for ( int iCurve = 0; iCurve < nInputCurves; ++iCurve ) { MPlug inputCurvePlug = inputCurveArrayPlug.elementByPhysicalIndex(iCurve); MDataHandle curveHandle = data.inputValue(inputCurvePlug); MObject curveObject = curveHandle.asNurbsCurve(); MFnNurbsCurve fnCurve( curveObject ); const bool isPeriodic = fnCurve.form() == MFnNurbsCurve::kPeriodic; if ( iCurve == 0 ) { curveInfo.isPeriodic = isPeriodic; } else if ( isPeriodic != curveInfo.isPeriodic ) { DISPLAY_ERROR( MString("Curve has a non-matching periodicity, skipping") ); continue; } const int order = fnCurve.degree() + 1; if ( iCurve == 0 ) { curveInfo.order = order; } else if ( curveInfo.order == HAPI_CURVE_ORDER_VARYING ) { orders.push_back( order ); } else if ( order != curveInfo.order ) { orders.resize( curveInfo.curveCount, curveInfo.order ); curveInfo.order = HAPI_CURVE_ORDER_VARYING; orders.push_back( order ); } MPointArray cvArray; CHECK_MSTATUS_AND_RETURN_IT( fnCurve.getCVs( cvArray, MSpace::kWorld ) ); unsigned int nCVs = cvArray.length(); // Maya provides fnCurve.degree() more cvs in its data definition // than Houdini for periodic curves -- but they are conincident // with the first ones. Houdini ignores them, so we don't // output them. if ( curveInfo.isPeriodic && static_cast<int>(nCVs) > fnCurve.degree() ) { nCVs -= fnCurve.degree(); } cvCounts.push_back(nCVs); for ( unsigned int iCV = 0; iCV < nCVs; ++iCV, ++curveInfo.vertexCount ) { const MPoint& cv = cvArray[iCV]; cvP.push_back((float) cv.x); cvP.push_back((float) cv.y); cvP.push_back((float) cv.z); if ( !curveInfo.isRational ) { if ( cv.w != 1.0 ) { curveInfo.isRational = true; cvPw.resize( curveInfo.vertexCount, 1.0f ); cvPw.push_back((float) cv.w); } } else { cvPw.push_back((float) cv.w); } } MDoubleArray knotsArray; CHECK_MSTATUS_AND_RETURN_IT( fnCurve.getKnots( knotsArray ) ); if ( knotsArray.length() > 0 ) { // Maya doesn't provide the first and last knots curveInfo.knotCount += knotsArray.length() + 2; knots.push_back( static_cast<float>(knotsArray[0]) ); for ( unsigned int iKnot = 0; iKnot < knotsArray.length(); ++iKnot ) { knots.push_back( static_cast<float>(knotsArray[iKnot]) ); } knots.push_back( static_cast<float>( knotsArray[knotsArray.length() - 1] ) ); } ++curveInfo.curveCount; names.push_back( Util::getNodeName(Util::plugSource(inputCurvePlug).node()).asChar() ); } curveInfo.hasKnots = curveInfo.knotCount > 0; HAPI_PartInfo partInfo = HAPI_PartInfo_Create(); partInfo.vertexCount = partInfo.pointCount = curveInfo.vertexCount; partInfo.faceCount = curveInfo.curveCount; partInfo.type = HAPI_PARTTYPE_CURVE; CHECK_HAPI(HAPI_SetPartInfo( Util::theHAPISession.get(), myNodeId, 0, &partInfo )); CHECK_HAPI(HAPI_SetCurveInfo( Util::theHAPISession.get(), myNodeId, 0, &curveInfo )); CHECK_HAPI(HAPI_SetCurveCounts( Util::theHAPISession.get(), myNodeId, 0, &cvCounts.front(), 0, cvCounts.size() )); if(curveInfo.order == HAPI_CURVE_ORDER_VARYING) { CHECK_HAPI(HAPI_SetCurveOrders( Util::theHAPISession.get(), myNodeId, 0, &orders.front(), 0, orders.size() )); } HAPI_AttributeInfo attrInfo = HAPI_AttributeInfo_Create(); attrInfo.count = partInfo.pointCount; attrInfo.tupleSize = 3; // 3 floats per CV (x, y, z) attrInfo.exists = true; attrInfo.owner = HAPI_ATTROWNER_POINT; attrInfo.storage = HAPI_STORAGETYPE_FLOAT; CHECK_HAPI(HAPI_AddAttribute( Util::theHAPISession.get(), myNodeId, 0, "P", &attrInfo )); CHECK_HAPI(HAPI_SetAttributeFloatData( Util::theHAPISession.get(), myNodeId, 0, "P", &attrInfo, &cvP.front(), 0, static_cast<int>(cvP.size() / 3) )); if ( curveInfo.isRational ) { attrInfo.tupleSize = 1; CHECK_HAPI(HAPI_AddAttribute( Util::theHAPISession.get(), myNodeId, 0, "Pw", &attrInfo )); CHECK_HAPI(HAPI_SetAttributeFloatData( Util::theHAPISession.get(), myNodeId, 0, "Pw", &attrInfo, &cvPw.front(), 0, static_cast<int>(cvPw.size()) )); } if ( curveInfo.hasKnots ) { CHECK_HAPI(HAPI_SetCurveKnots( Util::theHAPISession.get(), myNodeId, 0, &knots.front(), 0, static_cast<int>(knots.size()) )); } CHECK_HAPI(hapiSetPrimAttribute( myNodeId, 0, 1, "name", names )); CHECK_HAPI(HAPI_CommitGeo( Util::theHAPISession.get(), myNodeId )); data.setClean(plug); return MStatus::kSuccess; }
#include <maya/MFnNumericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MDataHandle.h> #include <maya/MPointArray.h> #include <maya/MFnNurbsCurve.h> #include "InputCurveNode.h" #include "MayaTypeID.h" #include "hapiutil.h" #include "util.h" #include <cassert> MString InputCurveNode::typeName = "houdiniInputCurve"; MTypeId InputCurveNode::typeId = MayaTypeID_HoudiniInputCurveNode; MObject InputCurveNode::inputCurve; MObject InputCurveNode::outputNodeId; void* InputCurveNode::creator() { InputCurveNode* ret = new InputCurveNode(); return ret; } MStatus InputCurveNode::initialize() { MFnNumericAttribute nAttr; MFnTypedAttribute tAttr; InputCurveNode::inputCurve = tAttr.create( "inputCurve", "inputCurve", MFnData::kNurbsCurve ); tAttr.setDisconnectBehavior(MFnAttribute::kDelete); tAttr.setArray(true); addAttribute(InputCurveNode::inputCurve); InputCurveNode::outputNodeId = nAttr.create( "outputNodeId", "outputNodeId", MFnNumericData::kInt ); nAttr.setStorable(false); nAttr.setWritable(false); addAttribute(InputCurveNode::outputNodeId); attributeAffects(InputCurveNode::inputCurve, InputCurveNode::outputNodeId); return MS::kSuccess; } InputCurveNode::InputCurveNode() : myNodeId(-1) { } InputCurveNode::~InputCurveNode() { if(!Util::theHAPISession.get()) return; if ( myNodeId > 0 ) { CHECK_HAPI(HAPI_DeleteNode( Util::theHAPISession.get(), myNodeId )); } } MStatus InputCurveNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; if ( plug != InputCurveNode::outputNodeId ) { return MPxNode::compute(plug, data); } if ( myNodeId < 0 ) { Util::PythonInterpreterLock pythonInterpreterLock; CHECK_HAPI(HAPI_CreateInputNode( Util::theHAPISession.get(), &myNodeId, NULL )); if ( !Util::statusCheckLoop() ) { DISPLAY_ERROR( MString("Unexpected error when creating input asset.") ); } // Meta data MDataHandle metaDataHandle = data.outputValue(InputCurveNode::outputNodeId); metaDataHandle.setInt(myNodeId); } MPlug inputCurveArrayPlug(thisMObject(), InputCurveNode::inputCurve); const int nInputCurves = inputCurveArrayPlug.numElements(); if ( nInputCurves <= 0 ) { data.setClean(plug); return MStatus::kSuccess; } HAPI_CurveInfo curveInfo = HAPI_CurveInfo_Create(); curveInfo.curveType = HAPI_CURVETYPE_NURBS; curveInfo.isRational = false; std::vector<float> cvP, cvPw; std::vector<int> cvCounts; std::vector<float> knots; std::vector<int> orders; std::vector<std::string> names; for ( int iCurve = 0; iCurve < nInputCurves; ++iCurve ) { MPlug inputCurvePlug = inputCurveArrayPlug.elementByPhysicalIndex(iCurve); MDataHandle curveHandle = data.inputValue(inputCurvePlug); MObject curveObject = curveHandle.asNurbsCurve(); MFnNurbsCurve fnCurve( curveObject ); const bool isPeriodic = fnCurve.form() == MFnNurbsCurve::kPeriodic; if ( iCurve == 0 ) { curveInfo.isPeriodic = isPeriodic; } else if ( isPeriodic != curveInfo.isPeriodic ) { DISPLAY_ERROR( MString("Curve has a non-matching periodicity, skipping") ); continue; } const int order = fnCurve.degree() + 1; if ( iCurve == 0 ) { curveInfo.order = order; } else if ( curveInfo.order == HAPI_CURVE_ORDER_VARYING ) { orders.push_back( order ); } else if ( order != curveInfo.order ) { orders.resize( curveInfo.curveCount, curveInfo.order ); curveInfo.order = HAPI_CURVE_ORDER_VARYING; orders.push_back( order ); } MPointArray cvArray; CHECK_MSTATUS_AND_RETURN_IT( fnCurve.getCVs( cvArray, MSpace::kWorld ) ); unsigned int nCVs = cvArray.length(); // Maya provides fnCurve.degree() more cvs in its data definition // than Houdini for periodic curves -- but they are conincident // with the first ones. Houdini ignores them, so we don't // output them. if ( curveInfo.isPeriodic && static_cast<int>(nCVs) > fnCurve.degree() ) { nCVs -= fnCurve.degree(); } cvCounts.push_back(nCVs); for ( unsigned int iCV = 0; iCV < nCVs; ++iCV, ++curveInfo.vertexCount ) { const MPoint& cv = cvArray[iCV]; cvP.push_back((float) cv.x); cvP.push_back((float) cv.y); cvP.push_back((float) cv.z); if ( !curveInfo.isRational ) { if ( cv.w != 1.0 ) { curveInfo.isRational = true; cvPw.resize( curveInfo.vertexCount, 1.0f ); cvPw.push_back((float) cv.w); } } else { cvPw.push_back((float) cv.w); } } MDoubleArray knotsArray; CHECK_MSTATUS_AND_RETURN_IT( fnCurve.getKnots( knotsArray ) ); if ( knotsArray.length() > 0 ) { // Maya doesn't provide the first and last knots curveInfo.knotCount += knotsArray.length() + 2; knots.push_back( static_cast<float>(knotsArray[0]) ); // Maya seems ok with having end knots of multiplicity > order // (counting the 1st and last knots added above) // so if we detect this, warn the user to rebuild their curves if(fabs(knotsArray[0] - knotsArray[order - 1]) < .0001) { MPlug curveSrcPlug = Util::plugSource(inputCurvePlug); MFnDependencyNode curveSrcObj(curveSrcPlug.node()); DISPLAY_WARNING( "Curve ^1s has knots with higher multiplicity than the order of the curve." "You may need to rebuild the curve in order to see it in Houdini", curveSrcObj.name() ); } for ( unsigned int iKnot = 0; iKnot < knotsArray.length(); ++iKnot ) { knots.push_back( static_cast<float>(knotsArray[iKnot]) ); } knots.push_back( static_cast<float>( knotsArray[knotsArray.length() - 1] ) ); } ++curveInfo.curveCount; names.push_back( Util::getNodeName(Util::plugSource(inputCurvePlug).node()).asChar() ); } curveInfo.hasKnots = curveInfo.knotCount > 0; HAPI_PartInfo partInfo = HAPI_PartInfo_Create(); partInfo.vertexCount = partInfo.pointCount = curveInfo.vertexCount; partInfo.faceCount = curveInfo.curveCount; partInfo.type = HAPI_PARTTYPE_CURVE; CHECK_HAPI(HAPI_SetPartInfo( Util::theHAPISession.get(), myNodeId, 0, &partInfo )); CHECK_HAPI(HAPI_SetCurveInfo( Util::theHAPISession.get(), myNodeId, 0, &curveInfo )); CHECK_HAPI(HAPI_SetCurveCounts( Util::theHAPISession.get(), myNodeId, 0, &cvCounts.front(), 0, cvCounts.size() )); if(curveInfo.order == HAPI_CURVE_ORDER_VARYING) { CHECK_HAPI(HAPI_SetCurveOrders( Util::theHAPISession.get(), myNodeId, 0, &orders.front(), 0, orders.size() )); } HAPI_AttributeInfo attrInfo = HAPI_AttributeInfo_Create(); attrInfo.count = partInfo.pointCount; attrInfo.tupleSize = 3; // 3 floats per CV (x, y, z) attrInfo.exists = true; attrInfo.owner = HAPI_ATTROWNER_POINT; attrInfo.storage = HAPI_STORAGETYPE_FLOAT; CHECK_HAPI(HAPI_AddAttribute( Util::theHAPISession.get(), myNodeId, 0, "P", &attrInfo )); CHECK_HAPI(HAPI_SetAttributeFloatData( Util::theHAPISession.get(), myNodeId, 0, "P", &attrInfo, &cvP.front(), 0, static_cast<int>(cvP.size() / 3) )); if ( curveInfo.isRational ) { attrInfo.tupleSize = 1; CHECK_HAPI(HAPI_AddAttribute( Util::theHAPISession.get(), myNodeId, 0, "Pw", &attrInfo )); CHECK_HAPI(HAPI_SetAttributeFloatData( Util::theHAPISession.get(), myNodeId, 0, "Pw", &attrInfo, &cvPw.front(), 0, static_cast<int>(cvPw.size()) )); } if ( curveInfo.hasKnots ) { CHECK_HAPI(HAPI_SetCurveKnots( Util::theHAPISession.get(), myNodeId, 0, &knots.front(), 0, static_cast<int>(knots.size()) )); } CHECK_HAPI(hapiSetPrimAttribute( myNodeId, 0, 1, "name", names )); CHECK_HAPI(HAPI_CommitGeo( Util::theHAPISession.get(), myNodeId )); data.setClean(plug); return MStatus::kSuccess; }
add a warning if an input curve in maya ends up with end knots with multiplicity greater than the order of the curve
add a warning if an input curve in maya ends up with end knots with multiplicity greater than the order of the curve
C++
mit
sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya,sideeffects/HoudiniEngineForMaya
604c12b4660c038503a3a970f1ef986027065a88
server-tools/instance-manager/thread_registry.cc
server-tools/instance-manager/thread_registry.cc
/* Copyright (C) 2004-2006 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION) #pragma implementation #endif #include "thread_registry.h" #include <thr_alarm.h> #include <signal.h> #include "log.h" #ifndef __WIN__ /* Kick-off signal handler */ enum { THREAD_KICK_OFF_SIGNAL= SIGUSR2 }; static void handle_signal(int __attribute__((unused)) sig_no) { } #endif /* Thread_info initializer methods */ void Thread_info::init(bool send_signal_on_shutdown_arg) { thread_id= pthread_self(); send_signal_on_shutdown= send_signal_on_shutdown_arg; } /* TODO: think about moving signal information (now it's shutdown_in_progress) to Thread_info. It will reduce contention and allow signal deliverence to a particular thread, not to the whole worker crew */ Thread_registry::Thread_registry() : shutdown_in_progress(FALSE) ,sigwait_thread_pid(pthread_self()) ,error_status(FALSE) { pthread_mutex_init(&LOCK_thread_registry, 0); pthread_cond_init(&COND_thread_registry_is_empty, 0); /* head is used by-value to simplify nodes inserting */ head.next= head.prev= &head; } Thread_registry::~Thread_registry() { /* Check that no one uses the repository. */ pthread_mutex_lock(&LOCK_thread_registry); if (head.next != &head) log_error("Not all threads died properly\n"); /* All threads must unregister */ DBUG_ASSERT(head.next == &head); pthread_mutex_unlock(&LOCK_thread_registry); pthread_cond_destroy(&COND_thread_registry_is_empty); pthread_mutex_destroy(&LOCK_thread_registry); } /* Set signal handler for kick-off thread, and insert a thread info to the repository. New node is appended to the end of the list; head.prev always points to the last node. */ void Thread_registry::register_thread(Thread_info *info, bool send_signal_on_shutdown) { info->init(send_signal_on_shutdown); DBUG_PRINT("info", ("Thread_registry: registering thread %lu...", (unsigned long) info->thread_id)); #ifndef __WIN__ struct sigaction sa; sa.sa_handler= handle_signal; sa.sa_flags= 0; sigemptyset(&sa.sa_mask); sigaction(THREAD_KICK_OFF_SIGNAL, &sa, 0); #endif info->current_cond= 0; pthread_mutex_lock(&LOCK_thread_registry); info->next= &head; info->prev= head.prev; head.prev->next= info; head.prev= info; pthread_mutex_unlock(&LOCK_thread_registry); } /* Unregister a thread from the repository and free Thread_info structure. Every registered thread must unregister. Unregistering should be the last thing a thread is doing, otherwise it could have no time to finalize. */ void Thread_registry::unregister_thread(Thread_info *info) { DBUG_PRINT("info", ("Thread_registry: unregistering thread %lu...", (unsigned long) info->thread_id)); pthread_mutex_lock(&LOCK_thread_registry); info->prev->next= info->next; info->next->prev= info->prev; if (head.next == &head) { DBUG_PRINT("info", ("Thread_registry: thread registry is empty!")); pthread_cond_signal(&COND_thread_registry_is_empty); } pthread_mutex_unlock(&LOCK_thread_registry); } /* Check whether shutdown is in progress, and if yes, return immediately. Else set info->current_cond and call pthread_cond_wait. When pthread_cond_wait returns, unregister current cond and check the shutdown status again. RETURN VALUE return value from pthread_cond_wait */ int Thread_registry::cond_wait(Thread_info *info, pthread_cond_t *cond, pthread_mutex_t *mutex) { pthread_mutex_lock(&LOCK_thread_registry); if (shutdown_in_progress) { pthread_mutex_unlock(&LOCK_thread_registry); return 0; } info->current_cond= cond; pthread_mutex_unlock(&LOCK_thread_registry); /* sic: race condition here, cond can be signaled in deliver_shutdown */ int rc= pthread_cond_wait(cond, mutex); pthread_mutex_lock(&LOCK_thread_registry); info->current_cond= 0; pthread_mutex_unlock(&LOCK_thread_registry); return rc; } int Thread_registry::cond_timedwait(Thread_info *info, pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *wait_time) { int rc; pthread_mutex_lock(&LOCK_thread_registry); if (shutdown_in_progress) { pthread_mutex_unlock(&LOCK_thread_registry); return 0; } info->current_cond= cond; pthread_mutex_unlock(&LOCK_thread_registry); /* sic: race condition here, cond can be signaled in deliver_shutdown */ if ((rc= pthread_cond_timedwait(cond, mutex, wait_time)) == ETIME) rc= ETIMEDOUT; // For easier usage pthread_mutex_lock(&LOCK_thread_registry); info->current_cond= 0; pthread_mutex_unlock(&LOCK_thread_registry); return rc; } /* Deliver shutdown message to the workers crew. As it's impossible to avoid all race conditions, signal latecomers again. */ void Thread_registry::deliver_shutdown() { pthread_mutex_lock(&LOCK_thread_registry); shutdown_in_progress= TRUE; #ifndef __WIN__ /* to stop reading from the network we need to flush alarm queue */ end_thr_alarm(0); /* We have to deliver final alarms this way, as the main thread has already stopped alarm processing. */ process_alarm(THR_SERVER_ALARM); #endif /* sic: race condition here, the thread may not yet fall into pthread_cond_wait. */ interrupt_threads(); wait_for_threads_to_unregister(); /* If previous signals did not reach some threads, they must be sleeping in pthread_cond_wait or in a blocking syscall. Wake them up: every thread shall check signal variables after each syscall/cond_wait, so this time everybody should be informed (presumably each worker can get CPU during shutdown_time.) */ interrupt_threads(); /* Get the last chance to threads to stop. */ wait_for_threads_to_unregister(); #ifndef DBUG_OFF /* Print out threads, that didn't stopped. Thread_registry destructor will probably abort the program if there is still any alive thread. */ if (head.next != &head) { DBUG_PRINT("info", ("Thread_registry: non-stopped threads:")); for (Thread_info *info= head.next; info != &head; info= info->next) DBUG_PRINT("info", (" - %lu", (unsigned long) info->thread_id)); } else { DBUG_PRINT("info", ("Thread_registry: all threads stopped.")); } #endif // DBUG_OFF pthread_mutex_unlock(&LOCK_thread_registry); } void Thread_registry::request_shutdown() { pthread_kill(sigwait_thread_pid, SIGTERM); } void Thread_registry::interrupt_threads() { for (Thread_info *info= head.next; info != &head; info= info->next) { if (!info->send_signal_on_shutdown) continue; pthread_kill(info->thread_id, THREAD_KICK_OFF_SIGNAL); if (info->current_cond) pthread_cond_signal(info->current_cond); } } void Thread_registry::wait_for_threads_to_unregister() { struct timespec shutdown_time; set_timespec(shutdown_time, 1); DBUG_PRINT("info", ("Thread_registry: joining threads...")); while (true) { if (head.next == &head) { DBUG_PRINT("info", ("Thread_registry: emptied.")); return; } int error= pthread_cond_timedwait(&COND_thread_registry_is_empty, &LOCK_thread_registry, &shutdown_time); if (error == ETIMEDOUT || error == ETIME) { DBUG_PRINT("info", ("Thread_registry: threads shutdown timed out.")); return; } } } /********************************************************************* class Thread *********************************************************************/ #if defined(__ia64__) || defined(__ia64) /* We can live with 32K, but reserve 64K. Just to be safe. On ia64 we need to reserve double of the size. */ #define IM_THREAD_STACK_SIZE (128*1024L) #else #define IM_THREAD_STACK_SIZE (64*1024) #endif /* Change the stack size and start a thread. Return an error if either pthread_attr_setstacksize or pthread_create fails. Arguments are the same as for pthread_create(). */ static int set_stacksize_and_create_thread(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { int rc= 0; #ifndef __WIN__ #ifndef PTHREAD_STACK_MIN #define PTHREAD_STACK_MIN 32768 #endif /* Set stack size to be safe on the platforms with too small default thread stack. */ rc= pthread_attr_setstacksize(attr, (size_t) (PTHREAD_STACK_MIN + IM_THREAD_STACK_SIZE)); #endif if (!rc) rc= pthread_create(thread, attr, start_routine, arg); return rc; } Thread::~Thread() { } void *Thread::thread_func(void *arg) { Thread *thread= (Thread *) arg; my_thread_init(); thread->run(); my_thread_end(); return NULL; } bool Thread::start(enum_thread_type thread_type) { pthread_attr_t attr; int rc; pthread_attr_init(&attr); if (thread_type == DETACHED) { detached = TRUE; pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); } else { detached = FALSE; } rc= set_stacksize_and_create_thread(&id, &attr, Thread::thread_func, this); pthread_attr_destroy(&attr); return rc != 0; } bool Thread::join() { DBUG_ASSERT(!detached); return pthread_join(id, NULL) != 0; } int Thread_registry::get_error_status() { int ret_error_status; pthread_mutex_lock(&LOCK_thread_registry); ret_error_status= error_status; pthread_mutex_unlock(&LOCK_thread_registry); return ret_error_status; } void Thread_registry::set_error_status() { pthread_mutex_lock(&LOCK_thread_registry); error_status= TRUE; pthread_mutex_unlock(&LOCK_thread_registry); }
/* Copyright (C) 2004-2006 MySQL AB 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if defined(__GNUC__) && defined(USE_PRAGMA_IMPLEMENTATION) #pragma implementation #endif #include "thread_registry.h" #include <thr_alarm.h> #include <signal.h> #include "log.h" #ifndef __WIN__ /* Kick-off signal handler */ enum { THREAD_KICK_OFF_SIGNAL= SIGUSR2 }; static void handle_signal(int __attribute__((unused)) sig_no) { } #endif /* Thread_info initializer methods */ void Thread_info::init(bool send_signal_on_shutdown_arg) { thread_id= pthread_self(); send_signal_on_shutdown= send_signal_on_shutdown_arg; } /* TODO: think about moving signal information (now it's shutdown_in_progress) to Thread_info. It will reduce contention and allow signal deliverence to a particular thread, not to the whole worker crew */ Thread_registry::Thread_registry() : shutdown_in_progress(FALSE) ,sigwait_thread_pid(pthread_self()) ,error_status(FALSE) { pthread_mutex_init(&LOCK_thread_registry, 0); pthread_cond_init(&COND_thread_registry_is_empty, 0); /* head is used by-value to simplify nodes inserting */ head.next= head.prev= &head; } Thread_registry::~Thread_registry() { /* Check that no one uses the repository. */ pthread_mutex_lock(&LOCK_thread_registry); if (head.next != &head) log_error("Not all threads died properly\n"); /* All threads must unregister */ // Disabled assert temporarily - BUG#28030 // DBUG_ASSERT(head.next == &head); pthread_mutex_unlock(&LOCK_thread_registry); pthread_cond_destroy(&COND_thread_registry_is_empty); pthread_mutex_destroy(&LOCK_thread_registry); } /* Set signal handler for kick-off thread, and insert a thread info to the repository. New node is appended to the end of the list; head.prev always points to the last node. */ void Thread_registry::register_thread(Thread_info *info, bool send_signal_on_shutdown) { info->init(send_signal_on_shutdown); DBUG_PRINT("info", ("Thread_registry: registering thread %lu...", (unsigned long) info->thread_id)); #ifndef __WIN__ struct sigaction sa; sa.sa_handler= handle_signal; sa.sa_flags= 0; sigemptyset(&sa.sa_mask); sigaction(THREAD_KICK_OFF_SIGNAL, &sa, 0); #endif info->current_cond= 0; pthread_mutex_lock(&LOCK_thread_registry); info->next= &head; info->prev= head.prev; head.prev->next= info; head.prev= info; pthread_mutex_unlock(&LOCK_thread_registry); } /* Unregister a thread from the repository and free Thread_info structure. Every registered thread must unregister. Unregistering should be the last thing a thread is doing, otherwise it could have no time to finalize. */ void Thread_registry::unregister_thread(Thread_info *info) { DBUG_PRINT("info", ("Thread_registry: unregistering thread %lu...", (unsigned long) info->thread_id)); pthread_mutex_lock(&LOCK_thread_registry); info->prev->next= info->next; info->next->prev= info->prev; if (head.next == &head) { DBUG_PRINT("info", ("Thread_registry: thread registry is empty!")); pthread_cond_signal(&COND_thread_registry_is_empty); } pthread_mutex_unlock(&LOCK_thread_registry); } /* Check whether shutdown is in progress, and if yes, return immediately. Else set info->current_cond and call pthread_cond_wait. When pthread_cond_wait returns, unregister current cond and check the shutdown status again. RETURN VALUE return value from pthread_cond_wait */ int Thread_registry::cond_wait(Thread_info *info, pthread_cond_t *cond, pthread_mutex_t *mutex) { pthread_mutex_lock(&LOCK_thread_registry); if (shutdown_in_progress) { pthread_mutex_unlock(&LOCK_thread_registry); return 0; } info->current_cond= cond; pthread_mutex_unlock(&LOCK_thread_registry); /* sic: race condition here, cond can be signaled in deliver_shutdown */ int rc= pthread_cond_wait(cond, mutex); pthread_mutex_lock(&LOCK_thread_registry); info->current_cond= 0; pthread_mutex_unlock(&LOCK_thread_registry); return rc; } int Thread_registry::cond_timedwait(Thread_info *info, pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *wait_time) { int rc; pthread_mutex_lock(&LOCK_thread_registry); if (shutdown_in_progress) { pthread_mutex_unlock(&LOCK_thread_registry); return 0; } info->current_cond= cond; pthread_mutex_unlock(&LOCK_thread_registry); /* sic: race condition here, cond can be signaled in deliver_shutdown */ if ((rc= pthread_cond_timedwait(cond, mutex, wait_time)) == ETIME) rc= ETIMEDOUT; // For easier usage pthread_mutex_lock(&LOCK_thread_registry); info->current_cond= 0; pthread_mutex_unlock(&LOCK_thread_registry); return rc; } /* Deliver shutdown message to the workers crew. As it's impossible to avoid all race conditions, signal latecomers again. */ void Thread_registry::deliver_shutdown() { pthread_mutex_lock(&LOCK_thread_registry); shutdown_in_progress= TRUE; #ifndef __WIN__ /* to stop reading from the network we need to flush alarm queue */ end_thr_alarm(0); /* We have to deliver final alarms this way, as the main thread has already stopped alarm processing. */ process_alarm(THR_SERVER_ALARM); #endif /* sic: race condition here, the thread may not yet fall into pthread_cond_wait. */ interrupt_threads(); wait_for_threads_to_unregister(); /* If previous signals did not reach some threads, they must be sleeping in pthread_cond_wait or in a blocking syscall. Wake them up: every thread shall check signal variables after each syscall/cond_wait, so this time everybody should be informed (presumably each worker can get CPU during shutdown_time.) */ interrupt_threads(); /* Get the last chance to threads to stop. */ wait_for_threads_to_unregister(); #ifndef DBUG_OFF /* Print out threads, that didn't stopped. Thread_registry destructor will probably abort the program if there is still any alive thread. */ if (head.next != &head) { DBUG_PRINT("info", ("Thread_registry: non-stopped threads:")); for (Thread_info *info= head.next; info != &head; info= info->next) DBUG_PRINT("info", (" - %lu", (unsigned long) info->thread_id)); } else { DBUG_PRINT("info", ("Thread_registry: all threads stopped.")); } #endif // DBUG_OFF pthread_mutex_unlock(&LOCK_thread_registry); } void Thread_registry::request_shutdown() { pthread_kill(sigwait_thread_pid, SIGTERM); } void Thread_registry::interrupt_threads() { for (Thread_info *info= head.next; info != &head; info= info->next) { if (!info->send_signal_on_shutdown) continue; pthread_kill(info->thread_id, THREAD_KICK_OFF_SIGNAL); if (info->current_cond) pthread_cond_signal(info->current_cond); } } void Thread_registry::wait_for_threads_to_unregister() { struct timespec shutdown_time; set_timespec(shutdown_time, 1); DBUG_PRINT("info", ("Thread_registry: joining threads...")); while (true) { if (head.next == &head) { DBUG_PRINT("info", ("Thread_registry: emptied.")); return; } int error= pthread_cond_timedwait(&COND_thread_registry_is_empty, &LOCK_thread_registry, &shutdown_time); if (error == ETIMEDOUT || error == ETIME) { DBUG_PRINT("info", ("Thread_registry: threads shutdown timed out.")); return; } } } /********************************************************************* class Thread *********************************************************************/ #if defined(__ia64__) || defined(__ia64) /* We can live with 32K, but reserve 64K. Just to be safe. On ia64 we need to reserve double of the size. */ #define IM_THREAD_STACK_SIZE (128*1024L) #else #define IM_THREAD_STACK_SIZE (64*1024) #endif /* Change the stack size and start a thread. Return an error if either pthread_attr_setstacksize or pthread_create fails. Arguments are the same as for pthread_create(). */ static int set_stacksize_and_create_thread(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { int rc= 0; #ifndef __WIN__ #ifndef PTHREAD_STACK_MIN #define PTHREAD_STACK_MIN 32768 #endif /* Set stack size to be safe on the platforms with too small default thread stack. */ rc= pthread_attr_setstacksize(attr, (size_t) (PTHREAD_STACK_MIN + IM_THREAD_STACK_SIZE)); #endif if (!rc) rc= pthread_create(thread, attr, start_routine, arg); return rc; } Thread::~Thread() { } void *Thread::thread_func(void *arg) { Thread *thread= (Thread *) arg; my_thread_init(); thread->run(); my_thread_end(); return NULL; } bool Thread::start(enum_thread_type thread_type) { pthread_attr_t attr; int rc; pthread_attr_init(&attr); if (thread_type == DETACHED) { detached = TRUE; pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); } else { detached = FALSE; } rc= set_stacksize_and_create_thread(&id, &attr, Thread::thread_func, this); pthread_attr_destroy(&attr); return rc != 0; } bool Thread::join() { DBUG_ASSERT(!detached); return pthread_join(id, NULL) != 0; } int Thread_registry::get_error_status() { int ret_error_status; pthread_mutex_lock(&LOCK_thread_registry); ret_error_status= error_status; pthread_mutex_unlock(&LOCK_thread_registry); return ret_error_status; } void Thread_registry::set_error_status() { pthread_mutex_lock(&LOCK_thread_registry); error_status= TRUE; pthread_mutex_unlock(&LOCK_thread_registry); }
Disable assert causing bug # 28030 temporarily, since it's non-critical, and the bug have been filed
thread_registry.cc: Disable assert causing bug # 28030 temporarily, since it's non-critical, and the bug have been filed server-tools/instance-manager/thread_registry.cc: Disable assert causing bug # 28030 temporarily, since it's non-critical, and the bug have been filed
C++
lgpl-2.1
natsys/mariadb_10.2,davidl-zend/zenddbi,natsys/mariadb_10.2,flynn1973/mariadb-aix,flynn1973/mariadb-aix,ollie314/server,flynn1973/mariadb-aix,flynn1973/mariadb-aix,davidl-zend/zenddbi,ollie314/server,ollie314/server,natsys/mariadb_10.2,flynn1973/mariadb-aix,davidl-zend/zenddbi,natsys/mariadb_10.2,ollie314/server,davidl-zend/zenddbi,natsys/mariadb_10.2,ollie314/server,flynn1973/mariadb-aix,davidl-zend/zenddbi,slanterns/server,davidl-zend/zenddbi,ollie314/server,flynn1973/mariadb-aix,flynn1973/mariadb-aix,flynn1973/mariadb-aix,ollie314/server,davidl-zend/zenddbi,ollie314/server,natsys/mariadb_10.2,natsys/mariadb_10.2,natsys/mariadb_10.2,flynn1973/mariadb-aix,davidl-zend/zenddbi,davidl-zend/zenddbi,ollie314/server,natsys/mariadb_10.2,ollie314/server,davidl-zend/zenddbi,ollie314/server,natsys/mariadb_10.2,flynn1973/mariadb-aix,natsys/mariadb_10.2,davidl-zend/zenddbi
974018a4dc13d30e1c51727e766f8669c5f372dc
source/glowutils/AxonometricLookAt.cpp
source/glowutils/AxonometricLookAt.cpp
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/quaternion.hpp> #include <glow/logging.h> #include <glowutils/AxonometricLookAt.h> using namespace glm; namespace glowutils { AxonometricLookAt::AxonometricLookAt( ProjectionType type , const vec3 & position , float zoom , const mat4 & rotation) : m_rotation(rotation) , m_position(position) , m_zoom(zoom) , m_rebuild(true) { setType(type); } AxonometricLookAt::AxonometricLookAt( float verticalAngle , float horizontalAngle , const vec3 & position , float zoom , const mat4 & rotation) : m_verticalAngle(verticalAngle) , m_horizontalAngle(horizontalAngle) , m_rotation(rotation) , m_position(position) , m_zoom(zoom) , m_type(Custom) , m_rebuild(true) { } void AxonometricLookAt::setType(ProjectionType type) { if (m_type == type) return; m_type = type; switch(m_type) { case Isometric30: m_verticalAngle = 30.f; m_horizontalAngle = 35.f; break; case Isometric12: m_verticalAngle = 27.f; m_horizontalAngle = 30.f; break; case Military: m_verticalAngle = 45.f; m_horizontalAngle = 45.f; break; case Dimetric427: m_verticalAngle = 70.f; m_horizontalAngle = 20.f; break; case Chinese: m_verticalAngle = 75.f; m_horizontalAngle = 10.f; break; case Custom: break; }; m_rebuild = true; } AxonometricLookAt::ProjectionType AxonometricLookAt::type() const { return m_type; } void AxonometricLookAt::setVerticalAngle(float angle) { if(m_verticalAngle == angle) return; m_verticalAngle = angle; m_type = Custom; m_rebuild = true; } float AxonometricLookAt::verticalAngle() const { return m_verticalAngle; } void AxonometricLookAt::setHorizontalAngle(float angle) { if (m_horizontalAngle == angle) return; m_horizontalAngle = angle; m_type = Custom; m_rebuild = true; } float AxonometricLookAt::horizontalAngle() const { return m_horizontalAngle; } void AxonometricLookAt::setPosition(const vec3 & position) { if (m_position == position) return; m_position = position; m_rebuild = true; } const vec3 & AxonometricLookAt::position() const { return m_position; } void AxonometricLookAt::setZoom(float zoom) { if (zoom <= 0.f) { glow::warning() << "Axonometric Look At zoom was set to 0.f (" << zoom << ")"; zoom = 0.f; } if (m_zoom == zoom) return; m_zoom = zoom; m_rebuild = true; } float AxonometricLookAt::zoom() const { return m_zoom; } void AxonometricLookAt::setRotation(const mat4 & rotation) { if (m_rotation == rotation) return; m_rotation = rotation; m_rebuild = true; } void AxonometricLookAt::rebuild() const { if(!m_rebuild) return; const mat4 vrot = mat4_cast(angleAxis(-m_verticalAngle, vec3( 0.f, 1.f, 0.f))); const mat4 hrot = mat4_cast(angleAxis(m_horizontalAngle, vec3( 1.f, 0.f, 0.f))); const mat4 zoom = scale(m_zoom, m_zoom, 1.f); const mat4 t = translate(-m_position); const mat4 T1 = translate(0.f, 0.f, -512.f); m_axonometric = T1 * hrot * vrot * t; // * m_rotation; m_rebuild = false; } const mat4 & AxonometricLookAt::matrix() const { if (m_rebuild) rebuild(); return m_axonometric; } } // namespace glowutils
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/quaternion.hpp> #include <glow/logging.h> #include <glowutils/AxonometricLookAt.h> using namespace glm; namespace glowutils { AxonometricLookAt::AxonometricLookAt( ProjectionType type , const vec3 & position , float zoom , const mat4 & rotation) : m_rotation(rotation) , m_position(position) , m_zoom(zoom) , m_rebuild(true) { setType(type); } AxonometricLookAt::AxonometricLookAt( float verticalAngle , float horizontalAngle , const vec3 & position , float zoom , const mat4 & rotation) : m_verticalAngle(verticalAngle) , m_horizontalAngle(horizontalAngle) , m_rotation(rotation) , m_position(position) , m_zoom(zoom) , m_type(Custom) , m_rebuild(true) { } void AxonometricLookAt::setType(ProjectionType type) { if (m_type == type) return; m_type = type; switch(m_type) { case Isometric30: m_verticalAngle = 30.f; m_horizontalAngle = 35.f; break; case Isometric12: m_verticalAngle = 27.f; m_horizontalAngle = 30.f; break; case Military: m_verticalAngle = 45.f; m_horizontalAngle = 45.f; break; case Dimetric427: m_verticalAngle = 70.f; m_horizontalAngle = 20.f; break; case Chinese: m_verticalAngle = 75.f; m_horizontalAngle = 10.f; break; case Custom: break; }; m_rebuild = true; } AxonometricLookAt::ProjectionType AxonometricLookAt::type() const { return m_type; } void AxonometricLookAt::setVerticalAngle(float angle) { if(m_verticalAngle == angle) return; m_verticalAngle = angle; m_type = Custom; m_rebuild = true; } float AxonometricLookAt::verticalAngle() const { return m_verticalAngle; } void AxonometricLookAt::setHorizontalAngle(float angle) { if (m_horizontalAngle == angle) return; m_horizontalAngle = angle; m_type = Custom; m_rebuild = true; } float AxonometricLookAt::horizontalAngle() const { return m_horizontalAngle; } void AxonometricLookAt::setPosition(const vec3 & position) { if (m_position == position) return; m_position = position; m_rebuild = true; } const vec3 & AxonometricLookAt::position() const { return m_position; } void AxonometricLookAt::setZoom(float zoom) { if (zoom <= 0.f) { glow::warning() << "Axonometric Look At zoom was set to 0.f (" << zoom << ")"; zoom = 0.f; } if (m_zoom == zoom) return; m_zoom = zoom; m_rebuild = true; } float AxonometricLookAt::zoom() const { return m_zoom; } void AxonometricLookAt::setRotation(const mat4 & rotation) { if (m_rotation == rotation) return; m_rotation = rotation; m_rebuild = true; } void AxonometricLookAt::rebuild() const { if(!m_rebuild) return; const mat4 vrot = mat4_cast(angleAxis(-m_verticalAngle, vec3( 0.f, 1.f, 0.f))); const mat4 hrot = mat4_cast(angleAxis(m_horizontalAngle, vec3( 1.f, 0.f, 0.f))); const mat4 zoom = scale(vec3(m_zoom, m_zoom, 1.f)); const mat4 t = translate(-m_position); const mat4 T1 = translate(vec3(0.f, 0.f, -512.f)); m_axonometric = T1 * hrot * vrot * t; // * m_rotation; m_rebuild = false; } const mat4 & AxonometricLookAt::matrix() const { if (m_rebuild) rebuild(); return m_axonometric; } } // namespace glowutils
fix compilation with newer versions of GLM (seems compatible with old version)
fix compilation with newer versions of GLM (seems compatible with old version)
C++
mit
j-o/globjects,j-o/globjects,j-o/globjects,hpi-r2d2/globjects,hpi-r2d2/globjects,j-o/globjects,cginternals/globjects,cginternals/globjects
eed041d26343f307d534eab4c05ecd9a16c4740d
extensions/ant_switch/extensions/ant_switch/ant_switch.cpp
extensions/ant_switch/extensions/ant_switch/ant_switch.cpp
// Copyright (c) 2018-2019 Kari Karvonen, OH1KK #include "ext.h" // all calls to the extension interface begin with "ext_", e.g. ext_register() #include "kiwi.h" #include "cfg.h" #include "str.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <math.h> #include <strings.h> #include <sys/types.h> #include <sys/wait.h> //#define ANT_SWITCH_DEBUG_MSG true #define ANT_SWITCH_DEBUG_MSG false // rx_chan is the receiver channel number we've been assigned, 0..RX_CHAN // We need this so the extension can support multiple users, each with their own ant_switch[] data structure. struct ant_switch_t { u1_t rx_chan; }; // Can't use RX_CHANS since 8-channel mode was introduced. // But also can't use the new MAX_RX_CHANS because of the backward compatibility issue. // So just define our own plausible maximum. #define ANT_SW_MAX_RX_CHANS 32 static ant_switch_t ant_switch[ANT_SW_MAX_RX_CHANS]; char * ant_switch_queryantennas() { char *cmd, *reply; static char selected_antennas[256]; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend s"); reply = non_blocking_cmd(cmd, NULL); n = sscanf(kstr_sp(reply), "Selected antennas: %250s", selected_antennas); free(cmd); //printf("frontend: s n=%d reply=<%s>\n", n, kstr_sp(reply)); if (!n) printf("ant_switch_queryantenna BAD STATUS? <%s>\n", kstr_sp(reply)); kstr_free(reply); return(selected_antennas); } int ant_switch_setantenna(char* antenna) { char *cmd, *reply; int status; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend %s", antenna); //printf("frontend: %s\n", antenna); reply = non_blocking_cmd(cmd,NULL); free(cmd); kstr_free(reply); return(0); } int ant_switch_toggleantenna(char* antenna) { char *cmd, *reply; int status; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend t%s", antenna); //printf("frontend: t%s\n", antenna); reply = non_blocking_cmd(cmd, NULL); free(cmd); kstr_free(reply); return(0); } int ant_switch_validate_cmd(char *cmd) { int is_valid_cmd = false; if (strcmp(cmd, "1") == 0) is_valid_cmd=true; if (strcmp(cmd, "2") == 0) is_valid_cmd=true; if (strcmp(cmd, "3") == 0) is_valid_cmd=true; if (strcmp(cmd, "4") == 0) is_valid_cmd=true; if (strcmp(cmd, "5") == 0) is_valid_cmd=true; if (strcmp(cmd, "6") == 0) is_valid_cmd=true; if (strcmp(cmd, "7") == 0) is_valid_cmd=true; if (strcmp(cmd, "8") == 0) is_valid_cmd=true; if (strcmp(cmd, "g") == 0) is_valid_cmd=true; return(is_valid_cmd); } bool ant_switch_read_denyswitching() { bool error; char cfgparam[26]="ant_switch.denyswitching\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then switching is allowed if (result == 1) return true; else return false; } bool ant_switch_read_denymixing() { bool error; char cfgparam[26]="ant_switch.denymixing\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed if (result == 1) return true; else return false; } bool ant_switch_read_denymultiuser() { bool error; char cfgparam[26]="ant_switch.denymultiuser\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then switching is allowed if (result == 1) { // option is set. Now check if more than 1 user online rx_util.cpp current_nusers variable if (current_nusers > 1) return true; else return false; } else { return false; } } bool ant_switch_read_thunderstorm() { bool error; char cfgparam[26]="ant_switch.thunderstorm\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed if (result == 1) return true; else return false; } bool ant_switch_msgs(char *msg, int rx_chan) { ant_switch_t *e = &ant_switch[rx_chan]; int n=0; char antenna[256]; //printf("### ant_switch_msgs RX%d <%s>\n", rx_chan, msg); if (strcmp(msg, "SET ext_server_init") == 0) { e->rx_chan = rx_chan; // remember our receiver channel number ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT ready"); return true; } n = sscanf(msg, "SET Antenna=%s", antenna); if (n == 1) { printf("ant_switch: RX%d %s\n", rx_chan, msg); if (ant_switch_read_thunderstorm()==true || ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1"); return true; } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0"); } // FIXME: or toggle antenna if antenna mixing is allowed if (ant_switch_validate_cmd(antenna)) { if (ant_switch_read_denymixing() == 1) { ant_switch_setantenna(antenna); } else { ant_switch_toggleantenna(antenna); } } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "Command not valid SET Antenna=%s",antenna); } return true; } if (strcmp(msg, "GET Antenna") == 0) { char *selected_antennas = ant_switch_queryantennas(); ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=%s", selected_antennas); if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1"); } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0"); } if (ant_switch_read_denymixing()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=1"); } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=0"); } if (ant_switch_read_thunderstorm()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=1"); // also ground antenna if not grounded if (strcmp(selected_antennas, "g")!=0) { char* groundall=(char*)"g\0"; ant_switch_setantenna(groundall); ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=g"); } return true; } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=0"); } return true; } return false; } void ant_switch_close(int rx_chan) { // do nothing } void ant_switch_main(); ext_t ant_switch_ext = { "ant_switch", ant_switch_main, ant_switch_close, ant_switch_msgs, }; void ant_switch_main() { ext_register(&ant_switch_ext); }
// Copyright (c) 2018-2019 Kari Karvonen, OH1KK #include "ext.h" // all calls to the extension interface begin with "ext_", e.g. ext_register() #include "kiwi.h" #include "cfg.h" #include "str.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <math.h> #include <strings.h> #include <sys/types.h> #include <sys/wait.h> //#define ANT_SWITCH_DEBUG_MSG true #define ANT_SWITCH_DEBUG_MSG false // rx_chan is the receiver channel number we've been assigned, 0..RX_CHAN // We need this so the extension can support multiple users, each with their own ant_switch[] data structure. struct ant_switch_t { u1_t rx_chan; }; // Can't use RX_CHANS since 8-channel mode was introduced. // But also can't use the new MAX_RX_CHANS because of the backward compatibility issue. // So just define our own plausible maximum. #define ANT_SW_MAX_RX_CHANS 32 static ant_switch_t ant_switch[ANT_SW_MAX_RX_CHANS]; char * ant_switch_queryantennas() { char *cmd, *reply; static char selected_antennas[256]; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend s"); reply = non_blocking_cmd(cmd, NULL); n = sscanf(kstr_sp(reply), "Selected antennas: %250s", selected_antennas); free(cmd); //printf("frontend: s n=%d reply=<%s>\n", n, kstr_sp(reply)); if (!n) printf("ant_switch_queryantenna BAD STATUS? <%s>\n", kstr_sp(reply)); kstr_free(reply); return(selected_antennas); } int ant_switch_setantenna(char* antenna) { char *cmd, *reply; int status; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend %s", antenna); //printf("frontend: %s\n", antenna); reply = non_blocking_cmd(cmd,NULL); free(cmd); kstr_free(reply); return(0); } int ant_switch_toggleantenna(char* antenna) { char *cmd, *reply; int status; int n; asprintf(&cmd, "/root/extensions/ant_switch/frontend/ant-switch-frontend t%s", antenna); //printf("frontend: t%s\n", antenna); reply = non_blocking_cmd(cmd, NULL); free(cmd); kstr_free(reply); return(0); } int ant_switch_validate_cmd(char *cmd) { int is_valid_cmd = false; if (strcmp(cmd, "1") == 0) is_valid_cmd=true; if (strcmp(cmd, "2") == 0) is_valid_cmd=true; if (strcmp(cmd, "3") == 0) is_valid_cmd=true; if (strcmp(cmd, "4") == 0) is_valid_cmd=true; if (strcmp(cmd, "5") == 0) is_valid_cmd=true; if (strcmp(cmd, "6") == 0) is_valid_cmd=true; if (strcmp(cmd, "7") == 0) is_valid_cmd=true; if (strcmp(cmd, "8") == 0) is_valid_cmd=true; if (strcmp(cmd, "g") == 0) is_valid_cmd=true; return(is_valid_cmd); } bool ant_switch_read_denyswitching() { bool error; char cfgparam[26]="ant_switch.denyswitching\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then switching is allowed if (result == 1) return true; else return false; } bool ant_switch_read_denymixing() { bool error; char cfgparam[26]="ant_switch.denymixing\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed if (result == 1) return true; else return false; } bool ant_switch_read_denymultiuser() { bool error; char cfgparam[26]="ant_switch.denymultiuser\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then switching is allowed if (result == 1) { // option is set. Now check if more than 1 user online rx_util.cpp current_nusers variable if (current_nusers > 1) return true; else return false; } else { return false; } } bool ant_switch_read_thunderstorm() { bool error; char cfgparam[26]="ant_switch.thunderstorm\0"; int result = cfg_int(cfgparam, &error, CFG_OPTIONAL); // error handling: if deny parameter is not defined, or it is 0, then mixing is allowed if (result == 1) return true; else return false; } bool ant_switch_msgs(char *msg, int rx_chan) { ant_switch_t *e = &ant_switch[rx_chan]; int n=0; char antenna[256]; //printf("### ant_switch_msgs RX%d <%s>\n", rx_chan, msg); if (strcmp(msg, "SET ext_server_init") == 0) { e->rx_chan = rx_chan; // remember our receiver channel number ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT ready"); return true; } n = sscanf(msg, "SET Antenna=%s", antenna); if (n == 1) { printf("ant_switch: RX%d %s\n", rx_chan, msg); if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1"); return true; } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0"); } // FIXME: or toggle antenna if antenna mixing is allowed if (ant_switch_validate_cmd(antenna)) { if (ant_switch_read_denymixing() == 1) { ant_switch_setantenna(antenna); } else { ant_switch_toggleantenna(antenna); } } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "Command not valid SET Antenna=%s",antenna); } return true; } if (strcmp(msg, "GET Antenna") == 0) { char *selected_antennas = ant_switch_queryantennas(); ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=%s", selected_antennas); if (ant_switch_read_denyswitching()==true || ant_switch_read_denymultiuser()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=1"); } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenySwitching=0"); } if (ant_switch_read_denymixing()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=1"); } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT AntennaDenyMixing=0"); } if (ant_switch_read_thunderstorm()==true) { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=1"); // also ground antenna if not grounded if (strcmp(selected_antennas, "g")!=0) { char* groundall=(char*)"g\0"; ant_switch_setantenna(groundall); ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Antenna=g"); } return true; } else { ext_send_msg(e->rx_chan, ANT_SWITCH_DEBUG_MSG, "EXT Thunderstorm=0"); } return true; } return false; } void ant_switch_close(int rx_chan) { // do nothing } void ant_switch_main(); ext_t ant_switch_ext = { "ant_switch", ant_switch_main, ant_switch_close, ant_switch_msgs, }; void ant_switch_main() { ext_register(&ant_switch_ext); }
Update ant_switch.cpp
Update ant_switch.cpp
C++
mit
OH1KK/KiwiSDR-antenna-switch-extension,OH1KK/KiwiSDR-antenna-switch-extension,OH1KK/KiwiSDR-antenna-switch-extension
32771673affaf216a06581b13ef3acf2ab08e378
Sources/Loaders/CardLoader.cpp
Sources/Loaders/CardLoader.cpp
/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Models/Card.h> #include <fstream> namespace Hearthstonepp { void CardLoader::Load() { // Read card data from JSON file std::ifstream cardFile("cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; Parse(j); cardFile.close(); } void CardLoader::Parse(json& j) { std::vector<Card> cards; cards.reserve(j.size()); } }
/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Models/Card.h> #include <fstream> namespace Hearthstonepp { void CardLoader::Load() { // Read card data from JSON file std::ifstream cardFile("cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; Parse(j); cardFile.close(); } void CardLoader::Parse(json& j) { std::vector<Card*> cards; cards.reserve(j.size()); // For test int nHeroCard = 0, nMinionCard = 0, nSpellCard = 0, nEnchantmentCard = 0, nWeaponCard = 0, nHeroPowerCard = 0; for (auto& card : j) { if (card["type"] == "HERO") { nHeroCard++; } else if (card["type"] == "MINION") { nMinionCard++; } else if (card["type"] == "SPELL") { nSpellCard++; } else if (card["type"] == "ENCHANTMENT") { nEnchantmentCard++; } else if (card["type"] == "WEAPON") { nWeaponCard++; } else if (card["type"] == "HERO_POWER") { nHeroPowerCard++; } } std::cout << "nHeroCard = " << nHeroCard << std::endl; std::cout << "nMinionCard = " << nMinionCard << std::endl; std::cout << "nSpellCard = " << nSpellCard << std::endl; std::cout << "nEnchantmentCard = " << nEnchantmentCard << std::endl; std::cout << "nWeaponCard = " << nWeaponCard << std::endl; std::cout << "nHeroPowerCard = " << nHeroPowerCard << std::endl; std::cout << "Total = " << nHeroCard + nMinionCard + nSpellCard + nEnchantmentCard + nWeaponCard + nHeroPowerCard << std::endl; } }
Update CardLoader.cpp - Prepare to parse card data
Update CardLoader.cpp - Prepare to parse card data
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
31a762cab37aa623a77f0e29bcbcfc6c2d430721
lumina-fm/main.cpp
lumina-fm/main.cpp
#include <QTranslator> #ifdef __FreeBSD__ #include <qtsingleapplication.h> #endif #include <QtGui/QApplication> #include <QDebug> #include <QFile> #include <QTextCodec> #include "MainUI.h" #include <LuminaOS.h> #include <LuminaThemes.h> int main(int argc, char ** argv) { QStringList in; for(int i=1; i<argc; i++){ //skip the first arg (app binary) in << QString(argv[i]); } if(in.isEmpty()){ in << QDir::homePath(); } #ifdef __FreeBSD__ QtSingleApplication a(argc, argv); if( a.isRunning() ){ return !(a.sendMessage(in.join("\n"))); } #else QApplication a(argc, argv); #endif a.setApplicationName("Insight File Manager"); LuminaThemeEngine themes(&a); //qDebug() << "StyleSheet:\n" << a.styleSheet(); //Load current Locale QTranslator translator; QLocale mylocale; QString langCode = mylocale.name(); if ( ! QFile::exists(LOS::LuminaShare()+"i18n/lumina-fm_" + langCode + ".qm" ) ) langCode.truncate(langCode.indexOf("_")); translator.load( QString("lumina-fm_") + langCode, LOS::LuminaShare()+"i18n/" ); a.installTranslator( &translator ); qDebug() << "Locale:" << langCode; //Load current encoding for this locale QTextCodec::setCodecForTr( QTextCodec::codecForLocale() ); //make sure to use the same codec qDebug() << "Locale Encoding:" << QTextCodec::codecForLocale()->name(); MainUI w; QObject::connect(&a, SIGNAL(messageReceived(const QString&)), &w, SLOT(slotSingleInstance(const QString&)) ); w.OpenDirs(in); w.show(); int retCode = a.exec(); return retCode; }
#include <QTranslator> #ifdef __FreeBSD__ #include <qtsingleapplication.h> #endif #include <QtGui/QApplication> #include <QDebug> #include <QFile> #include <QTextCodec> #include "MainUI.h" #include <LuminaOS.h> //#include <LuminaThemes.h> int main(int argc, char ** argv) { QStringList in; for(int i=1; i<argc; i++){ //skip the first arg (app binary) in << QString(argv[i]); } if(in.isEmpty()){ in << QDir::homePath(); } #ifdef __FreeBSD__ QtSingleApplication a(argc, argv); if( a.isRunning() ){ return !(a.sendMessage(in.join("\n"))); } #else QApplication a(argc, argv); #endif a.setApplicationName("Insight File Manager"); //LuminaThemeEngine themes(&a); //qDebug() << "StyleSheet:\n" << a.styleSheet(); //Load current Locale QTranslator translator; QLocale mylocale; QString langCode = mylocale.name(); if ( ! QFile::exists(LOS::LuminaShare()+"i18n/lumina-fm_" + langCode + ".qm" ) ) langCode.truncate(langCode.indexOf("_")); translator.load( QString("lumina-fm_") + langCode, LOS::LuminaShare()+"i18n/" ); a.installTranslator( &translator ); qDebug() << "Locale:" << langCode; //Load current encoding for this locale QTextCodec::setCodecForTr( QTextCodec::codecForLocale() ); //make sure to use the same codec qDebug() << "Locale Encoding:" << QTextCodec::codecForLocale()->name(); MainUI w; QObject::connect(&a, SIGNAL(messageReceived(const QString&)), &w, SLOT(slotSingleInstance(const QString&)) ); w.OpenDirs(in); w.show(); int retCode = a.exec(); return retCode; }
Disable the usage of the theme engine within lumina-fm for the moment. Still trying to work out some of the functionality and don't want to enable it by default until it is fully ready.
Disable the usage of the theme engine within lumina-fm for the moment. Still trying to work out some of the functionality and don't want to enable it by default until it is fully ready.
C++
bsd-3-clause
krytarowski/lumina,grahamperrin/lumina,cpforbes/lumina,trueos/lumina,krytarowski/lumina,mneumann/lumina,pcbsd/lumina,cpforbes/lumina,pcbsd/lumina,harcobbit/lumina,Nanolx/lumina,harcobbit/lumina,trueos/lumina,sasongko26/lumina,cpforbes/lumina,sasongko26/lumina,sasongko26/lumina,cpforbes/lumina,cpforbes/lumina,trueos/lumina,trueos/lumina,trueos/lumina,simplexb/lumina,trueos/lumina,trueos/lumina,grahamperrin/lumina,Nanolx/lumina,cpforbes/lumina,mneumann/lumina,sasongko26/lumina,sasongko26/lumina,harcobbit/lumina,sasongko26/lumina,Nanolx/lumina,cpforbes/lumina,simplexb/lumina,krytarowski/lumina,sasongko26/lumina,trueos/lumina,sasongko26/lumina,pcbsd/lumina,cpforbes/lumina
acf85a3bed5836901fbb8497f7318ab699bacff2
src/file-events/cpp/win_fsnotifier.cpp
src/file-events/cpp/win_fsnotifier.cpp
#ifdef _WIN32 #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, size_t bufferSize, const u16string& path) : path(path) , status(WatchPointStatus::NOT_LISTENING) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { throw FileWatcherException("Couldn't add watch", path, GetLastError()); } this->directoryHandle = directoryHandle; this->server = server; this->buffer.reserve(bufferSize); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; switch (listen()) { case ListenResult::SUCCESS: break; case ListenResult::DELETED: throw FileWatcherException("Couldn't start watching because path is not a directory", path); } } bool WatchPoint::cancel() { if (status == WatchPointStatus::LISTENING) { logToJava(LogLevel::FINE, "Cancelling %s", utf16ToUtf8String(path).c_str()); bool cancelled = (bool) CancelIoEx(directoryHandle, &overlapped); if (cancelled) { status = WatchPointStatus::CANCELLED; } else { DWORD cancelError = GetLastError(); close(); if (cancelError == ERROR_NOT_FOUND) { // Do nothing, looks like this is a typical scenario logToJava(LogLevel::FINE, "Watch point already finished %s", utf16ToUtf8String(path).c_str()); } else { throw FileWatcherException("Couldn't cancel watch point", path, cancelError); } } return cancelled; } return false; } WatchPoint::~WatchPoint() { try { if (cancel()) { SleepEx(0, true); } close(); } catch (const exception& ex) { logToJava(LogLevel::WARNING, "Couldn't cancel watch point %s: %s", utf16ToUtf8String(path).c_str(), ex.what()); } } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEventsInBuffer(errorCode, bytesTransferred); } bool WatchPoint::isValidDirectory() { wstring pathW(path.begin(), path.end()); DWORD attrib = GetFileAttributesW(pathW.c_str()); return (attrib != INVALID_FILE_ATTRIBUTES) && ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0); } ListenResult WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory &buffer[0], // read results buffer (DWORD) buffer.capacity(), // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); if (success) { status = WatchPointStatus::LISTENING; return ListenResult::SUCCESS; } else { DWORD listenError = GetLastError(); close(); if (listenError == ERROR_ACCESS_DENIED && !isValidDirectory()) { return ListenResult::DELETED; } else { throw FileWatcherException("Couldn't start watching", path, listenError); } } } void WatchPoint::close() { if (status != WatchPointStatus::FINISHED) { BOOL ret = CloseHandle(directoryHandle); if (!ret) { logToJava(LogLevel::SEVERE, "Couldn't close handle %p for '%ls': %d", directoryHandle, utf16ToUtf8String(path).c_str(), GetLastError()); } status = WatchPointStatus::FINISHED; } } void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) { if (errorCode == ERROR_OPERATION_ABORTED) { logToJava(LogLevel::FINE, "Finished watching '%s', status = %d", utf16ToUtf8String(path).c_str(), status); close(); return; } if (status != WatchPointStatus::LISTENING) { logToJava(LogLevel::FINE, "Ignoring incoming events for %s as watch-point is not listening (%d bytes, errorCode = %d, status = %d)", utf16ToUtf8String(path).c_str(), bytesTransferred, errorCode, status); return; } status = WatchPointStatus::NOT_LISTENING; server->handleEvents(this, errorCode, buffer, bytesTransferred); } void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) { unique_lock<mutex> lock(mutationMutex); JNIEnv* env = getThreadEnv(); const u16string& path = watchPoint->path; try { if (errorCode != ERROR_SUCCESS) { if (errorCode == ERROR_ACCESS_DENIED && !watchPoint->isValidDirectory()) { reportChangeEvent(env, ChangeType::REMOVED, path); watchPoint->close(); return; } else { throw FileWatcherException("Error received when handling events", path, errorCode); } } if (shouldTerminate) { logToJava(LogLevel::FINE, "Ignoring incoming events for %s because server is terminating (%d bytes, status = %d)", utf16ToUtf8String(path).c_str(), bytesTransferred, watchPoint->status); return; } if (bytesTransferred == 0) { // This is what the documentation has to say about a zero-length dataset: // // If the number of bytes transferred is zero, the buffer was either too large // for the system to allocate or too small to provide detailed information on // all the changes that occurred in the directory or subtree. In this case, // you should compute the changes by enumerating the directory or subtree. // // (See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw) // // We'll handle this as a simple overflow and report it as such. reportOverflow(env, path); } else { int index = 0; for (;;) { FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index]; handleEvent(env, path, current); if (current->NextEntryOffset == 0) { break; } index += current->NextEntryOffset; } } switch (watchPoint->listen()) { case ListenResult::SUCCESS: break; case ListenResult::DELETED: logToJava(LogLevel::FINE, "Watched directory removed for %s", utf16ToUtf8String(path).c_str()); reportChangeEvent(env, ChangeType::REMOVED, path); break; } } catch (const exception& ex) { reportFailure(env, ex); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } bool isLongPath(const u16string& path) { return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\"; } bool isUncLongPath(const u16string& path) { return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\"; } // TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation? void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } // It is already a long path, nothing to do here if (isLongPath(path)) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); } changedPath.insert(0, path); // TODO Remove long prefix for path once? if (isLongPath(changedPath)) { if (isUncLongPath(changedPath)) { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } logToJava(LogLevel::FINE, "Change detected: 0x%x '%s'", info->Action, utf16ToUtf8String(changedPath).c_str()); ChangeType type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = ChangeType::CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = ChangeType::REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = ChangeType::MODIFIED; } else { logToJava(LogLevel::WARNING, "Unknown event 0x%x for %s", info->Action, utf16ToUtf8String(changedPath).c_str()); reportUnknownEvent(env, changedPath); return; } reportChangeEvent(env, type, changedPath); } // // Server // Server::Server(JNIEnv* env, size_t bufferSize, long commandTimeoutInMillis, jobject watcherCallback) : AbstractServer(env, watcherCallback) , bufferSize(bufferSize) , commandTimeoutInMillis(commandTimeoutInMillis) { } void Server::initializeRunLoop() { // For some reason GetCurrentThread() returns a thread that doesn't accept APCs // so we need to use OpenThread() instead. threadHandle = OpenThread( THREAD_ALL_ACCESS, // dwDesiredAccess false, // bInheritHandle GetCurrentThreadId() // dwThreadId ); if (threadHandle == NULL) { throw FileWatcherException("Couldn't open current thread", GetLastError()); } } void Server::shutdownRunLoop() { executeOnRunLoop([this]() { shouldTerminate = true; return true; }); } void Server::runLoop() { while (!shouldTerminate) { SleepEx(INFINITE, true); } // We have received termination, cancel all watchers unique_lock<mutex> lock(mutationMutex); logToJava(LogLevel::FINE, "Finished with run loop, now cancelling remaining watch points", NULL); int pendingWatchPoints = 0; for (auto& it : watchPoints) { auto& watchPoint = it.second; switch (watchPoint.status) { case WatchPointStatus::LISTENING: try { if (watchPoint.cancel()) { pendingWatchPoints++; } } catch (const exception& ex) { logToJava(LogLevel::SEVERE, "%s", ex.what()); } break; case WatchPointStatus::CANCELLED: pendingWatchPoints++; break; default: break; } } // If there are any pending watchers, wait for them to finish if (pendingWatchPoints > 0) { logToJava(LogLevel::FINE, "Waiting for %d pending watch points to finish", pendingWatchPoints); SleepEx(0, true); } // Warn about any unfinished watchpoints for (auto& it : watchPoints) { auto& watchPoint = it.second; switch (watchPoint.status) { case WatchPointStatus::NOT_LISTENING: case WatchPointStatus::FINISHED: break; default: logToJava(LogLevel::WARNING, "Watch point %s did not finish before termination timeout (status = %d)", utf16ToUtf8String(watchPoint.path).c_str(), watchPoint.status); break; } } CloseHandle(threadHandle); } struct Command { function<bool()> function; mutex executionMutex; condition_variable executed; bool result; exception_ptr failure; }; static void CALLBACK executeOnRunLoopCallback(_In_ ULONG_PTR info) { Command* command = (Command*) info; try { command->result = command->function(); } catch (const exception&) { command->failure = current_exception(); } unique_lock<mutex> lock(command->executionMutex); command->executed.notify_all(); } bool Server::executeOnRunLoop(function<bool()> function) { Command command; command.function = function; unique_lock<mutex> lock(command.executionMutex); DWORD ret = QueueUserAPC(executeOnRunLoopCallback, threadHandle, (ULONG_PTR) &command); if (ret == 0) { throw FileWatcherException("Received error while queuing APC", GetLastError()); } auto status = command.executed.wait_for(lock, chrono::milliseconds(commandTimeoutInMillis)); if (status == cv_status::timeout) { throw FileWatcherException("Execution timed out"); } else if (command.failure) { rethrow_exception(command.failure); } else { return command.result; } } void Server::registerPaths(const vector<u16string>& paths) { executeOnRunLoop([this, paths]() { AbstractServer::registerPaths(paths); return true; }); } bool Server::unregisterPaths(const vector<u16string>& paths) { return executeOnRunLoop([this, paths]() { return AbstractServer::unregisterPaths(paths); }); } void Server::registerPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); auto it = watchPoints.find(longPath); if (it != watchPoints.end()) { if (it->second.status != WatchPointStatus::FINISHED) { throw FileWatcherException("Already watching path", path); } watchPoints.erase(it); } watchPoints.emplace(piecewise_construct, forward_as_tuple(longPath), forward_as_tuple(this, bufferSize, longPath)); } bool Server::unregisterPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); if (watchPoints.erase(longPath) == 0) { logToJava(LogLevel::INFO, "Path is not watched: %s", utf16ToUtf8String(path).c_str()); return false; } return true; } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher0(JNIEnv* env, jclass target, jint bufferSize, jlong commandTimeoutInMillis, jobject javaCallback) { return wrapServer(env, new Server(env, bufferSize, (long) commandTimeoutInMillis, javaCallback)); } #endif
#ifdef _WIN32 #include "win_fsnotifier.h" using namespace std; // // WatchPoint // WatchPoint::WatchPoint(Server* server, size_t bufferSize, const u16string& path) : path(path) , status(WatchPointStatus::NOT_LISTENING) { wstring pathW(path.begin(), path.end()); HANDLE directoryHandle = CreateFileW( pathW.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode CREATE_SHARE, // share mode NULL, // security descriptor OPEN_EXISTING, // how to create CREATE_FLAGS, // file attributes NULL // file with attributes to copy ); if (directoryHandle == INVALID_HANDLE_VALUE) { throw FileWatcherException("Couldn't add watch", path, GetLastError()); } this->directoryHandle = directoryHandle; this->server = server; this->buffer.reserve(bufferSize); ZeroMemory(&this->overlapped, sizeof(OVERLAPPED)); this->overlapped.hEvent = this; switch (listen()) { case ListenResult::SUCCESS: break; case ListenResult::DELETED: throw FileWatcherException("Couldn't start watching because path is not a directory", path); } } bool WatchPoint::cancel() { if (status == WatchPointStatus::LISTENING) { logToJava(LogLevel::FINE, "Cancelling %s", utf16ToUtf8String(path).c_str()); bool cancelled = (bool) CancelIoEx(directoryHandle, &overlapped); if (cancelled) { status = WatchPointStatus::CANCELLED; } else { DWORD cancelError = GetLastError(); close(); if (cancelError == ERROR_NOT_FOUND) { // Do nothing, looks like this is a typical scenario logToJava(LogLevel::FINE, "Watch point already finished %s", utf16ToUtf8String(path).c_str()); } else { throw FileWatcherException("Couldn't cancel watch point", path, cancelError); } } return cancelled; } return false; } WatchPoint::~WatchPoint() { try { if (cancel()) { SleepEx(0, true); } close(); } catch (const exception& ex) { logToJava(LogLevel::WARNING, "Couldn't cancel watch point %s: %s", utf16ToUtf8String(path).c_str(), ex.what()); } } static void CALLBACK handleEventCallback(DWORD errorCode, DWORD bytesTransferred, LPOVERLAPPED overlapped) { WatchPoint* watchPoint = (WatchPoint*) overlapped->hEvent; watchPoint->handleEventsInBuffer(errorCode, bytesTransferred); } bool WatchPoint::isValidDirectory() { wstring pathW(path.begin(), path.end()); DWORD attrib = GetFileAttributesW(pathW.c_str()); return (attrib != INVALID_FILE_ATTRIBUTES) && ((attrib & FILE_ATTRIBUTE_DIRECTORY) != 0); } ListenResult WatchPoint::listen() { BOOL success = ReadDirectoryChangesW( directoryHandle, // handle to directory &buffer[0], // read results buffer (DWORD) buffer.capacity(), // length of buffer TRUE, // include children EVENT_MASK, // filter conditions NULL, // bytes returned &overlapped, // overlapped buffer &handleEventCallback // completion routine ); if (success) { status = WatchPointStatus::LISTENING; return ListenResult::SUCCESS; } else { DWORD listenError = GetLastError(); close(); if (listenError == ERROR_ACCESS_DENIED && !isValidDirectory()) { return ListenResult::DELETED; } else { throw FileWatcherException("Couldn't start watching", path, listenError); } } } void WatchPoint::close() { if (status != WatchPointStatus::FINISHED) { try { BOOL ret = CloseHandle(directoryHandle); if (!ret) { logToJava(LogLevel::SEVERE, "Couldn't close handle %p for '%ls': %d", directoryHandle, utf16ToUtf8String(path).c_str(), GetLastError()); } } catch (const exception& ex) { // Apparently with debugging enabled CloseHandle() can also throw, see: // https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle#return-value logToJava(LogLevel::SEVERE, "Couldn't close handle %p for '%ls': %s", directoryHandle, utf16ToUtf8String(path).c_str(), ex.what()); } status = WatchPointStatus::FINISHED; } } void WatchPoint::handleEventsInBuffer(DWORD errorCode, DWORD bytesTransferred) { if (errorCode == ERROR_OPERATION_ABORTED) { logToJava(LogLevel::FINE, "Finished watching '%s', status = %d", utf16ToUtf8String(path).c_str(), status); close(); return; } if (status != WatchPointStatus::LISTENING) { logToJava(LogLevel::FINE, "Ignoring incoming events for %s as watch-point is not listening (%d bytes, errorCode = %d, status = %d)", utf16ToUtf8String(path).c_str(), bytesTransferred, errorCode, status); return; } status = WatchPointStatus::NOT_LISTENING; server->handleEvents(this, errorCode, buffer, bytesTransferred); } void Server::handleEvents(WatchPoint* watchPoint, DWORD errorCode, const vector<BYTE>& buffer, DWORD bytesTransferred) { unique_lock<mutex> lock(mutationMutex); JNIEnv* env = getThreadEnv(); const u16string& path = watchPoint->path; try { if (errorCode != ERROR_SUCCESS) { if (errorCode == ERROR_ACCESS_DENIED && !watchPoint->isValidDirectory()) { reportChangeEvent(env, ChangeType::REMOVED, path); watchPoint->close(); return; } else { throw FileWatcherException("Error received when handling events", path, errorCode); } } if (shouldTerminate) { logToJava(LogLevel::FINE, "Ignoring incoming events for %s because server is terminating (%d bytes, status = %d)", utf16ToUtf8String(path).c_str(), bytesTransferred, watchPoint->status); return; } if (bytesTransferred == 0) { // This is what the documentation has to say about a zero-length dataset: // // If the number of bytes transferred is zero, the buffer was either too large // for the system to allocate or too small to provide detailed information on // all the changes that occurred in the directory or subtree. In this case, // you should compute the changes by enumerating the directory or subtree. // // (See https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw) // // We'll handle this as a simple overflow and report it as such. reportOverflow(env, path); } else { int index = 0; for (;;) { FILE_NOTIFY_INFORMATION* current = (FILE_NOTIFY_INFORMATION*) &buffer[index]; handleEvent(env, path, current); if (current->NextEntryOffset == 0) { break; } index += current->NextEntryOffset; } } switch (watchPoint->listen()) { case ListenResult::SUCCESS: break; case ListenResult::DELETED: logToJava(LogLevel::FINE, "Watched directory removed for %s", utf16ToUtf8String(path).c_str()); reportChangeEvent(env, ChangeType::REMOVED, path); break; } } catch (const exception& ex) { reportFailure(env, ex); } } bool isAbsoluteLocalPath(const u16string& path) { if (path.length() < 3) { return false; } return ((u'a' <= path[0] && path[0] <= u'z') || (u'A' <= path[0] && path[0] <= u'Z')) && path[1] == u':' && path[2] == u'\\'; } bool isAbsoluteUncPath(const u16string& path) { if (path.length() < 3) { return false; } return path[0] == u'\\' && path[1] == u'\\'; } bool isLongPath(const u16string& path) { return path.length() >= 4 && path.substr(0, 4) == u"\\\\?\\"; } bool isUncLongPath(const u16string& path) { return path.length() >= 8 && path.substr(0, 8) == u"\\\\?\\UNC\\"; } // TODO How can this be done nicer, wihtout both unnecessary copy and in-place mutation? void convertToLongPathIfNeeded(u16string& path) { // Technically, this should be MAX_PATH (i.e. 260), except some Win32 API related // to working with directory paths are actually limited to 240. It is just // safer/simpler to cover both cases in one code path. if (path.length() <= 240) { return; } // It is already a long path, nothing to do here if (isLongPath(path)) { return; } if (isAbsoluteLocalPath(path)) { // Format: C:\... -> \\?\C:\... path.insert(0, u"\\\\?\\"); } else if (isAbsoluteUncPath(path)) { // In this case, we need to skip the first 2 characters: // Format: \\server\share\... -> \\?\UNC\server\share\... path.erase(0, 2); path.insert(0, u"\\\\?\\UNC\\"); } else { // It is some sort of unknown format, don't mess with it } } void Server::handleEvent(JNIEnv* env, const u16string& path, FILE_NOTIFY_INFORMATION* info) { wstring changedPathW = wstring(info->FileName, 0, info->FileNameLength / sizeof(wchar_t)); u16string changedPath(changedPathW.begin(), changedPathW.end()); if (!changedPath.empty()) { changedPath.insert(0, 1, u'\\'); } changedPath.insert(0, path); // TODO Remove long prefix for path once? if (isLongPath(changedPath)) { if (isUncLongPath(changedPath)) { changedPath.erase(0, 8).insert(0, u"\\\\"); } else { changedPath.erase(0, 4); } } logToJava(LogLevel::FINE, "Change detected: 0x%x '%s'", info->Action, utf16ToUtf8String(changedPath).c_str()); ChangeType type; if (info->Action == FILE_ACTION_ADDED || info->Action == FILE_ACTION_RENAMED_NEW_NAME) { type = ChangeType::CREATED; } else if (info->Action == FILE_ACTION_REMOVED || info->Action == FILE_ACTION_RENAMED_OLD_NAME) { type = ChangeType::REMOVED; } else if (info->Action == FILE_ACTION_MODIFIED) { type = ChangeType::MODIFIED; } else { logToJava(LogLevel::WARNING, "Unknown event 0x%x for %s", info->Action, utf16ToUtf8String(changedPath).c_str()); reportUnknownEvent(env, changedPath); return; } reportChangeEvent(env, type, changedPath); } // // Server // Server::Server(JNIEnv* env, size_t bufferSize, long commandTimeoutInMillis, jobject watcherCallback) : AbstractServer(env, watcherCallback) , bufferSize(bufferSize) , commandTimeoutInMillis(commandTimeoutInMillis) { } void Server::initializeRunLoop() { // For some reason GetCurrentThread() returns a thread that doesn't accept APCs // so we need to use OpenThread() instead. threadHandle = OpenThread( THREAD_ALL_ACCESS, // dwDesiredAccess false, // bInheritHandle GetCurrentThreadId() // dwThreadId ); if (threadHandle == NULL) { throw FileWatcherException("Couldn't open current thread", GetLastError()); } } void Server::shutdownRunLoop() { executeOnRunLoop([this]() { shouldTerminate = true; return true; }); } void Server::runLoop() { while (!shouldTerminate) { SleepEx(INFINITE, true); } // We have received termination, cancel all watchers unique_lock<mutex> lock(mutationMutex); logToJava(LogLevel::FINE, "Finished with run loop, now cancelling remaining watch points", NULL); int pendingWatchPoints = 0; for (auto& it : watchPoints) { auto& watchPoint = it.second; switch (watchPoint.status) { case WatchPointStatus::LISTENING: try { if (watchPoint.cancel()) { pendingWatchPoints++; } } catch (const exception& ex) { logToJava(LogLevel::SEVERE, "%s", ex.what()); } break; case WatchPointStatus::CANCELLED: pendingWatchPoints++; break; default: break; } } // If there are any pending watchers, wait for them to finish if (pendingWatchPoints > 0) { logToJava(LogLevel::FINE, "Waiting for %d pending watch points to finish", pendingWatchPoints); SleepEx(0, true); } // Warn about any unfinished watchpoints for (auto& it : watchPoints) { auto& watchPoint = it.second; switch (watchPoint.status) { case WatchPointStatus::NOT_LISTENING: case WatchPointStatus::FINISHED: break; default: logToJava(LogLevel::WARNING, "Watch point %s did not finish before termination timeout (status = %d)", utf16ToUtf8String(watchPoint.path).c_str(), watchPoint.status); break; } } CloseHandle(threadHandle); } struct Command { function<bool()> function; mutex executionMutex; condition_variable executed; bool result; exception_ptr failure; }; static void CALLBACK executeOnRunLoopCallback(_In_ ULONG_PTR info) { Command* command = (Command*) info; try { command->result = command->function(); } catch (const exception&) { command->failure = current_exception(); } unique_lock<mutex> lock(command->executionMutex); command->executed.notify_all(); } bool Server::executeOnRunLoop(function<bool()> function) { Command command; command.function = function; unique_lock<mutex> lock(command.executionMutex); DWORD ret = QueueUserAPC(executeOnRunLoopCallback, threadHandle, (ULONG_PTR) &command); if (ret == 0) { throw FileWatcherException("Received error while queuing APC", GetLastError()); } auto status = command.executed.wait_for(lock, chrono::milliseconds(commandTimeoutInMillis)); if (status == cv_status::timeout) { throw FileWatcherException("Execution timed out"); } else if (command.failure) { rethrow_exception(command.failure); } else { return command.result; } } void Server::registerPaths(const vector<u16string>& paths) { executeOnRunLoop([this, paths]() { AbstractServer::registerPaths(paths); return true; }); } bool Server::unregisterPaths(const vector<u16string>& paths) { return executeOnRunLoop([this, paths]() { return AbstractServer::unregisterPaths(paths); }); } void Server::registerPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); auto it = watchPoints.find(longPath); if (it != watchPoints.end()) { if (it->second.status != WatchPointStatus::FINISHED) { throw FileWatcherException("Already watching path", path); } watchPoints.erase(it); } watchPoints.emplace(piecewise_construct, forward_as_tuple(longPath), forward_as_tuple(this, bufferSize, longPath)); } bool Server::unregisterPath(const u16string& path) { u16string longPath = path; convertToLongPathIfNeeded(longPath); if (watchPoints.erase(longPath) == 0) { logToJava(LogLevel::INFO, "Path is not watched: %s", utf16ToUtf8String(path).c_str()); return false; } return true; } // // JNI calls // JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_WindowsFileEventFunctions_startWatcher0(JNIEnv* env, jclass target, jint bufferSize, jlong commandTimeoutInMillis, jobject javaCallback) { return wrapServer(env, new Server(env, bufferSize, (long) commandTimeoutInMillis, javaCallback)); } #endif
Handle exception thrown by CloseHandle Windows API
Handle exception thrown by CloseHandle Windows API CloseHandle() can throw a structured exception (SEH) which we must handle in WatchPoint::close() instead of letting it buble up to ~WatchPoint().
C++
apache-2.0
adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform
3b69e3f6737f30f429361889c62ec9f324b6ffa2
firmware/nuengine/Rasterizer.cpp
firmware/nuengine/Rasterizer.cpp
// // Copyright 2011-2013 Jeff Bush // // 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 "Debug.h" #include "Rasterizer.h" #include "vectypes.h" const veci16 kXStep = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }; const veci16 kYStep = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 }; Rasterizer::Rasterizer() : fShader(nullptr) { } void Rasterizer::setupEdge(int left, int top, int tileSize, int x1, int y1, int x2, int y2, int &outAcceptEdgeValue, int &outRejectEdgeValue, veci16 &outAcceptStepMatrix, veci16 &outRejectStepMatrix) { veci16 xAcceptStepValues = kXStep * splati(tileSize / 4); veci16 yAcceptStepValues = kYStep * splati(tileSize / 4); veci16 xRejectStepValues = xAcceptStepValues; veci16 yRejectStepValues = yAcceptStepValues; int trivialAcceptX = left; int trivialAcceptY = top; int trivialRejectX = left; int trivialRejectY = top; const int kThreeQuarterTile = tileSize * 3 / 4; if (y2 > y1) { trivialAcceptX += tileSize - 1; xAcceptStepValues = xAcceptStepValues - splati(kThreeQuarterTile); } else { trivialRejectX += tileSize - 1; xRejectStepValues = xRejectStepValues - splati(kThreeQuarterTile); } if (x2 > x1) { trivialRejectY += tileSize - 1; yRejectStepValues = yRejectStepValues - splati(kThreeQuarterTile); } else { trivialAcceptY += tileSize - 1; yAcceptStepValues = yAcceptStepValues - splati(kThreeQuarterTile); } int xStep = y2 - y1; int yStep = x2 - x1; outAcceptEdgeValue = (trivialAcceptX - x1) * xStep - (trivialAcceptY - y1) * yStep; outRejectEdgeValue = (trivialRejectX - x1) * xStep - (trivialRejectY - y1) * yStep; // Set up xStepValues xAcceptStepValues *= splati(xStep); xRejectStepValues *= splati(xStep); // Set up yStepValues yAcceptStepValues *= splati(yStep); yRejectStepValues *= splati(yStep); // Add together outAcceptStepMatrix = xAcceptStepValues - yAcceptStepValues; outRejectStepMatrix = xRejectStepValues - yRejectStepValues; } void Rasterizer::subdivideTile( int acceptCornerValue1, int acceptCornerValue2, int acceptCornerValue3, int rejectCornerValue1, int rejectCornerValue2, int rejectCornerValue3, veci16 acceptStep1, veci16 acceptStep2, veci16 acceptStep3, veci16 rejectStep1, veci16 rejectStep2, veci16 rejectStep3, int tileSize, int left, int top) { veci16 acceptEdgeValue1; veci16 acceptEdgeValue2; veci16 acceptEdgeValue3; veci16 rejectEdgeValue1; veci16 rejectEdgeValue2; veci16 rejectEdgeValue3; int trivialAcceptMask; int trivialRejectMask; int recurseMask; int index; int x, y; // Compute accept masks acceptEdgeValue1 = acceptStep1 + splati(acceptCornerValue1); trivialAcceptMask = __builtin_vp_mask_cmpi_sle(acceptEdgeValue1, splati(0)); acceptEdgeValue2 = acceptStep2 + splati(acceptCornerValue2); trivialAcceptMask &= __builtin_vp_mask_cmpi_sle(acceptEdgeValue2, splati(0)); acceptEdgeValue3 = acceptStep3 + splati(acceptCornerValue3); trivialAcceptMask &= __builtin_vp_mask_cmpi_sle(acceptEdgeValue3, splati(0)); if (tileSize == 4) { // End recursion fShader->fillMasked(left, top, trivialAcceptMask); return; } // Reduce tile size for sub blocks tileSize = tileSize / 4; // Process all trivially accepted blocks if (trivialAcceptMask != 0) { int index; int currentMask = trivialAcceptMask; while (currentMask) { index = __builtin_clz(currentMask) - 16; currentMask &= ~(0x8000 >> index); int blockLeft = left + tileSize * (index & 3); int blockTop = top + tileSize * (index >> 2); for (int y = 0; y < tileSize; y += 4) { for (int x = 0; x < tileSize; x += 4) fShader->fillMasked(blockLeft + x, blockTop + y, 0xffff); } } } // Compute reject masks rejectEdgeValue1 = rejectStep1 + splati(rejectCornerValue1); trivialRejectMask = __builtin_vp_mask_cmpi_sge(rejectEdgeValue1, splati(0)); rejectEdgeValue2 = rejectStep2 + splati(rejectCornerValue2); trivialRejectMask |= __builtin_vp_mask_cmpi_sge(rejectEdgeValue2, splati(0)); rejectEdgeValue3 = rejectStep3 + splati(rejectCornerValue3); trivialRejectMask |= __builtin_vp_mask_cmpi_sge(rejectEdgeValue3, splati(0)); recurseMask = (trivialAcceptMask | trivialRejectMask) ^ 0xffff; if (recurseMask) { // Divide each step matrix by 4 acceptStep1 = acceptStep1 >> splati(2); acceptStep2 = acceptStep2 >> splati(2); acceptStep3 = acceptStep3 >> splati(2); rejectStep1 = rejectStep1 >> splati(2); rejectStep2 = rejectStep2 >> splati(2); rejectStep3 = rejectStep3 >> splati(2); // Recurse into blocks that are neither trivially rejected or accepted. // They are partially overlapped and need to be further subdivided. while (recurseMask) { index = __builtin_clz(recurseMask) - 16; recurseMask &= ~(0x8000 >> index); x = left + tileSize * (index & 3); y = top + tileSize * (index >> 2); subdivideTile( acceptEdgeValue1[index], acceptEdgeValue2[index], acceptEdgeValue3[index], rejectEdgeValue1[index], rejectEdgeValue2[index], rejectEdgeValue3[index], acceptStep1, acceptStep2, acceptStep3, rejectStep1, rejectStep2, rejectStep3, tileSize, x, y); } } } void Rasterizer::rasterizeTriangle(PixelShader *shader, int left, int top, int tileSize, int x1, int y1, int x2, int y2, int x3, int y3) { int acceptValue1; int rejectValue1; veci16 acceptStepMatrix1; veci16 rejectStepMatrix1; int acceptValue2; int rejectValue2; veci16 acceptStepMatrix2; veci16 rejectStepMatrix2; int acceptValue3; int rejectValue3; veci16 acceptStepMatrix3; veci16 rejectStepMatrix3; fShader = shader; setupEdge(left, top, tileSize, x1, y1, x2, y2, acceptValue1, rejectValue1, acceptStepMatrix1, rejectStepMatrix1); setupEdge(left, top, tileSize, x2, y2, x3, y3, acceptValue2, rejectValue2, acceptStepMatrix2, rejectStepMatrix2); setupEdge(left, top, tileSize, x3, y3, x1, y1, acceptValue3, rejectValue3, acceptStepMatrix3, rejectStepMatrix3); subdivideTile( acceptValue1, acceptValue2, acceptValue3, rejectValue1, rejectValue2, rejectValue3, acceptStepMatrix1, acceptStepMatrix2, acceptStepMatrix3, rejectStepMatrix1, rejectStepMatrix2, rejectStepMatrix3, tileSize, left, top); }
// // Copyright 2011-2013 Jeff Bush // // 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 "Debug.h" #include "Rasterizer.h" #include "vectypes.h" const veci16 kXStep = { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }; const veci16 kYStep = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 }; Rasterizer::Rasterizer() : fShader(nullptr) { } void Rasterizer::setupEdge(int left, int top, int tileSize, int x1, int y1, int x2, int y2, int &outAcceptEdgeValue, int &outRejectEdgeValue, veci16 &outAcceptStepMatrix, veci16 &outRejectStepMatrix) { veci16 xAcceptStepValues = kXStep * splati(tileSize / 4); veci16 yAcceptStepValues = kYStep * splati(tileSize / 4); veci16 xRejectStepValues = xAcceptStepValues; veci16 yRejectStepValues = yAcceptStepValues; int trivialAcceptX = left; int trivialAcceptY = top; int trivialRejectX = left; int trivialRejectY = top; const int kThreeQuarterTile = tileSize * 3 / 4; if (y2 > y1) { trivialAcceptX += tileSize - 1; xAcceptStepValues = xAcceptStepValues - splati(kThreeQuarterTile); } else { trivialRejectX += tileSize - 1; xRejectStepValues = xRejectStepValues - splati(kThreeQuarterTile); } if (x2 > x1) { trivialRejectY += tileSize - 1; yRejectStepValues = yRejectStepValues - splati(kThreeQuarterTile); } else { trivialAcceptY += tileSize - 1; yAcceptStepValues = yAcceptStepValues - splati(kThreeQuarterTile); } int xStep = y2 - y1; int yStep = x2 - x1; outAcceptEdgeValue = (trivialAcceptX - x1) * xStep - (trivialAcceptY - y1) * yStep; outRejectEdgeValue = (trivialRejectX - x1) * xStep - (trivialRejectY - y1) * yStep; if (y1 > y2 || (y1 == y2 && x2 > x1)) { // This is a top or left edge. We adjust the edge equation values by one // so it doesn't overlap. outAcceptEdgeValue++; outRejectEdgeValue++; } // Set up xStepValues xAcceptStepValues *= splati(xStep); xRejectStepValues *= splati(xStep); // Set up yStepValues yAcceptStepValues *= splati(yStep); yRejectStepValues *= splati(yStep); // Add together outAcceptStepMatrix = xAcceptStepValues - yAcceptStepValues; outRejectStepMatrix = xRejectStepValues - yRejectStepValues; } void Rasterizer::subdivideTile( int acceptCornerValue1, int acceptCornerValue2, int acceptCornerValue3, int rejectCornerValue1, int rejectCornerValue2, int rejectCornerValue3, veci16 acceptStep1, veci16 acceptStep2, veci16 acceptStep3, veci16 rejectStep1, veci16 rejectStep2, veci16 rejectStep3, int tileSize, int left, int top) { veci16 acceptEdgeValue1; veci16 acceptEdgeValue2; veci16 acceptEdgeValue3; veci16 rejectEdgeValue1; veci16 rejectEdgeValue2; veci16 rejectEdgeValue3; int trivialAcceptMask; int trivialRejectMask; int recurseMask; int index; int x, y; // Compute accept masks acceptEdgeValue1 = acceptStep1 + splati(acceptCornerValue1); trivialAcceptMask = __builtin_vp_mask_cmpi_sle(acceptEdgeValue1, splati(0)); acceptEdgeValue2 = acceptStep2 + splati(acceptCornerValue2); trivialAcceptMask &= __builtin_vp_mask_cmpi_sle(acceptEdgeValue2, splati(0)); acceptEdgeValue3 = acceptStep3 + splati(acceptCornerValue3); trivialAcceptMask &= __builtin_vp_mask_cmpi_sle(acceptEdgeValue3, splati(0)); if (tileSize == 4) { // End recursion fShader->fillMasked(left, top, trivialAcceptMask); return; } // Reduce tile size for sub blocks tileSize = tileSize / 4; // Process all trivially accepted blocks if (trivialAcceptMask != 0) { int index; int currentMask = trivialAcceptMask; while (currentMask) { index = __builtin_clz(currentMask) - 16; currentMask &= ~(0x8000 >> index); int blockLeft = left + tileSize * (index & 3); int blockTop = top + tileSize * (index >> 2); for (int y = 0; y < tileSize; y += 4) { for (int x = 0; x < tileSize; x += 4) fShader->fillMasked(blockLeft + x, blockTop + y, 0xffff); } } } // Compute reject masks rejectEdgeValue1 = rejectStep1 + splati(rejectCornerValue1); trivialRejectMask = __builtin_vp_mask_cmpi_sgt(rejectEdgeValue1, splati(0)); rejectEdgeValue2 = rejectStep2 + splati(rejectCornerValue2); trivialRejectMask |= __builtin_vp_mask_cmpi_sgt(rejectEdgeValue2, splati(0)); rejectEdgeValue3 = rejectStep3 + splati(rejectCornerValue3); trivialRejectMask |= __builtin_vp_mask_cmpi_sgt(rejectEdgeValue3, splati(0)); recurseMask = (trivialAcceptMask | trivialRejectMask) ^ 0xffff; if (recurseMask) { // Divide each step matrix by 4 acceptStep1 = acceptStep1 >> splati(2); acceptStep2 = acceptStep2 >> splati(2); acceptStep3 = acceptStep3 >> splati(2); rejectStep1 = rejectStep1 >> splati(2); rejectStep2 = rejectStep2 >> splati(2); rejectStep3 = rejectStep3 >> splati(2); // Recurse into blocks that are neither trivially rejected or accepted. // They are partially overlapped and need to be further subdivided. while (recurseMask) { index = __builtin_clz(recurseMask) - 16; recurseMask &= ~(0x8000 >> index); x = left + tileSize * (index & 3); y = top + tileSize * (index >> 2); subdivideTile( acceptEdgeValue1[index], acceptEdgeValue2[index], acceptEdgeValue3[index], rejectEdgeValue1[index], rejectEdgeValue2[index], rejectEdgeValue3[index], acceptStep1, acceptStep2, acceptStep3, rejectStep1, rejectStep2, rejectStep3, tileSize, x, y); } } } void Rasterizer::rasterizeTriangle(PixelShader *shader, int left, int top, int tileSize, int x1, int y1, int x2, int y2, int x3, int y3) { int acceptValue1; int rejectValue1; veci16 acceptStepMatrix1; veci16 rejectStepMatrix1; int acceptValue2; int rejectValue2; veci16 acceptStepMatrix2; veci16 rejectStepMatrix2; int acceptValue3; int rejectValue3; veci16 acceptStepMatrix3; veci16 rejectStepMatrix3; fShader = shader; setupEdge(left, top, tileSize, x1, y1, x2, y2, acceptValue1, rejectValue1, acceptStepMatrix1, rejectStepMatrix1); setupEdge(left, top, tileSize, x2, y2, x3, y3, acceptValue2, rejectValue2, acceptStepMatrix2, rejectStepMatrix2); setupEdge(left, top, tileSize, x3, y3, x1, y1, acceptValue3, rejectValue3, acceptStepMatrix3, rejectStepMatrix3); subdivideTile( acceptValue1, acceptValue2, acceptValue3, rejectValue1, rejectValue2, rejectValue3, acceptStepMatrix1, acceptStepMatrix2, acceptStepMatrix3, rejectStepMatrix1, rejectStepMatrix2, rejectStepMatrix3, tileSize, left, top); }
Make rasterizer obey top left fill convention.
Make rasterizer obey top left fill convention.
C++
apache-2.0
hoangt/NyuziProcessor,FulcronZ/NyuziProcessor,FulcronZ/NyuziProcessor,hoangt/NyuziProcessor,jbush001/NyuziProcessor,FulcronZ/NyuziProcessor,FulcronZ/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,hoangt/NyuziProcessor,hoangt/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor,jbush001/NyuziProcessor
e325ea87cc7bc486b67d1f06228b8e5d63d60cbc
source/adios2/toolkit/format/bp/BPSerializer.tcc
source/adios2/toolkit/format/bp/BPSerializer.tcc
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BPSerializer.tcc * * Created on: Sep 16, 2019 * Author: William F Godoy [email protected] */ #ifndef ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ #define ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ #include "BPSerializer.h" namespace adios2 { namespace format { template <class T> inline void BPSerializer::PutAttributeCharacteristicValueInIndex( uint8_t &characteristicsCounter, const core::Attribute<T> &attribute, std::vector<char> &buffer) noexcept { const uint8_t characteristicID = CharacteristicID::characteristic_value; helper::InsertToBuffer(buffer, &characteristicID); if (attribute.m_IsSingleValue) // single value { helper::InsertToBuffer(buffer, &attribute.m_DataSingleValue); } else // array { helper::InsertToBuffer(buffer, attribute.m_DataArray.data(), attribute.m_Elements); } ++characteristicsCounter; } template <class T> void BPSerializer::PutCharacteristicRecord(const uint8_t characteristicID, uint8_t &characteristicsCounter, const T &value, std::vector<char> &buffer) noexcept { const uint8_t id = characteristicID; helper::InsertToBuffer(buffer, &id); helper::InsertToBuffer(buffer, &value); ++characteristicsCounter; } template <class T> void BPSerializer::PutCharacteristicRecord(const uint8_t characteristicID, uint8_t &characteristicsCounter, const T &value, std::vector<char> &buffer, size_t &position) noexcept { const uint8_t id = characteristicID; helper::CopyToBuffer(buffer, position, &id); helper::CopyToBuffer(buffer, position, &value); ++characteristicsCounter; } template <class T> inline void BPSerializer::PutPayloadInBuffer( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo, const bool sourceRowMajor) noexcept { const size_t blockSize = helper::GetTotalSize(blockInfo.Count); m_Profiler.Start("memcpy"); #ifdef ADIOS2_HAVE_CUDA if (blockInfo.IsGPU) { helper::CopyFromGPUToBuffer(m_Data.m_Buffer, m_Data.m_Position, blockInfo.Data, blockSize); m_Profiler.Stop("memcpy"); m_Data.m_AbsolutePosition += blockSize * sizeof(T); return; } #endif if (!blockInfo.MemoryStart.empty()) { helper::CopyMemoryBlock( reinterpret_cast<T *>(m_Data.m_Buffer.data() + m_Data.m_Position), blockInfo.Start, blockInfo.Count, sourceRowMajor, blockInfo.Data, blockInfo.Start, blockInfo.Count, sourceRowMajor, false, Dims(), Dims(), blockInfo.MemoryStart, blockInfo.MemoryCount); m_Data.m_Position += blockSize * sizeof(T); } else { helper::CopyToBufferThreads(m_Data.m_Buffer, m_Data.m_Position, blockInfo.Data, blockSize, m_Parameters.Threads); } m_Profiler.Stop("memcpy"); m_Data.m_AbsolutePosition += blockSize * sizeof(T); // payload size } // PRIVATE template <class T> void BPSerializer::UpdateIndexOffsetsCharacteristics(size_t &currentPosition, const DataTypes dataType, std::vector<char> &buffer) { const bool isLittleEndian = helper::IsLittleEndian(); helper::ReadValue<uint8_t>(buffer, currentPosition, isLittleEndian); const uint32_t characteristicsLength = helper::ReadValue<uint32_t>(buffer, currentPosition, isLittleEndian); const size_t endPosition = currentPosition + static_cast<size_t>(characteristicsLength); size_t dimensionsSize = 0; // get it from dimensions characteristics while (currentPosition < endPosition) { const uint8_t id = helper::ReadValue<uint8_t>(buffer, currentPosition, isLittleEndian); switch (id) { case (characteristic_time_index): { currentPosition += sizeof(uint32_t); break; } case (characteristic_file_index): { currentPosition += sizeof(uint32_t); break; } case (characteristic_value): { if (dataType == type_string) { // first get the length of the string const size_t length = static_cast<size_t>( helper::ReadValue<uint16_t>(buffer, currentPosition, isLittleEndian)); currentPosition += length; } // using this function only for variables // TODO string array if string arrays are supported in the future else { currentPosition += sizeof(T); } break; } case (characteristic_min): { currentPosition += sizeof(T); break; } case (characteristic_max): { currentPosition += sizeof(T); break; } case (characteristic_minmax): { // first get the number of subblocks const uint16_t M = helper::ReadValue<uint16_t>(buffer, currentPosition); currentPosition += 2 * sizeof(T); // block min/max if (M > 1) { currentPosition += 1 + 8; // method (byte), blockSize (uint64_t) currentPosition += dimensionsSize * sizeof(uint16_t); // N-dim division currentPosition += 2 * M * sizeof(T); // M * min/max } break; } case (characteristic_offset): { const uint64_t currentOffset = helper::ReadValue<uint64_t>( buffer, currentPosition, isLittleEndian); const uint64_t updatedOffset = currentOffset + static_cast<uint64_t>(m_Data.m_AbsolutePosition); currentPosition -= sizeof(uint64_t); helper::CopyToBuffer(buffer, currentPosition, &updatedOffset); break; } case (characteristic_payload_offset): { const uint64_t currentPayloadOffset = helper::ReadValue<uint64_t>( buffer, currentPosition, isLittleEndian); const uint64_t updatedPayloadOffset = currentPayloadOffset + static_cast<uint64_t>(m_Data.m_AbsolutePosition); currentPosition -= sizeof(uint64_t); helper::CopyToBuffer(buffer, currentPosition, &updatedPayloadOffset); break; } case (characteristic_dimensions): { dimensionsSize = static_cast<size_t>(helper::ReadValue<uint8_t>( buffer, currentPosition, isLittleEndian)); currentPosition += 3 * sizeof(uint64_t) * dimensionsSize + 2; // 2 is for length break; } case (characteristic_transform_type): { const size_t typeLength = static_cast<size_t>(helper::ReadValue<uint8_t>( buffer, currentPosition, isLittleEndian)); // skip over operator name (transform type) string currentPosition += typeLength; // skip over pre-data type (1) and dimensionsSize (1) currentPosition += 2; const uint16_t dimensionsLength = helper::ReadValue<uint16_t>( buffer, currentPosition, isLittleEndian); // skip over dimensions currentPosition += dimensionsLength; const size_t metadataLength = static_cast<size_t>(helper::ReadValue<uint16_t>( buffer, currentPosition, isLittleEndian)); // skip over operator metadata currentPosition += metadataLength; break; } default: { throw std::invalid_argument( "ERROR: characteristic ID " + std::to_string(id) + " not supported when updating offsets\n"); } } // end id switch } // end while } template <class T> inline size_t BPSerializer::GetAttributeSizeInData(const core::Attribute<T> &attribute) const noexcept { size_t size = 14 + attribute.m_Name.size() + 10; size += 4 + sizeof(T) * attribute.m_Elements; return size; } template <class T> void BPSerializer::PutAttributeInData(const core::Attribute<T> &attribute, Stats<T> &stats) noexcept { DoPutAttributeInData(attribute, stats); } template <class T> void BPSerializer::PutAttributeInIndex(const core::Attribute<T> &attribute, const Stats<T> &stats) noexcept { SerialElementIndex index(stats.MemberID); auto &buffer = index.Buffer; // index.Valid = true; // when the attribute is put, set this flag to true size_t indexLengthPosition = buffer.size(); buffer.insert(buffer.end(), 4, '\0'); // skip attribute length (4) helper::InsertToBuffer(buffer, &stats.MemberID); buffer.insert(buffer.end(), 2, '\0'); // skip group name PutNameRecord(attribute.m_Name, buffer); buffer.insert(buffer.end(), 2, '\0'); // skip path uint8_t dataType = TypeTraits<T>::type_enum; // dataType if (dataType == type_string && !attribute.m_IsSingleValue) { dataType = type_string_array; } helper::InsertToBuffer(buffer, &dataType); // Characteristics Sets Count in Metadata index.Count = 1; helper::InsertToBuffer(buffer, &index.Count); // START OF CHARACTERISTICS const size_t characteristicsCountPosition = buffer.size(); // skip characteristics count(1) + length (4) buffer.insert(buffer.end(), 5, '\0'); uint8_t characteristicsCounter = 0; // DIMENSIONS PutCharacteristicRecord(characteristic_time_index, characteristicsCounter, stats.Step, buffer); PutCharacteristicRecord(characteristic_file_index, characteristicsCounter, stats.FileIndex, buffer); uint8_t characteristicID = characteristic_dimensions; helper::InsertToBuffer(buffer, &characteristicID); constexpr uint8_t dimensions = 1; helper::InsertToBuffer(buffer, &dimensions); // count constexpr uint16_t dimensionsLength = 24; helper::InsertToBuffer(buffer, &dimensionsLength); // length PutDimensionsRecord({attribute.m_Elements}, {}, {}, buffer); ++characteristicsCounter; // VALUE PutAttributeCharacteristicValueInIndex(characteristicsCounter, attribute, buffer); PutCharacteristicRecord(characteristic_offset, characteristicsCounter, stats.Offset, buffer); PutCharacteristicRecord(characteristic_payload_offset, characteristicsCounter, stats.PayloadOffset, buffer); // END OF CHARACTERISTICS // Back to characteristics count and length size_t backPosition = characteristicsCountPosition; helper::CopyToBuffer(buffer, backPosition, &characteristicsCounter); // count (1) // remove its own length (4) + characteristic counter (1) const uint32_t characteristicsLength = static_cast<uint32_t>( buffer.size() - characteristicsCountPosition - 4 - 1); helper::CopyToBuffer(buffer, backPosition, &characteristicsLength); // length // Remember this attribute and its serialized piece // should not affect BP3 as it's recalculated const uint32_t indexLength = static_cast<uint32_t>(buffer.size() - indexLengthPosition - 4); helper::CopyToBuffer(buffer, indexLengthPosition, &indexLength); m_MetadataSet.AttributesIndices.emplace(attribute.m_Name, index); m_SerializedAttributes.emplace(attribute.m_Name); } // operations related functions template <class T> void BPSerializer::PutCharacteristicOperation( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo, std::vector<char> &buffer) noexcept { auto &operation = blockInfo.Operations[0]; const std::string type = operation.Op->m_TypeString; const uint8_t typeLength = static_cast<uint8_t>(type.size()); helper::InsertToBuffer(buffer, &typeLength); helper::InsertToBuffer(buffer, type.c_str(), type.size()); // pre-transform type const uint8_t dataType = TypeTraits<T>::type_enum; helper::InsertToBuffer(buffer, &dataType); // pre-transform dimensions const uint8_t dimensions = static_cast<uint8_t>(blockInfo.Count.size()); helper::InsertToBuffer(buffer, &dimensions); // count const uint16_t dimensionsLength = static_cast<uint16_t>(24 * dimensions); helper::InsertToBuffer(buffer, &dimensionsLength); // length PutDimensionsRecord(blockInfo.Count, blockInfo.Shape, blockInfo.Start, buffer); // here put the metadata info depending on operation const uint64_t inputSize = static_cast<uint64_t>( helper::GetTotalSize(blockInfo.Count) * sizeof(T)); // being naughty here Params &info = const_cast<Params &>(operation.Info); info["InputSize"] = std::to_string(inputSize); // fixed size only stores inputSize 8-bytes and outputSize 8-bytes constexpr uint16_t metadataSize = 16; helper::InsertToBuffer(buffer, &metadataSize); helper::InsertToBuffer(buffer, &inputSize); info["OutputSizeMetadataPosition"] = std::to_string(buffer.size()); constexpr uint64_t outputSize = 0; helper::InsertToBuffer(buffer, &outputSize); } template <class T> void BPSerializer::PutOperationPayloadInBuffer( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo) { core::Operator &op = *blockInfo.Operations[0].Op; const Params &parameters = blockInfo.Operations[0].Parameters; // being naughty here Params &info = const_cast<Params &>(blockInfo.Operations[0].Info); const size_t outputSize = op.Operate(reinterpret_cast<char *>(blockInfo.Data), blockInfo.Start, blockInfo.Count, variable.m_Type, m_Data.m_Buffer.data() + m_Data.m_Position, parameters); info["OutputSize"] = std::to_string(outputSize); m_Data.m_Position += outputSize; m_Data.m_AbsolutePosition += outputSize; // update metadata bool isFound = false; SerialElementIndex &variableIndex = GetSerialElementIndex( variable.m_Name, m_MetadataSet.VarsIndices, isFound); size_t backPosition = static_cast<size_t>(std::stoll( blockInfo.Operations[0].Info.at("OutputSizeMetadataPosition"))); helper::CopyToBuffer(variableIndex.Buffer, backPosition, &outputSize); info.erase("OutputSizeMetadataPosition"); } } // end namespace format } // end namespace adios2 #endif /* ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ */
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * BPSerializer.tcc * * Created on: Sep 16, 2019 * Author: William F Godoy [email protected] */ #ifndef ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ #define ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ #include "BPSerializer.h" namespace adios2 { namespace format { template <class T> inline void BPSerializer::PutAttributeCharacteristicValueInIndex( uint8_t &characteristicsCounter, const core::Attribute<T> &attribute, std::vector<char> &buffer) noexcept { const uint8_t characteristicID = CharacteristicID::characteristic_value; helper::InsertToBuffer(buffer, &characteristicID); if (attribute.m_IsSingleValue) // single value { helper::InsertToBuffer(buffer, &attribute.m_DataSingleValue); } else // array { helper::InsertToBuffer(buffer, attribute.m_DataArray.data(), attribute.m_Elements); } ++characteristicsCounter; } template <class T> void BPSerializer::PutCharacteristicRecord(const uint8_t characteristicID, uint8_t &characteristicsCounter, const T &value, std::vector<char> &buffer) noexcept { const uint8_t id = characteristicID; helper::InsertToBuffer(buffer, &id); helper::InsertToBuffer(buffer, &value); ++characteristicsCounter; } template <class T> void BPSerializer::PutCharacteristicRecord(const uint8_t characteristicID, uint8_t &characteristicsCounter, const T &value, std::vector<char> &buffer, size_t &position) noexcept { const uint8_t id = characteristicID; helper::CopyToBuffer(buffer, position, &id); helper::CopyToBuffer(buffer, position, &value); ++characteristicsCounter; } template <class T> inline void BPSerializer::PutPayloadInBuffer( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo, const bool sourceRowMajor) noexcept { const size_t blockSize = helper::GetTotalSize(blockInfo.Count); m_Profiler.Start("memcpy"); #ifdef ADIOS2_HAVE_CUDA if (blockInfo.IsGPU) { helper::CopyFromGPUToBuffer(m_Data.m_Buffer, m_Data.m_Position, blockInfo.Data, blockSize); m_Profiler.Stop("memcpy"); m_Data.m_AbsolutePosition += blockSize * sizeof(T); return; } #endif if (!blockInfo.MemoryStart.empty()) { helper::CopyMemoryBlock( reinterpret_cast<T *>(m_Data.m_Buffer.data() + m_Data.m_Position), blockInfo.Start, blockInfo.Count, sourceRowMajor, blockInfo.Data, blockInfo.Start, blockInfo.Count, sourceRowMajor, false, Dims(), Dims(), blockInfo.MemoryStart, blockInfo.MemoryCount); m_Data.m_Position += blockSize * sizeof(T); } else { helper::CopyToBufferThreads(m_Data.m_Buffer, m_Data.m_Position, blockInfo.Data, blockSize, m_Parameters.Threads); } m_Profiler.Stop("memcpy"); m_Data.m_AbsolutePosition += blockSize * sizeof(T); // payload size } // PRIVATE template <class T> void BPSerializer::UpdateIndexOffsetsCharacteristics(size_t &currentPosition, const DataTypes dataType, std::vector<char> &buffer) { const bool isLittleEndian = helper::IsLittleEndian(); helper::ReadValue<uint8_t>(buffer, currentPosition, isLittleEndian); const uint32_t characteristicsLength = helper::ReadValue<uint32_t>(buffer, currentPosition, isLittleEndian); const size_t endPosition = currentPosition + static_cast<size_t>(characteristicsLength); size_t dimensionsSize = 0; // get it from dimensions characteristics while (currentPosition < endPosition) { const uint8_t id = helper::ReadValue<uint8_t>(buffer, currentPosition, isLittleEndian); switch (id) { case (characteristic_time_index): { currentPosition += sizeof(uint32_t); break; } case (characteristic_file_index): { currentPosition += sizeof(uint32_t); break; } case (characteristic_value): { if (dataType == type_string) { // first get the length of the string const size_t length = static_cast<size_t>( helper::ReadValue<uint16_t>(buffer, currentPosition, isLittleEndian)); currentPosition += length; } // using this function only for variables // TODO string array if string arrays are supported in the future else { currentPosition += sizeof(T); } break; } case (characteristic_min): { currentPosition += sizeof(T); break; } case (characteristic_max): { currentPosition += sizeof(T); break; } case (characteristic_minmax): { // first get the number of subblocks const uint16_t M = helper::ReadValue<uint16_t>(buffer, currentPosition); currentPosition += 2 * sizeof(T); // block min/max if (M > 1) { currentPosition += 1 + 8; // method (byte), blockSize (uint64_t) currentPosition += dimensionsSize * sizeof(uint16_t); // N-dim division currentPosition += 2 * M * sizeof(T); // M * min/max } break; } case (characteristic_offset): { const uint64_t currentOffset = helper::ReadValue<uint64_t>( buffer, currentPosition, isLittleEndian); const uint64_t updatedOffset = currentOffset + static_cast<uint64_t>(m_Data.m_AbsolutePosition); currentPosition -= sizeof(uint64_t); helper::CopyToBuffer(buffer, currentPosition, &updatedOffset); break; } case (characteristic_payload_offset): { const uint64_t currentPayloadOffset = helper::ReadValue<uint64_t>( buffer, currentPosition, isLittleEndian); const uint64_t updatedPayloadOffset = currentPayloadOffset + static_cast<uint64_t>(m_Data.m_AbsolutePosition); currentPosition -= sizeof(uint64_t); helper::CopyToBuffer(buffer, currentPosition, &updatedPayloadOffset); break; } case (characteristic_dimensions): { dimensionsSize = static_cast<size_t>(helper::ReadValue<uint8_t>( buffer, currentPosition, isLittleEndian)); currentPosition += 3 * sizeof(uint64_t) * dimensionsSize + 2; // 2 is for length break; } case (characteristic_transform_type): { const size_t typeLength = static_cast<size_t>(helper::ReadValue<uint8_t>( buffer, currentPosition, isLittleEndian)); // skip over operator name (transform type) string currentPosition += typeLength; // skip over pre-data type (1) and dimensionsSize (1) currentPosition += 2; const uint16_t dimensionsLength = helper::ReadValue<uint16_t>( buffer, currentPosition, isLittleEndian); // skip over dimensions currentPosition += dimensionsLength; const size_t metadataLength = static_cast<size_t>(helper::ReadValue<uint16_t>( buffer, currentPosition, isLittleEndian)); // skip over operator metadata currentPosition += metadataLength; break; } default: { throw std::invalid_argument( "ERROR: characteristic ID " + std::to_string(id) + " not supported when updating offsets\n"); } } // end id switch } // end while } template <class T> inline size_t BPSerializer::GetAttributeSizeInData(const core::Attribute<T> &attribute) const noexcept { size_t size = 14 + attribute.m_Name.size() + 10; size += 4 + sizeof(T) * attribute.m_Elements; return size; } template <class T> void BPSerializer::PutAttributeInData(const core::Attribute<T> &attribute, Stats<T> &stats) noexcept { DoPutAttributeInData(attribute, stats); } template <class T> void BPSerializer::PutAttributeInIndex(const core::Attribute<T> &attribute, const Stats<T> &stats) noexcept { SerialElementIndex index(stats.MemberID); auto &buffer = index.Buffer; // index.Valid = true; // when the attribute is put, set this flag to true size_t indexLengthPosition = buffer.size(); buffer.insert(buffer.end(), 4, '\0'); // skip attribute length (4) helper::InsertToBuffer(buffer, &stats.MemberID); buffer.insert(buffer.end(), 2, '\0'); // skip group name PutNameRecord(attribute.m_Name, buffer); buffer.insert(buffer.end(), 2, '\0'); // skip path uint8_t dataType = TypeTraits<T>::type_enum; // dataType if (dataType == type_string && !attribute.m_IsSingleValue) { dataType = type_string_array; } helper::InsertToBuffer(buffer, &dataType); // Characteristics Sets Count in Metadata index.Count = 1; helper::InsertToBuffer(buffer, &index.Count); // START OF CHARACTERISTICS const size_t characteristicsCountPosition = buffer.size(); // skip characteristics count(1) + length (4) buffer.insert(buffer.end(), 5, '\0'); uint8_t characteristicsCounter = 0; // DIMENSIONS PutCharacteristicRecord(characteristic_time_index, characteristicsCounter, stats.Step, buffer); PutCharacteristicRecord(characteristic_file_index, characteristicsCounter, stats.FileIndex, buffer); uint8_t characteristicID = characteristic_dimensions; helper::InsertToBuffer(buffer, &characteristicID); constexpr uint8_t dimensions = 1; helper::InsertToBuffer(buffer, &dimensions); // count constexpr uint16_t dimensionsLength = 24; helper::InsertToBuffer(buffer, &dimensionsLength); // length PutDimensionsRecord({attribute.m_Elements}, {}, {}, buffer); ++characteristicsCounter; // VALUE PutAttributeCharacteristicValueInIndex(characteristicsCounter, attribute, buffer); PutCharacteristicRecord(characteristic_offset, characteristicsCounter, stats.Offset, buffer); PutCharacteristicRecord(characteristic_payload_offset, characteristicsCounter, stats.PayloadOffset, buffer); // END OF CHARACTERISTICS // Back to characteristics count and length size_t backPosition = characteristicsCountPosition; helper::CopyToBuffer(buffer, backPosition, &characteristicsCounter); // count (1) // remove its own length (4) + characteristic counter (1) const uint32_t characteristicsLength = static_cast<uint32_t>( buffer.size() - characteristicsCountPosition - 4 - 1); helper::CopyToBuffer(buffer, backPosition, &characteristicsLength); // length // Remember this attribute and its serialized piece // should not affect BP3 as it's recalculated const uint32_t indexLength = static_cast<uint32_t>(buffer.size() - indexLengthPosition - 4); helper::CopyToBuffer(buffer, indexLengthPosition, &indexLength); m_MetadataSet.AttributesIndices.emplace(attribute.m_Name, index); m_SerializedAttributes.emplace(attribute.m_Name); } // operations related functions template <class T> void BPSerializer::PutCharacteristicOperation( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo, std::vector<char> &buffer) noexcept { const std::string type = blockInfo.Operations[0].Op->m_TypeString; const uint8_t typeLength = static_cast<uint8_t>(type.size()); helper::InsertToBuffer(buffer, &typeLength); helper::InsertToBuffer(buffer, type.c_str(), type.size()); // pre-transform type const uint8_t dataType = TypeTraits<T>::type_enum; helper::InsertToBuffer(buffer, &dataType); // pre-transform dimensions const uint8_t dimensions = static_cast<uint8_t>(blockInfo.Count.size()); helper::InsertToBuffer(buffer, &dimensions); // count const uint16_t dimensionsLength = static_cast<uint16_t>(24 * dimensions); helper::InsertToBuffer(buffer, &dimensionsLength); // length PutDimensionsRecord(blockInfo.Count, blockInfo.Shape, blockInfo.Start, buffer); // here put the metadata info depending on operation const uint64_t inputSize = static_cast<uint64_t>( helper::GetTotalSize(blockInfo.Count) * sizeof(T)); // being naughty here Params &info = const_cast<Params &>(blockInfo.Operations[0].Info); info["InputSize"] = std::to_string(inputSize); // fixed size only stores inputSize 8-bytes and outputSize 8-bytes constexpr uint16_t metadataSize = 16; helper::InsertToBuffer(buffer, &metadataSize); helper::InsertToBuffer(buffer, &inputSize); info["OutputSizeMetadataPosition"] = std::to_string(buffer.size()); constexpr uint64_t outputSize = 0; helper::InsertToBuffer(buffer, &outputSize); } template <class T> void BPSerializer::PutOperationPayloadInBuffer( const core::Variable<T> &variable, const typename core::Variable<T>::BPInfo &blockInfo) { const Params &parameters = blockInfo.Operations[0].Parameters; // being naughty here Params &info = const_cast<Params &>(blockInfo.Operations[0].Info); const size_t outputSize = blockInfo.Operations[0].Op->Operate( reinterpret_cast<char *>(blockInfo.Data), blockInfo.Start, blockInfo.Count, variable.m_Type, m_Data.m_Buffer.data() + m_Data.m_Position, parameters); info["OutputSize"] = std::to_string(outputSize); m_Data.m_Position += outputSize; m_Data.m_AbsolutePosition += outputSize; // update metadata bool isFound = false; SerialElementIndex &variableIndex = GetSerialElementIndex( variable.m_Name, m_MetadataSet.VarsIndices, isFound); size_t backPosition = static_cast<size_t>(std::stoll( blockInfo.Operations[0].Info.at("OutputSizeMetadataPosition"))); helper::CopyToBuffer(variableIndex.Buffer, backPosition, &outputSize); info.erase("OutputSizeMetadataPosition"); } } // end namespace format } // end namespace adios2 #endif /* ADIOS2_TOOLKIT_FORMAT_BP_BPSERIALIZER_TCC_ */
clean up
clean up
C++
apache-2.0
ornladios/ADIOS2,ornladios/ADIOS2,JasonRuonanWang/ADIOS2,JasonRuonanWang/ADIOS2,ornladios/ADIOS2,JasonRuonanWang/ADIOS2,ornladios/ADIOS2,JasonRuonanWang/ADIOS2,JasonRuonanWang/ADIOS2,ornladios/ADIOS2
983d8d2ca250c2c613848fa60b145a2abc3ff0c1
source/core/search-manager/FuzzySearchRanker.cpp
source/core/search-manager/FuzzySearchRanker.cpp
#include "FuzzySearchRanker.h" #include "SearchManagerPreProcessor.h" #include "CustomRanker.h" #include "Sorter.h" #include "HitQueue.h" #include <configuration-manager/ProductRankingConfig.h> #include <query-manager/SearchKeywordOperation.h> #include <query-manager/ActionItem.h> #include <common/PropSharedLockSet.h> #include <mining-manager/product-scorer/ProductScorer.h> #include "mining-manager/custom-rank-manager/CustomRankManager.h" #include <algorithm> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <iostream> using namespace sf1r; FuzzySearchRanker::FuzzySearchRanker(SearchManagerPreProcessor& preprocessor) : preprocessor_(preprocessor) , fuzzyScoreWeight_(0) , isCategoryClassify_(false) , customRankManager_(NULL) { } void FuzzySearchRanker::setFuzzyScoreWeight(const ProductRankingConfig& rankConfig) { const ProductScoreConfig& fuzzyConfig = rankConfig.scores[FUZZY_SCORE]; fuzzyScoreWeight_ = fuzzyConfig.weight; } void FuzzySearchRanker::rankByProductScore( const KeywordSearchActionItem& actionItem, std::vector<ScoreDocId>& resultList, bool isCompare) { PropSharedLockSet propSharedLockSet; boost::scoped_ptr<ProductScorer> productScorer( preprocessor_.createProductScorer(actionItem, propSharedLockSet, NULL)); if (!productScorer) return; std::set<docid_t> excludeDocIds; getExcludeDocIds_(actionItem.env_.normalizedQueryString_, excludeDocIds); const std::size_t count = resultList.size(); std::size_t current = 0; for (std::size_t i = 0; i < count; ++i) { docid_t docId = resultList[i].second; // ignore the exclude docids if (excludeDocIds.find(docId) != excludeDocIds.end()) continue; double fuzzyScore = resultList[i].first; double productScore = productScorer->score(docId); if (isCategoryClassify_) { // ignore the docs with zero category score if (isCompare) { if (productScore < 0.9) continue; } else { if (productScore < 0.00009) productScore = -1; } fuzzyScore = static_cast<int>(fuzzyScore * fuzzyScoreWeight_); } resultList[i].first = fuzzyScore + productScore; //cout << "fuzzyScore:" << fuzzyScore << " productScore" << productScore<< endl; resultList[current++] = resultList[i]; } resultList.resize(current); std::sort(resultList.begin(), resultList.end(), std::greater<ScoreDocId>()); if (resultList.size() > 0) { unsigned int topPrintDocNum = 5; std::cout << "The top fuzzyScore is:" << std::endl; for (unsigned int i = 0; i < topPrintDocNum && i < resultList.size(); ++i) { std::cout << resultList[i].first << std::endl; } } if (current == count) { LOG(INFO) << "rank by product score, topk count not changed: " << count; } else { LOG(INFO) << "rank by product score, topk count changed from " << count << " to " << current; } } void FuzzySearchRanker::getExcludeDocIds_(const std::string& query, std::set<docid_t>& excludeDocIds) { if (customRankManager_ == NULL) return; CustomRankDocId customDocId; if (customRankManager_->getCustomValue(query, customDocId)) { excludeDocIds.insert(customDocId.excludeIds.begin(), customDocId.excludeIds.end()); } } void FuzzySearchRanker::rankByPropValue( const SearchKeywordOperation& actionOperation, uint32_t start, std::vector<uint32_t>& docid_list, std::vector<float>& result_score_list, std::vector<float>& custom_score_list) { if (docid_list.size() <= start) return; CustomRankerPtr customRanker; boost::shared_ptr<Sorter> pSorter; try { preprocessor_.prepareSorterCustomRanker(actionOperation, pSorter, customRanker); } catch (std::exception& e) { return; } if (!customRanker && preprocessor_.isSortByRankProp(actionOperation.actionItem_.sortPriorityList_)) { LOG(INFO) << "no need to resort, sorting by original fuzzy match order."; return; } const std::size_t count = docid_list.size(); PropSharedLockSet propSharedLockSet; boost::scoped_ptr<HitQueue> scoreItemQueue; if (pSorter) { ///sortby scoreItemQueue.reset(new PropertySortedHitQueue(pSorter, count, propSharedLockSet)); } else { scoreItemQueue.reset(new ScoreSortedHitQueue(count)); } ScoreDoc tmpdoc; for (size_t i = 0; i < count; ++i) { tmpdoc.docId = docid_list[i]; tmpdoc.score = result_score_list[i]; if (customRanker) { tmpdoc.custom_score = customRanker->evaluate(tmpdoc.docId); } scoreItemQueue->insert(tmpdoc); //cout << "doc : " << tmpdoc.docId << ", score is:" << tmpdoc.score << "," << tmpdoc.custom_score << endl; } const std::size_t need_count = scoreItemQueue->size() - start; docid_list.resize(need_count); result_score_list.resize(need_count); if (customRanker) { custom_score_list.resize(need_count); } for (size_t i = 0; i < need_count; ++i) { const ScoreDoc& pScoreItem = scoreItemQueue->pop(); docid_list[need_count - i - 1] = pScoreItem.docId; result_score_list[need_count - i - 1] = pScoreItem.score; if (customRanker) { custom_score_list[need_count - i - 1] = pScoreItem.custom_score; } } }
#include "FuzzySearchRanker.h" #include "SearchManagerPreProcessor.h" #include "CustomRanker.h" #include "Sorter.h" #include "HitQueue.h" #include <configuration-manager/ProductRankingConfig.h> #include <query-manager/SearchKeywordOperation.h> #include <query-manager/ActionItem.h> #include <common/PropSharedLockSet.h> #include <mining-manager/product-scorer/ProductScorer.h> #include "mining-manager/custom-rank-manager/CustomRankManager.h" #include "mining-manager/product-scorer/CategoryClassifyScorer.h" #include <algorithm> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <iostream> using namespace sf1r; FuzzySearchRanker::FuzzySearchRanker(SearchManagerPreProcessor& preprocessor) : preprocessor_(preprocessor) , fuzzyScoreWeight_(0) , isCategoryClassify_(false) , customRankManager_(NULL) { } void FuzzySearchRanker::setFuzzyScoreWeight(const ProductRankingConfig& rankConfig) { const ProductScoreConfig& fuzzyConfig = rankConfig.scores[FUZZY_SCORE]; fuzzyScoreWeight_ = fuzzyConfig.weight; } void FuzzySearchRanker::rankByProductScore( const KeywordSearchActionItem& actionItem, std::vector<ScoreDocId>& resultList, bool isCompare) { PropSharedLockSet propSharedLockSet; boost::scoped_ptr<ProductScorer> productScorer( preprocessor_.createProductScorer(actionItem, propSharedLockSet, NULL)); if (!productScorer) return; std::set<docid_t> excludeDocIds; getExcludeDocIds_(actionItem.env_.normalizedQueryString_, excludeDocIds); const std::size_t count = resultList.size(); std::size_t current = 0; for (std::size_t i = 0; i < count; ++i) { docid_t docId = resultList[i].second; // ignore the exclude docids if (excludeDocIds.find(docId) != excludeDocIds.end()) continue; double fuzzyScore = resultList[i].first; double productScore = productScorer->score(docId); if (isCategoryClassify_) { // ignore the docs with zero category score if (productScore < CategoryClassifyScorer::kMinClassifyScore || (isCompare && productScore < 0.9)) { continue; } fuzzyScore = static_cast<int>(fuzzyScore * fuzzyScoreWeight_); } resultList[i].first = fuzzyScore + productScore; //cout << "fuzzyScore:" << fuzzyScore << " productScore" << productScore<< endl; resultList[current++] = resultList[i]; } resultList.resize(current); std::sort(resultList.begin(), resultList.end(), std::greater<ScoreDocId>()); if (resultList.size() > 0) { unsigned int topPrintDocNum = 5; std::cout << "The top fuzzyScore is:" << std::endl; for (unsigned int i = 0; i < topPrintDocNum && i < resultList.size(); ++i) { std::cout << resultList[i].first << std::endl; } } if (current == count) { LOG(INFO) << "rank by product score, topk count not changed: " << count; } else { LOG(INFO) << "rank by product score, topk count changed from " << count << " to " << current; } } void FuzzySearchRanker::getExcludeDocIds_(const std::string& query, std::set<docid_t>& excludeDocIds) { if (customRankManager_ == NULL) return; CustomRankDocId customDocId; if (customRankManager_->getCustomValue(query, customDocId)) { excludeDocIds.insert(customDocId.excludeIds.begin(), customDocId.excludeIds.end()); } } void FuzzySearchRanker::rankByPropValue( const SearchKeywordOperation& actionOperation, uint32_t start, std::vector<uint32_t>& docid_list, std::vector<float>& result_score_list, std::vector<float>& custom_score_list) { if (docid_list.size() <= start) return; CustomRankerPtr customRanker; boost::shared_ptr<Sorter> pSorter; try { preprocessor_.prepareSorterCustomRanker(actionOperation, pSorter, customRanker); } catch (std::exception& e) { return; } if (!customRanker && preprocessor_.isSortByRankProp(actionOperation.actionItem_.sortPriorityList_)) { LOG(INFO) << "no need to resort, sorting by original fuzzy match order."; return; } const std::size_t count = docid_list.size(); PropSharedLockSet propSharedLockSet; boost::scoped_ptr<HitQueue> scoreItemQueue; if (pSorter) { ///sortby scoreItemQueue.reset(new PropertySortedHitQueue(pSorter, count, propSharedLockSet)); } else { scoreItemQueue.reset(new ScoreSortedHitQueue(count)); } ScoreDoc tmpdoc; for (size_t i = 0; i < count; ++i) { tmpdoc.docId = docid_list[i]; tmpdoc.score = result_score_list[i]; if (customRanker) { tmpdoc.custom_score = customRanker->evaluate(tmpdoc.docId); } scoreItemQueue->insert(tmpdoc); //cout << "doc : " << tmpdoc.docId << ", score is:" << tmpdoc.score << "," << tmpdoc.custom_score << endl; } const std::size_t need_count = scoreItemQueue->size() - start; docid_list.resize(need_count); result_score_list.resize(need_count); if (customRanker) { custom_score_list.resize(need_count); } for (size_t i = 0; i < need_count; ++i) { const ScoreDoc& pScoreItem = scoreItemQueue->pop(); docid_list[need_count - i - 1] = pScoreItem.docId; result_score_list[need_count - i - 1] = pScoreItem.score; if (customRanker) { custom_score_list[need_count - i - 1] = pScoreItem.custom_score; } } }
Revise fuzzy search prune logic.
Revise fuzzy search prune logic. In fuzzy search result, if its category score is zero, it would be pruned.
C++
apache-2.0
pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-ad-delivery,pombredanne/sf1r-lite,izenecloud/sf1r-lite,pombredanne/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite,izenecloud/sf1r-lite,izenecloud/sf1r-ad-delivery,izenecloud/sf1r-lite
5305e8ff0ce2e36b79fb95b45dba3632bb30d296
vika1/main.cpp
vika1/main.cpp
#include <iostream> #include "toplayer.h" using namespace std; int main() { toplayer ui; ui.run(); //hallo return 0; } //Pétur Push3
#include <iostream> #include "toplayer.h" using namespace std; int main() { toplayer ui; ui.run(); //hallo return 0; } //Pétur Push3 //Pétur Pull
Update main.cpp
Update main.cpp
C++
mit
Tyrath/T113-VLN
12229e4826ae5f90b64e08f23fc7d952d1ce4433
vvp/functor.cc
vvp/functor.cc
/* * Copyright (c) 2001 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: functor.cc,v 1.14 2001/04/26 15:52:22 steve Exp $" #endif # include "functor.h" # include "udp.h" # include "schedule.h" # include "vthread.h" # include <assert.h> /* * Functors are created as the source design is read in. Each is * assigned an ipoint_t address starting from 1. The design is * expected to have a create many functors, so it makes sense to * allocate the functors in chunks. This structure describes a chunk * of functors. * * The 32bit vvp_ipoint_t allows for 2**30 functors in the * design. (2 bits are used to select the input of the functor.) The * functor address is, for the purpose of lookup up addresses, divided * into three parts, the index within a chunk, the index of the chunk * within an index1 table, and the index of the index1 within the root * table. There is a single root table. The index1 tables and chunk * tables are allocated as needed. */ const unsigned functor_index0_size = 2 << 9; const unsigned functor_index1_size = 2 << 11; const unsigned functor_index2_size = 2 << 10; struct functor_index0 { struct functor_s table[functor_index0_size]; }; struct functor_index1 { struct functor_index0* table[functor_index1_size]; }; static vvp_ipoint_t functor_count = 0; static struct functor_index1*functor_table[functor_index2_size] = { 0 }; /* * This function initializes the functor address space by creating the * zero functor. This means creating a functor_index1 and a * functor_index0, and initializing the count to 1. */ void functor_init(void) { functor_table[0] = new struct functor_index1; functor_table[0]->table[0] = new struct functor_index0; functor_count = 1; } /* * Allocate normally is just a matter of incrementing the functor_count * and returning a pointer to the next unallocated functor. However, * if we overrun a chunk or an index, we need to allocate the needed * bits first. */ static vvp_ipoint_t functor_allocate_(void) { vvp_ipoint_t idx = functor_count; idx /= functor_index0_size; unsigned index1 = idx % functor_index1_size; idx /= functor_index1_size; assert( idx < functor_index2_size); if (functor_table[idx] == 0) functor_table[idx] = new struct functor_index1; if (functor_table[idx]->table[index1] == 0) functor_table[idx]->table[index1] = new struct functor_index0; vvp_ipoint_t res = functor_count; functor_count += 1; return res * 4; } vvp_ipoint_t functor_allocate(unsigned wid) { assert(wid > 0); vvp_ipoint_t res = functor_allocate_(); wid -= 1; while (wid > 0) { functor_allocate_(); wid -= 1; } return res; } /* * Given a vvp_ipoint_t pointer, return a pointer to the detailed * functor structure. This does not use the low 2 bits, which address * a specific port of the functor. */ functor_t functor_index(vvp_ipoint_t point) { point /= 4; assert(point < functor_count); assert(point > 0); unsigned index0 = point % functor_index0_size; point /= functor_index0_size; unsigned index1 = point % functor_index1_size; point /= functor_index1_size; return functor_table[point]->table[index1]->table + index0; } static void functor_set_mode0(vvp_ipoint_t ptr, functor_t fp, bool push) { /* Locate the new output value in the table. */ unsigned char out = fp->table[fp->ival >> 2]; out >>= 2 * (fp->ival&0x03); out &= 0x03; /* If the output changes, then create a propagation event. */ if (out != fp->oval) { fp->oval = out; if (push) functor_propagate(ptr); else schedule_functor(ptr, 0); } } const unsigned char vvp_edge_posedge[16] = { 0, 1, 1, 1, // 0 -> ... 0, 0, 0, 0, // 1 -> ... 0, 1, 0, 0, // x -> ... 0, 1, 0, 0 // z -> ... }; const unsigned char vvp_edge_negedge[16] = { 0, 0, 0, 0, // 0 -> ... 1, 0, 1, 1, // 1 -> ... 1, 0, 0, 0, // x -> ... 1, 0, 0, 0 // z -> ... }; const unsigned char vvp_edge_anyedge[16] = { 0, 1, 1, 1, // 0 -> ... 1, 0, 1, 1, // 1 -> ... 1, 1, 0, 1, // x -> ... 1, 1, 1, 0 // z -> ... }; static void functor_set_mode1(functor_t fp) { vvp_event_t ep = fp->event; for (unsigned idx = 0 ; ep->threads && (idx < 4) ; idx += 1) { unsigned oval = (ep->ival >> 2*idx) & 3; unsigned nval = (fp->ival >> 2*idx) & 3; unsigned val = (oval << 2) | nval; unsigned char edge_p = ep->vvp_edge_tab[val]; if (edge_p) { vthread_t tmp = ep->threads; ep->threads = 0; vthread_schedule_list(tmp); } } /* the new value is the new old value. */ ep->ival = fp->ival; if (fp->out) schedule_assign(fp->out, 0, 0); } /* * A mode-2 functor is a named event. In this case, any set at all is * enough to trigger the blocked threads. */ static void functor_set_mode2(functor_t fp) { vvp_event_t ep = fp->event; if (ep->threads) { vthread_t tmp = ep->threads; ep->threads = 0; vthread_schedule_list(tmp); } if (fp->out) schedule_assign(fp->out, 0, 0); } /* * Set the addressed bit of the functor, and recalculate the * output. If the output changes any, then generate the necessary * propagation events to pass the output on. */ void functor_set(vvp_ipoint_t ptr, unsigned bit, bool push) { functor_t fp = functor_index(ptr); unsigned pp = ipoint_port(ptr); assert(fp); // assert(fp->table); /* Change the bits of the input. */ static const unsigned char mask_table[4] = { 0xfc, 0xf3, 0xcf, 0x3f }; unsigned char mask = mask_table[pp]; fp->ival = (fp->ival & mask) | (bit << (2*pp)); switch (fp->mode) { case 0: functor_set_mode0(ptr, fp, push); break; case 1: functor_set_mode1(fp); break; case 2: functor_set_mode2(fp); break; case M42: if (!fp->obj) { ptr = fp->out; fp = functor_index(ptr); } fp->obj->set(ptr, fp, push); break; } } unsigned functor_get(vvp_ipoint_t ptr) { functor_t fp = functor_index(ptr); assert(fp); if (fp->mode == M42 && fp->obj && fp->obj->get) return fp->obj->get(ptr, fp); return fp->oval & 3; } /* * This function is used by the scheduler to implement the propagation * event. The input is the pointer to the functor who's output is to * be propagated. Pass the output to the inputs of all the connected * functors. */ void functor_propagate(vvp_ipoint_t ptr) { functor_t fp = functor_index(ptr); unsigned char oval = fp->oval; vvp_ipoint_t idx = fp->out; while (idx) { functor_t idxp = functor_index(idx); vvp_ipoint_t next = idxp->port[ipoint_port(idx)]; functor_set(idx, oval); idx = next; } } void functor_dump(FILE*fd) { for (unsigned idx = 1 ; idx < functor_count ; idx += 1) { functor_t cur = functor_index(idx*4); fprintf(fd, "%08x: out=%x port={%x %x %x %x}\n", (idx*4), cur->out, cur->port[0], cur->port[1], cur->port[2], cur->port[3]); } } /* * The variable functor is special. This is the truth table for it. */ const unsigned char ft_var[16] = { 0xe4, /* 0 0: 11, 10, 01, 00 */ 0xe4, /* 0 1: 11, 10, 01, 00 */ 0xe4, /* 0 x: 11, 10, 01, 00 */ 0xe4, /* 0 z: 11, 10, 01, 00 */ 0x00, /* 1 0: 00, 00, 00, 00 */ 0x55, /* 1 1: 01, 01, 01, 01 */ 0xaa, /* 1 x: 10, 10, 10, 10 */ 0xff, /* 1 z: 11, 11, 11, 11 */ 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4 }; /* * $Log: functor.cc,v $ * Revision 1.14 2001/04/26 15:52:22 steve * Add the mode-42 functor concept to UDPs. * * Revision 1.13 2001/04/24 02:23:59 steve * Support for UDP devices in VVP (Stephen Boettcher) * * Revision 1.12 2001/04/18 04:21:23 steve * Put threads into scopes. * * Revision 1.11 2001/04/14 05:10:56 steve * support the .event/or statement. * * Revision 1.10 2001/04/03 03:18:34 steve * support functor_set push for blocking assignment. * * Revision 1.9 2001/03/31 19:29:23 steve * Fix compilation warnings. * * Revision 1.8 2001/03/29 03:46:36 steve * Support named events as mode 2 functors. * * Revision 1.7 2001/03/26 04:00:39 steve * Add the .event statement and the %wait instruction. * * Revision 1.6 2001/03/25 00:35:35 steve * Add the .net statement. * * Revision 1.5 2001/03/22 05:28:16 steve * no longer need out message. * * Revision 1.4 2001/03/22 05:08:00 steve * implement %load, %inv, %jum/0 and %cmp/u * * Revision 1.3 2001/03/20 06:16:24 steve * Add support for variable vectors. * * Revision 1.2 2001/03/11 22:42:11 steve * Functor values and propagation. * * Revision 1.1 2001/03/11 00:29:38 steve * Add the vvp engine to cvs. * */
/* * Copyright (c) 2001 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: functor.cc,v 1.15 2001/05/03 04:54:33 steve Exp $" #endif # include "functor.h" # include "udp.h" # include "schedule.h" # include "vthread.h" # include <assert.h> /* * Functors are created as the source design is read in. Each is * assigned an ipoint_t address starting from 1. The design is * expected to have a create many functors, so it makes sense to * allocate the functors in chunks. This structure describes a chunk * of functors. * * The 32bit vvp_ipoint_t allows for 2**30 functors in the * design. (2 bits are used to select the input of the functor.) The * functor address is, for the purpose of lookup up addresses, divided * into three parts, the index within a chunk, the index of the chunk * within an index1 table, and the index of the index1 within the root * table. There is a single root table. The index1 tables and chunk * tables are allocated as needed. */ const unsigned functor_index0_size = 2 << 9; const unsigned functor_index1_size = 2 << 11; const unsigned functor_index2_size = 2 << 10; struct functor_index0 { struct functor_s table[functor_index0_size]; }; struct functor_index1 { struct functor_index0* table[functor_index1_size]; }; static vvp_ipoint_t functor_count = 0; static struct functor_index1*functor_table[functor_index2_size] = { 0 }; /* * This function initializes the functor address space by creating the * zero functor. This means creating a functor_index1 and a * functor_index0, and initializing the count to 1. */ void functor_init(void) { functor_table[0] = new struct functor_index1; functor_table[0]->table[0] = new struct functor_index0; functor_count = 1; } /* * Allocate normally is just a matter of incrementing the functor_count * and returning a pointer to the next unallocated functor. However, * if we overrun a chunk or an index, we need to allocate the needed * bits first. */ static vvp_ipoint_t functor_allocate_(void) { vvp_ipoint_t idx = functor_count; idx /= functor_index0_size; unsigned index1 = idx % functor_index1_size; idx /= functor_index1_size; assert( idx < functor_index2_size); if (functor_table[idx] == 0) functor_table[idx] = new struct functor_index1; if (functor_table[idx]->table[index1] == 0) functor_table[idx]->table[index1] = new struct functor_index0; vvp_ipoint_t res = functor_count; functor_count += 1; return res * 4; } vvp_ipoint_t functor_allocate(unsigned wid) { assert(wid > 0); vvp_ipoint_t res = functor_allocate_(); wid -= 1; while (wid > 0) { functor_allocate_(); wid -= 1; } return res; } /* * Given a vvp_ipoint_t pointer, return a pointer to the detailed * functor structure. This does not use the low 2 bits, which address * a specific port of the functor. */ functor_t functor_index(vvp_ipoint_t point) { point /= 4; assert(point < functor_count); assert(point > 0); unsigned index0 = point % functor_index0_size; point /= functor_index0_size; unsigned index1 = point % functor_index1_size; point /= functor_index1_size; return functor_table[point]->table[index1]->table + index0; } static void functor_set_mode0(vvp_ipoint_t ptr, functor_t fp, bool push) { /* Locate the new output value in the table. */ unsigned char out = fp->table[fp->ival >> 2]; out >>= 2 * (fp->ival&0x03); out &= 0x03; /* If the output changes, then create a propagation event. */ if (out != fp->oval) { fp->oval = out; if (push) functor_propagate(ptr); else schedule_functor(ptr, 0); } } const unsigned char vvp_edge_posedge[16] = { 0, 1, 1, 1, // 0 -> ... 0, 0, 0, 0, // 1 -> ... 0, 1, 0, 0, // x -> ... 0, 1, 0, 0 // z -> ... }; const unsigned char vvp_edge_negedge[16] = { 0, 0, 0, 0, // 0 -> ... 1, 0, 1, 1, // 1 -> ... 1, 0, 0, 0, // x -> ... 1, 0, 0, 0 // z -> ... }; const unsigned char vvp_edge_anyedge[16] = { 0, 1, 1, 1, // 0 -> ... 1, 0, 1, 1, // 1 -> ... 1, 1, 0, 1, // x -> ... 1, 1, 1, 0 // z -> ... }; /* * A mode1 functor is a probe of some sort that is looking for an edge * of some specified type on any of its inputs. If it finds the right * kind of edge, then it awakens all the threads that are waiting on * this functor *and* it schedules an assign for any output it might * have. The latter is to support wider event/or then a single functor * can support. */ static void functor_set_mode1(functor_t fp) { vvp_event_t ep = fp->event; /* Only go through the effort if there is someone interested in the results... */ if (ep->threads || fp->out) { for (unsigned idx = 0 ; idx < 4 ; idx += 1) { unsigned oval = (ep->ival >> 2*idx) & 3; unsigned nval = (fp->ival >> 2*idx) & 3; unsigned val = (oval << 2) | nval; unsigned char edge_p = ep->vvp_edge_tab[val]; if (edge_p) { vthread_t tmp = ep->threads; ep->threads = 0; vthread_schedule_list(tmp); if (fp->out) schedule_assign(fp->out, 0, 0); } } } /* the new value is the new old value. */ ep->ival = fp->ival; } /* * A mode-2 functor is a named event. In this case, any set at all is * enough to trigger the blocked threads. */ static void functor_set_mode2(functor_t fp) { vvp_event_t ep = fp->event; if (ep->threads) { vthread_t tmp = ep->threads; ep->threads = 0; vthread_schedule_list(tmp); } if (fp->out) schedule_assign(fp->out, 0, 0); } /* * Set the addressed bit of the functor, and recalculate the * output. If the output changes any, then generate the necessary * propagation events to pass the output on. */ void functor_set(vvp_ipoint_t ptr, unsigned bit, bool push) { functor_t fp = functor_index(ptr); unsigned pp = ipoint_port(ptr); assert(fp); // assert(fp->table); /* Change the bits of the input. */ static const unsigned char mask_table[4] = { 0xfc, 0xf3, 0xcf, 0x3f }; unsigned char mask = mask_table[pp]; fp->ival = (fp->ival & mask) | (bit << (2*pp)); switch (fp->mode) { case 0: functor_set_mode0(ptr, fp, push); break; case 1: functor_set_mode1(fp); break; case 2: functor_set_mode2(fp); break; case M42: if (!fp->obj) { ptr = fp->out; fp = functor_index(ptr); } fp->obj->set(ptr, fp, push); break; } } unsigned functor_get(vvp_ipoint_t ptr) { functor_t fp = functor_index(ptr); assert(fp); if (fp->mode == M42 && fp->obj && fp->obj->get) return fp->obj->get(ptr, fp); return fp->oval & 3; } /* * This function is used by the scheduler to implement the propagation * event. The input is the pointer to the functor who's output is to * be propagated. Pass the output to the inputs of all the connected * functors. */ void functor_propagate(vvp_ipoint_t ptr) { functor_t fp = functor_index(ptr); unsigned char oval = fp->oval; vvp_ipoint_t idx = fp->out; while (idx) { functor_t idxp = functor_index(idx); vvp_ipoint_t next = idxp->port[ipoint_port(idx)]; functor_set(idx, oval); idx = next; } } void functor_dump(FILE*fd) { for (unsigned idx = 1 ; idx < functor_count ; idx += 1) { functor_t cur = functor_index(idx*4); fprintf(fd, "%08x: out=%x port={%x %x %x %x}\n", (idx*4), cur->out, cur->port[0], cur->port[1], cur->port[2], cur->port[3]); } } /* * The variable functor is special. This is the truth table for it. */ const unsigned char ft_var[16] = { 0xe4, /* 0 0: 11, 10, 01, 00 */ 0xe4, /* 0 1: 11, 10, 01, 00 */ 0xe4, /* 0 x: 11, 10, 01, 00 */ 0xe4, /* 0 z: 11, 10, 01, 00 */ 0x00, /* 1 0: 00, 00, 00, 00 */ 0x55, /* 1 1: 01, 01, 01, 01 */ 0xaa, /* 1 x: 10, 10, 10, 10 */ 0xff, /* 1 z: 11, 11, 11, 11 */ 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4, 0xe4 }; /* * $Log: functor.cc,v $ * Revision 1.15 2001/05/03 04:54:33 steve * Fix handling of a mode 1 functor that feeds into a * mode 2 functor. Feed the result only if the event * is triggered, and do pass to the output even if no * threads are waiting. * * Revision 1.14 2001/04/26 15:52:22 steve * Add the mode-42 functor concept to UDPs. * * Revision 1.13 2001/04/24 02:23:59 steve * Support for UDP devices in VVP (Stephen Boettcher) * * Revision 1.12 2001/04/18 04:21:23 steve * Put threads into scopes. * * Revision 1.11 2001/04/14 05:10:56 steve * support the .event/or statement. * * Revision 1.10 2001/04/03 03:18:34 steve * support functor_set push for blocking assignment. * * Revision 1.9 2001/03/31 19:29:23 steve * Fix compilation warnings. * * Revision 1.8 2001/03/29 03:46:36 steve * Support named events as mode 2 functors. * * Revision 1.7 2001/03/26 04:00:39 steve * Add the .event statement and the %wait instruction. * * Revision 1.6 2001/03/25 00:35:35 steve * Add the .net statement. * * Revision 1.5 2001/03/22 05:28:16 steve * no longer need out message. * * Revision 1.4 2001/03/22 05:08:00 steve * implement %load, %inv, %jum/0 and %cmp/u * * Revision 1.3 2001/03/20 06:16:24 steve * Add support for variable vectors. * * Revision 1.2 2001/03/11 22:42:11 steve * Functor values and propagation. * * Revision 1.1 2001/03/11 00:29:38 steve * Add the vvp engine to cvs. * */
Fix handling of a mode 1 functor that feeds into a mode 2 functor. Feed the result only if the event is triggered, and do pass to the output even if no threads are waiting.
Fix handling of a mode 1 functor that feeds into a mode 2 functor. Feed the result only if the event is triggered, and do pass to the output even if no threads are waiting.
C++
lgpl-2.1
CastMi/iverilog,themperek/iverilog,CastMi/iverilog,themperek/iverilog,CastMi/iverilog,themperek/iverilog
c560f88e915158b78c198fbc982a35cbbdf03644
lib/Transforms/Scalar/DCE.cpp
lib/Transforms/Scalar/DCE.cpp
//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // * Eliminates method prototypes that are not referenced // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DCE.h" #include "llvm/Module.h" #include "llvm/GlobalVariable.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iPHINode.h" #include "llvm/Assembly/Writer.h" #include "Support/STLExtras.h" #include <algorithm> // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL, BasicBlock::iterator &BBI) { // Look for un"used" definitions... if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() && !isa<TerminatorInst>(*BBI)) { delete BBIL.remove(BBI); // Bye bye return true; } return false; } static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) { bool Changed = false; for (BasicBlock::InstListType::iterator DI = Vals.begin(); DI != Vals.end(); ) if (DeadCodeElimination::dceInstruction(Vals, DI)) Changed = true; else ++DI; return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { BasicBlock::pred_iterator PI(BB->pred_begin()); if (PI == BB->pred_end() || ++PI != BB->pred_end()) return false; // More than one predecessor... Instruction *I = BB->front(); if (!isa<PHINode>(I)) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *BB->pred_begin(); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = cast<PHINode>(I); assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (isa<PHINode>(I)); return true; // Yes, we nuked at least one phi node } static void ReplaceUsesWithConstant(Instruction *I) { Constant *CPV = Constant::getNullConstant(I->getType()); // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. This function returns true (failure) if the Succ BB already // has a predecessor that is a predecessor of BB. // // Assumption: Succ is the single successor for BB. // static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(*BB->succ_begin() == Succ && "Succ is not successor of BB!"); assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const std::vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end()); // Check to see if one of the predecessors of BB is already a predecessor of // Succ. If so, we cannot do the transformation! // for (BasicBlock::pred_iterator PI = Succ->pred_begin(), PE = Succ->pred_end(); PI != PE; ++PI) { if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) return true; } BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = cast<PHINode>(*I); Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while (isa<PHINode>(*I)); return false; } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool SimplifyCFG(Method::iterator &BBIt) { BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB && BB->getParent() && "Block not embedded in method!"); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (BB->pred_begin() == BB->pred_end() && !BB->hasConstantReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(BB->succ_begin(), BB->succ_end(), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. BasicBlock::succ_iterator SI(BB->succ_begin()); if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ? if (BB->front()->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // Be careful though, if this transformation fails (returns true) then // we cannot do this transformation! // if (!isa<PHINode>(Succ->front()) || !PropogatePredecessorsForPHIs(BB, Succ)) { BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. BasicBlock::pred_iterator PI(BB->pred_begin()); if (PI != BB->pred_end() && *PI != BB && // Not empty? Not same BB? ++PI == BB->pred_end() && !BB->hasConstantReferences()) { BasicBlock *Pred = *BB->pred_begin(); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? BasicBlock::succ_iterator SI(Pred->succ_begin()); if (++SI == Pred->succ_end()) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } return Changed; } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool DeadCodeElimination::doDCE(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) { bool Changed = false; for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) { Method *Meth = *MI; if (Meth->isExternal() && Meth->use_size() == 0) { // No references to prototype? //cerr << "Removing method proto: " << Meth->getName() << endl; delete Mod->getMethodList().remove(MI); // Remove prototype // Remove moves iterator to point to the next one automatically Changed = true; } else { ++MI; // Skip prototype in use. } } for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) { GlobalVariable *GV = *GI; if (!GV->hasInitializer() && GV->use_size() == 0) { // No references to uninitialized global variable? //cerr << "Removing global var: " << GV->getName() << endl; delete Mod->getGlobalList().remove(GI); // Remove moves iterator to point to the next one automatically Changed = true; } else { ++GI; } } return Changed; }
//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // * Eliminates method prototypes that are not referenced // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DCE.h" #include "llvm/Module.h" #include "llvm/GlobalVariable.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iPHINode.h" #include "llvm/Assembly/Writer.h" #include "Support/STLExtras.h" #include <algorithm> // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL, BasicBlock::iterator &BBI) { // Look for un"used" definitions... if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() && !isa<TerminatorInst>(*BBI)) { delete BBIL.remove(BBI); // Bye bye return true; } return false; } static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) { bool Changed = false; for (BasicBlock::InstListType::iterator DI = Vals.begin(); DI != Vals.end(); ) if (DeadCodeElimination::dceInstruction(Vals, DI)) Changed = true; else ++DI; return Changed; } bool DeadInstElimination::runOnBasicBlock(BasicBlock *BB) { return RemoveUnusedDefs(BB->getInstList()); } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { BasicBlock::pred_iterator PI(BB->pred_begin()); if (PI == BB->pred_end() || ++PI != BB->pred_end()) return false; // More than one predecessor... Instruction *I = BB->front(); if (!isa<PHINode>(I)) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *BB->pred_begin(); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = cast<PHINode>(I); assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (isa<PHINode>(I)); return true; // Yes, we nuked at least one phi node } static void ReplaceUsesWithConstant(Instruction *I) { Constant *CPV = Constant::getNullConstant(I->getType()); // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. This function returns true (failure) if the Succ BB already // has a predecessor that is a predecessor of BB. // // Assumption: Succ is the single successor for BB. // static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(*BB->succ_begin() == Succ && "Succ is not successor of BB!"); assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const std::vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end()); // Check to see if one of the predecessors of BB is already a predecessor of // Succ. If so, we cannot do the transformation! // for (BasicBlock::pred_iterator PI = Succ->pred_begin(), PE = Succ->pred_end(); PI != PE; ++PI) { if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) return true; } BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = cast<PHINode>(*I); Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while (isa<PHINode>(*I)); return false; } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool SimplifyCFG(Method::iterator &BBIt) { BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB && BB->getParent() && "Block not embedded in method!"); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (BB->pred_begin() == BB->pred_end() && !BB->hasConstantReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(BB->succ_begin(), BB->succ_end(), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. BasicBlock::succ_iterator SI(BB->succ_begin()); if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ? if (BB->front()->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // Be careful though, if this transformation fails (returns true) then // we cannot do this transformation! // if (!isa<PHINode>(Succ->front()) || !PropogatePredecessorsForPHIs(BB, Succ)) { BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. BasicBlock::pred_iterator PI(BB->pred_begin()); if (PI != BB->pred_end() && *PI != BB && // Not empty? Not same BB? ++PI == BB->pred_end() && !BB->hasConstantReferences()) { BasicBlock *Pred = *BB->pred_begin(); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? BasicBlock::succ_iterator SI(Pred->succ_begin()); if (++SI == Pred->succ_end()) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } return Changed; } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool DeadCodeElimination::doDCE(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) { bool Changed = false; for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) { Method *Meth = *MI; if (Meth->isExternal() && Meth->use_size() == 0) { // No references to prototype? //cerr << "Removing method proto: " << Meth->getName() << endl; delete Mod->getMethodList().remove(MI); // Remove prototype // Remove moves iterator to point to the next one automatically Changed = true; } else { ++MI; // Skip prototype in use. } } for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) { GlobalVariable *GV = *GI; if (!GV->hasInitializer() && GV->use_size() == 0) { // No references to uninitialized global variable? //cerr << "Removing global var: " << GV->getName() << endl; delete Mod->getGlobalList().remove(GI); // Remove moves iterator to point to the next one automatically Changed = true; } else { ++GI; } } return Changed; }
Implement new DeadInstElmination pass remove old comment
Implement new DeadInstElmination pass remove old comment git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@1555 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm
faebb34f17c0636e4d997575bd1d0f2932073ff2
test/matrix.cpp
test/matrix.cpp
#include "mat.hpp" #include "lib/catch.hpp" static const float EPSILON = 1e-6; TEST_CASE( "base matrix accessors", "" ) { Mat<1,1> x = { 5 }; REQUIRE( x[0] == 5 ); x[0] = 9; REQUIRE( x[0] == 9 ); Mat<2,2> xy = { 1, 2, 3, 4 }; REQUIRE( xy[0] == 1 ); REQUIRE( xy[1] == 2 ); REQUIRE( xy[2] == 3 ); REQUIRE( xy[3] == 4 ); Mat<100,100> big; for ( int i = 0; i < 100; i++ ) big[i] = i; for ( int i = 0; i < 100; i++ ) REQUIRE( big[i] == i ); } TEST_CASE( "structured matrix accessors", "" ) { Vec2 xy = { 1, 2 }; REQUIRE( xy.x == 1 ); REQUIRE( xy.y == 2 ); }
#include "mat.hpp" #include "lib/catch.hpp" static const float EPSILON = 1e-6; TEST_CASE( "base matrix accessors", "" ) { Mat<1,1> x = { 5 }; REQUIRE( x[0] == 5 ); x[0] = 9; REQUIRE( x[0] == 9 ); Mat<2,2> xy = { 1, 2, 3, 4 }; REQUIRE( xy[0] == 1 ); REQUIRE( xy[1] == 2 ); REQUIRE( xy[2] == 3 ); REQUIRE( xy[3] == 4 ); Mat<100,100> big; for ( int i = 0; i < 100; i++ ) big[i] = i; for ( int i = 0; i < 100; i++ ) REQUIRE( big[i] == i ); } TEST_CASE( "structured matrix accessors", "" ) { Mat4 x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; REQUIRE( x.m00 == 1 ); REQUIRE( x.m01 == 2 ); REQUIRE( x.m02 == 3 ); REQUIRE( x.m03 == 4 ); REQUIRE( x.m10 == 5 ); REQUIRE( x.m11 == 6 ); REQUIRE( x.m12 == 7 ); REQUIRE( x.m13 == 8 ); REQUIRE( x.m20 == 9 ); REQUIRE( x.m21 == 10 ); REQUIRE( x.m22 == 11 ); REQUIRE( x.m23 == 12 ); REQUIRE( x.m30 == 13 ); REQUIRE( x.m31 == 14 ); REQUIRE( x.m32 == 15 ); REQUIRE( x.m33 == 16 ); }
add Mat4 structured accessor test
add Mat4 structured accessor test
C++
mit
davidyu/gml-cpp,davidyu/gml-cpp
834469c889c3ae19170f3d7aa30c74b32a3ab783
MyOpenCV/MyOpenCVIF.cpp
MyOpenCV/MyOpenCVIF.cpp
#include "MyOpenCVIF.hpp" MyOpenCVIF::MyOpenCVIF() : m_FPSCounter(), m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml") { } void MyOpenCVIF::ProcessFrame(Mat& frame) { m_FPSCounter.ProcessFrame(frame); m_systemMonitor.ProcessFrame(frame); m_humanDetector.ProcessFrame(frame); m_HUD.ProcessFrame(frame); }
#include "MyOpenCVIF.hpp" MyOpenCVIF::MyOpenCVIF() : m_FPSCounter(), m_humanDetector("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml") { } void MyOpenCVIF::ProcessFrame(Mat& frame) { m_FPSCounter.ProcessFrame(frame); //m_systemMonitor.ProcessFrame(frame); //m_humanDetector.ProcessFrame(frame); m_HUD.ProcessFrame(frame); }
Comment out sample HumanDetector and SystemMonitor to show performance
Comment out sample HumanDetector and SystemMonitor to show performance
C++
mit
lark-mp/raspicam_cvlan,lark-mp/raspicam_cvlan
30ab5292bf998b6cbc8ba454e500bc2e3cf9e574
Native/Core/DG/Code.cpp
Native/Core/DG/Code.cpp
/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include <Fabric/Core/DG/Code.h> #include <Fabric/Core/DG/ExecutionEngine.h> #include <Fabric/Core/CG/Scope.h> #include <Fabric/Core/OCL/OCL.h> #include <Fabric/Core/RT/Manager.h> #include <Fabric/Core/CG/Context.h> #include <Fabric/Core/CG/Manager.h> #include <Fabric/Core/CG/ModuleBuilder.h> #include <Fabric/Core/AST/GlobalList.h> #include <Fabric/Core/AST/Function.h> #include <Fabric/Core/AST/Operator.h> #include <Fabric/Core/AST/UseInfo.h> #include <Fabric/Core/RT/Desc.h> #include <Fabric/Core/RT/Impl.h> #include <Fabric/Core/Plug/Manager.h> #include <Fabric/Core/DG/Context.h> #include <Fabric/Core/DG/Function.h> #include <Fabric/Core/MT/LogCollector.h> #include <Fabric/Core/MT/IdleTaskQueue.h> #include <Fabric/Core/DG/IRCache.h> #include <Fabric/Core/KL/StringSource.h> #include <Fabric/Core/KL/Scanner.h> #include <Fabric/Core/KL/Parser.hpp> #include <Fabric/Core/Util/Log.h> #include <llvm/Module.h> #include <llvm/Function.h> #include <llvm/Target/TargetData.h> #include <llvm/Target/TargetSelect.h> #include <llvm/Target/TargetOptions.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/Assembly/Parser.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Analysis/Verifier.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/IPO.h> #include <llvm/Support/raw_ostream.h> #include <llvm/PassManager.h> #include <llvm/Support/StandardPasses.h> // [pzion 20110307] Include this last because it does lots of // #defines on Linux that mess up llvm // #include <Fabric/Core/OGL/OGL.h> namespace Fabric { namespace DG { static MT::Mutex s_globalCompileLock( "Global Compile Lock" ); RC::ConstHandle<Code> Code::Create( RC::ConstHandle<Context> const &context, std::string const &sourceCode ) { return new Code( context, sourceCode ); } Code::Code( RC::ConstHandle<Context> const &context, std::string const &sourceCode ) : m_contextWeakRef( context ) , m_mutex( "DG::Code" ) , m_sourceCode( sourceCode ) , m_registeredFunctionSetMutex( "DG::Code::m_registeredFunctionSet" ) { compileSourceCode(); } Code::~Code() { } void Code::compileSourceCode() { MT::Mutex::Lock mutexLock( m_mutex ); llvm::InitializeNativeTarget(); LLVMLinkInJIT(); FABRIC_ASSERT( m_sourceCode.length() > 0 ); RC::ConstHandle<KL::Source> source = KL::StringSource::Create( m_sourceCode ); RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source ); m_ast = AST::GlobalList::Create( m_ast, KL::Parse( scanner, m_diagnostics ) ); if ( !m_diagnostics.containsError() ) compileAST( false ); } void Code::compileAST( bool optimize ) { RC::ConstHandle<Context> context = m_contextWeakRef.makeStrong(); if ( !context ) return; MT::Mutex::Lock mutexLock( m_mutex ); FABRIC_ASSERT( m_ast ); RC::ConstHandle<AST::GlobalList> ast = m_ast; AST::UseNameToLocationMap uses; m_ast->collectUses( uses ); std::set<std::string> includedUses; while ( !uses.empty() ) { AST::UseNameToLocationMap::iterator it = uses.begin(); std::string const &name = it->first; if ( includedUses.find( name ) == includedUses.end() ) { RC::ConstHandle<AST::GlobalList> useAST = Plug::Manager::Instance()->maybeGetASTForExt( name ); if ( !useAST ) { RC::ConstHandle<RC::Object> typeAST; if ( context->getRTManager()->maybeGetASTForType( name, typeAST ) ) useAST = typeAST? RC::ConstHandle<AST::GlobalList>::StaticCast( typeAST ): AST::GlobalList::Create(); } if ( useAST ) { useAST->collectUses( uses ); ast = AST::GlobalList::Create( useAST, ast ); includedUses.insert( name ); } else m_diagnostics.addError( it->second, "no registered type or plugin named " + _(it->first) ); } uses.erase( it ); } if ( !m_diagnostics.containsError() ) { RC::Handle<CG::Manager> cgManager = context->getCGManager(); RC::Handle<CG::Context> cgContext = CG::Context::Create(); llvm::OwningPtr<llvm::Module> module( new llvm::Module( "DG::Code", cgContext->getLLVMContext() ) ); CG::ModuleBuilder moduleBuilder( cgManager, cgContext, module.get() ); OCL::llvmPrepareModule( moduleBuilder, context->getRTManager() ); CG::Diagnostics optimizeDiagnostics; CG::Diagnostics &diagnostics = (false && optimize)? optimizeDiagnostics: m_diagnostics; llvm::NoFramePointerElim = true; llvm::JITExceptionHandling = true; std::string irCacheKeyForAST = IRCache::Instance()->keyForAST( ast ); std::string ir = IRCache::Instance()->get( irCacheKeyForAST ); if ( ir.length() > 0 ) { RC::Handle<CG::Manager> cgManager = context->getCGManager(); llvm::SMDiagnostic error; llvm::ParseAssemblyString( ir.c_str(), module.get(), error, cgContext->getLLVMContext() ); ast->registerTypes( cgManager, diagnostics ); FABRIC_ASSERT( !diagnostics.containsError() ); FABRIC_ASSERT( !llvm::verifyModule( *module, llvm::PrintMessageAction ) ); linkModule( cgContext, module, true ); return; } ast->registerTypes( cgManager, diagnostics ); if ( !diagnostics.containsError() ) { ast->llvmCompileToModule( moduleBuilder, diagnostics, false ); } if ( !diagnostics.containsError() ) { ast->llvmCompileToModule( moduleBuilder, diagnostics, true ); } if ( !diagnostics.containsError() ) { #if defined(FABRIC_BUILD_DEBUG) std::string optimizeByteCode; std::string &byteCode = (false && optimize)? optimizeByteCode: m_byteCode; llvm::raw_string_ostream byteCodeStream( byteCode ); module->print( byteCodeStream, 0 ); byteCodeStream.flush(); #endif llvm::OwningPtr<llvm::PassManager> passManager( new llvm::PassManager ); if ( optimize ) { llvm::createStandardFunctionPasses( passManager.get(), 2 ); llvm::createStandardModulePasses( passManager.get(), 2, false, true, true, true, false, llvm::createFunctionInliningPass() ); llvm::createStandardLTOPasses( passManager.get(), true, true, false ); } #if defined(FABRIC_BUILD_DEBUG) passManager->add( llvm::createVerifierPass() ); #endif passManager->run( *module ); if ( optimize ) { std::string ir; llvm::raw_string_ostream irStream( ir ); module->print( irStream, 0 ); irStream.flush(); IRCache::Instance()->put( irCacheKeyForAST, ir ); } linkModule( cgContext, module, optimize ); } } } void Code::linkModule( RC::Handle<CG::Context> const &cgContext, llvm::OwningPtr<llvm::Module> &module, bool optimize ) { RC::ConstHandle<Context> context = m_contextWeakRef.makeStrong(); if ( !context ) return; MT::Mutex::Lock mutexLock( m_mutex ); RC::ConstHandle<ExecutionEngine> executionEngine = ExecutionEngine::Create( context, cgContext, module.take() ); { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); for ( RegisteredFunctionSet::const_iterator it=m_registeredFunctionSet.begin(); it!=m_registeredFunctionSet.end(); ++it ) { Function *function = *it; function->onExecutionEngineChange( executionEngine ); } } m_executionEngine = executionEngine; if ( !optimize ) { retain(); MT::IdleTaskQueue::Instance()->submit( &Code::CompileOptimizedAST, this ); } } std::string const &Code::getSourceCode() const { return m_sourceCode; } #if defined(FABRIC_BUILD_DEBUG) std::string const &Code::getByteCode() const { return m_byteCode; } #endif RC::ConstHandle<AST::GlobalList> Code::getAST() const { return m_ast; } RC::ConstHandle<ExecutionEngine> Code::getExecutionEngine() const { return m_executionEngine; } CG::Diagnostics const &Code::getDiagnostics() const { return m_diagnostics; } void Code::registerFunction( Function *function ) const { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); m_registeredFunctionSet.insert( function ); } void Code::unregisterFunction( Function *function ) const { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); RegisteredFunctionSet::iterator it = m_registeredFunctionSet.find( function ); FABRIC_ASSERT( it != m_registeredFunctionSet.end() ); m_registeredFunctionSet.erase( it ); } }; };
/* * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved. */ #include <Fabric/Core/DG/Code.h> #include <Fabric/Core/DG/ExecutionEngine.h> #include <Fabric/Core/CG/Scope.h> #include <Fabric/Core/OCL/OCL.h> #include <Fabric/Core/RT/Manager.h> #include <Fabric/Core/CG/Context.h> #include <Fabric/Core/CG/Manager.h> #include <Fabric/Core/CG/ModuleBuilder.h> #include <Fabric/Core/AST/GlobalList.h> #include <Fabric/Core/AST/Function.h> #include <Fabric/Core/AST/Operator.h> #include <Fabric/Core/AST/UseInfo.h> #include <Fabric/Core/RT/Desc.h> #include <Fabric/Core/RT/Impl.h> #include <Fabric/Core/Plug/Manager.h> #include <Fabric/Core/DG/Context.h> #include <Fabric/Core/DG/Function.h> #include <Fabric/Core/MT/LogCollector.h> #include <Fabric/Core/MT/IdleTaskQueue.h> #include <Fabric/Core/DG/IRCache.h> #include <Fabric/Core/KL/StringSource.h> #include <Fabric/Core/KL/Scanner.h> #include <Fabric/Core/KL/Parser.hpp> #include <Fabric/Core/Util/Log.h> #include <llvm/Module.h> #include <llvm/Function.h> #include <llvm/Target/TargetData.h> #include <llvm/Target/TargetSelect.h> #include <llvm/Target/TargetOptions.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/Assembly/Parser.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Analysis/Verifier.h> #include <llvm/Transforms/Scalar.h> #include <llvm/Transforms/IPO.h> #include <llvm/Support/raw_ostream.h> #include <llvm/PassManager.h> #include <llvm/Support/StandardPasses.h> namespace Fabric { namespace DG { RC::ConstHandle<Code> Code::Create( RC::ConstHandle<Context> const &context, std::string const &sourceCode ) { return new Code( context, sourceCode ); } Code::Code( RC::ConstHandle<Context> const &context, std::string const &sourceCode ) : m_contextWeakRef( context ) , m_mutex( "DG::Code" ) , m_sourceCode( sourceCode ) , m_registeredFunctionSetMutex( "DG::Code::m_registeredFunctionSet" ) { compileSourceCode(); } Code::~Code() { } void Code::compileSourceCode() { MT::Mutex::Lock mutexLock( m_mutex ); llvm::InitializeNativeTarget(); LLVMLinkInJIT(); FABRIC_ASSERT( m_sourceCode.length() > 0 ); RC::ConstHandle<KL::Source> source = KL::StringSource::Create( m_sourceCode ); RC::Handle<KL::Scanner> scanner = KL::Scanner::Create( source ); m_ast = AST::GlobalList::Create( m_ast, KL::Parse( scanner, m_diagnostics ) ); if ( !m_diagnostics.containsError() ) compileAST( false ); } void Code::compileAST( bool optimize ) { RC::ConstHandle<Context> context = m_contextWeakRef.makeStrong(); if ( !context ) return; MT::Mutex::Lock mutexLock( m_mutex ); FABRIC_ASSERT( m_ast ); RC::ConstHandle<AST::GlobalList> ast = m_ast; AST::UseNameToLocationMap uses; m_ast->collectUses( uses ); std::set<std::string> includedUses; while ( !uses.empty() ) { AST::UseNameToLocationMap::iterator it = uses.begin(); std::string const &name = it->first; if ( includedUses.find( name ) == includedUses.end() ) { RC::ConstHandle<AST::GlobalList> useAST = Plug::Manager::Instance()->maybeGetASTForExt( name ); if ( !useAST ) { RC::ConstHandle<RC::Object> typeAST; if ( context->getRTManager()->maybeGetASTForType( name, typeAST ) ) useAST = typeAST? RC::ConstHandle<AST::GlobalList>::StaticCast( typeAST ): AST::GlobalList::Create(); } if ( useAST ) { useAST->collectUses( uses ); ast = AST::GlobalList::Create( useAST, ast ); includedUses.insert( name ); } else m_diagnostics.addError( it->second, "no registered type or plugin named " + _(it->first) ); } uses.erase( it ); } if ( !m_diagnostics.containsError() ) { RC::Handle<CG::Manager> cgManager = context->getCGManager(); RC::Handle<CG::Context> cgContext = CG::Context::Create(); llvm::OwningPtr<llvm::Module> module( new llvm::Module( "DG::Code", cgContext->getLLVMContext() ) ); CG::ModuleBuilder moduleBuilder( cgManager, cgContext, module.get() ); OCL::llvmPrepareModule( moduleBuilder, context->getRTManager() ); CG::Diagnostics optimizeDiagnostics; CG::Diagnostics &diagnostics = (false && optimize)? optimizeDiagnostics: m_diagnostics; llvm::NoFramePointerElim = true; llvm::JITExceptionHandling = true; std::string irCacheKeyForAST = IRCache::Instance()->keyForAST( ast ); std::string ir = IRCache::Instance()->get( irCacheKeyForAST ); if ( ir.length() > 0 ) { RC::Handle<CG::Manager> cgManager = context->getCGManager(); llvm::SMDiagnostic error; llvm::ParseAssemblyString( ir.c_str(), module.get(), error, cgContext->getLLVMContext() ); ast->registerTypes( cgManager, diagnostics ); FABRIC_ASSERT( !diagnostics.containsError() ); FABRIC_ASSERT( !llvm::verifyModule( *module, llvm::PrintMessageAction ) ); linkModule( cgContext, module, true ); return; } ast->registerTypes( cgManager, diagnostics ); if ( !diagnostics.containsError() ) { ast->llvmCompileToModule( moduleBuilder, diagnostics, false ); } if ( !diagnostics.containsError() ) { ast->llvmCompileToModule( moduleBuilder, diagnostics, true ); } if ( !diagnostics.containsError() ) { #if defined(FABRIC_BUILD_DEBUG) std::string optimizeByteCode; std::string &byteCode = (false && optimize)? optimizeByteCode: m_byteCode; llvm::raw_string_ostream byteCodeStream( byteCode ); module->print( byteCodeStream, 0 ); byteCodeStream.flush(); #endif llvm::OwningPtr<llvm::PassManager> passManager( new llvm::PassManager ); if ( optimize ) { llvm::createStandardFunctionPasses( passManager.get(), 2 ); llvm::createStandardModulePasses( passManager.get(), 2, false, true, true, true, false, llvm::createFunctionInliningPass() ); llvm::createStandardLTOPasses( passManager.get(), true, true, false ); } #if defined(FABRIC_BUILD_DEBUG) passManager->add( llvm::createVerifierPass() ); #endif passManager->run( *module ); if ( optimize ) { std::string ir; llvm::raw_string_ostream irStream( ir ); module->print( irStream, 0 ); irStream.flush(); IRCache::Instance()->put( irCacheKeyForAST, ir ); } linkModule( cgContext, module, optimize ); } } } void Code::linkModule( RC::Handle<CG::Context> const &cgContext, llvm::OwningPtr<llvm::Module> &module, bool optimize ) { RC::ConstHandle<Context> context = m_contextWeakRef.makeStrong(); if ( !context ) return; MT::Mutex::Lock mutexLock( m_mutex ); RC::ConstHandle<ExecutionEngine> executionEngine = ExecutionEngine::Create( context, cgContext, module.take() ); { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); for ( RegisteredFunctionSet::const_iterator it=m_registeredFunctionSet.begin(); it!=m_registeredFunctionSet.end(); ++it ) { Function *function = *it; function->onExecutionEngineChange( executionEngine ); } } m_executionEngine = executionEngine; if ( !optimize ) { retain(); MT::IdleTaskQueue::Instance()->submit( &Code::CompileOptimizedAST, this ); } } std::string const &Code::getSourceCode() const { return m_sourceCode; } #if defined(FABRIC_BUILD_DEBUG) std::string const &Code::getByteCode() const { return m_byteCode; } #endif RC::ConstHandle<AST::GlobalList> Code::getAST() const { return m_ast; } RC::ConstHandle<ExecutionEngine> Code::getExecutionEngine() const { return m_executionEngine; } CG::Diagnostics const &Code::getDiagnostics() const { return m_diagnostics; } void Code::registerFunction( Function *function ) const { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); m_registeredFunctionSet.insert( function ); } void Code::unregisterFunction( Function *function ) const { MT::Mutex::Lock lock( m_registeredFunctionSetMutex ); RegisteredFunctionSet::iterator it = m_registeredFunctionSet.find( function ); FABRIC_ASSERT( it != m_registeredFunctionSet.end() ); m_registeredFunctionSet.erase( it ); } }; };
Remove global compile lock that is not even used
Remove global compile lock that is not even used
C++
agpl-3.0
chbfiv/fabric-engine-old,chbfiv/fabric-engine-old,errordeveloper/fe-devel,errordeveloper/fe-devel,errordeveloper/fe-devel,chbfiv/fabric-engine-old,errordeveloper/fe-devel,chbfiv/fabric-engine-old,errordeveloper/fe-devel,chbfiv/fabric-engine-old,errordeveloper/fe-devel,chbfiv/fabric-engine-old,chbfiv/fabric-engine-old,errordeveloper/fe-devel
094d7c4926e53fd2da0c1eb55b17208a3f21e067
samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp
samples/cpp/tutorial_code/ImgTrans/HoughCircle_Demo.cpp
/** * @file HoughCircle_Demo.cpp * @brief Demo code for Hough Transform * @author OpenCV team */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> using namespace cv; namespace { // windows and trackbars name const std::string windowName = "Hough Circle Detection Demo"; const std::string cannyThresholdTrackbarName = "Canny threshold"; const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold"; // initial and max values of the parameters of interests. const int cannyThresholdInitialValue = 200; const int accumulatorThresholdInitialValue = 50; const int maxAccumulatorThreshold = 200; const int maxCannyThreshold = 255; void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold) { // will hold the results of the detection std::vector<Vec3f> circles; // runs the actual detection HoughCircles( src_gray, circles, HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 ); // clone the colour, input image for displaying purposes Mat display = src_display.clone(); for( size_t i = 0; i < circles.size(); i++ ) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // circle center circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 ); // circle outline circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 ); } // shows the results imshow( windowName, display); } } int main(int, char** argv) { Mat src, src_gray; // Read the image src = imread( argv[1], 1 ); if( !src.data ) { std::cerr<<"Invalid input image\n"; std::cout<<"Usage : tutorial_HoughCircle_Demo <path_to_input_image>\n"; return -1; } // Convert it to gray cvtColor( src, src_gray, COLOR_BGR2GRAY ); // Reduce the noise so we avoid false circle detection GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 ); //declare and initialize both parameters that are subjects to change int cannyThreshold = cannyThresholdInitialValue; int accumulatorThreshold = accumulatorThresholdInitialValue; // create the main window, and attach the trackbars namedWindow( windowName, WINDOW_AUTOSIZE ); createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold); createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold); // infinite loop to display // and refresh the content of the output image // until the user presses q or Q int key = 0; while(key != 'q' && key != 'Q') { // those paramaters cannot be =0 // so we must check here cannyThreshold = std::max(cannyThreshold, 1); accumulatorThreshold = std::max(accumulatorThreshold, 1); //runs the detection, and update the display HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold); // get user key key = waitKey(10); } return 0; }
/** * @file HoughCircle_Demo.cpp * @brief Demo code for Hough Transform * @author OpenCV team */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> using namespace cv; namespace { // windows and trackbars name const std::string windowName = "Hough Circle Detection Demo"; const std::string cannyThresholdTrackbarName = "Canny threshold"; const std::string accumulatorThresholdTrackbarName = "Accumulator Threshold"; // initial and max values of the parameters of interests. const int cannyThresholdInitialValue = 200; const int accumulatorThresholdInitialValue = 50; const int maxAccumulatorThreshold = 200; const int maxCannyThreshold = 255; void HoughDetection(const Mat& src_gray, const Mat& src_display, int cannyThreshold, int accumulatorThreshold) { // will hold the results of the detection std::vector<Vec3f> circles; // runs the actual detection HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows/8, cannyThreshold, accumulatorThreshold, 0, 0 ); // clone the colour, input image for displaying purposes Mat display = src_display.clone(); for( size_t i = 0; i < circles.size(); i++ ) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // circle center circle( display, center, 3, Scalar(0,255,0), -1, 8, 0 ); // circle outline circle( display, center, radius, Scalar(0,0,255), 3, 8, 0 ); } // shows the results imshow( windowName, display); } } int main(int, char** argv) { Mat src, src_gray; // Read the image src = imread( argv[1], 1 ); if( !src.data ) { std::cerr<<"Invalid input image\n"; std::cout<<"Usage : tutorial_HoughCircle_Demo <path_to_input_image>\n"; return -1; } // Convert it to gray cvtColor( src, src_gray, COLOR_BGR2GRAY ); // Reduce the noise so we avoid false circle detection GaussianBlur( src_gray, src_gray, Size(9, 9), 2, 2 ); //declare and initialize both parameters that are subjects to change int cannyThreshold = cannyThresholdInitialValue; int accumulatorThreshold = accumulatorThresholdInitialValue; // create the main window, and attach the trackbars namedWindow( windowName, WINDOW_AUTOSIZE ); createTrackbar(cannyThresholdTrackbarName, windowName, &cannyThreshold,maxCannyThreshold); createTrackbar(accumulatorThresholdTrackbarName, windowName, &accumulatorThreshold, maxAccumulatorThreshold); // infinite loop to display // and refresh the content of the output image // until the user presses q or Q int key = 0; while(key != 'q' && key != 'Q') { // those paramaters cannot be =0 // so we must check here cannyThreshold = std::max(cannyThreshold, 1); accumulatorThreshold = std::max(accumulatorThreshold, 1); //runs the detection, and update the display HoughDetection(src_gray, src, cannyThreshold, accumulatorThreshold); // get user key key = waitKey(10); } return 0; }
build fix
build fix
C++
apache-2.0
opencv/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,opencv/opencv
6a793ea51e9446845b886d0f3825a54fbd47c692
searchlib/src/vespa/searchlib/queryeval/split_float.cpp
searchlib/src/vespa/searchlib/queryeval/split_float.cpp
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "split_float.h" #include <cctype> namespace search::queryeval { SplitFloat::SplitFloat(const vespalib::string &input) { bool seenText = false; for (size_t i = 0; i < input.size(); ++i) { unsigned char c = input[i]; if (isalnum(c)) { if (!seenText) { _parts.push_back(vespalib::string()); } _parts.back().push_back(c); seenText = true; } else { seenText = false; } } } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "split_float.h" #include <cctype> namespace search::queryeval { SplitFloat::SplitFloat(const vespalib::string &input) { bool seenText = false; for (size_t i = 0; i < input.size(); ++i) { unsigned char c = input[i]; if (isalnum(c)) { if (!seenText) { _parts.push_back(vespalib::string()); } _parts.back().push_back(c); seenText = true; } else { seenText = false; } } } }
Add newline
Add newline
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
f30c7f37f00456497642f35647bbeadce751b125
src/plugins/qt4projectmanager/qt-maemo/maemodeployables.cpp
src/plugins/qt4projectmanager/qt-maemo/maemodeployables.cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemodeployables.h" #include "maemoprofilesupdatedialog.h" #include <profileevaluator.h> #include <projectexplorer/buildstep.h> #include <qt4projectmanager/qt4projectmanagerconstants.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <qt4projectmanager/qt4target.h> #include <QtCore/QTimer> namespace Qt4ProjectManager { namespace Internal { MaemoDeployables::MaemoDeployables(const Qt4Target *target) : m_target(target), m_updateTimer(new QTimer(this)) { QTimer::singleShot(0, this, SLOT(init())); m_updateTimer->setInterval(1500); connect(m_updateTimer, SIGNAL(timeout()), this, SLOT(createModels())); } MaemoDeployables::~MaemoDeployables() {} void MaemoDeployables::init() { Qt4Project * const pro = m_target->qt4Project(); connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); // TODO do we want to disable the view createModels(); } void MaemoDeployables::createModels() { if (m_target->project()->activeTarget() != m_target) return; const Qt4ProFileNode *const rootNode = m_target->qt4Project()->rootProjectNode(); if (!rootNode) // Happens on project creation by wizard. return; m_updateTimer->stop(); disconnect(m_target->qt4Project(), SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); beginResetModel(); qDeleteAll(m_listModels); m_listModels.clear(); createModels(rootNode); QList<MaemoDeployableListModel *> modelsWithoutTargetPath; foreach (MaemoDeployableListModel *const model, m_listModels) { if (!model->hasTargetPath()) { if (model->proFileUpdateSetting() == MaemoDeployableListModel::AskToUpdateProFile) modelsWithoutTargetPath << model; } } if (!modelsWithoutTargetPath.isEmpty()) { MaemoProFilesUpdateDialog dialog(modelsWithoutTargetPath); dialog.exec(); const QList<MaemoProFilesUpdateDialog::UpdateSetting> &settings = dialog.getUpdateSettings(); foreach (const MaemoProFilesUpdateDialog::UpdateSetting &setting, settings) { const MaemoDeployableListModel::ProFileUpdateSetting updateSetting = setting.second ? MaemoDeployableListModel::UpdateProFile : MaemoDeployableListModel::DontUpdateProFile; m_updateSettings.insert(setting.first->proFilePath(), updateSetting); setting.first->setProFileUpdateSetting(updateSetting); } } endResetModel(); connect(m_target->qt4Project(), SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); } void MaemoDeployables::createModels(const Qt4ProFileNode *proFileNode) { switch (proFileNode->projectType()) { case ApplicationTemplate: case LibraryTemplate: case ScriptTemplate: { UpdateSettingsMap::ConstIterator it = m_updateSettings.find(proFileNode->path()); const MaemoDeployableListModel::ProFileUpdateSetting updateSetting = it != m_updateSettings.end() ? it.value() : MaemoDeployableListModel::AskToUpdateProFile; MaemoDeployableListModel *const newModel = new MaemoDeployableListModel(proFileNode, updateSetting, this); m_listModels << newModel; break; } case SubDirsTemplate: { const QList<ProjectExplorer::ProjectNode *> &subProjects = proFileNode->subProjectNodes(); foreach (const ProjectExplorer::ProjectNode *subProject, subProjects) { const Qt4ProFileNode * const qt4SubProject = qobject_cast<const Qt4ProFileNode *>(subProject); if (qt4SubProject && !qt4SubProject->path() .endsWith(QLatin1String(".pri"))) createModels(qt4SubProject); } } default: break; } } void MaemoDeployables::setUnmodified() { foreach (MaemoDeployableListModel *model, m_listModels) model->setUnModified(); } bool MaemoDeployables::isModified() const { foreach (const MaemoDeployableListModel *model, m_listModels) { if (model->isModified()) return true; } return false; } int MaemoDeployables::deployableCount() const { int count = 0; foreach (const MaemoDeployableListModel *model, m_listModels) count += model->rowCount(); return count; } MaemoDeployable MaemoDeployables::deployableAt(int i) const { foreach (const MaemoDeployableListModel *model, m_listModels) { Q_ASSERT(i >= 0); if (i < model->rowCount()) return model->deployableAt(i); i -= model->rowCount(); } Q_ASSERT(!"Invalid deployable number"); return MaemoDeployable(QString(), QString()); } QString MaemoDeployables::remoteExecutableFilePath(const QString &localExecutableFilePath) const { foreach (const MaemoDeployableListModel *model, m_listModels) { if (model->localExecutableFilePath() == localExecutableFilePath) return model->remoteExecutableFilePath(); } return QString(); } int MaemoDeployables::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : modelCount(); } QVariant MaemoDeployables::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() < 0 || index.row() >= modelCount() || index.column() != 0) return QVariant(); const MaemoDeployableListModel *const model = m_listModels.at(index.row()); if (role == Qt::ForegroundRole && !model->hasTargetPath()) { QBrush brush; brush.setColor(Qt::red); return brush; } if (role == Qt::DisplayRole) return QFileInfo(model->proFilePath()).fileName(); return QVariant(); } } // namespace Qt4ProjectManager } // namespace Internal
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Qt Creator. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "maemodeployables.h" #include "maemoprofilesupdatedialog.h" #include <profileevaluator.h> #include <projectexplorer/buildstep.h> #include <qt4projectmanager/qt4projectmanagerconstants.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <qt4projectmanager/qt4target.h> #include <QtCore/QTimer> namespace Qt4ProjectManager { namespace Internal { MaemoDeployables::MaemoDeployables(const Qt4Target *target) : m_target(target), m_updateTimer(new QTimer(this)) { QTimer::singleShot(0, this, SLOT(init())); m_updateTimer->setInterval(1500); m_updateTimer->setSingleShot(true); connect(m_updateTimer, SIGNAL(timeout()), this, SLOT(createModels())); } MaemoDeployables::~MaemoDeployables() {} void MaemoDeployables::init() { Qt4Project * const pro = m_target->qt4Project(); connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); // TODO do we want to disable the view createModels(); } void MaemoDeployables::createModels() { if (m_target->project()->activeTarget() != m_target) return; const Qt4ProFileNode *const rootNode = m_target->qt4Project()->rootProjectNode(); if (!rootNode) // Happens on project creation by wizard. return; m_updateTimer->stop(); disconnect(m_target->qt4Project(), SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); beginResetModel(); qDeleteAll(m_listModels); m_listModels.clear(); createModels(rootNode); QList<MaemoDeployableListModel *> modelsWithoutTargetPath; foreach (MaemoDeployableListModel *const model, m_listModels) { if (!model->hasTargetPath()) { if (model->proFileUpdateSetting() == MaemoDeployableListModel::AskToUpdateProFile) modelsWithoutTargetPath << model; } } if (!modelsWithoutTargetPath.isEmpty()) { MaemoProFilesUpdateDialog dialog(modelsWithoutTargetPath); dialog.exec(); const QList<MaemoProFilesUpdateDialog::UpdateSetting> &settings = dialog.getUpdateSettings(); foreach (const MaemoProFilesUpdateDialog::UpdateSetting &setting, settings) { const MaemoDeployableListModel::ProFileUpdateSetting updateSetting = setting.second ? MaemoDeployableListModel::UpdateProFile : MaemoDeployableListModel::DontUpdateProFile; m_updateSettings.insert(setting.first->proFilePath(), updateSetting); setting.first->setProFileUpdateSetting(updateSetting); } } endResetModel(); connect(m_target->qt4Project(), SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), m_updateTimer, SLOT(start())); } void MaemoDeployables::createModels(const Qt4ProFileNode *proFileNode) { switch (proFileNode->projectType()) { case ApplicationTemplate: case LibraryTemplate: case ScriptTemplate: { UpdateSettingsMap::ConstIterator it = m_updateSettings.find(proFileNode->path()); const MaemoDeployableListModel::ProFileUpdateSetting updateSetting = it != m_updateSettings.end() ? it.value() : MaemoDeployableListModel::AskToUpdateProFile; MaemoDeployableListModel *const newModel = new MaemoDeployableListModel(proFileNode, updateSetting, this); m_listModels << newModel; break; } case SubDirsTemplate: { const QList<ProjectExplorer::ProjectNode *> &subProjects = proFileNode->subProjectNodes(); foreach (const ProjectExplorer::ProjectNode *subProject, subProjects) { const Qt4ProFileNode * const qt4SubProject = qobject_cast<const Qt4ProFileNode *>(subProject); if (qt4SubProject && !qt4SubProject->path() .endsWith(QLatin1String(".pri"))) createModels(qt4SubProject); } } default: break; } } void MaemoDeployables::setUnmodified() { foreach (MaemoDeployableListModel *model, m_listModels) model->setUnModified(); } bool MaemoDeployables::isModified() const { foreach (const MaemoDeployableListModel *model, m_listModels) { if (model->isModified()) return true; } return false; } int MaemoDeployables::deployableCount() const { int count = 0; foreach (const MaemoDeployableListModel *model, m_listModels) count += model->rowCount(); return count; } MaemoDeployable MaemoDeployables::deployableAt(int i) const { foreach (const MaemoDeployableListModel *model, m_listModels) { Q_ASSERT(i >= 0); if (i < model->rowCount()) return model->deployableAt(i); i -= model->rowCount(); } Q_ASSERT(!"Invalid deployable number"); return MaemoDeployable(QString(), QString()); } QString MaemoDeployables::remoteExecutableFilePath(const QString &localExecutableFilePath) const { foreach (const MaemoDeployableListModel *model, m_listModels) { if (model->localExecutableFilePath() == localExecutableFilePath) return model->remoteExecutableFilePath(); } return QString(); } int MaemoDeployables::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : modelCount(); } QVariant MaemoDeployables::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() < 0 || index.row() >= modelCount() || index.column() != 0) return QVariant(); const MaemoDeployableListModel *const model = m_listModels.at(index.row()); if (role == Qt::ForegroundRole && !model->hasTargetPath()) { QBrush brush; brush.setColor(Qt::red); return brush; } if (role == Qt::DisplayRole) return QFileInfo(model->proFilePath()).fileName(); return QVariant(); } } // namespace Qt4ProjectManager } // namespace Internal
Fix timer bug.
Maemo: Fix timer bug.
C++
lgpl-2.1
malikcjm/qtcreator,yinyunqiao/qtcreator,amyvmiwei/qt-creator,ostash/qt-creator-i18n-uk,maui-packages/qt-creator,Distrotech/qtcreator,KDE/android-qt-creator,darksylinc/qt-creator,omniacreator/qtcreator,colede/qtcreator,omniacreator/qtcreator,kuba1/qtcreator,colede/qtcreator,pcacjr/qt-creator,AltarBeastiful/qt-creator,jonnor/qt-creator,syntheticpp/qt-creator,hdweiss/qt-creator-visualizer,kuba1/qtcreator,ostash/qt-creator-i18n-uk,renatofilho/QtCreator,kuba1/qtcreator,Distrotech/qtcreator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,pcacjr/qt-creator,malikcjm/qtcreator,KDAB/KDAB-Creator,jonnor/qt-creator,KDE/android-qt-creator,azat/qtcreator,kuba1/qtcreator,pcacjr/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,KDAB/KDAB-Creator,duythanhphan/qt-creator,darksylinc/qt-creator,KDAB/KDAB-Creator,richardmg/qtcreator,KDAB/KDAB-Creator,hdweiss/qt-creator-visualizer,xianian/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,AltarBeastiful/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,colede/qtcreator,KDE/android-qt-creator,danimo/qt-creator,renatofilho/QtCreator,colede/qtcreator,richardmg/qtcreator,Distrotech/qtcreator,syntheticpp/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,sandsmark/qtcreator-minimap,KDAB/KDAB-Creator,dmik/qt-creator-os2,sandsmark/qtcreator-minimap,pcacjr/qt-creator,malikcjm/qtcreator,malikcjm/qtcreator,yinyunqiao/qtcreator,darksylinc/qt-creator,martyone/sailfish-qtcreator,omniacreator/qtcreator,ostash/qt-creator-i18n-uk,azat/qtcreator,malikcjm/qtcreator,syntheticpp/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,pcacjr/qt-creator,duythanhphan/qt-creator,amyvmiwei/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,danimo/qt-creator,renatofilho/QtCreator,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,bakaiadam/collaborative_qt_creator,maui-packages/qt-creator,malikcjm/qtcreator,dmik/qt-creator-os2,amyvmiwei/qt-creator,KDE/android-qt-creator,jonnor/qt-creator,amyvmiwei/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,Distrotech/qtcreator,sandsmark/qtcreator-minimap,Distrotech/qtcreator,xianian/qt-creator,farseerri/git_code,KDE/android-qt-creator,hdweiss/qt-creator-visualizer,dmik/qt-creator-os2,kuba1/qtcreator,yinyunqiao/qtcreator,renatofilho/QtCreator,amyvmiwei/qt-creator,darksylinc/qt-creator,jonnor/qt-creator,duythanhphan/qt-creator,amyvmiwei/qt-creator,omniacreator/qtcreator,maui-packages/qt-creator,xianian/qt-creator,colede/qtcreator,xianian/qt-creator,danimo/qt-creator,darksylinc/qt-creator,syntheticpp/qt-creator,danimo/qt-creator,KDE/android-qt-creator,AltarBeastiful/qt-creator,yinyunqiao/qtcreator,azat/qtcreator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,syntheticpp/qt-creator,richardmg/qtcreator,azat/qtcreator,azat/qtcreator,yinyunqiao/qtcreator,colede/qtcreator,jonnor/qt-creator,danimo/qt-creator,pcacjr/qt-creator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,syntheticpp/qt-creator,farseerri/git_code,ostash/qt-creator-i18n-uk,darksylinc/qt-creator,renatofilho/QtCreator,bakaiadam/collaborative_qt_creator,farseerri/git_code,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,richardmg/qtcreator,maui-packages/qt-creator,sandsmark/qtcreator-minimap,KDE/android-qt-creator,martyone/sailfish-qtcreator,farseerri/git_code,yinyunqiao/qtcreator,richardmg/qtcreator,omniacreator/qtcreator,malikcjm/qtcreator,AltarBeastiful/qt-creator,farseerri/git_code,dmik/qt-creator-os2,hdweiss/qt-creator-visualizer,darksylinc/qt-creator,xianian/qt-creator,dmik/qt-creator-os2,sandsmark/qtcreator-minimap,sandsmark/qtcreator-minimap,colede/qtcreator,AltarBeastiful/qt-creator,kuba1/qtcreator,duythanhphan/qt-creator,AltarBeastiful/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,farseerri/git_code,xianian/qt-creator,yinyunqiao/qtcreator,dmik/qt-creator-os2,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,dmik/qt-creator-os2,kuba1/qtcreator,richardmg/qtcreator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,xianian/qt-creator,martyone/sailfish-qtcreator,martyone/sailfish-qtcreator,AltarBeastiful/qt-creator,maui-packages/qt-creator,renatofilho/QtCreator,maui-packages/qt-creator,duythanhphan/qt-creator,pcacjr/qt-creator,syntheticpp/qt-creator,Distrotech/qtcreator,azat/qtcreator,danimo/qt-creator,xianian/qt-creator
33c5095110b9324c082055ad0226b568d7ec8f60
GraphConverter/LoaderABIDE.cpp
GraphConverter/LoaderABIDE.cpp
#include "stdafx.h" #include "LoaderABIDE.h" #include "CheckerFactory.h" using namespace std; const int LoaderABIDE::POS_ID = 6; const int LoaderABIDE::POS_DX = 7; //const std::string LoaderABIDE::filePrefix = "/Outputs/cpac/nofilt_global/"; const std::vector<std::string> LoaderABIDE::header = { "","Unnamed: 0","SUB_ID","X","subject","SITE_ID","FILE_ID","DX_GROUP","DSM_IV_TR","AGE_AT_SCAN", "SEX","HANDEDNESS_CATEGORY","HANDEDNESS_SCORES","FIQ","VIQ","PIQ","FIQ_TEST_TYPE","VIQ_TEST_TYPE","PIQ_TEST_TYPE","ADI_R_SOCIAL_TOTAL_A", "ADI_R_VERBAL_TOTAL_BV","ADI_RRB_TOTAL_C","ADI_R_ONSET_TOTAL_D","ADI_R_RSRCH_RELIABLE","ADOS_MODULE","ADOS_TOTAL","ADOS_COMM","ADOS_SOCIAL","ADOS_STEREO_BEHAV","ADOS_RSRCH_RELIABLE", "ADOS_GOTHAM_SOCAFFECT","ADOS_GOTHAM_RRB","ADOS_GOTHAM_TOTAL","ADOS_GOTHAM_SEVERITY","SRS_VERSION","SRS_RAW_TOTAL","SRS_AWARENESS","SRS_COGNITION","SRS_COMMUNICATION","SRS_MOTIVATION", "SRS_MANNERISMS","SCQ_TOTAL","AQ_TOTAL","COMORBIDITY","CURRENT_MED_STATUS","MEDICATION_NAME","OFF_STIMULANTS_AT_SCAN","VINELAND_RECEPTIVE_V_SCALED","VINELAND_EXPRESSIVE_V_SCALED","VINELAND_WRITTEN_V_SCALED", "VINELAND_COMMUNICATION_STANDARD","VINELAND_PERSONAL_V_SCALED","VINELAND_DOMESTIC_V_SCALED","VINELAND_COMMUNITY_V_SCALED","VINELAND_DAILYLVNG_STANDARD","VINELAND_INTERPERSONAL_V_SCALED","VINELAND_PLAY_V_SCALED","VINELAND_COPING_V_SCALED","VINELAND_SOCIAL_STANDARD","VINELAND_SUM_SCORES", "VINELAND_ABC_STANDARD","VINELAND_INFORMANT","WISC_IV_VCI","WISC_IV_PRI","WISC_IV_WMI","WISC_IV_PSI","WISC_IV_SIM_SCALED","WISC_IV_VOCAB_SCALED","WISC_IV_INFO_SCALED","WISC_IV_BLK_DSN_SCALED", "WISC_IV_PIC_CON_SCALED","WISC_IV_MATRIX_SCALED","WISC_IV_DIGIT_SPAN_SCALED","WISC_IV_LET_NUM_SCALED","WISC_IV_CODING_SCALED","WISC_IV_SYM_SCALED","EYE_STATUS_AT_SCAN","AGE_AT_MPRAGE","BMI","anat_cnr", "anat_efc","anat_fber","anat_fwhm","anat_qi1","anat_snr","func_efc","func_fber","func_fwhm","func_dvars","func_outlier", "func_quality","func_mean_fd","func_num_fd","func_perc_fd","func_gsr","qc_rater_1","qc_notes_rater_1","qc_anat_rater_2","qc_anat_notes_rater_2","qc_func_rater_2", "qc_func_notes_rater_2","qc_anat_rater_3","qc_anat_notes_rater_3","qc_func_rater_3","qc_func_notes_rater_3","SUB_IN_SMP" }; bool LoaderABIDE::FLG_QC_SET = false; std::vector<int> LoaderABIDE::POS_QC; // qc_rater_1, qc_anat_rater_2, qc_func_rater_2, qc_anat_rater_3 void LoaderABIDE::InitPOS_QC() { if(!FLG_QC_SET) { POS_QC = FindOffsets(header, { "qc_rater_1", "qc_anat_rater_2", "qc_func_rater_2", "qc_anat_rater_3" }); FLG_QC_SET = true; } } bool LoaderABIDE::checkHeader(const std::string &line) { int count = 0; for(size_t plast = 0, p = line.find(','); p != string::npos;) { if(line.substr(plast, p - plast) != header[count]) { return false; } plast = p + 1; p = line.find(',', plast); ++count; } return true; } std::vector<SubjectInfo> LoaderABIDE::loadSubjectsFromDescFile( const std::string& fn, const std::string& qcMethod, const int nSubject, const int nSkip) { InitPOS_QC(); string filename(fn); if(filename.find("Phenotypic_V1_0b_preprocessed1") == string::npos) { size_t pos_slash = filename.find_last_of("/\\"); if(pos_slash == filename.length() - 1) { filename += "Phenotypic_V1_0b_preprocessed1.csv"; } else { filename += "/Phenotypic_V1_0b_preprocessed1.csv"; } } ifstream fin(filename); if(!fin) { cerr << "Cannot open phenotype file with given parameter: " << fn << (fn == filename ? "" : ", file: " + filename) << endl; throw invalid_argument("cannot create valid list with given phenotype file location"); } std::string line; getline(fin, line); if(!checkHeader(line)) { cerr << "Header line of file '" << fn << "' is not correct!" << endl; throw invalid_argument("file header does not match that of the specific dataset"); } int limit = nSubject >= 0 ? nSubject + max(0, nSkip) : numeric_limits<int>::max(); QCChecker * pchecker = CheckerFactory::generate(qcMethod, POS_QC.size()); vector<SubjectInfo> res; int cnt = 0; while(getline(fin, line)) { if(++cnt <= nSkip) continue; bool valid; string sid; int type; tie(valid, sid, type) = parsePhenotypeLine(line, pchecker); pchecker->reset(); if(valid) { res.push_back(SubjectInfo{ sid,type }); } if(cnt > limit) break; } fin.close(); return res; } std::vector<SubjectInfo> LoaderABIDE::pruneAndAddScanViaScanFile( std::vector<SubjectInfo>& vldList, const std::string & root) { using namespace boost::filesystem; vector<SubjectInfo> res; res.reserve(vldList.size()); path base(root); if(!exists(base)) { cerr << "Warning: cannot access the given directory for the subject files." << endl; return res; } regex reg(R"(^(\w+_\d{7})_rois_.+?\.1D$)"); set<string> files; for(auto it = directory_iterator(base); it != directory_iterator(); ++it) { smatch m; string fn = it->path().filename().string(); if(regex_match(fn, m, reg)) { files.insert(m[1].str()); } } regex regID(R"(^[\w_]+_(\d{7})$)"); for(SubjectInfo& s : vldList) { auto it = files.find(s.id); if(it==files.end()) continue; smatch m; if(!regex_match(*it, m, regID)) continue; string id = m[1].str(); nameMapping[id] = *it; SubjectInfo si(move(id), s.type, 0); res.push_back(move(si)); } return res; } string LoaderABIDE::getFilePath(const SubjectInfo &sub) { static regex reg(R"(^\d{7}$)"); string fn = sub.id; smatch m; if(regex_match(fn,m,reg)) { fn = nameMapping.at(m[0].str()); } // TODO: handle differnt ROI return fn + "_rois_aal.1D"; } tc_t LoaderABIDE::loadTimeCourse(const std::string &fn) { return loadTimeCourse1D(fn); } std::tuple<bool, std::string, int> LoaderABIDE::parsePhenotypeLine( const std::string &line, QCChecker* pchecker) { std::string id; int dx;// Autism==1, Control==2 static const int minPos = max(POS_ID, POS_DX); static const int maxPos= max(max(POS_ID, POS_DX), *max_element(POS_QC.begin(), POS_QC.end())); size_t plast = 0; size_t p = line.find(','); int count = 0; while(p != string::npos && count <= maxPos && (pchecker->needMore() || count <= minPos)) { if(count == POS_ID) { id = line.substr(plast, p - plast); if(id == "no_filename") { return make_tuple(false, move(id), dx); } } else if(count == POS_DX) { dx = stoi(line.substr(plast, p - plast)); } else if(find(POS_QC.begin(), POS_QC.end(), count) != POS_QC.end()) { if(p != plast) { string x = line.substr(plast, p - plast); pchecker->input(stoi(x) > 0); } else { pchecker->input(); } } plast = p + 1; p = line.find(',', plast); ++count; } // id = padID2Head(id, ID_LENGTH_FILE, PADDING); return make_tuple(pchecker->result(), move(id), dx); }
#include "stdafx.h" #include "LoaderABIDE.h" #include "CheckerFactory.h" using namespace std; const int LoaderABIDE::POS_ID = 6; const int LoaderABIDE::POS_DX = 7; //const std::string LoaderABIDE::filePrefix = "/Outputs/cpac/nofilt_global/"; const std::vector<std::string> LoaderABIDE::header = { "","Unnamed: 0","SUB_ID","X","subject","SITE_ID","FILE_ID","DX_GROUP","DSM_IV_TR","AGE_AT_SCAN", "SEX","HANDEDNESS_CATEGORY","HANDEDNESS_SCORES","FIQ","VIQ","PIQ","FIQ_TEST_TYPE","VIQ_TEST_TYPE","PIQ_TEST_TYPE","ADI_R_SOCIAL_TOTAL_A", "ADI_R_VERBAL_TOTAL_BV","ADI_RRB_TOTAL_C","ADI_R_ONSET_TOTAL_D","ADI_R_RSRCH_RELIABLE","ADOS_MODULE","ADOS_TOTAL","ADOS_COMM","ADOS_SOCIAL","ADOS_STEREO_BEHAV","ADOS_RSRCH_RELIABLE", "ADOS_GOTHAM_SOCAFFECT","ADOS_GOTHAM_RRB","ADOS_GOTHAM_TOTAL","ADOS_GOTHAM_SEVERITY","SRS_VERSION","SRS_RAW_TOTAL","SRS_AWARENESS","SRS_COGNITION","SRS_COMMUNICATION","SRS_MOTIVATION", "SRS_MANNERISMS","SCQ_TOTAL","AQ_TOTAL","COMORBIDITY","CURRENT_MED_STATUS","MEDICATION_NAME","OFF_STIMULANTS_AT_SCAN","VINELAND_RECEPTIVE_V_SCALED","VINELAND_EXPRESSIVE_V_SCALED","VINELAND_WRITTEN_V_SCALED", "VINELAND_COMMUNICATION_STANDARD","VINELAND_PERSONAL_V_SCALED","VINELAND_DOMESTIC_V_SCALED","VINELAND_COMMUNITY_V_SCALED","VINELAND_DAILYLVNG_STANDARD","VINELAND_INTERPERSONAL_V_SCALED","VINELAND_PLAY_V_SCALED","VINELAND_COPING_V_SCALED","VINELAND_SOCIAL_STANDARD","VINELAND_SUM_SCORES", "VINELAND_ABC_STANDARD","VINELAND_INFORMANT","WISC_IV_VCI","WISC_IV_PRI","WISC_IV_WMI","WISC_IV_PSI","WISC_IV_SIM_SCALED","WISC_IV_VOCAB_SCALED","WISC_IV_INFO_SCALED","WISC_IV_BLK_DSN_SCALED", "WISC_IV_PIC_CON_SCALED","WISC_IV_MATRIX_SCALED","WISC_IV_DIGIT_SPAN_SCALED","WISC_IV_LET_NUM_SCALED","WISC_IV_CODING_SCALED","WISC_IV_SYM_SCALED","EYE_STATUS_AT_SCAN","AGE_AT_MPRAGE","BMI","anat_cnr", "anat_efc","anat_fber","anat_fwhm","anat_qi1","anat_snr","func_efc","func_fber","func_fwhm","func_dvars","func_outlier", "func_quality","func_mean_fd","func_num_fd","func_perc_fd","func_gsr","qc_rater_1","qc_notes_rater_1","qc_anat_rater_2","qc_anat_notes_rater_2","qc_func_rater_2", "qc_func_notes_rater_2","qc_anat_rater_3","qc_anat_notes_rater_3","qc_func_rater_3","qc_func_notes_rater_3","SUB_IN_SMP" }; bool LoaderABIDE::FLG_QC_SET = false; std::vector<int> LoaderABIDE::POS_QC; // qc_rater_1, qc_anat_rater_2, qc_func_rater_2, qc_anat_rater_3 void LoaderABIDE::InitPOS_QC() { if(!FLG_QC_SET) { POS_QC = FindOffsets(header, { "qc_rater_1", "qc_anat_rater_2", "qc_func_rater_2", "qc_anat_rater_3" }); FLG_QC_SET = true; } } bool LoaderABIDE::checkHeader(const std::string &line) { int count = 0; for(size_t plast = 0, p = line.find(','); p != string::npos;) { if(line.substr(plast, p - plast) != header[count]) { return false; } plast = p + 1; p = line.find(',', plast); ++count; } return true; } std::vector<SubjectInfo> LoaderABIDE::loadSubjectsFromDescFile( const std::string& fn, const std::string& qcMethod, const int nSubject, const int nSkip) { InitPOS_QC(); string filename(fn); if(filename.find("Phenotypic_V1_0b_preprocessed1") == string::npos) { size_t pos_slash = filename.find_last_of("/\\"); if(pos_slash == filename.length() - 1) { filename += "Phenotypic_V1_0b_preprocessed1.csv"; } else { filename += "/Phenotypic_V1_0b_preprocessed1.csv"; } } ifstream fin(filename); if(!fin) { cerr << "Cannot open phenotype file with given parameter: " << fn << (fn == filename ? "" : ", file: " + filename) << endl; throw invalid_argument("cannot create valid list with given phenotype file location"); } std::string line; getline(fin, line); if(!checkHeader(line)) { cerr << "Header line of file '" << fn << "' is not correct!" << endl; throw invalid_argument("file header does not match that of the specific dataset"); } int limit = nSubject >= 0 ? nSubject + max(0, nSkip) : numeric_limits<int>::max(); QCChecker * pchecker = CheckerFactory::generate(qcMethod, POS_QC.size()); vector<SubjectInfo> res; int cnt = 0; while(getline(fin, line)) { if(++cnt <= nSkip) continue; bool valid; string sid; int type; tie(valid, sid, type) = parsePhenotypeLine(line, pchecker); pchecker->reset(); if(valid) { res.push_back(SubjectInfo{ sid,type }); } if(cnt > limit) break; } fin.close(); return res; } std::vector<SubjectInfo> LoaderABIDE::pruneAndAddScanViaScanFile( std::vector<SubjectInfo>& vldList, const std::string & root) { using namespace boost::filesystem; vector<SubjectInfo> res; res.reserve(vldList.size()); path base(root); if(!exists(base)) { cerr << "Warning: cannot access the given directory for the subject files." << endl; return res; } regex reg(R"(^(\w+_\d{7})_rois_.+?\.1D$)"); set<string> files; for(auto it = directory_iterator(base); it != directory_iterator(); ++it) { smatch m; string fn = it->path().filename().string(); if(regex_match(fn, m, reg)) { files.insert(m[1].str()); } } regex regID(R"(^[\w_]+_(\d{7})$)"); for(SubjectInfo& s : vldList) { auto it = files.find(s.id); if(it==files.end()) continue; smatch m; if(!regex_match(*it, m, regID)) continue; string id = m[1].str(); nameMapping[id] = *it; SubjectInfo si(move(id), s.type, 0); res.push_back(move(si)); } return res; } string LoaderABIDE::getFilePath(const SubjectInfo &sub) { static regex reg(R"(^\d{7}$)"); string fn = sub.id; smatch m; if(regex_match(fn,m,reg)) { fn = nameMapping.at(m[0].str()); } // TODO: handle differnt ROI return fn + "_rois_aal.1D"; } tc_t LoaderABIDE::loadTimeCourse(const std::string &fn) { return loadTimeCourse1D(fn); } std::tuple<bool, std::string, int> LoaderABIDE::parsePhenotypeLine( const std::string &line, QCChecker* pchecker) { std::string id; int dx;// Autism==1, Control==2 static const int minPos = max(POS_ID, POS_DX); static const int maxPos= max(max(POS_ID, POS_DX), *max_element(POS_QC.begin(), POS_QC.end())); size_t plast = 0; size_t p = line.find(','); int count = 0; while(p != string::npos && count <= maxPos && (pchecker->needMore() || count <= minPos)) { if(count == POS_ID) { id = line.substr(plast, p - plast); if(id == "no_filename") { return make_tuple(false, move(id), dx); } } else if(count == POS_DX) { dx = stoi(line.substr(plast, p - plast)); } else if(find(POS_QC.begin(), POS_QC.end(), count) != POS_QC.end()) { if(p != plast) { string x = line.substr(plast, p - plast); pchecker->input(x == "OK"); } else { pchecker->input(); } } plast = p + 1; p = line.find(',', plast); ++count; } // id = padID2Head(id, ID_LENGTH_FILE, PADDING); return make_tuple(pchecker->result(), move(id), dx); }
fix a qc-checker bug for ABIDE loader
fix a qc-checker bug for ABIDE loader
C++
apache-2.0
yxtj/GSDM,yxtj/GSDM,yxtj/GSDM,yxtj/GSDM,yxtj/GSDM
d0abc36a99ff89a190687467e7b4c3df664307f0
IlmBase/IexMath/IexMathFpu.cpp
IlmBase/IexMath/IexMathFpu.cpp
// // Copyright (c) 1997 Industrial Light and Magic. // All rights reserved. Used under authorization. // This material contains the confidential and proprietary // information of Industrial Light and Magic and // may not be copied in whole or in part without the express // written permission of Industrial Light and Magic. // This copyright notice does not imply publication. // //------------------------------------------------------------------------ // // Functions to control floating point exceptions. // //------------------------------------------------------------------------ #include <IexMathFpu.h> #include <IlmBaseConfig.h> #if 0 #include <iostream> #define debug(x) (std::cout << x << std::flush) #else #define debug(x) #endif #ifdef HAVE_UCONTEXT_H #include <ucontext.h> #include <signal.h> #include <iostream> #include <stdint.h> namespace Iex { namespace FpuControl { //------------------------------------------------------------------- // // Modern x86 processors and all AMD64 processors have two // sets of floating-point control/status registers: cw and sw // for legacy x87 stack-based arithmetic, and mxcsr for // SIMD arithmetic. When setting exception masks or checking // for exceptions, we must set/check all relevant registers, // since applications may contain code that uses either FP // model. // // These functions handle both FP models for x86 and AMD64. // //------------------------------------------------------------------- //------------------------------------------------------------------- // // Restore the control register state from a signal handler // user context, optionally clearing the exception bits // in the restored control register, if applicable. // //------------------------------------------------------------------- void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions = false); //------------------------------------------------------------ // // Set exception mask bits in the control register state. // A value of 1 means the exception is masked, a value of // 0 means the exception is enabled. // // setExceptionMask returns the previous mask value. If // the 'exceptions' pointer is non-null, it returns in // this argument the FPU exception bits. // //------------------------------------------------------------ const int INVALID_EXC = (1<<0); const int DENORMAL_EXC = (1<<1); const int DIVZERO_EXC = (1<<2); const int OVERFLOW_EXC = (1<<3); const int UNDERFLOW_EXC = (1<<4); const int INEXACT_EXC = (1<<5); const int ALL_EXC = INVALID_EXC | DENORMAL_EXC | DIVZERO_EXC | OVERFLOW_EXC | UNDERFLOW_EXC | INEXACT_EXC; int setExceptionMask (int mask, int * exceptions = 0); int getExceptionMask (); //--------------------------------------------- // // Get/clear the exception bits in the FPU. // //--------------------------------------------- int getExceptions (); void clearExceptions (); //------------------------------------------------------------------ // // Everything below here is implementation. Do not use these // constants or functions in your applications or libraries. // This is not the code you're looking for. Move along. // // Optimization notes -- on a Pentium 4, at least, it appears // to be faster to get the mxcsr first and then the cw; and to // set the cw first and then the mxcsr. Also, it seems to // be faster to clear the sw exception bits after setting // cw and mxcsr. // //------------------------------------------------------------------ static inline uint16_t getSw () { uint16_t sw; asm volatile ("fnstsw %0" : "=m" (sw) : ); return sw; } static inline void setCw (uint16_t cw) { asm volatile ("fldcw %0" : : "m" (cw) ); } static inline uint16_t getCw () { uint16_t cw; asm volatile ("fnstcw %0" : "=m" (cw) : ); return cw; } static inline void setMxcsr (uint32_t mxcsr, bool clearExceptions) { mxcsr &= clearExceptions ? 0xffffffc0 : 0xffffffff; asm volatile ("ldmxcsr %0" : : "m" (mxcsr) ); } static inline uint32_t getMxcsr () { uint32_t mxcsr; asm volatile ("stmxcsr %0" : "=m" (mxcsr) : ); return mxcsr; } static inline int calcMask (uint16_t cw, uint32_t mxcsr) { // // Hopefully, if the user has been using FpuControl functions, // the masks are the same, but just in case they're not, we // AND them together to report the proper subset of the masks. // return (cw & ALL_EXC) & ((mxcsr >> 7) & ALL_EXC); } inline int setExceptionMask (int mask, int * exceptions) { uint16_t cw = getCw (); uint32_t mxcsr = getMxcsr (); if (exceptions) *exceptions = (mxcsr & ALL_EXC) | (getSw () & ALL_EXC); int oldmask = calcMask (cw, mxcsr); // // The exception constants are chosen very carefully so that // we can do a simple mask and shift operation to insert // them into the control words. The mask operation is for // safety, in case the user accidentally set some other // bits in the exception mask. // mask &= ALL_EXC; cw = (cw & ~ALL_EXC) | mask; mxcsr = (mxcsr & ~(ALL_EXC << 7)) | (mask << 7); setCw (cw); setMxcsr (mxcsr, false); return oldmask; } inline int getExceptionMask () { uint32_t mxcsr = getMxcsr (); uint16_t cw = getCw (); return calcMask (cw, mxcsr); } inline int getExceptions () { return (getMxcsr () | getSw ()) & ALL_EXC; } void clearExceptions () { uint32_t mxcsr = getMxcsr () & 0xffffffc0; asm volatile ("ldmxcsr %0\n" "fnclex" : : "m" (mxcsr) ); } // If the fpe was taken while doing a float-to-int cast using the x87, // the rounding mode and possibly the precision will be wrong. So instead // of restoring to the state as of the fault, we force the rounding mode // to be 'nearest' and the precision to be double extended. // // rounding mode is in bits 10-11, value 00 == round to nearest // precision is in bits 8-9, value 11 == double extended (80-bit) // const uint16_t cwRestoreMask = ~((3 << 10) | (3 << 8)); const uint16_t cwRestoreVal = (0 << 10) | (3 << 8); inline void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions) { setCw ((ucon.uc_mcontext.fpregs->cwd & cwRestoreMask) | cwRestoreVal); setMxcsr (ucon.uc_mcontext.fpregs->mxcsr, clearExceptions); } #if 0 // // Ugly, the mxcsr isn't defined in GNU libc ucontext_t, but // it's passed to the signal handler by the kernel. Use // the kernel's version of the ucontext to get it, see // <asm/sigcontext.h> // #include <asm/sigcontext.h> inline void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions) { setCw ((ucon.uc_mcontext.fpregs->cw & cwRestoreMask) | cwRestoreVal); _fpstate * kfp = reinterpret_cast<_fpstate *> (ucon.uc_mcontext.fpregs); setMxcsr (kfp->magic == 0 ? kfp->mxcsr : 0, clearExceptions); } #endif } // namespace FpuControl namespace { volatile FpExceptionHandler fpeHandler = 0; extern "C" void catchSigFpe (int sig, siginfo_t *info, ucontext_t *ucon) { debug ("catchSigFpe (sig = "<< sig << ", ...)\n"); FpuControl::restoreControlRegs (*ucon, true); if (fpeHandler == 0) return; if (info->si_code == SI_USER) { fpeHandler (0, "Floating-point exception, caused by " "a signal sent from another process."); return; } if (sig == SIGFPE) { switch (info->si_code) { // // IEEE 754 floating point exceptions: // case FPE_FLTDIV: fpeHandler (IEEE_DIVZERO, "Floating-point division by zero."); return; case FPE_FLTOVF: fpeHandler (IEEE_OVERFLOW, "Floating-point overflow."); return; case FPE_FLTUND: fpeHandler (IEEE_UNDERFLOW, "Floating-point underflow."); return; case FPE_FLTRES: fpeHandler (IEEE_INEXACT, "Inexact floating-point result."); return; case FPE_FLTINV: fpeHandler (IEEE_INVALID, "Invalid floating-point operation."); return; // // Other arithmetic exceptions which can also // be trapped by the operating system: // case FPE_INTDIV: fpeHandler (0, "Integer division by zero."); break; case FPE_INTOVF: fpeHandler (0, "Integer overflow."); break; case FPE_FLTSUB: fpeHandler (0, "Subscript out of range."); break; } } fpeHandler (0, "Floating-point exception."); } } // namespace void setFpExceptions (int when) { int mask = FpuControl::ALL_EXC; if (when & IEEE_OVERFLOW) mask &= ~FpuControl::OVERFLOW_EXC; if (when & IEEE_UNDERFLOW) mask &= ~FpuControl::UNDERFLOW_EXC; if (when & IEEE_DIVZERO) mask &= ~FpuControl::DIVZERO_EXC; if (when & IEEE_INEXACT) mask &= ~FpuControl::INEXACT_EXC; if (when & IEEE_INVALID) mask &= ~FpuControl::INVALID_EXC; // // The Linux kernel apparently sometimes passes // incorrect si_info to signal handlers unless // the exception flags are cleared. // // XXX is this still true on 2.4+ kernels? // FpuControl::setExceptionMask (mask); FpuControl::clearExceptions (); } int fpExceptions () { int mask = FpuControl::getExceptionMask (); int when = 0; if (!(mask & FpuControl::OVERFLOW_EXC)) when |= IEEE_OVERFLOW; if (!(mask & FpuControl::UNDERFLOW_EXC)) when |= IEEE_UNDERFLOW; if (!(mask & FpuControl::DIVZERO_EXC)) when |= IEEE_DIVZERO; if (!(mask & FpuControl::INEXACT_EXC)) when |= IEEE_INEXACT; if (!(mask & FpuControl::INVALID_EXC)) when |= IEEE_INVALID; return when; } void handleExceptionsSetInRegisters() { if (fpeHandler == 0) return; int mask = FpuControl::getExceptionMask (); int exc = FpuControl::getExceptions(); if (!(mask & FpuControl::DIVZERO_EXC) && (exc & FpuControl::DIVZERO_EXC)) { fpeHandler(IEEE_DIVZERO, "Floating-point division by zero."); return; } if (!(mask & FpuControl::OVERFLOW_EXC) && (exc & FpuControl::OVERFLOW_EXC)) { fpeHandler(IEEE_OVERFLOW, "Floating-point overflow."); return; } if (!(mask & FpuControl::UNDERFLOW_EXC) && (exc & FpuControl::UNDERFLOW_EXC)) { fpeHandler(IEEE_UNDERFLOW, "Floating-point underflow."); return; } if (!(mask & FpuControl::INEXACT_EXC) && (exc & FpuControl::INEXACT_EXC)) { fpeHandler(IEEE_INEXACT, "Inexact floating-point result."); return; } if (!(mask & FpuControl::INVALID_EXC) && (exc & FpuControl::INVALID_EXC)) { fpeHandler(IEEE_INVALID, "Invalid floating-point operation."); return; } } void setFpExceptionHandler (FpExceptionHandler handler) { if (fpeHandler == 0) { struct sigaction action; sigemptyset (&action.sa_mask); action.sa_flags = SA_SIGINFO | SA_NOMASK; action.sa_sigaction = (void (*) (int, siginfo_t *, void *)) catchSigFpe; action.sa_restorer = 0; sigaction (SIGFPE, &action, 0); } fpeHandler = handler; } } // namespace Iex #else #include <signal.h> #include <assert.h> namespace Iex { namespace { volatile FpExceptionHandler fpeHandler = 0; void fpExc_(int x) { if (fpeHandler != 0) { fpeHandler(x, ""); } else { assert(0 != "Floating point exception"); } } } void setFpExceptions( int ) { } void setFpExceptionHandler (FpExceptionHandler handler) { // improve floating point exception handling nanoscopically above "nothing at all" fpeHandler = handler; signal(SIGFPE, fpExc_); } int fpExceptions() { return 0; } void handleExceptionsSetInRegisters() { // No implementation on this platform } } // namespace Iex #endif
// // Copyright (c) 1997 Industrial Light and Magic. // All rights reserved. Used under authorization. // This material contains the confidential and proprietary // information of Industrial Light and Magic and // may not be copied in whole or in part without the express // written permission of Industrial Light and Magic. // This copyright notice does not imply publication. // //------------------------------------------------------------------------ // // Functions to control floating point exceptions. // //------------------------------------------------------------------------ #include <stdint.h> #include <IexMathFpu.h> #include <IlmBaseConfig.h> #if 0 #include <iostream> #define debug(x) (std::cout << x << std::flush) #else #define debug(x) #endif #ifdef HAVE_UCONTEXT_H #include <ucontext.h> #include <signal.h> #include <iostream> #include <stdint.h> namespace Iex { namespace FpuControl { //------------------------------------------------------------------- // // Modern x86 processors and all AMD64 processors have two // sets of floating-point control/status registers: cw and sw // for legacy x87 stack-based arithmetic, and mxcsr for // SIMD arithmetic. When setting exception masks or checking // for exceptions, we must set/check all relevant registers, // since applications may contain code that uses either FP // model. // // These functions handle both FP models for x86 and AMD64. // //------------------------------------------------------------------- //------------------------------------------------------------------- // // Restore the control register state from a signal handler // user context, optionally clearing the exception bits // in the restored control register, if applicable. // //------------------------------------------------------------------- void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions = false); //------------------------------------------------------------ // // Set exception mask bits in the control register state. // A value of 1 means the exception is masked, a value of // 0 means the exception is enabled. // // setExceptionMask returns the previous mask value. If // the 'exceptions' pointer is non-null, it returns in // this argument the FPU exception bits. // //------------------------------------------------------------ const int INVALID_EXC = (1<<0); const int DENORMAL_EXC = (1<<1); const int DIVZERO_EXC = (1<<2); const int OVERFLOW_EXC = (1<<3); const int UNDERFLOW_EXC = (1<<4); const int INEXACT_EXC = (1<<5); const int ALL_EXC = INVALID_EXC | DENORMAL_EXC | DIVZERO_EXC | OVERFLOW_EXC | UNDERFLOW_EXC | INEXACT_EXC; int setExceptionMask (int mask, int * exceptions = 0); int getExceptionMask (); //--------------------------------------------- // // Get/clear the exception bits in the FPU. // //--------------------------------------------- int getExceptions (); void clearExceptions (); //------------------------------------------------------------------ // // Everything below here is implementation. Do not use these // constants or functions in your applications or libraries. // This is not the code you're looking for. Move along. // // Optimization notes -- on a Pentium 4, at least, it appears // to be faster to get the mxcsr first and then the cw; and to // set the cw first and then the mxcsr. Also, it seems to // be faster to clear the sw exception bits after setting // cw and mxcsr. // //------------------------------------------------------------------ static inline uint16_t getSw () { uint16_t sw; asm volatile ("fnstsw %0" : "=m" (sw) : ); return sw; } static inline void setCw (uint16_t cw) { asm volatile ("fldcw %0" : : "m" (cw) ); } static inline uint16_t getCw () { uint16_t cw; asm volatile ("fnstcw %0" : "=m" (cw) : ); return cw; } static inline void setMxcsr (uint32_t mxcsr, bool clearExceptions) { mxcsr &= clearExceptions ? 0xffffffc0 : 0xffffffff; asm volatile ("ldmxcsr %0" : : "m" (mxcsr) ); } static inline uint32_t getMxcsr () { uint32_t mxcsr; asm volatile ("stmxcsr %0" : "=m" (mxcsr) : ); return mxcsr; } static inline int calcMask (uint16_t cw, uint32_t mxcsr) { // // Hopefully, if the user has been using FpuControl functions, // the masks are the same, but just in case they're not, we // AND them together to report the proper subset of the masks. // return (cw & ALL_EXC) & ((mxcsr >> 7) & ALL_EXC); } inline int setExceptionMask (int mask, int * exceptions) { uint16_t cw = getCw (); uint32_t mxcsr = getMxcsr (); if (exceptions) *exceptions = (mxcsr & ALL_EXC) | (getSw () & ALL_EXC); int oldmask = calcMask (cw, mxcsr); // // The exception constants are chosen very carefully so that // we can do a simple mask and shift operation to insert // them into the control words. The mask operation is for // safety, in case the user accidentally set some other // bits in the exception mask. // mask &= ALL_EXC; cw = (cw & ~ALL_EXC) | mask; mxcsr = (mxcsr & ~(ALL_EXC << 7)) | (mask << 7); setCw (cw); setMxcsr (mxcsr, false); return oldmask; } inline int getExceptionMask () { uint32_t mxcsr = getMxcsr (); uint16_t cw = getCw (); return calcMask (cw, mxcsr); } inline int getExceptions () { return (getMxcsr () | getSw ()) & ALL_EXC; } void clearExceptions () { uint32_t mxcsr = getMxcsr () & 0xffffffc0; asm volatile ("ldmxcsr %0\n" "fnclex" : : "m" (mxcsr) ); } // If the fpe was taken while doing a float-to-int cast using the x87, // the rounding mode and possibly the precision will be wrong. So instead // of restoring to the state as of the fault, we force the rounding mode // to be 'nearest' and the precision to be double extended. // // rounding mode is in bits 10-11, value 00 == round to nearest // precision is in bits 8-9, value 11 == double extended (80-bit) // const uint16_t cwRestoreMask = ~((3 << 10) | (3 << 8)); const uint16_t cwRestoreVal = (0 << 10) | (3 << 8); inline void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions) { setCw ((ucon.uc_mcontext.fpregs->cwd & cwRestoreMask) | cwRestoreVal); setMxcsr (ucon.uc_mcontext.fpregs->mxcsr, clearExceptions); } #if 0 // // Ugly, the mxcsr isn't defined in GNU libc ucontext_t, but // it's passed to the signal handler by the kernel. Use // the kernel's version of the ucontext to get it, see // <asm/sigcontext.h> // #include <asm/sigcontext.h> inline void restoreControlRegs (const ucontext_t & ucon, bool clearExceptions) { setCw ((ucon.uc_mcontext.fpregs->cw & cwRestoreMask) | cwRestoreVal); _fpstate * kfp = reinterpret_cast<_fpstate *> (ucon.uc_mcontext.fpregs); setMxcsr (kfp->magic == 0 ? kfp->mxcsr : 0, clearExceptions); } #endif } // namespace FpuControl namespace { volatile FpExceptionHandler fpeHandler = 0; extern "C" void catchSigFpe (int sig, siginfo_t *info, ucontext_t *ucon) { debug ("catchSigFpe (sig = "<< sig << ", ...)\n"); FpuControl::restoreControlRegs (*ucon, true); if (fpeHandler == 0) return; if (info->si_code == SI_USER) { fpeHandler (0, "Floating-point exception, caused by " "a signal sent from another process."); return; } if (sig == SIGFPE) { switch (info->si_code) { // // IEEE 754 floating point exceptions: // case FPE_FLTDIV: fpeHandler (IEEE_DIVZERO, "Floating-point division by zero."); return; case FPE_FLTOVF: fpeHandler (IEEE_OVERFLOW, "Floating-point overflow."); return; case FPE_FLTUND: fpeHandler (IEEE_UNDERFLOW, "Floating-point underflow."); return; case FPE_FLTRES: fpeHandler (IEEE_INEXACT, "Inexact floating-point result."); return; case FPE_FLTINV: fpeHandler (IEEE_INVALID, "Invalid floating-point operation."); return; // // Other arithmetic exceptions which can also // be trapped by the operating system: // case FPE_INTDIV: fpeHandler (0, "Integer division by zero."); break; case FPE_INTOVF: fpeHandler (0, "Integer overflow."); break; case FPE_FLTSUB: fpeHandler (0, "Subscript out of range."); break; } } fpeHandler (0, "Floating-point exception."); } } // namespace void setFpExceptions (int when) { int mask = FpuControl::ALL_EXC; if (when & IEEE_OVERFLOW) mask &= ~FpuControl::OVERFLOW_EXC; if (when & IEEE_UNDERFLOW) mask &= ~FpuControl::UNDERFLOW_EXC; if (when & IEEE_DIVZERO) mask &= ~FpuControl::DIVZERO_EXC; if (when & IEEE_INEXACT) mask &= ~FpuControl::INEXACT_EXC; if (when & IEEE_INVALID) mask &= ~FpuControl::INVALID_EXC; // // The Linux kernel apparently sometimes passes // incorrect si_info to signal handlers unless // the exception flags are cleared. // // XXX is this still true on 2.4+ kernels? // FpuControl::setExceptionMask (mask); FpuControl::clearExceptions (); } int fpExceptions () { int mask = FpuControl::getExceptionMask (); int when = 0; if (!(mask & FpuControl::OVERFLOW_EXC)) when |= IEEE_OVERFLOW; if (!(mask & FpuControl::UNDERFLOW_EXC)) when |= IEEE_UNDERFLOW; if (!(mask & FpuControl::DIVZERO_EXC)) when |= IEEE_DIVZERO; if (!(mask & FpuControl::INEXACT_EXC)) when |= IEEE_INEXACT; if (!(mask & FpuControl::INVALID_EXC)) when |= IEEE_INVALID; return when; } void handleExceptionsSetInRegisters() { if (fpeHandler == 0) return; int mask = FpuControl::getExceptionMask (); int exc = FpuControl::getExceptions(); if (!(mask & FpuControl::DIVZERO_EXC) && (exc & FpuControl::DIVZERO_EXC)) { fpeHandler(IEEE_DIVZERO, "Floating-point division by zero."); return; } if (!(mask & FpuControl::OVERFLOW_EXC) && (exc & FpuControl::OVERFLOW_EXC)) { fpeHandler(IEEE_OVERFLOW, "Floating-point overflow."); return; } if (!(mask & FpuControl::UNDERFLOW_EXC) && (exc & FpuControl::UNDERFLOW_EXC)) { fpeHandler(IEEE_UNDERFLOW, "Floating-point underflow."); return; } if (!(mask & FpuControl::INEXACT_EXC) && (exc & FpuControl::INEXACT_EXC)) { fpeHandler(IEEE_INEXACT, "Inexact floating-point result."); return; } if (!(mask & FpuControl::INVALID_EXC) && (exc & FpuControl::INVALID_EXC)) { fpeHandler(IEEE_INVALID, "Invalid floating-point operation."); return; } } void setFpExceptionHandler (FpExceptionHandler handler) { if (fpeHandler == 0) { struct sigaction action; sigemptyset (&action.sa_mask); action.sa_flags = SA_SIGINFO | SA_NOMASK; action.sa_sigaction = (void (*) (int, siginfo_t *, void *)) catchSigFpe; action.sa_restorer = 0; sigaction (SIGFPE, &action, 0); } fpeHandler = handler; } } // namespace Iex #else #include <signal.h> #include <assert.h> namespace Iex { namespace { volatile FpExceptionHandler fpeHandler = 0; void fpExc_(int x) { if (fpeHandler != 0) { fpeHandler(x, ""); } else { assert(0 != "Floating point exception"); } } } void setFpExceptions( int ) { } void setFpExceptionHandler (FpExceptionHandler handler) { // improve floating point exception handling nanoscopically above "nothing at all" fpeHandler = handler; signal(SIGFPE, fpExc_); } int fpExceptions() { return 0; } void handleExceptionsSetInRegisters() { // No implementation on this platform } } // namespace Iex #endif
Fix build with gcc-4.7
Fix build with gcc-4.7
C++
bsd-3-clause
oglops/PyIlmBase,oglops/IlmBase,oglops/OpenEXR,oglops/PyIlmBase,oglops/OpenEXR,oglops/PyIlmBase,oglops/PyIlmBase,oglops/IlmBase,oglops/IlmBase,oglops/OpenEXR
8dd3a0bdad83f5bc41ebeb3ff803599c3101b743
tests/Clone.cpp
tests/Clone.cpp
#include "TestHelpers.h" #include <QCoreApplication> #include <QTimer> #include <iostream> #include <bitset> #include "qgitcommit.h" #include "qgitrepository.h" using namespace LibQGit2; class TestClone : public QObject { Q_OBJECT public: TestClone(); public slots: void cloneProgress(int p) { m_clone_progress = p; if (p % 20 == 0) { qDebug() << qPrintable(QString("Progress : %1%").arg(p)); } } private slots: void fileProtocol(); void gitProtocol(); void httpProtocol(); void httpsProtocol(); private: int m_clone_progress; const QString testdir; void clone(const QString& url); }; TestClone::TestClone() : testdir(VALUE_TO_STR(TEST_DIR)) { } void TestClone::clone(const QString& url) { LibQGit2::Repository repo; connect(&repo, SIGNAL(cloneProgress(int)), this, SLOT(cloneProgress(int))); QString dirname = url; dirname.replace(":", ""); dirname.replace("//", "/"); dirname.replace("//", "/"); dirname.replace("/", "_"); dirname.replace(".", "_"); const QString repoPath = testdir + "/clone_test/" + dirname; removeDir(repoPath); sleep::ms(500); m_clone_progress = 0; qDebug() << "Cloning " << url; try { repo.clone(url, repoPath); } catch (const LibQGit2::Exception& ex) { QFAIL(ex.what()); } QCOMPARE(m_clone_progress, 100); } void TestClone::fileProtocol() { clone("file:///" + VALUE_TO_QSTR(TEST_EXISTING_REPOSITORY) + "/.git"); } void TestClone::gitProtocol() { clone("git://anongit.kde.org/libqgit2"); } void TestClone::httpProtocol() { clone("http://anongit.kde.org/libqgit2"); } void TestClone::httpsProtocol() { clone("https://github.com/lgiordani/libqgit2.git"); } QTEST_MAIN(TestClone); #include "Clone.moc"
/****************************************************************************** * Copyright (C) 2014 Peter Kmmel <[email protected]> * * Permission to use, copy, modify, and distribute the software * and its documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appear in all * copies and that both that the copyright notice and this * permission notice and warranty disclaimer appear in supporting * documentation, and that the name of the author not be used in * advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * * The author disclaim all warranties with regard to this * software, including all implied warranties of merchantability * and fitness. In no event shall the author be liable for any * special, indirect or consequential damages or any damages * whatsoever resulting from loss of use, data or profits, whether * in an action of contract, negligence or other tortious action, * arising out of or in connection with the use or performance of * this software. */ #include "TestHelpers.h" #include <QCoreApplication> #include <QTimer> #include <iostream> #include <bitset> #include "qgitcommit.h" #include "qgitrepository.h" using namespace LibQGit2; class TestClone : public QObject { Q_OBJECT public: TestClone(); public slots: void cloneProgress(int p) { m_clone_progress = p; if (p % 20 == 0) { qDebug() << qPrintable(QString("Progress : %1%").arg(p)); } } private slots: void fileProtocol(); void gitProtocol(); void httpProtocol(); void httpsProtocol(); private: int m_clone_progress; const QString testdir; void clone(const QString& url); }; TestClone::TestClone() : testdir(VALUE_TO_STR(TEST_DIR)) { } void TestClone::clone(const QString& url) { LibQGit2::Repository repo; connect(&repo, SIGNAL(cloneProgress(int)), this, SLOT(cloneProgress(int))); QString dirname = url; dirname.replace(":", ""); dirname.replace("//", "/"); dirname.replace("//", "/"); dirname.replace("/", "_"); dirname.replace(".", "_"); const QString repoPath = testdir + "/clone_test/" + dirname; removeDir(repoPath); sleep::ms(500); m_clone_progress = 0; qDebug() << "Cloning " << url; try { repo.clone(url, repoPath); } catch (const LibQGit2::Exception& ex) { QFAIL(ex.what()); } QCOMPARE(m_clone_progress, 100); } void TestClone::fileProtocol() { clone("file:///" + VALUE_TO_QSTR(TEST_EXISTING_REPOSITORY) + "/.git"); } void TestClone::gitProtocol() { clone("git://anongit.kde.org/libqgit2"); } void TestClone::httpProtocol() { clone("http://anongit.kde.org/libqgit2"); } void TestClone::httpsProtocol() { clone("https://github.com/lgiordani/libqgit2.git"); } QTEST_MAIN(TestClone); #include "Clone.moc"
Use MIT license for the test code
Use MIT license for the test code
C++
lgpl-2.1
pav0n/libqgit2,KDE/libqgit2,KDE/libqgit2,syntheticpp/libqgit2,syntheticpp/libqgit2,pav0n/libqgit2
7b7f8885c8de08b940ca46aeec3bc278c3855473
src/import/hwpf/fapi2/include/fapi2_vpd_access.H
src/import/hwpf/fapi2/include/fapi2_vpd_access.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_vpd_access.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file fapi2_vpd_access.H /// @brief Common file that defines the vpd access functions that /// platform code must implement. /// // #ifndef _FAPI2_VPDACCESS_H_ #define _FAPI2_VPDACCESS_H_ #include <return_code.H> #include <target_types.H> #include <vpd_access_defs.H> #include <plat_vpd_access.H> namespace fapi2 { /// constants for VPD Info constexpr uint64_t VPD_INFO_INVALID_64 = 0xffffffffffffffff; constexpr uint64_t VPD_INFO_INVALID_16 = 0xffff; constexpr uint64_t VPD_INFO_INVALID_8 = 0xff; /// @brief Specialized class representing required VPDInfo to be used /// in collecting VPD for the MCS target type. /// @tparam T fapi2::TARGET_TYPE_MCS template<> class VPDInfo<TARGET_TYPE_MCS> { public: /// @brief VPDInfo constructor /// @param[in] i_vpd_type Type of VPD data to return VPDInfo( const fapi2::MemVpdData& i_vpd_type) : iv_vpd_type(i_vpd_type), iv_size(VPD_INFO_INVALID_64), iv_freq_mhz(VPD_INFO_INVALID_64), iv_rank_count_dimm_0(VPD_INFO_INVALID_64), iv_rank_count_dimm_1(VPD_INFO_INVALID_64), iv_is_config_ffdc_enabled(true) {}; // type of vpd field to return fapi2::MemVpdData_t iv_vpd_type; // size of the vpd data size_t iv_size; // frequency of memory bus uint64_t iv_freq_mhz; // number of ranks per dimm position uint64_t iv_rank_count_dimm_0; uint64_t iv_rank_count_dimm_1; // set to false to avoid collecting a real ReturnCode bool iv_is_config_ffdc_enabled; }; /// @brief Specialized class representing required VPDInfo to be used /// in collecting VPD for the OCMB_CHIP target type. /// @tparam T fapi2::TARGET_TYPE_OCMB_CHIP template<> class VPDInfo<TARGET_TYPE_OCMB_CHIP> { public: /// @brief VPDInfo constructor /// @param[in] i_vpd_type Type of VPD data to return VPDInfo( const fapi2::MemVpdData& i_vpd_type) : iv_vpd_type(i_vpd_type), iv_size(VPD_INFO_INVALID_64), iv_omi_freq_mhz(VPD_INFO_INVALID_64), iv_rank(VPD_INFO_INVALID_64), iv_is_config_ffdc_enabled(true), iv_efd_type(VPD_INFO_INVALID_8), iv_dmb_mfg_id(VPD_INFO_INVALID_16), iv_dmb_revision(VPD_INFO_INVALID_8), iv_ddr_mode(VPD_INFO_INVALID_8) {}; // *** INPUT DATA *** // type of vpd field to return fapi2::MemVpdData_t iv_vpd_type; // size of the vpd data in bytes size_t iv_size; // frequency of attached OMI bus uint64_t iv_omi_freq_mhz; // rank for which settings are valid uint64_t iv_rank; // set to false to avoid collecting a real ReturnCode bool iv_is_config_ffdc_enabled; // *** OUTPUT DATA *** // metadata describing the EFD data that was returned uint8_t iv_efd_type; // e.g. byte 288 of DDIMM SPD uint16_t iv_dmb_mfg_id; // buffer manufacturer uint8_t iv_dmb_revision; // buffer revision uint8_t iv_ddr_mode; // DDR4 or DDR5 }; /// @brief Return a blob of memory VPD data associated with the input target /// @param[in] i_target a valid fapi2 target /// @param[in] io_vpd_info fapi2::VPDInfo class that specifies which piece of data to return /// @param[out] o_blob the blob of raw data from the vpd /// @return FAPI2_RC_SUCCESS if there's no problem /// @note passing nullptr for o_blob will return the size of the keyword /// /// Example: /// fapi2::VPDInfo<fapi2::TARGET_TYPE_MCS> vpdInfo(MR_keyword); /// vpdInfo.iv_freq = 2667; /// /// uint8_t * blob = NULL; /// /// FAPI_TRY(getVPD( mcs, vpdInfo, blob )); /// blob = static_cast<uint8_t *>(malloc(vpdInfo.iv_size)); /// FAPI_TRY(getVPD( mcs, vpdInfo, blob )); /// blob now contains the VPD data for the MCS. /// template<TargetType T, MulticastType M, typename V> ReturnCode getVPD(const Target<T, M, V>& i_target, VPDInfo<T>& io_vpd_info, uint8_t* o_blob); }; #endif
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/fapi2_vpd_access.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file fapi2_vpd_access.H /// @brief Common file that defines the vpd access functions that /// platform code must implement. /// // #ifndef _FAPI2_VPDACCESS_H_ #define _FAPI2_VPDACCESS_H_ #include <return_code.H> #include <target_types.H> #include <vpd_access_defs.H> #include <plat_vpd_access.H> namespace fapi2 { /// constants for VPD Info constexpr uint64_t VPD_INFO_INVALID_64 = 0xffffffffffffffff; constexpr uint64_t VPD_INFO_INVALID_16 = 0xffff; constexpr uint64_t VPD_INFO_INVALID_8 = 0xff; /// @brief Specialized class representing required VPDInfo to be used /// in collecting VPD for the MCS target type. /// @tparam T fapi2::TARGET_TYPE_MCS template<> class VPDInfo<TARGET_TYPE_MCS> { public: /// @brief VPDInfo constructor /// @param[in] i_vpd_type Type of VPD data to return VPDInfo( const fapi2::MemVpdData& i_vpd_type) : iv_vpd_type(i_vpd_type), iv_size(VPD_INFO_INVALID_64), iv_freq_mhz(VPD_INFO_INVALID_64), iv_rank_count_dimm_0(VPD_INFO_INVALID_64), iv_rank_count_dimm_1(VPD_INFO_INVALID_64), iv_is_config_ffdc_enabled(true) {}; // type of vpd field to return fapi2::MemVpdData_t iv_vpd_type; // size of the vpd data size_t iv_size; // frequency of memory bus uint64_t iv_freq_mhz; // number of ranks per dimm position uint64_t iv_rank_count_dimm_0; uint64_t iv_rank_count_dimm_1; // set to false to avoid collecting a real ReturnCode bool iv_is_config_ffdc_enabled; }; /// @brief Specialized class representing required VPDInfo to be used /// in collecting VPD for the OCMB_CHIP target type. /// @tparam T fapi2::TARGET_TYPE_OCMB_CHIP template<> class VPDInfo<TARGET_TYPE_OCMB_CHIP> { public: /// @brief VPDInfo constructor /// @param[in] i_vpd_type Type of VPD data to return VPDInfo( const fapi2::MemVpdData& i_vpd_type) : iv_vpd_type(i_vpd_type), iv_size(VPD_INFO_INVALID_64), iv_omi_freq_mhz(VPD_INFO_INVALID_64), iv_rank(VPD_INFO_INVALID_64), iv_is_config_ffdc_enabled(true), iv_efd_type(VPD_INFO_INVALID_8), iv_dmb_mfg_id(VPD_INFO_INVALID_16), iv_dmb_revision(VPD_INFO_INVALID_8), iv_ddr_mode(VPD_INFO_INVALID_8), iv_dimm_count(VPD_INFO_INVALID_64), iv_total_ranks_dimm0(VPD_INFO_INVALID_64), iv_total_ranks_dimm1(VPD_INFO_INVALID_64), iv_dimm_type(VPD_INFO_INVALID_64) {}; // *** INPUT DATA *** // type of vpd field to return fapi2::MemVpdData_t iv_vpd_type; // size of the vpd data in bytes size_t iv_size; // frequency of attached OMI bus uint64_t iv_omi_freq_mhz; // rank for which settings are valid uint64_t iv_rank; // set to false to avoid collecting a real ReturnCode bool iv_is_config_ffdc_enabled; // *** OUTPUT DATA *** // metadata describing the EFD data that was returned uint8_t iv_efd_type; // e.g. byte 288 of DDIMM SPD uint16_t iv_dmb_mfg_id; // buffer manufacturer uint8_t iv_dmb_revision; // buffer revision uint8_t iv_ddr_mode; // DDR4 or DDR5 // total number of DIMMs attached uint64_t iv_dimm_count; // total number of ranks on each of the DIMMs attached uint64_t iv_total_ranks_dimm0; uint64_t iv_total_ranks_dimm1; // DIMM type encoding, matches 'DIMMs Supported' byte 7 in EFD: // (bits numbered right to left) // bit7: reserved, code as 0 // bit6: '1' if the DIMM is 3DS // bit5: '1' if the DIMM supports DDP // bit4: '1' if the DIMM supports quad rank mode // bits3,2: b00 for UDIMM, b01 for RDIMM // bit1: '1' for DIMM in slot 1 // bit0: '1' for DIMM in slot 0 uint64_t iv_dimm_type; }; /// @brief Return a blob of memory VPD data associated with the input target /// @param[in] i_target a valid fapi2 target /// @param[in] io_vpd_info fapi2::VPDInfo class that specifies which piece of data to return /// @param[out] o_blob the blob of raw data from the vpd /// @return FAPI2_RC_SUCCESS if there's no problem /// @note passing nullptr for o_blob will return the size of the keyword /// /// Example: /// fapi2::VPDInfo<fapi2::TARGET_TYPE_MCS> vpdInfo(MR_keyword); /// vpdInfo.iv_freq = 2667; /// /// uint8_t * blob = NULL; /// /// FAPI_TRY(getVPD( mcs, vpdInfo, blob )); /// blob = static_cast<uint8_t *>(malloc(vpdInfo.iv_size)); /// FAPI_TRY(getVPD( mcs, vpdInfo, blob )); /// blob now contains the VPD data for the MCS. /// template<TargetType T, MulticastType M, typename V> ReturnCode getVPD(const Target<T, M, V>& i_target, VPDInfo<T>& io_vpd_info, uint8_t* o_blob); }; #endif
Add fields in VPDInfo to support planar SPD lookup
Add fields in VPDInfo to support planar SPD lookup The new fields in the VPDInfo class are filled in by memory HWPs on a planar memory system and used by ddimm_get_efd to look up the correct EFD section for a given ISDIMM config Change-Id: I180c6f8585ac3f9200ae4ba1be0aaf46905ef218 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/138108 Tested-by: PPE CI <[email protected]> Tested-by: Jenkins Server <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Tested-by: FSP CI Jenkins <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: Sumit Kumar <[email protected]> Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/138118 Tested-by: Jenkins OP Build CI <[email protected]> Tested-by: Jenkins Combined Simics CI <[email protected]> Tested-by: Jenkins OP HW <[email protected]> Reviewed-by: Daniel M Crowell <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
4a58b629ce48679bdec9dd1c2ee8c40e865dc6d4
toml/traits.hpp
toml/traits.hpp
// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_TRAITS_HPP #define TOML11_TRAITS_HPP #include <type_traits> #include <utility> #include <chrono> #include <tuple> namespace toml { class value; // forward decl namespace detail { template<typename T> using unwrap_t = typename std::decay<T>::type; // --------------------------------------------------------------------------- // check whether type T is a kind of container/map class struct has_iterator_impl { template<typename T> static std::true_type check(typename T::iterator*); template<typename T> static std::false_type check(...); }; struct has_value_type_impl { template<typename T> static std::true_type check(typename T::value_type*); template<typename T> static std::false_type check(...); }; struct has_key_type_impl { template<typename T> static std::true_type check(typename T::key_type*); template<typename T> static std::false_type check(...); }; struct has_mapped_type_impl { template<typename T> static std::true_type check(typename T::mapped_type*); template<typename T> static std::false_type check(...); }; struct has_resize_method_impl { constexpr static std::size_t dummy=0; template<typename T> static std::true_type check(decltype(std::declval<T>().resize(dummy))*); template<typename T> static std::false_type check(...); }; struct has_from_toml_method_impl { template<typename T> static std::true_type check( decltype(std::declval<T>().from_toml(std::declval<::toml::value>()))*); template<typename T> static std::false_type check(...); }; struct has_into_toml_method_impl { template<typename T> static std::true_type check(decltype(std::declval<T>().into_toml())*); template<typename T> static std::false_type check(...); }; /// Intel C++ compiler can not use decltype in parent class declaration, here /// is a hack to work around it. https://stackoverflow.com/a/23953090/4692076 #ifdef __INTEL_COMPILER #define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type #endif template<typename T> struct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){}; template<typename T> struct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){}; template<typename T> struct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){}; template<typename T> struct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){}; template<typename T> struct has_resize_method : decltype(has_resize_method_impl::check<T>(nullptr)){}; template<typename T> struct has_from_toml_method : decltype(has_from_toml_method_impl::check<T>(nullptr)){}; template<typename T> struct has_into_toml_method : decltype(has_into_toml_method_impl::check<T>(nullptr)){}; #ifdef __INTEL_COMPILER #undef decltype(...) #endif // --------------------------------------------------------------------------- // C++17 and/or/not template<typename ...> struct conjunction : std::true_type{}; template<typename T> struct conjunction<T> : T{}; template<typename T, typename ... Ts> struct conjunction<T, Ts...> : std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type {}; template<typename ...> struct disjunction : std::false_type{}; template<typename T> struct disjunction<T> : T {}; template<typename T, typename ... Ts> struct disjunction<T, Ts...> : std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type {}; template<typename T> struct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{}; // --------------------------------------------------------------------------- // normal type checker template<typename T> struct is_std_pair : std::false_type{}; template<typename T1, typename T2> struct is_std_pair<std::pair<T1, T2>> : std::true_type{}; template<typename T> struct is_std_tuple : std::false_type{}; template<typename ... Ts> struct is_std_tuple<std::tuple<Ts...>> : std::true_type{}; template<typename T> struct is_chrono_duration: std::false_type{}; template<typename Rep, typename Period> struct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{}; // --------------------------------------------------------------------------- // C++14 index_sequence template<std::size_t ... Ns> struct index_sequence{}; template<typename IS, std::size_t N> struct push_back_index_sequence{}; template<std::size_t N, std::size_t ... Ns> struct push_back_index_sequence<index_sequence<Ns...>, N> { typedef index_sequence<Ns..., N> type; }; template<std::size_t N> struct index_sequence_maker { typedef typename push_back_index_sequence< typename index_sequence_maker<N-1>::type, N>::type type; }; template<> struct index_sequence_maker<0> { typedef index_sequence<0> type; }; template<std::size_t N> using make_index_sequence = typename index_sequence_maker<N-1>::type; // --------------------------------------------------------------------------- // return_type_of_t #if __cplusplus >= 201703L template<typename F, typename ... Args> using return_type_of_t = std::invoke_result_t<F, Args...>; #else // result_of is deprecated after C++17 template<typename F, typename ... Args> using return_type_of_t = typename std::result_of<F(Args...)>::type; #endif }// detail }//toml #endif // TOML_TRAITS
// Copyright Toru Niina 2017. // Distributed under the MIT License. #ifndef TOML11_TRAITS_HPP #define TOML11_TRAITS_HPP #include <type_traits> #include <utility> #include <chrono> #include <tuple> namespace toml { class value; // forward decl namespace detail { template<typename T> using unwrap_t = typename std::decay<T>::type; // --------------------------------------------------------------------------- // check whether type T is a kind of container/map class struct has_iterator_impl { template<typename T> static std::true_type check(typename T::iterator*); template<typename T> static std::false_type check(...); }; struct has_value_type_impl { template<typename T> static std::true_type check(typename T::value_type*); template<typename T> static std::false_type check(...); }; struct has_key_type_impl { template<typename T> static std::true_type check(typename T::key_type*); template<typename T> static std::false_type check(...); }; struct has_mapped_type_impl { template<typename T> static std::true_type check(typename T::mapped_type*); template<typename T> static std::false_type check(...); }; struct has_resize_method_impl { constexpr static std::size_t dummy=0; template<typename T> static std::true_type check(decltype(std::declval<T>().resize(dummy))*); template<typename T> static std::false_type check(...); }; struct has_from_toml_method_impl { template<typename T> static std::true_type check( decltype(std::declval<T>().from_toml(std::declval<::toml::value>()))*); template<typename T> static std::false_type check(...); }; struct has_into_toml_method_impl { template<typename T> static std::true_type check(decltype(std::declval<T>().into_toml())*); template<typename T> static std::false_type check(...); }; /// Intel C++ compiler can not use decltype in parent class declaration, here /// is a hack to work around it. https://stackoverflow.com/a/23953090/4692076 #ifdef __INTEL_COMPILER #define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type #endif template<typename T> struct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){}; template<typename T> struct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){}; template<typename T> struct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){}; template<typename T> struct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){}; template<typename T> struct has_resize_method : decltype(has_resize_method_impl::check<T>(nullptr)){}; template<typename T> struct has_from_toml_method : decltype(has_from_toml_method_impl::check<T>(nullptr)){}; template<typename T> struct has_into_toml_method : decltype(has_into_toml_method_impl::check<T>(nullptr)){}; #ifdef __INTEL_COMPILER #undef decltype(...) #endif // --------------------------------------------------------------------------- // C++17 and/or/not template<typename ...> struct conjunction : std::true_type{}; template<typename T> struct conjunction<T> : T{}; template<typename T, typename ... Ts> struct conjunction<T, Ts...> : std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type {}; template<typename ...> struct disjunction : std::false_type{}; template<typename T> struct disjunction<T> : T {}; template<typename T, typename ... Ts> struct disjunction<T, Ts...> : std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type {}; template<typename T> struct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{}; // --------------------------------------------------------------------------- // normal type checker template<typename T> struct is_std_pair : std::false_type{}; template<typename T1, typename T2> struct is_std_pair<std::pair<T1, T2>> : std::true_type{}; template<typename T> struct is_std_tuple : std::false_type{}; template<typename ... Ts> struct is_std_tuple<std::tuple<Ts...>> : std::true_type{}; template<typename T> struct is_chrono_duration: std::false_type{}; template<typename Rep, typename Period> struct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{}; // --------------------------------------------------------------------------- // C++14 index_sequence template<std::size_t ... Ns> struct index_sequence{}; template<typename IS, std::size_t N> struct push_back_index_sequence{}; template<std::size_t N, std::size_t ... Ns> struct push_back_index_sequence<index_sequence<Ns...>, N> { typedef index_sequence<Ns..., N> type; }; template<std::size_t N> struct index_sequence_maker { typedef typename push_back_index_sequence< typename index_sequence_maker<N-1>::type, N>::type type; }; template<> struct index_sequence_maker<0> { typedef index_sequence<0> type; }; template<std::size_t N> using make_index_sequence = typename index_sequence_maker<N-1>::type; // --------------------------------------------------------------------------- // return_type_of_t #if __cplusplus >= 201703L template<typename F, typename ... Args> using return_type_of_t = std::invoke_result_t<F, Args...>; #else // result_of is deprecated after C++17 template<typename F, typename ... Args> using return_type_of_t = typename std::result_of<F(Args...)>::type; #endif // --------------------------------------------------------------------------- // is_string_literal // // to use this, pass `typename remove_reference<T>::type` to T. template<typename T> struct is_string_literal: disjunction< std::is_same<const char*, T>, conjunction< std::is_array<T>, std::is_same<const char, typename std::remove_extent<T>::type> > >{}; }// detail }//toml #endif // TOML_TRAITS
add a way to check arg is "string literal"
feat: add a way to check arg is "string literal"
C++
mit
ToruNiina/toml11
bd298e8984bf1360ffc975d759ae55d02bd1185c
type_traits.hpp
type_traits.hpp
#ifndef HMLIB_TYPETRAITS_INC #define HMLIB_TYPETRAITS_INC 100 # #include<type_traits> #include<iterator> namespace hmLib{ template<typename type1, typename type2> struct select_derived{ template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value> struct check{ using ans_type = void; }; template<typename type> struct check<type, true, false>{ using ans_type = type2; }; template<typename type> struct check<type, false, true>{ using ans_type = type1; }; using type = typename check<void>::ans_type; }; template<typename terget, typename... others> struct near_base_of{ template<typename terget_, typename candidate_> struct check{ using ans_type = candidate_; }; using type = typename check<terget, void>::ans_type; }; template<typename terget, typename try_type, typename... others> struct near_base_of<terget, try_type, others...>{ template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value> struct check{ using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type; }; template<typename terget_, typename candidate_> struct check<terget_, candidate_, true>{ using new_candidate = typename select_derived<candidate_, try_type>::type; using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type; }; template<typename terget_> struct check<terget_, void, true>{ using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type; }; using type = typename check<terget, void>::ans_type; }; namespace detail { struct has_begin_and_end_impl { template <class T> static auto check(T&& x)->decltype(x.begin(), x.end(), std::true_type{}); template <class T> static auto check(...)->std::false_type; }; } template <class T> class has_begin_and_end :public decltype(detail::has_begin_and_end_impl::check<T>(std::declval<T>())) {}; template<typename iterator> using is_const_iterator = typename std::is_const< typename std::remove_reference<typename std::iterator_traits<iterator>::reference>::type >::type; } # #endif
#ifndef HMLIB_TYPETRAITS_INC #define HMLIB_TYPETRAITS_INC 100 # #include<type_traits> #include<iterator> namespace hmLib{ template<typename type1, typename type2> struct select_derived{ template<typename type, bool Type1IsBase = std::is_base_of<type1,type2>::value, bool Type2IsBase = std::is_base_of<type2, type1>::value> struct check{ using ans_type = void; }; template<typename type> struct check<type, true, false>{ using ans_type = type2; }; template<typename type> struct check<type, false, true>{ using ans_type = type1; }; using type = typename check<void>::ans_type; }; template<typename terget, typename... others> struct near_base_of{ template<typename terget_, typename candidate_> struct check{ using ans_type = candidate_; }; using type = typename check<terget, void>::ans_type; }; template<typename terget, typename try_type, typename... others> struct near_base_of<terget, try_type, others...>{ template<typename terget_, typename candidate_, bool IsBase = std::is_base_of<try_type, terget>::value> struct check{ using ans_type = typename near_base_of<terget, others...>::template check<terget_, candidate_>::ans_type; }; template<typename terget_, typename candidate_> struct check<terget_, candidate_, true>{ using new_candidate = typename select_derived<candidate_, try_type>::type; using ans_type = typename near_base_of<terget, others...>::template check<terget_, new_candidate>::ans_type; }; template<typename terget_> struct check<terget_, void, true>{ using ans_type = typename near_base_of<terget, others...>::template check<terget_, try_type>::ans_type; }; using type = typename check<terget, void>::ans_type; }; template <typename T> struct has_begin_and_end { private: template <class U> static auto check(U&& x)->decltype(x.begin(), x.end(), std::true_type{}); static auto check(...)->std::false_type; public: using type = decltype(check(std::declval<typename std::decay<T>::type>())); constexpr static bool value = type::value; }; template<typename T> struct is_iterator{ private: template<typename U> static auto check(U&&)->decltype(typename std::iterator_traits<U>::iterator_category{}, std::true_type{}); static auto check(...)->std::false_type; public: using type = decltype(check(std::declval<typename std::decay<T>::type>())); constexpr static bool value = type::value; }; template<typename T, bool is_iterator_ = is_iterator<T>::value> struct is_const_iterator: public std::false_type {}; template<typename T> struct is_const_iterator<T, true> { public: using type = typename std::is_const< typename std::remove_reference<typename std::iterator_traits<T>::reference>::type >::type; constexpr static bool value = type::value; }; } # #endif
Add is_iterator and is_const_iterator.
Add is_iterator and is_const_iterator.
C++
mit
hmito/hmLib,hmito/hmLib
27af84bd9a074880c2e39c3d7f7e04e538022d29
ibctl/ibctl.cpp
ibctl/ibctl.cpp
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- ibctl * * A CLI for sending control messages to a running IronBee engine manager. * * @author Sam Baskinger <[email protected]> */ #include <string> #include <vector> #include <iostream> #include <boost/algorithm/string/join.hpp> #include <boost/program_options/cmdline.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <ironbee/engine_manager_control_channel.h> #include <ironbeepp/catch.hpp> #include <ironbeepp/exception.hpp> #include <ironbeepp/memory_pool_lite.hpp> #include <ironbeepp/memory_manager.hpp> #include <ironbeepp/throw.hpp> namespace { /** * The command line parser puts all its parsed output here. */ struct parsed_options_t { std::vector<std::string> cmd; /**< Command to send to the server. */ std::string sock_path; /**< Server socket path. */ }; /** * A type of runtime error that signals this program to exit with non-zero. * * This is used to centralize the program termination. */ class exit_exception : public std::runtime_error { public: explicit exit_exception(const std::string& what): std::runtime_error(what) { } }; /** * Parse the program options. * * This function may call @c exit(). * * @param[in] argc The number of elements in @a argv. * @param[in] argv An array of nul-terminated strings. * @param[in] vm The variable map to populate with config values. * */ void parse_options( int argc, const char** argv, parsed_options_t& parsed_options ) { namespace po = boost::program_options; try { po::variables_map vm; /* Positional options. These are non-flag command line elements. */ po::positional_options_description desc_pos; /* Hidden options. */ po::options_description desc_hidden("Hidden options"); /* All options. */ po::options_description desc_all("All options"); /* Options whose help text we will show to the user. */ po::options_description desc_visible( "ibctl [options] <command> <command options...>\n" "Commands:\n" " echo <text to echo>\n" " Echo the arguments to the caller.\n" " version\n" " Return the version of the IronBee engine.\n" " enable\n" " Reenable a disabled IronBee instance.\n" " disable\n" " Disable IronBee. Running transactions will complete.\n" " cleanup\n" " Force a cleanup of old idle IronBee engines.\n" " engine_create <ironbee configuration file>\n" " Change the current IronBee engine being used.\n" "Options" ); desc_pos.add("cmd", -1); desc_visible.add_options() ("help,h", "Print this screen.") ("sock,s", po::value<std::string>(), "Socket path") ; desc_hidden.add_options() ("cmd", po::value<std::vector< std::string > >()) ; /* Bind the visible and hidden options into a single description. */ desc_all.add(desc_visible).add(desc_hidden); po::store( po::command_line_parser(argc, argv). options(desc_all). positional(desc_pos). run(), vm); po::notify(vm); if (vm.count("help") > 0) { std::cout << desc_visible; exit(0); } if (vm.count("cmd") > 0) { parsed_options.cmd = vm["cmd"].as<std::vector<std::string> >(); } if (vm.count("sock") > 0) { parsed_options.sock_path = vm["sock"].as<std::string>(); } } catch (const boost::program_options::multiple_occurrences& err) { BOOST_THROW_EXCEPTION(exit_exception(err.what())); } catch (const boost::program_options::unknown_option& err) { BOOST_THROW_EXCEPTION(exit_exception(err.what())); } } /** * Send a command. * * @param[in] opts The parsed program options that specify what to send. * * @throws IronBee::error on API errors. */ void send_cmd(const parsed_options_t& opts) { std::string cmd = boost::algorithm::join(opts.cmd, " "); std::string sock; IronBee::ScopedMemoryPoolLite mp; IronBee::MemoryManager mm(mp); const char* response; /* Pick a socket file (or use a default). */ if (opts.sock_path == "") { sock = ib_engine_manager_control_channel_socket_path_default(); } else { sock = opts.sock_path; } IronBee::throw_if_error( ib_engine_manager_control_send( sock.c_str(), cmd.c_str(), mm.ib(), &response ), (std::string("Failed to send message to server socket ")+sock).c_str() ); /* On success, report the response string back to the user. */ std::cout << response << std::endl; } } // anon namespace int main(int argc, const char** argv) { parsed_options_t parsed_options; try { parse_options(argc, argv, parsed_options); ib_util_initialize(); send_cmd(parsed_options); ib_util_shutdown(); } catch (const IronBee::error& err) { IronBee::convert_exception(); return 1; } catch (const std::exception& err) { std::cerr<< "Error: " << err.what() << std::endl; return 1; } return 0; }
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee --- ibctl * * A CLI for sending control messages to a running IronBee engine manager. * * @author Sam Baskinger <[email protected]> */ #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string/join.hpp> #include <boost/program_options/cmdline.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <ironbee/engine_manager_control_channel.h> #include <ironbeepp/catch.hpp> #include <ironbeepp/exception.hpp> #include <ironbeepp/memory_pool_lite.hpp> #include <ironbeepp/memory_manager.hpp> #include <ironbeepp/throw.hpp> namespace { /** * The command line parser puts all its parsed output here. */ struct parsed_options_t { std::vector<std::string> cmd; /**< Command to send to the server. */ std::string sock_path; /**< Server socket path. */ }; /** * A type of runtime error that signals this program to exit with non-zero. * * This is used to centralize the program termination. */ class exit_exception : public std::runtime_error { public: explicit exit_exception(const std::string& what): std::runtime_error(what) { } }; /** * Parse the program options. * * This function may call @c exit(). * * @param[in] argc The number of elements in @a argv. * @param[in] argv An array of nul-terminated strings. * @param[in] vm The variable map to populate with config values. * */ void parse_options( int argc, const char** argv, parsed_options_t& parsed_options ) { namespace po = boost::program_options; try { po::variables_map vm; /* Positional options. These are non-flag command line elements. */ po::positional_options_description desc_pos; /* Hidden options. */ po::options_description desc_hidden("Hidden options"); /* All options. */ po::options_description desc_all("All options"); /* Options whose help text we will show to the user. */ po::options_description desc_visible( "ibctl [options] <command> <command options...>\n" "Commands:\n" " echo <text to echo>\n" " Echo the arguments to the caller.\n" " version\n" " Return the version of the IronBee engine.\n" " enable\n" " Reenable a disabled IronBee instance.\n" " disable\n" " Disable IronBee. Running transactions will complete.\n" " cleanup\n" " Force a cleanup of old idle IronBee engines.\n" " engine_create <ironbee configuration file>\n" " Change the current IronBee engine being used.\n" "Options" ); desc_pos.add("cmd", -1); desc_visible.add_options() ("help,h", "Print this screen.") ("sock,s", po::value<std::string>(), "Socket path") ; desc_hidden.add_options() ("cmd", po::value<std::vector< std::string > >()) ; /* Bind the visible and hidden options into a single description. */ desc_all.add(desc_visible).add(desc_hidden); po::store( po::command_line_parser(argc, argv). options(desc_all). positional(desc_pos). run(), vm); po::notify(vm); if (vm.count("help") > 0) { std::cout << desc_visible; exit(0); } if (vm.count("cmd") > 0) { parsed_options.cmd = vm["cmd"].as<std::vector<std::string> >(); } if (vm.count("sock") > 0) { parsed_options.sock_path = vm["sock"].as<std::string>(); } } catch (const boost::program_options::multiple_occurrences& err) { BOOST_THROW_EXCEPTION(exit_exception(err.what())); } catch (const boost::program_options::unknown_option& err) { BOOST_THROW_EXCEPTION(exit_exception(err.what())); } } /** * Send a command. * * @param[in] opts The parsed program options that specify what to send. * * @throws IronBee::error on API errors. */ void send_cmd(const parsed_options_t& opts) { std::string cmd = boost::algorithm::join(opts.cmd, " "); std::string sock; IronBee::ScopedMemoryPoolLite mp; IronBee::MemoryManager mm(mp); const char* response; /* Pick a socket file (or use a default). */ if (opts.sock_path == "") { sock = ib_engine_manager_control_channel_socket_path_default(); } else { sock = opts.sock_path; } IronBee::throw_if_error( ib_engine_manager_control_send( sock.c_str(), cmd.c_str(), mm.ib(), &response ), (std::string("Failed to send message to server socket ")+sock).c_str() ); /* On success, report the response string back to the user. */ std::cout << response << std::endl; } } // anon namespace int main(int argc, const char** argv) { parsed_options_t parsed_options; try { parse_options(argc, argv, parsed_options); ib_util_initialize(); send_cmd(parsed_options); ib_util_shutdown(); } catch (const IronBee::error& err) { IronBee::convert_exception(); return 1; } catch (const std::exception& err) { std::cerr<< "Error: " << err.what() << std::endl; return 1; } return 0; }
Move location of included header to better follow ironbee style.
ibctl: Move location of included header to better follow ironbee style.
C++
apache-2.0
ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee,ironbee/ironbee,b1v1r/ironbee,b1v1r/ironbee,ironbee/ironbee
8a207398d28c7efbdd5424cd94ba7540bd18bcbd
TelegramQt/DcConfiguration.hpp
TelegramQt/DcConfiguration.hpp
#ifndef TELEGRAM_SERVER_DC_CONFIGURATION_HPP #define TELEGRAM_SERVER_DC_CONFIGURATION_HPP #include "TelegramNamespace.hpp" #if QT_VERSION < QT_VERSION_CHECK(5, 6, 0) #include <QHash> #endif // Qt-5.6 #include <QVector> namespace Telegram { struct ConnectionSpec { enum class RequestFlag { None = 0, Ipv4Only = 1 << 1, Ipv6Only = 1 << 2, MediaOnly = 1 << 3, }; Q_DECLARE_FLAGS(RequestFlags, RequestFlag) ConnectionSpec() = default; explicit ConnectionSpec(quint32 id, RequestFlags f = RequestFlags()) : dcId(id), flags(f) { } bool operator==(const ConnectionSpec &spec) const { return spec.dcId == dcId && spec.flags == flags; } quint32 dcId = 0; RequestFlags flags; }; struct DcConfiguration { int dcCount() const; DcOption getOption(const ConnectionSpec spec) const; bool isValid() const { return !dcOptions.isEmpty(); } DcConfiguration &operator=(const DcConfiguration &other) { dcOptions = other.dcOptions; return *this; } QVector<DcOption> dcOptions; }; inline uint qHash(const ConnectionSpec &key, uint seed) { return ::qHash(static_cast<uint>(key.dcId | (static_cast<quint32>(key.flags) << 20)), seed); } } // Telegram namespace #endif // TELEGRAM_SERVER_DC_CONFIGURATION_HPP
#ifndef TELEGRAM_SERVER_DC_CONFIGURATION_HPP #define TELEGRAM_SERVER_DC_CONFIGURATION_HPP #include "TelegramNamespace.hpp" #if QT_VERSION < QT_VERSION_CHECK(5, 6, 0) #include <QHash> #endif // Qt-5.6 #include <QVector> namespace Telegram { struct ConnectionSpec { enum class RequestFlag { None = 0, Ipv4Only = 1 << 1, Ipv6Only = 1 << 2, MediaOnly = 1 << 3, }; Q_DECLARE_FLAGS(RequestFlags, RequestFlag) ConnectionSpec() = default; explicit ConnectionSpec(quint32 id, RequestFlags f = RequestFlags()) : dcId(id), flags(f) { } bool operator==(const ConnectionSpec &spec) const { return spec.dcId == dcId && spec.flags == flags; } quint32 dcId = 0; RequestFlags flags; }; struct DcConfiguration { int dcCount() const; DcOption getOption(const ConnectionSpec spec) const; bool isValid() const { return !dcOptions.isEmpty(); } QVector<DcOption> dcOptions; }; inline uint qHash(const ConnectionSpec &key, uint seed) { return ::qHash(static_cast<uint>(key.dcId | (static_cast<quint32>(key.flags) << 20)), seed); } } // Telegram namespace #endif // TELEGRAM_SERVER_DC_CONFIGURATION_HPP
Remove the custom assignment operator
DcConfiguration: Remove the custom assignment operator
C++
lgpl-2.1
Kaffeine/telegram-qt,Kaffeine/telegram-qt,Kaffeine/telegram-qt
814728a561e3c3d678a56a4d19b005d4fb08c40d
RPi_utils/RFSniffer.cpp
RPi_utils/RFSniffer.cpp
/* RFSniffer Usage: ./RFSniffer [<pulseLength>] [] = optional Hacked from http://code.google.com/p/rc-switch/ by @justy to provide a handy RF code sniffer */ #include "../rc-switch/RCSwitch.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> RCSwitch mySwitch; int main(int argc, char *argv[]) { // This pin is not the first pin on the RPi GPIO header! // Consult https://projects.drogon.net/raspberry-pi/wiringpi/pins/ // for more information. int PIN = 2; if(wiringPiSetup() == -1) { printf("wiringPiSetup failed, exiting..."); return 0; } int pulseLength = 0; if (argv[1] != NULL) pulseLength = atoi(argv[1]); mySwitch = RCSwitch(); if (pulseLength != 0) mySwitch.setPulseLength(pulseLength); mySwitch.enableReceive(PIN); // Receiver on interrupt 0 => that is pin #2 while(1) { if (mySwitch.available()) { int value = mySwitch.getReceivedValue(); if (value == 0) { printf("Unknown encoding\n"); } else { printf("Received %i\n", mySwitch.getReceivedValue() ); } mySwitch.resetAvailable(); } // usleep(100); } exit(0); }
/* RFSniffer Usage: ./RFSniffer [<pulseLength>] [] = optional Hacked from http://code.google.com/p/rc-switch/ by @justy to provide a handy RF code sniffer */ #include "../rc-switch/RCSwitch.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> RCSwitch mySwitch; int main(int argc, char *argv[]) { // This pin is not the first pin on the RPi GPIO header! // Consult https://projects.drogon.net/raspberry-pi/wiringpi/pins/ // for more information. int PIN = 2; if(wiringPiSetup() == -1) { printf("wiringPiSetup failed, exiting..."); return 0; } int pulseLength = 0; if (argv[1] != NULL) pulseLength = atoi(argv[1]); mySwitch = RCSwitch(); if (pulseLength != 0) mySwitch.setPulseLength(pulseLength); mySwitch.enableReceive(PIN); // Receiver on interrupt 0 => that is pin #2 while(1) { if (mySwitch.available()) { int value = mySwitch.getReceivedValue(); if (value == 0) { printf("Unknown encoding\n"); } else { printf("Received %i\n", mySwitch.getReceivedValue() ); } mySwitch.resetAvailable(); } usleep(100); } exit(0); }
enable usleep
enable usleep
C++
mit
ninjablocks/433Utils
872b9caeab4c8e1cf1eb5c9134c5f5230c977854
MMgc/GCStack.cpp
MMgc/GCStack.cpp
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "MMgc.h" //#define TESTING_MARKSTACK #define MARKSTACK_ALLOWANCE 1 namespace MMgc { #ifdef TESTING_MARKSTACK static int markstack_allowance = 2*MARKSTACK_ALLOWANCE; // Two stacks! #endif static inline void* AllocStackSegment(bool mustSucceed) { #ifdef TESTING_MARKSTACK if (markstack_allowance == 0) return NULL; --markstack_allowance; #endif if (mustSucceed) return GCHeap::GetGCHeap()->Alloc(1, GCHeap::flags_Alloc); else return GCHeap::GetGCHeap()->AllocNoOOM(1, GCHeap::flags_Alloc | GCHeap::kCanFail); } static inline void FreeStackSegment(void* p) { #ifdef TESTING_MARKSTACK ++markstack_allowance; #endif GCHeap::GetGCHeap()->FreeNoOOM(p); } GCMarkStack::GCMarkStack() : m_base(NULL) , m_top(NULL) , m_limit(NULL) , m_topSegment(NULL) , m_hiddenCount(0) , m_extraSegment(NULL) #ifdef MMGC_MARKSTACK_DEPTH , m_maxDepth(0) #endif { // The value of kMarkStackItems is derived from on a block size of 4096; this // assert keeps us honest. Talk to Lars if you get into trouble here. GCAssert(GCHeap::kBlockSize == 4096); GCAssert(sizeof(GCMarkStack::GCStackSegment) <= GCHeap::kBlockSize); PushSegment(true); GCAssert(Invariants()); } GCMarkStack::~GCMarkStack() { while (m_topSegment != NULL) PopSegment(); if (m_extraSegment) FreeStackSegment(m_extraSegment); } void GCMarkStack::Clear() { // Clear out the elements while (m_topSegment->m_prev != NULL) PopSegment(); m_top = m_base; // Discard the cached segment if (m_extraSegment != NULL) { FreeStackSegment(m_extraSegment); m_extraSegment = NULL; } GCAssert(Invariants()); } bool GCMarkStack::PushSegment(bool mustSucceed) { GCAssert(sizeof(GCStackSegment) <= GCHeap::kBlockSize); GCAssert(m_top == m_limit); if (m_extraSegment == NULL) { void *memory = AllocStackSegment(mustSucceed); if (memory == NULL) return false; m_extraSegment = new (memory) GCStackSegment(); } if (m_topSegment != NULL) m_hiddenCount += kMarkStackItems; GCStackSegment* seg = m_extraSegment; m_extraSegment = NULL; seg->m_prev = m_topSegment; m_topSegment = seg; m_base = m_topSegment->m_items; m_limit = m_base + kMarkStackItems; m_top = m_base; return true; } void GCMarkStack::PopSegment() { m_hiddenCount -= kMarkStackItems; GCStackSegment* seg = m_topSegment; m_topSegment = seg->m_prev; m_base = m_topSegment->m_items; m_limit = m_base + kMarkStackItems; m_top = m_limit; if (m_extraSegment == NULL) { seg->m_prev = NULL; m_extraSegment = seg; } else FreeStackSegment(seg); } bool GCMarkStack::TransferOneFullSegmentFrom(GCMarkStack& other) { GCAssert(other.EntirelyFullSegments() > 0); GCStackSegment* seg; if (other.m_topSegment->m_prev == NULL) { // Picking off the only segment GCAssert(other.m_top == other.m_limit); seg = other.m_topSegment; other.m_topSegment = NULL; other.m_base = NULL; other.m_top = NULL; other.m_limit = NULL; if (!other.PushSegment()) { // Oops: couldn't push it, so undo. We're out of memory but we // don't want to signal OOM here, we want to recover, signal failure, // and let the caller handle it. other.m_topSegment = seg; other.m_base = seg->m_items; other.m_top = other.m_limit = other.m_base + kMarkStackItems; return false; } } else { // Picking off the one below the top always seg = other.m_topSegment->m_prev; other.m_topSegment->m_prev = seg->m_prev; other.m_hiddenCount -= kMarkStackItems; } // Insert it below our top segment seg->m_prev = m_topSegment->m_prev; m_topSegment->m_prev = seg; m_hiddenCount += kMarkStackItems; // Special case that occurs if a segment was inserted into an empty stack. if (m_top == m_base) PopSegment(); GCAssert(Invariants()); GCAssert(other.Invariants()); return true; } GCWorkItem *GCMarkStack::GetItemAbove(GCWorkItem *item) { if(item == Peek()) return NULL; GCStackSegment *seg = m_topSegment; GCStackSegment *last = NULL; while(seg) { if(item >= seg->m_items && item < seg->m_items + kMarkStackItems) { if(item+1 == seg->m_items + kMarkStackItems) { // The two items spanned a segment, above is first item in next // segment (or "last" in the backwards traversal sense). return &last->m_items[0]; } else { return item+1; } } last = seg; seg = seg->m_prev; } GCAssertMsg(false, "Invalid attempt to get the item above an item not in the stack."); return NULL; } #ifdef _DEBUG bool GCMarkStack::Invariants() { GCAssert(m_base+kMarkStackItems == m_limit); GCAssert(m_top >= m_base); GCAssert(m_top <= m_limit); GCAssert(m_topSegment->m_prev == NULL || m_top > m_base); uint32_t hc = 0; uint32_t ns = 0; for ( GCStackSegment* seg=m_topSegment->m_prev ; seg != NULL ; seg = seg->m_prev ) { hc += kMarkStackItems; ns++; } GCAssert(ns == EntirelyFullSegments() || (m_top == m_limit && ns+1 == EntirelyFullSegments())); GCAssert(hc == m_hiddenCount); GCAssert(Count() == hc + (m_top - m_base)); return true; } #endif }
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "MMgc.h" //#define TESTING_MARKSTACK #define MARKSTACK_ALLOWANCE 1 namespace MMgc { #ifdef TESTING_MARKSTACK static int markstack_allowance = 2*MARKSTACK_ALLOWANCE; // Two stacks! #endif static inline void* AllocStackSegment(bool mustSucceed) { #ifdef TESTING_MARKSTACK if (markstack_allowance == 0) return NULL; --markstack_allowance; #endif if (mustSucceed) return GCHeap::GetGCHeap()->Alloc(1, GCHeap::flags_Alloc); else return GCHeap::GetGCHeap()->AllocNoOOM(1, GCHeap::flags_Alloc | GCHeap::kCanFail); } static inline void FreeStackSegment(void* p) { #ifdef TESTING_MARKSTACK ++markstack_allowance; #endif GCHeap::GetGCHeap()->FreeNoOOM(p); } GCMarkStack::GCMarkStack() : m_base(NULL) , m_top(NULL) , m_limit(NULL) , m_topSegment(NULL) , m_hiddenCount(0) , m_extraSegment(NULL) #ifdef MMGC_MARKSTACK_DEPTH , m_maxDepth(0) #endif { // The value of kMarkStackItems is derived from on a block size of 4096; this // assert keeps us honest. Talk to Lars if you get into trouble here. GCAssert(GCHeap::kBlockSize == 4096); GCAssert(sizeof(GCMarkStack::GCStackSegment) <= GCHeap::kBlockSize); PushSegment(true); GCAssert(Invariants()); } GCMarkStack::~GCMarkStack() { while (m_topSegment != NULL) PopSegment(); if (m_extraSegment) FreeStackSegment(m_extraSegment); } void GCMarkStack::Clear() { // Clear out the elements while (m_topSegment->m_prev != NULL) PopSegment(); m_top = m_base; // Discard the cached segment if (m_extraSegment != NULL) { FreeStackSegment(m_extraSegment); m_extraSegment = NULL; } GCAssert(Invariants()); } bool GCMarkStack::PushSegment(bool mustSucceed) { GCAssert(sizeof(GCStackSegment) <= GCHeap::kBlockSize); GCAssert(m_top == m_limit); if (m_extraSegment == NULL) { void *memory = AllocStackSegment(mustSucceed); if (memory == NULL) return false; m_extraSegment = new (memory) GCStackSegment(); } if (m_topSegment != NULL) m_hiddenCount += kMarkStackItems; GCStackSegment* seg = m_extraSegment; m_extraSegment = NULL; seg->m_prev = m_topSegment; m_topSegment = seg; m_base = m_topSegment->m_items; m_limit = m_base + kMarkStackItems; m_top = m_base; return true; } void GCMarkStack::PopSegment() { m_hiddenCount -= kMarkStackItems; GCStackSegment* seg = m_topSegment; m_topSegment = seg->m_prev; m_base = m_topSegment->m_items; m_limit = m_base + kMarkStackItems; m_top = m_limit; if (m_extraSegment == NULL) { seg->m_prev = NULL; m_extraSegment = seg; } else FreeStackSegment(seg); } bool GCMarkStack::TransferOneFullSegmentFrom(GCMarkStack& other) { // Unchecked invariant: 'other' has no multi-item stack entries, // like sentinels. GCAssert(other.EntirelyFullSegments() > 0); GCStackSegment* seg; if (other.m_topSegment->m_prev == NULL) { // Picking off the only segment GCAssert(other.m_top == other.m_limit); seg = other.m_topSegment; other.m_topSegment = NULL; other.m_base = NULL; other.m_top = NULL; other.m_limit = NULL; if (!other.PushSegment()) { // Oops: couldn't push it, so undo. We're out of memory but we // don't want to signal OOM here, we want to recover, signal failure, // and let the caller handle it. other.m_topSegment = seg; other.m_base = seg->m_items; other.m_top = other.m_limit = other.m_base + kMarkStackItems; return false; } } else { // Picking off the one below the top always seg = other.m_topSegment->m_prev; other.m_topSegment->m_prev = seg->m_prev; other.m_hiddenCount -= kMarkStackItems; } // Insert it at the bottom of our stack. That is the easiest way to avoid // splitting multi-item entries on the stack, see eg Bugzilla 622834. // It's OK to cdr down the list to find the last one, block transfer is not // a hot operation. GCStackSegment* first = m_topSegment; while (first->m_prev != NULL) first = first->m_prev; first->m_prev = seg; seg->m_prev = NULL; m_hiddenCount += kMarkStackItems; // Special case that occurs if a segment was inserted into an empty stack. if (m_top == m_base) PopSegment(); GCAssert(Invariants()); GCAssert(other.Invariants()); return true; } GCWorkItem *GCMarkStack::GetItemAbove(GCWorkItem *item) { if(item == Peek()) return NULL; GCStackSegment *seg = m_topSegment; GCStackSegment *last = NULL; while(seg) { if(item >= seg->m_items && item < seg->m_items + kMarkStackItems) { if(item+1 == seg->m_items + kMarkStackItems) { // The two items spanned a segment, above is first item in next // segment (or "last" in the backwards traversal sense). return &last->m_items[0]; } else { return item+1; } } last = seg; seg = seg->m_prev; } GCAssertMsg(false, "Invalid attempt to get the item above an item not in the stack."); return NULL; } #ifdef _DEBUG bool GCMarkStack::Invariants() { GCAssert(m_base+kMarkStackItems == m_limit); GCAssert(m_top >= m_base); GCAssert(m_top <= m_limit); GCAssert(m_topSegment->m_prev == NULL || m_top > m_base); uint32_t hc = 0; uint32_t ns = 0; for ( GCStackSegment* seg=m_topSegment->m_prev ; seg != NULL ; seg = seg->m_prev ) { hc += kMarkStackItems; ns++; } GCAssert(ns == EntirelyFullSegments() || (m_top == m_limit && ns+1 == EntirelyFullSegments())); GCAssert(hc == m_hiddenCount); GCAssert(Count() == hc + (m_top - m_base)); return true; } #endif }
Fix 622834 - Assertion failed: '((payload.GetSentinel2Type() == GCWorkItem::kInertPayload))' (r=edwsmith)
Fix 622834 - Assertion failed: '((payload.GetSentinel2Type() == GCWorkItem::kInertPayload))' (r=edwsmith)
C++
mpl-2.0
pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux
3be9c4b28766b073a329a022e87523376b8d2ea8
src/lib/extract_sv_reads/SamReader.hpp
src/lib/extract_sv_reads/SamReader.hpp
#pragma once #include "ThreadPool.hpp" #include <htslib/sam.h> #include <htslib/hts.h> #include <boost/format.hpp> #include <string> #include <stdexcept> #include <iostream> class SamReader { public: SamReader(char const* path, char const* reference=NULL, ThreadPool* thread_pool=NULL, bool reduced=false) : _in(hts_open(path, "r")) , _required_flags(0) , _skip_flags(0) { using boost::format; if (!_in) { throw std::runtime_error(str(format( "Failed to open input file %1%" ) % path)); } if (reference && *reference != '\0') { if (hts_set_opt(_in, CRAM_OPT_REFERENCE, reference) != 0) { throw std::runtime_error(str(format( "Unable to use reference %1%" ) % reference)); } } if (thread_pool) { if (hts_set_opt(_in, HTS_OPT_THREAD_POOL, thread_pool->pool()) != 0) { throw std::runtime_error(str(format( "Failed to use threads to read %1%" ) % path)); } } if (_in->format.format == cram) { // CRAM is flexible in terms of what it can decode. // Only ask for what we need uint32_t rf = SAM_FLAG | SAM_QNAME | SAM_RNAME | SAM_POS | SAM_CIGAR | SAM_TLEN | SAM_AUX; if (!reduced) { rf = rf | SAM_SEQ | SAM_QUAL; } if (hts_set_opt(_in, CRAM_OPT_REQUIRED_FIELDS, rf) != 0) { throw std::runtime_error(str(format( "Unable to set CRAM reading options on %1%" ) % path)); } if (hts_set_opt(_in, CRAM_OPT_DECODE_MD, 0) != 0) { throw std::runtime_error(str(format( "Unable to set MD tag decoding off on %1%" ) % path)); } } if (!(_hdr = sam_hdr_read(_in))) { throw std::runtime_error(str(format( "Failed to read header from file %1%" ) % path)); } } ~SamReader() { if (_hdr) { bam_hdr_destroy(_hdr); } if (_in) { hts_close(_in); } } bam_hdr_t* header() const { return _hdr; } void required_flags(uint32_t flags) { _required_flags = flags; } void skip_flags(uint32_t flags) { _skip_flags = flags; } bool want(uint32_t flag) const { return (flag & _required_flags) == _required_flags && (flag & _skip_flags) == 0; } bool next(bam1_t* record) { while (sam_read1(_in, _hdr, record) > 0) { if (want(record->core.flag)) { return true; } } return false; } private: htsFile* _in; bam_hdr_t* _hdr; uint32_t _required_flags; uint32_t _skip_flags; };
#pragma once #include "ThreadPool.hpp" #include <htslib/sam.h> #include <htslib/hts.h> #include <boost/format.hpp> #include <string> #include <stdexcept> #include <iostream> class SamReader { public: SamReader(char const* path, char const* reference=NULL, ThreadPool* thread_pool=NULL, bool reduced=false) : _in(hts_open(path, "r")) , _required_flags(0) , _skip_flags(0) { using boost::format; if (!_in) { throw std::runtime_error(str(format( "Failed to open input file %1%" ) % path)); } if (reference && *reference != '\0') { if (hts_set_opt(_in, CRAM_OPT_REFERENCE, reference) != 0) { throw std::runtime_error(str(format( "Unable to use reference %1%" ) % reference)); } } if (thread_pool) { if (hts_set_opt(_in, HTS_OPT_THREAD_POOL, thread_pool->pool()) != 0) { throw std::runtime_error(str(format( "Failed to use threads to read %1%" ) % path)); } } if (_in->format.format == cram) { // CRAM is flexible in terms of what it can decode. // Only ask for what we need uint32_t rf = SAM_FLAG | SAM_QNAME | SAM_RNAME | SAM_POS | SAM_MAPQ | SAM_CIGAR | SAM_RNEXT | SAM_PNEXT | SAM_TLEN | SAM_AUX | SAM_RGAUX; if (!reduced) { rf = rf | SAM_SEQ | SAM_QUAL; } if (hts_set_opt(_in, CRAM_OPT_REQUIRED_FIELDS, rf) != 0) { throw std::runtime_error(str(format( "Unable to set CRAM reading options on %1%" ) % path)); } if (hts_set_opt(_in, CRAM_OPT_DECODE_MD, 0) != 0) { throw std::runtime_error(str(format( "Unable to set MD tag decoding off on %1%" ) % path)); } } if (!(_hdr = sam_hdr_read(_in))) { throw std::runtime_error(str(format( "Failed to read header from file %1%" ) % path)); } } ~SamReader() { if (_hdr) { bam_hdr_destroy(_hdr); } if (_in) { hts_close(_in); } } bam_hdr_t* header() const { return _hdr; } void required_flags(uint32_t flags) { _required_flags = flags; } void skip_flags(uint32_t flags) { _skip_flags = flags; } bool want(uint32_t flag) const { return (flag & _required_flags) == _required_flags && (flag & _skip_flags) == 0; } bool next(bam1_t* record) { while (sam_read1(_in, _hdr, record) > 0) { if (want(record->core.flag)) { return true; } } return false; } private: htsFile* _in; bam_hdr_t* _hdr; uint32_t _required_flags; uint32_t _skip_flags; };
Add back in CRAM fields
Add back in CRAM fields
C++
mit
hall-lab/extract_sv_reads,hall-lab/extract_sv_reads,hall-lab/extract_sv_reads
94c2de9f5e20bbfeddbb8050751437bd1791ad94
src/plugins/protocolhandler/http/httphandler.cpp
src/plugins/protocolhandler/http/httphandler.cpp
/* Copyright (c) 2012 Silk Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Silk 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 SILK 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 "httphandler.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkCookie> #include <qhttprequest.h> #include <qhttpreply.h> class HttpHandler::Private : public QObject { Q_OBJECT public: Private(HttpHandler *parent); void load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message); private slots: void finished(); void error(QNetworkReply::NetworkError error); void httpReplyDestroyed(QObject *object); private: HttpHandler *q; QMap<QObject *, QHttpRequest*> requestMap; QMap<QObject *, QHttpReply*> replyMap; QMap<QObject *, QNetworkReply*> replyMap2; static QNetworkAccessManager networkAccessManager; }; QNetworkAccessManager HttpHandler::Private::networkAccessManager; HttpHandler::Private::Private(HttpHandler *parent) : QObject(parent) , q(parent) { } void HttpHandler::Private::load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message) { // qDebug() << url; Q_UNUSED(message) QNetworkRequest req(url); foreach (const QByteArray &headerName, request->rawHeaderList()) { req.setRawHeader(headerName, request->rawHeader(headerName)); } QNetworkReply *rep; if (request->method() == "POST") { rep = networkAccessManager.post(req, request); } else if (request->method() == "PUT") { rep = networkAccessManager.put(req, request); } else if (request->method() == "GET") { rep = networkAccessManager.get(req); } else if (request->method() == "HEAD") { rep = networkAccessManager.head(req); } else { rep = networkAccessManager.sendCustomRequest(req, request->method(), request); } requestMap.insert(rep, request); replyMap.insert(rep, reply); replyMap2.insert(reply, rep); connect(rep, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); connect(rep, SIGNAL(finished()), this, SLOT(finished())); connect(reply, SIGNAL(destroyed(QObject*)), this, SLOT(httpReplyDestroyed(QObject*))); } void HttpHandler::Private::finished() { QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); // qDebug() << Q_FUNC_INFO << __LINE__ << rep->url(); /*QHttpRequest *request = */requestMap.take(rep); QHttpReply *reply = replyMap.take(rep); replyMap2.take(reply); foreach (const QByteArray &headerName, rep->rawHeaderList()) { reply->setRawHeader(headerName, rep->rawHeader(headerName)); // qDebug() << headerName << rep->rawHeader(headerName); } int status = rep->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // qDebug() << status; reply->setStatus(status); QByteArray data = rep->readAll(); // qDebug() << data.length(); reply->write(data); reply->close(); rep->deleteLater(); // qDebug() << Q_FUNC_INFO << __LINE__; } void HttpHandler::Private::error(QNetworkReply::NetworkError error) { Q_UNUSED(error) QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); // qDebug() << Q_FUNC_INFO << __LINE__ << rep->url() << error; QHttpRequest *request = requestMap.value(rep); QHttpReply *reply = replyMap.value(rep); emit q->error(403, request, reply, rep->errorString()); // qDebug() << Q_FUNC_INFO << __LINE__; } void HttpHandler::Private::httpReplyDestroyed(QObject* object) { // qDebug() << Q_FUNC_INFO << __LINE__; if (replyMap2.contains(object)) { QNetworkReply *reply = replyMap2.take(object); reply->deleteLater(); } // qDebug() << Q_FUNC_INFO << __LINE__; } HttpHandler::HttpHandler(QObject *parent) : SilkAbstractProtocolHandler(parent) , d(new Private(this)) { } bool HttpHandler::load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message) { d->load(url, request, reply, message); return true; } #include "httphandler.moc"
/* Copyright (c) 2012 Silk Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Silk 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 SILK 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 "httphandler.h" #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkCookie> #include <qhttprequest.h> #include <qhttpreply.h> class HttpHandler::Private : public QObject { Q_OBJECT public: Private(HttpHandler *parent); void load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message); private slots: void finished(); void error(QNetworkReply::NetworkError error); void httpReplyDestroyed(QObject *object); private: HttpHandler *q; QMap<QObject *, QHttpRequest*> requestMap; QMap<QObject *, QHttpReply*> replyMap; QMap<QObject *, QNetworkReply*> replyMap2; static QNetworkAccessManager *networkAccessManager; }; QNetworkAccessManager *HttpHandler::Private::networkAccessManager = 0; HttpHandler::Private::Private(HttpHandler *parent) : QObject(parent) , q(parent) { } void HttpHandler::Private::load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message) { // qDebug() << url; Q_UNUSED(message) QNetworkRequest req(url); foreach (const QByteArray &headerName, request->rawHeaderList()) { req.setRawHeader(headerName, request->rawHeader(headerName)); } if (!networkAccessManager) { networkAccessManager = new QNetworkAccessManager; } QNetworkReply *rep; if (request->method() == "POST") { rep = networkAccessManager->post(req, request); } else if (request->method() == "PUT") { rep = networkAccessManager->put(req, request); } else if (request->method() == "GET") { rep = networkAccessManager->get(req); } else if (request->method() == "HEAD") { rep = networkAccessManager->head(req); } else { rep = networkAccessManager->sendCustomRequest(req, request->method(), request); } requestMap.insert(rep, request); replyMap.insert(rep, reply); replyMap2.insert(reply, rep); connect(rep, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); connect(rep, SIGNAL(finished()), this, SLOT(finished())); connect(reply, SIGNAL(destroyed(QObject*)), this, SLOT(httpReplyDestroyed(QObject*))); } void HttpHandler::Private::finished() { QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); // qDebug() << Q_FUNC_INFO << __LINE__ << rep->url(); /*QHttpRequest *request = */requestMap.take(rep); QHttpReply *reply = replyMap.take(rep); replyMap2.take(reply); foreach (const QByteArray &headerName, rep->rawHeaderList()) { reply->setRawHeader(headerName, rep->rawHeader(headerName)); // qDebug() << headerName << rep->rawHeader(headerName); } int status = rep->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // qDebug() << status; reply->setStatus(status); QByteArray data = rep->readAll(); // qDebug() << data.length(); reply->write(data); reply->close(); rep->deleteLater(); // qDebug() << Q_FUNC_INFO << __LINE__; } void HttpHandler::Private::error(QNetworkReply::NetworkError error) { Q_UNUSED(error) QNetworkReply *rep = qobject_cast<QNetworkReply *>(sender()); // qDebug() << Q_FUNC_INFO << __LINE__ << rep->url() << error; QHttpRequest *request = requestMap.value(rep); QHttpReply *reply = replyMap.value(rep); emit q->error(403, request, reply, rep->errorString()); // qDebug() << Q_FUNC_INFO << __LINE__; } void HttpHandler::Private::httpReplyDestroyed(QObject* object) { // qDebug() << Q_FUNC_INFO << __LINE__; if (replyMap2.contains(object)) { QNetworkReply *reply = replyMap2.take(object); reply->deleteLater(); } // qDebug() << Q_FUNC_INFO << __LINE__; } HttpHandler::HttpHandler(QObject *parent) : SilkAbstractProtocolHandler(parent) , d(new Private(this)) { } bool HttpHandler::load(const QUrl &url, QHttpRequest *request, QHttpReply *reply, const QString &message) { d->load(url, request, reply, message); return true; } #include "httphandler.moc"
make static QNetworkAccessManager to pointer
make static QNetworkAccessManager to pointer it didn't work on Qt 5.2.0 Change-Id: Ia915dc30063be75b4ca3936707e665ff6af7f188 Reviewed-on: http://cr.qtquick.me/785 Tested-by: http://ci.qtquick.me/ Reviewed-by: Tasuku Suzuki <[email protected]> Tested-by: Tasuku Suzuki <[email protected]>
C++
bsd-3-clause
yatsek/silk,qt-users-jp/silk,qt-users-jp/silk,qt-users-jp/silk,yatsek/silk,yatsek/silk,qt-users-jp/silk,yatsek/silk
002c464a1c259174d202a638e25303d5d2f74869
test/test_binding_character.cpp
test/test_binding_character.cpp
#include <gmock/gmock.h> #include "script/LuaTestSupportScript.hpp" #include "Monster.hpp" #include "World.hpp" class MockWorld : public World { public: MockWorld() { World::_self = this; } MOCK_METHOD1(findCharacter, Character*(TYPE_OF_CHARACTER_ID id)); MOCK_METHOD2(getMonsterDefinition, bool(TYPE_OF_CHARACTER_ID, MonsterStruct &)); }; using ::testing::Return; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::AtLeast; using ::testing::_; class world_bindings : public ::testing::Test { public: MockWorld world; MonsterStruct monsterDefinition; Monster *monster; ~world_bindings() { LuaScript::shutdownLua(); delete monster; } world_bindings() { ON_CALL(world, getMonsterDefinition(_, _)).WillByDefault(DoAll(SetArgReferee<1>(monsterDefinition), Return(true))); EXPECT_CALL(world, getMonsterDefinition(_, _)).Times(AtLeast(0)); monster = new Monster(5, position(1, 2, 3)); ON_CALL(world, findCharacter(monster->getId())).WillByDefault(Return(monster)); EXPECT_CALL(world, findCharacter(monster->getId())).Times(AtLeast(0)); } }; TEST_F(world_bindings, isNewPlayer) { LuaTestSupportScript script {"function test(monster) return monster:isNewPlayer() end"}; bool result = script.test<Monster *, bool>(monster); EXPECT_FALSE(result); } /* TEST_F(world_bindings, pageGM) { LuaTestSupportScript script {"function test(monster) return monster:pageGM('test') end"}; EXPECT_FALSE(script.test(&monster)); } TEST_F(world_bindings, requestInputDialog) { LuaTestSupportScript script {"function test(monster) return monster:requestInputDialog() end"}; EXPECT_FALSE(script.test(&monster)); } */ /* "player:requestInputDialog(nil) " "player:requestMessageDialog(nil) " "player:requestMerchantDialog(nil) " "player:requestSelectionDialog(nil) " "player:requestCraftingDialog(nil) " "player:requestCraftingLookAt(0, ItemLookAt()) " "player:requestCraftingLookAtIngredient(0, ItemLookAt()) " "player:idleTime() " "return true " "end", }; MockCharacter &player = *world.player; EXPECT_CALL(player, isNewPlayer()).Times(1); EXPECT_CALL(player, pageGM(_)).Times(1); EXPECT_CALL(player, requestInputDialog(_)).Times(1); EXPECT_CALL(player, requestMessageDialog(_)).Times(1); EXPECT_CALL(player, requestMerchantDialog(_)).Times(1); EXPECT_CALL(player, requestSelectionDialog(_)).Times(1); EXPECT_CALL(player, requestCraftingDialog(_)).Times(1); EXPECT_CALL(player, requestCraftingLookAt(_, _)).Times(1); EXPECT_CALL(player, requestCraftingLookAtIngredient(_, _)).Times(1); EXPECT_CALL(player, idleTime()).Times(1); script.test((Character*)&player); } */ int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <gmock/gmock.h> #include "script/LuaTestSupportScript.hpp" #include "Monster.hpp" #include "World.hpp" class MockWorld : public World { public: MockWorld() { World::_self = this; } MOCK_METHOD1(findCharacter, Character*(TYPE_OF_CHARACTER_ID id)); MOCK_METHOD2(getMonsterDefinition, bool(TYPE_OF_CHARACTER_ID, MonsterStruct &)); }; class MockMonster : public Monster { public: MockMonster() : Monster(5, position(1, 2, 3), nullptr) {} MOCK_CONST_METHOD0(isNewPlayer, bool()); }; using ::testing::Return; using ::testing::AtLeast; using ::testing::_; class world_bindings : public ::testing::Test { public: MockWorld world; MockMonster *monster; ~world_bindings() { LuaScript::shutdownLua(); delete monster; } world_bindings() { ON_CALL(world, getMonsterDefinition(_, _)).WillByDefault(Return(true)); EXPECT_CALL(world, getMonsterDefinition(_, _)).Times(AtLeast(0)); monster = new MockMonster(); ON_CALL(world, findCharacter(monster->getId())).WillByDefault(Return(monster)); EXPECT_CALL(world, findCharacter(monster->getId())).Times(AtLeast(0)); ON_CALL(*monster, isNewPlayer()).WillByDefault(Return(false)); } }; TEST_F(world_bindings, isNewPlayer) { LuaTestSupportScript script {"function test(monster) return monster:isNewPlayer() end"}; EXPECT_CALL(*monster, isNewPlayer()).WillOnce(Return(false)); bool isNewPlayer = script.test<Monster *, bool>(monster); EXPECT_FALSE(isNewPlayer); } /* TEST_F(world_bindings, pageGM) { LuaTestSupportScript script {"function test(monster) return monster:pageGM('test') end"}; bool result = script.test<Monster *, bool>(monster); EXPECT_FALSE(result); } TEST_F(world_bindings, requestInputDialog) { LuaTestSupportScript script {"function test(monster) return monster:requestInutDialog('test', 'bla') end"}; } */ /* "player:requestInputDialog(nil) " "player:requestMessageDialog(nil) " "player:requestMerchantDialog(nil) " "player:requestSelectionDialog(nil) " "player:requestCraftingDialog(nil) " "player:requestCraftingLookAt(0, ItemLookAt()) " "player:requestCraftingLookAtIngredient(0, ItemLookAt()) " "player:idleTime() " "return true " "end", }; MockCharacter &player = *world.player; EXPECT_CALL(player, isNewPlayer()).Times(1); EXPECT_CALL(player, pageGM(_)).Times(1); EXPECT_CALL(player, requestInputDialog(_)).Times(1); EXPECT_CALL(player, requestMessageDialog(_)).Times(1); EXPECT_CALL(player, requestMerchantDialog(_)).Times(1); EXPECT_CALL(player, requestSelectionDialog(_)).Times(1); EXPECT_CALL(player, requestCraftingDialog(_)).Times(1); EXPECT_CALL(player, requestCraftingLookAt(_, _)).Times(1); EXPECT_CALL(player, requestCraftingLookAtIngredient(_, _)).Times(1); EXPECT_CALL(player, idleTime()).Times(1); script.test((Character*)&player); } */ int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
Check expected function calls
Check expected function calls
C++
agpl-3.0
Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server,Illarion-eV/Illarion-Server
904afa4126b5df5f73e5b5cdb131b54fa97b0200
src/bin/clients/tools/json_rpc_server/src/rpc_state.cpp
src/bin/clients/tools/json_rpc_server/src/rpc_state.cpp
#include <pthread.h> #include <sys/time.h> #include "stinger_core/xmalloc.h" #include "stinger_core/x86_full_empty.h" #include "stinger_core/stinger_shared.h" #include "rpc_state.h" #include "stinger_core/stinger.h" using namespace gt::stinger; JSON_RPCServerState & JSON_RPCServerState::get_server_state() { static JSON_RPCServerState state; return state; } JSON_RPCServerState::JSON_RPCServerState() : next_session_id(1), session_lock(0), max_sessions(20), StingerMon() { } JSON_RPCServerState::~JSON_RPCServerState() { } void JSON_RPCServerState::add_rpc_function(std::string name, JSON_RPCFunction * func) { LOG_D_A("Adding RPC function %s", name.c_str()); if(func) function_map[name] = func; } JSON_RPCFunction * JSON_RPCServerState::get_rpc_function(std::string name) { return function_map[name]; } bool JSON_RPCServerState::has_rpc_function(std::string name) { return function_map.count(name) > 0; } void JSON_RPCServerState::add_rpc_session(std::string name, JSON_RPCSession * func) { LOG_D_A("Adding RPC session type %s", name.c_str()); if(func) session_map[name] = func; } JSON_RPCSession * JSON_RPCServerState::get_rpc_session(std::string name) { return session_map[name]; } bool JSON_RPCServerState::has_rpc_session(std::string name) { return session_map.count(name) > 0; } void JSON_RPCServerState::update_algs(stinger_t * stinger_copy, std::string new_loc, int64_t new_sz, std::vector<StingerAlgState *> * new_algs, std::map<std::string, StingerAlgState *> * new_alg_map, const StingerBatch & batch) { StingerMon::update_algs(stinger_copy, new_loc, new_sz, new_algs, new_alg_map, batch); readfe((uint64_t *)&session_lock); for(std::map<int64_t, JSON_RPCSession *>::iterator tmp = active_session_map.begin(); tmp != active_session_map.end(); tmp++) { JSON_RPCSession * session = tmp->second; session->lock(); if (session->is_timed_out()) { int64_t session_id = session->get_session_id(); LOG_D_A ("Session %ld timed out. Destroying...", (long) session_id); delete active_session_map[session_id]; active_session_map.erase (session_id); } else { session->update(batch); session->unlock(); } } writeef((uint64_t *)&session_lock, 0); } bool JSON_RPCFunction::contains_params(rpc_params_t * p, rapidjson::Value * params) { if (!params) return true; while(p->name) { if(!params->HasMember(p->name)) { if(p->optional) { switch(p->type) { case TYPE_INT64: { *((int64_t *)p->output) = p->def; } break; case TYPE_STRING: { *((char **)p->output) = (char *) p->def; } break; case TYPE_DOUBLE: { *((double *)p->output) = (double) p->def; } break; case TYPE_BOOL: { *((bool *)p->output) = (bool) p->def; } break; case TYPE_ARRAY: { params_array_t * ptr = (params_array_t *) p->output; ptr->len = 0; ptr->arr = NULL; } break; } } else { return false; } } else { stinger_t * S = server_state->get_stinger(); switch(p->type) { case TYPE_VERTEX: { if((*params)[p->name].IsInt64()) { int64_t tmp = (*params)[p->name].GetInt64(); if (tmp < 0 || tmp >= STINGER_MAX_LVERTICES) return false; *((int64_t *)p->output) = tmp; } else if((*params)[p->name].IsString()) { int64_t tmp = stinger_mapping_lookup(S, (*params)[p->name].GetString(), (*params)[p->name].GetStringLength()); if (tmp == -1) return false; *((int64_t *)p->output) = tmp; } else { return false; } } break; case TYPE_INT64: { if(!(*params)[p->name].IsInt64()) { return false; } *((int64_t *)p->output) = (*params)[p->name].GetInt64(); } break; case TYPE_STRING: { if(!(*params)[p->name].IsString()) { return false; } *((char **)p->output) = (char *) (*params)[p->name].GetString(); } break; case TYPE_DOUBLE: { if(!(*params)[p->name].IsDouble()) { return false; } *((double *)p->output) = (*params)[p->name].GetDouble(); } break; case TYPE_BOOL: { if(!(*params)[p->name].IsBool()) { return false; } *((bool *)p->output) = (*params)[p->name].GetBool(); } break; case TYPE_ARRAY: { if(!(*params)[p->name].IsArray()) { return false; } params_array_t * ptr = (params_array_t *) p->output; ptr->len = (*params)[p->name].Size(); ptr->arr = (int64_t *) xmalloc(sizeof(int64_t) * ptr->len); for (int64_t i = 0; i < ptr->len; i++) { if ((*params)[p->name][i].IsInt64()) { int64_t tmp = (*params)[p->name][i].GetInt64(); if (tmp < 0 || tmp >= STINGER_MAX_LVERTICES) { return false; } ptr->arr[i] = tmp; } else if ((*params)[p->name][i].IsString()) { int64_t tmp = stinger_mapping_lookup(S, (*params)[p->name][i].GetString(), (*params)[p->name][i].GetStringLength()); if (tmp == -1) { return false; } ptr->arr[i] = tmp; } } } break; } } p++; } return true; } void JSON_RPCSession::lock() { readfe((uint64_t *)&the_lock); } void JSON_RPCSession::unlock() { writeef((uint64_t *)&the_lock, 0); } bool JSON_RPCSession::is_timed_out() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec > last_touched + 30; } int64_t JSON_RPCSession::reset_timeout() { struct timeval tv; gettimeofday(&tv, NULL); return last_touched = tv.tv_sec; } int64_t JSON_RPCSession::get_session_id() { return session_id; } int64_t JSON_RPCSession::get_time_since() { return last_touched; } params_array_t::params_array_t():arr(NULL) {} params_array_t::~params_array_t() { if (arr) free (arr); } int64_t JSON_RPCServerState::get_next_session() { readfe((uint64_t *)&session_lock); int64_t rtn = next_session_id++; writeef((uint64_t *)&session_lock, 0); return rtn; } int64_t JSON_RPCServerState::add_session(int64_t session_id, JSON_RPCSession * session) { readfe((uint64_t *)&session_lock); if (active_session_map.size() < max_sessions) { active_session_map.insert( std::pair<int64_t, JSON_RPCSession *>(session_id, session) ); } else { session_id = -1; } writeef((uint64_t *)&session_lock, 0); return session_id; } int64_t JSON_RPCServerState::destroy_session(int64_t session_id) { readfe((uint64_t *)&session_lock); delete active_session_map[session_id]; int64_t rtn = active_session_map.erase (session_id); writeef((uint64_t *)&session_lock, 0); return rtn; } int64_t JSON_RPCServerState::get_num_sessions() { readfe((uint64_t *)&session_lock); int64_t rtn = active_session_map.size(); writeef((uint64_t *)&session_lock, 0); return rtn; } JSON_RPCSession * JSON_RPCServerState::get_session(int64_t session_id) { readfe((uint64_t *)&session_lock); std::map<int64_t, JSON_RPCSession *>::iterator tmp = active_session_map.find(session_id); writeef((uint64_t *)&session_lock, 0); if (tmp == active_session_map.end()) return NULL; else return tmp->second; }
#include <pthread.h> #include <sys/time.h> #include "stinger_core/xmalloc.h" #include "stinger_core/x86_full_empty.h" #include "stinger_core/stinger_shared.h" #include "rpc_state.h" #include "stinger_core/stinger.h" using namespace gt::stinger; JSON_RPCServerState & JSON_RPCServerState::get_server_state() { static JSON_RPCServerState state; return state; } JSON_RPCServerState::JSON_RPCServerState() : next_session_id(1), session_lock(0), max_sessions(20), StingerMon() { } JSON_RPCServerState::~JSON_RPCServerState() { } void JSON_RPCServerState::add_rpc_function(std::string name, JSON_RPCFunction * func) { LOG_D_A("Adding RPC function %s", name.c_str()); if(func) function_map[name] = func; } JSON_RPCFunction * JSON_RPCServerState::get_rpc_function(std::string name) { return function_map[name]; } bool JSON_RPCServerState::has_rpc_function(std::string name) { return function_map.count(name) > 0; } void JSON_RPCServerState::add_rpc_session(std::string name, JSON_RPCSession * func) { LOG_D_A("Adding RPC session type %s", name.c_str()); if(func) session_map[name] = func; } JSON_RPCSession * JSON_RPCServerState::get_rpc_session(std::string name) { return session_map[name]; } bool JSON_RPCServerState::has_rpc_session(std::string name) { return session_map.count(name) > 0; } void JSON_RPCServerState::update_algs(stinger_t * stinger_copy, std::string new_loc, int64_t new_sz, std::vector<StingerAlgState *> * new_algs, std::map<std::string, StingerAlgState *> * new_alg_map, const StingerBatch & batch) { StingerMon::update_algs(stinger_copy, new_loc, new_sz, new_algs, new_alg_map, batch); readfe((uint64_t *)&session_lock); for(std::map<int64_t, JSON_RPCSession *>::iterator tmp = active_session_map.begin(); tmp != active_session_map.end(); tmp++) { JSON_RPCSession * session = tmp->second; session->lock(); if (session->is_timed_out()) { int64_t session_id = session->get_session_id(); LOG_D_A ("Session %ld timed out. Destroying...", (long) session_id); delete active_session_map[session_id]; active_session_map.erase (session_id); } else { session->update(batch); session->unlock(); } } writeef((uint64_t *)&session_lock, 0); } bool JSON_RPCFunction::contains_params(rpc_params_t * p, rapidjson::Value * params) { if (!params) return true; //shouldn't this be return false? if (params->IsArray()) return false; while(p->name) { if(!params->HasMember(p->name)) { if(p->optional) { switch(p->type) { case TYPE_INT64: { *((int64_t *)p->output) = p->def; } break; case TYPE_STRING: { *((char **)p->output) = (char *) p->def; } break; case TYPE_DOUBLE: { *((double *)p->output) = (double) p->def; } break; case TYPE_BOOL: { *((bool *)p->output) = (bool) p->def; } break; case TYPE_ARRAY: { params_array_t * ptr = (params_array_t *) p->output; ptr->len = 0; ptr->arr = NULL; } break; } } else { return false; } } else { stinger_t * S = server_state->get_stinger(); switch(p->type) { case TYPE_VERTEX: { if((*params)[p->name].IsInt64()) { int64_t tmp = (*params)[p->name].GetInt64(); if (tmp < 0 || tmp >= STINGER_MAX_LVERTICES) return false; *((int64_t *)p->output) = tmp; } else if((*params)[p->name].IsString()) { int64_t tmp = stinger_mapping_lookup(S, (*params)[p->name].GetString(), (*params)[p->name].GetStringLength()); if (tmp == -1) return false; *((int64_t *)p->output) = tmp; } else { return false; } } break; case TYPE_INT64: { if(!(*params)[p->name].IsInt64()) { return false; } *((int64_t *)p->output) = (*params)[p->name].GetInt64(); } break; case TYPE_STRING: { if(!(*params)[p->name].IsString()) { return false; } *((char **)p->output) = (char *) (*params)[p->name].GetString(); } break; case TYPE_DOUBLE: { if(!(*params)[p->name].IsDouble()) { return false; } *((double *)p->output) = (*params)[p->name].GetDouble(); } break; case TYPE_BOOL: { if(!(*params)[p->name].IsBool()) { return false; } *((bool *)p->output) = (*params)[p->name].GetBool(); } break; case TYPE_ARRAY: { if(!(*params)[p->name].IsArray()) { return false; } params_array_t * ptr = (params_array_t *) p->output; ptr->len = (*params)[p->name].Size(); ptr->arr = (int64_t *) xmalloc(sizeof(int64_t) * ptr->len); for (int64_t i = 0; i < ptr->len; i++) { if ((*params)[p->name][i].IsInt64()) { int64_t tmp = (*params)[p->name][i].GetInt64(); if (tmp < 0 || tmp >= STINGER_MAX_LVERTICES) { return false; } ptr->arr[i] = tmp; } else if ((*params)[p->name][i].IsString()) { int64_t tmp = stinger_mapping_lookup(S, (*params)[p->name][i].GetString(), (*params)[p->name][i].GetStringLength()); if (tmp == -1) { return false; } ptr->arr[i] = tmp; } } } break; } } p++; } return true; } void JSON_RPCSession::lock() { readfe((uint64_t *)&the_lock); } void JSON_RPCSession::unlock() { writeef((uint64_t *)&the_lock, 0); } bool JSON_RPCSession::is_timed_out() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec > last_touched + 30; } int64_t JSON_RPCSession::reset_timeout() { struct timeval tv; gettimeofday(&tv, NULL); return last_touched = tv.tv_sec; } int64_t JSON_RPCSession::get_session_id() { return session_id; } int64_t JSON_RPCSession::get_time_since() { return last_touched; } params_array_t::params_array_t():arr(NULL) {} params_array_t::~params_array_t() { if (arr) free (arr); } int64_t JSON_RPCServerState::get_next_session() { readfe((uint64_t *)&session_lock); int64_t rtn = next_session_id++; writeef((uint64_t *)&session_lock, 0); return rtn; } int64_t JSON_RPCServerState::add_session(int64_t session_id, JSON_RPCSession * session) { readfe((uint64_t *)&session_lock); if (active_session_map.size() < max_sessions) { active_session_map.insert( std::pair<int64_t, JSON_RPCSession *>(session_id, session) ); } else { session_id = -1; } writeef((uint64_t *)&session_lock, 0); return session_id; } int64_t JSON_RPCServerState::destroy_session(int64_t session_id) { readfe((uint64_t *)&session_lock); delete active_session_map[session_id]; int64_t rtn = active_session_map.erase (session_id); writeef((uint64_t *)&session_lock, 0); return rtn; } int64_t JSON_RPCServerState::get_num_sessions() { readfe((uint64_t *)&session_lock); int64_t rtn = active_session_map.size(); writeef((uint64_t *)&session_lock, 0); return rtn; } JSON_RPCSession * JSON_RPCServerState::get_session(int64_t session_id) { readfe((uint64_t *)&session_lock); std::map<int64_t, JSON_RPCSession *>::iterator tmp = active_session_map.find(session_id); writeef((uint64_t *)&session_lock, 0); if (tmp == active_session_map.end()) return NULL; else return tmp->second; }
check for params being array in contains_params
check for params being array in contains_params
C++
bsd-3-clause
davidediger/stinger,ogreen/stinger,sirpoovey/stinger,sirpoovey/stinger,ogreen/stinger,sirpoovey/stinger,ogreen/stinger,ehein6/stinger,ehein6/stinger,davidediger/stinger,sirpoovey/stinger,ehein6/stinger,sirpoovey/stinger,ehein6/stinger,ogreen/stinger,ehein6/stinger,ehein6/stinger,ogreen/stinger,davidediger/stinger,davidediger/stinger,davidediger/stinger,davidediger/stinger,ogreen/stinger,sirpoovey/stinger
a03201b1569c99b11fd61c1ca60871516e03e270
test/unit/WorkQueuePerfTest.cpp
test/unit/WorkQueuePerfTest.cpp
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "WorkQueue.h" #include <chrono> #include <random> //========== // Test for performance //========== template <typename T> double calculate_speedup(std::vector<int>& wait_times, int num_threads) { auto wq = workqueue_mapreduce<int, int>( [](int a) { boost::this_thread::sleep_for(T(a)); return a; }, [](int a, int b) { return a + b; }, num_threads); for (auto& item : wait_times) { wq.add_item(item); } auto single_start = std::chrono::high_resolution_clock::now(); auto sum = 0; for (auto& item : wait_times) { boost::this_thread::sleep_for(T(item)); sum += item; } auto single_end = std::chrono::high_resolution_clock::now(); auto para_start = std::chrono::high_resolution_clock::now(); auto para_sum = wq.run_all(); auto para_end = std::chrono::high_resolution_clock::now(); assert(sum == para_sum); double duration1 = std::chrono::duration_cast<T>(single_end - single_start).count(); double duration2 = std::chrono::duration_cast<T>(para_end - para_start).count(); double speedup = duration1 / duration2; return speedup; } void profileBusyLoop() { std::vector<int> times; for (int i = 0; i < 1000; ++i) { times.push_back(20); } double speedup = calculate_speedup<std::chrono::milliseconds>( times, boost::thread::hardware_concurrency()); printf("speedup busy loop: %f\n", speedup); } void variableLengthTasks() { std::vector<int> times; for (int i = 0; i < 50; ++i) { auto secs = rand() % 1000; times.push_back(secs); } double speedup = calculate_speedup<std::chrono::milliseconds>(times, 8); printf("speedup variable length tasks: %f\n", speedup); } void smallLengthTasks() { std::vector<int> times; for (int i = 0; i < 1000; ++i) { times.push_back(10); } double speedup = calculate_speedup<std::chrono::microseconds>(times, 8); printf("speedup small length tasks: %f\n", speedup); } int main() { printf("Begin!\n"); profileBusyLoop(); variableLengthTasks(); smallLengthTasks(); }
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "WorkQueue.h" #include <thread> #include <chrono> #include <random> //========== // Test for performance //========== template <typename T> double calculate_speedup(std::vector<int>& wait_times, int num_threads) { auto wq = workqueue_mapreduce<int, int>( [](int a) { std::this_thread::sleep_for(T(a)); return a; }, [](int a, int b) { return a + b; }, num_threads); for (auto& item : wait_times) { wq.add_item(item); } auto single_start = std::chrono::high_resolution_clock::now(); auto sum = 0; for (auto& item : wait_times) { std::this_thread::sleep_for(T(item)); sum += item; } auto single_end = std::chrono::high_resolution_clock::now(); auto para_start = std::chrono::high_resolution_clock::now(); auto para_sum = wq.run_all(); auto para_end = std::chrono::high_resolution_clock::now(); assert(sum == para_sum); double duration1 = std::chrono::duration_cast<T>(single_end - single_start).count(); double duration2 = std::chrono::duration_cast<T>(para_end - para_start).count(); double speedup = duration1 / duration2; return speedup; } void profileBusyLoop() { std::vector<int> times; for (int i = 0; i < 1000; ++i) { times.push_back(20); } double speedup = calculate_speedup<std::chrono::milliseconds>( times, std::thread::hardware_concurrency()); printf("speedup busy loop: %f\n", speedup); } void variableLengthTasks() { std::vector<int> times; for (int i = 0; i < 50; ++i) { auto secs = rand() % 1000; times.push_back(secs); } double speedup = calculate_speedup<std::chrono::milliseconds>(times, 8); printf("speedup variable length tasks: %f\n", speedup); } void smallLengthTasks() { std::vector<int> times; for (int i = 0; i < 1000; ++i) { times.push_back(10); } double speedup = calculate_speedup<std::chrono::microseconds>(times, 8); printf("speedup small length tasks: %f\n", speedup); } int main() { printf("Begin!\n"); profileBusyLoop(); variableLengthTasks(); smallLengthTasks(); }
fix work-queue-perf-test
fix work-queue-perf-test Summary: Sleep call with units from matching library It would be nice if we just used boost thread/chrono throughout. I tried to add boost_chrono as a dependency but it's not headerless and the third party libs haven't already built them. Adding the source myself became a huge hassle and I gave up. Reviewed By: int3, minjang Differential Revision: D6954134 fbshipit-source-id: e7d7273d5dad75ab98ba3eaa084f2ee911518658
C++
mit
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
6ce47c3f8b926dd6a8975ec10f61534b8ecc7317
src/cis-splice-effects/cis_splice_effects_associator.cc
src/cis-splice-effects/cis_splice_effects_associator.cc
/* cis_splice_effects_associator.cc -- 'cis-splice-effects associate' methods Copyright (c) 2015, The Griffith Lab Author: Avinash Ramu <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdexcept> #include <set> #include "common.h" #include "cis_splice_effects_associator.h" #include "junctions_annotator.h" #include "junctions_extractor.h" #include "variants_annotator.h" //Usage for this tool void CisSpliceEffectsAssociator::usage(ostream& out) { out << "Usage:" << "\t\t" << "regtools cis-splice-effects associate [options] variants.vcf junctions.bed ref.fa annotations.gtf" << endl; out << "Options:" << endl; out << "\t\t" << "-o STR\tOutput file containing the aberrant splice junctions with annotations. [STDOUT]" << endl; out << "\t\t" << "-v STR\tOutput file containing variants annotated as splice relevant (VCF format)." << endl; out << "\t\t" << "-j STR\tOutput file containing the aberrant junctions in BED12 format." << endl; out << "\t\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum \n" << "\t\t\t " << "anchor length on both sides are reported. [8]" << endl; out << "\t\t" << "-m INT\tMinimum intron length. [70]" << endl; out << "\t\t" << "-M INT\tMaximum intron length. [500000]" << endl; out << "\t\t" << "-w INT\tWindow size in b.p to identify splicing events in.\n" << "\t\t\t " << "The tool identifies events in variant.start +/- w basepairs.\n" << "\t\t\t " << "Default behaviour is to look at the window between previous and next exons." << endl; out << "\t\t" << "-e INT\tMaximum distance from the start/end of an exon \n" << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n" << "\t\t\t " << "is in exonic space, i.e a coding variant. [3]" << endl; out << "\t\t" << "-i INT\tMaximum distance from the start/end of an exon \n" << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n" << "\t\t\t " << "is in intronic space. [2]" << endl; out << "\t\t" << "-I\tAnnotate variants in intronic space within a transcript(not to be used with -i)." << endl; out << "\t\t" << "-E\tAnnotate variants in exonic space within a transcript(not to be used with -e)." << endl; out << "\t\t" << "-S\tDon't skip single exon transcripts." << endl; out << endl; } //Return stream to write output to void CisSpliceEffectsAssociator::close_ostream() { if(ofs_.is_open()) ofs_.close(); } //Return stream to write output to //If output file is not empty, attempt to open //If output file is empty, set to cout void CisSpliceEffectsAssociator::set_ostream() { if(output_file_ == "NA") { common::copy_stream(cout, ofs_); } else { ofs_.open(output_file_.c_str()); if(!ofs_.is_open()) throw runtime_error("Unable to open " + output_file_); } if(output_junctions_bed_ != "NA") { ofs_junctions_bed_.open(output_junctions_bed_.c_str()); if(!ofs_junctions_bed_.is_open()) throw runtime_error("Unable to open " + output_junctions_bed_); } } //Do QC on files void CisSpliceEffectsAssociator::file_qc() { if(vcf_ == "NA" || bed_ == "NA" || ref_ == "NA" || gtf_ == "NA") { usage(std::cout); throw runtime_error("Error parsing inputs!(2)\n\n"); } if(!common::file_exists(vcf_) || !common::file_exists(bed_) || !common::file_exists(ref_) || !common::file_exists(gtf_)) { throw runtime_error("Please make sure input files exist.\n\n"); } } //Parse command line options void CisSpliceEffectsAssociator::parse_options(int argc, char* argv[]) { optind = 1; //Reset before parsing again. stringstream help_ss; char c; while((c = getopt(argc, argv, "o:w:v:j:e:Ei:ISha:m:M:")) != -1) { switch(c) { case 'o': output_file_ = string(optarg); break; case 'w': window_size_ = atoi(optarg); break; case 'v': annotated_variant_file_ = string(optarg); break; case 'j': output_junctions_bed_ = string(optarg); break; case 'i': intronic_min_distance_ = atoi(optarg); break; case 'e': exonic_min_distance_ = atoi(optarg); break; case 'I': all_intronic_space_ = true; break; case 'E': all_exonic_space_ = true; break; case 'S': skip_single_exon_genes_ = false; break; case 'h': usage(help_ss); throw common::cmdline_help_exception(help_ss.str()); default: usage(std::cerr); throw runtime_error("Error parsing inputs!(1)\n\n"); } } if(argc - optind >= 4) { vcf_ = string(argv[optind++]); bed_ = string(argv[optind++]); ref_ = string(argv[optind++]); gtf_ = string(argv[optind++]); } if(optind < argc || vcf_ == "NA" || bed_ == "NA" || ref_ == "NA" || gtf_ == "NA"){ usage(std::cerr); throw runtime_error("Error parsing inputs!(2)\n\n"); } file_qc(); cerr << "Variant file: " << vcf_ << endl; cerr << "Junctions BED file: " << bed_ << endl; cerr << "Reference fasta file: " << ref_ << endl; cerr << "Annotation file: " << gtf_ << endl; if(window_size_ != 0) { cerr << "Window size: " << window_size_ << endl; } if(output_file_ != "NA") cerr << "Output file: " << output_file_ << endl; if(output_junctions_bed_ != "NA") cerr << "Output junctions BED file: " << output_junctions_bed_ << endl; if(annotated_variant_file_ != "NA") { cerr << "Annotated variants file: " << annotated_variant_file_ << endl; write_annotated_variants_ = true; } cerr << endl; } //Call the junctions annotator; duplication of identify void CisSpliceEffectsAssociator::annotate_junctions(const GtfParser& gp1) { JunctionsAnnotator ja1(ref_, gp1); ja1.set_gtf_parser(gp1); set_ostream(); //Annotate the junctions in the set and write to file AnnotatedJunction::print_header(ofs_, true); int i = 0; //This is ugly, waiting to start using C++11/14 for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) { Junction j = *j1; AnnotatedJunction line(j); ja1.get_splice_site(line); ja1.annotate_junction_with_gtf(line); line.name = j.name = get_junction_name(++i); if(output_junctions_bed_ != "NA") { j.print(ofs_junctions_bed_); } line.variant_info = variant_set_to_string(junction_to_variant_[j]); line.print(ofs_, true); } close_ostream(); } //get name for the junction; duplication of identify string CisSpliceEffectsAssociator::get_junction_name(int i) { stringstream name_ss; name_ss << "JUNC" << setfill('0') << setw(8) << i; return name_ss.str(); } //parse BED into vector of junctions vector<Junction> CisSpliceEffectsAssociator::parse_BED_to_junctions(){ vector<Junction> junctions; JunctionsAnnotator anno(bed_); BED line; Junction junc; anno.open_junctions(); while(anno.get_single_junction(line)) { junc.chrom = line.fields[0]; junc.thick_start = line.start; junc.thick_end = line.end; anno.adjust_junction_ends(line); junc.start = line.start; junc.end = line.end-1; //will block ends need to be fixed? junc.name = line.fields[3]; junc.score = line.fields[4]; junc.read_count = common::str_to_num(junc.score); junc.strand = line.fields[5]; junc.color = line.fields[8]; junc.nblocks = common::str_to_num(line.fields[9]); junc.has_left_min_anchor = true; junc.has_right_min_anchor = true; junctions.push_back(junc); // are we making a copy or just adding a pointer? } anno.close_junctions(); return junctions; } //The workhorse void CisSpliceEffectsAssociator::associate() { //GTF parser object GtfParser gp1(gtf_); gp1.load(); //variant annotator VariantsAnnotator va(vcf_, gp1, annotated_variant_file_, intronic_min_distance_, exonic_min_distance_, all_intronic_space_, all_exonic_space_, skip_single_exon_genes_); va.open_vcf_in(); if(write_annotated_variants_) va.open_vcf_out(); cerr << endl; //Get junctions from BED vector<Junction> junctions = parse_BED_to_junctions(); //Annotate each variant and pay attention to splicing related ones while(va.read_next_record()) { AnnotatedVariant v1 = va.annotate_record_with_transcripts(); if(v1.annotation != non_splice_region_annotation_string) { string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) : common::num_to_str(v1.cis_effect_start); string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) : common::num_to_str(v1.cis_effect_end); string variant_region = v1.chrom + ":" + region_start + "-" + region_end; cerr << "Variant " << v1; cerr << "Variant region is " << variant_region << endl; cerr << endl; if(write_annotated_variants_) va.write_annotation_output(v1); //Add all the junctions to the unique set for (size_t i = 0; i < junctions.size(); i++) { //Allow partial overlap - either junction start or end is within window if((junctions[i].start >= v1.cis_effect_start && junctions[i].start <= v1.cis_effect_end) || (junctions[i].end <= v1.cis_effect_end && junctions[i].end >= v1.cis_effect_start)) { unique_junctions_.insert(junctions[i]); //add to the map of junctions to variants junction_to_variant_[junctions[i]].insert(v1); } } } } annotate_junctions(gp1); }
/* cis_splice_effects_associator.cc -- 'cis-splice-effects associate' methods Copyright (c) 2015, The Griffith Lab Author: Avinash Ramu <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdexcept> #include <set> #include "common.h" #include "cis_splice_effects_associator.h" #include "junctions_annotator.h" #include "junctions_extractor.h" #include "variants_annotator.h" //Usage for this tool void CisSpliceEffectsAssociator::usage(ostream& out) { out << "Usage:" << "\t\t" << "regtools cis-splice-effects associate [options] variants.vcf junctions.bed ref.fa annotations.gtf" << endl; out << "Options:" << endl; out << "\t\t" << "-o STR\tOutput file containing the aberrant splice junctions with annotations. [STDOUT]" << endl; out << "\t\t" << "-v STR\tOutput file containing variants annotated as splice relevant (VCF format)." << endl; out << "\t\t" << "-j STR\tOutput file containing the aberrant junctions in BED12 format." << endl; out << "\t\t" << "-a INT\tMinimum anchor length. Junctions which satisfy a minimum \n" << "\t\t\t " << "anchor length on both sides are reported. [8]" << endl; out << "\t\t" << "-m INT\tMinimum intron length. [70]" << endl; out << "\t\t" << "-M INT\tMaximum intron length. [500000]" << endl; out << "\t\t" << "-w INT\tWindow size in b.p to identify splicing events in.\n" << "\t\t\t " << "The tool identifies events in variant.start +/- w basepairs.\n" << "\t\t\t " << "Default behaviour is to look at the window between previous and next exons." << endl; out << "\t\t" << "-e INT\tMaximum distance from the start/end of an exon \n" << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n" << "\t\t\t " << "is in exonic space, i.e a coding variant. [3]" << endl; out << "\t\t" << "-i INT\tMaximum distance from the start/end of an exon \n" << "\t\t\t " << "to annotate a variant as relevant to splicing, the variant \n" << "\t\t\t " << "is in intronic space. [2]" << endl; out << "\t\t" << "-I\tAnnotate variants in intronic space within a transcript(not to be used with -i)." << endl; out << "\t\t" << "-E\tAnnotate variants in exonic space within a transcript(not to be used with -e)." << endl; out << "\t\t" << "-S\tDon't skip single exon transcripts." << endl; out << endl; } //Return stream to write output to void CisSpliceEffectsAssociator::close_ostream() { if(ofs_.is_open()) ofs_.close(); } //Return stream to write output to //If output file is not empty, attempt to open //If output file is empty, set to cout void CisSpliceEffectsAssociator::set_ostream() { if(output_file_ == "NA") { common::copy_stream(cout, ofs_); } else { ofs_.open(output_file_.c_str()); if(!ofs_.is_open()) throw runtime_error("Unable to open " + output_file_); } if(output_junctions_bed_ != "NA") { ofs_junctions_bed_.open(output_junctions_bed_.c_str()); if(!ofs_junctions_bed_.is_open()) throw runtime_error("Unable to open " + output_junctions_bed_); } } //Do QC on files void CisSpliceEffectsAssociator::file_qc() { if(vcf_ == "NA" || bed_ == "NA" || ref_ == "NA" || gtf_ == "NA") { usage(std::cout); throw runtime_error("Error parsing inputs!(2)\n\n"); } if(!common::file_exists(vcf_) || !common::file_exists(bed_) || !common::file_exists(ref_) || !common::file_exists(gtf_)) { throw runtime_error("Please make sure input files exist.\n\n"); } } //Parse command line options void CisSpliceEffectsAssociator::parse_options(int argc, char* argv[]) { optind = 1; //Reset before parsing again. stringstream help_ss; char c; while((c = getopt(argc, argv, "o:w:v:j:e:Ei:ISha:m:M:")) != -1) { switch(c) { case 'o': output_file_ = string(optarg); break; case 'w': window_size_ = atoi(optarg); break; case 'v': annotated_variant_file_ = string(optarg); break; case 'j': output_junctions_bed_ = string(optarg); break; case 'i': intronic_min_distance_ = atoi(optarg); break; case 'e': exonic_min_distance_ = atoi(optarg); break; case 'I': all_intronic_space_ = true; break; case 'E': all_exonic_space_ = true; break; case 'S': skip_single_exon_genes_ = false; break; case 'h': usage(help_ss); throw common::cmdline_help_exception(help_ss.str()); default: usage(std::cerr); throw runtime_error("Error parsing inputs!(1)\n\n"); } } if(argc - optind >= 4) { vcf_ = string(argv[optind++]); bed_ = string(argv[optind++]); ref_ = string(argv[optind++]); gtf_ = string(argv[optind++]); } if(optind < argc || vcf_ == "NA" || bed_ == "NA" || ref_ == "NA" || gtf_ == "NA"){ usage(std::cerr); throw runtime_error("Error parsing inputs!(2)\n\n"); } file_qc(); cerr << "Variant file: " << vcf_ << endl; cerr << "Junctions BED file: " << bed_ << endl; cerr << "Reference fasta file: " << ref_ << endl; cerr << "Annotation file: " << gtf_ << endl; if(window_size_ != 0) { cerr << "Window size: " << window_size_ << endl; } if(output_file_ != "NA") cerr << "Output file: " << output_file_ << endl; if(output_junctions_bed_ != "NA") cerr << "Output junctions BED file: " << output_junctions_bed_ << endl; if(annotated_variant_file_ != "NA") { cerr << "Annotated variants file: " << annotated_variant_file_ << endl; write_annotated_variants_ = true; } cerr << endl; } //Call the junctions annotator; duplication of identify void CisSpliceEffectsAssociator::annotate_junctions(const GtfParser& gp1) { JunctionsAnnotator ja1(ref_, gp1); ja1.set_gtf_parser(gp1); set_ostream(); //Annotate the junctions in the set and write to file AnnotatedJunction::print_header(ofs_, true); int i = 0; //This is ugly, waiting to start using C++11/14 for (set<Junction>::iterator j1 = unique_junctions_.begin(); j1 != unique_junctions_.end(); j1++) { Junction j = *j1; AnnotatedJunction line(j); ja1.get_splice_site(line); ja1.annotate_junction_with_gtf(line); line.name = j.name = get_junction_name(++i); if(output_junctions_bed_ != "NA") { j.print(ofs_junctions_bed_); } line.variant_info = variant_set_to_string(junction_to_variant_[j]); line.print(ofs_, true); } close_ostream(); } //get name for the junction; duplication of identify string CisSpliceEffectsAssociator::get_junction_name(int i) { stringstream name_ss; name_ss << "JUNC" << setfill('0') << setw(8) << i; return name_ss.str(); } //parse BED into vector of junctions vector<Junction> CisSpliceEffectsAssociator::parse_BED_to_junctions(){ vector<Junction> junctions; JunctionsAnnotator anno(bed_); BED line; Junction junc; anno.open_junctions(); while(anno.get_single_junction(line)) { junc.chrom = line.fields[0]; junc.thick_start = line.start; junc.thick_end = line.end; anno.adjust_junction_ends(line); junc.start = line.start; junc.end = line.end-1; //will block ends need to be fixed? junc.name = line.fields[3]; junc.score = line.fields[4]; junc.read_count = common::str_to_num(junc.score); junc.strand = line.fields[5]; junc.color = line.fields[8]; junc.nblocks = common::str_to_num(line.fields[9]); junc.has_left_min_anchor = true; junc.has_right_min_anchor = true; junctions.push_back(junc); // are we making a copy or just adding a pointer? } anno.close_junctions(); return junctions; } //The workhorse void CisSpliceEffectsAssociator::associate() { //GTF parser object GtfParser gp1(gtf_); gp1.load(); //variant annotator VariantsAnnotator va(vcf_, gp1, annotated_variant_file_, intronic_min_distance_, exonic_min_distance_, all_intronic_space_, all_exonic_space_, skip_single_exon_genes_); va.open_vcf_in(); if(write_annotated_variants_) va.open_vcf_out(); cerr << endl; //Get junctions from BED vector<Junction> junctions = parse_BED_to_junctions(); //Annotate each variant and pay attention to splicing related ones while(va.read_next_record()) { AnnotatedVariant v1 = va.annotate_record_with_transcripts(); if(v1.annotation != non_splice_region_annotation_string) { string region_start = window_size_ ? common::num_to_str(v1.start - window_size_) : common::num_to_str(v1.cis_effect_start); string region_end = window_size_ ? common::num_to_str(v1.end + window_size_) : common::num_to_str(v1.cis_effect_end); string variant_region = v1.chrom + ":" + region_start + "-" + region_end; cerr << "Variant " << v1; cerr << "Variant region is " << variant_region << endl; cerr << endl; if(write_annotated_variants_) va.write_annotation_output(v1); //Add all the junctions to the unique set for (size_t i = 0; i < junctions.size(); i++) { //Allow partial overlap - either junction start or end is within window if(junctions[i].chrom ==v1.chrom && ((junctions[i].start >= v1.cis_effect_start && junctions[i].start <= v1.cis_effect_end) || (junctions[i].end <= v1.cis_effect_end && junctions[i].end >= v1.cis_effect_start))) { unique_junctions_.insert(junctions[i]); //add to the map of junctions to variants junction_to_variant_[junctions[i]].insert(v1); } } } } annotate_junctions(gp1); }
check chrom in associate
check chrom in associate
C++
mit
griffithlab/regtools,griffithlab/regtools,griffithlab/regtools,griffithlab/regtools,griffithlab/regtools,griffithlab/regtools
d38979894c6f2591fbe54fdf87fee59ffff18ca7
RawSpeed/PefDecoder.cpp
RawSpeed/PefDecoder.cpp
#include "StdAfx.h" #include "PefDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { PefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD) { decoderVersion = 3; } PefDecoder::~PefDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage PefDecoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) ThrowRDE("PEF Decoder: No image data found"); TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); if (1 == compression || compression == 32773) { decodeUncompressed(raw, BitOrder_Jpeg); return mRaw; } if (65535 != compression) ThrowRDE("PEF Decoder: Unsupported compression"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("PEF Decoder: Multiple Strips found: %u", offsets->count); } if (counts->count != offsets->count) { ThrowRDE("PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count); } if (!mFile->isValid(offsets->getInt() + counts->getInt())) ThrowRDE("PEF Decoder: Truncated file."); uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); try { PentaxDecompressor l(mFile, mRaw); l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt()); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } return mRaw; } void PefDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("PEF Support check: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("PEF Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void PefDecoder::decodeMetaDataInternal(CameraMetaData *meta) { int iso = 0; mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("PEF Meta Decoder: Model name found"); TiffIFD* raw = data[0]; string make = raw->getEntry(MAKE)->getString(); string model = raw->getEntry(MODEL)->getString(); if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); // Read black level if (mRootIFD->hasEntryRecursive((TiffTag)0x200)) { TiffEntry *black = mRootIFD->getEntryRecursive((TiffTag)0x200); const ushort16 *levels = black->getShortArray(); for (int i = 0; i < 4; i++) mRaw->blackLevelSeparate[i] = levels[i]; } } } // namespace RawSpeed
#include "StdAfx.h" #include "PefDecoder.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { PefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) : RawDecoder(file), mRootIFD(rootIFD) { decoderVersion = 3; } PefDecoder::~PefDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; } RawImage PefDecoder::decodeRawInternal() { // Set the whitebalance if (mRootIFD->hasEntryRecursive((TiffTag) 0x0201)) { TiffEntry *wb = mRootIFD->getEntryRecursive((TiffTag) 0x0201); if (wb->count != 4) ThrowRDE("PEF: WB has %d entries instead of 4", wb->count); const ushort16 *tmp = wb->getShortArray(); mRaw->wbCoeffs[0] = tmp[0]; mRaw->wbCoeffs[1] = tmp[1]; mRaw->wbCoeffs[2] = tmp[3]; } vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) ThrowRDE("PEF Decoder: No image data found"); TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); if (1 == compression || compression == 32773) { decodeUncompressed(raw, BitOrder_Jpeg); return mRaw; } if (65535 != compression) ThrowRDE("PEF Decoder: Unsupported compression"); TiffEntry *offsets = raw->getEntry(STRIPOFFSETS); TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS); if (offsets->count != 1) { ThrowRDE("PEF Decoder: Multiple Strips found: %u", offsets->count); } if (counts->count != offsets->count) { ThrowRDE("PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count); } if (!mFile->isValid(offsets->getInt() + counts->getInt())) ThrowRDE("PEF Decoder: Truncated file."); uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); try { PentaxDecompressor l(mFile, mRaw); l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt()); } catch (IOException &e) { mRaw->setError(e.what()); // Let's ignore it, it may have delivered somewhat useful data. } return mRaw; } void PefDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("PEF Support check: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("PEF Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void PefDecoder::decodeMetaDataInternal(CameraMetaData *meta) { int iso = 0; mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("PEF Meta Decoder: Model name found"); TiffIFD* raw = data[0]; string make = raw->getEntry(MAKE)->getString(); string model = raw->getEntry(MODEL)->getString(); if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); // Read black level if (mRootIFD->hasEntryRecursive((TiffTag)0x200)) { TiffEntry *black = mRootIFD->getEntryRecursive((TiffTag)0x200); const ushort16 *levels = black->getShortArray(); for (int i = 0; i < 4; i++) mRaw->blackLevelSeparate[i] = levels[i]; } } } // namespace RawSpeed
Implement whitebalance for PEF files
Implement whitebalance for PEF files
C++
lgpl-2.1
darktable-org/rawspeed,LebedevRI/rawspeed,mgehre/rawspeed,klauspost/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,mgehre/rawspeed,anarsoul/rawspeed,anarsoul/rawspeed,klauspost/rawspeed,anarsoul/rawspeed,LebedevRI/rawspeed
552a701526e965755c1133b6f95361880b8d88cd
src/sw/settings/src/sw.settings.program_name.cpp
src/sw/settings/src/sw.settings.program_name.cpp
#include <string> #if defined(CPPAN_EXECUTABLE) namespace sw { std::string getProgramName() { return PACKAGE_NAME_CLEAN; } } namespace primitives { std::string getVersionString() { std::string s; s += ::sw::getProgramName(); s += " version "; s += PACKAGE_VERSION; return s; } } #endif
#ifndef _MSC_VER #include <primitives/sw/settings.h> #else #include <string> #endif #if defined(CPPAN_EXECUTABLE) namespace sw { std::string getProgramName() { return PACKAGE_NAME_CLEAN; } } namespace primitives { std::string getVersionString() { std::string s; s += ::sw::getProgramName(); s += " version "; s += PACKAGE_VERSION; return s; } } #endif
Fix linux build.
Fix linux build.
C++
mpl-2.0
egorpugin/primitives,egorpugin/primitives
cc4fbca77def183312491d75d51017551bdd5707
You-QueryEngine/comparator.cpp
You-QueryEngine/comparator.cpp
#include "stdafx.h" #include "comparator.h" namespace You { namespace QueryEngine { Comparator Comparator::notSorted() { return Comparator([](const Task&, const Task&) { return ComparisonResult::GT; }); } Comparator Comparator::byDescription() { return byApplying<Task::Description>([](const Task& task) { return task.getDescription(); }); } Comparator Comparator::byDeadline() { return byApplying<Task::Time>([](const Task& task) { return task.getDeadline(); }); } Comparator Comparator::byDependenciesCount() { return byApplying<int>([](const Task& task) { return task.getDependencies().size(); }); } Comparator Comparator::byPriority() { return byApplying<int>([](const Task& task) { if (task.getPriority() == Task::Priority::NORMAL) { return 1; } else { return 0; } }); } Comparator::Comparator(const ComparatorFunc& func) { comparators.push_back(func); } bool Comparator::operator() (const Task& lhs, const Task& rhs) const { for (auto comparator = comparators.cbegin(); comparator != comparators.cend(); ++comparator) { ComparisonResult result = (*comparator)(lhs, rhs); if (result != ComparisonResult::EQ) { return result == ComparisonResult::LT; } else { continue; } } /// If identical, assume greater than. return true; } void Comparator::negateAllComparators() { std::vector<const ComparatorFunc> newComparators; std::for_each(comparators.cbegin(), comparators.cend(), [&] (const ComparatorFunc& func) { newComparators.push_back(this->negate(func)); } ); comparators = newComparators; } Comparator& Comparator::ascending() { if (!isAscending) { negateAllComparators(); } isAscending = true; return *this; } Comparator& Comparator::descending() { if (isAscending) { negateAllComparators(); } isAscending = false; return *this; } Comparator& Comparator::operator&&(const Comparator& rhs) { comparators.insert(comparators.end(), rhs.comparators.begin(), rhs.comparators.end()); return *this; } Comparator::ComparatorFunc Comparator::negate(const ComparatorFunc& comp) { return [=] (const Task& lhs, const Task& rhs) { ComparisonResult result = comp(lhs, rhs); if (result == ComparisonResult::LT) { return ComparisonResult::GT; } else if (result == ComparisonResult::GT) { return ComparisonResult::LT; } else { return ComparisonResult::EQ; } }; } } // namespace QueryEngine } // namespace You
#include "stdafx.h" #include "comparator.h" namespace You { namespace QueryEngine { Comparator Comparator::notSorted() { return Comparator([](const Task&, const Task&) { return ComparisonResult::EQ; }); } Comparator Comparator::byDescription() { return byApplying<Task::Description>([](const Task& task) { return task.getDescription(); }); } Comparator Comparator::byDeadline() { return byApplying<Task::Time>([](const Task& task) { return task.getDeadline(); }); } Comparator Comparator::byDependenciesCount() { return byApplying<int>([](const Task& task) { return task.getDependencies().size(); }); } Comparator Comparator::byPriority() { return byApplying<int>([](const Task& task) { if (task.getPriority() == Task::Priority::NORMAL) { return 1; } else { return 0; } }); } Comparator::Comparator(const ComparatorFunc& func) { comparators.push_back(func); } bool Comparator::operator() (const Task& lhs, const Task& rhs) const { for (auto comparator = comparators.cbegin(); comparator != comparators.cend(); ++comparator) { ComparisonResult result = (*comparator)(lhs, rhs); if (result != ComparisonResult::EQ) { return result == ComparisonResult::LT; } else { continue; } } /// If identical, assume greater than. return true; } void Comparator::negateAllComparators() { std::vector<const ComparatorFunc> newComparators; std::for_each(comparators.cbegin(), comparators.cend(), [&] (const ComparatorFunc& func) { newComparators.push_back(this->negate(func)); } ); comparators = newComparators; } Comparator& Comparator::ascending() { if (!isAscending) { negateAllComparators(); } isAscending = true; return *this; } Comparator& Comparator::descending() { if (isAscending) { negateAllComparators(); } isAscending = false; return *this; } Comparator& Comparator::operator&&(const Comparator& rhs) { comparators.insert(comparators.end(), rhs.comparators.begin(), rhs.comparators.end()); return *this; } Comparator::ComparatorFunc Comparator::negate(const ComparatorFunc& comp) { return [=] (const Task& lhs, const Task& rhs) { ComparisonResult result = comp(lhs, rhs); if (result == ComparisonResult::LT) { return ComparisonResult::GT; } else if (result == ComparisonResult::GT) { return ComparisonResult::LT; } else { return ComparisonResult::EQ; } }; } } // namespace QueryEngine } // namespace You
Fix bug in identity comparator
Fix bug in identity comparator
C++
mit
cs2103aug2014-w10-1c/main,cs2103aug2014-w10-1c/main
35728323a1456c87db5cb9c292ea33890f98befc
lib/src/itm-solver-common.hpp
lib/src/itm-solver-common.hpp
/* Copyright (C) 2016-2018 INRA * * 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 ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_SOLVER_COMMON_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_SOLVER_COMMON_HPP #include <baryonyx/core-compare> #include <algorithm> #include <chrono> #include <functional> #include <random> #include <utility> #include <vector> #include "observer.hpp" #include "private.hpp" #include "sparse-matrix.hpp" #include "utils.hpp" namespace baryonyx { namespace itm { template<typename Solver, typename Float, typename Mode, typename Order, typename Random, typename Observer> struct solver_functor { std::chrono::time_point<std::chrono::steady_clock> m_begin; std::chrono::time_point<std::chrono::steady_clock> m_end; const context_ptr& m_ctx; Random& m_rng; result m_best; solver_functor(const context_ptr& ctx, Random& rng, const std::vector<std::string>& variable_names, const affected_variables& affected_vars) : m_ctx(ctx) , m_rng(rng) { m_best.affected_vars = affected_vars; m_best.variable_name = variable_names; } result operator()(const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { x_type x(variables); m_begin = std::chrono::steady_clock::now(); m_end = m_begin; int i = 0; int pushed = -1; int best_remaining = -1; int pushing_iteration = m_ctx->parameters.pushing_iteration_limit; const auto& p = m_ctx->parameters; const auto kappa_min = static_cast<Float>(p.kappa_min); const auto kappa_step = static_cast<Float>(p.kappa_step); const auto kappa_max = static_cast<Float>(p.kappa_max); const auto alpha = static_cast<Float>(p.alpha); const auto theta = static_cast<Float>(p.theta); const auto delta = p.delta < 0 ? compute_delta<Float>(m_ctx, norm_costs, theta, variables) : static_cast<Float>(p.delta); const auto pushing_k_factor = static_cast<Float>(p.pushing_k_factor); const auto pushing_objective_amplifier = static_cast<Float>(p.pushing_objective_amplifier); auto kappa = kappa_min; Solver slv( m_rng, length(constraints), variables, norm_costs, constraints); init_solver(slv, x, p.init_policy, p.init_random); Order compute(slv, x, m_rng); auto max_cost = max_cost_init(original_costs, variables, Mode()); bounds_printer<Float, Mode> bound_print(max_cost); Observer obs(slv, "img", p.limit); info(m_ctx, "* solver starts:\n"); m_best.variables = slv.m; m_best.constraints = slv.n; bool start_pushing = false; for (;;) { int remaining = compute.run(slv, x, kappa, delta, theta); obs.make_observation(); if (best_remaining == -1 || remaining < best_remaining) { best_remaining = remaining; m_best.duration = compute_duration(m_begin, m_end); m_best.loop = i; m_best.remaining_constraints = remaining; if (remaining == 0) { m_best.status = baryonyx::result_status::success; store_if_better( slv.results(x, original_costs, cost_constant), x, i); start_pushing = true; } else { // bound_print(slv, m_ctx, m_best); info(m_ctx, " - violated constraints: {}/{} at {}s (loop: {})\n", remaining, slv.m, compute_duration(m_begin, m_end), i); } } #ifndef BARYONYX_FULL_OPTIMIZATION print_solver(slv, x, m_ctx, m_best.variable_name, p.print_level); #endif if (start_pushing) { ++pushing_iteration; if (pushed == -1) info(m_ctx, " - start push system:\n"); if (pushing_iteration >= p.pushing_iteration_limit) { pushed++; pushing_iteration = 0; remaining = compute.push_and_run(slv, x, pushing_k_factor * kappa, delta, theta, pushing_objective_amplifier); if (remaining == 0) store_if_better( slv.results(x, original_costs, cost_constant), x, i); } if (pushed > p.pushes_limit) { info( m_ctx, " - Push system limit reached. Solution found: {}\n", m_best.solutions.back().value); return m_best; } } if (i > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); ++i; if (p.limit > 0 && i > p.limit) { info(m_ctx, " - Loop limit reached: {}\n", i); if (pushed == -1) m_best.status = result_status::limit_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } if (kappa > kappa_max) { info(m_ctx, " - Kappa max reached: {:+.6f}\n", kappa); if (pushed == -1) m_best.status = result_status::kappa_max_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } m_end = std::chrono::steady_clock::now(); if (is_time_limit(p.time_limit, m_begin, m_end)) { info(m_ctx, " - Time limit reached: {} {:+.6f}\n", i, kappa); if (pushed == -1) m_best.status = result_status::time_limit_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } } } private: void store_if_better(double current, const x_type& x, int i) { if (m_best.solutions.empty() || is_better_solution( current, m_best.solutions.back().value, Mode())) { m_best.solutions.emplace_back(x.data(), current); m_best.duration = compute_duration(m_begin, m_end); m_best.loop = i; m_best.solutions.emplace_back(x.data(), current); info(m_ctx, " - Best solution found: {:+.6f} (i={} t={}s)\n", current, m_best.loop, m_best.duration); } } }; template<typename Solver, typename Float, typename Mode, typename Order, typename Random> inline result solve_problem(const context_ptr& ctx, const problem& pb) { info(ctx, "- Solver initializing\n"); print(ctx); result ret; auto affected_vars = std::move(pb.affected_vars); auto constraints{ make_merged_constraints(ctx, pb) }; if (!constraints.empty() && !pb.vars.values.empty()) { Random rng(init_random_generator_seed<Random>(ctx)); auto variables = numeric_cast<int>(pb.vars.values.size()); auto cost = make_objective_function<Float>(pb.objective, variables); auto norm_costs = normalize_costs<Float, Random>(ctx, cost, rng, variables); auto cost_constant = pb.objective.value; auto names = std::move(pb.vars.names); switch (ctx->parameters.observer) { case solver_parameters::observer_type::pnm: { using obs = pnm_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); } break; case solver_parameters::observer_type::file: { using obs = file_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); } break; default: { using obs = none_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); break; } } ret.variable_name = std::move(names); } else { ret.status = result_status::success; } ret.affected_vars = std::move(affected_vars); return ret; } } // namespace itm } // namespace baryonyx #endif
/* Copyright (C) 2016-2018 INRA * * 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 ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_SOLVER_COMMON_HPP #define ORG_VLEPROJECT_BARYONYX_SOLVER_ITM_SOLVER_COMMON_HPP #include <baryonyx/core-compare> #include <algorithm> #include <chrono> #include <functional> #include <random> #include <utility> #include <vector> #include "observer.hpp" #include "private.hpp" #include "sparse-matrix.hpp" #include "utils.hpp" namespace baryonyx { namespace itm { template<typename Solver, typename Float, typename Mode, typename Order, typename Random, typename Observer> struct solver_functor { std::chrono::time_point<std::chrono::steady_clock> m_begin; std::chrono::time_point<std::chrono::steady_clock> m_end; const context_ptr& m_ctx; Random& m_rng; result m_best; solver_functor(const context_ptr& ctx, Random& rng, const std::vector<std::string>& variable_names, const affected_variables& affected_vars) : m_ctx(ctx) , m_rng(rng) { m_best.affected_vars = affected_vars; m_best.variable_name = variable_names; } result operator()(const std::vector<merged_constraint>& constraints, int variables, const std::unique_ptr<Float[]>& original_costs, const std::unique_ptr<Float[]>& norm_costs, double cost_constant) { x_type x(variables); m_begin = std::chrono::steady_clock::now(); m_end = m_begin; int i = 0; int pushed = -1; int best_remaining = -1; int pushing_iteration = 0; const auto& p = m_ctx->parameters; const auto kappa_min = static_cast<Float>(p.kappa_min); const auto kappa_step = static_cast<Float>(p.kappa_step); const auto kappa_max = static_cast<Float>(p.kappa_max); const auto alpha = static_cast<Float>(p.alpha); const auto theta = static_cast<Float>(p.theta); const auto delta = p.delta < 0 ? compute_delta<Float>(m_ctx, norm_costs, theta, variables) : static_cast<Float>(p.delta); const auto pushing_k_factor = static_cast<Float>(p.pushing_k_factor); const auto pushing_objective_amplifier = static_cast<Float>(p.pushing_objective_amplifier); auto kappa = kappa_min; Solver slv( m_rng, length(constraints), variables, norm_costs, constraints); init_solver(slv, x, p.init_policy, p.init_random); Order compute(slv, x, m_rng); auto max_cost = max_cost_init(original_costs, variables, Mode()); bounds_printer<Float, Mode> bound_print(max_cost); Observer obs(slv, "img", p.limit); info(m_ctx, "* solver starts:\n"); m_best.variables = slv.m; m_best.constraints = slv.n; bool start_pushing = false; for (;;) { int remaining = compute.run(slv, x, kappa, delta, theta); obs.make_observation(); if (best_remaining == -1 || remaining < best_remaining) { best_remaining = remaining; m_best.duration = compute_duration(m_begin, m_end); m_best.loop = i; m_best.remaining_constraints = remaining; if (remaining == 0) { m_best.status = baryonyx::result_status::success; store_if_better( slv.results(x, original_costs, cost_constant), x, i); start_pushing = true; } else { // bound_print(slv, m_ctx, m_best); info(m_ctx, " - violated constraints: {}/{} at {}s (loop: {})\n", remaining, slv.m, compute_duration(m_begin, m_end), i); } } #ifndef BARYONYX_FULL_OPTIMIZATION print_solver(slv, x, m_ctx, m_best.variable_name, p.print_level); #endif if (start_pushing) { ++pushing_iteration; if (pushed == -1) info(m_ctx, " - start push system:\n"); if (pushing_iteration >= p.pushing_iteration_limit) { pushed++; pushing_iteration = 0; remaining = compute.push_and_run(slv, x, pushing_k_factor * kappa, delta, theta, pushing_objective_amplifier); if (remaining == 0) store_if_better( slv.results(x, original_costs, cost_constant), x, i); } if (pushed > p.pushes_limit) { info( m_ctx, " - Push system limit reached. Solution found: {}\n", m_best.solutions.back().value); return m_best; } } if (i > p.w) kappa += kappa_step * std::pow(static_cast<Float>(remaining) / static_cast<Float>(slv.m), alpha); ++i; if (p.limit > 0 && i > p.limit) { info(m_ctx, " - Loop limit reached: {}\n", i); if (pushed == -1) m_best.status = result_status::limit_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } if (kappa > kappa_max) { info(m_ctx, " - Kappa max reached: {:+.6f}\n", kappa); if (pushed == -1) m_best.status = result_status::kappa_max_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } m_end = std::chrono::steady_clock::now(); if (is_time_limit(p.time_limit, m_begin, m_end)) { info(m_ctx, " - Time limit reached: {} {:+.6f}\n", i, kappa); if (pushed == -1) m_best.status = result_status::time_limit_reached; // if (context_get_integer_parameter(m_ctx, "print-level", 0) > // 0) // print_missing_constraint(m_ctx, // slv.ap, // slv.A, // m_best.variable_value, // slv.b, // m_variable_names); return m_best; } } } private: void store_if_better(double current, const x_type& x, int i) { if (m_best.solutions.empty() || is_better_solution( current, m_best.solutions.back().value, Mode())) { m_best.solutions.emplace_back(x.data(), current); m_best.duration = compute_duration(m_begin, m_end); m_best.loop = i; m_best.solutions.emplace_back(x.data(), current); info(m_ctx, " - Best solution found: {:+.6f} (i={} t={}s)\n", current, m_best.loop, m_best.duration); } } }; template<typename Solver, typename Float, typename Mode, typename Order, typename Random> inline result solve_problem(const context_ptr& ctx, const problem& pb) { info(ctx, "- Solver initializing\n"); print(ctx); result ret; auto affected_vars = std::move(pb.affected_vars); auto constraints{ make_merged_constraints(ctx, pb) }; if (!constraints.empty() && !pb.vars.values.empty()) { Random rng(init_random_generator_seed<Random>(ctx)); auto variables = numeric_cast<int>(pb.vars.values.size()); auto cost = make_objective_function<Float>(pb.objective, variables); auto norm_costs = normalize_costs<Float, Random>(ctx, cost, rng, variables); auto cost_constant = pb.objective.value; auto names = std::move(pb.vars.names); switch (ctx->parameters.observer) { case solver_parameters::observer_type::pnm: { using obs = pnm_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); } break; case solver_parameters::observer_type::file: { using obs = file_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); } break; default: { using obs = none_observer<Solver, Float>; solver_functor<Solver, Float, Mode, Order, Random, obs> slv( ctx, rng, names, affected_vars); ret = slv(constraints, variables, cost, norm_costs, cost_constant); break; } } ret.variable_name = std::move(names); } else { ret.status = result_status::success; } ret.affected_vars = std::move(affected_vars); return ret; } } // namespace itm } // namespace baryonyx #endif
fix push system in solver
itm: fix push system in solver
C++
mit
quesnel/baryonyx,quesnel/baryonyx,quesnel/baryonyx
f10d0545253705d9c76ca7637c52109ed0e2e14e
SnakePredictor/main.cpp
SnakePredictor/main.cpp
#include "stdafx.h" int main(int argc, char* args[]) { const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const String SCREEN_TITLE = "Snake Predictor"; const int SCREEN_FPS = 60; ScreenManager* _sys_screenManager = NULL; _sys_screenManager = new ScreenManager(); SDL_Window* _sys_window = _sys_screenManager->Initialize(SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT); printf("SDL START: Running Main Loop\n"); while (_sys_screenManager->Loop()) // Update game and check its still running { _sys_screenManager->Render(); // Render game SDL_Delay(1000 / SCREEN_FPS); // Lock to FPS } printf("SDL STOP: Unloading Everything\n"); // Game exited, so unload everything _sys_screenManager->UnloadAll(); printf("SDL EXIT: Destroying Window and Quitting\n"); SDL_DestroyWindow(_sys_window); SDL_Quit(); return 0; }
#include "stdafx.h" int main(int argc, char* args[]) { const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const String SCREEN_TITLE = "Snake Predictor"; const int SCREEN_FPS = 60; ScreenManager* _sys_screenManager = NULL; _sys_screenManager = new ScreenManager(); SDL_Window* _sys_window = _sys_screenManager->Initialize(SCREEN_TITLE, SCREEN_WIDTH, SCREEN_HEIGHT); printf("SDL START: Running Main Loop\n"); while (_sys_screenManager->Loop()) // Update screens and check its still running { _sys_screenManager->Render(); // Render screens SDL_Delay(1000 / SCREEN_FPS); // Lock to FPS } printf("SDL STOP: Unloading Everything\n"); // Game exited, so unload everything _sys_screenManager->UnloadAll(); printf("SDL EXIT: Destroying Window and Quitting\n"); SDL_DestroyWindow(_sys_window); SDL_Quit(); return 0; }
Make comments more consistent
Make comments more consistent
C++
mit
DanielMcAssey/SnakePredictor,DanielMcAssey/SnakePredictor
d1148455a59e8896f5584105c2b789911d6b3406
Source/CSpringSwing.cpp
Source/CSpringSwing.cpp
// // CSpringSwing.cpp // SwingGame // // Created by Tim Brier on 07/12/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "CSpringSwing.hpp" #include "CPlayer.hpp" // ============================================================================= // Static members // ----------------------------------------------------------------------------- float CSpringSwing::smMinStretchFactor = 1.0f; float CSpringSwing::smMaxStretchFactor = 7.5f; float CSpringSwing::smLaunchMultiplier = 500.0f; // ============================================================================= // CSpringSwing constructor/destructor // ----------------------------------------------------------------------------- CSpringSwing::CSpringSwing(CPlayer *theBob, CLevel *theParentLevel) : CSwing(theBob, theParentLevel) { } CSpringSwing::~CSpringSwing() { } // ============================================================================= // CSpringSwing::AttemptToAttach // ----------------------------------------------------------------------------- void CSpringSwing::AttemptToAttach(CVector2f theAimPoint) { // Call the parent method CSwing::AttemptToAttach(theAimPoint); // Remember the original length mOriginalLength = mLength; } // ============================================================================= // CSpringSwing::AttenuateGravity // ----------------------------------------------------------------------------- CVector2f CSpringSwing::AttenuateGravity(CVector2f gravity) { // Don't alter gravity return gravity; } // ============================================================================= // CSpringSwing::Update // ----------------------------------------------------------------------------- void CSpringSwing::Update(CTime elapsedTime) { if (mAttached) { // Update the length mLength = GetDistanceToBob(); HandleInput(elapsedTime); HandleCollisions(); } } // ============================================================================= // CSpringSwing::HandleInput // ----------------------------------------------------------------------------- void CSpringSwing::HandleInput(CTime elapsedTime) { // Do nothing } // ============================================================================= // CSpringSwing::RespondToAttach // ----------------------------------------------------------------------------- void CSpringSwing::RespondToAttach() { // Do nothing } // ============================================================================= // CSpringSwing::RespondToDetach // ----------------------------------------------------------------------------- void CSpringSwing::RespondToDetach() { // Shoot the player off towards the origin with a velocity related to how // far the spring has stretched CVector2f bobToOrigin = mOrigin - mBob->GetPosition(); bobToOrigin.Normalise(); float finalLength = GetDistanceToBob(); float stretchedFactor = finalLength / mOriginalLength; stretchedFactor = std::min(stretchedFactor, smMaxStretchFactor); // Only apply the springyness if we were stretched enough if (stretchedFactor >= smMinStretchFactor) { CVector2f launchVel = bobToOrigin * smLaunchMultiplier * stretchedFactor; mBob->SetVelocity(launchVel + mBob->GetVelocity()); DEBUG_LOG("ogLength: %f", mOriginalLength); DEBUG_LOG("finalLength: %f", finalLength); DEBUG_LOG("stretchedFactor: %f", stretchedFactor); DEBUG_LOG("launchVel: (%f, %f), magnitude: %f", launchVel.x, launchVel.y, launchVel.GetMagnitude()); } } // ============================================================================= // CSpringSwing::RespondToCollisionAt // ----------------------------------------------------------------------------- void CSpringSwing::RespondToCollisionAt(CVector2f intersectionPoint) { // Break on collision Detach(); }
// // CSpringSwing.cpp // SwingGame // // Created by Tim Brier on 07/12/2014. // Copyright (c) 2014 tbrier. All rights reserved. // // ============================================================================= // Include Files // ----------------------------------------------------------------------------- #include "CSpringSwing.hpp" #include "CPlayer.hpp" // ============================================================================= // Static members // ----------------------------------------------------------------------------- float CSpringSwing::smMinStretchFactor = 1.0f; float CSpringSwing::smMaxStretchFactor = 7.5f; float CSpringSwing::smLaunchMultiplier = 500.0f; // ============================================================================= // CSpringSwing constructor/destructor // ----------------------------------------------------------------------------- CSpringSwing::CSpringSwing(CPlayer *theBob, CLevel *theParentLevel) : CSwing(theBob, theParentLevel) { } CSpringSwing::~CSpringSwing() { } // ============================================================================= // CSpringSwing::AttemptToAttach // ----------------------------------------------------------------------------- void CSpringSwing::AttemptToAttach(CVector2f theAimPoint) { // Call the parent method CSwing::AttemptToAttach(theAimPoint); // Remember the original length mOriginalLength = mLength; } // ============================================================================= // CSpringSwing::AttenuateGravity // ----------------------------------------------------------------------------- CVector2f CSpringSwing::AttenuateGravity(CVector2f gravity) { // Don't alter gravity return gravity; } // ============================================================================= // CSpringSwing::Update // ----------------------------------------------------------------------------- void CSpringSwing::Update(CTime elapsedTime) { if (mAttached) { // Update the length mLength = GetDistanceToBob(); HandleInput(elapsedTime); HandleCollisions(); } } // ============================================================================= // CSpringSwing::HandleInput // ----------------------------------------------------------------------------- void CSpringSwing::HandleInput(CTime elapsedTime) { // Do nothing } // ============================================================================= // CSpringSwing::RespondToAttach // ----------------------------------------------------------------------------- void CSpringSwing::RespondToAttach() { // Do nothing } // ============================================================================= // CSpringSwing::RespondToDetach // ----------------------------------------------------------------------------- void CSpringSwing::RespondToDetach() { // Shoot the player off towards the origin with a velocity related to how // far the spring has stretched CVector2f bobToOrigin = mOrigin - mBob->GetPosition(); bobToOrigin.Normalise(); float finalLength = GetDistanceToBob(); float stretchedFactor = finalLength / mOriginalLength; stretchedFactor = std::min(stretchedFactor, smMaxStretchFactor); // Only apply the springyness if we were stretched enough if (stretchedFactor >= smMinStretchFactor) { CVector2f launchVel = bobToOrigin * smLaunchMultiplier * stretchedFactor; mBob->SetVelocity(launchVel + mBob->GetVelocity()); } } // ============================================================================= // CSpringSwing::RespondToCollisionAt // ----------------------------------------------------------------------------- void CSpringSwing::RespondToCollisionAt(CVector2f intersectionPoint) { // Break on collision Detach(); }
Remove some logging
Remove some logging
C++
mit
sizlo/SwingGame,sizlo/SwingGame,sizlo/SwingGame
4ef1d94e3f995ce7a378bb7c48579f4c39e1945e
src/utils/FileRecordTools/FileRecordMergeMgr.cpp
src/utils/FileRecordTools/FileRecordMergeMgr.cpp
/* * FileRecordMergeMgr.cpp * * Created on: Mar 19, 2014 * Author: nek3d */ #include "FileRecordMergeMgr.h" FileRecordMergeMgr::FileRecordMergeMgr(const QuickString & filename) : FileRecordMgr(filename), _desiredStrand(ANY_STRAND), _maxDistance(0) { } //Record *FileRecordMergeMgr::allocateAndGetNextMergedRecord(WANT_STRAND_TYPE desiredStrand, int maxDistance) { // RecordKeyList recList; // if (!allocateAndGetNextMergedRecord(recList, desiredStrand, maxDistance)) { // return NULL; // } // deleteAllMergedItemsButKey(recList); // return const_cast<Record *>(recList.getKey()); //want key to be non-const //} Record *FileRecordMergeMgr::getNextRecord(RecordKeyList *recList) { if (!recList->allClear()) { deleteMergedRecord(*recList); } _mustBeForward = _desiredStrand == SAME_STRAND_FORWARD; _mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE; Record *startRecord = tryToTakeFromStorage(); // if we couldn't use a previously stored record for starters, //then begin with a new one that matches strand criteria. while (startRecord == NULL) { startRecord = FileRecordMgr::getNextRecord(); if (startRecord == NULL) { //hit EOF!! return NULL; } if ((_mustBeForward && (startRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (startRecord->getStrandVal() != Record::REVERSE))) { //record is reverse, only want forward, OR record is forward, wanted reverse deleteRecord(startRecord); startRecord = NULL; continue; } if (startRecord->getStrandVal() == Record::UNKNOWN && _desiredStrand != ANY_STRAND) { //there is an unknown strand, but the user specified strandedness. deleteRecord(startRecord); startRecord = NULL; } } // OK!! We have a start record! Re-evaluate strand requirements for next recored. _mustBeForward = _desiredStrand == SAME_STRAND_FORWARD || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::FORWARD)); _mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::REVERSE)); bool mustKeepOpposite = (_desiredStrand == SAME_STRAND_EITHER); const QuickString &currChrom = startRecord->getChrName(); _foundChroms.insert(currChrom); bool madeComposite = false; recList->push_back(startRecord); recList->setKey(startRecord); //key of recList will just be the startRecord unless we're able to merge more. Record::strandType currStrand = startRecord->getStrandVal(); bool mustMatchStrand = _desiredStrand != ANY_STRAND; int currEnd = startRecord->getEndPos(); //now look for more records to merge with this one. //stop when they're out of range, not on the same chromosome, or we hit EOF. //ignore if they don't comply with strand. Record *nextRecord = NULL; while (nextRecord == NULL) { bool takenFromStorage = false; nextRecord = mustMatchStrand ? tryToTakeFromStorage(currStrand) : tryToTakeFromStorage(); if (nextRecord == NULL) { nextRecord = FileRecordMgr::getNextRecord(); } else { takenFromStorage = true; } if (nextRecord == NULL) { // EOF hit break; } //delete any record from file with an unknown strand if we are doing stranded merge, but first check //that it's chrom was the same and it's not out of range. If either is true, stop scanning. bool mustDelete = (mustMatchStrand && nextRecord->getStrandVal() == Record::UNKNOWN); //check that we are still on the same chromosome. const QuickString &newChrom = nextRecord->getChrName(); if (newChrom != currChrom) { //hit a different chromosome. if (_foundChroms.find(newChrom) == _foundChroms.end() || takenFromStorage) { //haven't seen this chromosome before, sort order is already enforced in the base class method. if (!mustDelete) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; break; } } //check whether it's in range int nextStart = nextRecord->getStartPos(); if (nextStart > currEnd + _maxDistance) { //no, it's out of range. if (!mustDelete) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; break; } // NOW, going back, we can delete any unknown strand records. But don't stop scanning. if (mustDelete) { deleteRecord(nextRecord); nextRecord = NULL; continue; } //if taken from file, and wrong strand, store or delete. if (!takenFromStorage && ((_mustBeForward && (nextRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (nextRecord->getStrandVal() != Record::REVERSE)))) { if (mustKeepOpposite) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; continue; //get the next record } //ok, they're on the same chrom and in range, and the strand is good. Do a merge. recList->push_back(nextRecord); madeComposite = true; int nextEnd = nextRecord->getEndPos(); if (nextEnd > currEnd) { currEnd = nextEnd; } nextRecord = NULL; } if (madeComposite) { Record *newKey = _recordMgr->allocateRecord(); (*newKey) = (*startRecord); newKey->setEndPos(currEnd); recList->setKey(newKey); } _totalMergedRecordLength += (unsigned long)(recList->getKey()->getEndPos() - recList->getKey()->getStartPos()); return const_cast<Record *>(recList->getKey()); } void FileRecordMergeMgr::addToStorage(Record *record) { //if the strand requirements are strict, and the record doesn't match, //store in the "round file". if ((_desiredStrand == SAME_STRAND_FORWARD && record->getStrandVal() != Record::FORWARD) || (_desiredStrand == SAME_STRAND_REVERSE && record->getStrandVal() != Record::REVERSE) || (_desiredStrand != ANY_STRAND && record->getStrandVal() == Record::UNKNOWN)) { deleteRecord(record); return; } _storedRecords.push(record); } Record *FileRecordMergeMgr::tryToTakeFromStorage() { Record *record = _storedRecords.top(); if (record != NULL) { _storedRecords.pop(); } return record; } Record *FileRecordMergeMgr::tryToTakeFromStorage(Record::strandType strand) { Record *record = _storedRecords.top(strand); if (record != NULL) { _storedRecords.pop(strand); } return record; } void FileRecordMergeMgr::deleteMergedRecord(RecordKeyList &recList) { deleteAllMergedItemsButKey(recList); deleteRecord(recList.getKey()); recList.setKey(NULL); } bool FileRecordMergeMgr::eof(){ return (_fileReader->eof() && _storedRecords.empty()); } void FileRecordMergeMgr::deleteAllMergedItemsButKey(RecordKeyList &recList) { //if the key is also in the list, this method won't delete it. for (RecordKeyList::const_iterator_type iter = recList.begin(); iter != recList.end(); iter = recList.next()) { if (iter->value() == recList.getKey()) { continue; } deleteRecord(iter->value()); } recList.clearList(); }
/* * FileRecordMergeMgr.cpp * * Created on: Mar 19, 2014 * Author: nek3d */ #include "FileRecordMergeMgr.h" FileRecordMergeMgr::FileRecordMergeMgr(const QuickString & filename) : FileRecordMgr(filename), _desiredStrand(ANY_STRAND), _maxDistance(0) { } //Record *FileRecordMergeMgr::allocateAndGetNextMergedRecord(WANT_STRAND_TYPE desiredStrand, int maxDistance) { // RecordKeyList recList; // if (!allocateAndGetNextMergedRecord(recList, desiredStrand, maxDistance)) { // return NULL; // } // deleteAllMergedItemsButKey(recList); // return const_cast<Record *>(recList.getKey()); //want key to be non-const //} Record *FileRecordMergeMgr::getNextRecord(RecordKeyList *recList) { if (!recList->allClear()) { deleteMergedRecord(*recList); } _mustBeForward = _desiredStrand == SAME_STRAND_FORWARD; _mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE; Record *startRecord = tryToTakeFromStorage(); // if we couldn't use a previously stored record for starters, //then begin with a new one that matches strand criteria. while (startRecord == NULL) { startRecord = FileRecordMgr::getNextRecord(); if (startRecord == NULL) { //hit EOF!! return NULL; } if ((_mustBeForward && (startRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (startRecord->getStrandVal() != Record::REVERSE))) { //record is reverse, only want forward, OR record is forward, wanted reverse deleteRecord(startRecord); startRecord = NULL; continue; } if (startRecord->getStrandVal() == Record::UNKNOWN && _desiredStrand != ANY_STRAND) { //there is an unknown strand, but the user specified strandedness. deleteRecord(startRecord); startRecord = NULL; } } // OK!! We have a start record! Re-evaluate strand requirements for next recored. _mustBeForward = _desiredStrand == SAME_STRAND_FORWARD || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::FORWARD)); _mustBeReverse = _desiredStrand == SAME_STRAND_REVERSE || (_desiredStrand == SAME_STRAND_EITHER && (startRecord->getStrandVal() == Record::REVERSE)); bool mustKeepOpposite = (_desiredStrand == SAME_STRAND_EITHER); const QuickString &currChrom = startRecord->getChrName(); _foundChroms.insert(currChrom); bool madeComposite = false; recList->push_back(startRecord); recList->setKey(startRecord); //key of recList will just be the startRecord unless we're able to merge more. Record::strandType currStrand = startRecord->getStrandVal(); bool mustMatchStrand = _desiredStrand != ANY_STRAND; int currEnd = startRecord->getEndPos(); //now look for more records to merge with this one. //stop when they're out of range, not on the same chromosome, or we hit EOF. //ignore if they don't comply with strand. Record *nextRecord = NULL; while (nextRecord == NULL) { bool takenFromStorage = false; nextRecord = mustMatchStrand ? tryToTakeFromStorage(currStrand) : tryToTakeFromStorage(); if (nextRecord == NULL) { nextRecord = FileRecordMgr::getNextRecord(); } else { takenFromStorage = true; } if (nextRecord == NULL) { // EOF hit break; } //delete any record from file with an unknown strand if we are doing stranded merge, but first check //that it's chrom was the same and it's not out of range. If either is true, stop scanning. bool mustDelete = (mustMatchStrand && nextRecord->getStrandVal() == Record::UNKNOWN); //check that we are still on the same chromosome. const QuickString &newChrom = nextRecord->getChrName(); if (newChrom != currChrom) { //hit a different chromosome. //haven't seen this chromosome before, sort order is already enforced in the base class method. if (!mustDelete) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; break; } //check whether it's in range int nextStart = nextRecord->getStartPos(); if (nextStart > currEnd + _maxDistance) { //no, it's out of range. if (!mustDelete) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; break; } // NOW, going back, we can delete any unknown strand records. But don't stop scanning. if (mustDelete) { deleteRecord(nextRecord); nextRecord = NULL; continue; } //if taken from file, and wrong strand, store or delete. if (!takenFromStorage && ((_mustBeForward && (nextRecord->getStrandVal() != Record::FORWARD)) || (_mustBeReverse && (nextRecord->getStrandVal() != Record::REVERSE)))) { if (mustKeepOpposite) { addToStorage(nextRecord); } else { deleteRecord(nextRecord); } nextRecord = NULL; continue; //get the next record } //ok, they're on the same chrom and in range, and the strand is good. Do a merge. recList->push_back(nextRecord); madeComposite = true; int nextEnd = nextRecord->getEndPos(); if (nextEnd > currEnd) { currEnd = nextEnd; } nextRecord = NULL; } if (madeComposite) { Record *newKey = _recordMgr->allocateRecord(); (*newKey) = (*startRecord); newKey->setEndPos(currEnd); recList->setKey(newKey); } _totalMergedRecordLength += (unsigned long)(recList->getKey()->getEndPos() - recList->getKey()->getStartPos()); return const_cast<Record *>(recList->getKey()); } void FileRecordMergeMgr::addToStorage(Record *record) { //if the strand requirements are strict, and the record doesn't match, //store in the "round file". if ((_desiredStrand == SAME_STRAND_FORWARD && record->getStrandVal() != Record::FORWARD) || (_desiredStrand == SAME_STRAND_REVERSE && record->getStrandVal() != Record::REVERSE) || (_desiredStrand != ANY_STRAND && record->getStrandVal() == Record::UNKNOWN)) { deleteRecord(record); return; } _storedRecords.push(record); } Record *FileRecordMergeMgr::tryToTakeFromStorage() { Record *record = _storedRecords.top(); if (record != NULL) { _storedRecords.pop(); } return record; } Record *FileRecordMergeMgr::tryToTakeFromStorage(Record::strandType strand) { Record *record = _storedRecords.top(strand); if (record != NULL) { _storedRecords.pop(strand); } return record; } void FileRecordMergeMgr::deleteMergedRecord(RecordKeyList &recList) { deleteAllMergedItemsButKey(recList); deleteRecord(recList.getKey()); recList.setKey(NULL); } bool FileRecordMergeMgr::eof(){ return (_fileReader->eof() && _storedRecords.empty()); } void FileRecordMergeMgr::deleteAllMergedItemsButKey(RecordKeyList &recList) { //if the key is also in the list, this method won't delete it. for (RecordKeyList::const_iterator_type iter = recList.begin(); iter != recList.end(); iter = recList.next()) { if (iter->value() == recList.getKey()) { continue; } deleteRecord(iter->value()); } recList.clearList(); }
Test commit
Test commit
C++
mit
jmarshall/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,jmarshall/bedtools2,arq5x/bedtools2,arq5x/bedtools2
e7d2ac8cf061786f774386b8f3eab921ac9325a9
tests/core/hash_table_bench.cpp
tests/core/hash_table_bench.cpp
/******************************************************************************* * tests/core/hash_table_bench.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/core/reduce_pre_table.hpp> #include <c7a/core/reduce_pre_table_bench.hpp> #include <tests/c7a_tests.hpp> #include <c7a/api/context.hpp> #include <functional> #include <cstdio> #include "gtest/gtest.h" TEST(BenchTable, ActualTable1KKInts) { auto emit = [](int in) { in = in; //std::cout << in << std::endl; }; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(1, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST(BenchTable, ChausTable1KKInts) { auto emit = [](int in) { in = in; //std::cout << in << std::endl; }; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(1, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST(BenchTable, ActualTable10Workers) { auto emit = [](int in) { in = in; //std::cout << in << std::endl; }; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(10, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST(BenchTable, ChausTable10Workers) { auto emit = [](int in) { in = in; //std::cout << in << std::endl; }; auto key_ex = [](int in) { return in; }; auto red_fn = [](int in1, int in2) { return in1 + in2; }; c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(10, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } // TODO(ms): add one test with a for loop inserting 10000 items. -> trigger // resize! /******************************************************************************/
/******************************************************************************* * tests/core/hash_table_bench.cpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <c7a/core/reduce_pre_table.hpp> #include <c7a/core/reduce_pre_table_bench.hpp> #include <tests/c7a_tests.hpp> #include <c7a/api/context.hpp> #include <functional> #include <cstdio> #include "gtest/gtest.h" struct BenchTable : public::testing::Test { std::function<void(int)> emit = [](int /*in*/){ }; std::function<int(int)> key_ex = [](int in){ return in; }; std::function<int(int, int)> red_fn = [](int in1, int in2){ return in1 + in2; }; }; TEST_F(BenchTable, ActualTable1KKInts) { c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(1, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST_F(BenchTable, ChausTable1KKInts) { c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(1, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST_F(BenchTable, ActualTable10Workers) { c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(10, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } TEST_F(BenchTable, ChausTable10Workers) { c7a::core::ReducePreTableBench<decltype(key_ex), decltype(red_fn), decltype(emit)> table(10, key_ex, red_fn, { emit }); for (int i = 0; i < 1000000; i++) { table.Insert(i * 17); } table.Flush(); } // TODO(ms): add one test with a for loop inserting 10000 items. -> trigger // resize! /******************************************************************************/
use test fixture instead of copy pasta code :-/
use test fixture instead of copy pasta code :-/
C++
bsd-2-clause
manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill