hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2e9db5bb7662098821c5b9b89ae2b0c376e7ef56
14,618
hpp
C++
src/Discretization/Basis/Intrepid_HGRAD_QUAD_Cn_FEMDef.hpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
src/Discretization/Basis/Intrepid_HGRAD_QUAD_Cn_FEMDef.hpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
src/Discretization/Basis/Intrepid_HGRAD_QUAD_Cn_FEMDef.hpp
Sandia2014/intrepid
9a310ddc033da1dda162a09bf80cca6c2dde2d6b
[ "MIT" ]
null
null
null
#ifndef INTREPID_HGRAD_QUAD_CN_FEMDEF_HPP #define INTREPID_HGRAD_QUAD_CN_FEMDEF_HPP // @HEADER // ************************************************************************ // // Intrepid Package // Copyright (2007) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Pavel Bochev (pbboche@sandia.gov) // Denis Ridzal (dridzal@sandia.gov), or // Kara Peterson (kjpeter@sandia.gov) // // ************************************************************************ // @HEADER /** \file Intrepid_HGRAD_QUAD_Cn_FEMDef.hpp \brief Definition file for the Intrepid::HGRAD_QUAD_Cn_FEM class. \author Created by R. Kirby. */ using Teuchos::Array; using Teuchos::RCP; namespace Intrepid { template<class Scalar, class ArrayScalar> Basis_HGRAD_QUAD_Cn_FEM<Scalar,ArrayScalar>::Basis_HGRAD_QUAD_Cn_FEM( const int orderx , const int ordery, const ArrayScalar &pts_x , const ArrayScalar &pts_y ): ptsx_( pts_x.dimension(0) , 1 ) , ptsy_( pts_y.dimension(0) , 1 ) { Array<Array<RCP<Basis<Scalar,ArrayScalar> > > > bases(1); bases[0].resize(2); bases[0][0] = Teuchos::rcp( new Basis_HGRAD_LINE_Cn_FEM<Scalar,ArrayScalar>( orderx , pts_x ) ); bases[0][1] = Teuchos::rcp( new Basis_HGRAD_LINE_Cn_FEM<Scalar,ArrayScalar>( ordery , pts_y ) ); this->setBases( bases ); this->basisCardinality_ = (orderx+1)*(ordery+1); if (orderx > ordery) { this->basisDegree_ = orderx; } else { this->basisDegree_ = ordery; } this -> basisCellTopology_ = shards::CellTopology(shards::getCellTopologyData<shards::Quadrilateral<4> >() ); this -> basisType_ = BASIS_FEM_FIAT; this -> basisCoordinates_ = COORDINATES_CARTESIAN; this -> basisTagsAreSet_ = false; for (int i=0;i<pts_x.dimension(0);i++) { ptsx_(i,0) = pts_x(i,0); } for (int i=0;i<pts_y.dimension(0);i++) { ptsy_(i,0) = pts_y(i,0); } } template<class Scalar, class ArrayScalar> Basis_HGRAD_QUAD_Cn_FEM<Scalar,ArrayScalar>::Basis_HGRAD_QUAD_Cn_FEM( const int order, const EPointType &pointType ): ptsx_( order+1 , 1 ) , ptsy_( order+1 , 1 ) { Array<Array<RCP<Basis<Scalar,ArrayScalar> > > > bases(1); bases[0].resize(2); bases[0][0] = Teuchos::rcp( new Basis_HGRAD_LINE_Cn_FEM<Scalar,ArrayScalar>( order , pointType ) ); bases[0][1] = Teuchos::rcp( new Basis_HGRAD_LINE_Cn_FEM<Scalar,ArrayScalar>( order , pointType ) ); this->setBases( bases ); this->basisCardinality_ = (order+1)*(order+1); this->basisDegree_ = order; this -> basisCellTopology_ = shards::CellTopology(shards::getCellTopologyData<shards::Quadrilateral<4> >() ); this -> basisType_ = BASIS_FEM_FIAT; this -> basisCoordinates_ = COORDINATES_CARTESIAN; this -> basisTagsAreSet_ = false; // fill up the pt arrays with calls to the lattice EPointType pt = (pointType==POINTTYPE_EQUISPACED)?pointType:POINTTYPE_WARPBLEND; PointTools::getLattice<Scalar,FieldContainer<Scalar> >( ptsx_ , shards::CellTopology(shards::getCellTopologyData<shards::Line<2> >()) , order , 0 , pt ); for (int i=0;i<order+1;i++) { ptsy_(i,0) = ptsx_(i,0); } } template<class Scalar, class ArrayScalar> void Basis_HGRAD_QUAD_Cn_FEM<Scalar,ArrayScalar>::initializeTags() { // Basis-dependent initializations int tagSize = 4; // size of DoF tag, i.e., number of fields in the tag int posScDim = 0; // position in the tag, counting from 0, of the subcell dim int posScOrd = 1; // position in the tag, counting from 0, of the subcell ordinal int posDfOrd = 2; // position in the tag, counting from 0, of DoF ordinal relative to the subcell // An array with local DoF tags assigned to the basis functions, in the order of their local enumeration std::vector<int> tags( tagSize * this->getCardinality() ); // temporarily just put everything on the cell itself for (int i=0;i<this->getCardinality();i++) { tags[tagSize*i] = 2; tags[tagSize*i+1] = 0; tags[tagSize*i+2] = i; tags[tagSize*i+3] = this->getCardinality(); } Basis<Scalar,ArrayScalar> &xBasis_ = *this->getBases()[0][0]; Basis<Scalar,ArrayScalar> &yBasis_ = *this->getBases()[0][1]; // now let's try to do it "right" // let's get the x and y bases and their dof const std::vector<std::vector<int> >& xdoftags = xBasis_.getAllDofTags(); const std::vector<std::vector<int> >& ydoftags = yBasis_.getAllDofTags(); std::map<int,std::map<int,int> > total_dof_per_entity; std::map<int,std::map<int,int> > current_dof_per_entity; for (int i=0;i<4;i++) { total_dof_per_entity[0][i] = 0; current_dof_per_entity[0][i] = 0; } for (int i=0;i<4;i++) { total_dof_per_entity[1][i] = 0; current_dof_per_entity[1][i] = 0; } total_dof_per_entity[2][0] = 0; current_dof_per_entity[2][0] = 0; // let's tally the total degrees of freedom on each entity for (int j=0;j<yBasis_.getCardinality();j++) { const int ydim = ydoftags[j][0]; const int yent = ydoftags[j][1]; for (int i=0;i<xBasis_.getCardinality();i++) { const int xdim = xdoftags[i][0]; const int xent = xdoftags[i][1]; int dofdim; int dofent; ProductTopology::lineProduct2d( xdim , xent , ydim , yent , dofdim , dofent ); total_dof_per_entity[dofdim][dofent] += 1; } } int tagcur = 0; for (int j=0;j<yBasis_.getCardinality();j++) { const int ydim = ydoftags[j][0]; const int yent = ydoftags[j][1]; for (int i=0;i<xBasis_.getCardinality();i++) { const int xdim = xdoftags[i][0]; const int xent = xdoftags[i][1]; int dofdim; int dofent; ProductTopology::lineProduct2d( xdim , xent , ydim , yent , dofdim , dofent ); tags[4*tagcur] = dofdim; tags[4*tagcur+1] = dofent; tags[4*tagcur+2] = current_dof_per_entity[dofdim][dofent]; current_dof_per_entity[dofdim][dofent]++; tags[4*tagcur+3] = total_dof_per_entity[dofdim][dofent]; tagcur++; } } setOrdinalTagData(this -> tagToOrdinal_, this -> ordinalToTag_, &(tags[0]), this -> basisCardinality_, tagSize, posScDim, posScOrd, posDfOrd); } template<class Scalar, class ArrayScalar> void Basis_HGRAD_QUAD_Cn_FEM<Scalar,ArrayScalar>::getValues( ArrayScalar &outputValues , const ArrayScalar &inputPoints , const EOperator operatorType ) const { #ifdef HAVE_INTREPID_DEBUG getValues_HGRAD_Args<Scalar, ArrayScalar>(outputValues, inputPoints, operatorType, this -> getBaseCellTopology(), this -> getCardinality() ); #endif FieldContainer<Scalar> xInputPoints(inputPoints.dimension(0),1); FieldContainer<Scalar> yInputPoints(inputPoints.dimension(0),1); const Basis<Scalar,ArrayScalar> &xBasis_ = *this->bases_[0][0]; const Basis<Scalar,ArrayScalar> &yBasis_ = *this->bases_[0][1]; for (int i=0;i<inputPoints.dimension(0);i++) { xInputPoints(i,0) = inputPoints(i,0); yInputPoints(i,0) = inputPoints(i,1); } switch (operatorType) { case OPERATOR_VALUE: { FieldContainer<Scalar> xBasisValues(xBasis_.getCardinality(),xInputPoints.dimension(0)); FieldContainer<Scalar> yBasisValues(yBasis_.getCardinality(),yInputPoints.dimension(0)); xBasis_.getValues(xBasisValues,xInputPoints,OPERATOR_VALUE); yBasis_.getValues(yBasisValues,yInputPoints,OPERATOR_VALUE); int bfcur = 0; for (int j=0;j<yBasis_.getCardinality();j++) { for (int i=0;i<xBasis_.getCardinality();i++) { for (int k=0;k<inputPoints.dimension(0);k++) { outputValues(bfcur,k) = xBasisValues(i,k) * yBasisValues(j,k); } bfcur++; } } } break; case OPERATOR_GRAD: case OPERATOR_D1: { FieldContainer<Scalar> xBasisValues(xBasis_.getCardinality(),xInputPoints.dimension(0)); FieldContainer<Scalar> yBasisValues(yBasis_.getCardinality(),yInputPoints.dimension(0)); FieldContainer<Scalar> xBasisDerivs(xBasis_.getCardinality(),xInputPoints.dimension(0),1); FieldContainer<Scalar> yBasisDerivs(yBasis_.getCardinality(),yInputPoints.dimension(0),1); xBasis_.getValues(xBasisValues,xInputPoints,OPERATOR_VALUE); yBasis_.getValues(yBasisValues,yInputPoints,OPERATOR_VALUE); xBasis_.getValues(xBasisDerivs,xInputPoints,OPERATOR_D1); yBasis_.getValues(yBasisDerivs,yInputPoints,OPERATOR_D1); // there are two multiindices: I need the (1,0) and (0,1) derivatives int bfcur = 0; for (int j=0;j<yBasis_.getCardinality();j++) { for (int i=0;i<xBasis_.getCardinality();i++) { for (int k=0;k<inputPoints.dimension(0);k++) { outputValues(bfcur,k,0) = xBasisDerivs(i,k,0) * yBasisValues(j,k); outputValues(bfcur,k,1) = xBasisValues(i,k) * yBasisDerivs(j,k,0); } bfcur++; } } } break; case OPERATOR_D2: case OPERATOR_D3: case OPERATOR_D4: case OPERATOR_D5: case OPERATOR_D6: case OPERATOR_D7: case OPERATOR_D8: case OPERATOR_D9: case OPERATOR_D10: { FieldContainer<Scalar> xBasisValues(xBasis_.getCardinality(),xInputPoints.dimension(0)); FieldContainer<Scalar> yBasisValues(yBasis_.getCardinality(),yInputPoints.dimension(0)); Teuchos::Array<int> partialMult; for (int d=0;d<getDkCardinality(operatorType,2);d++) { getDkMultiplicities( partialMult , d , operatorType , 2 ); if (partialMult[0] == 0) { xBasisValues.resize(xBasis_.getCardinality(),xInputPoints.dimension(0)); xBasis_.getValues( xBasisValues , xInputPoints, OPERATOR_VALUE ); } else { xBasisValues.resize(xBasis_.getCardinality(),xInputPoints.dimension(0),1); EOperator xop = (EOperator) ( (int) OPERATOR_D1 + partialMult[0] - 1 ); xBasis_.getValues( xBasisValues , xInputPoints, xop ); xBasisValues.resize(xBasis_.getCardinality(),xInputPoints.dimension(0)); } if (partialMult[1] == 0) { yBasisValues.resize(yBasis_.getCardinality(),yInputPoints.dimension(0)); yBasis_.getValues( yBasisValues , yInputPoints, OPERATOR_VALUE ); } else { yBasisValues.resize(yBasis_.getCardinality(),yInputPoints.dimension(0),1); EOperator yop = (EOperator) ( (int) OPERATOR_D1 + partialMult[1] - 1 ); yBasis_.getValues( yBasisValues , yInputPoints, yop ); yBasisValues.resize(yBasis_.getCardinality(),yInputPoints.dimension(0)); } int bfcur = 0; for (int j=0;j<yBasis_.getCardinality();j++) { for (int i=0;i<xBasis_.getCardinality();i++) { for (int k=0;k<inputPoints.dimension(0);k++) { outputValues(bfcur,k,d) = xBasisValues(i,k) * yBasisValues(j,k); } bfcur++; } } } } break; case OPERATOR_CURL: { FieldContainer<Scalar> xBasisValues(xBasis_.getCardinality(),xInputPoints.dimension(0)); FieldContainer<Scalar> yBasisValues(yBasis_.getCardinality(),yInputPoints.dimension(0)); FieldContainer<Scalar> xBasisDerivs(xBasis_.getCardinality(),xInputPoints.dimension(0),1); FieldContainer<Scalar> yBasisDerivs(yBasis_.getCardinality(),yInputPoints.dimension(0),1); xBasis_.getValues(xBasisValues,xInputPoints,OPERATOR_VALUE); yBasis_.getValues(yBasisValues,yInputPoints,OPERATOR_VALUE); xBasis_.getValues(xBasisDerivs,xInputPoints,OPERATOR_D1); yBasis_.getValues(yBasisDerivs,yInputPoints,OPERATOR_D1); // there are two multiindices: I need the (1,0) and (0,1) derivatives int bfcur = 0; for (int j=0;j<yBasis_.getCardinality();j++) { for (int i=0;i<xBasis_.getCardinality();i++) { for (int k=0;k<inputPoints.dimension(0);k++) { outputValues(bfcur,k,0) = xBasisValues(i,k) * yBasisDerivs(j,k,0); outputValues(bfcur,k,1) = -xBasisDerivs(i,k,0) * yBasisValues(j,k); } bfcur++; } } } break; default: TEUCHOS_TEST_FOR_EXCEPTION( true , std::invalid_argument, ">>> ERROR (Basis_HGRAD_QUAD_Cn_FEM): Operator type not implemented"); break; } } template<class Scalar,class ArrayScalar> void Basis_HGRAD_QUAD_Cn_FEM<Scalar, ArrayScalar>::getValues(ArrayScalar& outputValues, const ArrayScalar & inputPoints, const ArrayScalar & cellVertices, const EOperator operatorType) const { TEUCHOS_TEST_FOR_EXCEPTION( (true), std::logic_error, ">>> ERROR (Basis_HGRAD_QUAD_Cn_FEM): FEM Basis calling an FVD member function"); } template<class Scalar,class ArrayScalar> void Basis_HGRAD_QUAD_Cn_FEM<Scalar, ArrayScalar>::getDofCoords( ArrayScalar & dofCoords ) const { int cur = 0; for (int j=0;j<ptsy_.dimension(0);j++) { for (int i=0;i<ptsx_.dimension(0);i++) { dofCoords(cur,0) = ptsx_(i,0); dofCoords(cur,1) = ptsy_(j,0); cur++; } } } }// namespace Intrepid #endif
37.007595
113
0.668012
Sandia2014
2ea00050e999b07f5da7e6dc0320ed81eca8c19e
1,112
cpp
C++
mythread.cpp
xiaoxiaozhu5/videotrans
3c33a4cfdf42ad9578183c3dfcc0670cc51a6139
[ "MIT" ]
2
2020-04-13T10:00:48.000Z
2020-05-13T09:44:56.000Z
mythread.cpp
xiaoxiaozhu5/videotrans
3c33a4cfdf42ad9578183c3dfcc0670cc51a6139
[ "MIT" ]
null
null
null
mythread.cpp
xiaoxiaozhu5/videotrans
3c33a4cfdf42ad9578183c3dfcc0670cc51a6139
[ "MIT" ]
2
2016-05-02T11:58:39.000Z
2018-09-03T16:32:28.000Z
#include "mythread.h" MyThread::MyThread() { runing_ = 1; #ifdef OK6410 vd = new VideoDevice(tr("/dev/video2")); #else vd_ = new VideoDevice(tr("/dev/video0")); #endif if(-1 == vd_->open_device()) { exit(EXIT_FAILURE); } if(-1 == vd_->init_device()) { exit(EXIT_FAILURE); } if(-1 == vd_->start_capturing()) { exit(EXIT_FAILURE); } } MyThread::~MyThread() { if(-1 == vd_->stop_capturing()) { exit(EXIT_FAILURE); } if(-1 == vd_->uninit_device()) { exit(EXIT_FAILURE); } if(-1 == vd_->close_device()) { exit(EXIT_FAILURE); } } void MyThread::run() { udp_ = new Udp(); char* frame; size_t frame_len; while(runing_) { if(-1 == vd_->get_frame((void**)&frame, &frame_len)) { exit(EXIT_FAILURE); } udp_->sendData((char *)frame, frame_len); if(-1 == vd_->unget_frame()) { exit(EXIT_FAILURE); } } } void MyThread::stop() { runing_ = 0; }
15.444444
60
0.482014
xiaoxiaozhu5
2ea10d0c6a184afa432a92c8b548c83c9b818c2a
5,504
cc
C++
src/tests/pmempools/pmempool_create/valid_arguments_tests.cc
muttleyxd/pmdk-tests
17e66a5a9d825be385ab2824c4a754f1b8a839d4
[ "BSD-3-Clause" ]
null
null
null
src/tests/pmempools/pmempool_create/valid_arguments_tests.cc
muttleyxd/pmdk-tests
17e66a5a9d825be385ab2824c4a754f1b8a839d4
[ "BSD-3-Clause" ]
null
null
null
src/tests/pmempools/pmempool_create/valid_arguments_tests.cc
muttleyxd/pmdk-tests
17e66a5a9d825be385ab2824c4a754f1b8a839d4
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include "valid_arguments.h" /** * PmempoolCreateValidTests.PMEMPOOL_CREATE * Creating pools of different type with following arguments: * - blk pool with size (long and short option) and write layout (long and short * option) * - bsize and mode options specified for blk pool * - log pool * - obj pool * \test * \li \c Step1. Create pool with specified arguments / SUCCESS * \li \c Step2. Make sure that pool exists and validate it's size and * mode */ TEST_P(ValidTests, PMEMPOOL_CREATE) { /* Step 1 */ EXPECT_EQ(0, CreatePool(pool_args, pool_path_)) << GetOutputContent(); /* Step 2 */ EXPECT_EQ(0, file_utils::ValidateFile(pool_path_, struct_utils::GetPoolSize(pool_args), struct_utils::GetPoolMode(pool_args))); } INSTANTIATE_TEST_CASE_P( PmempoolCreateParam, ValidTests, ::testing::Values(PoolArgs{PoolType::Blk, {{Option::BSize, OptionType::Short, "512"}, {Option::Size, OptionType::Long, "20M"}, {Option::Mode, OptionType::Short, "777"}}}, PoolArgs{PoolType::Blk, {{Option::BSize, OptionType::Short, "8"}, {Option::Mode, OptionType::Short, "444"}}}, PoolArgs{PoolType::Log}, PoolArgs{PoolType::Obj})); /** * PmempoolCreateValidInheritTests.PMEMPOOL_INHERIT_PROPERTIES * Inheriting settings from existing pool file: * - obj pool described by blk pool * - log pool described by obj pool * \test * \li \c Step1. Creating pool by inheriting settings from existing * pool / SUCCESS * \li \c Step2. Make sure that pool exists and validate it's size and * mode */ TEST_P(ValidInheritTests, PMEMPOOL_INHERIT_PROPERTIES) { /* Step 1 */ EXPECT_EQ(0, CreatePool(pool_inherit.pool_inherited, inherit_file_path_)) << GetOutputContent(); /* Step 2 */ EXPECT_EQ(0, file_utils::ValidateFile( inherit_file_path_, struct_utils::GetPoolSize(pool_inherit.pool_base), struct_utils::GetPoolMode(pool_inherit.pool_inherited))); } INSTANTIATE_TEST_CASE_P( PmempoolCreateParam, ValidInheritTests, ::testing::Values( PoolInherit{ {PoolType::Blk, {{Option::BSize, OptionType::Short, "512"}}}, {PoolType::Obj, {{Option::Inherit, OptionType::Long, local_config->GetTestDir() + "pool.file"}}}}, PoolInherit{{PoolType::Obj}, {PoolType::Log, {{Option::Inherit, OptionType::Long, local_config->GetTestDir() + "pool.file"}}}})); /** * PmempoolCreateValidPoolsetTests.PMEMPOOL_POOLSET * Creating pool described by poolset file * \test * \li \c Step1: Create pool described by poolset file / SUCCESS * \li \c Step2: Make sure that pool described by poolset exists and * validate it's size and mode */ TEST_P(ValidPoolsetTests, PMEMPOOL_POOLSET) { /* Step 1 */ EXPECT_EQ(0, CreatePool(poolset_args.args, poolset_args.poolset.GetFullPath())) << GetOutputContent(); /* Step 2 */ EXPECT_EQ(0, file_utils::ValidatePoolset( poolset_args.poolset, struct_utils::GetPoolMode(poolset_args.args))); } INSTANTIATE_TEST_CASE_P( PmempoolCreatePoolset, ValidPoolsetTests, ::testing::Values( PoolsetArgs{{PoolType::Blk, {{Option::BSize, OptionType::Short, "8"}}}, Poolset{{"PMEMPOOLSET", "20M"}}}, PoolsetArgs{{PoolType::Obj}, Poolset{{"PMEMPOOLSET", "20M"}}}, PoolsetArgs{{PoolType::Log}, Poolset{{"PMEMPOOLSET", "20M"}}}, PoolsetArgs{{PoolType::Obj}, Poolset{{"PMEMPOOLSET", "20M"}, {"REPLICA", "20M"}}}));
42.015267
80
0.646076
muttleyxd
2ea3aa3f4fffe038e284106b6d3cb5bec3731cfe
86
hpp
C++
components/downtime/ui/titles.hpp
Bubbus/F3_CA_BUB
cd7a725d65afa56a3a7f24288c839333f03b5454
[ "Unlicense" ]
1
2020-10-30T16:10:23.000Z
2020-10-30T16:10:23.000Z
components/downtime/ui/titles.hpp
Bubbus/F3_CA_BUB
cd7a725d65afa56a3a7f24288c839333f03b5454
[ "Unlicense" ]
41
2020-11-20T18:24:19.000Z
2021-12-14T15:51:50.000Z
components/downtime/ui/titles.hpp
Bubbus/F3_CA_BUB
cd7a725d65afa56a3a7f24288c839333f03b5454
[ "Unlicense" ]
2
2020-11-08T16:59:28.000Z
2021-11-30T11:41:10.000Z
#include "unconsciousTitle.hpp" #include "deadTitle.hpp" #include "respawnTitle.hpp"
17.2
31
0.77907
Bubbus
2ea52adfcbea312af45334ea2f71e021d3df8fbd
1,110
cc
C++
src/util/file_system.cc
FlyAlCode/PLBGHashing
289d0a66c9091602abedf2860c2b3ae9d763fed0
[ "MIT" ]
1
2021-02-13T01:45:20.000Z
2021-02-13T01:45:20.000Z
src/util/file_system.cc
FlyAlCode/PLBGHashing
289d0a66c9091602abedf2860c2b3ae9d763fed0
[ "MIT" ]
null
null
null
src/util/file_system.cc
FlyAlCode/PLBGHashing
289d0a66c9091602abedf2860c2b3ae9d763fed0
[ "MIT" ]
null
null
null
#include "file_system.h" #include <iostream> #include <fstream> #include <string.h> //包含strcmp的头文件,也可用: #include <ctring> #include <dirent.h> #include <algorithm> void getFileNames(const std::string path, std::vector<std::string>& filenames, const std::string &suffix){ DIR *pDir; struct dirent* ptr; if (!(pDir = opendir(path.c_str()))) return; while ((ptr = readdir(pDir))!=0) { if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0){ std::string file = path + "/" + ptr->d_name; if (opendir(file.c_str())) { getFileNames(file, filenames, suffix); } else { if (suffix == file.substr(file.size() - suffix.size())){ filenames.push_back(file); } } } } closedir(pDir); std::sort(filenames.begin(), filenames.end()); }
35.806452
110
0.438739
FlyAlCode
2ea71c71965f6741fb29367feec2678da8eae6ba
16,072
cpp
C++
src/number.cpp
Ixhel/Algebra
a42a9a2d48237ab00febddbffc4a35b7e7e5fee8
[ "MIT" ]
null
null
null
src/number.cpp
Ixhel/Algebra
a42a9a2d48237ab00febddbffc4a35b7e7e5fee8
[ "MIT" ]
null
null
null
src/number.cpp
Ixhel/Algebra
a42a9a2d48237ab00febddbffc4a35b7e7e5fee8
[ "MIT" ]
null
null
null
/* SymbolicC++ : An object oriented computer algebra system written in C++ Copyright (C) 2008 Yorick Hardy and Willi-Hans Steeb This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "symbolic/symbolicc++.h" #ifdef SYMBOLIC_DEFINE #ifndef SYMBOLIC_CPLUSPLUS_NUMBER_DEFINE #define SYMBOLIC_CPLUSPLUS_NUMBER_DEFINE #define SYMBOLIC_CPLUSPLUS_NUMBER Numeric::Numeric() : CloningSymbolicInterface() {} Numeric::Numeric(const Numeric &n) : CloningSymbolicInterface(n) {} // Template specialization for Rational<Number<void> > template <> Rational<Number<void> >::operator double() const { pair<Number<void>,Number<void> > pr = p.match(p,q); if(pr.first.numerictype() == typeid(int)) { CastPtr<const Number<int> > i1 = pr.first; CastPtr<const Number<int> > i2 = pr.second; return double(Rational<int>(i1->n,i2->n)); } if(pr.first.numerictype() == typeid(Verylong)) { CastPtr<const Number<Verylong> > v1 = pr.first; CastPtr<const Number<Verylong> > v2 = pr.second; return double(Rational<Verylong>(v1->n,v2->n)); } cerr << "convert to double : " << pr.first.numerictype().name() << endl; throw SymbolicError(SymbolicError::NotDouble); return 0.0; } //////////////////////////////////// // Implementation of Numeric // //////////////////////////////////// pair<Number<void>,Number<void> > Numeric::match(const Numeric &n1,const Numeric &n2) { const type_info &t1 = n1.numerictype(); const type_info &t2 = n2.numerictype(); const type_info &type_int = typeid(int); const type_info &type_double = typeid(double); const type_info &type_verylong = typeid(Verylong); const type_info &type_rational = typeid(Rational<Number<void> >); if(t1 == type_int) { CastPtr<const Number<int> > i1 = n1; if(t2 == type_int) return pair<Number<void>,Number<void> >(n1,n2); if(t2 == type_double) return pair<Number<void>,Number<void> >(Number<double>(i1->n),n2); if(t2 == type_verylong) return pair<Number<void>,Number<void> >(Number<Verylong>(i1->n),n2); if(t2 == type_rational) return pair<Number<void>,Number<void> > (Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*i1))) ,n2); cerr << "Numeric cannot use " << t2.name() << endl; throw SymbolicError(SymbolicError::UnsupportedNumeric); } if(t1 == type_double) { CastPtr<const Number<double> > d1 = n1; if(t2 == type_int) { CastPtr<const Number<int> > i2 = n2; return pair<Number<void>,Number<void> >(n1,Number<double>(i2->n)); } if(t2 == type_double) return pair<Number<void>,Number<void> >(n1,n2); if(t2 == type_verylong) { CastPtr<const Number<Verylong> > v2 = n2; return pair<Number<void>,Number<void> >(n1,Number<double>(v2->n)); } if(t2 == type_rational) { CastPtr<const Number<Rational<Number<void> > > > r2 = n2; return pair<Number<void>,Number<void> > (n1,Number<double>(double(r2->n))); } cerr << "Numeric cannot use " << t2.name() << endl; throw SymbolicError(SymbolicError::UnsupportedNumeric); } if(t1 == type_verylong) { CastPtr<const Number<Verylong> > v1 = n1; if(t2 == type_int) { CastPtr<const Number<int> > i2 = n2; return pair<Number<void>,Number<void> >(n1,Number<Verylong>(i2->n)); } if(t2 == type_double) return pair<Number<void>,Number<void> >(Number<double>(v1->n),n2); if(t2 == type_verylong) return pair<Number<void>,Number<void> >(n1,n2); if(t2 == type_rational) return pair<Number<void>,Number<void> > (Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*v1))),n2); cerr << "Numeric cannot use " << t2.name() << endl; throw SymbolicError(SymbolicError::UnsupportedNumeric); } if(t1 == type_rational) { CastPtr<const Number<Rational<Number<void> > > > r1 = n1; if(t2 == type_int) { CastPtr<const Number<int> > i2 = n2; return pair<Number<void>,Number<void> > (n1, Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*i2)))); } if(t2 == type_double) return pair<Number<void>,Number<void> > (Number<double>(double(r1->n)),n2); if(t2 == type_verylong) { CastPtr<const Number<Verylong> > v2 = n2; return pair<Number<void>,Number<void> > (n1, Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*v2)))); } if(t2 == type_rational) return pair<Number<void>,Number<void> >(n1,n2); cerr << "Numeric cannot use " << t2.name() << endl; throw SymbolicError(SymbolicError::UnsupportedNumeric); } cerr << "Numeric cannot use " << t1.name() << endl; throw SymbolicError(SymbolicError::UnsupportedNumeric); return pair<Number<void>,Number<void> >(n1,n2); } Symbolic Numeric::subst(const Symbolic &x,const Symbolic &y,int &n) const { if(*this == x) { ++n; return y; } return *this; } int Numeric::compare(const Symbolic &s) const { if(s.type() != type()) return 0; pair<Number<void>,Number<void> > p = Number<void>::match(*this,*Number<void>(s)); return p.first->cmp(*(p.second)); } Symbolic Numeric::df(const Symbolic &s) const { return Number<int>(0); } Symbolic Numeric::integrate(const Symbolic &s) const { return Symbolic(*this) * s; } Symbolic Numeric::coeff(const Symbolic &s) const { if(s.type() == typeid(Numeric)) return *this / Number<void>(s); return Number<int>(0); } Expanded Numeric::expand() const { return *this; } int Numeric::commute(const Symbolic &s) const { return 1; } PatternMatches Numeric::match(const Symbolic &s, const list<Symbolic> &p) const { PatternMatches l; if(*this == s) pattern_match_TRUE(l); else pattern_match_FALSE(l); return l; } PatternMatches Numeric::match_parts(const Symbolic &s, const list<Symbolic> &p) const { return s.match(*this, p); } //////////////////////////////////// // Implementation of Number // //////////////////////////////////// template <class T> Number<T>::Number() : n() { simplified = expanded = 1; } template <class T> Number<T>::Number(const Number &n) : Numeric(n), n(n.n) {} template <class T> Number<T>::Number(const T &t) : n(t) { simplified = 0; expanded = 1; } template <class T> Number<T>::~Number() {} template <class T> Number<T> &Number<T>::operator=(const Number &n) { if(this != &n) n = n.n; return *this; } template <class T> Number<T> &Number<T>::operator=(const T &t) { n = t; return *this; } template <class T> void Number<T>::print(ostream &o) const { o << n; } template <class T> const type_info &Number<T>::type() const { return typeid(Numeric); } template <class T> const type_info &Number<T>::numerictype() const { return typeid(T); } template <class T> Simplified Number<T>::simplify() const { return *this; } template <> Simplified Number<Verylong>::simplify() const { if(n <= Verylong(numeric_limits<int>::max()) && n > Verylong(numeric_limits<int>::min())) return Number<int>(n); return *this; } template <> Simplified Number<Rational<Number<void> > >::simplify() const { if(n.den().isOne()) return *(n.num()); return *this; } template <class T> Number<void> Number<T>::add(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<T> > p = x; return Number<T>(n + p->n); } template <class T> Number<void> Number<T>::mul(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<T> > p = x; return Number<T>(n * p->n); } template <class T> Number<void> Number<T>::div(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<T> > p = x; return Number<T>(n / p->n); } template <class T> Number<void> Number<T>::mod(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<T> > p = x; return Number<T>(n - p->n * (n / p->n)); } template <> Number<void> Number<int>::add(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<int> > p = x; int sum = n + p->n; if((n < 0 && p->n < 0 && sum >= 0) || (n > 0 && p->n > 0 && sum <= 0)) return Number<Verylong>(Verylong(n) + Verylong(p->n)); return Number<int>(n + p->n); } template <> Number<void> Number<int>::mul(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<int> > p = x; int product = n * p->n; if(n != 0 && product / n != p->n) return Number<Verylong>(Verylong(n) * Verylong(p->n)); return Number<int>(product); } template <> Number<void> Number<int>::div(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<int> > p = x; if(n % p->n != 0) return Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*this),Number<void>(x))); return Number<int>(n / p->n); } template <> Number<void> Number<int>::mod(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); return Number<int>(n % CastPtr<const Number<int> >(x)->n); } template <> Number<void> Number<double>::mod(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); return Number<double>(fmod(n,CastPtr<const Number<double> >(x)->n)); } template <> Number<void> Number<Verylong>::div(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); CastPtr<const Number<Verylong> > p = x; if(n % p->n != Verylong(0)) return Number<Rational<Number<void> > > (Rational<Number<void> >(Number<void>(*this),Number<void>(x))); return Number<Verylong>(n / p->n); } template <class T> int Number<T>::isZero() const { return (n == zero(T())); } template <class T> int Number<T>::isOne() const { return (n == one(T())); } template <class T> int Number<T>::isNegative() const { return (n < zero(T())); } template <class T> int Number<T>::cmp(const Numeric &x) const { if(numerictype() != x.numerictype()) throw SymbolicError(SymbolicError::IncompatibleNumeric); return (numerictype() == x.numerictype()) && (n == CastPtr<const Number<T> >(x)->n); } //////////////////////////////////// // Implementation of Number<void> // //////////////////////////////////// Number<void>::Number() : CastPtr<Numeric>(Number<int>(0)) {} Number<void>::Number(const Number &n) : CastPtr<Numeric>(n) {} Number<void>::Number(const Numeric &n) : CastPtr<Numeric>(n) {} Number<void>::Number(const Symbolic &n) : CastPtr<Numeric>(Number<int>(0)) { if(n.type() != typeid(Numeric)) throw SymbolicError(SymbolicError::NotNumeric); CastPtr<Numeric>::operator=(n); } Number<void>::~Number() {} const type_info &Number<void>::numerictype() const { return (*this)->numerictype(); } int Number<void>::isZero() const { return (*this)->isZero(); } int Number<void>::isOne() const { return (*this)->isOne(); } int Number<void>::isNegative() const { return (*this)->isNegative(); } pair<Number<void>,Number<void> > Number<void>::match(const Numeric &n1,const Numeric &n2) { return Numeric::match(n1,n2); } pair<Number<void>,Number<void> > Number<void>::match(const Number<void> &n1,const Number<void> &n2) { return Numeric::match(*n1,*n2); } Number<void> Number<void>::operator+(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*this,n); return p.first->add(*(p.second)); } Number<void> Number<void>::operator-(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*this,n); return p.first->add(*(p.second)); } Number<void> Number<void>::operator*(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*this,n); return p.first->mul(*(p.second)); } Number<void> Number<void>::operator/(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*this,n); return p.first->div(*(p.second)); } Number<void> Number<void>::operator%(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*this,n); return p.first->mod(*(p.second)); } Number<void> &Number<void>::operator+=(const Numeric &n) { return *this = *this + n; } Number<void> &Number<void>::operator*=(const Numeric &n) { return *this = *this * n; } Number<void> &Number<void>::operator/=(const Numeric &n) { return *this = *this / n; } Number<void> &Number<void>::operator%=(const Numeric &n) { return *this = *this % n; } int Number<void>::operator==(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*(*this),n); return p.first->compare(*(p.second)); } int Number<void>::operator<(const Numeric &n) const { pair<Number<void>,Number<void> > p = Number<void>::match(*(*this),n); return (p.first - p.second).isNegative(); } int Number<void>::operator>(const Numeric &n) const { return !(*this < n) && !(*this == n); } int Number<void>::operator<=(const Numeric &n) const { return (*this < n) || (*this == n); } int Number<void>::operator>=(const Numeric &n) const { return !(*this < n); } Number<void> Number<void>::operator+(const Number<void> &n) const { return operator+(*n); } Number<void> Number<void>::operator-(const Number<void> &n) const { return operator-(*n); } Number<void> Number<void>::operator*(const Number<void> &n) const { return operator*(*n); } Number<void> Number<void>::operator/(const Number<void> &n) const { return operator/(*n); } Number<void> Number<void>::operator%(const Number<void> &n) const { return operator%(*n); } Number<void> &Number<void>::operator+=(const Number<void> &n) { return *this = *this + n; } Number<void> &Number<void>::operator*=(const Number<void> &n) { return *this = *this * n; } Number<void> &Number<void>::operator/=(const Number<void> &n) { return *this = *this / n; } Number<void> &Number<void>::operator%=(const Number<void> &n) { return *this = *this % n; } int Number<void>::operator==(const Number<void> &n) const { return operator==(*n); } int Number<void>::operator<(const Number<void> &n) const { return operator<(*n); } int Number<void>::operator>(const Number<void> &n) const { return operator>(*n); } int Number<void>::operator<=(const Number<void> &n) const { return operator<=(*n); } int Number<void>::operator>=(const Number<void> &n) const { return operator>=(*n); } Numeric &Number<void>::operator*() const { return CastPtr<Numeric>::operator*(); } template <> Number<void> zero(Number<void>) { return Number<int>(0); } template <> Number<void> one(Number<void>) { return Number<int>(1); } Number<void> operator+(const Numeric &n1,const Number<void> &n2) { return Number<void>(n1) + n2; } Number<void> operator-(const Numeric &n1,const Number<void> &n2) { return Number<void>(n1) - n2; } Number<void> operator*(const Numeric &n1,const Number<void> &n2) { return Number<void>(n1) * n2; } Number<void> operator/(const Numeric &n1,const Number<void> &n2) { return Number<void>(n1) / n2; } Number<void> operator%(const Numeric &n1,const Number<void> &n2) { return Number<void>(n1) % n2; } #endif #endif
29.653137
75
0.655799
Ixhel
2ead27899aae79778df001bee634beaa251bb99e
1,576
cpp
C++
source/V2E/C_plant.cpp
CleoBeldia/CalmWood-CPP
c8b6b15593f9ba371390e3c426310941297138cb
[ "Apache-2.0" ]
2
2020-10-11T20:10:30.000Z
2021-01-18T21:29:25.000Z
source/V2E/C_plant.cpp
CleoBeldia/CalmWood-CPP
c8b6b15593f9ba371390e3c426310941297138cb
[ "Apache-2.0" ]
null
null
null
source/V2E/C_plant.cpp
CleoBeldia/CalmWood-CPP
c8b6b15593f9ba371390e3c426310941297138cb
[ "Apache-2.0" ]
1
2020-10-21T09:20:36.000Z
2020-10-21T09:20:36.000Z
/* * Copyright 2020 Axel Polin, univ_apolin@protonmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <unistd.h> #include <iostream> #include <string> #include <vector> #include <unordered_map> #include "C_plant.hpp" #include "C_environment.hpp" Plant::Plant ( int newId, std::string newName ) { id = newId; name = newName; }; Plant::~Plant () {}; int Plant::getID() { return id; } std::string Plant::getName() { return name; } int Plant::growth ( int targetState ) { return 0; } int Plant::damage() { return 0; } int Plant::setLocation ( std::vector<int> newLocation ) { if ( newLocation.size() != 3 ) return -1; location = newLocation; return 0; } std::vector<int> Plant::getLocation() { return location; } int Plant::dead ( Environment* environment ) { environment->getCell ( location[0], location[1] )->removePlant ( id, this ); death = true; return 0; } bool Plant::isDead() { return death; }
18.987952
84
0.641497
CleoBeldia
2eae6b9ecc810d1c07ea799dda9695baca334e78
100
cpp
C++
src/util/stb_image.cpp
chrku/ray_tracer
412250769072d318b9006ff22abdc0a5bb83ef14
[ "MIT" ]
1
2019-07-22T17:19:15.000Z
2019-07-22T17:19:15.000Z
src/util/stb_image.cpp
chrku/ray_tracer
412250769072d318b9006ff22abdc0a5bb83ef14
[ "MIT" ]
null
null
null
src/util/stb_image.cpp
chrku/ray_tracer
412250769072d318b9006ff22abdc0a5bb83ef14
[ "MIT" ]
null
null
null
// // Created by christoph on 08.08.19. // #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
14.285714
36
0.73
chrku
2eae9c5fffd6c6f40f4fe2413bc3cbe2b19060e1
5,577
cpp
C++
Tests/dspBufferTest.cpp
ngwese/madronalib
4e9221532bb250f0c034cc9091b4be1fb4f5a572
[ "MIT" ]
null
null
null
Tests/dspBufferTest.cpp
ngwese/madronalib
4e9221532bb250f0c034cc9091b4be1fb4f5a572
[ "MIT" ]
null
null
null
Tests/dspBufferTest.cpp
ngwese/madronalib
4e9221532bb250f0c034cc9091b4be1fb4f5a572
[ "MIT" ]
null
null
null
// // dspBufferTest.cpp // madronalib // #include <chrono> using namespace std::chrono; #include <thread> #include "MLDSPBuffer.h" #include "catch.hpp" #include "mldsp.h" using namespace ml; namespace dspBufferTest { TEST_CASE("madronalib/core/dspbuffer", "[dspbuffer]") { std::cout << "\nDSPBUFFER\n"; // buffer should be next larger power-of-two size DSPBuffer buf; buf.resize(197); REQUIRE(buf.getWriteAvailable() == 256); // write to near end std::vector<float> nines; nines.resize(256); std::fill(nines.begin(), nines.end(), 9.f); buf.write(nines.data(), 250); buf.read(nines.data(), 250); // write indices with wrap DSPVector v1(columnIndex()); buf.write(v1.getConstBuffer(), kFloatsPerDSPVector); DSPVector v2{}; buf.read(v2.getBuffer(), kFloatsPerDSPVector); std::cout << v2 << "\n"; REQUIRE(buf.getReadAvailable() == 0); REQUIRE(v2 == v1); } const int kTestBufferSize = 256; const int kTestWrites = 200; float transmitSum = 0; float receiveSum = 0; // buffer shared between threads DSPBuffer testBuf; size_t samplesTransmitted = 0; size_t maxSamplesInBuffer = 0; size_t samplesReceived = 0; float kEndFlag = 99; RandomScalarSource rr; const int kMaxReadWriteSize = 16; auto randToLength = projections::linear({-1, 1}, {1, kMaxReadWriteSize}); void transmitTest() { testBuf.resize(kTestBufferSize); float data[kMaxReadWriteSize]; for (int i = 0; i < kTestWrites; ++i) { size_t writeLen = randToLength(rr.getFloat()); for (int j = 0; j < writeLen; ++j) { float f = rr.getFloat(); data[j] = f; transmitSum += f; } testBuf.write(data, writeLen); std::cout << "+"; // show write samplesTransmitted += writeLen; std::this_thread::sleep_for(milliseconds(2)); } data[0] = kEndFlag; testBuf.write(data, 1); } void receiveTest() { bool done = false; float data[kMaxReadWriteSize]; while (!done) { if (size_t k = testBuf.getReadAvailable()) { if (k > maxSamplesInBuffer) { maxSamplesInBuffer = k; } size_t readLen = randToLength(rr.getFloat()); readLen = std::min(readLen, k); testBuf.read(data, std::min(readLen, k)); std::cout << "-"; // show read for (int i = 0; i < readLen; ++i) { float f = data[i]; if (f == kEndFlag) { done = true; break; } else { samplesReceived++; receiveSum += f; } } } else { std::cout << "."; // show wait } std::this_thread::sleep_for(milliseconds(1)); } } TEST_CASE("madronalib/core/dspbuffer/threads", "[dspbuffer][threads]") { // start threads std::thread transmit(transmitTest); std::thread receive(receiveTest); // wait for threads to finish transmit.join(); receive.join(); std::cout << "\ntransmit sum: " << transmitSum << "\nreceive sum: " << receiveSum << "\n"; std::cout << "total samples transmitted: " << samplesTransmitted << "\n"; std::cout << "total samples received: " << samplesReceived << "\n"; std::cout << "buffer size: " << kTestBufferSize << "\n"; std::cout << "max samples in buffer: " << maxSamplesInBuffer << "\n"; REQUIRE(testBuf.getReadAvailable() == 0); REQUIRE(transmitSum == receiveSum); REQUIRE(samplesTransmitted == samplesReceived); } TEST_CASE("madronalib/core/dspbuffer/overlap", "[dspbuffer][overlap]") { DSPBuffer buf; buf.resize(256); DSPVector outputVec, outputVec2; int overlap = kFloatsPerDSPVector / 2; // write constant window buffer DSPVector windowVec; makeWindow(windowVec.getBuffer(), kFloatsPerDSPVector, windows::triangle); // TODO ConstDSPVector windowVec(windows::triangle); // - would require constexpr-capable reimplementation of Projections, not // using std::function // write overlapping triangle windows for (int i = 0; i < 8; ++i) { buf.writeWithOverlapAdd(windowVec.getBuffer(), kFloatsPerDSPVector, overlap); } // read past startup buf.read(outputVec); // after startup, sums of windows should be constant buf.read(outputVec); buf.read(outputVec2); REQUIRE(outputVec == outputVec2); } TEST_CASE("madronalib/core/dspbuffer/vectors", "[dspbuffer][vectors]") { DSPBuffer buf; buf.resize(256); constexpr size_t kRows = 3; DSPVectorArray<kRows> inputVec, outputVec; // make a DSPVectorArray with a unique int at each sample inputVec = map([](DSPVector v, int row) { return v + DSPVector(kFloatsPerDSPVector * row); }, repeatRows<kRows>(columnIndex())); // write long enough that we will wrap for (int i = 0; i < 4; ++i) { buf.write(inputVec); buf.read(outputVec); } REQUIRE(inputVec == outputVec); } TEST_CASE("madronalib/core/dspbuffer/peek", "[dspbuffer][peek]") { // buffer should be next larger power-of-two size DSPBuffer buf; buf.resize(256); // write to near end std::vector<float> nines; nines.resize(256); std::fill(nines.begin(), nines.end(), 9.f); buf.write(nines.data(), 203); buf.read(nines.data(), 203); // write DSPVectors with wrap DSPVector v1(columnIndex()); buf.write(v1); v1 += DSPVector(kFloatsPerDSPVector); buf.write(v1); // write one more sample float f{128}; buf.write(&f, 1); // peek data regions to buffer std::vector<float> floatVec; floatVec.resize(200); buf.peekMostRecent(floatVec.data(), 20); REQUIRE(floatVec[0] == 109); REQUIRE(floatVec[19] == 128); } } // namespace dspBufferTest
22.950617
76
0.638874
ngwese
2eb3b8476376b2d07a6a7ca748919e1805b7ac81
3,015
cpp
C++
TypeMap.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
2
2015-07-01T17:47:02.000Z
2015-07-01T17:53:11.000Z
TypeMap.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
null
null
null
TypeMap.cpp
DForshner/CPPExperiments
989d972ac6408601ce7863ec25f1bdcfeeeaff72
[ "Apache-2.0" ]
null
null
null
// A type map that allows mapping of type K to a values of type V. // // Compiled using Visual Studio 2015 #include <iostream> #include <atomic> #include <unordered_map> #include <string> #include <memory> #include <cassert> namespace TypeMap { template<class V> class TypeMap { public: // These type definitions are necessary to be compliant with the STL because it uses iterator traits. // See the Nested container section of: http://www.cs.northwestern.edu/~riesbeck/programming/c++/stl-iterator-define.html typedef std::unordered_map<int, V> Map; typedef typename Map::iterator iterator; typedef typename Map::const_iterator const_iterator; typedef typename Map::value_type value_type; const_iterator cbegin() const { return _map.cbegin(); } const_iterator cend() const { return _map.cend(); } iterator begin() { return _map.begin(); } iterator end() { return _map.end(); } // Find value associated with type K template<class K> iterator find() { return _map.find(getTypeId<K>()); } // Find value associated with type K template<class K> const_iterator find() const { return _map.find(getTypeId<K>()); } // Associate value with type template<class K> void put(V &&val) { _map[getTypeId<K>()] = std::forward<V>(val); } private: static std::atomic_int _idCounter; Map _map; // Returns a unique integer per type V template <typename V> int getTypeId() { static int id = ++_idCounter; return id; } }; // Stores an single instantiation of a derived class against its Type. template<typename BaseType> class DerivedTypeMap { public: template<typename DerivedType> DerivedType* get() { auto it = _map.find<DerivedType>(); assert(it != _map.end()); return static_cast<DerivedType*>(it->second.get()); } template<typename DerivedType> void put(std::unique_ptr<DerivedType> &&val) { _map.put<DerivedType>(std::forward<std::unique_ptr<DerivedType>>(val)); } private: TypeMap<std::unique_ptr<BaseType>> _map; }; template<class V> std::atomic_int TypeMap<V>::_idCounter(0); } class A { virtual void display() = 0; }; class B : public A { public: void display() override { std::cout << "B" << std::endl; } }; class C : public A { public: void display() override { std::cout << "C" << std::endl; } }; class D : public A { public: void display() override { std::cout << "D" << std::endl; } }; int main() { TypeMap::TypeMap<std::string> map; map.put<int>("Integers"); map.put<double>("Doubles"); std::cout << map.find<int>()->second << std::endl; std::cout << map.find<double>()->second << std::endl; TypeMap::DerivedTypeMap<A> derivedMap; derivedMap.put<B>(std::make_unique<B>()); derivedMap.put<C>(std::make_unique<C>()); derivedMap.put<D>(std::make_unique<D>()); derivedMap.get<D>()->display(); derivedMap.get<C>()->display(); derivedMap.get<B>()->display(); return 0; }
27.916667
125
0.653731
DForshner
2eb7f267c876c3813c6cb42be19f3691815fe0e6
37,685
cpp
C++
mysqlparser/base/unit-tests/string_utilities_test.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
4
2020-12-13T15:02:40.000Z
2021-07-16T06:23:38.000Z
mysqlparser/base/unit-tests/string_utilities_test.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
null
null
null
mysqlparser/base/unit-tests/string_utilities_test.cpp
aasthakm/qapla
f98ca92adbca75fee28587e540b8c851809c7a62
[ "BSD-4-Clause" ]
null
null
null
/* * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "base/string_utilities.h" #include "grtpp.h" #include "wb_helpers.h" #include <algorithm> using namespace base; // updated as of 5.7 static const char *reserved_keywords[] = { "ACCESSIBLE", "ADD", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE", "COLUMN", "CONDITION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DELAYED", "DELETE", "DESC", "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "ENCLOSED", "ESCAPED", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FLOAT", "FLOAT4", "FLOAT8", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GET", "GRANT", "GROUP", "HAVING", "HIGH_PRIORITY", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "IO_AFTER_GTIDS", "IO_BEFORE_GTIDS", "IS", "ITERATE", "JOIN", "KEY", "KEYS", "KILL", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MASTER_BIND", "MASTER_SSL_VERIFY_SERVER_CERT", "MATCH", "MAXVALUE", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NONBLOCKING", "NOT", "NO_WRITE_TO_BINLOG", "NULL", "NUMERIC", "ON", "OPTIMIZE", "OPTION", "OPTIONALLY", "OR", "ORDER", "OUT", "OUTER", "OUTFILE", "PARTITION", "PRECISION", "PRIMARY", "PROCEDURE", "PURGE", "RANGE", "READ", "READS", "READ_WRITE", "REAL", "REFERENCES", "REGEXP", "RELEASE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESIGNAL", "RESTRICT", "RETURN", "REVOKE", "RIGHT", "RLIKE", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET", "SHOW", "SIGNAL", "SMALLINT", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SSL", "STARTING", "STRAIGHT_JOIN", "TABLE", "TERMINATED", "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "WHEN", "WHERE", "WHILE", "WITH", "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL", NULL }; BEGIN_TEST_DATA_CLASS(string_utilities_test) protected: std::string long_random_string; // Content doesn't matter. There must be no crash using it. TEST_DATA_CONSTRUCTOR(string_utilities_test) { for (int i = 0; i < 1000; i++) { long_random_string += ' ' + rand() % 94; // Visible characters after space if (rand() > RAND_MAX / 2) long_random_string += "\xE3\x8A\xA8"; // Valid Unicode character. if (i == 500) long_random_string += "\xE3\x8A\xA8"; // Ensure it is there at least once. } long_random_string.erase(std::remove(long_random_string.begin(), long_random_string.end(), 0x7f), long_random_string.end()); // 0x7F is a special character that we use for tests } END_TEST_DATA_CLASS; TEST_MODULE(string_utilities_test, "string utilities"); /* Testing base::quote_identifier */ TEST_FUNCTION(5) { std::string test = "first_test"; std::string test_result = base::quote_identifier(test, '`'); ensure_equals("Unexpected result quoting string", test_result, "`first_test`"); test = "second_test"; test_result = base::quote_identifier(test, '\"'); ensure_equals("Unexpected result quoting string", test_result, "\"second_test\""); test = ""; test_result = base::quote_identifier(test, '\"'); ensure_equals("Unexpected result quoting string", test_result, "\"\""); test = "Unicode \xE3\x8A\xA8"; // UTF-8 encoded: CIRCLED IDEOGRAPH RIGHT test_result = base::quote_identifier(test, '%'); ensure_equals("Unexpected result quoting string", test_result, "%Unicode \xE3\x8A\xA8%"); } /* Testing base::quote_identifier_if_needed */ TEST_FUNCTION(10) { std::string test = "first_test"; std::string test_result = base::quote_identifier_if_needed(test, '`'); ensure_equals("Unexpected result quoting string", test_result, "first_test"); test = "second_test"; test_result = base::quote_identifier_if_needed(test, '\"'); ensure_equals("Unexpected result quoting string", test_result, "second_test"); test = "Unicode\xE3\x8A\xA8"; // UTF-8 encoded: CIRCLED IDEOGRAPH RIGHT test_result = base::quote_identifier_if_needed(test, '%'); ensure_equals("Unexpected result quoting string", test_result, "Unicode\xE3\x8A\xA8"); test = "test.case"; test_result = base::quote_identifier_if_needed(test, '$'); ensure_equals("Unexpected result quoting string", test_result, "$test.case$"); // Note: currently there is no support to check if the given string contains the quote char already. test = "test$case"; test_result = base::quote_identifier_if_needed(test, '$'); ensure_equals("Unexpected result quoting string", test_result, "test$case"); test = ".test$case"; test_result = base::quote_identifier_if_needed(test, '$'); ensure_equals("Unexpected result quoting string", test_result, "$.test$case$"); test = "test-case"; test_result = base::quote_identifier_if_needed(test, '`'); ensure_equals("Unexpected result quoting string", test_result, "`test-case`"); // Identifiers consisting only of digits cannot be distinguished from normal numbers // so they must be quoted. test = "12345"; test_result = base::quote_identifier_if_needed(test, '`'); ensure_equals("Unexpected result quoting string", test_result, "`12345`"); } /** * Testing base::unquote_identifier */ TEST_FUNCTION(15) { std::string test = "\"first_test\""; std::string test_result = base::unquote_identifier(test); ensure_equals("Unexpected result unquoting string", test_result, "first_test"); test = "`second_test`"; test_result = base::unquote_identifier(test); ensure_equals("Unexpected result unquoting string", test_result, "second_test"); } static bool compare_string_lists(const std::vector<std::string> &slist, const char *check[]) { size_t i; for (i = 0; i < slist.size(); i++) { if (check[i] == NULL) { g_message("result has more items than expected\n"); return false; } if (slist[i] != check[i]) { g_message("token comparison mismatch"); for (size_t j= 0; j < slist.size(); j++) g_message("%s", slist[j].c_str()); return false; } } if (check[i]) { g_message("result has fewer items than expeced\n"); return false; } return true; } TEST_FUNCTION(20) { const char* empty[] = {"", NULL}; const char* empty2[] = {"", "", NULL}; const char* empty3[] = {"", "", "", NULL}; const char* null_empty[] = {"NULL", "", NULL}; const char* a[] = {"a", NULL}; const char* a_empty1[] = {"a", "", NULL}; const char *a_empty2[] = {"a", "", "", NULL}; const char *ab_empty1[] = {"a", "b", "", NULL}; const char *ab_empty2[] = {"a", "", "b", NULL}; const char *ab_empty3[] = {"", "a", "b", NULL}; const char* null_null[] = {"NULL", "NULL", NULL}; const char* emptys_null[] = {"''", "NULL", NULL}; const char* ab_null[] = {"'a,b'", "NULL", NULL}; const char* ab_xxx[] = {"'a,b'", "\"x\\xx\"", "'fo''bar'", NULL}; ensure("split tokens empty1", compare_string_lists(base::split_token_list("", ','), empty)); ensure("split tokens empty2", compare_string_lists(base::split_token_list(",", ','), empty2)); ensure("split tokens empty2a", compare_string_lists(base::split_token_list(" ,", ','), empty2)); ensure("split tokens empty2b", compare_string_lists(base::split_token_list(", ", ','), empty2)); ensure("split tokens empty3", compare_string_lists(base::split_token_list(",,", ','), empty3)); ensure("split tokens empty4", compare_string_lists(base::split_token_list("NULL,", ','), null_empty)); ensure("split tokens a", compare_string_lists(base::split_token_list("a", ','), a)); ensure("split tokens a_empty1", compare_string_lists(base::split_token_list("a,", ','), a_empty1)); ensure("split tokens a_empty2", compare_string_lists(base::split_token_list("a,,", ','), a_empty2)); ensure("split tokens ab_empty1", compare_string_lists(base::split_token_list("a,b,", ','), ab_empty1)); ensure("split tokens ab_empty2", compare_string_lists(base::split_token_list("a,,b", ','), ab_empty2)); ensure("split tokens ab_empty3", compare_string_lists(base::split_token_list(",a,b", ','), ab_empty3)); ensure("split tokens null,", compare_string_lists(base::split_token_list("NULL,", ','), null_empty)); ensure("split tokens null,null", compare_string_lists(base::split_token_list("NULL,NULL", ','), null_null)); ensure("split tokens '',null", compare_string_lists(base::split_token_list("'',NULL", ','), emptys_null)); ensure("split tokens 'a,b',null", compare_string_lists(base::split_token_list("'a,b',NULL", ','), ab_null)); ensure("split tokens 'a,b' , \"x\\xx\",'fo''bar'", compare_string_lists(base::split_token_list("'a,b' , \"x\\xx\",'fo''bar' ", ','), ab_xxx)); } // Testing split_by_set. TEST_FUNCTION(25) { const char *input[] = {NULL}; ensure("Split by set 1", compare_string_lists(base::split_by_set("", ""), input)); ensure("Split by set 2", compare_string_lists(base::split_by_set("", " "), input)); ensure("Split by set 3", compare_string_lists(base::split_by_set("", long_random_string), input)); const char *input2[] = {long_random_string.c_str(), NULL}; ensure("Split by set 4", compare_string_lists(base::split_by_set(long_random_string, ""), input2)); ensure("Split by set 5", base::split_by_set(long_random_string, "\xA8").size() > 1); // Works only because our implementation is not utf-8 aware. const char *input3[] = {"Lorem", "ipsum", "dolor", "sit", "amet.", NULL}; ensure("Split by set 6", compare_string_lists(base::split_by_set("Lorem ipsum dolor sit amet.", " "), input3)); const char *input4[] = {"Lorem", "ipsum", "dolor sit amet.", NULL}; ensure("Split by set 7", compare_string_lists(base::split_by_set("Lorem ipsum dolor sit amet.", " ", 2), input4)); const char *input5[] = {"\"Lorem\"", "\"ipsum\"", "\"dolor\"", "\"sit\"", "\"amet\"", NULL}; ensure("Split by set 8", compare_string_lists(base::split_by_set("\"Lorem\"\t\"ipsum\"\t\"dolor\"\t\"sit\"\t\"amet\"", "\t"), input5)); const char *input6[] = {"\"Lorem\"", "\"ipsum\"", "\"dolor\"", "\"sit\"", "\"amet\"", NULL}; ensure("Split by set 9", compare_string_lists(base::split_by_set("\"Lorem\"\t\"ipsum\"\n\"dolor\"\t\"sit\"\n\"amet\"", " \t\n"), input6)); const char *input7[] = {"\"Lorem\"", "\"ip", "sum\"", "\"dolor\"", "\"sit\"", "\"amet\"", NULL}; ensure("Split by set 10", compare_string_lists(base::split_by_set("\"Lorem\"\t\"ip sum\"\n\"dolor\"\t\"sit\"\n\"amet\"", " \t\n"), input7)); const char *input8[] = {"", "Lorem", "", " ", "ipsum", "", " ", "dolor", "", " ", "sit", "", " ", "amet", "", NULL}; ensure("Split by set 11", compare_string_lists(base::split_by_set("\"Lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet\"", ",\""), input8)); ensure("Split by set 12", compare_string_lists(base::split_by_set("\"Lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet\"", ",\"", 100), input8)); const char *input9[] = {"", "Lorem", "", " ", "ipsum", "", " ", "dolor\", \"sit\", \"amet\"", NULL}; ensure("Split by set 13", compare_string_lists(base::split_by_set("\"Lorem\", \"ipsum\", \"dolor\", \"sit\", \"amet\"", ",\"", 7), input9)); } // Testing trim_right, trim_left, trim. TEST_FUNCTION(30) { ensure_equals("Trim left 1", base::trim_left(""), ""); ensure_equals("Trim left 2", base::trim_left(" "), ""); ensure_equals("Trim left 3", base::trim_left(" \n\t\t\t\t a"), "a"); ensure_equals("Trim left 4", base::trim_left("a \n\t\t\t\t "), "a \n\t\t\t\t "); ensure_equals("Trim left 5", base::trim_left("", long_random_string), ""); ensure_equals("Trim left 6", base::trim_left("\xE3\x8A\xA8\xE3\x8A\xA8\x7F", long_random_string), "\x7F"); ensure_equals("Trim left 7", base::trim_left("\t\t\tLorem ipsum dolor sit amet\n\n\n"), "Lorem ipsum dolor sit amet\n\n\n"); ensure_equals("Trim left 8", base::trim_left("\t\t\tLorem ipsum dolor sit amet\n\n\n", "L"), "\t\t\tLorem ipsum dolor sit amet\n\n\n"); ensure_equals("Trim left 9", base::trim_left("\t\t\tLorem ipsum dolor sit amet\n\n\n", "\t\t\tL"), "orem ipsum dolor sit amet\n\n\n"); ensure_equals("Trim right 1", base::trim_right(""), ""); ensure_equals("Trim right 2", base::trim_right(" "), ""); ensure_equals("Trim right 3", base::trim_right(" \n\t\t\t\t a"), " \n\t\t\t\t a"); ensure_equals("Trim right 4", base::trim_right("a \n\t\t\t\t "), "a"); ensure_equals("Trim right 5", base::trim_right("", long_random_string), ""); ensure_equals("Trim right 6", base::trim_right("\x7F\xE3\x8A\xA8\xE3\x8A\xA8", long_random_string), "\x7F"); ensure_equals("Trim right 7", base::trim_right("\t\t\tLorem ipsum dolor sit amet\n\n\n"), "\t\t\tLorem ipsum dolor sit amet"); ensure_equals("Trim right 8", base::trim_right("\t\t\tLorem ipsum dolor sit amet\n\n\n", "L"), "\t\t\tLorem ipsum dolor sit amet\n\n\n"); ensure_equals("Trim right 9", base::trim_right("\t\t\tLorem ipsum dolor sit amet\n\n\n", "\n\n\nt"), "\t\t\tLorem ipsum dolor sit ame"); ensure_equals("Trim 1", base::trim(""), ""); ensure_equals("Trim 2", base::trim(" "), ""); ensure_equals("Trim 3", base::trim(" \n\t\t\t\t a"), "a"); ensure_equals("Trim 4", base::trim("a \n\t\t\t\t "), "a"); ensure_equals("Trim 5", base::trim("", long_random_string), ""); ensure_equals("Trim 6", base::trim("\xE3\x8A\xA8\xE3\x8A\xA8\x7F\xE3\x8A\xA8\xE3\x8A\xA8", long_random_string), "\x7F"); ensure_equals("Trim 7", base::trim("\t\t\tLorem ipsum dolor sit amet\n\n\n"), "Lorem ipsum dolor sit amet"); ensure_equals("Trim 8", base::trim("\t\t\tLorem ipsum dolor sit amet\n\n\n", "L"), "\t\t\tLorem ipsum dolor sit amet\n\n\n"); ensure_equals("Trim 9", base::trim("\t\t\tLorem ipsum dolor sit amet\n\n\n", "\n\n\t\t\ttL"), "orem ipsum dolor sit ame"); } /** * Testing base::unescape_sql_string, which also includes escape sequence handling. */ TEST_FUNCTION(35) { std::string test_result = base::unescape_sql_string("", '`'); ensure_equals("Unquoting 35.1", test_result, ""); test_result = base::unescape_sql_string("lorem ipsum dolor sit amet", '"'); ensure_equals("Unquoting 35.2", test_result, "lorem ipsum dolor sit amet"); test_result = base::unescape_sql_string("lorem ipsum dolor`` sit amet", '"'); ensure_equals("Unquoting 35.3", test_result, "lorem ipsum dolor`` sit amet"); test_result = base::unescape_sql_string("lorem ipsum \"\"dolor sit amet", '"'); ensure_equals("Unquoting 35.4", test_result, "lorem ipsum \"dolor sit amet"); test_result = base::unescape_sql_string("lorem \"\"\"\"ipsum \"\"dolor\"\" sit amet", '"'); ensure_equals("Unquoting 35.5", test_result, "lorem \"\"ipsum \"dolor\" sit amet"); test_result = base::unescape_sql_string("lorem \\\"\\\"ipsum\"\" \\\\dolor sit amet", '"'); ensure_equals("Unquoting 35.6", test_result, "lorem \"\"ipsum\" \\dolor sit amet"); test_result = base::unescape_sql_string("lorem \\\"\\\"ipsum\"\" \\\\dolor sit amet", '\''); ensure_equals("Unquoting 35.7", test_result, "lorem \"\"ipsum\"\" \\dolor sit amet"); // Embedded 0 is more difficult to test due to limitations when comparing strings. So we do this // in a separate test. test_result = base::unescape_sql_string("lorem\\n ip\\t\\rsum dolor\\b sit \\Zamet", '"'); ensure_equals("Unquoting 35.8", test_result, "lorem\n ip\t\rsum dolor\b sit \032amet"); test_result = base::unescape_sql_string("lorem ipsum \\zd\\a\\olor sit amet", '"'); ensure_equals("Unquoting 35.9", test_result, "lorem ipsum zdaolor sit amet"); test_result = base::unescape_sql_string("\\0\\n\\t\\r\\b\\Z", '"'); ensure("Unquoting 35.10", test_result[0] == 0 && test_result[1] == 10 && test_result[2] == 9 && test_result[3] == 13 && test_result[4] == '\b' && test_result[5] == 26 ); std::string long_string; long_string.resize(2000); std::fill(long_string.begin(), long_string.end(), '`'); test_result = base::unescape_sql_string(long_string, '`'); ensure_equals("Unquoting 35.11", test_result, long_string.substr(0, 1000)); } TEST_FUNCTION(36) { std::string content1 = "11111111 22222 3333 444444 555555555 666666 77777777 88888 999999999 00000000"; std::string content2 = "\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81 \xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89 \xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D \xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93 \xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A"; std::string content3 = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; std::string content4 = "aaaaa bbbbb cccc dddd \xAA\xBB\xCC\xDD"; std::string content5 = "aaaa bbbb cccc dddd eeee"; // 模板名,使用英文,保证唯一性。格式建议:“类型_动作”,如“blog_add”或“credit_blog_add” // Template name, in English, to ensure uniqueness. Format advice: "type _ action," such as "blog_add" or "credit_blog_add" unsigned char content6[] = { 0x20 , 0x20 , 0x6e , 0x61 , 0x6d , 0x65 , 0x3a , 0x20 , 0xe6, 0xa8, 0xa1 , 0xe6, 0x9d, 0xbf // 10 , 0xe5, 0x90, 0x8d , 0xef, 0xbc, 0x8c , 0xe4, 0xbd, 0xbf , 0xe7, 0x94, 0xa8 , 0xe8, 0x8b, 0xb1 , 0xe6, 0x96, 0x87 , 0xef, 0xbc, 0x8c , 0xe4, 0xbf, 0x9d , 0xe8, 0xaf, 0x81 , 0xe5, 0x94, 0xaf // 20 , 0xe4, 0xb8, 0x80 , 0xe6, 0x80, 0xa7 , 0xe3, 0x80, 0x82 , 0xe6, 0xa0, 0xbc , 0xe5, 0xbc, 0x8f , 0xe5, 0xbb, 0xba , 0xe8, 0xae, 0xae , 0xef, 0xbc, 0x9a , 0xe2, 0x80, 0x9c , 0xe7, 0xb1, 0xbb // 30 , 0xe5, 0x9e, 0x8b , 0x5f , 0xe5, 0x8a, 0xa8 , 0xe4, 0xbd, 0x9c , 0xe2, 0x80, 0x9d , 0xef, 0xbc, 0x8c , 0xe5, 0xa6, 0x82 , 0xe2, 0x80, 0x9c , 0x62 , 0x6c // 40 , 0x6f , 0x67 , 0x5f , 0x61 , 0x64 , 0x64 , 0xe2, 0x80, 0x9d , 0xe6, 0x88, 0x96 , 0xe2, 0x80, 0x9c , 0x63 // 50 , 0x72 , 0x65 , 0x64 , 0x69 , 0x74 , 0x5f , 0x62 , 0x6c , 0x6f , 0x67 // 60 , 0x5f , 0x61 , 0x64 , 0x64 , 0xe2, 0x80, 0x9d // 65 , 0x00 }; std::string expected1 = " 11111111 22222 \n 3333 444444 \n 555555555 666666 \n 77777777 88888 \n 999999999 \n 00000000"; std::string expected2 = "11111111 22222 \n 3333 444444 \n 555555555 666666 \n 77777777 88888 \n 999999999 \n 00000000"; std::string expected3 = " \xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81\xC3\x81 \xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89 \n \xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D\xC3\x8D \n \xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93\xC3\x93 \xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A\xC3\x9A"; std::string expected4 = " 11111111 22222 \n 3333 444444 \n(...)"; std::string expected5 = " 111111111111111111\n 111111111111111111\n 111111111111111111\n 111111111111111111\n 111111111111111111\n 111111111111111111\n 111111111111111111\n 11111111111111"; std::string expected6 = ""; std::string expected7 = "aaaa \nbbbb \ncccc \ndddd \neeee"; std::string result; try { base::reflow_text(content4, 20, " "); fail("TEST 36.1: Didn't throw an exception"); } catch(std::invalid_argument) { // Exception was expected } try { result = base::reflow_text(content1, 20, " ", true, 10); // Indentation } catch(std::logic_error &e) { fail(std::string("TEST 36.2: Unexpected exception: ") + e.what()); } ensure_equals("Comparing word wrap with indentation", result, expected1); try { result = base::reflow_text(content1, 20, " ", false, 10); // Do not indent first line } catch(std::logic_error &e) { fail(std::string("TEST 36.3: Unexpected exception: ") + e.what()); } ensure_equals("Comparing word wrap without indentation", result, expected2); try { result = base::reflow_text(content2, 20, " ", true, 10); // String with multi-byte characters } catch(std::logic_error &e) { fail(std::string("TEST 36.4: Unexpected exception: ") + e.what()); } ensure_equals("Comparing word wrap with multi-byte", result, expected3); try { result = base::reflow_text(content1, 20, " ", true, 2); // Line limit reached } catch(std::logic_error &e) { fail(std::string("TEST 36.5: Unexpected exception: ") + e.what()); } ensure_equals("Comparing word wrap line limit", result, expected4); try { result = base::reflow_text(content3, 20, " ", true, 10); // Big word } catch(std::logic_error &e) { fail(std::string("TEST 36.6: Unexpected exception: ") + e.what()); } ensure_equals("Test with very big word", result, expected5); try { result = base::reflow_text("", 20, " ", true, 10); // Empty string } catch(std::logic_error &e) { fail(std::string("TEST 36.7: Unexpected exception: ") + e.what()); } ensure_equals("Test with empty string", result, expected6); try { result = base::reflow_text(content5, 6, " ", true, 10); // Left fill automatic removal } catch(std::logic_error &e) { fail(std::string("TEST 36.8: Unexpected exception: ") + e.what()); } ensure_equals("Left fill automatic removal", result, expected7); try { result = base::reflow_text(content5, 4, " ", true, 10); // Invalid line length } catch(std::logic_error &e) { fail(std::string("TEST 36.9: Unexpected exception: ") + e.what()); } ensure_equals("Invalid line length", result, ""); // This test is to ensure that a big string won't mess up algorithm std::string dictionary[] = { "one", "big", "speech", "made", "words", "a", "of", "out" }; std::string long_text; while (long_text.size() < SHRT_MAX) { int index = rand() % 8; // 8 is the size of the dictionary long_text += dictionary[index] + " "; } try { result = base::reflow_text(long_text, 100, " ", true, 1000); // Short string, long line } catch(std::logic_error &e) { fail(std::string("TEST 36.9: Unexpected exception: ") + e.what()); } try { result = base::reflow_text(std::string((char*)content6), 10, " ", false); // Short string, long line } catch(std::logic_error &e) { fail(std::string("TEST 36.10: Unexpected exception: ") + e.what()); } // Remove the line feed and fill to verify coherence std::size_t position = 0; while((position = result.find("\n ", position)) != std::string::npos) result.replace(position, 3, ""); ensure_equals("Removing separators test", result, std::string((char*)content6)); // This test was a specific case of a bug try { result = base::reflow_text(std::string((char*)content6), 60, " "); // Short string, long line } catch(std::logic_error &e) { fail(std::string("TEST 36.10: Unexpected exception: ") + e.what()); } } TEST_FUNCTION(37) { ensure_equals("TEST 37.1: unable to extract and convert number from string", base::atoi<int>("10G", 0), 10); ensure_equals("TEST 37.2: unable to convert string to number", base::atoi<int>("10", 0), 10); ensure_equals("TEST 37.3: default return value mismatch ", base::atoi<int>("G", -1), -1); bool test_exception = false; try { base::atoi<int>("G"); test_exception = true; } catch (std::exception &) { } ensure_equals("TEST 37.4: missed exception on mismatched string", test_exception, false); } TEST_FUNCTION(40) { std::string test_string = "This is a test string...to test."; std::string test_string_unicode = "\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89...Now that is a unicode string...\xE3\x8A\xA8"; // Base tests ensure_equals("TEST 40.1: Starts with (success test)", base::starts_with(test_string, "This"), true); ensure_equals("TEST 40.2: Starts with (exists somwehere in the middle)", base::starts_with(test_string, "is"), false); ensure_equals("TEST 40.3: Starts with (exists in the end)", base::starts_with(test_string, "test."), false); ensure_equals("TEST 40.4: Starts with (search text don't exist)", base::starts_with(test_string, "blablabla"), false); ensure_equals("TEST 40.5: Starts with (search an empty string)", base::starts_with(test_string, ""), true); ensure_equals("TEST 40.6: Starts with (starting on the second character)", base::starts_with(test_string, "his"), false); ensure_equals("TEST 40.7: Starts with (whole string)", base::starts_with(test_string, test_string), true); ensure_equals("TEST 40.8: Starts with (more then the original string)", base::starts_with(test_string, test_string + " Second part..."), false); ensure_equals("TEST 40.9: Starts with (empty source)", base::starts_with("", "blablabla"), false); ensure_equals("TEST 40.10: Starts with (empty source, empty search)", base::starts_with("", ""), true); ensure_equals("TEST 40.11: Ends with (success test)", base::ends_with(test_string, "test."), true); ensure_equals("TEST 40.12: Ends with (exists somwehere in the middle)", base::ends_with(test_string, "to "), false); ensure_equals("TEST 40.13: Ends with (exists at the beginning)", base::ends_with(test_string, "This"), false); ensure_equals("TEST 40.14: Ends with (search text don't exist)", base::ends_with(test_string, "blablabla"), false); ensure_equals("TEST 40.15: Ends with (search an empty string)", base::ends_with(test_string, ""), true); ensure_equals("TEST 40.16: Ends with (starting on the second last character)", base::ends_with(test_string, "test"), false); ensure_equals("TEST 40.17: Ends with (whole string)", base::ends_with(test_string, test_string), true); ensure_equals("TEST 40.18: Ends with (more then the original string)", base::ends_with(test_string, test_string + " Second part..."), false); ensure_equals("TEST 40.19: Ends with (empty source)", base::ends_with("", "blablabla"), false); ensure_equals("TEST 40.20: Ends with (empty source, empty search)", base::ends_with("", ""), true); // Unicode tests ensure_equals("TEST 40.21: [Unicode]Starts with (success test)", base::starts_with(test_string_unicode, "\xC3\x89\xC3\x89"), true); ensure_equals("TEST 40.22: [Unicode]Starts with (exists somwehere in the middle)", base::starts_with(test_string_unicode, "is"), false); ensure_equals("TEST 40.23: [Unicode]Starts with (exists in the end)", base::starts_with(test_string_unicode, "\xE3\x8A\xA8"), false); ensure_equals("TEST 40.24: [Unicode]Starts with (search text don't exist)", base::starts_with(test_string_unicode, "blablabla"), false); ensure_equals("TEST 40.25: [Unicode]Starts with (search an empty string)", base::starts_with(test_string_unicode, ""), true); ensure_equals("TEST 40.26: [Unicode]Starts with (starting on the second character)", base::starts_with(test_string_unicode, "\x89\xC3\x89\xC3"), false); ensure_equals("TEST 40.27: [Unicode]Starts with (whole string)", base::starts_with(test_string_unicode, test_string_unicode), true); ensure_equals("TEST 40.28: [Unicode]Starts with (more then the original string)", base::starts_with(test_string_unicode, test_string_unicode + ". Second part..."), false); ensure_equals("TEST 40.29: [Unicode]Ends with (success test)", base::ends_with(test_string_unicode, ".\xE3\x8A\xA8"), true); ensure_equals("TEST 40.30: [Unicode]Ends with (exists somwehere in the middle)", base::ends_with(test_string_unicode, "to "), false); ensure_equals("TEST 40.31: [Unicode]Ends with (exists at the beginning)", base::ends_with(test_string_unicode, "\xC3\x89\xC3\x89"), false); ensure_equals("TEST 40.32: [Unicode]Ends with (search text don't exist)", base::ends_with(test_string_unicode, "blablabla"), false); ensure_equals("TEST 40.33: [Unicode]Ends with (search an empty string)", base::ends_with(test_string_unicode, ""), true); ensure_equals("TEST 40.34: [Unicode]Ends with (starting on the second last character)", base::ends_with(test_string_unicode, ".\xE3\x8A"), false); ensure_equals("TEST 40.35: [Unicode]Ends with (whole string)", base::ends_with(test_string_unicode, test_string_unicode), true); ensure_equals("TEST 40.36: [Unicode]Ends with (more then the original string)", base::ends_with(test_string_unicode, test_string_unicode + ". Second part..."), false); } TEST_FUNCTION(41) { std::string test_string = "This is a test string...to test."; std::string test_string_unicode = "\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89\xC3\x89...Now that is a unicode string...\xE3\x8A\xA8"; // Base tests ensure_equals("TEST 40.1: String left (regular testing)", base::left(test_string, 5), "This "); ensure_equals("TEST 40.2: String left (last character", base::left(test_string, 1), "T"); ensure_equals("TEST 40.3: String left (zero characters)", base::left(test_string, 0), ""); ensure_equals("TEST 40.4: String left (with empty string)", base::left("", 5), ""); ensure_equals("TEST 40.5: String left (whole string)", base::left(test_string, test_string.length()), test_string); ensure_equals("TEST 40.6: String left (more chars then the original string)", base::left(test_string, 50), test_string); ensure_equals("TEST 40.7: String right (regular testing)", base::right(test_string, 5), "test."); ensure_equals("TEST 40.8: String right (last character", base::right(test_string, 1), "."); ensure_equals("TEST 40.9: String right (zero characters)", base::right(test_string, 0), ""); ensure_equals("TEST 40.10: String right (with empty string)", base::right("", 5), ""); ensure_equals("TEST 40.11: String right (whole string)", base::right(test_string, test_string.length()), test_string); ensure_equals("TEST 40.12: String right (more chars then the original string)", base::right(test_string, 50), test_string); // Unicode tests ensure_equals("TEST 40.13: [Unicode]String left (regular testing)", base::left(test_string_unicode, 5), "\xC3\x89\xC3\x89\xC3"); ensure_equals("TEST 40.14: [Unicode]String left (last character", base::left(test_string_unicode, 1), "\xC3"); ensure_equals("TEST 40.15: [Unicode]String left (zero characters)", base::left(test_string_unicode, 0), ""); ensure_equals("TEST 40.16: [Unicode]String left (with empty string)", base::left("", 5), ""); ensure_equals("TEST 40.17: [Unicode]String left (whole string)", base::left(test_string_unicode, test_string_unicode.length()), test_string_unicode); ensure_equals("TEST 40.18: [Unicode]String left (more chars then the original string)", base::left(test_string_unicode, 500), test_string_unicode); ensure_equals("TEST 40.19: [Unicode]String right (regular testing)", base::right(test_string_unicode, 5), "..\xE3\x8A\xA8"); ensure_equals("TEST 40.20: [Unicode]String right (last character", base::right(test_string_unicode, 1), "\xA8"); ensure_equals("TEST 40.21: [Unicode]String right (zero characters)", base::right(test_string_unicode, 0), ""); ensure_equals("TEST 40.22: [Unicode]String right (with empty string)", base::right("", 5), ""); ensure_equals("TEST 40.23: [Unicode]String right (whole string)", base::right(test_string_unicode, test_string_unicode.length()), test_string_unicode); ensure_equals("TEST 40.24: [Unicode]String right (more chars then the original string)", base::right(test_string_unicode, 500), test_string_unicode); } TEST_FUNCTION(42) { for (const char **kw = reserved_keywords; *kw != NULL; ++kw) ensure("TEST 42.1: Testing keywords", base::is_reserved_word(*kw) == true); ensure("TEST 42.2: Testing no keyword", base::is_reserved_word("some_word") == false); ensure("TEST 42.3: Testing unicode keywords", base::is_reserved_word("\xC3\x89\xC3\x89\xC3") == false); ensure("TEST 42.4: Testing empty string", base::is_reserved_word("") == false); ensure("TEST 42.5: Testing similar string", base::is_reserved_word("COLUMNA") == false); ensure("TEST 42.6: Testing similar string", base::is_reserved_word("ACOLUMN") == false); ensure("TEST 42.7: Testing similar string", base::is_reserved_word("COLUM") == false); ensure("TEST 42.7: Testing duplicated string", base::is_reserved_word("COLUMNCOLUMN") == false); } TEST_FUNCTION(43) { std::string font_description; std::string font; float size = 0; bool bold = false; bool italic = false; font_description = "Sans 10"; ensure_true(base::strfmt("TEST 43.1: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_false(bold); assure_false(italic); font_description = "Sans 12"; ensure_true(base::strfmt("TEST 43.2: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 12); assure_false(bold); assure_false(italic); font_description = "Sans 10 bold"; ensure_true(base::strfmt("TEST 43.3: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_true(bold); assure_false(italic); font_description = "Sans 10 BOLD"; ensure_true(base::strfmt("TEST 43.4: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_true(bold); assure_false(italic); font_description = "Sans 10 italic"; ensure_true(base::strfmt("TEST 43.5: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_false(bold); assure_true(italic); font_description = "Sans 10 ITALIC"; ensure_true(base::strfmt("TEST 43.6: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_false(bold); assure_true(italic); font_description = "Sans 10 bold italic"; ensure_true(base::strfmt("TEST 43.7: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_true(bold); assure_true(italic); font_description = "Sans 10 BOLD ITALIC"; ensure_true(base::strfmt("TEST 43.8: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Sans"); ensure_equals("", size, 10); assure_true(bold); assure_true(italic); font_description = "My Font 10 BOLD ITALIC"; ensure_true(base::strfmt("TEST 43.8: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "My Font"); ensure_equals("", size, 10); assure_true(bold); assure_true(italic); font_description = "Helvetica Bold 12"; ensure_true(base::strfmt("TEST 43.8: Parsing for \"%s\"", font_description.c_str()), base::parse_font_description(font_description, font, size, bold, italic)); ensure_equals("", font, "Helvetica"); ensure_equals("", size, 12); assure_true(bold); assure_false(italic); } END_TESTS
38.770576
379
0.657105
aasthakm
e481c3b52bd9acdb8521879b7f281f912a2e51ac
2,568
cpp
C++
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Probes/svcraw_repl.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Probes/svcraw_repl.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
pin-3.22-98547-g7a303a835-gcc-linux/source/tools/Probes/svcraw_repl.cpp
ArthasZhang007/15418FinalProject
a71f698ea48ebbc446111734c198f16a55633669
[ "MIT" ]
null
null
null
/* * Copyright (C) 2007-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ /* ===================================================================== */ /*! @file Replaces svcraw_create(). Linux only, of course. On some OSes this routine can be probed only if Pin moves the whole routine to another place */ #include "pin.H" #include <iostream> #include <fstream> #include <stdlib.h> #include "tool_macros.h" using std::cerr; using std::cout; using std::endl; /* ===================================================================== */ /* Global Variables */ /* ===================================================================== */ typedef void* (*FUNCPTR)(); static void* (*pf_svcraw_create)(); /* ===================================================================== */ INT32 Usage() { cerr << "This pin tool replaces svcraw_create()\n" "\n"; cerr << KNOB_BASE::StringKnobSummary(); cerr << endl; return -1; } /* ===================================================================== */ void* SvcrawCreate(void* arg) { cout << "SvcrawCreate: calling original svcraw_create() from libc" << endl; return (pf_svcraw_create)(); } /* ===================================================================== */ // Called every time a new image is loaded. // Look for routines that we want to replace. VOID ImageLoad(IMG img, VOID* v) { RTN rtn = RTN_FindByName(img, C_MANGLE("svcraw_create")); if (RTN_Valid(rtn)) { if (RTN_IsSafeForProbedReplacementEx(rtn, PROBE_MODE_ALLOW_RELOCATION)) { // Save the function pointer that points to the new location of // the entry point of the original exit in this image. // pf_svcraw_create = (FUNCPTR)RTN_ReplaceProbedEx(rtn, PROBE_MODE_ALLOW_RELOCATION, AFUNPTR(SvcrawCreate)); cout << "ImageLoad: Replaced svcraw_create() in: " << IMG_Name(img) << endl; } else { cout << "ImageLoad: Pin can't replace svcraw_create() in: " << IMG_Name(img) << endl; PIN_ExitApplication(-1); } } } /* ===================================================================== */ int main(int argc, CHAR* argv[]) { PIN_InitSymbols(); if (PIN_Init(argc, argv)) return Usage(); IMG_AddInstrumentFunction(ImageLoad, 0); PIN_StartProgramProbed(); return 0; } /* ===================================================================== */ /* eof */ /* ===================================================================== */
27.319149
117
0.465732
ArthasZhang007
e4831c658db1347b687e50b3143b0efaba2d5b43
4,623
cpp
C++
tests/boss/test_rpc.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
null
null
null
tests/boss/test_rpc.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
null
null
null
tests/boss/test_rpc.cpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
null
null
null
#undef NDEBUG #include"Boss/Mod/Rpc.hpp" #include"Boss/Shutdown.hpp" #include"Ev/Io.hpp" #include"Ev/concurrent.hpp" #include"Ev/start.hpp" #include"Ev/yield.hpp" #include"Jsmn/Object.hpp" #include"Json/Out.hpp" #include"Net/Fd.hpp" #include"S/Bus.hpp" #include<assert.h> #include<cstdint> #include<fcntl.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> namespace { /* Simple server. */ class SimpleServer { private: Net::Fd socket; Ev::Io<void> writeloop(std::string to_write) { /* Yield to let other greenthreads run, then * keep trying to write. */ return Ev::yield().then([this, to_write]() { auto res = write( socket.get() , to_write.c_str(), to_write.size() ); if (res < 0 && ( errno == EWOULDBLOCK || errno == EAGAIN )) /* Loop. */ return writeloop(to_write); assert(size_t(res) == to_write.size()); return Ev::yield(); }); } /* Slurp any incoming data. */ Ev::Io<void> slurp() { return Ev::yield().then([this]() { char buf[256]; auto first = true; for (;;) { auto res = read( socket.get() , buf, sizeof(buf) ); if (res < 0 && ( errno == EWOULDBLOCK || errno == EAGAIN )) { if (first) /* No data from client yet. */ return slurp(); else break; } assert(res >= 0); first = false; } return Ev::yield(); }); } public: explicit SimpleServer(Net::Fd socket_) : socket(std::move(socket_)) { auto flags = fcntl(socket.get(), F_GETFL); flags |= O_NONBLOCK; fcntl(socket.get(), F_SETFL, flags); } SimpleServer(SimpleServer&& o) : socket(std::move(o.socket)) { } Ev::Io<void> respond(std::uint64_t id) { return Ev::yield().then([this]() { /* Slurp any data. */ return slurp(); }).then([this, id]() { /* Build response. */ auto js = Json::Out() .start_object() .field("jsonrpc", std::string("2.0")) .field("id", double(id)) .field("result", Json::Out().start_object().end_object()) .end_object() .output() ; return writeloop(js); }); } Ev::Io<void> error( std::uint64_t id , int code , std::string message ) { return Ev::yield().then([this]() { /* Slurp any data. */ return slurp(); }).then([this, id, code, message]() { /* Build response. */ auto err = Json::Out() .start_object() .field("code", double(code)) .field("message", message) .end_object() ; auto js = Json::Out() .start_object() .field("jsonrpc", std::string("2.0")) .field("id", double(id)) .field("error", err) .end_object() .output() ; return writeloop(js); }); } }; } int main() { auto bus = S::Bus(); int sockets[2]; auto res = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets); assert(res >= 0); auto server_socket = Net::Fd(sockets[0]); auto client_socket = Net::Fd(sockets[1]); auto server = SimpleServer(std::move(server_socket)); auto client = Boss::Mod::Rpc(bus, std::move(client_socket)); auto succeed_flag = false; auto errored_flag = false; auto shutdown_flag = false; /* Server responds with success, then failure, then shuts down. */ auto server_code = Ev::lift().then([&]() { return server.respond(0); }).then([&]() { return server.error(1, -32600, "Some error"); }).then([&]() { return bus.raise(Boss::Shutdown()); }); /* Client makes three attempts, the first succeeds, the second * fails, the third with a cancellation of commands. */ auto client_code = Ev::lift().then([&]() { auto params = Json::Out(); auto arr = params .start_object() .start_array("arr") ; for (auto i = size_t(0); i < 10000; ++i) arr.entry((double)i); arr .end_array() .end_object() ; return client.command("c1", params); }).then([&](Jsmn::Object ignored_result) { succeed_flag = true; return client.command("c2", Json::Out::empty_object()) .catching<Boss::Mod::RpcError>([&](Boss::Mod::RpcError const& e) { errored_flag = true; return Ev::lift(Jsmn::Object()); }); }).then([&](Jsmn::Object ignored_result) { return client.command("c3", Json::Out::empty_object()) .catching<Boss::Shutdown>([&](Boss::Shutdown const& e) { shutdown_flag = true; return Ev::lift(Jsmn::Object()); }); }).then([](Jsmn::Object ignored_result) { return Ev::lift(0); }); /* Launch code. */ auto code = Ev::lift().then([&]() { return Ev::concurrent(server_code); }).then([&]() { return client_code; }); auto ec = Ev::start(code); assert(succeed_flag); assert(errored_flag); assert(shutdown_flag); return ec; }
23.707692
70
0.594636
3nprob
e4839ba7ebd51b4d8bb191fa34ab317446643bea
12,605
cpp
C++
minesweeper/Board.cpp
elipwns/Data-Structures
6c9d6da1254aefd31dfed5edad5987a70c4423a9
[ "MIT" ]
null
null
null
minesweeper/Board.cpp
elipwns/Data-Structures
6c9d6da1254aefd31dfed5edad5987a70c4423a9
[ "MIT" ]
null
null
null
minesweeper/Board.cpp
elipwns/Data-Structures
6c9d6da1254aefd31dfed5edad5987a70c4423a9
[ "MIT" ]
null
null
null
#include "board.h" #include "Node.h" #include "LinkedList.h" #include <iostream> using std::cout; using std::cin; using std::endl; #include <stdlib.h> #include <time.h> /********************************************************************** * Purpose: Board no arg Ctor * * Entry: * * Exit: defaults the done flag to false, mines to 0 * ************************************************************************/ Board::Board() :m_done(false), m_mines(0) { } /********************************************************************** * Purpose: board dtor * * Entry: * * Exit: * ************************************************************************/ Board::~Board() { } /********************************************************************** * Purpose: board copy ctor * * Entry: passed a const board by ref * * Exit: copys the data memebers * ************************************************************************/ Board::Board(const Board & copy) { m_mines = copy.m_mines; m_done = copy.m_done; m_field = copy.m_field; } /********************************************************************** * Purpose: overloaded op = * * Entry: passed a const board by refrence * * Exit: if its not self assignment then copy data over * ************************************************************************/ Board & Board::operator=(const Board & rhs) { if (this != &rhs) { m_mines = rhs.m_mines; m_field = rhs.m_field; m_done = rhs.m_done; } return * this; } /********************************************************************** * Purpose: to clear the screen then display the board with coords shown * * Entry: the board should be setup with X,Y * * Exit: couts text that looks like a playing field * ************************************************************************/ void Board::DisplayBoard() { system("cls"); cout << " "; for(int k = 0; k < m_field.getColumn(); k++) { if (k > 9) cout << k; else cout << k << " "; } cout << endl; cout << " "; for(int k = 0; k < m_field.getColumn(); k++) cout << "__"; cout << endl; for (int i = 0; i < m_field.getRow(); i++) { if ( i < 10) cout << i << " |"; else cout << i << "|"; for(int j = 0; j < m_field.getColumn(); j++) cout << m_field[i][j] << " "; cout << endl; } } /********************************************************************** * Purpose: setter for row * * Entry: passed an int * * Exit: passes the int to the setter for array2d * ************************************************************************/ void Board::setRow(int rows) { m_field.setRow(rows); } /********************************************************************** * Purpose: getter for row * * Entry: * * Exit: returns the int returned by the getter for array2d * ************************************************************************/ int Board::getRow() { return m_field.getRow(); } /********************************************************************** * Purpose: getter for col * * Entry: * * Exit: returns the int returned by the getter for array2d * ************************************************************************/ int Board::getCol() { return m_field.getColumn(); } /********************************************************************** * Purpose: getter for mines * * Entry: * * Exit: returns m_mines * ************************************************************************/ int Board::getMines() { return m_mines; } /********************************************************************** * Purpose: setter for columns * * Entry: passed an int * * Exit: passes the int to the setter for array2d * ************************************************************************/ void Board::setCol(int cols) { m_field.setColumn(cols); } /********************************************************************** * Purpose: setter for mines * * Entry: passed an int * * Exit: sets mines to the int * ************************************************************************/ void Board::setMines(int mines) { m_mines = mines; } /********************************************************************** * Purpose: randomly lays the mines * * Entry: * * Exit: creates 2 random numbers and sets a mine at that coord * then calls set numbers to place numbers in relevant cells * then calls players turn * ************************************************************************/ void Board::Lay_Mines() { srand (time(NULL)); int randomX, randomY; for(int i = m_mines; i > 0; i--) { randomY = rand() % getRow(); randomX = rand() % getCol(); if (m_field[randomY][randomX].m_isBomb) i++; else { m_field[randomY][randomX].m_isBomb = true; m_field[randomY][randomX].m_symbol = 'X'; } } Set_Numbers(); Player_turn(); } /********************************************************************** * Purpose: sets the numbers * * Entry: assumes bombs already been placed * * Exit: checks each cells 8 nieghbors and adds one to a counter if bomb * ************************************************************************/ void Board::Set_Numbers() { int bombs_nearby = 0; for(int i = 0; i < m_field.getRow(); i++) { for(int j = 0; j < m_field.getColumn(); j++) { if (!m_field[i][j].m_isBomb) { if(i-1 >= 0) { if(m_field[i - 1][j].m_isBomb) bombs_nearby++; if(j-1 >= 0) if(m_field[i-1][j - 1].m_isBomb) bombs_nearby++; if(j+1 < m_field.getColumn()) if(m_field[i-1][j + 1].m_isBomb) bombs_nearby++; } if(i+1 < m_field.getRow()) { if(m_field[i + 1][j].m_isBomb) bombs_nearby++; if(j-1 >= 0) if(m_field[i + 1][j-1].m_isBomb) bombs_nearby++; if(j+1 < m_field.getColumn()) if(m_field[i + 1][j+1].m_isBomb) bombs_nearby++; } if(j-1 >= 0) if(m_field[i][j - 1].m_isBomb) bombs_nearby++; if(j+1 < m_field.getColumn()) if(m_field[i][j + 1].m_isBomb) bombs_nearby++; m_field[i][j].m_number = bombs_nearby; bombs_nearby = 0; } } } } /********************************************************************** * Purpose: deals with user input for coord and choices dealing with that * coord * * Entry: needs a board with bombs and numbers built * * Exit: asks user for a square and then asks if they want to toggle the * flag or uncover it * ************************************************************************/ void Board::Player_turn() { while(!m_done) { Check_Win(); DisplayBoard(); int x, y, choice = 0; cout << "Enter coord (Ex ~ 2 3) : "; cin >> x >> y; while (x < 0 || x > m_field.getColumn() || y < 0 || y > m_field.getRow() || (!m_field[y][x].m_covered && m_field[y][x].m_symbol != 'M')) { cout << "Enter coord (Ex ~ 2 3) : "; cin >> x >> y; } cout << "1) Uncover\n2) Mark for possible bomb\n"; cin >> choice; while(choice > 2 || choice < 1) { cout << "1) Uncover\n2) Mark for possible bomb\n"; cin >> choice; } if(choice == 1) Uncover(x, y); else if (choice == 2) { m_field[y][x].m_covered = false; if(m_field[y][x].m_symbol == 'M') { if(m_field[y][x].m_isBomb) m_field[y][x].m_symbol = 'X'; else m_field[y][x].m_symbol = ' '; m_field[y][x].m_covered = true; } else m_field[y][x].m_symbol = 'M'; } } } /********************************************************************** * Purpose: the uncover function * * Entry: passed an X,Y coord to uncover * * Exit: checks if bomb first, you lose * then checks if its a number, just display it * if its blank start up the uncover loop * ************************************************************************/ void Board::Uncover(int xStart, int yStart) { if (m_field[yStart][xStart].m_isBomb) { m_field[yStart][xStart].m_covered = false; DisplayBoard(); cout << "you lose\n"; m_done = true; } else if (m_field[yStart][xStart].m_number) { m_field[yStart][xStart].m_covered = false; } else { LinkedList start(xStart, yStart); Uncover_Loop(xStart, yStart, &start); while(start.m_head->GetNext() != nullptr) { start.Next(); Uncover_Loop(start.GetX(), start.GetY(), &start); } } } /********************************************************************** * Purpose: used to uncover cells and add them to a que to be checked * * Entry: is passed the X,Y coord to start at and a pointer to the linked list * * Exit: checks the 4 diagnals for a number to uncover and checks the 4 * sides for a blank spot to add to the que and to uncover * ************************************************************************/ void Board::Uncover_Loop(int xStart, int yStart, LinkedList * start) { m_field[yStart][xStart].m_covered = false; if(yStart - 1 >= 0) { if(!m_field[yStart - 1][xStart].m_isBomb) if(m_field[yStart - 1][xStart].m_covered) if(m_field[yStart - 1][xStart].m_symbol != 'M') if(!m_field[yStart - 1][xStart].m_number) { m_field[yStart - 1][xStart].m_covered = false; start->Add(xStart, yStart - 1); } else m_field[yStart - 1][xStart].m_covered = false; if (xStart - 1 >= 0) if(!m_field[yStart - 1][xStart - 1].m_isBomb) if(m_field[yStart - 1][xStart - 1].m_covered) if(m_field[yStart - 1][xStart - 1].m_symbol != 'M') if(!m_field[yStart - 1][xStart - 1].m_number) { m_field[yStart - 1][xStart - 1].m_covered = false; start->Add(xStart - 1, yStart - 1); } else m_field[yStart - 1][xStart - 1].m_covered = false; if (xStart + 1 < m_field.getColumn()) if(!m_field[yStart - 1][xStart + 1].m_isBomb) if(m_field[yStart - 1][xStart + 1].m_covered) if(m_field[yStart - 1][xStart + 1].m_symbol != 'M') if(!m_field[yStart - 1][xStart + 1].m_number) { m_field[yStart - 1][xStart + 1].m_covered = false; start->Add(xStart + 1, yStart - 1); } else m_field[yStart - 1][xStart + 1].m_covered = false; } if(yStart + 1 < m_field.getRow()) { if(!m_field[yStart + 1][xStart].m_isBomb) if(m_field[yStart + 1][xStart].m_covered) if(m_field[yStart + 1][xStart].m_symbol != 'M') if(!m_field[yStart + 1][xStart].m_number) { m_field[yStart + 1][xStart].m_covered = false; start->Add(xStart, yStart + 1); } else m_field[yStart + 1][xStart].m_covered = false; if (xStart - 1 >= 0) if(!m_field[yStart + 1][xStart - 1].m_isBomb) if(m_field[yStart + 1][xStart - 1].m_covered) if(m_field[yStart + 1][xStart - 1].m_symbol != 'M') if(!m_field[yStart + 1][xStart - 1].m_number) { m_field[yStart + 1][xStart - 1].m_covered = false; start->Add(xStart - 1, yStart + 1); } else m_field[yStart + 1][xStart - 1].m_covered = false; if(xStart + 1 < m_field.getColumn()) if(!m_field[yStart + 1][xStart + 1].m_isBomb) if(m_field[yStart + 1][xStart + 1].m_covered) if(m_field[yStart + 1][xStart + 1].m_symbol != 'M') if(!m_field[yStart + 1][xStart + 1].m_number) { m_field[yStart + 1][xStart + 1].m_covered = false; start->Add(xStart + 1, yStart + 1); } else m_field[yStart + 1][xStart + 1].m_covered = false; } if(xStart-1 >= 0) if(!m_field[yStart][xStart - 1].m_isBomb) if(m_field[yStart][xStart - 1].m_covered) if(m_field[yStart][xStart - 1].m_symbol != 'M') if(!m_field[yStart][xStart - 1].m_number) { m_field[yStart][xStart - 1].m_covered = false; start->Add(xStart - 1, yStart); } else m_field[yStart][xStart - 1].m_covered = false; if(xStart+1 < m_field.getColumn()) if(!m_field[yStart][xStart + 1].m_isBomb) if(m_field[yStart][xStart + 1].m_covered) if(m_field[yStart][xStart + 1].m_symbol != 'M') if(!m_field[yStart][xStart + 1].m_number) { m_field[yStart][xStart + 1].m_covered = false; start->Add(xStart + 1, yStart); } else m_field[yStart][xStart + 1].m_covered = false; DisplayBoard(); } /********************************************************************** * Purpose: this function checks to see if the player has won * * Entry: * * Exit: sets done to true and then checks every cell until it finds * a cell that fails the check, and then updates the done to false * ************************************************************************/ void Board::Check_Win() { m_done = true; for (int i = 0; i < m_field.getRow() && m_done; i++) for (int j = 0; j < m_field.getColumn() && m_done; j++) if(m_field[i][j].m_covered && !m_field[i][j].m_isBomb) m_done = false; }
25.464646
77
0.485442
elipwns
e483fc40b0f003010d558d9b203c73e3f3e9435b
973
cc
C++
src/leetcode/leetcode204_count_primes.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode204_count_primes.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode204_count_primes.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
// https://leetcode-cn.com/problems/count-primes/ #include <vector> using namespace std; class Solution { public: int countPrimes(int n) { // 0ms 秘诀 // if (n == 10000) // return 1229; // if (n == 499979) // return 41537; // if (n == 999983) // return 78497; // if (n == 1500000) // return 114155; vector<bool> isprime(n + 1, true); int count = 0; for (int i = 2; i < n; ++i) { if (isprime[i]) { ++count; for (int j = 2; i * j < n; ++j) { isprime[i * j] = false; } } } return count; } }; #include "gtest/gtest.h" TEST(leetcode204, sampleInputByProblem1) { Solution solution; ASSERT_EQ(4, solution.countPrimes(10)); } TEST(leetcode204, sampleInputByProblem2) { Solution solution; ASSERT_EQ(0, solution.countPrimes(0)); } TEST(leetcode204, sampleInputByProblem3) { Solution solution; ASSERT_EQ(0, solution.countPrimes(1)); }
17.690909
49
0.564234
zhaozigu
e4844cfa4f75fff58facfe7c11088de866535a88
3,110
hpp
C++
modules/scene_manager/include/map_msgs/srv/save_map__rosidl_typesupport_connext_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/scene_manager/include/map_msgs/srv/save_map__rosidl_typesupport_connext_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/scene_manager/include/map_msgs/srv/save_map__rosidl_typesupport_connext_cpp.hpp
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
// generated from // rosidl_typesupport_connext_cpp/resource/srv__rosidl_typesupport_connext_cpp.hpp.em // generated code does not contain a copyright notice #ifndef MAP_MSGS__SRV__SAVE_MAP__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_ #define MAP_MSGS__SRV__SAVE_MAP__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_ #include <rmw/types.h> #include "rosidl_typesupport_cpp/service_type_support.hpp" #include "rosidl_typesupport_interface/macros.h" #include "map_msgs/msg/rosidl_typesupport_connext_cpp__visibility_control.h" namespace map_msgs { namespace srv { namespace typesupport_connext_cpp { ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * create_requester__SaveMap( void * untyped_participant, const char * request_topic_str, const char * response_topic_str, const void * untyped_datareader_qos, const void * untyped_datawriter_qos, void ** untyped_reader, void ** untyped_writer, void * (*allocator)(size_t)); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs const char * destroy_requester__SaveMap( void * untyped_requester, void (* deallocator)(void *)); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs int64_t send_request__SaveMap( void * untyped_requester, const void * untyped_ros_request); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * create_replier__SaveMap( void * untyped_participant, const char * request_topic_str, const char * response_topic_str, const void * untyped_datareader_qos, const void * untyped_datawriter_qos, void ** untyped_reader, void ** untyped_writer, void * (*allocator)(size_t)); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs const char * destroy_replier__SaveMap( void * untyped_replier, void (* deallocator)(void *)); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs bool take_request__SaveMap( void * untyped_replier, rmw_request_id_t * request_header, void * untyped_ros_request); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs bool take_response__SaveMap( void * untyped_requester, rmw_request_id_t * request_header, void * untyped_ros_response); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs bool send_response__SaveMap( void * untyped_replier, const rmw_request_id_t * request_header, const void * untyped_ros_response); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * get_request_datawriter__SaveMap(void * untyped_requester); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * get_reply_datareader__SaveMap(void * untyped_requester); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * get_request_datareader__SaveMap(void * untyped_replier); ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs void * get_reply_datawriter__SaveMap(void * untyped_replier); } // namespace typesupport_connext_cpp } // namespace srv } // namespace map_msgs #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_CONNEXT_CPP_PUBLIC_map_msgs const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_connext_cpp, map_msgs, srv, SaveMap)(); #ifdef __cplusplus } #endif #endif // MAP_MSGS__SRV__SAVE_MAP__ROSIDL_TYPESUPPORT_CONNEXT_CPP_HPP_
25.491803
110
0.83537
Omnirobotic
e48749019a377c8ad9980398a2ae66700a95920a
6,610
cpp
C++
source/parallel_free_suitor.cpp
alanmazankiewicz/Cpp_Suitor_and_Local_Dominant_Matching
2fba808998cc58bd6c1a792b7c8d835e487bf3f5
[ "MIT" ]
null
null
null
source/parallel_free_suitor.cpp
alanmazankiewicz/Cpp_Suitor_and_Local_Dominant_Matching
2fba808998cc58bd6c1a792b7c8d835e487bf3f5
[ "MIT" ]
null
null
null
source/parallel_free_suitor.cpp
alanmazankiewicz/Cpp_Suitor_and_Local_Dominant_Matching
2fba808998cc58bd6c1a792b7c8d835e487bf3f5
[ "MIT" ]
null
null
null
#include "implementation/parallel_free_suitor.hpp" ParallelLocklessSuitor::ParallelLocklessSuitor(Input edgeLst) : G(edgeLst.second, edgeLst.first), suitor(std::make_unique<std::atomic<EdgeIterator>[]>(G.numNodes())) { for (auto iter = suitor.get(); iter != suitor.get() + G.numNodes(); ++iter) { iter->store(G.null_edge()); } } void ParallelLocklessSuitor::process(NodeHandle start, NodeHandle finish) { for (NodeHandle u = start; u != finish; ++u) { NodeHandle current = u; bool done = false; while (!done) { EdgeIterator partner = G.null_edge(); double heaviest = 0; for (EdgeIterator v = G.beginEdges(current); v != G.endEdges(current); ++v) { double weight_v = v->second; // to only load the array once if (weight_v > heaviest && weight_v > suitor[v->first].load()->second) { partner = v; heaviest = weight_v; } } done = true; if (heaviest > 0) { size_t partnerId = partner->first; // to only load the array once EdgeIterator current_suitor = suitor[partnerId]; if (current_suitor->second < heaviest) { if (suitor[partnerId].compare_exchange_strong(current_suitor, partner)) // here they swap (partner instead of counteredge to partner) { NodeHandle y = G.edgeHead(current_suitor); // therefore here 0 instead of 1 (edgehead -> instead of *current_suitor) -> only relevant at this point here if (y != G.null_node()) { current = y; done = false; } } else done = false; } else done = false; } } } } void ParallelLocklessSuitor::print_matching() const { for (auto iter = suitor.get(); iter != suitor.get() + G.numNodes(); ++iter) { EdgeIterator output = *iter; if (output != G.null_edge()) { std::cout << iter - suitor.get() << " " << G.nodeId(G.edgeHead(output)) << std::endl; } } } const double ParallelLocklessSuitor::matching_quality() const { double counter = 0; for (auto iter = suitor.get(); iter != suitor.get() + G.numNodes(); ++iter) { counter += iter->load()->second; } return counter / 2; } void ParallelLocklessSuitor::simple_procedure(size_t num_threads) { std::vector<std::thread> threads; threads.reserve(num_threads); size_t nodes_per_thread = G.numNodes() / num_threads; if(!nodes_per_thread) { for (size_t thread = 0; thread < G.numNodes(); ++thread) { threads.emplace_back( std::thread(&ParallelLocklessSuitor::process, this, G.begin() + thread, G.begin() + (thread + 1))); } } else { for (size_t thread = 0; thread < num_threads; ++thread) { if (thread != num_threads - 1) { threads.emplace_back( std::thread(&ParallelLocklessSuitor::process, this, G.begin() + thread * nodes_per_thread, G.begin() + (thread + 1) * nodes_per_thread)); } else { threads.emplace_back( std::thread(&ParallelLocklessSuitor::process, this, G.begin() + thread * nodes_per_thread, G.end())); } } } for (auto iter = threads.begin(); iter != threads.end(); ++iter) { iter->join(); } } void ParallelLocklessSuitor::clear_mate() { for (auto iter = suitor.get(); iter != suitor.get() + G.numNodes(); ++iter) { iter->store(G.null_edge()); } } void ParallelLocklessSuitor::test_matching() { for (NodeHandle u = G.begin(); u != G.end(); ++u) { if (suitor[G.nodeId(u)].load() != G.null_edge()) { EdgeIterator suit1 = suitor[G.nodeId(u)]; EdgeIterator suit2 = suitor[suit1->first]; assert(G.node(suit2->first) == u); } else assert(suitor[G.nodeId(u)].load() == G.null_edge()); } } int main(int argc, char *argv[]) { if(argc < 3 || argc > 3) { std::cout << "Invalid number of arguments" << std::endl; return 1; } int test_time = std::atoi(argv[1]); if(test_time < 0 || test_time > 1) { std::cout << "Invalid first argument" << std::endl; return 2; } if (test_time < 1) { std::string str = argv[2]; Input edgeLst = readEdges(str); ParallelLocklessSuitor test_1(edgeLst); for (size_t i = 0; i < 20; ++i) { test_1.simple_procedure(20); test_1.test_matching(); test_1.clear_mate(); } std::cout << "matching successfull" << std::endl; } else { std::string str = argv[2]; Input edgeLst = readEdges(str); ParallelLocklessSuitor test_1(edgeLst); ofstream myfile; std::size_t found = str.find_last_of("/\\"); std::string out = "../evaluation/ParFreeSuitor" + str.substr(found + 1) + ".txt"; myfile.open(out); std::stringstream header; header << "Algorithm Runtime Quality Threads" << std::endl; myfile << header.str(); cout << header.str(); size_t max_threads = std::thread::hardware_concurrency() > 32 ? 32 : std::thread::hardware_concurrency(); size_t rounds = 5; for (size_t threads = 2; threads <= max_threads; threads += 2) { for (size_t i = 0; i < rounds; ++i) { auto start = chrono::high_resolution_clock::now(); test_1.simple_procedure(threads); auto finish = chrono::high_resolution_clock::now(); chrono::duration<double> elapsed = finish - start; std::stringstream line; line << "ParFreeSuitorSimp " << elapsed.count() << " " << test_1.matching_quality() << " " << threads << std::endl; myfile << line.str(); cout << line.str(); test_1.clear_mate(); } } } return 0; }
31.47619
176
0.506505
alanmazankiewicz
e487edc57ca47f265618b70b409b2af3da2845ea
643
hpp
C++
libs/parsejson/include/sge/parse/json/get_return_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/parsejson/include/sge/parse/json/get_return_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/parsejson/include/sge/parse/json/get_return_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_PARSE_JSON_GET_RETURN_TYPE_HPP_INCLUDED #define SGE_PARSE_JSON_GET_RETURN_TYPE_HPP_INCLUDED #include <fcppt/reference_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::parse::json { template <typename T, typename Arg> using get_return_type = fcppt::reference<std::conditional_t<std::is_const_v<Arg>, T const, T>>; } #endif
27.956522
95
0.760498
cpreh
e487f596b569c234a2294b45d1e9eb5b738888b4
1,062
cc
C++
algo/searching/search_matrix.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/searching/search_matrix.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/searching/search_matrix.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
#include <cstdio> #include <cassert> #include <vector> using namespace std; bool binarySearch(vector<vector<int> > &matrix, int begin, int end, int target) { int M = matrix.size(); int N = matrix[0].size(); if (begin == end) { return false; } else { int mid = begin + (end - begin) / 2; int row = mid / N; int col = mid - row * N; printf("%d - %d - %d\n", mid, row, col); if (target == matrix[row][col]) { return true; } else if (target > matrix[row][col]) { return binarySearch(matrix, mid+1, end, target); } else { return binarySearch(matrix, begin, mid, target); } } } bool searchMatrix(vector<vector<int> > &matrix, int target) { int M = matrix.size(); if (M == 0) { return false; } int N = matrix[0].size(); return binarySearch(matrix, 0, M * N, target); } int main() { vector<int> v1 = {1, 1}; vector<vector<int> > v; v.push_back(v1); assert(!searchMatrix(v, 0)); return 0; }
24.697674
81
0.531073
liuheng
e48b9cb53e6ea2dbb31824c28d09eed3dd26b213
3,645
cpp
C++
main.cpp
HadesD/GoogleSearchCPP
f065e4c25d6192e1707566b4d03da337afe1041a
[ "MIT" ]
null
null
null
main.cpp
HadesD/GoogleSearchCPP
f065e4c25d6192e1707566b4d03da337afe1041a
[ "MIT" ]
null
null
null
main.cpp
HadesD/GoogleSearchCPP
f065e4c25d6192e1707566b4d03da337afe1041a
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <string> #include <regex> #include <curl/curl.h> // using namespace std; std::string url = "http://www.google.com.vn/search?q="; std::string query; std::string data; bool input(); std::string encode_query(std::string &q); size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up); bool curl(std::string url); int main(int argc, char* argv[]) { if (argc == 2) { query = argv[1]; } else { if (input() == false) { return 0; } } url += encode_query(query); std::cout << url << std::endl; curl(url); // Regex const std::regex r("<a.*?href=\"(.*?)\".*?>(.*?)</a>"); std::match_results<std::string::const_iterator> m; std::string::const_iterator searchStart = data.begin(); int i = 0; std::string uri[30]; while (std::regex_search(searchStart, data.cend(), m, r)) { searchStart = m[0].second; if (std::string(m[1]).find("/url?q=") == std::string::npos) { continue; } i++; uri[i] = std::string(m[1]); std::cout << "-[" << i << "]- " << m[2] << std::endl; if (std::string(m[1]).find("webcache.googleusercontent.com") == std::string::npos) { std::cout << "\tDirect: " << m[1] << std::endl; } else { std::cout << "\tCache: " << m[1] << std::endl; } } if (i > 0) { std::string choose; std::cout << "Choose a number: "; while ( !(std::cin >> choose) || choose > std::to_string(i) || choose <= std::to_string(0) || choose == "\n" ) { std::cout << "Number must be > 0 and < " << (i+1) << ": "; } curl("http://google.com.vn" + uri[std::stoi(choose)]); std::cout << data << std::endl; } return 0; } bool input() { while (query.empty()) { std::cout << "Type search query: "; getline(std::cin, query); } if (query == "q") { std::cout << "Exit..." << std::endl; return false; } return true; } std::string encode_query(std::string &s) { std::size_t pos = 0; // Replace all space std::string r(" "); while (pos < s.size()) { pos = s.find(r, pos); if (pos != std::string::npos) { s.replace(pos, r.length(), "+"); } } return s; } bool curl(std::string url) { std::cout << "Please wait..." << std::endl; // https://curl.haxx.se/libcurl/c/simple.html CURL *curl; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { CURLcode res; long http_code = 0; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCallback); // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // Header struct curl_slist *list = NULL; //list = curl_slist_append(list, "User-Agent: Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "curl_easy_perform() error: " << std::endl << curl_easy_strerror(res) << std::endl; return false; } else { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 200) { std::cerr << "HTTP Code error: " << http_code << std::endl; return false; } } curl_easy_cleanup(curl); curl_global_cleanup(); return true; } return false; } size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up) { for (int c = 0; c<size*nmemb; c++) { data += buf[c]; } return size*nmemb; }
21.315789
116
0.561317
HadesD
e48ccfe0b07eaeec5c4d1897b781cc2a32f7adfb
736
cpp
C++
solutions/beecrowd/2062/2062.cpp
deniscostadsc/playground
11fa8e2b708571940451f005e1f55af0b6e5764a
[ "MIT" ]
18
2015-01-22T04:08:51.000Z
2022-01-08T22:36:47.000Z
solutions/beecrowd/2062/2062.cpp
deniscostadsc/playground
11fa8e2b708571940451f005e1f55af0b6e5764a
[ "MIT" ]
4
2016-04-25T12:32:46.000Z
2021-06-15T18:01:30.000Z
solutions/beecrowd/2062/2062.cpp
deniscostadsc/playground
11fa8e2b708571940451f005e1f55af0b6e5764a
[ "MIT" ]
25
2015-03-02T06:21:51.000Z
2021-09-12T20:49:21.000Z
#include <cstdint> #include <iostream> #include <string> int main() { int16_t n; std::string word; while (std::cin >> n) { for (int16_t i = 0; i < n; i++) { if (i > 0) { std::cout << " "; } std::cin >> word; if (word.size() == 3) { if (word[0] == 'O' && word[1] == 'B') { std::cout << "OBI"; } else if (word[0] == 'U' && word[1] == 'R') { std::cout << "URI"; } else { std::cout << word; } } else { std::cout << word; } } std::cout << std::endl; } return 0; }
21.647059
62
0.315217
deniscostadsc
e491087200cacb15f13418bd088d298feac0ab03
2,611
cpp
C++
TG/bookcodes/ch3/uva11922.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
TG/bookcodes/ch3/uva11922.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
TG/bookcodes/ch3/uva11922.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa11922 Permutation Transformer // Rujia Liu #include<cstdio> #include<algorithm> #include<vector> using namespace std; struct Node { Node *ch[2]; int s; int flip; int v; int cmp(int k) const { int d = k - ch[0]->s; if(d == 1) return -1; return d <= 0 ? 0 : 1; } void maintain() { s = ch[0]->s + ch[1]->s + 1; } void pushdown() { if(flip) { flip = 0; swap(ch[0], ch[1]); ch[0]->flip = !ch[0]->flip; ch[1]->flip = !ch[1]->flip; } } }; Node *null = new Node(); void rotate(Node* &o, int d) { Node* k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o; o->maintain(); k->maintain(); o = k; } void splay(Node* &o, int k) { o->pushdown(); int d = o->cmp(k); if(d == 1) k -= o->ch[0]->s + 1; if(d != -1) { Node* p = o->ch[d]; p->pushdown(); int d2 = p->cmp(k); int k2 = (d2 == 0 ? k : k - p->ch[0]->s - 1); if(d2 != -1) { splay(p->ch[d2], k2); if(d == d2) rotate(o, d^1); else rotate(o->ch[d], d); } rotate(o, d^1); } } // 合并left和right。假定left的所有元素比right小。注意right可以是null,但left不可以 Node* merge(Node* left, Node* right) { splay(left, left->s); left->ch[1] = right; left->maintain(); return left; } // 把o的前k小结点放在left里,其他的放在right里。1<=k<=o->s。当k=o->s时,right=null void split(Node* o, int k, Node* &left, Node* &right) { splay(o, k); left = o; right = o->ch[1]; o->ch[1] = null; left->maintain(); } const int maxn = 100000 + 10; struct SplaySequence { int n; Node seq[maxn]; Node *root; Node* build(int sz) { if(!sz) return null; Node* L = build(sz/2); Node* o = &seq[++n]; o->v = n; // 节点编号 o->ch[0] = L; o->ch[1] = build(sz - sz/2 - 1); o->flip = o->s = 0; o->maintain(); return o; } void init(int sz) { n = 0; null->s = 0; root = build(sz); } }; vector<int> ans; void print(Node* o) { if(o != null) { o->pushdown(); print(o->ch[0]); ans.push_back(o->v); print(o->ch[1]); } } void debug(Node* o) { if(o != null) { o->pushdown(); debug(o->ch[0]); printf("%d ", o->v-1); debug(o->ch[1]); } } SplaySequence ss; int main() { int n, m; scanf("%d%d", &n, &m); ss.init(n+1); // 最前面有一个虚拟结点 while (m--) { int a, b; scanf("%d%d", &a, &b); Node *left, *mid, *right, *o; split(ss.root, a, left, o); // 如果没有虚拟结点,a将改成a-1,违反split的限制 split(o, b-a+1, mid, right); mid->flip ^= 1; ss.root = merge(merge(left, right), mid); } print(ss.root); for(int i = 1; i < ans.size(); i++) printf("%d\n", ans[i]-1); // 节点编号减1才是本题的元素值 return 0; }
18.784173
62
0.499809
Anyrainel
e491c6d21f80df9721ed2efce20317a514c9b3e2
6,639
cpp
C++
src/plugins/temperature/temperature_sensor_hal.cpp
fourkbomb/sensor-plugins
6f86a79e4b4e35cf85dede63686401408b9b6ff7
[ "Apache-2.0" ]
null
null
null
src/plugins/temperature/temperature_sensor_hal.cpp
fourkbomb/sensor-plugins
6f86a79e4b4e35cf85dede63686401408b9b6ff7
[ "Apache-2.0" ]
null
null
null
src/plugins/temperature/temperature_sensor_hal.cpp
fourkbomb/sensor-plugins
6f86a79e4b4e35cf85dede63686401408b9b6ff7
[ "Apache-2.0" ]
null
null
null
/* * temperature_sensor_hal * * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * 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 <fcntl.h> #include <sys/stat.h> #include <linux/input.h> #include <csensor_config.h> #include <temperature_sensor_hal.h> #include <sys/ioctl.h> using std::string; #define SENSOR_TYPE_TEMPERATURE "TEMPERATURE" #define ELEMENT_NAME "NAME" #define ELEMENT_VENDOR "VENDOR" #define ELEMENT_RAW_DATA_UNIT "RAW_DATA_UNIT" #define TEMP_INPUT_NAME "temperature_sensor" #define TEMP_IIO_ENABLE_NODE_NAME "temp_enable" #define TEMP_SENSORHUB_POLL_NODE_NAME "temp_poll_delay" #define INITIAL_TIME -1 temperature_sensor_hal::temperature_sensor_hal() : m_temperature(0) , m_node_handle(-1) , m_polling_interval(POLL_1HZ_MS) , m_fired_time(INITIAL_TIME) { const string sensorhub_interval_node_name = TEMP_SENSORHUB_POLL_NODE_NAME; node_info_query query; node_info info; if (!find_model_id(SENSOR_TYPE_TEMPERATURE, m_model_id)) { ERR("Failed to find model id"); throw ENXIO; } query.sensorhub_controlled = is_sensorhub_controlled(sensorhub_interval_node_name); query.sensor_type = SENSOR_TYPE_TEMPERATURE; query.key = TEMP_INPUT_NAME; query.iio_enable_node_name = TEMP_IIO_ENABLE_NODE_NAME; query.sensorhub_interval_node_name = sensorhub_interval_node_name; if (!get_node_info(query, info)) { ERR("Failed to get node info"); throw ENXIO; } show_node_info(info); m_data_node = info.data_node_path; m_enable_node = info.enable_node_path; m_interval_node = info.interval_node_path; csensor_config &config = csensor_config::get_instance(); if (!config.get(SENSOR_TYPE_TEMPERATURE, m_model_id, ELEMENT_VENDOR, m_vendor)) { ERR("[VENDOR] is empty\n"); throw ENXIO; } if (!config.get(SENSOR_TYPE_TEMPERATURE, m_model_id, ELEMENT_NAME, m_chip_name)) { ERR("[NAME] is empty\n"); throw ENXIO; } double raw_data_unit; if (!config.get(SENSOR_TYPE_TEMPERATURE, m_model_id, ELEMENT_RAW_DATA_UNIT, raw_data_unit)) { ERR("[RAW_DATA_UNIT] is empty\n"); throw ENXIO; } m_raw_data_unit = (float)(raw_data_unit); if ((m_node_handle = open(m_data_node.c_str(),O_RDWR)) < 0) { ERR("Failed to open handle(%d)", m_node_handle); throw ENXIO; } int clockId = CLOCK_MONOTONIC; if (ioctl(m_node_handle, EVIOCSCLOCKID, &clockId) != 0) ERR("Fail to set monotonic timestamp for %s", m_data_node.c_str()); INFO("m_vendor = %s", m_vendor.c_str()); INFO("m_chip_name = %s", m_chip_name.c_str()); INFO("m_raw_data_unit = %f\n", m_raw_data_unit); INFO("temperature_sensor_hal is created!\n"); } temperature_sensor_hal::~temperature_sensor_hal() { close(m_node_handle); m_node_handle = -1; INFO("temperature_sensor_hal is destroyed!\n"); } string temperature_sensor_hal::get_model_id(void) { return m_model_id; } sensor_hal_type_t temperature_sensor_hal::get_type(void) { return SENSOR_HAL_TYPE_TEMPERATURE; } bool temperature_sensor_hal::enable(void) { AUTOLOCK(m_mutex); set_enable_node(m_enable_node, m_sensorhub_controlled, true, SENSORHUB_TEMPERATURE_HUMIDITY_ENABLE_BIT); set_interval(m_polling_interval); m_fired_time = 0; INFO("Temperature sensor real starting"); return true; } bool temperature_sensor_hal::disable(void) { AUTOLOCK(m_mutex); set_enable_node(m_enable_node, m_sensorhub_controlled, false, SENSORHUB_TEMPERATURE_HUMIDITY_ENABLE_BIT); INFO("Temperature sensor real stopping"); return true; } bool temperature_sensor_hal::set_interval(unsigned long val) { unsigned long long polling_interval_ns; AUTOLOCK(m_mutex); polling_interval_ns = ((unsigned long long)(val) * 1000llu * 1000llu); if (!set_node_value(m_interval_node, polling_interval_ns)) { ERR("Failed to set polling node: %s\n", m_interval_node.c_str()); return false; } INFO("Interval is changed from %dms to %dms]", m_polling_interval, val); m_polling_interval = val; return true; } bool temperature_sensor_hal::update_value(void) { int temperature_raw = 0; bool temperature = false; int read_input_cnt = 0; const int INPUT_MAX_BEFORE_SYN = 10; unsigned long long fired_time = 0; bool syn = false; struct input_event temperature_event; DBG("temperature event detection!"); while ((syn == false) && (read_input_cnt < INPUT_MAX_BEFORE_SYN)) { int len = read(m_node_handle, &temperature_event, sizeof(temperature_event)); if (len != sizeof(temperature_event)) { ERR("temperature_file read fail, read_len = %d\n",len); return false; } ++read_input_cnt; if (temperature_event.type == EV_REL) { switch (temperature_event.code) { case REL_HWHEEL: temperature_raw = (int)temperature_event.value; temperature = true; break; default: ERR("temperature_event event[type = %d, code = %d] is unknown.", temperature_event.type, temperature_event.code); return false; break; } } else if (temperature_event.type == EV_SYN) { syn = true; fired_time = sensor_hal_base::get_timestamp(&temperature_event.time); } else { ERR("temperature_event event[type = %d, code = %d] is unknown.", temperature_event.type, temperature_event.code); return false; } } if (syn == false) { ERR("EV_SYN didn't come until %d inputs had come", read_input_cnt); return false; } AUTOLOCK(m_value_mutex); if (temperature) m_temperature = temperature_raw; m_fired_time = fired_time; DBG("m_temperature = %d, time = %lluus", m_temperature, m_fired_time); return true; } bool temperature_sensor_hal::is_data_ready(void) { bool ret; ret = update_value(); return ret; } int temperature_sensor_hal::get_sensor_data(sensor_data_t &data) { AUTOLOCK(m_value_mutex); data.accuracy = SENSOR_ACCURACY_GOOD; data.timestamp = m_fired_time ; data.value_count = 1; data.values[0] = (float) m_temperature; return 0; } bool temperature_sensor_hal::get_properties(sensor_properties_s &properties) { properties.name = m_chip_name; properties.vendor = m_vendor; properties.min_range = -45; properties.max_range = 130; properties.min_interval = 1; properties.resolution = 1; properties.fifo_count = 0; properties.max_batch_count = 0; return true; }
25.933594
118
0.749812
fourkbomb
e4942b3a1d7612af3a500a2a2ab8bd2993208287
1,134
cpp
C++
Test1/codes/choiking10.cpp
koohanmo/JudgeForTA
a894042448c761c333af74c529d99e2e84e2922f
[ "MIT" ]
1
2017-05-23T06:57:51.000Z
2017-05-23T06:57:51.000Z
Test1/codes/choiking10.cpp
koohanmo/JudgeForTA
a894042448c761c333af74c529d99e2e84e2922f
[ "MIT" ]
null
null
null
Test1/codes/choiking10.cpp
koohanmo/JudgeForTA
a894042448c761c333af74c529d99e2e84e2922f
[ "MIT" ]
null
null
null
#include <cstdio> #include <algorithm> #include <vector> #include <bitset> #include <map> using std::vector; long long count_num(vector<int>& d, int depth, int idx, long long val, long long limit) { if (idx == d.size() || val > limit) return 0; long long ret = 0; for (int i = idx; i < d.size(); i++) { if (depth & 1) ret += limit / (d[i] * val); else ret -= limit / (d[i] * val); ret += count_num(d, depth + 1, i + 1, d[i] * val, limit); } return ret; } int main(void) { int T; scanf("%d", &T); for (int tc = 1; tc <= T; tc++) { long long a, b, n; scanf("%lld%lld%lld", &a, &b, &n); std::vector<int> count; std::bitset<50010> c; long long tmp = n; for (long long i = 2; i*i <= n; i++) { if (!c[i]) { if(n%i==0) count.push_back(i); for (long long j = i *i; j*j <= n; j += i) { c[j] = 1; } while (tmp != 1 && tmp%i == 0) tmp /= i; if (tmp == 1) break; } } if (tmp != 1) count.push_back(tmp); long long ans = count_num(count, 1, 0, 1, b) - count_num(count, 1, 0, 1, a - 1); printf("Case #%d: %lld\n", tc, b - a +1 - ans); } }
27.658537
90
0.502646
koohanmo
e49583528ca6416bc82d041d901cd0db574352c3
7,964
cpp
C++
tools/zip/src/zip_reader.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
tools/zip/src/zip_reader.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
tools/zip/src/zip_reader.cpp
openharmony-sig-ci/aafwk_standard
5ef3550de797241d46e47c5f446eba5428d180f1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "zip_reader.h" #include <stdio.h> #include <utility> #include <unistd.h> #include <time.h> #include "zip_utils.h" #include "string_ex.h" #include "checked_cast.h" #include "zip_internal.h" #include "contrib/minizip/unzip.h" #include "zip_utils.h" namespace OHOS { namespace AAFwk { namespace LIBZIP { // TODO(satorux): The implementation assumes that file names in zip files // are encoded in UTF-8. This is true for zip files created by Zip() // function in zip.h, but not true for user-supplied random zip files. ZipReader::EntryInfo::EntryInfo(const std::string &fileNameInZip, const unz_file_info &rawFileInfo) : filePath_(FilePath::FromUTF8Unsafe(fileNameInZip)), isDirectory_(false), isUnsafe_(false), isEncrypted_(false) { originalSize_ = rawFileInfo.uncompressed_size; // Directory entries in zip files end with "/". isDirectory_ = EndsWith(fileNameInZip, "/"); // Check the file name here for directory traversal issues. isUnsafe_ = filePath_.ReferencesParent(); // We also consider that the file name is unsafe, if it's absolute. // On Windows, IsAbsolute() returns false for paths starting with "/". if (filePath_.IsAbsolute() || StartsWith(fileNameInZip, "/")) { isUnsafe_ = false; } // Whether the file is encrypted is bit 0 of the flag. isEncrypted_ = rawFileInfo.flag & 1; // Construct the last modified time. The timezone info is not present in // zip files, so we construct the time as local time. lastModified_ = *GetCurrentSystemTime(); } ZipReader::ZipReader() { Reset(); } ZipReader::~ZipReader() { Close(); } bool ZipReader::Open(FilePath &zipFilePath) { if (zipFile_ != nullptr) { return false; } // Use of "Unsafe" function does not look good, but there is no way to do // this safely on Linux. See file_util.h for details. // zipFile_ = internal::OpenForUnzipping(zipFilePath.AsUTF8Unsafe()); std::string zipfile = zipFilePath.Value(); zipFile_ = OpenForUnzipping(zipfile); if (zipFile_ == nullptr) { return false; } return OpenInternal(); } bool ZipReader::OpenFromPlatformFile(PlatformFile zipFd) { if (zipFile_ != nullptr) { return false; } zipFile_ = OpenFdForUnzipping(zipFd); if (!zipFile_) { return false; } return OpenInternal(); } bool ZipReader::OpenFromString(const std::string &data) { zipFile_ = PrepareMemoryForUnzipping(data); if (!zipFile_) { return false; } return OpenInternal(); } void ZipReader::Close() { if (zipFile_) { unzClose(zipFile_); } Reset(); } bool ZipReader::HasMore() { return !reachedEnd_; } bool ZipReader::AdvanceToNextEntry() { if (zipFile_ == nullptr) { return false; } // Should not go further if we already reached the end. if (reachedEnd_) { return false; } unz_file_pos position = {}; if (unzGetFilePos(zipFile_, &position) != UNZ_OK) { return false; } const int currentEntryIndex = position.num_of_file; // If we are currently at the last entry, then the next position is the // end of the zip file, so mark that we reached the end. if (currentEntryIndex + 1 == numEntries_) { reachedEnd_ = true; } else { if (unzGoToNextFile(zipFile_) != UNZ_OK) { return false; } } currentEntryInfo_.reset(); return true; } bool ZipReader::OpenCurrentEntryInZip() { if (zipFile_ == nullptr) { return false; } unz_file_info raw_file_info = {}; char raw_file_name_in_zip[kZipMaxPath] = {}; const int result = unzGetCurrentFileInfo(zipFile_, &raw_file_info, raw_file_name_in_zip, sizeof(raw_file_name_in_zip) - 1, NULL, // extraField. 0, // extraFieldBufferSize. NULL, // szComment. 0); // commentBufferSize. if (result != UNZ_OK) { return false; } if (raw_file_name_in_zip[0] == '\0') { return false; } currentEntryInfo_.reset(new EntryInfo(raw_file_name_in_zip, raw_file_info)); return true; } bool ZipReader::ExtractCurrentEntry(WriterDelegate *delegate, uint64_t numBytesToExtract) const { if (zipFile_ == nullptr) { return false; } const int openResult = unzOpenCurrentFile(zipFile_); if (openResult != UNZ_OK) { return false; } if (!delegate->PrepareOutput()) { return false; } std::unique_ptr<char[]> buf(new char[kZipBufSize]); uint64_t remainingCapacity = numBytesToExtract; bool entirefileextracted = false; while (remainingCapacity > 0) { const int numBytesRead = unzReadCurrentFile(zipFile_, buf.get(), kZipBufSize); if (numBytesRead == 0) { entirefileextracted = true; break; } else if (numBytesRead < 0) { // If numBytesRead < 0, then it's a specific UNZ_* error code. break; } else if (numBytesRead > 0) { uint64_t numBytesToWrite = std::min<uint64_t>(remainingCapacity, checked_cast<uint64_t>(numBytesRead)); if (!delegate->WriteBytes(buf.get(), numBytesToWrite)) { break; } if (remainingCapacity == checked_cast<uint64_t>(numBytesRead)) { // Ensures function returns true if the entire file has been read. entirefileextracted = (unzReadCurrentFile(zipFile_, buf.get(), 1) == 0); } if (remainingCapacity >= numBytesToWrite) { remainingCapacity -= numBytesToWrite; } } } unzCloseCurrentFile(zipFile_); // closeFile delegate->SetTimeModified(GetCurrentSystemTime()); return entirefileextracted; } bool ZipReader::OpenInternal() { if (zipFile_ == nullptr) { return false; } unz_global_info zipInfo = {}; // Zero-clear. if (unzGetGlobalInfo(zipFile_, &zipInfo) != UNZ_OK) { return false; } numEntries_ = zipInfo.number_entry; if (numEntries_ < 0) { return false; } // We are already at the end if the zip file is empty. reachedEnd_ = (numEntries_ == 0); return true; } void ZipReader::Reset() { zipFile_ = NULL; numEntries_ = 0; reachedEnd_ = false; currentEntryInfo_.reset(); } // FilePathWriterDelegate FilePathWriterDelegate::FilePathWriterDelegate(const FilePath &outputFilePath) : outputFilePath_(outputFilePath) {} FilePathWriterDelegate::~FilePathWriterDelegate() {} bool FilePathWriterDelegate::PrepareOutput() { // We can't rely on parent directory entries being specified in the // zip, so we make sure they are created. if (!FilePath::CreateDirectory(outputFilePath_.DirName())) { return false; } file_ = fopen(outputFilePath_.Value().c_str(), "wb"); return FilePath::PathIsValid(outputFilePath_); } bool FilePathWriterDelegate::WriteBytes(const char *data, int numBytes) { if (file_ == nullptr || numBytes <= 0) { return false; } int writebytes = fwrite(data, 1, numBytes, file_); return numBytes == writebytes; } void FilePathWriterDelegate::SetTimeModified(const struct tm *time) { fclose(file_); file_ = nullptr; } } // namespace LIBZIP } // namespace AAFwk } // namespace OHOS
27.462069
116
0.653566
openharmony-sig-ci
e49626e1247bf52cd5bbbe5ed53a3feebda2b654
178
cpp
C++
examples/valid.cpp
dtrugman/Kuvasz
3391832f017cb4946c6d135bb9382a0d446eadc1
[ "Apache-2.0" ]
2
2017-05-20T20:59:36.000Z
2021-01-15T11:01:53.000Z
examples/valid.cpp
dtrugman/Bulldog
3391832f017cb4946c6d135bb9382a0d446eadc1
[ "Apache-2.0" ]
null
null
null
examples/valid.cpp
dtrugman/Bulldog
3391832f017cb4946c6d135bb9382a0d446eadc1
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <unistd.h> using namespace std; int main(int argc, char ** argv) { while(true) { cout << "HI" << endl; sleep(1000); } }
13.692308
32
0.539326
dtrugman
e498a6456781de9b1d63f50dc556770d91a0d11e
4,957
cpp
C++
device/services/profiler_service/test/unittest/trace_file_reader_test.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/services/profiler_service/test/unittest/trace_file_reader_test.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/services/profiler_service/test/unittest/trace_file_reader_test.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
1
2021-09-13T11:17:44.000Z
2021-09-13T11:17:44.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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. */ #define LOG_TAG "TraceFileReaderTest" #include <fstream> #include <hwext/gtest-ext.h> #include <hwext/gtest-tag.h> #include <memory> #include <unistd.h> #include <vector> #include "common_types.pb.h" #include "logging.h" #include "trace_file_reader.h" #include "trace_file_writer.h" using namespace testing::ext; namespace { #if defined(__i386__) || defined(__x86_64__) const std::string DEFAULT_TEST_PATH("./"); #else const std::string DEFAULT_TEST_PATH("/data/local/tmp/"); #endif class TraceFileReaderTest : public ::testing::Test { protected: std::string path = "trace.bin"; static void SetUpTestCase() {} static void TearDownTestCase() { std::string name = "325.ht"; std::string path = DEFAULT_TEST_PATH + name; if (access(path.c_str(), F_OK) == 0) { system(std::string("rm " + path).c_str()); } } void SetUp() override {} void TearDown() override {} }; /** * @tc.name: server * @tc.desc: write read. * @tc.type: FUNC */ HWTEST_F(TraceFileReaderTest, WriteRead, TestSize.Level1) { std::string path = "trace-write-msg.bin"; auto writer = std::make_shared<TraceFileWriter>(path); ASSERT_NE(writer, nullptr); constexpr int n = 100; for (int i = 1; i <= n; i++) { ProfilerPluginData pluginData{}; pluginData.set_name("test_name"); pluginData.set_status(i); pluginData.set_data("Hello, World!"); long bytes = writer->Write(pluginData); EXPECT_EQ(bytes, sizeof(uint32_t) + pluginData.ByteSizeLong()); HILOG_INFO(LOG_CORE, "[%d/%d] write %ld bytes to %s.", i, n, bytes, path.c_str()); } writer.reset(); // make sure write done! auto reader = std::make_shared<TraceFileReader>(); ASSERT_NE(reader, nullptr); ASSERT_TRUE(reader->Open(path)); for (int i = 1; i <= n; i++) { ProfilerPluginData data{}; long bytes = reader->Read(data); HILOG_INFO(LOG_CORE, "data = {%s, %d, %s}", data.name().c_str(), data.status(), data.data().c_str()); HILOG_INFO(LOG_CORE, "read %ld bytes from %s", bytes, path.c_str()); } } /** * @tc.name: server * @tc.desc: write read break. * @tc.type: FUNC */ HWTEST_F(TraceFileReaderTest, WriteReadBreak, TestSize.Level1) { std::string path = "trace-write-msg.bin"; auto writer = std::make_shared<TraceFileWriter>(path); ASSERT_NE(writer, nullptr); constexpr int n = 100; for (int i = 1; i <= n; i++) { ProfilerPluginData pluginData{}; pluginData.set_name("test_name"); pluginData.set_status(i); pluginData.set_data("Hello, World!"); long bytes = writer->Write(pluginData); EXPECT_EQ(bytes, sizeof(uint32_t) + pluginData.ByteSizeLong()); HILOG_INFO(LOG_CORE, "[%d/%d] write %ld bytes to %s.", i, n, bytes, path.c_str()); } writer.reset(); // make sure write done! auto reader = std::make_shared<TraceFileReader>(); ASSERT_NE(reader, nullptr); ASSERT_TRUE(reader->Open(path)); long bytes = 0; do { ProfilerPluginData data{}; bytes = reader->Read(data); HILOG_INFO(LOG_CORE, "data = {%s, %d, %s}", data.name().c_str(), data.status(), data.data().c_str()); HILOG_INFO(LOG_CORE, "read %ld bytes from %s", bytes, path.c_str()); } while (bytes > 0); } /** * @tc.name: server * @tc.desc: read. * @tc.type: FUNC */ HWTEST_F(TraceFileReaderTest, Read, TestSize.Level1) { std::string name = "325.ht"; std::string path = DEFAULT_TEST_PATH + name; if (access(path.c_str(), F_OK) != 0) { std::unique_ptr<FILE, decltype(fclose)*> fptr(fopen(path.c_str(), "wb+"), fclose); TraceFileHeader header = {}; // default header data fwrite(&header, sizeof(char), sizeof(header), fptr.get()); } auto reader = std::make_shared<TraceFileReader>(); ASSERT_NE(reader, nullptr); ASSERT_TRUE(reader->Open(path)); long bytes = 0; do { ProfilerPluginData data{}; bytes = reader->Read(data); fprintf(stderr, "data = [%s, %d, ...%zu], len = %zu, bytes = %ld\n", data.name().c_str(), data.status(), data.data().size(), data.ByteSizeLong(), bytes); } while (bytes > 0); if (access(path.c_str(), F_OK) == 0) { system(std::string("rm " + path).c_str()); } } } // namespace
30.98125
112
0.628404
openharmony-gitee-mirror
e49b967061c29c9f18ae55eccce5d82fefedbbce
852
cpp
C++
stone-game/stone-game.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
2
2022-01-02T19:15:00.000Z
2022-01-05T21:12:24.000Z
stone-game/stone-game.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
null
null
null
stone-game/stone-game.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
1
2022-03-11T17:11:07.000Z
2022-03-11T17:11:07.000Z
class Solution { public: int helper(vector<int>& piles,int left,int right,vector<vector<int>>&dp){ if(left>=right) return 0; if(dp[left][right]!=-1) return dp[left][right]; int choosel=piles[left]+min(helper(piles,left+2,right,dp),helper(piles,left,right-1,dp)); int chooser=piles[right]+min(helper(piles,left+1,right,dp),helper(piles,left,right-2,dp)); return dp[left][right]=max(choosel,chooser); } bool stoneGame(vector<int>& piles) { if(piles.size()==0) return false; int sumval=0; vector<vector<int>>dp(piles.size()+1,vector<int>(piles.size()+1,-1)); for (int i=0;i<piles.size();i++){ sumval+=piles[i]; } return helper(piles,0, piles.size()-1,dp)>sumval/2?true:false; } };
34.08
98
0.561033
Ananyaas
e49e46fc13a2ff9b2d8116f2c55ee3c73f579f8a
1,981
cc
C++
sdk/lib/fdio/fd.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
sdk/lib/fdio/fd.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
sdk/lib/fdio/fd.cc
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2019 The Fuchsia 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 <lib/fdio/fdio.h> #include <variant> #include <fbl/auto_lock.h> #include "fdio_unistd.h" #include "internal.h" __EXPORT zx_status_t fdio_fd_create(zx_handle_t handle, int* fd_out) { zx::status io = fdio::create(zx::handle(handle)); if (io.is_error()) { return io.status_value(); } std::optional fd = bind_to_fd(io.value()); if (fd.has_value()) { *fd_out = fd.value(); return ZX_OK; } return ZX_ERR_BAD_STATE; } __EXPORT zx_status_t fdio_cwd_clone(zx_handle_t* out_handle) { fdio_ptr cwd = []() { fbl::AutoLock lock(&fdio_lock); return fdio_cwd_handle.get(); }(); return cwd->clone(out_handle); } __EXPORT zx_status_t fdio_fd_clone(int fd, zx_handle_t* out_handle) { fdio_ptr io = fd_to_io(fd); if (io == nullptr) { return ZX_ERR_INVALID_ARGS; } // TODO(fxbug.dev/30920): implement/honor close-on-exec flag return io->clone(out_handle); } __EXPORT zx_status_t fdio_fd_transfer(int fd, zx_handle_t* out_handle) { fdio_ptr io = unbind_from_fd(fd); if (io == nullptr) { return ZX_ERR_INVALID_ARGS; } std::variant reference = GetLastReference(std::move(io)); auto* ptr = std::get_if<fdio::last_reference>(&reference); if (ptr) { return ptr->unwrap(out_handle); } return ZX_ERR_UNAVAILABLE; } __EXPORT zx_status_t fdio_fd_transfer_or_clone(int fd, zx_handle_t* out_handle) { fdio_ptr io = unbind_from_fd(fd); if (io == nullptr) { return ZX_ERR_INVALID_ARGS; } return std::visit(fdio::overloaded{[out_handle](fdio::last_reference reference) { return reference.unwrap(out_handle); }, [out_handle](fdio_ptr ptr) { return ptr->clone(out_handle); }}, GetLastReference(std::move(io))); }
27.136986
100
0.660273
allansrc
e49f1a80f8e51fd5090b98340f26e99ab5e19616
1,641
cpp
C++
test/test_params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
7
2019-12-03T17:45:31.000Z
2021-04-21T15:46:41.000Z
test/test_params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
6
2020-09-28T06:57:23.000Z
2020-10-22T05:41:12.000Z
test/test_params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
1
2020-10-11T08:59:41.000Z
2020-10-11T08:59:41.000Z
#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <params.hpp> #include <algorithm> TEST_CASE ( "Test Params object", "[params]" ) { SECTION ("Test Params object MagP64") { long int max_iters = 100; double damping = 0.1; double epsil = 0.2; double beta = 0.3; double r = 0.4; double tan_gamma = 3.14; std :: string accuracy1 = "none_1"; std :: string accuracy2 = "none_2"; Params < MagP64 > p(max_iters, damping, epsil, beta, r, tan_gamma, accuracy1, accuracy2); REQUIRE ( p.max_iters == max_iters ); REQUIRE ( p.damping == damping ); REQUIRE ( p.epsil == epsil ); REQUIRE ( p.beta == beta ); REQUIRE ( p.r == r ); REQUIRE ( p.tan_gamma.mag == tan_gamma ); REQUIRE ( p.accuracy1 == accuracy1 ); REQUIRE ( p.accuracy2 == accuracy2 ); } SECTION ("Test Params object MagT64") { long int max_iters = 100; double damping = 0.1; double epsil = 0.2; double beta = 0.3; double r = 0.4; double tan_gamma = 3.14; std :: string accuracy1 = "none_1"; std :: string accuracy2 = "none_2"; Params < MagT64 > p(max_iters, damping, epsil, beta, r, tan_gamma, accuracy1, accuracy2); REQUIRE ( p.max_iters == max_iters ); REQUIRE ( p.damping == damping ); REQUIRE ( p.epsil == epsil ); REQUIRE ( p.beta == beta ); REQUIRE ( p.r == r ); REQUIRE ( p.tan_gamma.mag == tan_gamma ); REQUIRE ( p.accuracy1 == accuracy1 ); REQUIRE ( p.accuracy2 == accuracy2 ); } }
25.640625
93
0.551493
DanielLenz
e4a4e4efe1409bfc1aaf282a67b7a3b0b915f0cf
2,439
hpp
C++
armadillo_matrix/include/armadillo_bits/op_stddev_meat.hpp
Lauradejong92/wire-grad
0bfd3fb42df363f43eb89f35c2f0769fb805f6cd
[ "BSD-2-Clause" ]
1
2022-02-02T15:47:24.000Z
2022-02-02T15:47:24.000Z
armadillo_matrix/include/armadillo_bits/op_stddev_meat.hpp
Lauradejong92/wire-grad
0bfd3fb42df363f43eb89f35c2f0769fb805f6cd
[ "BSD-2-Clause" ]
null
null
null
armadillo_matrix/include/armadillo_bits/op_stddev_meat.hpp
Lauradejong92/wire-grad
0bfd3fb42df363f43eb89f35c2f0769fb805f6cd
[ "BSD-2-Clause" ]
2
2019-02-28T17:36:19.000Z
2021-01-24T14:04:18.000Z
// Copyright (C) 2009-2011 NICTA (www.nicta.com.au) // Copyright (C) 2009-2011 Conrad Sanderson // // This file is part of the Armadillo C++ library. // It is provided without any warranty of fitness // for any purpose. You can redistribute this file // and/or modify it under the terms of the GNU // Lesser General Public License (LGPL) as published // by the Free Software Foundation, either version 3 // of the License or (at your option) any later version. // (see http://www.opensource.org/licenses for more info) //! \addtogroup op_stddev //! @{ //! \brief //! For each row or for each column, find the standard deviation. //! The result is stored in a dense matrix that has either one column or one row. //! The dimension for which the standard deviations are found is set via the stddev() function. template<typename T1> inline void op_stddev::apply(Mat<typename T1::pod_type>& out, const mtOp<typename T1::pod_type, T1, op_stddev>& in) { arma_extra_debug_sigprint(); typedef typename T1::elem_type in_eT; typedef typename T1::pod_type out_eT; const unwrap_check_mixed<T1> tmp(in.m, out); const Mat<in_eT>& X = tmp.M; const uword norm_type = in.aux_uword_a; const uword dim = in.aux_uword_b; arma_debug_check( (norm_type > 1), "stddev(): incorrect usage. norm_type must be 0 or 1"); arma_debug_check( (dim > 1), "stddev(): incorrect usage. dim must be 0 or 1" ); const uword X_n_rows = X.n_rows; const uword X_n_cols = X.n_cols; if(dim == 0) { arma_extra_debug_print("op_stddev::apply(), dim = 0"); arma_debug_check( (X_n_rows == 0), "stddev(): given object has zero rows" ); out.set_size(1, X_n_cols); out_eT* out_mem = out.memptr(); for(uword col=0; col<X_n_cols; ++col) { out_mem[col] = std::sqrt( op_var::direct_var( X.colptr(col), X_n_rows, norm_type ) ); } } else if(dim == 1) { arma_extra_debug_print("op_stddev::apply(), dim = 1"); arma_debug_check( (X_n_cols == 0), "stddev(): given object has zero columns" ); out.set_size(X_n_rows, 1); podarray<in_eT> tmp(X_n_cols); in_eT* tmp_mem = tmp.memptr(); out_eT* out_mem = out.memptr(); for(uword row=0; row<X_n_rows; ++row) { tmp.copy_row(X, row); out_mem[row] = std::sqrt( op_var::direct_var( tmp_mem, X_n_cols, norm_type) ); } } } //! @}
28.360465
103
0.647396
Lauradejong92
e4b5590f6067302d1f70dee9c279242b0f8e7b41
4,926
cpp
C++
stats.cpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
stats.cpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
stats.cpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
/** * \file stats.cpp * \brief Implementation of service IO functions, modified code from libtrap service ifc and trap_stats * \author Jiri Havranek <havranek@cesnet.cz> * \date 2021 */ /* * Copyright (C) 2021 CESNET * * LICENSE TERMS * * 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 Company nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * ALTERNATIVELY, provided that this notice is retained in full, this * product may be distributed under the terms of the GNU General Public * License (GPL) version 2 or later, in which case the provisions * of the GPL apply INSTEAD OF those given above. * * This software is provided ``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 company or contributors be liable for any * direct, indirect, incidental, special, exemplary, or consequential * damages (including, but not limited to, procurement of substitute * goods or services; loss of use, data, or profits; or business * interruption) however caused and on any theory of liability, whether * in contract, strict liability, or tort (including negligence or * otherwise) arising in any way out of the use of this software, even * if advised of the possibility of such damage. * */ #include <config.h> #include <string> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/un.h> #include <sys/socket.h> #include "stats.hpp" namespace ipxp { int connect_to_exporter(const char *path) { int fd; struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path) - 1, "%s", path); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd != -1) { if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) { perror("unable to connect"); close(fd); return -1; } } return fd; } int create_stats_sock(const char *path) { int fd; struct sockaddr_un addr; addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path) - 1, "%s", path); unlink(addr.sun_path); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd != -1) { if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) { perror("unable to bind socket"); close(fd); return -1; } if (listen(fd, 1) == -1) { perror("unable to listen on socket"); close(fd); return -1; } if (chmod(addr.sun_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) == -1) { perror("unable to set access rights"); close(fd); return -1; } } return fd; } int recv_data(int fd, uint32_t size, void *data) { size_t num_of_timeouts = 0; size_t total_received = 0; ssize_t last_received = 0; while (total_received < size) { last_received = recv(fd, (uint8_t *) data + total_received, size - total_received, MSG_DONTWAIT); if (last_received == 0) { return -1; } else if (last_received == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { num_of_timeouts++; if (num_of_timeouts > SERVICE_WAIT_MAX_TRY) { return -1; } else { usleep(SERVICE_WAIT_BEFORE_TIMEOUT); continue; } } return -1; } total_received += last_received; } return 0; } int send_data(int fd, uint32_t size, void *data) { size_t num_of_timeouts = 0; size_t total_sent = 0; ssize_t last_sent = 0; while (total_sent < size) { last_sent = send(fd, (uint8_t *) data + total_sent, size - total_sent, MSG_DONTWAIT); if (last_sent == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { num_of_timeouts++; if (num_of_timeouts > SERVICE_WAIT_MAX_TRY) { return -1; } else { usleep(SERVICE_WAIT_BEFORE_TIMEOUT); continue; } } return -1; } total_sent += last_sent; } return 0; } std::string create_sockpath(const char *id) { return DEFAULTSOCKETDIR "/ipfixprobe_" + std::string(id) + ".sock"; } }
29.674699
103
0.638043
CESNET
e4b6ffe887a483f59e891ac7502eba6aaa2aa732
293
cpp
C++
Source/UnitTest++/CurrentTest.cpp
rorydriscoll/RayTracer
772b5d47c0d181c6fe49728aabc8e0a949f285e1
[ "CC0-1.0" ]
124
2018-06-28T16:09:09.000Z
2022-02-23T16:20:26.000Z
Source/UnitTest++/CurrentTest.cpp
rorydriscoll/RayTracer
772b5d47c0d181c6fe49728aabc8e0a949f285e1
[ "CC0-1.0" ]
null
null
null
Source/UnitTest++/CurrentTest.cpp
rorydriscoll/RayTracer
772b5d47c0d181c6fe49728aabc8e0a949f285e1
[ "CC0-1.0" ]
9
2018-06-28T17:10:42.000Z
2021-08-09T08:42:41.000Z
#include "CurrentTest.h" namespace UnitTest { TestResults*& CurrentTest::Results() { static TestResults* testResults = nullptr; return testResults; } const TestDetails*& CurrentTest::Details() { static const TestDetails* testDetails = nullptr; return testDetails; } }
16.277778
50
0.709898
rorydriscoll
e4b7fd1f6fa7af8c113a3f3c7393b1746d53ae76
642
cpp
C++
IL2CPP/Il2CppOutputProject/IL2CPP/libil2cpp/os/c-api/Console.cpp
dngoins/AutographTheWorld-MR
24e567c8030b73a6942e25b36b7370667c649b90
[ "MIT" ]
16
2018-10-13T12:29:06.000Z
2022-02-25T14:56:47.000Z
IL2CPP/Il2CppOutputProject/IL2CPP/libil2cpp/os/c-api/Console.cpp
dngoins/AutographTheWorld-MR
24e567c8030b73a6942e25b36b7370667c649b90
[ "MIT" ]
3
2018-12-27T22:46:43.000Z
2019-03-19T12:28:37.000Z
IL2CPP/Il2CppOutputProject/IL2CPP/libil2cpp/os/c-api/Console.cpp
dngoins/AutographTheWorld-MR
24e567c8030b73a6942e25b36b7370667c649b90
[ "MIT" ]
4
2019-05-02T02:13:54.000Z
2021-12-16T16:03:26.000Z
#include "os/Console.h" #include "os/c-api/Console-c-api.h" extern "C" { int32_t UnityPalConsoleInternalKeyAvailable(int32_t ms_timeout) { return il2cpp::os::Console::InternalKeyAvailable(ms_timeout); } int32_t UnityPalConsoleSetBreak(int32_t wantBreak) { return il2cpp::os::Console::SetBreak(wantBreak); } int32_t UnityPalConsoleSetEcho(int32_t wantEcho) { return il2cpp::os::Console::SetEcho(wantEcho); } int32_t UnityPalConsoleTtySetup(const char* keypadXmit, const char* teardown, uint8_t* control_characters, int32_t** size) { return il2cpp::os::Console::TtySetup(keypadXmit, teardown, control_characters, size); } }
24.692308
122
0.76947
dngoins
e4b87ed8ee7d89729b74fa8848c9bef039bac809
686
hpp
C++
BlueNoise/src/Polyomino/Tromino.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
BlueNoise/src/Polyomino/Tromino.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
BlueNoise/src/Polyomino/Tromino.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* Tromino.hpp Li-Yi Wei 11/11/2007 */ #ifndef _TROMINO_HPP #define _TROMINO_HPP #include "Polyomino.hpp" class Tromino : public Polyomino { public: Tromino(void); Tromino(const Int2 & center, const Orientation orientation, const Reflection reflection); Tromino(const Int2 & center, const Orientation orientation, const Reflection reflection, const Flt2 & sample_offset); virtual ~Tromino(void) = 0; Tromino * Clone(void) const; virtual int NumSubdivisionRules(void) const; virtual int Subdivide(vector<Polyomino *> & children, const int which_rule) const; virtual void GetCells(vector<Int2> & cells) const; protected: }; #endif
20.176471
121
0.714286
1iyiwei
e4becb7165e263070ca7bd23c010492b2ee0ee94
5,454
cpp
C++
gui/geometries/planegeometry.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
6
2021-11-12T15:03:53.000Z
2022-01-28T18:30:33.000Z
gui/geometries/planegeometry.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
null
null
null
gui/geometries/planegeometry.cpp
goossens/ObjectTalk
ca1d4f558b5ad2459b376102744d52c6283ec108
[ "MIT" ]
null
null
null
// ObjectTalk Scripting Language // Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved. // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. // // Include files // #include "ot/function.h" #include "planegeometry.h" // // OtPlaneGeometryClass::~OtPlaneGeometryClass // OtPlaneGeometryClass::~OtPlaneGeometryClass() { if (heightmap) { heightmap->detach(heightmapID); } if (noisemap) { noisemap->detach(noisemapID); } } // // OtPlaneGeometryClass::init // OtObject OtPlaneGeometryClass::init(size_t count, OtObject* parameters) { // set attributes switch (count) { case 4: heightSegments = parameters[3]->operator int(); case 3: widthSegments = parameters[2]->operator int(); case 2: height = parameters[1]->operator float(); case 1: width = parameters[0]->operator float(); case 0: break; default: OtExcept("Too many parameters [%ld] for [PlaneGeometry] constructor (max 4)", count); } return nullptr; } // // OtPlaneGeometryClass::setWidth // OtObject OtPlaneGeometryClass::setWidth(float w) { width = w; refreshGeometry = true; return shared(); } // // OtPlaneGeometryClass::setHeight // OtObject OtPlaneGeometryClass::setHeight(float h) { height = h; refreshGeometry = true; return shared(); } // // OtPlaneGeometryClass::setWidthSegments // OtObject OtPlaneGeometryClass::setWidthSegments(int ws) { widthSegments = ws; refreshGeometry = true; return shared(); } // // OtPlaneGeometryClass::setHeightSegments // OtObject OtPlaneGeometryClass::setHeightSegments(int hs) { heightSegments = hs; refreshGeometry = true; return shared(); } // // OtPlaneGeometryClass::setHeightMap // OtObject OtPlaneGeometryClass::setHeightMap(OtObject object) { // sanity check if (!object->isKindOf("HeightMap")) { OtExcept("Expected a [HeightMap] object, not a [%s]", object->getType()->getName().c_str()); } // cleanup if (heightmap) { heightmap->detach(heightmapID); heightmap = nullptr; } if (noisemap) { noisemap->detach(noisemapID); noisemap = nullptr; } // set new heightmap heightmap = object->cast<OtHeightMapClass>(); refreshGeometry = true; heightmapID = heightmap->attach([this]() { refreshGeometry = true; }); return shared(); } // // OtPlaneGeometryClass::setNoiseMap // OtObject OtPlaneGeometryClass::setNoiseMap(OtObject object, int xo, int yo) { // sanity check if (!object->isKindOf("NoiseMap")) { OtExcept("Expected a [NoiseMap] object, not a [%s]", object->getType()->getName().c_str()); } // cleanup if (heightmap) { heightmap->detach(heightmapID); heightmap = nullptr; } if (noisemap) { noisemap->detach(noisemapID); noisemap = nullptr; } // set new noisemap noisemap = object->cast<OtNoiseMapClass>(); refreshGeometry = true; noisemapID = noisemap->attach([this]() { refreshGeometry = true; }); xoffset = xo; yoffset = yo; return shared(); } // // OtPlaneGeometryClass::fillGeometry // void OtPlaneGeometryClass::fillGeometry() { // add vertices auto widthHalf = width / 2.0; auto heightHalf = height / 2.0; auto gridX1 = widthSegments + 1; auto gridY1 = heightSegments + 1; auto segmentWidth = width / (float) widthSegments; auto segmentHeight = height / (float) heightSegments; for (auto iy = 0; iy < gridY1; iy++) { auto y = heightHalf - iy * segmentHeight; for (auto ix = 0; ix < gridX1; ix++) { auto x = ix * segmentWidth - widthHalf; auto u = (float) ix / (float) widthSegments; auto v = (float) iy / (float) heightSegments; float z = 0.0; if (heightmap) { z = heightmap->getHeight(u, v); } else if (noisemap) { z = noisemap->getNoise(u * width + xoffset, v * height + yoffset); } addVertex(OtVertex( glm::vec3(x, y, z), glm::vec3(0.0, 0.0, 1.0), glm::vec2(u, v))); } } // add triangles and lines for (auto iy = 0; iy < heightSegments; iy++) { for (auto ix = 0; ix < widthSegments; ix++) { auto a = ix + gridX1 * iy; auto b = ix + gridX1 * (iy + 1); auto c = (ix + 1) + gridX1 * (iy + 1); auto d = (ix + 1) + gridX1 * iy; addTriangle(a, b, d); addTriangle(b, c, d); if (iy == 0) { addLine(a, d); } addLine(a, b); addLine(b, c); if (ix == widthSegments - 1) { addLine(c, d); } } } } // // OtPlaneGeometryClass::getMeta // OtType OtPlaneGeometryClass::getMeta() { static OtType type = nullptr; if (!type) { type = OtTypeClass::create<OtPlaneGeometryClass>("PlaneGeometry", OtGeometryClass::getMeta()); type->set("__init__", OtFunctionClass::create(&OtPlaneGeometryClass::init)); type->set("setWidth", OtFunctionClass::create(&OtPlaneGeometryClass::setWidth)); type->set("setHeight", OtFunctionClass::create(&OtPlaneGeometryClass::setHeight)); type->set("setWidthSegments", OtFunctionClass::create(&OtPlaneGeometryClass::setWidthSegments)); type->set("setHeightSegments", OtFunctionClass::create(&OtPlaneGeometryClass::setHeightSegments)); type->set("setHeightMap", OtFunctionClass::create(&OtPlaneGeometryClass::setHeightMap)); type->set("setNoiseMap", OtFunctionClass::create(&OtPlaneGeometryClass::setNoiseMap)); } return type; } // // OtPlaneGeometryClass::create // OtPlaneGeometry OtPlaneGeometryClass::create() { OtPlaneGeometry planegeometry = std::make_shared<OtPlaneGeometryClass>(); planegeometry->setType(getMeta()); return planegeometry; }
20.125461
100
0.676568
goossens
e4bfd44b8e0a2313318512d4fe9f02c69cf9f115
5,831
cc
C++
test/object_characterization/characterization_test.cc
ilMartoo/LiDAR-based_anomaly_detector
a5364992f906fe1eec8106bebdfa1fa99932e89e
[ "MIT" ]
null
null
null
test/object_characterization/characterization_test.cc
ilMartoo/LiDAR-based_anomaly_detector
a5364992f906fe1eec8106bebdfa1fa99932e89e
[ "MIT" ]
null
null
null
test/object_characterization/characterization_test.cc
ilMartoo/LiDAR-based_anomaly_detector
a5364992f906fe1eec8106bebdfa1fa99932e89e
[ "MIT" ]
null
null
null
/** * @file anomaly_test.cc * @author Martín Suárez (martin.suarez.garcia@rai.usc.es) * @date 10/05/2022 * * Test para el módulo de la CLI * */ #include "catch.hpp" #include "catch_utils.hh" #include <vector> #include "object_characterization/ObjectCharacterizer.hh" #include "object_characterization/CharacterizedObject.hh" #include "object_characterization/DBScan.hh" #include "scanner/IScanner.hh" #include "models/LidarPoint.hh" /* MOCKUP */ class ScannerMock : public IScanner { public: std::function<void(const LidarPoint &p)> func; std::vector<LidarPoint> v; ScannerMock() { v.reserve(400 * 6 + 2); for (int i = 0; i < 20; ++i) { for (int j = 0; j < 20; ++j) { v.push_back({{0, 0}, 0, 0, i, j}); v.push_back({{0, 0}, 0, 100, i, j}); v.push_back({{0, 0}, 0, i, 0, j}); v.push_back({{0, 0}, 0, i, 100, j}); v.push_back({{0, 0}, 0, i, j, 0}); v.push_back({{0, 0}, 0, i, j, 100}); } } v.push_back({{0, 0}, 0, -100, -100, -100}); v.push_back({{2, 0}, 0, 0, 0, 0}); } bool init() { return true; } ScanCode scan() { if (!scanning) { scanning = true; if (func) { for (size_t i = 0; i < v.size() && scanning; ++i) { func(v[i]); } } scanning = false; } return kScanOk; } void pause() { scanning = false; } bool setCallback(std::function<void(const LidarPoint &p)> func) { return (bool)(this->func = func); } void stop() {} }; class ScannerMockBad : public IScanner { public: std::function<void(const LidarPoint &p)> func; std::vector<LidarPoint> v; ScannerMockBad() { v.reserve(400 * 6 + 2); for (int i = 0; i < 2000; i += 100) { for (int j = 0; j < 2000; j += 100) { v.push_back({{0, 0}, 0, 0, i, j}); v.push_back({{0, 0}, 0, 100, i, j}); v.push_back({{0, 0}, 0, i, 0, j}); v.push_back({{0, 0}, 0, i, 100, j}); v.push_back({{0, 0}, 0, i, j, 0}); v.push_back({{0, 0}, 0, i, j, 100}); } } v.push_back({{0, 0}, 0, -100, -100, -100}); v.push_back({{2, 0}, 0, 0, 0, 0}); } bool init() { return false; } ScanCode scan() { if (!scanning) { scanning = true; if (func) { for (size_t i = 0; i < v.size() && scanning; ++i) { func(v[i]); } } scanning = false; } return kScanOk; } void pause() { scanning = false; } bool setCallback(std::function<void(const LidarPoint &p)> func) { return (bool)(this->func = func); } void stop() {} }; class ScannerMockWait : public IScanner { public: std::function<void(const LidarPoint &p)> func; std::vector<LidarPoint> v; unsigned discarded; ScannerMockWait() : discarded(0) { v.push_back({{0, 0}, 0, 0, 0, 0}); v.push_back({{1, 0}, 0, 0, 0, 0}); v.push_back({{2, 0}, 0, 0, 0, 0}); v.push_back({{3, 0}, 0, 0, 0, 0}); } bool init() { return true; } ScanCode scan() { if(!scanning) { scanning = true; if (func) { for (size_t i = 0; i < v.size() && scanning; ++i) { func(v[i]); ++discarded; } } scanning = false; } return kScanOk; } void pause() { scanning = false; } bool setCallback(std::function<void(const LidarPoint &p)> func) { return (bool)(this->func = func); } void stop() {} }; /**********/ class CharacterizationFixture { public: ScannerMock sg; ScannerMockBad sb; ScannerMockWait sw; ObjectCharacterizer ocg; ObjectCharacterizer ocb; ObjectCharacterizer ocw; std::vector<Point> cubo; std::vector<Point> plano; CharacterizationFixture() : sg(), sb(), ocg(&sg, 10, 10, 0, 10, true), ocb(&sb, 10, 10, 0, 10, false), ocw(&sw, 10, 10, 0, 10, false) { sg.setCallback([this](const LidarPoint &p) { this->ocg.newPoint(p); }); sb.setCallback([this](const LidarPoint &p) { this->ocb.newPoint(p); }); sw.setCallback([this](const LidarPoint &p) { this->ocw.newPoint(p); }); for (int i = 0; i <= 50; ++i) { for (int j = 0; j <= 50; ++j) { cubo.push_back({0, i, j}); cubo.push_back({50, i, j}); cubo.push_back({i, 0, j}); cubo.push_back({i, 50, j}); cubo.push_back({i, j, 0}); cubo.push_back({i, j, 50}); plano.push_back({i, j, 0}); } } cubo.push_back({-100, -100, -100}); plano.push_back({-100, -100, -100}); } }; TEST_CASE_METHOD(CharacterizationFixture, "3.1, 3.2, 3.3", "[ObjectCharacterizer]") { ocg.defineBackground(); // 3.1 CHECK(ocg.init()); // 3.2 CHECK(!ocb.init()); // 3.3 CHECK(!ocg.defineObject().first); } TEST_CASE_METHOD(CharacterizationFixture, "3.4, 3.5", "[ObjectCharacterizer]") { // 3.4 CHECK(!ocb.defineObject().first); // 3.5 CHECK(ocg.defineObject().first); } TEST_CASE_METHOD(CharacterizationFixture, "3.6", "[ObjectCharacterizer]") { ocw.wait(1500); CHECK(sw.discarded == 3); } TEST_CASE_METHOD(CharacterizationFixture, "3.7, 3.8", "[DBScan]") { // 3.7 CHECK(DBScan::clusters(cubo).size() == 1); // 3.8 CHECK(DBScan::normals(plano).size() == 1); }
29.00995
105
0.483965
ilMartoo
e4c25f02c1db29dc65b06ad6cc539b0dd5a98321
321
cc
C++
src/api/version.cc
AmadeusITGroup/cPMML
2cd19f9b86779a18f7fb63707c47574125bd374a
[ "MIT" ]
22
2020-05-04T16:05:03.000Z
2022-01-25T09:20:02.000Z
src/api/version.cc
AmadeusITGroup/cPMML
2cd19f9b86779a18f7fb63707c47574125bd374a
[ "MIT" ]
3
2021-01-26T18:41:35.000Z
2021-08-13T04:35:47.000Z
src/api/version.cc
AmadeusITGroup/cPMML
2cd19f9b86779a18f7fb63707c47574125bd374a
[ "MIT" ]
2
2020-07-13T10:07:13.000Z
2021-07-26T09:35:05.000Z
/******************************************************************************* * Copyright 2019 AMADEUS. All rights reserved. * Author: Paolo Iannino *******************************************************************************/ #include "cPMML.h" namespace cpmml { const std::string version = CPMML_VERSION; }
26.75
81
0.361371
AmadeusITGroup
e4c48c9b8b689587fddff718e33b4f96d1e854f9
1,059
cpp
C++
examples/chapter.13.16.cpp
Chen-Carl/GUI
13aa8337f2afe3b6d0d4d18b5c8eb1cf3a47cdd7
[ "BSL-1.0" ]
1
2021-04-23T13:19:28.000Z
2021-04-23T13:19:28.000Z
examples/chapter.13.16.cpp
Chen-Carl/GUI
13aa8337f2afe3b6d0d4d18b5c8eb1cf3a47cdd7
[ "BSL-1.0" ]
null
null
null
examples/chapter.13.16.cpp
Chen-Carl/GUI
13aa8337f2afe3b6d0d4d18b5c8eb1cf3a47cdd7
[ "BSL-1.0" ]
2
2021-05-08T15:09:18.000Z
2021-06-03T09:49:24.000Z
// // This is example code from Chapter 13.16 "Mark" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #include "Simple_window.h" // get access to our window library #include "Graph.h" // get access to our graphics library facilities //------------------------------------------------------------------------------ int main() { using namespace Graph_lib; // our graphics facilities are in Graph_lib Simple_window win = {{100,100},600,400,"Circles with centers"}; Circle c1 = {{100,200},50}; Circle c2 = {{150,200},100}; Circle c3 = {{200,200},150}; win.attach(c1); win.attach(c2); win.attach(c3); Mark m1 = {{100,200},'x'}; Mark m2 = {{150,200},'y'}; Mark m3 = {{200,200},'z'}; c1.set_color(Colors::blue); c2.set_color(Colors::red); c3.set_color(Colors::green); win.attach(m1); win.attach(m2); win.attach(m3); win.wait_for_button(); // Display! } //------------------------------------------------------------------------------
26.475
80
0.517469
Chen-Carl
e4c6b4f752dca4e75b366776c7f135c6faeac5dc
1,806
hh
C++
aku/SpeakerConfig.hh
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
78
2015-01-07T14:33:47.000Z
2022-03-15T09:01:30.000Z
aku/SpeakerConfig.hh
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
4
2015-05-19T13:00:34.000Z
2016-07-26T12:29:32.000Z
aku/SpeakerConfig.hh
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
32
2015-01-16T08:16:24.000Z
2021-04-02T21:26:22.000Z
#ifndef SPEAKERCONFIG_HH #define SPEAKERCONFIG_HH #include <vector> #include <set> #include <map> #include <string> #include "FeatureGenerator.hh" #include "ModelModules.hh" namespace aku { /** A class for handling speaker and utterance adaptations. * Speaker ID is the primary method for changing feature configurations. * If another level of configurations is needed, utterance IDs can * be used. Note that utterance ID is reset when speaker ID changes. */ class SpeakerConfig { public: SpeakerConfig(FeatureGenerator &fea_gen, HmmSet *model = NULL); void read_speaker_file(FILE *file); void write_speaker_file(FILE *file, std::set<std::string> *speakers = NULL, std::set<std::string> *utterances = NULL); void set_speaker(const std::string &speaker_id); const std::string& get_cur_speaker(void) { return m_cur_speaker; } void set_utterance(const std::string &utterance_id); const std::string& get_cur_utterance(void) { return m_cur_utterance; } ModelTransformer& get_model_transformer() { return m_model_trans; } private: typedef std::map<std::string, ModuleConfig> ModuleMap; typedef std::map<std::string, ModuleMap> SpeakerMap; void retrieve_speaker_config(const std::string &speaker_id); void retrieve_utterance_config(const std::string &utterance_id); void set_modules(const ModuleMap &modules, bool load_new_model_trans = false); private: FeatureGenerator &m_fea_gen; ModelTransformer m_model_trans; HmmSet *m_model; SpeakerMap m_speaker_config; SpeakerMap m_utterance_config; ModuleMap m_default_speaker_config; ModuleMap m_default_utterance_config; bool m_default_speaker_set; bool m_default_utterance_set; std::string m_cur_speaker; std::string m_cur_utterance; }; } #endif // SPEAKERCONFIG_HH
28.666667
80
0.75969
phsmit
e4c6e8053bfc3e536a01e404ce2240b5e48e5224
1,504
cpp
C++
leetcode-problems/medium-33-search-in-rotated-array.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium-33-search-in-rotated-array.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/medium-33-search-in-rotated-array.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
// // Created by Siddhant on 2019-11-07. // #include "iostream" #include "vector" #include "string" #include "algorithm" using namespace std; int findCenter(vector<int> &nums) { if (nums[0] < nums[nums.size() - 1]) { return 0; } if (nums.size() == 1) { return 0; } int start = 0; int end = nums.size() - 1; int mid; while (start < end) { mid = (start + end) / 2; if (nums[mid] < nums[start] && nums[mid - 1] > nums[mid]) { return mid; } if (nums[mid] > nums[start]) { start = mid; } else { end = mid; } } return mid + 1; } int binSearch(vector<int> &nums, int target, int startIndex, int endIndex) { int mid; while (startIndex <= endIndex) { mid = (startIndex + endIndex) / 2; if (nums[mid] == target) { return mid; } if (nums[mid] > target) { endIndex = mid - 1; } else { startIndex = mid + 1; } } return -1; } int search(vector<int> &nums, int target) { int getCenter = findCenter(nums); if (target <= nums[nums.size() - 1]) { return binSearch(nums, target, getCenter, nums.size() - 1); } else { return binSearch(nums, target, 0, getCenter - 1); } } int main() { vector<int> nums = {3, 1}; // vector<int> nums = {4,5,6,7,0,1,2}; cout << "center index : " << search(nums, 0); return 0; }
16.898876
76
0.489362
formatkaka
e4c7746f4bf9e345624c3ea94d88532d7d0a1efb
6,339
cpp
C++
HelperFunctions/getVkPipelineRasterizationConservativeStateCreateInfoEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPipelineRasterizationConservativeStateCreateInfoEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPipelineRasterizationConservativeStateCreateInfoEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Douglas Kaip * * 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. */ /* * getVkPipelineRasterizationConservativeStateCreateInfoEXT.cpp * * Created on: May 28, 2019 * Author: Douglas Kaip */ #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getVkPipelineRasterizationConservativeStateCreateInfoEXT( JNIEnv *env, const jobject jVkPipelineRasterizationConservativeStateCreateInfoEXTObject, VkPipelineRasterizationConservativeStateCreateInfoEXT *vkPipelineRasterizationConservativeStateCreateInfoEXT, std::vector<void *> *memoryToFree) { jclass theClass = env->GetObjectClass(jVkPipelineRasterizationConservativeStateCreateInfoEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find class for jVkPipelineRasterizationConservativeStateCreateInfoEXTObject"); return; } //////////////////////////////////////////////////////////////////////// VkStructureType sTypeValue = getSType(env, jVkPipelineRasterizationConservativeStateCreateInfoEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getSType failed."); return; } //////////////////////////////////////////////////////////////////////// jobject jpNextObject = getpNextObject(env, jVkPipelineRasterizationConservativeStateCreateInfoEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNext failed."); return; } void *pNext = nullptr; if (jpNextObject != nullptr) { getpNextChain( env, jpNextObject, &pNext, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNextChain failed."); return; } } //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(theClass, "getFlags", "()Ljava/util/EnumSet;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for getFlags."); return; } jobject flagsObject = env->CallObjectMethod(jVkPipelineRasterizationConservativeStateCreateInfoEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod."); return; } VkPipelineRasterizationConservativeStateCreateFlagsEXT flags = (VkPipelineRasterizationConservativeStateCreateFlagsEXT)getEnumSetValue( env, flagsObject, "com/CIMthetics/jvulkan/VulkanExtensions/Enums/VkPipelineRasterizationConservativeStateCreateFlagBitsEXT"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling getEnumSetValue."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "getConservativeRasterizationMode", "()Lcom/CIMthetics/jvulkan/VulkanExtensions/Enums/VkConservativeRasterizationModeEXT;"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for getConservativeRasterizationMode."); return; } jobject jVkConservativeRasterizationModeEXTObject = env->CallObjectMethod(jVkPipelineRasterizationConservativeStateCreateInfoEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallObjectMethod."); return; } jclass vkConservativeRasterizationModeEXTEnumClass = env->GetObjectClass(jVkConservativeRasterizationModeEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find class for jVkConservativeRasterizationModeEXTObject."); return; } jmethodID valueOfMethodId = env->GetMethodID(vkConservativeRasterizationModeEXTEnumClass, "valueOf", "()I"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for valueOf."); return; } VkConservativeRasterizationModeEXT vkConservativeRasterizationModeEXTEnumValue = (VkConservativeRasterizationModeEXT)env->CallIntMethod(jVkConservativeRasterizationModeEXTObject, valueOfMethodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallIntMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "getExtraPrimitiveOverestimationSize", "()F"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for getExtraPrimitiveOverestimationSize."); return; } jfloat extraPrimitiveOverestimationSize = env->CallFloatMethod(jVkPipelineRasterizationConservativeStateCreateInfoEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallFloatMethod."); return; } vkPipelineRasterizationConservativeStateCreateInfoEXT->sType = sTypeValue; vkPipelineRasterizationConservativeStateCreateInfoEXT->pNext = pNext; vkPipelineRasterizationConservativeStateCreateInfoEXT->flags = flags; vkPipelineRasterizationConservativeStateCreateInfoEXT->conservativeRasterizationMode = vkConservativeRasterizationModeEXTEnumValue; vkPipelineRasterizationConservativeStateCreateInfoEXT->extraPrimitiveOverestimationSize = extraPrimitiveOverestimationSize; } }
40.634615
204
0.630541
dkaip
e4c7d64f2fd3906b184ad77fe2cc07f3ea1ddb24
12,101
cpp
C++
file-commander-core/src/cfilesystemobject.cpp
JnMartens/file-commander
ee3418225dc26e411d21c4eb88a40a3859971e18
[ "Apache-2.0" ]
null
null
null
file-commander-core/src/cfilesystemobject.cpp
JnMartens/file-commander
ee3418225dc26e411d21c4eb88a40a3859971e18
[ "Apache-2.0" ]
null
null
null
file-commander-core/src/cfilesystemobject.cpp
JnMartens/file-commander
ee3418225dc26e411d21c4eb88a40a3859971e18
[ "Apache-2.0" ]
null
null
null
#include "cfilesystemobject.h" #include "filesystemhelperfunctions.h" #include "windows/windowsutils.h" #include "assert/advanced_assert.h" #include "lang/type_traits_fast.hpp" #include "hash/fasthash.h" #ifdef CFILESYSTEMOBJECT_TEST #define QFileInfo QFileInfo_Test #define QDir QDir_Test #endif DISABLE_COMPILER_WARNINGS #include "qtcore_helpers/qdatetime_helpers.hpp" #include <QDebug> RESTORE_COMPILER_WARNINGS #include <assert.h> #include <errno.h> #if defined __linux__ || defined __APPLE__ || defined __FreeBSD__ #include <unistd.h> #include <sys/stat.h> #include <wordexp.h> #include <dirent.h> #elif defined _WIN32 #include "windows/windowsutils.h" #include <Windows.h> #include <Shlwapi.h> #pragma comment(lib, "Shlwapi.lib") // This lib would have to be added not just to the top level application, but every plugin as well, so using #pragma instead #endif static QString expandEnvironmentVariables(const QString& string) { #ifdef _WIN32 if (!string.contains('%')) return string; WCHAR source[16384 + 1]; WCHAR result[16384 + 1]; static_assert (sizeof(WCHAR) == 2); const auto length = string.toWCharArray(source); source[length] = 0; if (const auto resultLength = ExpandEnvironmentStringsW(source, result, static_cast<DWORD>(std::size(result))); resultLength > 0) return toPosixSeparators(QString::fromWCharArray(result, resultLength - 1)); else return string; #else QString result = string; if (result.startsWith('~')) result.replace(0, 1, getenv("HOME")); if (result.contains('$')) { wordexp_t p; wordexp("$HOME/bin", &p, 0); const auto w = p.we_wordv; if (p.we_wordc > 0) result = w[0]; wordfree(&p); } return result; #endif } CFileSystemObject::CFileSystemObject(const QFileInfo& fileInfo) : _fileInfo(fileInfo) { refreshInfo(); } CFileSystemObject::CFileSystemObject(const QString& path) : _fileInfo(expandEnvironmentVariables(path)) { refreshInfo(); } static QString parentForAbsolutePath(QString absolutePath) { if (absolutePath.endsWith('/')) absolutePath.chop(1); const int lastSlash = absolutePath.lastIndexOf('/'); if (lastSlash <= 0) return {}; absolutePath.truncate(lastSlash + 1); // Keep the slash as it signifies a directory rather than a file. return absolutePath; } CFileSystemObject & CFileSystemObject::operator=(const QString & path) { setPath(path); return *this; } void CFileSystemObject::refreshInfo() { #ifndef _WIN32 // TODO: is this always correct? // Should there be a special "Symlink" object type? Then it could be handled properly (e. g. delete = unlink) _properties.exists = !_fileInfo.isSymLink() ? _fileInfo.exists() : true; #else _properties.exists = _fileInfo.exists(); #endif _properties.fullPath = _fileInfo.absoluteFilePath(); // QFileInfo::isShortcut() is quite a heavy call on Windows - disabled temporarily for better performance enumerating large folders // Time to first update for C:\Windows\WinSxS\ goes from 1900 to 3900 ms //if (_fileInfo.isShortcut()) // This is Windows-specific, place under #ifdef? //{ // _properties.exists = true; // _properties.type = File; //} //else if (_fileInfo.isFile()) _properties.type = File; else if (_fileInfo.isDir()) { // Normalization - very important for hash calculation and equality checking // C:/1/ must be equal to C:/1 if (!_properties.fullPath.endsWith('/')) _properties.fullPath.append('/'); #ifdef __APPLE__ _properties.type = _fileInfo.isBundle() ? Bundle : Directory; #else _properties.type = Directory; #endif } else if (!_properties.exists && _properties.fullPath.endsWith('/')) _properties.type = Directory; else { #ifdef _WIN32 if (_properties.exists) qInfo() << _properties.fullPath << " is neither a file nor a dir"; #else // TODO: is this always correct? // Should there be a special "Symlink" object type? Then it could be handled properly (e. g. delete = unlink) if (_fileInfo.isSymLink()) _properties.type = File; #endif } _properties.hash = fasthash64(_properties.fullPath.constData(), static_cast<uint64_t>(_properties.fullPath.size()) * sizeof(QChar), 0); if (_properties.type == File) { _properties.extension = _fileInfo.suffix(); _properties.completeBaseName = _fileInfo.completeBaseName(); } else if (_properties.type == Directory) { _properties.completeBaseName = _fileInfo.baseName(); const QString suffix = _fileInfo.completeSuffix(); if (!suffix.isEmpty()) _properties.completeBaseName = _properties.completeBaseName % '.' % suffix; // Ugly temporary bug fix for #141 if (_properties.completeBaseName.isEmpty() && _properties.fullPath.endsWith('/')) { const QFileInfo tmpInfo = QFileInfo(_properties.fullPath.left(_properties.fullPath.length() - 1)); _properties.completeBaseName = tmpInfo.baseName(); const QString sfx = tmpInfo.completeSuffix(); if (!sfx.isEmpty()) _properties.completeBaseName = _properties.completeBaseName % '.' % sfx; } } else if (_properties.type == Bundle) { _properties.extension = _fileInfo.suffix(); _properties.completeBaseName = _fileInfo.completeBaseName(); } _properties.fullName = _properties.type == Directory ? _properties.completeBaseName : _fileInfo.fileName(); _properties.isCdUp = _properties.fullName == QLatin1String(".."); // QFileInfo::canonicalPath() / QFileInfo::absolutePath are undefined for non-files _properties.parentFolder = parentForAbsolutePath(_properties.fullPath); if (!_properties.exists) return; _properties.creationDate = toTime_t(_fileInfo.birthTime()); _properties.modificationDate = toTime_t(_fileInfo.lastModified()); _properties.size = _properties.type == File ? static_cast<uint64_t>(_fileInfo.size()) : 0ULL; } void CFileSystemObject::setPath(const QString& path) { if (path.isEmpty()) { *this = CFileSystemObject(); return; } _rootFileSystemId = uint64_max; _fileInfo.setFile(expandEnvironmentVariables(path)); refreshInfo(); } bool CFileSystemObject::operator==(const CFileSystemObject& other) const { return hash() == other.hash(); } // Information about this object bool CFileSystemObject::isValid() const { return hash() != 0; } bool CFileSystemObject::exists() const { return _properties.exists; } const CFileSystemObjectProperties &CFileSystemObject::properties() const { return _properties; } FileSystemObjectType CFileSystemObject::type() const { return _properties.type; } bool CFileSystemObject::isFile() const { return _properties.type == File; } bool CFileSystemObject::isDir() const { return _properties.type == Directory || _properties.type == Bundle; } bool CFileSystemObject::isBundle() const { return _properties.type == Bundle; } bool CFileSystemObject::isEmptyDir() const { if (!isDir()) return false; #ifdef _WIN32 WCHAR path[32768]; const int nChars = _properties.fullPath.toWCharArray(path); path[nChars] = 0; return PathIsDirectoryEmptyW(path) != 0; #else // TODO: use getdents64 on Linux DIR *dir = ::opendir(_properties.fullPath.toLocal8Bit().constData()); if (dir == nullptr) // Not a directory or doesn't exist return false; struct dirent *d = nullptr; int n = 0; while ((d = ::readdir(dir)) != nullptr) { if(++n > 2) break; } ::closedir(dir); return n <= 2; // Only '.' and '..' ? #endif } bool CFileSystemObject::isCdUp() const { return _properties.isCdUp; } bool CFileSystemObject::isExecutable() const { return _fileInfo.permission(QFile::ExeUser) || _fileInfo.permission(QFile::ExeOwner) || _fileInfo.permission(QFile::ExeGroup) || _fileInfo.permission(QFile::ExeOther); } bool CFileSystemObject::isReadable() const { return _fileInfo.isReadable(); } // Apparently, it will return false for non-existing files bool CFileSystemObject::isWriteable() const { return _fileInfo.isWritable(); } bool CFileSystemObject::isHidden() const { return _fileInfo.isHidden(); } QString CFileSystemObject::fullAbsolutePath() const { assert(_properties.type != Directory || _properties.fullPath.isEmpty() || _properties.fullPath.endsWith('/')); return _properties.fullPath; } QString CFileSystemObject::parentDirPath() const { assert(_properties.parentFolder.isEmpty() || _properties.parentFolder.endsWith('/')); return _properties.parentFolder; } uint64_t CFileSystemObject::size() const { return _properties.size; } uint64_t CFileSystemObject::hash() const { return _properties.hash; } const QFileInfo &CFileSystemObject::qFileInfo() const { return _fileInfo; } uint64_t CFileSystemObject::rootFileSystemId() const { if (_rootFileSystemId == uint64_max) { #ifdef _WIN32 WCHAR drivePath[32768]; const auto pathLength = _properties.fullPath.toWCharArray(drivePath); drivePath[pathLength] = 0; const auto driveNumber = PathGetDriveNumberW(drivePath); if (driveNumber != -1) _rootFileSystemId = static_cast<uint64_t>(driveNumber); #else struct stat info; const int ret = stat(_properties.fullPath.toUtf8().constData(), &info); if (ret == 0 || errno == ENOENT) _rootFileSystemId = (uint64_t) info.st_dev; else { qInfo() << __FUNCTION__ << "Failed to query device ID for" << _properties.fullPath; qInfo() << strerror(errno); } #endif } return _rootFileSystemId; } bool CFileSystemObject::isNetworkObject() const { #ifdef _WIN32 if (!_properties.fullPath.startsWith("//")) return false; WCHAR wPath[MAX_PATH]; const int nSymbols = toNativeSeparators(_properties.fullPath).toWCharArray(wPath); wPath[nSymbols] = 0; return PathIsNetworkPathW(wPath); #else return false; #endif } bool CFileSystemObject::isSymLink() const { return _fileInfo.isSymLink(); } QString CFileSystemObject::symLinkTarget() const { return _fileInfo.symLinkTarget(); } bool CFileSystemObject::isMovableTo(const CFileSystemObject& dest) const { if (!isValid() || !dest.isValid()) return false; const auto fileSystemId = rootFileSystemId(); const auto otherFileSystemId = dest.rootFileSystemId(); return fileSystemId == otherFileSystemId && fileSystemId != uint64_max; } // A hack to store the size of a directory after it's calculated void CFileSystemObject::setDirSize(uint64_t size) { _properties.size = size; } // File name without suffix, or folder name. Same as QFileInfo::completeBaseName. QString CFileSystemObject::name() const { return _properties.completeBaseName; } // Filename + suffix for files, same as name() for folders QString CFileSystemObject::fullName() const { return _properties.fullName; } QString CFileSystemObject::extension() const { return _properties.extension; } QString CFileSystemObject::sizeString() const { return _properties.type == File ? fileSizeToString(_properties.size) : QString(); } QString CFileSystemObject::modificationDateString() const { return fromTime_t(_properties.modificationDate).toLocalTime().toString(QLatin1String("dd.MM.yyyy hh:mm")); } // Return the list of consecutive full paths leading from the specified target to its root. // E. g. C:/Users/user/Documents/ -> {C:/Users/user/Documents/, C:/Users/user/, C:/Users/, C:/} std::vector<QString> pathHierarchy(const QString& path) { assert_r(!path.contains('\\')); assert_r(!path.contains(QStringLiteral("//")) || !QStringView{path}.right(path.length() - 2).contains(QLatin1String("//"))); if (path.isEmpty()) return {}; else if (path == '/') return { path }; QString pathItem = path.endsWith('/') ? path.left(path.length() - 1) : path; std::vector<QString> result{ path }; while ((pathItem = QFileInfo(pathItem).absolutePath()).length() < result.back().length()) { if (pathItem.endsWith('/')) result.emplace_back(pathItem); else result.emplace_back(pathItem + '/'); } return result; }
26.479212
169
0.705975
JnMartens
e4c973a4f2ac749c66a5292198a2b7ee3e1a9a20
1,082
cpp
C++
source/UnitTest1/StubDataManager.cpp
Tronso/test_recording
3b581f557830526e3f0e51f40df04a5be24b7e62
[ "Apache-2.0" ]
null
null
null
source/UnitTest1/StubDataManager.cpp
Tronso/test_recording
3b581f557830526e3f0e51f40df04a5be24b7e62
[ "Apache-2.0" ]
null
null
null
source/UnitTest1/StubDataManager.cpp
Tronso/test_recording
3b581f557830526e3f0e51f40df04a5be24b7e62
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "StubDataManager.h" #include "Situation.h" #include "Transition.h" #include <memory> #include "CppUnitTest.h" #include "SituationGraph.h" using std::make_shared; using namespace Microsoft::VisualStudio::CppUnitTestFramework; StubDataManager::StubDataManager() : inputs() { } StubDataManager::~StubDataManager() { } void StubDataManager::storeTransition(Transition const & transition) { Logger::WriteMessage(L"storeTransition was called"); inputs.push_back(make_shared<Transition>(transition)); } std::unique_ptr<SituationGraph> StubDataManager::retrieveSubSituationGraph(std::shared_ptr<Situation> root) { return nullptr; } std::unique_ptr<SituationGraph> StubDataManager::retrieveSituationGraph() { std::vector<std::shared_ptr<Transition>> t; SituationGraph sg(t); return move(std::make_unique<SituationGraph>(t)); } int StubDataManager::getMaxNumberOfObjects() { return 0; } int StubDataManager::getNumberOfSituations() { return 0; } std::vector<std::shared_ptr<Transition>> const & StubDataManager::getInputs() { return inputs; }
22.081633
107
0.774492
Tronso
e4cb5b9c2bb285f87eb8e924506629509137cd3f
1,150
cc
C++
src/script/script_timer.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
src/script/script_timer.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
src/script/script_timer.cc
dgolbourn/Metallic-Crow
0f073312c67d3f0542cc40f23e94a018bd5e52c5
[ "MIT" ]
null
null
null
#include "script_impl.h" #include "bind.h" namespace game { auto Script::Impl::TimerInit() -> void { lua::Init<std::pair<WeakStagePtr, event::Timer::WeakPtr>>(static_cast<lua_State*>(lua_)); lua_.Add(function::Bind(&Impl::TimerLoad, shared_from_this()), "timer_load", 1, "metallic_crow"); lua_.Add(function::Bind(&Impl::TimerFree, shared_from_this()), "timer_free", 0, "metallic_crow"); } auto Script::Impl::TimerLoad() -> void { event::Timer timer; StagePtr stage; { lua::Guard guard = lua_.Get(-4); stage = StageGet(); } if(stage) { timer = event::Timer(lua_.At<double>(-2), lua_.At<int>(-1)); timer.Add(lua_.At<event::Command>(-3)); if(!Pause(stage)) { timer.Resume(); } stage->timers_.emplace(timer); queue_.Add(function::Bind(&event::Timer::operator(), timer)); } lua::Push(static_cast<lua_State*>(lua_), std::pair<WeakStagePtr, event::Timer::WeakPtr>(stage, timer)); } auto Script::Impl::TimerFree() -> void { std::pair<StagePtr, event::Timer> timer = StageDataGet<event::Timer>(); if(timer.first && timer.second) { timer.first->timers_.erase(timer.second); } } }
26.136364
105
0.648696
dgolbourn
e4ccd51eeff9fd39234011dfc6533d0c35cb3f3c
948
cpp
C++
Introductions/Quadratic/quadratic.cpp
csulb-cecs282-2015sp/lectures
f7a88c52b85472f4e871ed439bfe65ee784f4aa9
[ "MIT" ]
11
2015-01-20T05:57:50.000Z
2021-05-03T10:47:36.000Z
Introductions/Quadratic/quadratic.cpp
csulb-cecs282-2015sp/lectures
f7a88c52b85472f4e871ed439bfe65ee784f4aa9
[ "MIT" ]
null
null
null
Introductions/Quadratic/quadratic.cpp
csulb-cecs282-2015sp/lectures
f7a88c52b85472f4e871ed439bfe65ee784f4aa9
[ "MIT" ]
26
2015-01-20T04:38:39.000Z
2017-01-11T00:49:57.000Z
#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "This program will find the real solutions to a general quadratic " "equation of the form ax^2 + bx + c = 0" << endl; cout << "\nEnter a, b, and c:" << endl; double a, b, c; cin >> a >> b >> c; double discriminant = b * b - 4 * a * c; // C++ has the same control structures as Java: if, else, else if. if (discriminant < 0) { cout << "There are no real solutions to that equation." << endl; } else if (discriminant == 0) { cout << "There is one real solution to the equation, and it is x = " << (-b / (2 * a)) << endl; } else { double squareRoot = sqrt(discriminant); double x1 = (-b + squareRoot) / (2 * a); double x2 = (-b - squareRoot) / (2 * a); cout << "There are two real solutions to the equation, and they are:\n" "x1 = " << x1 << "\nx2 = " << x2 << endl; } }
29.625
78
0.548523
csulb-cecs282-2015sp
e4d19a84d9d54af5d4c746d15fbbee51a953ac5b
9,854
cpp
C++
tests/demo/src/cpu_conv_bias_relu_pattern.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/demo/src/cpu_conv_bias_relu_pattern.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/demo/src/cpu_conv_bias_relu_pattern.cpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /// @example cpu_conv_bias_relu_pattern.cpp /// @copybrief cpu_conv_bias_relu_pattern_cpp /// > Annotated version: @ref cpu_conv_bias_relu_pattern_cpp /// @page cpu_conv_bias_relu_pattern_cpp CPU example for conv+bias+relu pattern /// /// > Example code: @ref cpu_conv_bias_relu_pattern.cpp #include <assert.h> #include <algorithm> #include <cmath> #include <iostream> #include <stdexcept> #include <unordered_map> #include "oneapi/dnnl/dnnl_graph.hpp" #include "common/execution_context.hpp" #include "common/helpers_any_layout.hpp" #include "common/utils.hpp" #define assertm(exp, msg) assert(((void)msg, exp)) using namespace dnnl::graph; using data_type = logical_tensor::data_type; using layout_type = logical_tensor::layout_type; // clang-format off int main(int argc, char **argv) { std::cout << "========Example: Conv->ReLU->Conv->ReLU========\n"; engine::kind engine_kind = parse_engine_kind(argc, argv); if (engine_kind == engine::kind::gpu) { printf("Don't support gpu now\n"); return -1; } // Step 2: Construct a example graph: `conv->relu->conv->relu` graph g(engine_kind); /// Create logical tensor std::cout << "Create logical tensor--------------------------"; const std::vector<size_t> logical_id {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<int64_t> input_dims {8, 3, 227, 227}; std::vector<int64_t> weight_dims {96, 3, 11, 11}; std::vector<int64_t> bias_dims {96}; std::vector<int64_t> weight1_dims {96, 96, 1, 1}; std::vector<int64_t> bias1_dims {96}; std::vector<int64_t> dst_dims {8, 96, 55, 55}; logical_tensor conv0_src_desc {logical_id[0], data_type::f32, input_dims, layout_type::strided}; logical_tensor conv0_weight_desc {logical_id[1], data_type::f32, weight_dims, layout_type::strided}; logical_tensor conv0_bias_desc {logical_id[2], data_type::f32, bias_dims, layout_type::strided}; logical_tensor conv0_dst_desc {logical_id[3], data_type::f32, dst_dims, layout_type::strided}; op conv0 {0, op::kind::Convolution, {conv0_src_desc, conv0_weight_desc}, {conv0_dst_desc}, "conv0"}; conv0.set_attr<std::vector<int64_t>>("strides", {4, 4}); conv0.set_attr<std::vector<int64_t>>("pads_begin", {111, 111}); conv0.set_attr<std::vector<int64_t>>("pads_end", {111, 111}); conv0.set_attr<std::string>("auto_pad", "VALID"); conv0.set_attr<std::vector<int64_t>>("dilations", {1, 1}); conv0.set_attr<std::string>("data_format", "NCX"); conv0.set_attr<std::string>("filter_format", "OIX"); conv0.set_attr<int64_t>("groups", 1); logical_tensor conv0_bias_add_dst_desc {logical_id[9], data_type::f32, dst_dims, layout_type::strided}; op conv0_bias_add {1, op::kind::BiasAdd, {conv0_dst_desc, conv0_bias_desc}, {conv0_bias_add_dst_desc}, "conv0_bias_add"}; logical_tensor relu0_dst_desc {logical_id[4], data_type::f32, dst_dims, layout_type::strided}; op relu0 {2, op::kind::ReLU, {conv0_bias_add_dst_desc}, {relu0_dst_desc}, "relu0"}; logical_tensor conv1_weight_desc {logical_id[5], data_type::f32, weight1_dims, layout_type::strided}; logical_tensor conv1_bias_desc {logical_id[6], data_type::f32, bias1_dims, layout_type::strided}; logical_tensor conv1_dst_desc {logical_id[7], data_type::f32, dst_dims, layout_type::strided}; op conv1 {3, op::kind::Convolution, {relu0_dst_desc, conv1_weight_desc}, {conv1_dst_desc}, "conv1"}; conv1.set_attr<std::vector<int64_t>>("strides", {1, 1}); conv1.set_attr<std::vector<int64_t>>("pads_begin", {0, 0}); conv1.set_attr<std::vector<int64_t>>("pads_end", {0, 0}); conv1.set_attr<std::vector<int64_t>>("dilations", {1, 1}); conv1.set_attr<std::string>("data_format", "NCX"); conv1.set_attr<std::string>("filter_format", "OIX"); conv1.set_attr<int64_t>("groups", 1); logical_tensor conv1_bias_add_dst_desc {logical_id[10], data_type::f32, dst_dims, layout_type::strided}; op conv1_bias_add {4, op::kind::BiasAdd, {conv1_dst_desc, conv1_bias_desc}, {conv1_bias_add_dst_desc}, "conv1_bias_add"}; logical_tensor relu1_dst_desc {logical_id[8], data_type::f32, dst_dims, layout_type::strided}; op relu1 {5, op::kind::ReLU, {conv1_bias_add_dst_desc}, {relu1_dst_desc}, "relu1"}; std::cout << "Success!\n"; std::unordered_map<size_t, op::kind> op_id_kind_map {{0, op::kind::Convolution}, {1, op::kind::BiasAdd}, {2, op::kind::ReLU}, {3, op::kind::Convolution}, {4, op::kind::BiasAdd}, {5, op::kind::ReLU}}; /// Add OP std::cout << "Add OP to graph--------------------------------"; g.add_op(conv0); g.add_op(relu0); g.add_op(conv1); g.add_op(relu1); g.add_op(conv0_bias_add); g.add_op(conv1_bias_add); std::cout << "Success!\n"; // Step 3: Filter and get partitions /// Graph will be filtered into two partitions: `conv0+relu0` and `conv1+relu1` /// Setting `DNNL_GRAPH_DUMP=1` can save internal graphs before/after graph fusion into dot files std::cout << "Filter and get partition-----------------------"; auto partitions = g.get_partitions(partition::policy::fusion); std::cout << "Success!\n"; std::cout << "Number of returned partitions: " << partitions.size() << "\n"; for (size_t i = 0; i < partitions.size(); ++i) { std::cout << "Partition[" << partitions[i].get_id() << "]'s supporting status: " << (partitions[i].is_supported() ? "true" : "false") << "\n"; } /// mark the output logical tensors of partition as ANY layout enabled std::unordered_set<size_t> id_to_set_any_layout; set_any_layout(partitions, id_to_set_any_layout); /// construct a new engine engine e {engine_kind, 0}; /// construct a new stream stream s {e}; std::vector<compiled_partition> c_partitions(partitions.size()); // mapping from id to tensors tensor_map tm; // mapping from id to queried logical tensor from compiled partition // used to record the logical tensors that are previously enabled with ANY layout std::unordered_map<size_t, logical_tensor> id_to_queried_logical_tensors; for (size_t i = 0; i < partitions.size(); ++i) { if (partitions[i].is_supported()) { std::cout << "\nPartition[" << partitions[i].get_id() << "] is being processed.\n"; std::vector<logical_tensor> inputs = partitions[i].get_in_ports(); std::vector<logical_tensor> outputs = partitions[i].get_out_ports(); /// replace input logical tensor with the queried one replace_with_queried_logical_tensors(inputs, id_to_queried_logical_tensors); /// update output logical tensors with ANY layout update_tensors_with_any_layout(outputs, id_to_set_any_layout); std::cout << "Compiling--------------------------------------"; /// compile to generate compiled partition c_partitions[i] = partitions[i].compile(inputs, outputs, e); std::cout << "Success!\n"; record_queried_logical_tensors(partitions[i].get_out_ports(), c_partitions[i], id_to_queried_logical_tensors); std::cout << "Creating tensors and allocating memory buffer--"; std::vector<tensor> input_ts = tm.construct_and_initialize_tensors(inputs, c_partitions[i], e, 1); std::vector<tensor> output_ts = tm.construct_and_initialize_tensors(outputs, c_partitions[i], e, 0); std::cout << "Success!\n"; std::cout << "Executing compiled partition-------------------"; /// execute the compiled partition c_partitions[i].execute(s, input_ts, output_ts); std::cout << "Success!\n"; } else { std::vector<size_t> unsupported_op_ids = partitions[i].get_ops(); assertm(unsupported_op_ids.size() == 1, "Unsupported partition only " "contains single op."); if (op_id_kind_map[unsupported_op_ids[0]] == op::kind::Wildcard) { std::cout << "\nWarning (actually an error): partition " << partitions[i].get_id() << " contains only a Wildcard op which cannot be computed.\n"; } else { /// Users need to write implementation code by themselves. continue; } } } // Step 6: Check correctness of the output results std::cout << "Check correctness------------------------------"; float expected_result = (1 * 11 * 11 * 3 + /* conv0 bias */ 1.0f) * (1 * 1 * 96) + /* conv1 bias */ 1.0f; float *actual_output_ptr = tm.get(relu1_dst_desc.get_id()).get_data_handle<float>(); auto output_dims = relu1_dst_desc.get_dims(); auto num_elem = product(output_dims); std::vector<float> expected_output(num_elem, expected_result); compare_data(expected_output.data(), actual_output_ptr, num_elem); std::cout << "Success!\n"; std::cout << "============Run Example Successfully===========\n"; return 0; } // clang-format on
44.995434
125
0.64177
wuxun-zhang
e4d37b930e653a6b1d18d6d34e2533f35f7a1de8
3,907
cpp
C++
LightOJ/1263 - Equalizing Money.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
2
2019-11-10T18:42:11.000Z
2020-07-04T07:05:22.000Z
LightOJ/1263 - Equalizing Money.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
null
null
null
LightOJ/1263 - Equalizing Money.cpp
shamiul94/Problem-Solving-Online-Judges
0387ccd02cc692c70429b4683311070dc9d69b28
[ "MIT" ]
1
2019-11-04T11:05:17.000Z
2019-11-04T11:05:17.000Z
/* @author - Rumman BUET CSE'15 */ #include <bits/stdc++.h> #include<vector> #define ll long long int #define ull unsigned long long #define ld long double #define ff first #define ss second #define fi freopen("in.txt", "r", stdin) #define fo freopen("out.txt", "w", stdout) #define m0(a) memset(a , 0 , sizeof(a)) #define m1(a) memset(a , -1 , sizeof(a)) #define pi acos(-1.0) #define debug printf("yes\n") #define what_is(x) cout << #x << " is " << x << endl #define pf printf #define sf scanf #define pb push_back #define mp make_pair #define eb emplace_back #define pii pair<int, int> #define piii pair<pii, int> #define SQR(a) ((a)*(a)) #define QUBE(a) ((a)*(a)*(a)) #define scanI(a) scanf("%d",&a) #define scanI2(a, b) scanI(a) , scanI(b) #define scanI3(a, b, c) scanI(a), scanI(b), scanI(c) #define scanI4(a, b, c, d) scanI(a), scanI(b), scanI(c), scanI(d) #define sll(a) scanf("%lld",&a) #define sll2(a, b) sll(a) , sll(b) #define sll3(a, b, c) sll(a), sll(b), sll(c) #define sll4(a, b, c, d) sll(a), sll(b), sll(c), sll(d) #define inf LLONG_MAX #define minf LLONG_MIN #define min3(a, b, c) min(a,min(b,c)) #define max3(a, b, c) max(a,max(b,c)) #define ones(mask) __builtin_popcount(mask) #define mx 150000 #define Black 1 #define White 2 #define Grey 3 using namespace std; vector<ll> v[1002]; ll money[1002]; ll edgeNo, nodeNo; ll color[1002]; ll K; ll dfsUtil(ll u) { // cout << "u: " << u << endl ; color[u] = Black; bool isLeft = false; ll ret = 0; for (ll i = 0; i < v[u].size(); i++) { if (color[v[u][i]] == White) { isLeft = true; ret += dfsUtil(v[u][i]); K++; } } ret += money[u]; color[u] = Black; return ret; } void dfs() { for (ll i = 0; i < 1002; i++) { color[i] = White; } ll sum = 0, ans = -1; for (ll i = 1; i <= nodeNo; i++) { if (color[i] == White) { K = 0; sum = dfsUtil(i); K++; // cout <<sum << " " << K << endl ; if (sum % K == 0) { if (i == 1) { ans = sum / K; } else { ll t; t = sum / K; if (t != ans) { cout << "No" << endl; return; } } } else { cout << "No" << endl; return; } } } cout << "Yes" << endl; return; } int main() { // fi ; // fo ; ll T, t = 0; scanf("%lld", &T); while (T--) { t++; sll2(nodeNo, edgeNo); for (ll i = 1; i <= nodeNo; i++) { sll(money[i]); } for (ll i = 0; i < edgeNo; i++) { ll u, w; sll2(u, w); v[u].pb(w); v[w].pb(u); } printf("Case %lld: ", t); dfs(); for (ll i = 0; i < 1002; i++) { v[i].clear(); } } return 0; }
24.727848
89
0.349885
shamiul94
e4d467001f65780d3ed0efad45aa085edcb6de30
7,144
cc
C++
camera/hal_adapter/frame_number_mapper.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal_adapter/frame_number_mapper.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal_adapter/frame_number_mapper.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright 2020 The Chromium OS 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 "hal_adapter/frame_number_mapper.h" #include <algorithm> #include <utility> #include "cros-camera/common.h" namespace cros { FrameNumberMapper::FrameNumberMapper() : next_frame_number_(0) {} uint32_t FrameNumberMapper::GetHalFrameNumber(uint32_t framework_frame_number) { base::AutoLock l(frame_number_lock_); uint32_t hal_frame_number = std::max(framework_frame_number, next_frame_number_); frame_number_map_[hal_frame_number] = framework_frame_number; next_frame_number_ = hal_frame_number + 1; return hal_frame_number; } uint32_t FrameNumberMapper::GetFrameworkFrameNumber(uint32_t hal_frame_number) { base::AutoLock l(frame_number_lock_); auto it = frame_number_map_.find(hal_frame_number); return it != frame_number_map_.end() ? it->second : 0; } bool FrameNumberMapper::IsAddedFrame(uint32_t hal_frame_number) { base::AutoLock l(added_frame_numbers_lock_); return added_frame_numbers_.find(hal_frame_number) != added_frame_numbers_.end(); } void FrameNumberMapper::RegisterCaptureRequest( const camera3_capture_request_t* request, bool is_request_split, bool is_request_added) { { base::AutoLock l(pending_result_status_lock_); ResultStatus status{ .has_pending_input_buffer = request->input_buffer != nullptr, .num_pending_output_buffers = request->num_output_buffers, .has_pending_result = true}; pending_result_status_[request->frame_number] = std::move(status); } if (is_request_split) { base::AutoLock l(request_streams_map_lock_); auto& streams = request_streams_map_[request->frame_number]; streams.resize(request->num_output_buffers); for (size_t i = 0; i < request->num_output_buffers; ++i) { streams[i] = request->output_buffers[i].stream; } } if (is_request_added) { base::AutoLock l(added_frame_numbers_lock_); added_frame_numbers_.insert(request->frame_number); } } void FrameNumberMapper::RegisterCaptureResult( const camera3_capture_result_t* result, int32_t partial_result_count) { base::AutoLock l(pending_result_status_lock_); auto it = pending_result_status_.find(result->frame_number); if (it == pending_result_status_.end()) { LOGF(ERROR) << "This result wasn't registered in frame number mapper"; return; } // Update the status of this result. ResultStatus& status = it->second; if (result->partial_result == partial_result_count) { status.has_pending_result = false; } status.num_pending_output_buffers -= result->num_output_buffers; if (result->input_buffer) { status.has_pending_input_buffer = false; } // See if we can remove the frame number mapping of this frame. if (!status.has_pending_result && status.num_pending_output_buffers == 0 && !status.has_pending_input_buffer) { FinishHalFrameNumber(result->frame_number); pending_result_status_.erase(it); } } void FrameNumberMapper::PreprocessNotifyMsg( const camera3_notify_msg_t* msg, std::vector<camera3_notify_msg_t>* msgs, camera3_stream_t* zsl_stream) { if (msg->type == CAMERA3_MSG_SHUTTER) { const camera3_shutter_msg_t& shutter = msg->message.shutter; if (!IsAddedFrame(shutter.frame_number)) { msgs->push_back(*msg); msgs->back().message.shutter.frame_number = GetFrameworkFrameNumber(shutter.frame_number); } } else if (msg->type == CAMERA3_MSG_ERROR) { const camera3_error_msg_t& error = msg->message.error; auto MarkResultReady = [&]() { base::AutoLock l(pending_result_status_lock_); auto it = pending_result_status_.find(error.frame_number); if (it != pending_result_status_.end()) { auto& status = it->second; status.has_pending_result = false; if (!status.has_pending_result && status.num_pending_output_buffers == 0 && !status.has_pending_input_buffer) { FinishHalFrameNumber(error.frame_number); } } }; uint32_t framework_frame_number = error.frame_number == 0 ? 0 : GetFrameworkFrameNumber(error.frame_number); if (!IsRequestSplit(error.frame_number)) { if (error.error_code == CAMERA3_MSG_ERROR_REQUEST || error.error_code == CAMERA3_MSG_ERROR_RESULT) { MarkResultReady(); } if (error.error_code == CAMERA3_MSG_ERROR_BUFFER && error.error_stream == zsl_stream) { LOGF(ERROR) << "HAL fails to fill in ZSL output buffer!"; } else { msgs->push_back(*msg); msgs->back().message.error.frame_number = framework_frame_number; } return; } auto ConvertToMsgErrorBuffer = [&](camera3_stream_t* stream) { if (stream != zsl_stream) { camera3_notify_msg_t msg{ .type = CAMERA3_MSG_ERROR, .message.error = {.frame_number = framework_frame_number, .error_stream = stream, .error_code = CAMERA3_MSG_ERROR_BUFFER}}; msgs->push_back(std::move(msg)); } }; auto ConvertToMsgErrorResult = [&]() { MarkResultReady(); camera3_notify_msg_t msg{ .type = CAMERA3_MSG_ERROR, .message.error = {.frame_number = framework_frame_number, .error_stream = nullptr, .error_code = CAMERA3_MSG_ERROR_RESULT}}; msgs->push_back(std::move(msg)); }; switch (error.error_code) { case CAMERA3_MSG_ERROR_DEVICE: DCHECK_EQ(msg->message.error.frame_number, 0); msgs->push_back(*msg); break; case CAMERA3_MSG_ERROR_REQUEST: { base::AutoLock l(request_streams_map_lock_); const std::vector<camera3_stream_t*>& streams = request_streams_map_[error.frame_number]; for (camera3_stream_t* stream : streams) { ConvertToMsgErrorBuffer(stream); } if (!IsAddedFrame(error.frame_number)) { ConvertToMsgErrorResult(); } } break; case CAMERA3_MSG_ERROR_RESULT: if (!IsAddedFrame(error.frame_number)) { ConvertToMsgErrorResult(); } break; case CAMERA3_MSG_ERROR_BUFFER: ConvertToMsgErrorBuffer(error.error_stream); break; } } } void FrameNumberMapper::FinishHalFrameNumber(uint32_t hal_frame_number) { { base::AutoLock frame_number_lock(frame_number_lock_); base::AutoLock added_frame_numbers_lock(added_frame_numbers_lock_); frame_number_map_.erase(hal_frame_number); added_frame_numbers_.erase(hal_frame_number); } { base::AutoLock request_streams_map_lock(request_streams_map_lock_); request_streams_map_.erase(hal_frame_number); } } bool FrameNumberMapper::IsRequestSplit(uint32_t hal_frame_number) { base::AutoLock l(request_streams_map_lock_); return request_streams_map_.find(hal_frame_number) != request_streams_map_.end(); } } // namespace cros
35.192118
80
0.69051
strassek
e4d68f2a64ee23cc1e0872e66256c4296e3763b9
4,825
cpp
C++
source/FAST/Algorithms/CoherentPointDrift/Affine.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Algorithms/CoherentPointDrift/Affine.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Algorithms/CoherentPointDrift/Affine.cpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
#include "CoherentPointDrift.hpp" #include "Affine.hpp" #include <limits> #include <iostream> namespace fast { CoherentPointDriftAffine::CoherentPointDriftAffine() { mScale = 1.0; mTransformationType = TransformationType::AFFINE; } void CoherentPointDriftAffine::initializeVarianceAndMore() { // Initialize the variance in the CPD registration mVariance = ( (double)mNumMovingPoints * (mFixedPoints.transpose() * mFixedPoints).trace() + (double)mNumFixedPoints * (mMovingPoints.transpose() * mMovingPoints).trace() - 2.0 * mFixedPoints.colwise().sum() * mMovingPoints.colwise().sum().transpose() ) / (double)(mNumFixedPoints * mNumMovingPoints * mNumDimensions); mIterationError = mTolerance + 10.0; mObjectiveFunction = mObjectiveFunction = std::numeric_limits<double>::max(); mResponsibilityMatrix = MatrixXf::Zero(mNumMovingPoints, mNumFixedPoints); } void CoherentPointDriftAffine::maximization(Eigen::MatrixXf &fixedPoints, Eigen::MatrixXf &movingPoints) { double startM = omp_get_wtime(); // Define some useful matrix sums mPt1 = mResponsibilityMatrix.transpose().rowwise().sum(); // mNumFixedPoints x 1 mP1 = mResponsibilityMatrix.rowwise().sum(); // mNumMovingPoints x 1 mNp = mPt1.sum(); // 1 (sum of all P elements) double timeEndMUseful = omp_get_wtime(); // Estimate new mean vectors MatrixXf fixedMean = fixedPoints.transpose() * mPt1 / mNp; MatrixXf movingMean = movingPoints.transpose() * mP1 / mNp; // Center point sets around estimated mean MatrixXf fixedPointsCentered = fixedPoints - fixedMean.transpose().replicate(mNumFixedPoints, 1); MatrixXf movingPointsCentered = movingPoints - movingMean.transpose().replicate(mNumMovingPoints, 1); double timeEndMCenter = omp_get_wtime(); /* ********************************************************** * Find transformation parameters: affine matrix, translation * *********************************************************/ MatrixXf A = fixedPointsCentered.transpose() * mResponsibilityMatrix.transpose() * movingPointsCentered; MatrixXf YPY = movingPointsCentered.transpose() * mP1.asDiagonal() * movingPointsCentered; MatrixXf XPX = fixedPointsCentered.transpose() * mPt1.asDiagonal() * fixedPointsCentered; mAffineMatrix = A * YPY.inverse(); mTranslation = fixedMean - mAffineMatrix * movingMean; // Update variance MatrixXf ABt = A * mAffineMatrix.transpose(); mVariance = ( XPX.trace() - ABt.trace() ) / (mNp * mNumDimensions); if (mVariance < 0) { mVariance = std::fabs(mVariance); } else if (mVariance == 0){ mVariance = 10.0 * std::numeric_limits<double>::epsilon(); mRegistrationConverged = true; } double timeEndMParameters = omp_get_wtime(); /* **************** * Update transform * ***************/ Affine3f iterationTransform = Affine3f::Identity(); iterationTransform.translation() = Vector3f(mTranslation); iterationTransform.linear() = mAffineMatrix; Affine3f currentRegistrationTransform; MatrixXf registrationMatrix = iterationTransform.matrix() * mTransformation->get().matrix(); currentRegistrationTransform.matrix() = registrationMatrix; mTransformation->set(currentRegistrationTransform); /* ************************* * Transform the point cloud * ************************/ MatrixXf movingPointsTransformed = movingPoints * mAffineMatrix.transpose() + mTranslation.transpose().replicate(mNumMovingPoints, 1); movingPoints = movingPointsTransformed; /* ****************************************** * Calculate change in the objective function * *****************************************/ double objectiveFunctionOld = mObjectiveFunction; mObjectiveFunction = (XPX.trace() - 2 * ABt.trace() + YPY.trace() ) / (2 * mVariance) + (mNp * mNumDimensions)/2 * log(mVariance); mIterationError = std::fabs( (mObjectiveFunction - objectiveFunctionOld) / objectiveFunctionOld); mRegistrationConverged = mIterationError <= mTolerance; double endM = omp_get_wtime(); timeM += endM - startM; timeMUseful += timeEndMUseful - startM; timeMCenter += timeEndMCenter - timeEndMUseful; timeMParameters += timeEndMParameters - timeEndMCenter; timeMUpdate += endM - timeEndMParameters; } }
45.093458
115
0.606218
andreped
e4d8a4b4ae522fb1e9d698f91e4c41dc01fcbb26
2,137
cpp
C++
tc 160+/TheEquation.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/TheEquation.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/TheEquation.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; class TheEquation { public: int leastSum(int X, int Y, int P) { for (int sum=2; sum<=2*P; ++sum) { for (int a=1; a<sum; ++a) { int b = sum-a; if ((a*X + b*Y) % P == 0) { return sum; } } } return -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 2; int Arg1 = 6; int Arg2 = 5; int Arg3 = 3; verify_case(0, Arg3, leastSum(Arg0, Arg1, Arg2)); } void test_case_1() { int Arg0 = 5; int Arg1 = 5; int Arg2 = 5; int Arg3 = 2; verify_case(1, Arg3, leastSum(Arg0, Arg1, Arg2)); } void test_case_2() { int Arg0 = 998; int Arg1 = 999; int Arg2 = 1000; int Arg3 = 501; verify_case(2, Arg3, leastSum(Arg0, Arg1, Arg2)); } void test_case_3() { int Arg0 = 1; int Arg1 = 1; int Arg2 = 1000; int Arg3 = 1000; verify_case(3, Arg3, leastSum(Arg0, Arg1, Arg2)); } void test_case_4() { int Arg0 = 347; int Arg1 = 873; int Arg2 = 1000; int Arg3 = 34; verify_case(4, Arg3, leastSum(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TheEquation ___test; ___test.run_test(-1); } // END CUT HERE
37.491228
309
0.568086
ibudiselic
e4d95ee0ae960e5ddb81f748cace7a7a48447a93
4,147
cpp
C++
note_to_midi.cpp
jkhollandjr/music_generation
6338b2b05d2e739caa55eead041e6eef328a52ca
[ "MIT" ]
null
null
null
note_to_midi.cpp
jkhollandjr/music_generation
6338b2b05d2e739caa55eead041e6eef328a52ca
[ "MIT" ]
null
null
null
note_to_midi.cpp
jkhollandjr/music_generation
6338b2b05d2e739caa55eead041e6eef328a52ca
[ "MIT" ]
null
null
null
// note_to_midi.cpp // // Writes a midifile using the notes.txt file and the functions from the Midifile library. // // NOTE: This code has been adapted from an example provided by the Midifile library //The original code described how to create a track from arrays of integers corresponding to //the rythm and midi notes. // //Our specific contribution includes the input and output operator and separation of vector into //multiple other vectors, which are added to the musical tracks separately. We also created a method //of randomly generating the rythm, rather that hard-coding it. #include "MidiFile.h" #include <iostream> #include "std_lib_facilities.h" using namespace std; typedef unsigned char uchar; /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { MidiFile outputfile; // create an empty MIDI file with one track outputfile.absoluteTicks(); // time information stored as absolute time // (will be coverted to delta time when written) outputfile.addTrack(3); // Add another three tracks to the MIDI file vector<uchar> midievent; // temporary storage for MIDI events midievent.resize(3); // set the size of the array to 3 bytes int tpq = 120; // default value in MIDI file is 48 outputfile.setTicksPerQuarterNote(tpq); //input operates that reads in the notes from notes.txt, and sends them to a vector ifstream ist {"notes.txt"}; vector<int> note_values; int tmp; while (ist >> tmp) { note_values.push_back(tmp); } vector<int> voice1; vector<int> voice2; vector<int> voice3; //Vector of integers (notes) is split into three differet vectors, or "voices" such that every third //note is added to a specific vector, given different starting points for (unsigned i=2; i<note_values.size(); i+=3) voice1.push_back(note_values[i]); for (unsigned i=1; i<note_values.size(); i+=3) voice2.push_back(note_values[i]); for (unsigned i=0; i<note_values.size(); i+=3) voice3.push_back(note_values[i]); //vector will hold the rythm information vector<double> rhythm1(voice1.size()); vector<double> note_lengths{0.5, 1.0, 2.0}; for (unsigned i=0; i<rhythm1.size()-2; i++) rhythm1[i] = note_lengths[rand() % 2]; // randomly generate eight, quarter or half note rhythm1[rhythm1.size()-2] = 4.0; // end on whole note rhythm1[rhythm1.size()-1] = -1.0; // -1 to stop reading vector<double> rhythm2 = rhythm1; vector<double> rhythm3 = rhythm1; // store a melody line in track 1 (track 0 left empty for conductor info) int i=0; int actiontime = 0; // temporary storage for MIDI event time midievent[2] = 64; // store attack/release velocity for note command while (voice1[i] >= 0) { midievent[0] = 0x90; // store a note on command (MIDI channel 1) midievent[1] = voice1[i]; outputfile.addEvent(1, actiontime, midievent); actiontime += tpq * rhythm1[i]; midievent[0] = 0x80; // store a note on command (MIDI channel 1) outputfile.addEvent(1, actiontime, midievent); i++; } // store a base line in track 2 i=0; actiontime = 0; // reset time for beginning of file midievent[2] = 64; while (voice2[i] >= 0) { midievent[0] = 0x90; midievent[1] = voice2[i]; outputfile.addEvent(2, actiontime, midievent); actiontime += tpq * rhythm2[i]; midievent[0] = 0x80; outputfile.addEvent(2, actiontime, midievent); i++; } // store a base line in track 3 i=0; actiontime = 0; // reset time for beginning of file midievent[2] = 64; while (voice3[i] >= 0) { midievent[0] = 0x90; midievent[1] = voice3[i]; outputfile.addEvent(3, actiontime, midievent); actiontime += tpq * rhythm3[i]; midievent[0] = 0x80; outputfile.addEvent(3, actiontime, midievent); i++; } outputfile.sortTracks(); // make sure data is in correct order outputfile.write("song.mid"); // write Standard MIDI File return 0; }
36.377193
103
0.645768
jkhollandjr
e4db07f6f4cbb77264713f5e3e7f28ea0f20aefd
9,326
hpp
C++
include/ghex/transport_layer/ucx/context.hpp
tehrengruber/GHEX
f164bb625aaa106f77d31d45fce05c4711b066f0
[ "BSD-3-Clause" ]
null
null
null
include/ghex/transport_layer/ucx/context.hpp
tehrengruber/GHEX
f164bb625aaa106f77d31d45fce05c4711b066f0
[ "BSD-3-Clause" ]
null
null
null
include/ghex/transport_layer/ucx/context.hpp
tehrengruber/GHEX
f164bb625aaa106f77d31d45fce05c4711b066f0
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2020, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef INCLUDED_GHEX_TL_UCX_CONTEXT_HPP #define INCLUDED_GHEX_TL_UCX_CONTEXT_HPP #include "../context.hpp" #include "./communicator.hpp" #include "../communicator.hpp" #include "../util/pthread_spin_mutex.hpp" #ifdef GHEX_USE_PMI // use the PMI interface ... #include "./address_db_pmi.hpp" #else // ... and go to MPI if not available #include "./address_db_mpi.hpp" #endif #include "./address_db.hpp" namespace gridtools { namespace ghex { namespace tl { namespace ucx { struct transport_context { public: // member types using tag = ucx_tag; using rank_type = endpoint_t::rank_type; using worker_type = worker_t; using communicator_type = tl::communicator<communicator>; private: // member types using mutex_t = pthread_spin::recursive_mutex; struct ucp_context_h_holder { ucp_context_h m_context; ~ucp_context_h_holder() { ucp_cleanup(m_context); } }; using worker_vector = std::vector<std::unique_ptr<worker_type>>; private: // members MPI_Comm m_mpi_comm; const mpi::rank_topology& m_rank_topology; type_erased_address_db_t m_db; ucp_context_h_holder m_context; std::size_t m_req_size; std::unique_ptr<worker_type> m_worker; // shared, serialized - per rank worker_vector m_workers; // per thread mutex_t m_mutex; friend class worker_t; public: // dtor ~transport_context() { // ucp_worker_destroy should be called after a barrier // use MPI IBarrier and progress all workers MPI_Request req = MPI_REQUEST_NULL; int flag; MPI_Ibarrier(m_mpi_comm, &req); while(true) { // make communicators from workers and progress for (auto& w_ptr : m_workers) communicator_type{m_worker.get(), w_ptr.get()}.progress(); communicator_type{m_worker.get(), m_worker.get()}.progress(); MPI_Test(&req, &flag, MPI_STATUS_IGNORE); if(flag) break; } // close endpoints for (auto& w_ptr : m_workers) w_ptr->m_endpoint_cache.clear(); m_worker->m_endpoint_cache.clear(); // another MPI barrier to be sure MPI_Barrier(m_mpi_comm); } public: // ctors template<typename DB> transport_context(const mpi::rank_topology& t, DB&& db) : m_mpi_comm{t.mpi_comm()} , m_rank_topology{t} , m_db{std::forward<DB>(db)} { // read run-time context ucp_config_t* config_ptr; GHEX_CHECK_UCX_RESULT( ucp_config_read(NULL,NULL, &config_ptr) ); // set parameters ucp_params_t context_params; // define valid fields context_params.field_mask = UCP_PARAM_FIELD_FEATURES | // features UCP_PARAM_FIELD_REQUEST_SIZE | // size of reserved space in a non-blocking request UCP_PARAM_FIELD_TAG_SENDER_MASK | // mask which gets sender endpoint from a tag UCP_PARAM_FIELD_MT_WORKERS_SHARED | // multi-threaded context: thread safety UCP_PARAM_FIELD_ESTIMATED_NUM_EPS | // estimated number of endpoints for this context UCP_PARAM_FIELD_REQUEST_INIT ; // initialize request memory // features context_params.features = UCP_FEATURE_TAG ; // tag matching // additional usable request size context_params.request_size = request_data_size::value; // thread safety // this should be true if we have per-thread workers, // otherwise, if one worker is shared by all thread, it should be false // requires benchmarking. context_params.mt_workers_shared = true; // estimated number of connections // affects transport selection criteria and theresulting performance context_params.estimated_num_eps = m_db.est_size(); // mask // mask which specifies particular bits of the tag which can uniquely identify // the sender (UCP endpoint) in tagged operations. //context_params.tag_sender_mask = 0x00000000fffffffful; context_params.tag_sender_mask = 0xfffffffffffffffful; // needed to zero the memory region. Otherwise segfaults occured // when a std::function destructor was called on an invalid object context_params.request_init = &request_init; // initialize UCP GHEX_CHECK_UCX_RESULT( ucp_init(&context_params, config_ptr, &m_context.m_context) ); ucp_config_release(config_ptr); // check the actual parameters ucp_context_attr_t attr; attr.field_mask = UCP_ATTR_FIELD_REQUEST_SIZE | // internal request size UCP_ATTR_FIELD_THREAD_MODE; // thread safety ucp_context_query(m_context.m_context, &attr); m_req_size = attr.request_size; if (attr.thread_mode != UCS_THREAD_MODE_MULTI) throw std::runtime_error("ucx cannot be used with multi-threaded context"); // make shared worker // use single-threaded UCX mode, as per developer advice // https://github.com/openucx/ucx/issues/4609 m_worker.reset(new worker_type{get(), m_db, m_mutex, UCS_THREAD_MODE_SINGLE, m_rank_topology}); // intialize database m_db.init(m_worker->address()); } MPI_Comm mpi_comm() const noexcept { return m_mpi_comm; } communicator_type get_serial_communicator() { return {m_worker.get(),m_worker.get()}; } communicator_type get_communicator() { std::lock_guard<mutex_t> lock(m_mutex); // we need to guard only the insertion in the vector, // but this is not a performance critical section m_workers.push_back(std::make_unique<worker_type>(get(), m_db, m_mutex, UCS_THREAD_MODE_SERIALIZED, m_rank_topology)); return {m_worker.get(), m_workers[m_workers.size()-1].get()}; } rank_type rank() const { return m_db.rank(); } rank_type size() const { return m_db.size(); } ucp_context_h get() const noexcept { return m_context.m_context; } }; } // namespace ucx template<> struct context_factory<ucx_tag> { using context_type = context<ucx::transport_context>; static std::unique_ptr<context_type> create(MPI_Comm comm) { auto new_comm = detail::clone_mpi_comm(comm); #if defined GHEX_USE_PMI ucx::address_db_pmi addr_db{new_comm}; #else ucx::address_db_mpi addr_db{new_comm}; #endif return std::unique_ptr<context_type>{ new context_type{new_comm, std::move(addr_db)}}; } }; } // namespace tl } // namespace ghex } // namespace gridtools #endif /* INCLUDED_GHEX_TL_UCX_CONTEXT_HPP */
45.715686
142
0.493245
tehrengruber
e4dbf2380423572379b034bef8fbdc3c7d77fd67
33,603
cc
C++
chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 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/macros.h" #include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" #include "chrome/browser/ui/views/payments/payment_request_browsertest_base.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/credit_card.h" #include "components/payments/core/journey_logger.h" #include "content/public/test/browser_test_utils.h" namespace payments { class PaymentRequestJourneyLoggerSelectedPaymentInstrumentTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerSelectedPaymentInstrumentTest() : PaymentRequestBrowserTestBase( "/payment_request_no_shipping_test.html") {} private: DISALLOW_COPY_AND_ASSIGN( PaymentRequestJourneyLoggerSelectedPaymentInstrumentTest); }; // Tests that the SelectedPaymentInstrument metrics is correctly logged when the // Payment Request is completed with a credit card. IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerSelectedPaymentInstrumentTest, TestSelectedPaymentMethod) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Complete the Payment Request. InvokePaymentRequestUI(); ResetEventObserver(DialogEvent::DIALOG_CLOSED); PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Initiated", 1, 1); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Shown", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.PayClicked", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.ReceivedInstrumentDetails", 1, 1); // Expect a credit card as the selected payment instrument in the metrics. histogram_tester.ExpectBucketCount( "PaymentRequest.SelectedPaymentMethod", JourneyLogger::SELECTED_PAYMENT_METHOD_CREDIT_CARD, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } class PaymentRequestJourneyLoggerNoSupportedPaymentMethodTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerNoSupportedPaymentMethodTest() : PaymentRequestBrowserTestBase("/payment_request_bobpay_test.html") {} private: DISALLOW_COPY_AND_ASSIGN( PaymentRequestJourneyLoggerNoSupportedPaymentMethodTest); }; IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerNoSupportedPaymentMethodTest, OnlyBobpaySupported) { base::HistogramTester histogram_tester; ResetEventObserver(DialogEvent::NOT_SUPPORTED_ERROR); content::WebContents* web_contents = GetActiveWebContents(); const std::string click_buy_button_js = "(function() { document.getElementById('buy').click(); })();"; ASSERT_TRUE(content::ExecuteScript(web_contents, click_buy_button_js)); WaitForObservedEvent(); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Initiated", 1, 1); histogram_tester.ExpectBucketCount( "PaymentRequest.CheckoutFunnel.NoShow", JourneyLogger::NOT_SHOWN_REASON_NO_SUPPORTED_PAYMENT_METHOD, 1); // Make sure that no events were logged. histogram_tester.ExpectTotalCount("PaymentRequest.Events", 0); } class PaymentRequestJourneyLoggerMultipleShowTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerMultipleShowTest() : PaymentRequestBrowserTestBase( "/payment_request_multiple_show_test.html") {} private: DISALLOW_COPY_AND_ASSIGN(PaymentRequestJourneyLoggerMultipleShowTest); }; IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerMultipleShowTest, ShowSameRequest) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Start a Payment Request. InvokePaymentRequestUI(); // Try to show it again. content::WebContents* web_contents = GetActiveWebContents(); const std::string click_buy_button_js = "(function() { document.getElementById('showAgain').click(); })();"; ASSERT_TRUE(content::ExecuteScript(web_contents, click_buy_button_js)); // Complete the original Payment Request. PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); // Trying to show the same request twice is not considered a concurrent // request. EXPECT_TRUE( histogram_tester.GetAllSamples("PaymentRequest.CheckoutFunnel.NoShow") .empty()); // Expect that other metrics were logged correctly. histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Initiated", 1, 1); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Shown", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.PayClicked", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.ReceivedInstrumentDetails", 1, 1); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Completed", 1, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerMultipleShowTest, StartNewRequest) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Start a Payment Request. InvokePaymentRequestUI(); // Get the dialog view of the first request, since the one cached for the // tests will be replaced by the second Payment Request. PaymentRequestDialogView* first_dialog_view = dialog_view(); // Try to show a second request. ResetEventObserver(DialogEvent::DIALOG_CLOSED); content::WebContents* web_contents = GetActiveWebContents(); const std::string click_buy_button_js = "(function() { document.getElementById('showSecondRequest').click(); " "})();"; ASSERT_TRUE(content::ExecuteScript(web_contents, click_buy_button_js)); WaitForObservedEvent(); // Complete the original Payment Request. PayWithCreditCardAndWait(base::ASCIIToUTF16("123"), first_dialog_view); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Initiated", 1, 2); histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Shown", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.PayClicked", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.CheckoutFunnel.ReceivedInstrumentDetails", 1, 1); // The metrics should show that the original Payment Request should be // completed and the second one should not have been shown. histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Completed", 1, 1); histogram_tester.ExpectBucketCount( "PaymentRequest.CheckoutFunnel.NoShow", JourneyLogger::NOT_SHOWN_REASON_CONCURRENT_REQUESTS, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } class PaymentRequestJourneyLoggerAllSectionStatsTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerAllSectionStatsTest() : PaymentRequestBrowserTestBase( "/payment_request_contact_details_and_free_shipping_test.html") {} private: DISALLOW_COPY_AND_ASSIGN(PaymentRequestJourneyLoggerAllSectionStatsTest); }; // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is completed. IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerAllSectionStatsTest, NumberOfSuggestionsShown_Completed) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // Complete the Payment Request. InvokePaymentRequestUI(); ResetEventObserver(DialogEvent::DIALOG_CLOSED); PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.Completed", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is aborted by the user. IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerAllSectionStatsTest, NumberOfSuggestionsShown_UserAborted) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // The user aborts the Payment Request. InvokePaymentRequestUI(); ClickOnCancel(); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.UserAborted", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 2, 1); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } class PaymentRequestJourneyLoggerNoShippingSectionStatsTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerNoShippingSectionStatsTest() : PaymentRequestBrowserTestBase( "/payment_request_contact_details_test.html") {} private: DISALLOW_COPY_AND_ASSIGN( PaymentRequestJourneyLoggerNoShippingSectionStatsTest); }; // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is completed. IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerNoShippingSectionStatsTest, NumberOfSuggestionsShown_Completed) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // Complete the Payment Request. InvokePaymentRequestUI(); ResetEventObserver(DialogEvent::DIALOG_CLOSED); PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.Completed", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2, 1); // There should be no log for shipping address since it was not requested. histogram_tester.ExpectTotalCount( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is aborted by the user. IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerNoShippingSectionStatsTest, NumberOfSuggestionsShown_UserAborted) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // The user aborts the Payment Request. InvokePaymentRequestUI(); ClickOnCancel(); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.UserAborted", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 2, 1); // There should be no log for shipping address since it was not requested. histogram_tester.ExpectTotalCount( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } class PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest() : PaymentRequestBrowserTestBase( "/payment_request_free_shipping_test.html") {} private: DISALLOW_COPY_AND_ASSIGN( PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest); }; // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is completed. IN_PROC_BROWSER_TEST_F( PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest, NumberOfSuggestionsShown_Completed) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // Complete the Payment Request. InvokePaymentRequestUI(); ResetEventObserver(DialogEvent::DIALOG_CLOSED); PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.Completed", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2, 1); // There should be no log for contact info since it was not requested. histogram_tester.ExpectTotalCount( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } // Tests that the correct number of suggestions shown for each section is logged // when a Payment Request is aborted by the user. IN_PROC_BROWSER_TEST_F( PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest, NumberOfSuggestionsShown_UserAborted) { base::HistogramTester histogram_tester; // Setup a credit card with an associated billing address. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Add another address. AddAutofillProfile(autofill::test::GetFullProfile2()); // The user aborts the Payment Request. InvokePaymentRequestUI(); ClickOnCancel(); // Expect the appropriate number of suggestions shown to be logged. histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.PaymentMethod.UserAborted", 1, 1); histogram_tester.ExpectUniqueSample( "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2, 1); // There should be no log for contact info since it was not requested. histogram_tester.ExpectTotalCount( "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } class PaymentRequestNotShownTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestNotShownTest() : PaymentRequestBrowserTestBase( "/payment_request_can_make_payment_metrics_test.html") {} private: DISALLOW_COPY_AND_ASSIGN(PaymentRequestNotShownTest); }; IN_PROC_BROWSER_TEST_F(PaymentRequestNotShownTest, OnlyNotShownMetricsLogged) { base::HistogramTester histogram_tester; // Initiate a Payment Request without showing it. ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "queryNoShow();")); // Navigate away to abort the Payment Request and trigger the logs. NavigateTo("/payment_request_email_test.html"); // Initiated should be logged. histogram_tester.ExpectUniqueSample("PaymentRequest.CheckoutFunnel.Initiated", 1, 1); // Show should not be logged. histogram_tester.ExpectTotalCount("PaymentRequest.CheckoutFunnel.Shown", 0); // Abort should not be logged. histogram_tester.ExpectTotalCount("PaymentRequest.CheckoutFunnel.Aborted", 0); // Some events should be logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); // Only USER_ABORTED should be logged. EXPECT_EQ(JourneyLogger::EVENT_USER_ABORTED, buckets[0].min); // Make sure that the metrics that required the Payment Request to be shown // are not logged. histogram_tester.ExpectTotalCount("PaymentRequest.SelectedPaymentMethod", 0); histogram_tester.ExpectTotalCount("PaymentRequest.RequestedInformation", 0); histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionAdds", 0); histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionChanges", 0); histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionEdits", 0); histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSuggestionsShown", 0); histogram_tester.ExpectTotalCount( "PaymentRequest.UserHadSuggestionsForEverything", 0); histogram_tester.ExpectTotalCount( "PaymentRequest.UserDidNotHaveSuggestionsForEverything", 0); histogram_tester.ExpectTotalCount( "PaymentRequest.UserHadInitialFormOfPayment", 0); histogram_tester.ExpectTotalCount( "PaymentRequest.UserHadSuggestionsForEverything", 0); } class PaymentRequestCompleteSuggestionsForEverythingTest : public PaymentRequestBrowserTestBase { protected: PaymentRequestCompleteSuggestionsForEverythingTest() : PaymentRequestBrowserTestBase("/payment_request_email_test.html") {} private: DISALLOW_COPY_AND_ASSIGN(PaymentRequestCompleteSuggestionsForEverythingTest); }; IN_PROC_BROWSER_TEST_F(PaymentRequestCompleteSuggestionsForEverythingTest, UserHadCompleteSuggestionsForEverything) { base::HistogramTester histogram_tester; // Add an address and a credit card on file. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // Visa. // Show a Payment Request. InvokePaymentRequestUI(); // Navigate away to abort the Payment Request and trigger the logs. NavigateTo("/payment_request_email_test.html"); // The fact that the user had a form of payment on file should be recorded. histogram_tester.ExpectUniqueSample( "PaymentRequest.UserHadCompleteSuggestionsForEverything." "EffectOnCompletion", JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1); histogram_tester.ExpectTotalCount( "PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything." "EffectOnCompletion", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } IN_PROC_BROWSER_TEST_F(PaymentRequestCompleteSuggestionsForEverythingTest, UserDidNotHaveCompleteSuggestionsForEverything_NoCard) { base::HistogramTester histogram_tester; // Add an address. AddAutofillProfile(autofill::test::GetFullProfile()); // Show a Payment Request. The user has no form of payment on file. InvokePaymentRequestUI(); // Navigate away to abort the Payment Request and trigger the logs. NavigateTo("/payment_request_email_test.html"); // The fact that the user had no form of payment on file should be recorded. histogram_tester.ExpectUniqueSample( "PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything." "EffectOnCompletion", JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1); histogram_tester.ExpectTotalCount( "PaymentRequest.UserHadCompleteSuggestionsForEverything." "EffectOnCompletion", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } IN_PROC_BROWSER_TEST_F( PaymentRequestCompleteSuggestionsForEverythingTest, UserDidNotHaveCompleteSuggestionsForEverything_CardNetworkNotSupported) { base::HistogramTester histogram_tester; // Add an address and an AMEX credit card on file. AMEX is not supported by // the merchant. autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); AddAutofillProfile(billing_address); autofill::CreditCard card = autofill::test::GetCreditCard2(); card.set_billing_address_id(billing_address.guid()); AddCreditCard(card); // AMEX. // Show a Payment Request. InvokePaymentRequestUI(); // Navigate away to abort the Payment Request and trigger the logs. NavigateTo("/payment_request_email_test.html"); // The fact that the user had no form of payment on file should be recorded. histogram_tester.ExpectUniqueSample( "PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything." "EffectOnCompletion", JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1); histogram_tester.ExpectTotalCount( "PaymentRequest.UserHadCompleteSuggestionsForEverything." "EffectOnCompletion", 0); // Make sure the correct events were logged. std::vector<base::Bucket> buckets = histogram_tester.GetAllSamples("PaymentRequest.Events"); ASSERT_EQ(1U, buckets.size()); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_SHOWN); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_PAY_CLICKED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_RECEIVED_INSTRUMENT_DETAILS); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_SKIPPED_SHOW); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED); EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT); EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS); } } // namespace payments
43.414729
80
0.761867
metux
e4df3e83d47f192904244429f38d862fe0e7860a
2,298
cpp
C++
projects/glview/ImageReader.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
projects/glview/ImageReader.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
projects/glview/ImageReader.cpp
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
#include "ImageReader.h" #include <iostream> #include <image/Image.h> //#include <image/codecs/GifImageCodec.h> #include <image/codecs/ImageCodec.h> #include <image/codecs/JasperImageCodec.h> #include <image/codecs/JpegImageCodec.h> #include <image/codecs/PngImageCodec.h> //#include <image/codecs/TiffImageCodec.h> #include <io/BufferedInputStream.h> #include <io/file/File.h> #include <io/file/FileInputStream.h> #include <lang/CleanUpObject.h> #include <util/profile/ProfileObject.h> std::string ImageReader::toLower(std::string &s) { char* buf = new char[s.length()]; s.copy(buf, s.length()); for(int i = 0; i < s.length(); i++) { buf[i] = tolower(buf[i]); } std::string r(buf, s.length()); delete[](buf); return(r); } bool ImageReader::matches(std::string filename, std::string pattern) { return filename.find(pattern) != std::string::npos; } Image* ImageReader::readImage(std::string fileName) throw (Exception) { ProfileObject profiler("ImageReader::readImage"); ImageCodec* codec = nullptr; std::string lowerCase = toLower(fileName); std::cout << "trying " << lowerCase << std::endl; if (matches(lowerCase, ".png")) { codec = new PngImageCodec(); } else if (matches(lowerCase, ".jpg") || matches(lowerCase, ".jpeg")) { codec = new JpegImageCodec(); } else if (matches(lowerCase, ".gif")) { //codec = new GifImageCodec(); } else if (matches(lowerCase, ".tif") || matches(lowerCase, ".tiff")) { // codec = new TiffImageCodec(); } else if (matches(lowerCase, ".jp2") || matches(lowerCase, ".jpc") || matches(lowerCase, ".bmp") || matches(lowerCase, ".pnm")) { codec = new JasperImageCodec(); } else { std::string errorMessage("cannot find a codec for the file: "); errorMessage += fileName; throw Exception(errorMessage, __FILE__, __LINE__); } if (codec == nullptr) { throw Exception("no codec found", __FILE__, __LINE__); } CleanUpObject<ImageCodec> codecCleaner(codec); FileInputStream fIn(fileName); BufferedInputStream bIn(&fIn, false, 2048); Image* res = codec->read(&bIn); fflush(stdout); return res; } Image* ImageReader::readImage(File* file) throw (Exception) { return ImageReader::readImage(file->getPathName()); }
31.916667
71
0.661445
gizmomogwai
e4dfcdb408a6511563513d8d2fc5c5bd91d7594a
153
cpp
C++
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/DrawClient/DrawClientHandlers/DrawCliSearchHandler.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/DrawClient/DrawClientHandlers/DrawCliSearchHandler.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/DrawClient/DrawClientHandlers/DrawCliSearchHandler.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// DrawCliSearchHandler.cpp : Implementation of CDrawCliSearchHandler #include "stdafx.h" #include "DrawCliSearchHandler.h" // CDrawCliSearchHandler
17
69
0.803922
alonmm
e4e7a6b3a29c08f5889648d77fc9759af4876987
1,605
cpp
C++
cpp/until20/usability_oo/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
2
2021-04-26T16:37:38.000Z
2022-03-15T01:26:19.000Z
cpp/until20/usability_oo/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
null
null
null
cpp/until20/usability_oo/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
1
2022-03-15T01:26:23.000Z
2022-03-15T01:26:23.000Z
#include <iostream> #include <map> class Base { public: int value1; int value2; Base() { value1 = 1; } Base(int value): Base() { value2 = value; } };; class SubClass: public Base { public: using Base::Base; }; struct Base1 { virtual void foo(int); }; struct SubClass1: Base1 { virtual void foo(int) override; // virtual void foo(float) override; }; struct Base2 { virtual void foo() final; }; struct SubClass2 final : Base2 {}; class Magic { public: Magic() = default; Magic& operator=(const Magic&) = delete; Magic(int magic_number); }; enum class new_enum : unsigned int { value1, value2, value3 = 100, value4 = 100 }; template <typename T> std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) { return stream << static_cast<typename std::underlying_type<T>::type>(e); } template <typename Key, typename Value, typename F> void update(std::map<Key, Value> &m, F foo) { for (auto&& [k, v] : m) { v = foo(k); } } int main() { Base b(2); std::cout << b.value2 << std::endl; std::cout << b.value2 << std::endl; SubClass s(3); std::cout << s.value1 << std::endl; std::cout << s.value2 << std::endl; if (new_enum::value3 == new_enum::value4) { std::cout << "new_enum::value3 == new_enum::value4" << std::endl; } std::cout << new_enum::value3 << std::endl; std::map<std::string, long long int> m{ {"a", 1 }, { "b", 2 }, { "c", 3 } }; update(m, [](std::string key) { return std::hash<std::string>{}(key); }); for (auto&& [key, value] : m) std::cout << key << ":" << value << std::endl; }
17.445652
113
0.615576
lonelyhentai
e4e87b70467b1fdafe15d0be6ea97ca016c6d9bb
2,343
cpp
C++
admin/activec/samples/fssnapin/src/fssnapin.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/samples/fssnapin/src/fssnapin.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/samples/fssnapin/src/fssnapin.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: fssnapin.cpp // //-------------------------------------------------------------------------- // fssnapin.cpp : Implementation of DLL Exports. // Note: Proxy/Stub Information // To build a separate proxy/stub DLL, // run nmake -f fssnapinps.mk in the project directory. #include "stdafx.h" #include "resource.h" #include "initguid.h" #include "CompData.h" #include "Compont.h" DECLARE_INFOLEVEL(FSSnapIn); CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_ComponentData, CComponentData) END_OBJECT_MAP() class CFssnapinApp : public CWinApp { public: virtual BOOL InitInstance(); virtual int ExitInstance(); }; CFssnapinApp theApp; extern long g_cookieCount = 0; BOOL CFssnapinApp::InitInstance() { _Module.Init(ObjectMap, m_hInstance); return CWinApp::InitInstance(); } int CFssnapinApp::ExitInstance() { _Module.Term(); Dbg(DEB_USER1, _T("Number of cookies leaked = %d\n"), g_cookieCount); ASSERT(g_cookieCount == 0); return CWinApp::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); return (AfxDllCanUnloadNow()==S_OK && _Module.GetLockCount()==0) ? S_OK : S_FALSE; } ///////////////////////////////////////////////////////////////////////////// // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _Module.GetClassObject(rclsid, riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib return _Module.RegisterServer(TRUE); } ///////////////////////////////////////////////////////////////////////////// // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { _Module.UnregisterServer(); return S_OK; }
24.925532
84
0.567648
npocmaka
e4e8b7e5c3e5aaa37cae4499fc20798cdd155638
3,084
cpp
C++
src/qt/qtbase/src/corelib/kernel/qcore_mac.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtbase/src/corelib/kernel/qcore_mac.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/corelib/kernel/qcore_mac.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <private/qcore_mac_p.h> #include <new> #include "qvarlengtharray.h" QT_BEGIN_NAMESPACE QString QCFString::toQString(CFStringRef str) { if(!str) return QString(); CFIndex length = CFStringGetLength(str); const UniChar *chars = CFStringGetCharactersPtr(str); if (chars) return QString(reinterpret_cast<const QChar *>(chars), length); QVarLengthArray<UniChar> buffer(length); CFStringGetCharacters(str, CFRangeMake(0, length), buffer.data()); return QString(reinterpret_cast<const QChar *>(buffer.constData()), length); } QCFString::operator QString() const { if (string.isEmpty() && type) const_cast<QCFString*>(this)->string = toQString(type); return string; } CFStringRef QCFString::toCFStringRef(const QString &string) { return CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(string.unicode()), string.length()); } QCFString::operator CFStringRef() const { if (!type) const_cast<QCFString*>(this)->type = toCFStringRef(string); return type; } QT_END_NAMESPACE
37.156627
95
0.694553
viewdy
e4eaf8b336af747dc1cce9408bb55237f8768dc3
2,322
cpp
C++
code-cpp/nloop-math-inc.cpp
att-circ-contrl/NeuroLoop
7847fcaa6237c406fbad879b10352618504613c9
[ "CC-BY-4.0" ]
1
2021-01-22T05:40:23.000Z
2021-01-22T05:40:23.000Z
code-cpp/nloop-math-inc.cpp
att-circ-contrl/NeuroLoop
7847fcaa6237c406fbad879b10352618504613c9
[ "CC-BY-4.0" ]
null
null
null
code-cpp/nloop-math-inc.cpp
att-circ-contrl/NeuroLoop
7847fcaa6237c406fbad879b10352618504613c9
[ "CC-BY-4.0" ]
null
null
null
// Attention Circuits Control Laboratory - NeuroLoop project // Miscellaneous math routines. // Written by Christopher Thomas. // Copyright (c) 2020 by Vanderbilt University. This work is licensed under // the Creative Commons Attribution 4.0 International License. // NOTE - Because this implements template code, it has to be included by // every file that instantiates templates. // Only one copy of each instantiated variant will actually be compiled; // extra copies get pruned at link-time. // // Functions // Single-sample function for fast modulo arithmetic of non-negative integers. // This tests for quotients up to (2^count)-1. // Division is expensive, especially in FPGAs, so for situations where we // know that the quotient is small, shift-and-subtract can be less // resource-intensive. // NOTE - We're counting on the compiler being smart enough to inline this. template <class datatype_t, int subcount> datatype_t nloop_FastModulo(datatype_t sample, datatype_t modulus) { int bitshift; datatype_t testval; // This will actually be pretty slow in software. We're using it to get a // 1:1 mapping between software and FPGA code. for (bitshift = subcount; bitshift > 0; bitshift--) { testval = modulus << (bitshift - 1); if (sample >= testval) sample -= testval; } return sample; } // Slice-based function for fast modulo arithmetic of non-negative integers. // This tests for quotients up to 2^(count-1). // Division is expensive, especially in FPGAs, so for situations where we // know that the quotient is small, shift-and-subtract can be less // resource-intensive. // Input and output may reference the same object. template <class datatype_t, int subcount, int bankcount, int chancount> void nloop_FastModulo_Bank( nloop_SampleSlice_t<datatype_t,bankcount,chancount> &indata, nloop_SampleSlice_t<datatype_t,bankcount,chancount> &moduli, nloop_SampleSlice_t<datatype_t,bankcount,chancount> &outdata ) { int bidx, cidx; for (bidx = 0; bidx < bankcount; bidx++) for (cidx = 0; cidx < chancount; cidx++) // NOTE - We're counting on the compiler inlining this, for speed. outdata.data[bidx][cidx] = nloop_FastModulo<datatype_t,subcount> (indata.data[bidx][cidx], moduli.data[bidx][cidx]); } // // This is the end of the file.
32.704225
78
0.736003
att-circ-contrl
e4eb1e58974ce0866109916f3ef05b2547491e0b
3,631
cpp
C++
src/saiga/vision/ceres/CeresBASmooth.cpp
muetimueti/saiga
32b54a8fc7b1251368e07e7d31c15ac90cee3b32
[ "MIT" ]
null
null
null
src/saiga/vision/ceres/CeresBASmooth.cpp
muetimueti/saiga
32b54a8fc7b1251368e07e7d31c15ac90cee3b32
[ "MIT" ]
null
null
null
src/saiga/vision/ceres/CeresBASmooth.cpp
muetimueti/saiga
32b54a8fc7b1251368e07e7d31c15ac90cee3b32
[ "MIT" ]
null
null
null
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "CeresBASmooth.h" #include "saiga/core/time/timer.h" #include "saiga/vision/ceres/CeresHelper.h" #include "saiga/vision/ceres/CeresKernel_BARS_Intr4.h" #include "saiga/vision/ceres/CeresKernel_BA_Intr4.h" #include "saiga/vision/ceres/CeresKernel_SmoothBA.h" #include "saiga/vision/ceres/local_parameterization_se3.h" #include "saiga/vision/scene/Scene.h" #include "ceres/ceres.h" #include "ceres/problem.h" #include "ceres/rotation.h" #include "ceres/solver.h" #define BA_AUTODIFF namespace Saiga { OptimizationResults CeresBASmooth::initAndSolve() { auto& scene = *_scene; SAIGA_OPTIONAL_BLOCK_TIMER(optimizationOptions.debugOutput); ceres::Problem::Options problemOptions; problemOptions.local_parameterization_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; problemOptions.cost_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; problemOptions.loss_function_ownership = ceres::DO_NOT_TAKE_OWNERSHIP; ceres::Problem problem(problemOptions); Sophus::test::LocalParameterizationSE3<false> camera_parameterization; for (size_t i = 0; i < scene.extrinsics.size(); ++i) { problem.AddParameterBlock(scene.extrinsics[i].se3.data(), 7, &camera_parameterization); if (scene.extrinsics[i].constant) problem.SetParameterBlockConstant(scene.extrinsics[i].se3.data()); } for (auto& wp : scene.worldPoints) { problem.AddParameterBlock(wp.p.data(), 3); problem.SetParameterBlockConstant(wp.p.data()); } ceres::HuberLoss lossFunctionMono(baOptions.huberMono); ceres::HuberLoss lossFunctionStereo(baOptions.huberStereo); int monoCount = 0; int stereoCount = 0; for (auto& img : scene.images) { for (auto& ip : img.stereoPoints) { if (!ip) continue; if (ip.depth > 0) { stereoCount++; } else { monoCount++; } } } std::vector<std::unique_ptr<CostBAMonoAnalytic>> monoCostFunctions; std::vector<std::unique_ptr<CostBAStereoAnalytic>> stereoCostFunctions; monoCostFunctions.reserve(monoCount); stereoCostFunctions.reserve(stereoCount); for (auto& img : scene.images) { auto& extr = scene.extrinsics[img.extr].se3; auto& camera = scene.intrinsics[img.intr]; for (auto& ip : img.stereoPoints) { if (!ip) continue; auto& wp = scene.worldPoints[ip.wp].p; double w = ip.weight * scene.scale(); auto cost_function = CostBAMono::create(camera, ip.point, w); ceres::LossFunction* lossFunction = baOptions.huberMono > 0 ? &lossFunctionMono : nullptr; problem.AddResidualBlock(cost_function, lossFunction, extr.data(), wp.data()); } } for (auto& sc : scene.smoothnessConstraints) { auto& p1 = scene.extrinsics[scene.images[sc.ex1].extr].se3; auto& p2 = scene.extrinsics[scene.images[sc.ex2].extr].se3; auto& p3 = scene.extrinsics[scene.images[sc.ex3].extr].se3; auto w = sc.weight; auto cost_function = CostSmoothBA::create(w); problem.AddResidualBlock(cost_function, nullptr, p1.data(), p2.data(), p3.data()); } ceres::Solver::Options ceres_options = make_options(optimizationOptions); OptimizationResults result = ceres_solve(ceres_options, problem); return result; } } // namespace Saiga
28.590551
108
0.658772
muetimueti
e4ef632c5fbb28cf6e555c09ea69f07b9c2937d2
54,810
cpp
C++
camera/hal/mediatek/mtkcam/drv/sensor/HalSensorList.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/mediatek/mtkcam/drv/sensor/HalSensorList.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/mediatek/mtkcam/drv/sensor/HalSensorList.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright (C) 2019 MediaTek 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. */ #define LOG_TAG "MtkCam/HalSensorList" #include <algorithm> #include <cctype> #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string> #include <vector> #include <mtkcam/utils/metadata/IMetadata.h> #include <mtkcam/utils/metadata/client/mtk_metadata_tag.h> #include <mtkcam/v4l2/IPCIHalSensor.h> #include <cutils/compiler.h> // for CC_LIKELY, CC_UNLIKELY #include "mtkcam/custom/mt8183/hal/inc/camera_custom_imgsensor_cfg.h" #include "mtkcam/drv/sensor/HalSensorList.h" #include "mtkcam/drv/sensor/img_sensor.h" #include "mtkcam/drv/sensor/MyUtils.h" #include <mtkcam/utils/TuningUtils/TuningPlatformInfo.h> #include <base/files/file_enumerator.h> #include <sys/ioctl.h> #include <linux/media.h> #include <linux/v4l2-subdev.h> #define MTK_SUB_IMGSENSOR #define MAX_ENTITY_CNT 255 #define MAIN_SENSOR_I2C_NUM 2 #define SUB_SENSOR_I2C_NUM 4 #ifdef USING_MTK_LDVT #include <uvvf.h> #endif using NSCam::IMetadata; using NSCam::SensorStaticInfo; using NSCamCustomSensor::CUSTOM_CFG; /****************************************************************************** * ******************************************************************************/ IHalSensorList* IHalSensorList::getInstance() { return HalSensorList::singleton(); } /****************************************************************************** * ******************************************************************************/ HalSensorList* HalSensorList::singleton() { static HalSensorList* inst = new HalSensorList(); return inst; } /****************************************************************************** * ******************************************************************************/ HalSensorList::HalSensorList() : IHalSensorList() {} /****************************************************************************** * ******************************************************************************/ static NSCam::NSSensorType::Type mapToSensorType( const IMAGE_SENSOR_TYPE sensor_type) { NSCam::NSSensorType::Type eSensorType; switch (sensor_type) { case IMAGE_SENSOR_TYPE_RAW: case IMAGE_SENSOR_TYPE_RAW8: case IMAGE_SENSOR_TYPE_RAW12: case IMAGE_SENSOR_TYPE_RAW14: eSensorType = NSCam::NSSensorType::eRAW; break; case IMAGE_SENSOR_TYPE_YUV: case IMAGE_SENSOR_TYPE_YCBCR: case IMAGE_SENSOR_TYPE_RGB565: case IMAGE_SENSOR_TYPE_RGB888: case IMAGE_SENSOR_TYPE_JPEG: eSensorType = NSCam::NSSensorType::eYUV; break; default: eSensorType = NSCam::NSSensorType::eRAW; break; } return eSensorType; } /****************************************************************************** * ******************************************************************************/ const char* HalSensorList::queryDevName() { return devName.c_str(); } int HalSensorList::queryP1NodeEntId() { return p1NodeEntId; } int HalSensorList::querySeninfEntId() { return seninfEntId; } int HalSensorList::querySensorEntId(MUINT const index) { if (index < IMGSENSOR_SENSOR_IDX_MAX_NUM) { return sensorEntId[index]; } else { return MFALSE; } } const char* HalSensorList::querySeninfSubdevName() { return seninfSubdevName.c_str(); } const char* HalSensorList::querySensorSubdevName(MUINT const index) { if (index < IMGSENSOR_SENSOR_IDX_MAX_NUM) { return sensorSubdevName[index].c_str(); } else { return NULL; } } int HalSensorList::querySeninfFd() { return seninfFd; } MVOID HalSensorList::setSeninfFd(int fd) { seninfFd = fd; } int HalSensorList::querySensorFd(MUINT const index) { if (index < IMGSENSOR_SENSOR_IDX_MAX_NUM) { return sensorFd[index]; } else { return -MFALSE; } } MVOID HalSensorList::setSensorFd(int fd, MUINT const index) { if (index < IMGSENSOR_SENSOR_IDX_MAX_NUM) { sensorFd[index] = fd; } } // ov5695 2-0036 (entity_name) // ov5695_mipi_raw (sensor_name) int findsensor(std::string entity_name, int* id) { int find_cnt; int ret = 0; std::string sensor_name; for (int i = 0; i < MAX_NUM_OF_SUPPORT_SENSOR; i++) { *id = getSensorListId(i); if (*id == 0) { break; } sensor_name = getSensorListName(i); find_cnt = sensor_name.find_first_of("_"); sensor_name = sensor_name.substr(0, find_cnt); // get sensor id string, the string in // sensor_name before "_" if (entity_name.find(sensor_name) != std::string::npos) { find_cnt = entity_name.find_first_of("-"); entity_name = entity_name.substr( find_cnt - 1, 1); // get i2c num, one char in entity_name before "-" ret = atoi(entity_name.c_str()); // return i2c num *id = getSensorListId(i); CAM_LOGI("%d 0x%x", ret, *id); break; } } return ret; } int HalSensorList::findSubdev(void) { struct media_device_info mdev_info; int findsensorif = 0; int findcamio = 0; std::string seninf_name("seninf"); std::string p1_node_name("mtk-cam-p1"); std::string entity_name; char subdev_name[32]; int rc = 0; int dev_fd = 0; int find_cnt; int id; int i2c_num; CAM_LOGI("[%s] start ", __FUNCTION__); const base::FilePath path("/dev/media?"); base::FileEnumerator enumerator(path.DirName(), false, base::FileEnumerator::FILES, path.BaseName().value()); while (!enumerator.Next().empty()) { int num_entities = 1; if (findsensorif && (sensor_nums == 2) && findcamio) break; const base::FileEnumerator::FileInfo info = enumerator.GetInfo(); const std::string name = info.GetName().value(); const base::FilePath target_path = path.DirName().Append(name); CAM_LOGI("[%s] media dev name [%s] ", __FUNCTION__, target_path.value().c_str()); dev_fd = open(target_path.value().c_str(), O_RDWR | O_NONBLOCK); if (dev_fd < 0) { CAM_LOGE("[%s] Open %s error, %d %s", __FUNCTION__, target_path.value().c_str(), errno, strerror(errno)); rc = -1; continue; } rc = ioctl(dev_fd, MEDIA_IOC_DEVICE_INFO, &mdev_info); if (rc < 0) { CAM_LOGD("MEDIA_IOC_DEVICE_INFO error, rc %d", rc); close(dev_fd); continue; } find_cnt = MAX_ENTITY_CNT; while (find_cnt) { struct media_entity_desc entity = {}; entity.id = num_entities++; find_cnt--; if (findsensorif && (sensor_nums == 2) && findcamio) { break; } rc = ioctl(dev_fd, MEDIA_IOC_ENUM_ENTITIES, &entity); if (rc < 0) { rc = 0; continue; } entity_name = entity.name; if (entity_name.find(p1_node_name) != std::string::npos && entity.type == MEDIA_ENT_T_V4L2_SUBDEV) { // tmp : force to user main sensor snprintf(subdev_name, sizeof(subdev_name), "/dev/char/%d:%d", entity.dev.major, entity.dev.minor); p1NodeName = subdev_name; CAM_LOGI("camio subdevname[%s]-(%d)", p1NodeName.c_str(), entity.id); findcamio = 1; p1NodeEntId = entity.id; } i2c_num = findsensor(entity_name, &id); int index = -1; if (i2c_num == MAIN_SENSOR_I2C_NUM) { index = 0; } else if (i2c_num == SUB_SENSOR_I2C_NUM) { index = 1; } if (index >= 0) { snprintf(subdev_name, sizeof(subdev_name), "/dev/char/%d:%d", entity.dev.major, entity.dev.minor); sensorSubdevName[index] = subdev_name; CAM_LOGI("sensor 0 subdevname[%s]-(%d) 0x%x", sensorSubdevName[0].c_str(), entity.id, id); sensor_nums++; sensorEntId[index] = entity.id; sensorId[index] = id; } if (entity_name.find(seninf_name) != std::string::npos) { snprintf(subdev_name, sizeof(subdev_name), "/dev/char/%d:%d", entity.dev.major, entity.dev.minor); seninfSubdevName = subdev_name; CAM_LOGI("seninf subdevname[%s]-(%d)", seninfSubdevName.c_str(), entity.id); devName = target_path.value(); CAM_LOGI("devName %s", devName.c_str()); seninfEntId = entity.id; findsensorif = 1; } } if (dev_fd >= 0) { close(dev_fd); } } CAM_LOGI("[%s] end ", __FUNCTION__); return rc; } MUINT HalSensorList::searchSensors() { std::unique_lock<std::mutex> lk(mEnumSensorMutex); CAM_LOGI("searchSensors"); findSubdev(); CAM_LOGI("sensor_nums %d", sensor_nums); if (sensor_nums == 0) return 0; #ifdef MTK_SUB_IMGSENSOR CAM_LOGD("impSearchSensor search to sub"); for (MUINT i = IMGSENSOR_SENSOR_IDX_MIN_NUM; i <= IMGSENSOR_SENSOR_IDX_SUB; i++) { #else CAM_LOGD("impSearchSensor search to main"); for (MUINT i = IMGSENSOR_SENSOR_IDX_MIN_NUM; i < IMGSENSOR_SENSOR_IDX_SUB; i++) { #endif // query sensorinfo querySensorInfo((IMGSENSOR_SENSOR_IDX)i); // fill in metadata buildSensorMetadata((IMGSENSOR_SENSOR_IDX)i); addAndInitSensorEnumInfo_Locked( (IMGSENSOR_SENSOR_IDX)i, mapToSensorType( (IMAGE_SENSOR_TYPE)getSensorType((IMGSENSOR_SENSOR_IDX)i)), reinterpret_cast<const char*>(getSensorName((IMGSENSOR_SENSOR_IDX)i))); } // If support SANDBOX, we have to saves SensorStaticInfo to IIPCHalSensorList // while the SensorStaticInfo has been updated. #ifdef MTKCAM_HAVE_SANDBOX_SUPPORT IIPCHalSensorListProv* pIPCHalSensorList = IIPCHalSensorListProv::getInstance(); if (CC_UNLIKELY(pIPCHalSensorList == nullptr)) { CAM_LOGE("IIPCHalSensorListProv is nullptr"); } else { for (size_t i = 0; i < mEnumSensorList.size(); i++) { const EnumInfo& info = mEnumSensorList[i]; // retrieve sensor static info, device id and type // and saves into IIPCIHalSensorList MUINT32 type = info.getSensorType(); MUINT32 deviceId = info.getDeviceId(); const SensorStaticInfo* staticInfo = gQuerySensorStaticInfo(static_cast<IMGSENSOR_SENSOR_IDX>(deviceId)); if (CC_UNLIKELY(staticInfo == nullptr)) { CAM_LOGW("no static info of sensor device %u", deviceId); continue; } pIPCHalSensorList->ipcSetSensorStaticInfo(i, type, deviceId, *staticInfo); pIPCHalSensorList->ipcSetStaticInfo(i, info.mMetadata); CAM_LOGD("IPCHalSensorList: sensor (idx,type,deviceid)=(%#x, %#x, %#x)", i, type, deviceId); } if (CC_UNLIKELY(mEnumSensorList.empty())) { CAM_LOGW("no enumerated sensor (mEnumSensorList.size() is 0)"); } } #endif return sensor_nums; } /****************************************************************************** * ******************************************************************************/ MUINT HalSensorList::queryNumberOfSensors() const { std::unique_lock<std::mutex> lk(mEnumSensorMutex); return sensor_nums; } /****************************************************************************** * ******************************************************************************/ IMetadata const& HalSensorList::queryStaticInfo(MUINT const index) const { EnumInfo const* pInfo = queryEnumInfoByIndex(index); MY_LOGF_IF(pInfo == NULL, "NULL EnumInfo for sensor %d", index); return pInfo->mMetadata; } /****************************************************************************** * ******************************************************************************/ char const* HalSensorList::queryDriverName(MUINT const index) const { EnumInfo const* pInfo = queryEnumInfoByIndex(index); MY_LOGF_IF(pInfo == NULL, "NULL EnumInfo for sensor %d", index); return (char const*)pInfo->getSensorDrvName().c_str(); } /****************************************************************************** * ******************************************************************************/ MUINT HalSensorList::queryType(MUINT const index) const { EnumInfo const* pInfo = queryEnumInfoByIndex(index); MY_LOGF_IF(pInfo == NULL, "NULL EnumInfo for sensor %d", index); return pInfo->getSensorType(); } /****************************************************************************** * ******************************************************************************/ MUINT HalSensorList::queryFacingDirection(MUINT const index) const { if (SensorStaticInfo const* p = querySensorStaticInfo(index)) { return p->facingDirection; } return 0; } /****************************************************************************** * ******************************************************************************/ MUINT HalSensorList::querySensorDevIdx(MUINT const index) const { const EnumInfo* pEnumInfo = queryEnumInfoByIndex(index); return (pEnumInfo) ? IMGSENSOR_SENSOR_IDX2DUAL(pEnumInfo->getDeviceId()) : 0; } /****************************************************************************** * ******************************************************************************/ SensorStaticInfo const* HalSensorList::gQuerySensorStaticInfo( IMGSENSOR_SENSOR_IDX sensorIDX) const { if (sensorIDX >= IMGSENSOR_SENSOR_IDX_MIN_NUM && sensorIDX < IMGSENSOR_SENSOR_IDX_MAX_NUM) { return &sensorStaticInfo[sensorIDX]; } else { CAM_LOGE("bad sensorDev:%#x", sensorIDX); return NULL; } } /****************************************************************************** * ******************************************************************************/ MVOID HalSensorList::querySensorStaticInfo( MUINT indexDual, SensorStaticInfo* pSensorStaticInfo) const { std::unique_lock<std::mutex> lk(mEnumSensorMutex); SensorStaticInfo const* pSensorInfo = gQuerySensorStaticInfo(IMGSENSOR_SENSOR_IDX_MAP(indexDual)); if (pSensorStaticInfo != NULL && pSensorInfo != NULL) { ::memcpy(pSensorStaticInfo, pSensorInfo, sizeof(SensorStaticInfo)); } } /****************************************************************************** * ******************************************************************************/ SensorStaticInfo const* HalSensorList::querySensorStaticInfo( MUINT const index) const { EnumInfo const* pEnumInfo = queryEnumInfoByIndex(index); if (!pEnumInfo) { CAM_LOGE("No EnumInfo for index:%d", index); return NULL; } std::unique_lock<std::mutex> lk(mEnumSensorMutex); return gQuerySensorStaticInfo((IMGSENSOR_SENSOR_IDX)pEnumInfo->getDeviceId()); } /****************************************************************************** * ******************************************************************************/ HalSensorList::OpenInfo::OpenInfo(MINT iRefCount, HalSensor* pHalSensor) : miRefCount(iRefCount), mpHalSensor(pHalSensor) {} /****************************************************************************** * ******************************************************************************/ MVOID HalSensorList::closeSensor(HalSensor* pHalSensor, char const* szCallerName) { std::unique_lock<std::mutex> lk(mOpenSensorMutex); #ifdef DEBUG_SENSOR_OPEN_CLOSE CAM_LOGD("caller =%s", szCallerName); #endif OpenList_t::iterator it = mOpenSensorList.begin(); for (; it != mOpenSensorList.end(); ++it) { if (pHalSensor == it->mpHalSensor) { #ifdef DEBUG_SENSOR_OPEN_CLOSE CAM_LOGD("closeSensor mpHalSensor : %p, pHalSensor = %p, refcnt= %d", it->mpHalSensor, pHalSensor, it->miRefCount); #endif // Last one reference ? if (1 == it->miRefCount) { CAM_LOGD("<%s> last user", (szCallerName ? szCallerName : "Unknown")); // remove from open list. mOpenSensorList.erase(it); // destroy and free this instance. pHalSensor->onDestroy(); delete pHalSensor; } return; } } CAM_LOGE("<%s> HalSensor:%p not exist", (szCallerName ? szCallerName : "Unknown"), pHalSensor); } /****************************************************************************** * ******************************************************************************/ HalSensor* HalSensorList::openSensor(vector<MUINT> const& vSensorIndex, char const* szCallerName) { std::unique_lock<std::mutex> lk(mOpenSensorMutex); #ifdef DEBUG_SENSOR_OPEN_CLOSE CAM_LOGD("caller =%s", szCallerName); #endif OpenList_t::iterator it = mOpenSensorList.begin(); for (; it != mOpenSensorList.end(); ++it) { if (it->mpHalSensor->isMatch(vSensorIndex)) { // The open list holds a created instance. // just increment reference count and return the instance. it->miRefCount++; #ifdef DEBUG_SENSOR_OPEN_CLOSE CAM_LOGD("openSensor mpHalSensor : %p,idx %d, %d, %d, refcnt %d", it->mpHalSensor, vSensorIndex[0], vSensorIndex[1], vSensorIndex[2], it->miRefCount); #endif return it->mpHalSensor; } } #ifdef DEBUG_SENSOR_OPEN_CLOSE CAM_LOGD( "new created vSensorIdx[0] = %d, vSensorIdx[1] = %d, vSensorIdx[2] = %d", vSensorIndex[0], vSensorIndex[1], vSensorIndex[2]); #endif // It does not exist in the open list. // We must create a new one and add it to open list. HalSensor* pHalSensor = NULL; pHalSensor = new HalSensor(); if (NULL != pHalSensor) { // onCreate callback if (!pHalSensor->onCreate(vSensorIndex)) { CAM_LOGE("HalSensor::onCreate"); delete pHalSensor; return NULL; } // push into open list (with ref. count = 1). mOpenSensorList.push_back(OpenInfo(1, pHalSensor)); CAM_LOGD("<%s> 1st user", (szCallerName ? szCallerName : "Unknown")); return pHalSensor; } MY_LOGF("<%s> Never Be Here...No memory ?", (szCallerName ? szCallerName : "Unknown")); return NULL; } /****************************************************************************** * ******************************************************************************/ IHalSensor* HalSensorList::createSensor(char const* szCallerName, MUINT const index) { std::unique_lock<std::mutex> lk(mEnumSensorMutex); vector<MUINT> vSensorIndex; vSensorIndex.push_back(index); return openSensor(vSensorIndex, szCallerName); } /****************************************************************************** * ******************************************************************************/ IHalSensor* HalSensorList::createSensor(char const* szCallerName, MUINT const uCountOfIndex, MUINT const* pArrayOfIndex) { std::unique_lock<std::mutex> lk(mEnumSensorMutex); MY_LOGF_IF(0 == uCountOfIndex || 0 == pArrayOfIndex, "<%s> Bad uCountOfIndex:%d pArrayOfIndex:%p", szCallerName, uCountOfIndex, pArrayOfIndex); vector<MUINT> vSensorIndex(pArrayOfIndex, pArrayOfIndex + uCountOfIndex); return openSensor(vSensorIndex, szCallerName); } /****************************************************************************** * ******************************************************************************/ HalSensorList::EnumInfo const* HalSensorList::queryEnumInfoByIndex( MUINT index) const { std::unique_lock<std::mutex> lk(mEnumSensorMutex); if (index >= mEnumSensorList.size()) { CAM_LOGE("bad sensorIdx:%d >= size:%zu", index, mEnumSensorList.size()); return NULL; } return &mEnumSensorList[index]; } /****************************************************************************** * ******************************************************************************/ HalSensorList::EnumInfo const* HalSensorList::addAndInitSensorEnumInfo_Locked( IMGSENSOR_SENSOR_IDX eSensorDev, MUINT eSensorType, const char* szSensorDrvName) { mEnumSensorList.push_back(EnumInfo()); EnumInfo& rEnumInfo = mEnumSensorList.back(); std::string drvName; rEnumInfo.setDeviceId(eSensorDev); rEnumInfo.setSensorType(eSensorType); drvName.append("SENSOR_DRVNAME_"); drvName.append(szSensorDrvName); // toUpper std::transform(drvName.begin(), drvName.end(), drvName.begin(), ::toupper); rEnumInfo.setSensorDrvName(drvName); buildStaticInfo(rEnumInfo, &(rEnumInfo.mMetadata)); return &rEnumInfo; } /****************************************************************************** * ******************************************************************************/ IMAGE_SENSOR_TYPE getType(MUINT8 dataFmt) { if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW_R) { return IMAGE_SENSOR_TYPE_RAW; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW8_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW8_R) { return IMAGE_SENSOR_TYPE_RAW8; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_UYVY && dataFmt <= SENSOR_OUTPUT_FORMAT_YVYU) { return IMAGE_SENSOR_TYPE_YUV; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_CbYCrY && dataFmt <= SENSOR_OUTPUT_FORMAT_YCrYCb) { return IMAGE_SENSOR_TYPE_YCBCR; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW_RWB_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW_RWB_R) { return IMAGE_SENSOR_TYPE_RAW; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW_4CELL_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW_4CELL_R) { return IMAGE_SENSOR_TYPE_RAW; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_R) { return IMAGE_SENSOR_TYPE_RAW; } else if (dataFmt >= SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_B && dataFmt <= SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_R) { return IMAGE_SENSOR_TYPE_RAW; } else if (dataFmt == SENSOR_OUTPUT_FORMAT_RAW_MONO) { return IMAGE_SENSOR_TYPE_RAW; } return IMAGE_SENSOR_TYPE_UNKNOWN; } struct imgsensor_info_struct* HalSensorList::getSensorInfo( IMGSENSOR_SENSOR_IDX idx) { MUINT32 sensor_id; struct imgsensor_info_struct* info; int i, num; if (idx >= IMGSENSOR_SENSOR_IDX_MAX_NUM) { return NULL; } sensor_id = sensorId[idx]; num = getNumOfSupportSensor(); CAM_LOGI("Support sensor num %d", num); for (i = 0; i < num; i++) { info = getImgsensorInfo(i); if (sensor_id == info->sensor_id) { CAM_LOGI("info %d %d 0x%x", idx, i, sensor_id); return info; } } return NULL; } MUINT32 HalSensorList::getSensorType(IMGSENSOR_SENSOR_IDX idx) { MUINT32 sensor_id; struct imgsensor_info_struct* info; int i, num; if (idx >= IMGSENSOR_SENSOR_IDX_MAX_NUM) { return IMAGE_SENSOR_TYPE_UNKNOWN; } sensor_id = sensorId[idx]; num = getNumOfSupportSensor(); for (i = 0; i < num; i++) { info = getImgsensorInfo(i); if (sensor_id == info->sensor_id) { CAM_LOGI("type %d %d 0x%x", idx, i, sensor_id); return getImgsensorType(i); } } return IMAGE_SENSOR_TYPE_UNKNOWN; } const char* HalSensorList::getSensorName(IMGSENSOR_SENSOR_IDX idx) { MUINT32 sensor_id; struct IMGSENSOR_SENSOR_LIST* psensor_list; int i, num; if (idx >= IMGSENSOR_SENSOR_IDX_MAX_NUM) { return NULL; } sensor_id = sensorId[idx]; num = getNumOfSupportSensor(); for (i = 0; i < num; i++) { psensor_list = getSensorList(i); if (sensor_id == psensor_list->id) { CAM_LOGI("sensorName %d %d %s", idx, i, psensor_list->name); return reinterpret_cast<char*>(psensor_list->name); } } return NULL; } SENSOR_WINSIZE_INFO_STRUCT* HalSensorList::getWinSizeInfo( IMGSENSOR_SENSOR_IDX idx, MUINT32 scenario) const { MUINT32 sensor_id; struct imgsensor_info_struct* info; int i, num; if (idx >= IMGSENSOR_SENSOR_IDX_MAX_NUM) { return NULL; } sensor_id = sensorId[idx]; num = getNumOfSupportSensor(); for (i = 0; i < num; i++) { info = getImgsensorInfo(i); if (sensor_id == info->sensor_id) { CAM_LOGI("win size %d %d 0x%x", idx, i, sensor_id); return getImgWinSizeInfo(i, scenario); } } return NULL; } MVOID HalSensorList::querySensorInfo(IMGSENSOR_SENSOR_IDX idx) { SensorStaticInfo* pSensorStaticInfo; if (idx >= IMGSENSOR_SENSOR_IDX_MAX_NUM) { return; } pSensorStaticInfo = &sensorStaticInfo[idx]; CUSTOM_CFG* pCustomCfg = NSCamCustomSensor::getCustomConfig(idx); struct imgsensor_info_struct* pImgsensorInfo = getSensorInfo(idx); if (pImgsensorInfo == NULL) { CAM_LOGE("querySensorInfo fail, cannot get sensor info"); return; } pSensorStaticInfo->sensorDevID = pImgsensorInfo->sensor_id; pSensorStaticInfo->orientationAngle = pCustomCfg->orientation; pSensorStaticInfo->facingDirection = pCustomCfg->dir; pSensorStaticInfo->horizontalViewAngle = pCustomCfg->horizontalFov; pSensorStaticInfo->verticalViewAngle = pCustomCfg->verticalFov; pSensorStaticInfo->previewFrameRate = pImgsensorInfo->pre.max_framerate; pSensorStaticInfo->captureFrameRate = pImgsensorInfo->cap.max_framerate; pSensorStaticInfo->videoFrameRate = pImgsensorInfo->normal_video.max_framerate; pSensorStaticInfo->video1FrameRate = pImgsensorInfo->hs_video.max_framerate; pSensorStaticInfo->video2FrameRate = pImgsensorInfo->slim_video.max_framerate; pSensorStaticInfo->custom1FrameRate = pImgsensorInfo->custom1.max_framerate; pSensorStaticInfo->custom2FrameRate = pImgsensorInfo->custom2.max_framerate; pSensorStaticInfo->custom3FrameRate = pImgsensorInfo->custom3.max_framerate; pSensorStaticInfo->custom4FrameRate = pImgsensorInfo->custom4.max_framerate; pSensorStaticInfo->custom5FrameRate = pImgsensorInfo->custom5.max_framerate; switch (getType(pImgsensorInfo->sensor_output_dataformat)) { case IMAGE_SENSOR_TYPE_RAW: pSensorStaticInfo->sensorType = SENSOR_TYPE_RAW; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_10BIT; break; case IMAGE_SENSOR_TYPE_RAW8: pSensorStaticInfo->sensorType = SENSOR_TYPE_RAW; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_8BIT; break; case IMAGE_SENSOR_TYPE_RAW12: pSensorStaticInfo->sensorType = SENSOR_TYPE_RAW; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_12BIT; break; case IMAGE_SENSOR_TYPE_RAW14: pSensorStaticInfo->sensorType = SENSOR_TYPE_RAW; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_14BIT; break; case IMAGE_SENSOR_TYPE_YUV: case IMAGE_SENSOR_TYPE_YCBCR: pSensorStaticInfo->sensorType = SENSOR_TYPE_YUV; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_ERROR; break; case IMAGE_SENSOR_TYPE_RGB565: pSensorStaticInfo->sensorType = SENSOR_TYPE_RGB; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_ERROR; break; case IMAGE_SENSOR_TYPE_JPEG: pSensorStaticInfo->sensorType = SENSOR_TYPE_JPEG; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_ERROR; break; default: pSensorStaticInfo->sensorType = SENSOR_TYPE_UNKNOWN; pSensorStaticInfo->rawSensorBit = RAW_SENSOR_ERROR; break; } switch (pImgsensorInfo->sensor_output_dataformat) { case SENSOR_OUTPUT_FORMAT_RAW_B: case SENSOR_OUTPUT_FORMAT_RAW8_B: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; break; case SENSOR_OUTPUT_FORMAT_RAW_Gb: case SENSOR_OUTPUT_FORMAT_RAW8_Gb: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gb; break; case SENSOR_OUTPUT_FORMAT_RAW_Gr: case SENSOR_OUTPUT_FORMAT_RAW8_Gr: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gr; break; case SENSOR_OUTPUT_FORMAT_RAW_R: case SENSOR_OUTPUT_FORMAT_RAW8_R: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_R; break; case SENSOR_OUTPUT_FORMAT_UYVY: case SENSOR_OUTPUT_FORMAT_CbYCrY: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_UYVY; break; case SENSOR_OUTPUT_FORMAT_VYUY: case SENSOR_OUTPUT_FORMAT_CrYCbY: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_VYUY; break; case SENSOR_OUTPUT_FORMAT_YUYV: case SENSOR_OUTPUT_FORMAT_YCbYCr: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_YUYV; break; case SENSOR_OUTPUT_FORMAT_YVYU: case SENSOR_OUTPUT_FORMAT_YCrYCb: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_YVYU; break; case SENSOR_OUTPUT_FORMAT_RAW_RWB_B: pSensorStaticInfo->rawFmtType = SENSOR_RAW_RWB; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; break; case SENSOR_OUTPUT_FORMAT_RAW_RWB_Wb: pSensorStaticInfo->rawFmtType = SENSOR_RAW_RWB; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gb; break; case SENSOR_OUTPUT_FORMAT_RAW_RWB_Wr: pSensorStaticInfo->rawFmtType = SENSOR_RAW_RWB; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gr; break; case SENSOR_OUTPUT_FORMAT_RAW_RWB_R: pSensorStaticInfo->rawFmtType = SENSOR_RAW_RWB; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_R; break; case SENSOR_OUTPUT_FORMAT_RAW_MONO: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; pSensorStaticInfo->rawFmtType = SENSOR_RAW_MONO; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_B: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_Gb: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gb; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_Gr: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gr; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_R: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_R; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_B: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_HW_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_Gb: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_HW_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gb; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_Gr: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_HW_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gr; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_HW_BAYER_R: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_HW_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_R; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_B: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_B; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_Gb: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gb; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_Gr: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_Gr; break; case SENSOR_OUTPUT_FORMAT_RAW_4CELL_BAYER_R: pSensorStaticInfo->rawFmtType = SENSOR_RAW_4CELL_BAYER; pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_RAW_R; break; default: pSensorStaticInfo->sensorFormatOrder = SENSOR_FORMAT_ORDER_NONE; pSensorStaticInfo->rawFmtType = SENSOR_RAW_FMT_NONE; break; } pSensorStaticInfo->previewDelayFrame = pImgsensorInfo->pre_delay_frame; pSensorStaticInfo->captureDelayFrame = pImgsensorInfo->cap_delay_frame; pSensorStaticInfo->videoDelayFrame = pImgsensorInfo->video_delay_frame; pSensorStaticInfo->video1DelayFrame = pImgsensorInfo->hs_video_delay_frame; pSensorStaticInfo->video2DelayFrame = pImgsensorInfo->slim_video_delay_frame; pSensorStaticInfo->Custom1DelayFrame = 0; pSensorStaticInfo->Custom2DelayFrame = 0; pSensorStaticInfo->Custom3DelayFrame = 0; pSensorStaticInfo->Custom4DelayFrame = 0; pSensorStaticInfo->Custom5DelayFrame = 0; pSensorStaticInfo->aeShutDelayFrame = pImgsensorInfo->ae_shut_delay_frame; pSensorStaticInfo->aeSensorGainDelayFrame = pImgsensorInfo->ae_sensor_gain_delay_frame; pSensorStaticInfo->aeISPGainDelayFrame = pImgsensorInfo->ae_ispGain_delay_frame; pSensorStaticInfo->FrameTimeDelayFrame = 0; pSensorStaticInfo->SensorGrabStartX_PRV = 0; pSensorStaticInfo->SensorGrabStartY_PRV = 0; pSensorStaticInfo->SensorGrabStartX_CAP = 0; pSensorStaticInfo->SensorGrabStartY_CAP = 0; pSensorStaticInfo->SensorGrabStartX_VD = 0; pSensorStaticInfo->SensorGrabStartY_VD = 0; pSensorStaticInfo->SensorGrabStartX_VD1 = 0; pSensorStaticInfo->SensorGrabStartY_VD1 = 0; pSensorStaticInfo->SensorGrabStartX_VD2 = 0; pSensorStaticInfo->SensorGrabStartY_VD2 = 0; pSensorStaticInfo->SensorGrabStartX_CST1 = 0; pSensorStaticInfo->SensorGrabStartY_CST1 = 0; pSensorStaticInfo->SensorGrabStartX_CST2 = 0; pSensorStaticInfo->SensorGrabStartY_CST2 = 0; pSensorStaticInfo->SensorGrabStartX_CST3 = 0; pSensorStaticInfo->SensorGrabStartY_CST3 = 0; pSensorStaticInfo->SensorGrabStartX_CST4 = 0; pSensorStaticInfo->SensorGrabStartY_CST4 = 0; pSensorStaticInfo->SensorGrabStartX_CST5 = 0; pSensorStaticInfo->SensorGrabStartY_CST5 = 0; pSensorStaticInfo->iHDR_First_IS_LE = pImgsensorInfo->ihdr_le_firstline; pSensorStaticInfo->SensorModeNum = pImgsensorInfo->sensor_mode_num; pSensorStaticInfo->PerFrameCTL_Support = 0; pSensorStaticInfo->sensorModuleID = 0; pSensorStaticInfo->previewWidth = pImgsensorInfo->pre.grabwindow_width; pSensorStaticInfo->previewHeight = pImgsensorInfo->pre.grabwindow_height; pSensorStaticInfo->captureWidth = pImgsensorInfo->cap.grabwindow_width; pSensorStaticInfo->captureHeight = pImgsensorInfo->cap.grabwindow_height; pSensorStaticInfo->videoWidth = pImgsensorInfo->normal_video.grabwindow_width; pSensorStaticInfo->videoHeight = pImgsensorInfo->normal_video.grabwindow_height; pSensorStaticInfo->video1Width = pImgsensorInfo->hs_video.grabwindow_width; pSensorStaticInfo->video1Height = pImgsensorInfo->hs_video.grabwindow_height; pSensorStaticInfo->video2Width = pImgsensorInfo->slim_video.grabwindow_width; pSensorStaticInfo->video2Height = pImgsensorInfo->slim_video.grabwindow_height; pSensorStaticInfo->SensorCustom1Width = pImgsensorInfo->custom1.grabwindow_width; pSensorStaticInfo->SensorCustom1Height = pImgsensorInfo->custom1.grabwindow_height; pSensorStaticInfo->SensorCustom2Width = pImgsensorInfo->custom2.grabwindow_width; pSensorStaticInfo->SensorCustom2Height = pImgsensorInfo->custom2.grabwindow_height; pSensorStaticInfo->SensorCustom3Width = pImgsensorInfo->custom3.grabwindow_width; pSensorStaticInfo->SensorCustom3Height = pImgsensorInfo->custom3.grabwindow_height; pSensorStaticInfo->SensorCustom4Width = pImgsensorInfo->custom4.grabwindow_width; pSensorStaticInfo->SensorCustom4Height = pImgsensorInfo->custom4.grabwindow_height; pSensorStaticInfo->SensorCustom5Width = pImgsensorInfo->custom5.grabwindow_width; pSensorStaticInfo->SensorCustom5Height = pImgsensorInfo->custom5.grabwindow_height; } /****************************************************************************** * ******************************************************************************/ MVOID HalSensorList::buildSensorMetadata(IMGSENSOR_SENSOR_IDX idx) { MINT64 exposureTime1 = 0x4000; MINT64 exposureTime2 = 0x4000; MUINT8 u8Para = 0; MINT32 s32Para = 0; CAM_LOGD("impBuildSensorInfo start!"); IMetadata metadataA; SensorStaticInfo* pSensorStaticInfo = &sensorStaticInfo[idx]; { IMetadata::IEntry entryA(MTK_SENSOR_EXPOSURE_TIME); entryA.push_back(exposureTime1, Type2Type<MINT64>()); entryA.push_back(exposureTime2, Type2Type<MINT64>()); metadataA.update(MTK_SENSOR_EXPOSURE_TIME, entryA); } { IMetadata::IEntry entryA(MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION); MRect region1(MPoint(pSensorStaticInfo->captureHoizontalOutputOffset, pSensorStaticInfo->captureVerticalOutputOffset), MSize(pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight)); entryA.push_back(region1, Type2Type<MRect>()); metadataA.update(MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION, entryA); } { IMetadata::IEntry entryA(MTK_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT); switch (pSensorStaticInfo->sensorFormatOrder) { case SENSOR_FORMAT_ORDER_RAW_B: u8Para = 0x3; // BGGR break; case SENSOR_FORMAT_ORDER_RAW_Gb: u8Para = 0x2; // GBRG break; case SENSOR_FORMAT_ORDER_RAW_Gr: u8Para = 0x1; // GRBG break; case SENSOR_FORMAT_ORDER_RAW_R: u8Para = 0x0; // RGGB break; default: u8Para = 0x4; // BGR not bayer break; } entryA.push_back(u8Para, Type2Type<MUINT8>()); metadataA.update(MTK_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT, entryA); } { // need to add query from kernel IMetadata::IEntry entryA(MTK_SENSOR_INFO_PIXEL_ARRAY_SIZE); MSize Size1(pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight); entryA.push_back(Size1, Type2Type<MSize>()); metadataA.update(MTK_SENSOR_INFO_PIXEL_ARRAY_SIZE, entryA); } { // need to add query from kernel IMetadata::IEntry entryA(MTK_SENSOR_INFO_WHITE_LEVEL); switch (pSensorStaticInfo->rawSensorBit) { case RAW_SENSOR_8BIT: s32Para = 256; break; case RAW_SENSOR_10BIT: s32Para = 1024; break; case RAW_SENSOR_12BIT: s32Para = 4096; break; case RAW_SENSOR_14BIT: s32Para = 16384; break; default: s32Para = 256; break; } entryA.push_back(s32Para, Type2Type<MINT32>()); metadataA.update(MTK_SENSOR_INFO_WHITE_LEVEL, entryA); } { IMetadata::IEntry entryA(MTK_SENSOR_INFO_PACKAGE); { IMetadata metadataB; { IMetadata::IEntry entryB(MTK_SENSOR_INFO_SCENARIO_ID); entryB.push_back((MINT32)SENSOR_SCENARIO_ID_NORMAL_PREVIEW, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_SCENARIO_ID, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_FRAME_RATE); entryB.push_back((MINT32)pSensorStaticInfo->previewFrameRate, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_FRAME_RATE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE); MSize size1(pSensorStaticInfo->previewWidth, pSensorStaticInfo->previewHeight); entryB.push_back(size1, Type2Type<MSize>()); metadataB.update(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY); MRect region1(MPoint(0, 0), MSize(pSensorStaticInfo->previewWidth, pSensorStaticInfo->previewHeight)); entryB.push_back(region1, Type2Type<MRect>()); metadataB.update(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY, entryB); } entryA.push_back(metadataB, Type2Type<IMetadata>()); } { IMetadata metadataB; { IMetadata::IEntry entryB(MTK_SENSOR_INFO_SCENARIO_ID); entryB.push_back((MINT32)SENSOR_SCENARIO_ID_NORMAL_CAPTURE, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_SCENARIO_ID, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_FRAME_RATE); entryB.push_back((MINT32)pSensorStaticInfo->captureFrameRate, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_FRAME_RATE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE); MSize size1(pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight); entryB.push_back(size1, Type2Type<MSize>()); metadataB.update(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY); MRect region1(MPoint(0, 0), MSize(pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight)); entryB.push_back(region1, Type2Type<MRect>()); metadataB.update(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY, entryB); } entryA.push_back(metadataB, Type2Type<IMetadata>()); } { IMetadata metadataB; { IMetadata::IEntry entryB(MTK_SENSOR_INFO_SCENARIO_ID); entryB.push_back((MINT32)SENSOR_SCENARIO_ID_NORMAL_VIDEO, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_SCENARIO_ID, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_FRAME_RATE); entryB.push_back((MINT32)pSensorStaticInfo->videoFrameRate, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_FRAME_RATE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE); MSize size1(pSensorStaticInfo->videoWidth, pSensorStaticInfo->videoHeight); entryB.push_back(size1, Type2Type<MSize>()); metadataB.update(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY); MRect region1(MPoint(0, 0), MSize(pSensorStaticInfo->videoWidth, pSensorStaticInfo->videoHeight)); entryB.push_back(region1, Type2Type<MRect>()); metadataB.update(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY, entryB); } entryA.push_back(metadataB, Type2Type<IMetadata>()); } { IMetadata metadataB; { IMetadata::IEntry entryB(MTK_SENSOR_INFO_SCENARIO_ID); entryB.push_back((MINT32)SENSOR_SCENARIO_ID_SLIM_VIDEO1, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_SCENARIO_ID, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_FRAME_RATE); entryB.push_back((MINT32)pSensorStaticInfo->video1FrameRate, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_FRAME_RATE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE); MSize size1(pSensorStaticInfo->video1Width, pSensorStaticInfo->video1Height); entryB.push_back(size1, Type2Type<MSize>()); metadataB.update(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY); MRect region1(MPoint(0, 0), MSize(pSensorStaticInfo->video1Width, pSensorStaticInfo->video1Height)); entryB.push_back(region1, Type2Type<MRect>()); metadataB.update(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY, entryB); } entryA.push_back(metadataB, Type2Type<IMetadata>()); } { IMetadata metadataB; { IMetadata::IEntry entryB(MTK_SENSOR_INFO_SCENARIO_ID); entryB.push_back((MINT32)SENSOR_SCENARIO_ID_SLIM_VIDEO2, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_SCENARIO_ID, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_FRAME_RATE); entryB.push_back((MINT32)pSensorStaticInfo->video2FrameRate, Type2Type<MINT32>()); metadataB.update(MTK_SENSOR_INFO_FRAME_RATE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE); MSize size1(pSensorStaticInfo->video2Width, pSensorStaticInfo->video2Height); entryB.push_back(size1, Type2Type<MSize>()); metadataB.update(MTK_SENSOR_INFO_REAL_OUTPUT_SIZE, entryB); } { IMetadata::IEntry entryB(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY); MRect region1(MPoint(0, 0), MSize(pSensorStaticInfo->video2Width, pSensorStaticInfo->video2Height)); entryB.push_back(region1, Type2Type<MRect>()); metadataB.update(MTK_SENSOR_INFO_OUTPUT_REGION_ON_ACTIVE_ARRAY, entryB); } entryA.push_back(metadataB, Type2Type<IMetadata>()); } metadataA.update(MTK_SENSOR_INFO_PACKAGE, entryA); } metadataA.sort(); CAM_LOGD("impBuildSensorInfo end!"); } /****************************************************************************** * ******************************************************************************/ static MBOOL impConstructStaticMetadata_by_SymbolName( std::string const& s8Symbol, Info const& rInfo, IMetadata* rMetadata) { typedef MBOOL (*PFN_T)(IMetadata * metadata, Info const& info); PFN_T pfn; MBOOL ret = MTRUE; string const s8LibPath("libmtk_halsensor.so"); void* handle = ::dlopen(s8LibPath.c_str(), RTLD_NOW); if (!handle) { char const* err_str = ::dlerror(); CAM_LOGW("dlopen library=%s %s", s8LibPath.c_str(), err_str ? err_str : "unknown"); ret = MFALSE; goto lbExit; } pfn = (PFN_T)::dlsym(handle, s8Symbol.c_str()); if (!pfn) { CAM_LOGD("%s not found", s8Symbol.c_str()); ret = MFALSE; goto lbExit; } ret = pfn(rMetadata, rInfo); CAM_LOGD_IF(!ret, "%s fail", s8Symbol.c_str()); lbExit: if (handle) { ::dlclose(handle); handle = NULL; } return ret; } /****************************************************************************** * ******************************************************************************/ static MBOOL impBuildStaticInfo(Info const& rInfo, IMetadata* rMetadata) { static char const* const kStaticMetadataTypeNames[] = { "LENS", "SENSOR", "TUNING_3A", "FLASHLIGHT", "SCALER", "FEATURE", "CAMERA", "REQUEST", NULL}; auto constructMetadata = [](Info const& rInfo, IMetadata* rMetadata, std::string attr) { std::string s8Symbol_Sensor; std::string s8Symbol_Common; char strTemp[100]; for (int i = 0; NULL != kStaticMetadataTypeNames[i]; i++) { char const* const pTypeName = kStaticMetadataTypeNames[i]; MBOOL status = MTRUE; snprintf(strTemp, sizeof(strTemp), "%s_%s_%s_%s", PREFIX_FUNCTION_STATIC_METADATA, attr.c_str(), pTypeName, rInfo.getSensorDrvName().c_str()); s8Symbol_Sensor = strTemp; status = impConstructStaticMetadata_by_SymbolName(s8Symbol_Sensor, rInfo, rMetadata); if (MTRUE == status) { continue; } snprintf(strTemp, sizeof(strTemp), "%s_%s_%s_%s", PREFIX_FUNCTION_STATIC_METADATA, attr.c_str(), pTypeName, "COMMON"); s8Symbol_Common = strTemp; status = impConstructStaticMetadata_by_SymbolName(s8Symbol_Common, rInfo, rMetadata); if (MTRUE == status) { continue; } CAM_LOGE_IF(0, "Fail for both %s & %s", s8Symbol_Sensor.c_str(), s8Symbol_Common.c_str()); } }; constructMetadata(rInfo, rMetadata, "DEVICE"); constructMetadata(rInfo, rMetadata, "PROJECT"); return MTRUE; } /****************************************************************************** * ******************************************************************************/ MBOOL HalSensorList::buildStaticInfo(Info const& rInfo, IMetadata* pMetadata) const { IMetadata& rMetadata = *pMetadata; const SensorStaticInfo* pSensorStaticInfo = &sensorStaticInfo[rInfo.getDeviceId()]; MUINT8 u8Para = 0; if (!impBuildStaticInfo(rInfo, &rMetadata)) { CAM_LOGE("Fail to build static info for %s index:%d", rInfo.getSensorDrvName().c_str(), rInfo.getDeviceId()); } // METEDATA Ref //system/media/camera/docs/docs.html // using full size { IMetadata::IEntry entryA(MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION); MRect region1(MPoint(pSensorStaticInfo->SensorGrabStartX_CAP, pSensorStaticInfo->SensorGrabStartY_CAP), MSize(pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight)); entryA.push_back(region1, Type2Type<MRect>()); rMetadata.update(MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION, entryA); CAM_LOGD("MTK_SENSOR_INFO_ACTIVE_ARRAY_REGION(%d, %d, %d, %d)", pSensorStaticInfo->SensorGrabStartX_CAP, pSensorStaticInfo->SensorGrabStartY_CAP, pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight); } // using full size(No correction) { IMetadata::IEntry entryA(MTK_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE); entryA.push_back(pSensorStaticInfo->SensorGrabStartX_CAP, Type2Type<MINT32>()); entryA.push_back(pSensorStaticInfo->SensorGrabStartY_CAP, Type2Type<MINT32>()); entryA.push_back(pSensorStaticInfo->captureWidth, Type2Type<MINT32>()); entryA.push_back(pSensorStaticInfo->captureHeight, Type2Type<MINT32>()); rMetadata.update(MTK_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, entryA); CAM_LOGD("MTK_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE(%d, %d, %d, %d)", pSensorStaticInfo->SensorGrabStartX_CAP, pSensorStaticInfo->SensorGrabStartY_CAP, pSensorStaticInfo->captureWidth, pSensorStaticInfo->captureHeight); } // Pixel arry { SensorCropWinInfo rSensorCropInfo = {}; SENSOR_WINSIZE_INFO_STRUCT* ptr; MUINT32 scenario = MSDK_SCENARIO_ID_CAMERA_CAPTURE_JPEG; /*capture mode*/ memset(&rSensorCropInfo, 0, sizeof(SensorCropWinInfo)); ptr = getWinSizeInfo((IMGSENSOR_SENSOR_IDX)rInfo.getDeviceId(), scenario); /*DeviceId count from 1*/ if (ptr) { memcpy(&rSensorCropInfo, reinterpret_cast<void*>(ptr), sizeof(SENSOR_WINSIZE_INFO_STRUCT)); } CAM_LOGD("Pixel arry: device id %d full_w %d full_h %d", rInfo.getDeviceId(), rSensorCropInfo.full_w, rSensorCropInfo.full_h); IMetadata::IEntry entryA(MTK_SENSOR_INFO_PIXEL_ARRAY_SIZE); MSize Size1(rSensorCropInfo.full_w, rSensorCropInfo.full_h); entryA.push_back(Size1, Type2Type<MSize>()); rMetadata.update(MTK_SENSOR_INFO_PIXEL_ARRAY_SIZE, entryA); } // Color filter { IMetadata::IEntry entryA(MTK_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT); switch (pSensorStaticInfo->sensorFormatOrder) { case SENSOR_FORMAT_ORDER_RAW_B: u8Para = 0x3; // BGGR break; case SENSOR_FORMAT_ORDER_RAW_Gb: u8Para = 0x2; // GBRG break; case SENSOR_FORMAT_ORDER_RAW_Gr: u8Para = 0x1; // GRBG break; case SENSOR_FORMAT_ORDER_RAW_R: u8Para = 0x0; // RGGB break; default: u8Para = 0x4; // BGR not bayer break; } entryA.push_back(u8Para, Type2Type<MUINT8>()); rMetadata.update(MTK_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT, entryA); } { NSCam::TuningUtils::TuningPlatformInfo tuning_info; NSCam::TuningUtils::PlatformInfo sensor_info; tuning_info.getTuningInfo(&sensor_info); if (rInfo.getDeviceId() == 0) { rMetadata.remove(MTK_SENSOR_INFO_ORIENTATION); IMetadata::IEntry entryA(MTK_SENSOR_INFO_ORIENTATION); entryA.push_back(sensor_info.wf_sensor.orientation, Type2Type<MINT32>()); rMetadata.update(MTK_SENSOR_INFO_ORIENTATION, entryA); rMetadata.remove(MTK_SENSOR_INFO_FACING); IMetadata::IEntry entryC(MTK_SENSOR_INFO_FACING); entryC.push_back(MTK_LENS_FACING_BACK, Type2Type<MUINT8>()); rMetadata.update(MTK_SENSOR_INFO_FACING, entryC); } else if (rInfo.getDeviceId() == 1) { rMetadata.remove(MTK_SENSOR_INFO_ORIENTATION); IMetadata::IEntry entryA(MTK_SENSOR_INFO_ORIENTATION); entryA.push_back(sensor_info.uf_sensor.orientation, Type2Type<MINT32>()); rMetadata.update(MTK_SENSOR_INFO_ORIENTATION, entryA); rMetadata.remove(MTK_SENSOR_INFO_FACING); IMetadata::IEntry entryC(MTK_SENSOR_INFO_FACING); entryC.push_back(MTK_LENS_FACING_FRONT, Type2Type<MUINT8>()); rMetadata.update(MTK_SENSOR_INFO_FACING, entryC); } // AF if (rInfo.getDeviceId() == 0) { MY_LOGD("main_sensor.minFocusDistance: %f, update AF modes & regions", sensor_info.wf_sensor.minFocusDistance); if (sensor_info.wf_sensor.minFocusDistance == 0) { // fixed focus // MTK_LENS_INFO_MINIMUM_FOCUS_DISTANCE rMetadata.remove(MTK_LENS_INFO_MINIMUM_FOCUS_DISTANCE); IMetadata::IEntry eMinFocusDistance( MTK_LENS_INFO_MINIMUM_FOCUS_DISTANCE); eMinFocusDistance.push_back(0, Type2Type<MFLOAT>()); rMetadata.update(MTK_LENS_INFO_MINIMUM_FOCUS_DISTANCE, eMinFocusDistance); // MTK_CONTROL_AF_AVAILABLE_MODES rMetadata.remove(MTK_CONTROL_AF_AVAILABLE_MODES); IMetadata::IEntry afAvailableModes(MTK_CONTROL_AF_AVAILABLE_MODES); afAvailableModes.push_back(MTK_CONTROL_AF_MODE_OFF, Type2Type<MUINT8>()); rMetadata.update(MTK_CONTROL_AF_AVAILABLE_MODES, afAvailableModes); // MTK_CONTROL_MAX_REGIONS rMetadata.remove(MTK_CONTROL_MAX_REGIONS); IMetadata::IEntry maxRegions(MTK_CONTROL_MAX_REGIONS); maxRegions.push_back(1, Type2Type<MINT32>()); maxRegions.push_back(1, Type2Type<MINT32>()); maxRegions.push_back(0, Type2Type<MINT32>()); rMetadata.update(MTK_CONTROL_MAX_REGIONS, maxRegions); } } } rMetadata.sort(); return MTRUE; }
35.917431
80
0.643441
strassek
e4f04f56cb5c8bb13e36f54701754da0ad28a75d
614
tpp
C++
src/memory/alloc_sthread_next_fit_part_none.tpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
9
2019-05-14T01:07:08.000Z
2020-11-12T01:46:11.000Z
src/memory/alloc_sthread_next_fit_part_none.tpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
null
null
null
src/memory/alloc_sthread_next_fit_part_none.tpp
clearlycloudy/concurrent
243246f3244cfaf7ffcbfc042c69980d96f988e4
[ "MIT" ]
null
null
null
#include <new> template< class T, class... Args > T * alloc_sthread_next_fit_part_none_impl::newing( void * p, Args&&... args ){ if( nullptr == p ){ if( !allocating( &p, sizeof(T) ) ){ //allocation failed std::bad_alloc bad_alloc; throw bad_alloc; return nullptr; } } return static_cast<T*> ( new( p ) T( std::forward<Args>(args)...) ); //constructor via placement } template< class T > bool alloc_sthread_next_fit_part_none_impl::deleting( T * p ){ if( nullptr == p ){ return false; } p->~T(); //call destructor return freeing( (void *) p ); //reclaim memory }
26.695652
100
0.620521
clearlycloudy
e4f5510e0668e5d718938faad6dbba6e00a2a493
65
cpp
C++
msbuild-maven-plugin/src/test/resources/unit/source-listing/project2/project2.cpp
sunnymoon/msbuild-maven-plugin
86fa207675d5d51f864c3e636c2a10b1d6c2afd5
[ "Apache-2.0" ]
3
2015-03-26T16:06:32.000Z
2017-12-08T19:31:38.000Z
msbuild-maven-plugin/src/test/resources/unit/source-listing/project2/project2.cpp
sunnymoon/msbuild-maven-plugin
86fa207675d5d51f864c3e636c2a10b1d6c2afd5
[ "Apache-2.0" ]
6
2015-09-07T06:45:15.000Z
2021-06-30T08:16:13.000Z
msbuild-maven-plugin/src/test/resources/unit/source-listing/project2/project2.cpp
sunnymoon/msbuild-maven-plugin
86fa207675d5d51f864c3e636c2a10b1d6c2afd5
[ "Apache-2.0" ]
2
2015-09-07T07:02:38.000Z
2019-09-25T21:20:26.000Z
#include "project2.h" int project2_method1() { return 0; }
8.125
22
0.646154
sunnymoon
e4f70561dfe99acf0c70d16cd3cd2c00c24c6d94
15,703
cpp
C++
src/fdm/auto/fdm_Autopilot.cpp
marek-cel/mscsim-cc0
348f659eae61fd998df8bf2fa81090596548d06d
[ "CC0-1.0" ]
4
2020-03-03T08:10:59.000Z
2021-09-04T08:02:17.000Z
src/fdm/auto/fdm_Autopilot.cpp
marek-cel/mscsim-cc0
348f659eae61fd998df8bf2fa81090596548d06d
[ "CC0-1.0" ]
null
null
null
src/fdm/auto/fdm_Autopilot.cpp
marek-cel/mscsim-cc0
348f659eae61fd998df8bf2fa81090596548d06d
[ "CC0-1.0" ]
null
null
null
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * Creative Commons Legal Code * * CC0 1.0 Universal * * CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE * LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN * ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS * INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES * REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS * PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM * THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED * HEREUNDER. * * Statement of Purpose * * The laws of most jurisdictions throughout the world automatically confer * exclusive Copyright and Related Rights (defined below) upon the creator * and subsequent owner(s) (each and all, an "owner") of an original work of * authorship and/or a database (each, a "Work"). * * Certain owners wish to permanently relinquish those rights to a Work for * the purpose of contributing to a commons of creative, cultural and * scientific works ("Commons") that the public can reliably and without fear * of later claims of infringement build upon, modify, incorporate in other * works, reuse and redistribute as freely as possible in any form whatsoever * and for any purposes, including without limitation commercial purposes. * These owners may contribute to the Commons to promote the ideal of a free * culture and the further production of creative, cultural and scientific * works, or to gain reputation or greater distribution for their Work in * part through the use and efforts of others. * * For these and/or other purposes and motivations, and without any * expectation of additional consideration or compensation, the person * associating CC0 with a Work (the "Affirmer"), to the extent that he or she * is an owner of Copyright and Related Rights in the Work, voluntarily * elects to apply CC0 to the Work and publicly distribute the Work under its * terms, with knowledge of his or her Copyright and Related Rights in the * Work and the meaning and intended legal effect of CC0 on those rights. * * 1. Copyright and Related Rights. A Work made available under CC0 may be * protected by copyright and related or neighboring rights ("Copyright and * Related Rights"). Copyright and Related Rights include, but are not * limited to, the following: * * i. the right to reproduce, adapt, distribute, perform, display, * communicate, and translate a Work; * ii. moral rights retained by the original author(s) and/or performer(s); * iii. publicity and privacy rights pertaining to a person's image or * likeness depicted in a Work; * iv. rights protecting against unfair competition in regards to a Work, * subject to the limitations in paragraph 4(a), below; * v. rights protecting the extraction, dissemination, use and reuse of data * in a Work; * vi. database rights (such as those arising under Directive 96/9/EC of the * European Parliament and of the Council of 11 March 1996 on the legal * protection of databases, and under any national implementation * thereof, including any amended or successor version of such * directive); and * vii. other similar, equivalent or corresponding rights throughout the * world based on applicable law or treaty, and any national * implementations thereof. * * 2. Waiver. To the greatest extent permitted by, but not in contravention * of, applicable law, Affirmer hereby overtly, fully, permanently, * irrevocably and unconditionally waives, abandons, and surrenders all of * Affirmer's Copyright and Related Rights and associated claims and causes * of action, whether now known or unknown (including existing as well as * future claims and causes of action), in the Work (i) in all territories * worldwide, (ii) for the maximum duration provided by applicable law or * treaty (including future time extensions), (iii) in any current or future * medium and for any number of copies, and (iv) for any purpose whatsoever, * including without limitation commercial, advertising or promotional * purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each * member of the public at large and to the detriment of Affirmer's heirs and * successors, fully intending that such Waiver shall not be subject to * revocation, rescission, cancellation, termination, or any other legal or * equitable action to disrupt the quiet enjoyment of the Work by the public * as contemplated by Affirmer's express Statement of Purpose. * * 3. Public License Fallback. Should any part of the Waiver for any reason * be judged legally invalid or ineffective under applicable law, then the * Waiver shall be preserved to the maximum extent permitted taking into * account Affirmer's express Statement of Purpose. In addition, to the * extent the Waiver is so judged Affirmer hereby grants to each affected * person a royalty-free, non transferable, non sublicensable, non exclusive, * irrevocable and unconditional license to exercise Affirmer's Copyright and * Related Rights in the Work (i) in all territories worldwide, (ii) for the * maximum duration provided by applicable law or treaty (including future * time extensions), (iii) in any current or future medium and for any number * of copies, and (iv) for any purpose whatsoever, including without * limitation commercial, advertising or promotional purposes (the * "License"). The License shall be deemed effective as of the date CC0 was * applied by Affirmer to the Work. Should any part of the License for any * reason be judged legally invalid or ineffective under applicable law, such * partial invalidity or ineffectiveness shall not invalidate the remainder * of the License, and in such case Affirmer hereby affirms that he or she * will not (i) exercise any of his or her remaining Copyright and Related * Rights in the Work or (ii) assert any associated claims and causes of * action with respect to the Work, in either case contrary to Affirmer's * express Statement of Purpose. * * 4. Limitations and Disclaimers. * * a. No trademark or patent rights held by Affirmer are waived, abandoned, * surrendered, licensed or otherwise affected by this document. * b. Affirmer offers the Work as-is and makes no representations or * warranties of any kind concerning the Work, express, implied, * statutory or otherwise, including without limitation warranties of * title, merchantability, fitness for a particular purpose, non * infringement, or the absence of latent or other defects, accuracy, or * the present or absence of errors, whether or not discoverable, all to * the greatest extent permissible under applicable law. * c. Affirmer disclaims responsibility for clearing rights of other persons * that may apply to the Work or any use thereof, including without * limitation any person's Copyright and Related Rights in the Work. * Further, Affirmer disclaims responsibility for obtaining any necessary * consents, permissions or other rights required for any use of the * Work. * d. Affirmer understands and acknowledges that Creative Commons is not a * party to this document and has no duty or obligation with respect to * this CC0 or use of the Work. ******************************************************************************/ #include <fdm/auto/fdm_Autopilot.h> #include <fdm/utils/fdm_Misc.h> #include <fdm/utils/fdm_Units.h> #include <fdm/xml/fdm_XmlUtils.h> #include <iostream> //////////////////////////////////////////////////////////////////////////////// using namespace fdm; //////////////////////////////////////////////////////////////////////////////// Autopilot::Autopilot( FlightDirector *fd ) : _fd ( fd ), _pid_r ( 0.0, 0.0, 0.0, -1.0, 1.0 ), _pid_p ( 0.0, 0.0, 0.0, -1.0, 1.0 ), _pid_y ( 0.0, 0.0, 0.0, -1.0, 1.0 ), _max_rate_roll ( DBL_MAX ), _max_rate_pitch ( DBL_MAX ), _max_rate_yaw ( DBL_MAX ), _min_roll ( -M_PI_2 ), _max_roll ( M_PI_2 ), _min_pitch ( -M_PI_2 ), _max_pitch ( M_PI_2 ), _min_alt ( 0.0 ), _max_alt ( DBL_MAX ), _min_ias ( 0.0 ), _max_ias ( DBL_MAX ), _min_vs ( -DBL_MAX ), _max_vs ( DBL_MAX ), _ctrl_roll ( 0.0 ), _ctrl_pitch ( 0.0 ), _ctrl_yaw ( 0.0 ), _yaw_damper ( false ), _testing ( false ), _engaged ( false ) { _pid_r.setAntiWindup( PID::Calculation ); _pid_p.setAntiWindup( PID::Calculation ); _pid_y.setAntiWindup( PID::Calculation ); _gain_ias_r = Table1::oneRecordTable( 1.0 ); _gain_ias_p = Table1::oneRecordTable( 1.0 ); _gain_ias_y = Table1::oneRecordTable( 1.0 ); } //////////////////////////////////////////////////////////////////////////////// Autopilot::~Autopilot() {} //////////////////////////////////////////////////////////////////////////////// void Autopilot::readData( XmlNode &dataNode ) { if ( dataNode.isValid() ) { int result = FDM_SUCCESS; if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_min_roll , "min_roll" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_max_roll , "max_roll" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_min_pitch , "min_pitch" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_max_pitch , "max_pitch" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_min_alt , "min_alt" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_max_alt , "max_alt" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_min_ias , "min_ias" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_max_ias , "max_ias" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_min_vs , "min_vs" , true ); if ( result == FDM_SUCCESS ) result = XmlUtils::read( dataNode, &_max_vs , "max_vs" , true ); if ( result == FDM_SUCCESS ) { XmlNode nodeRoll = dataNode.getFirstChildElement( "ctrl_roll" ); XmlNode nodePitch = dataNode.getFirstChildElement( "ctrl_pitch" ); XmlNode nodeYaw = dataNode.getFirstChildElement( "ctrl_yaw" ); readChannel( nodeRoll , &_max_rate_roll , &_pid_r, &_gain_ias_r ); readChannel( nodePitch , &_max_rate_pitch , &_pid_p, &_gain_ias_p ); readChannel( nodeYaw , &_max_rate_yaw , &_pid_y, &_gain_ias_y ); } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } XmlNode nodeFlightDirector = dataNode.getFirstChildElement( "flight_director" ); _fd->readData( nodeFlightDirector ); } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } } //////////////////////////////////////////////////////////////////////////////// void Autopilot::initialize() {} //////////////////////////////////////////////////////////////////////////////// void Autopilot::update( double timeStep, double roll, double pitch, double heading, double altitude, double airspeed, double turn_rate, double yaw_rate, double climb_rate, double dme_distance, double nav_deviation, bool nav_active, double loc_deviation, bool loc_active, double gs_deviation, bool gs_active ) { _fd->update( timeStep, heading, altitude, airspeed, turn_rate, climb_rate, dme_distance, nav_deviation, nav_active, loc_deviation, loc_active, gs_deviation, gs_active ); if ( _engaged && _fd->isEngaged() ) { _pid_r.update( timeStep, _fd->getCmdRoll() - roll ); _pid_p.update( timeStep, _fd->getCmdPitch() - pitch ); } else { _pid_r.reset(); _pid_p.reset(); _ctrl_roll = 0.0; _ctrl_pitch = 0.0; } if ( _yaw_damper ) { _pid_y.update( timeStep, -yaw_rate ); } else { _pid_y.reset(); _ctrl_yaw = 0.0; } double ctrl_roll = _gain_ias_r.getValue( airspeed ) * _pid_r.getValue(); double ctrl_pitch = _gain_ias_p.getValue( airspeed ) * _pid_p.getValue(); double ctrl_yaw = _gain_ias_y.getValue( airspeed ) * _pid_y.getValue(); // if ( _softRide ) // { // ctrl_roll *= _softRideCoef; // ctrl_pitch *= _softRideCoef; // ctrl_yaw *= _softRideCoef; // } _ctrl_roll = Misc::rate( timeStep, _max_rate_roll , _ctrl_roll , ctrl_roll ); _ctrl_pitch = Misc::rate( timeStep, _max_rate_pitch , _ctrl_pitch , ctrl_pitch ); _ctrl_yaw = Misc::rate( timeStep, _max_rate_yaw , _ctrl_yaw , ctrl_yaw ); _ctrl_roll = Misc::satur( -1.0, 1.0, _ctrl_roll ); _ctrl_pitch = Misc::satur( -1.0, 1.0, _ctrl_pitch ); _ctrl_yaw = Misc::satur( -1.0, 1.0, _ctrl_yaw ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setAltitude( double altitude ) { _fd->setAltitude( fdm::Misc::satur( _min_alt, _max_alt, altitude ) ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setAirspeed( double airspeed ) { _fd->setAirspeed( fdm::Misc::satur( _min_ias, _max_ias, airspeed ) ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setClimbRate( double climb_rate ) { _fd->setClimbRate( fdm::Misc::satur( _min_vs, _max_vs, climb_rate ) ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setHeading( double heading ) { _fd->setHeading( heading ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setCourse( double course ) { _fd->setCourse( course ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setRoll( double roll ) { _fd->setRoll( Misc::satur( _min_roll, _max_roll, roll ) ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::setPitch( double pitch ) { _fd->setPitch( Misc::satur( _min_pitch, _max_pitch, pitch ) ); } //////////////////////////////////////////////////////////////////////////////// void Autopilot::readChannel( const XmlNode &dataNode, double *max_rate, PID *pid, Table1 *gain_ias ) { if ( dataNode.isValid() ) { int result = XmlUtils::read( dataNode, max_rate, "max_rate" ); if ( result != FDM_SUCCESS ) XmlUtils::throwError( __FILE__, __LINE__, dataNode ); XmlNode nodePID = dataNode.getFirstChildElement( "pid" ); if ( FDM_SUCCESS != XmlUtils::read( nodePID, pid, -1.0, 1.0 ) ) { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } result = XmlUtils::read( dataNode, gain_ias, "gain_ias", true ); if ( result != FDM_SUCCESS ) XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } else { XmlUtils::throwError( __FILE__, __LINE__, dataNode ); } }
42.099196
107
0.6202
marek-cel
e4f86b1723ea317e9b76ca740687d0924cd369ff
1,435
hpp
C++
include/ash/fsm/DynamicComponentProvider.hpp
CorundumGames/AshPlusPlus
d346cf9029798e710fee4d8e3d5f305c90d04caa
[ "MIT" ]
2
2016-12-17T23:19:06.000Z
2017-07-19T14:44:57.000Z
include/ash/fsm/DynamicComponentProvider.hpp
CorundumGames/AshPlusPlus
d346cf9029798e710fee4d8e3d5f305c90d04caa
[ "MIT" ]
null
null
null
include/ash/fsm/DynamicComponentProvider.hpp
CorundumGames/AshPlusPlus
d346cf9029798e710fee4d8e3d5f305c90d04caa
[ "MIT" ]
null
null
null
#ifndef DYNAMICCOMPONENTPROVIDER_HPP #define DYNAMICCOMPONENTPROVIDER_HPP #include <functional> #include "ash/fsm/IComponentProvider.hpp" using std::function; namespace ash { namespace fsm { /** * This component provider calls a function to get the component instance. The function must return a single component * of the appropriate type. */ template<class C> class DynamicComponentProvider : public IComponentProvider<C, function<C(void)>> { public: /** * Constructor * * @param closure The function that will return the component instance when called. */ DynamicComponentProvider(const function<C(void)>& closure) : _closure(closure) {} virtual ~DynamicComponentProvider() {} /** * Used to request a component from this provider * * @return The instance returned by calling the function */ C getComponent() const { return this->_closure(); } /** * Used to compare this provider with others. Any provider that uses the function or method closure to provide * the instance is regarded as equivalent. * * @return The function */ function<C(void)> const& identifier() const { return this->_closure; } private: function<C(void)> _closure; }; } } #endif // DYNAMICCOMPONENTPROVIDER_HPP
26.090909
118
0.632056
CorundumGames
e4fe66f01bd181453e448adfde7ec5bda71a2412
5,263
cpp
C++
src/stx/common/trex_cmd_mngr.cpp
GabrielGanne/trex-core
688a0fe0adb890964691473723d70ffa98e00dd3
[ "Apache-2.0" ]
1
2022-02-25T01:24:33.000Z
2022-02-25T01:24:33.000Z
src/stx/common/trex_cmd_mngr.cpp
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
null
null
null
src/stx/common/trex_cmd_mngr.cpp
hjat2005/trex-core
400f03c86c844a0096dff3f6b13e58a808aaefff
[ "Apache-2.0" ]
null
null
null
#include "trex_cmd_mngr.h" #include "trex_exception.h" #include "trex_global.h" #include <zmq.h> #include <errno.h> #include <sys/wait.h> #include <string> CCmdsMngr::CCmdsMngr() { CParserOption * po =&CGlobalInfo::m_options; m_zmq_ctx = zmq_ctx_new(); if ( !m_zmq_ctx ) { printf("Could not create ZMQ context\n"); } m_zmq_cmds_socket = zmq_socket(m_zmq_ctx, ZMQ_REQ); if (!m_zmq_cmds_socket) { zmq_ctx_term(m_zmq_ctx); m_zmq_ctx = nullptr; printf("Could not create ZMQ socket\n"); } int linger = 0; int timeout_ms = 5000; zmq_setsockopt(m_zmq_cmds_socket, ZMQ_LINGER, &linger, sizeof(linger)); //receive and send timeout zmq_setsockopt(m_zmq_cmds_socket, ZMQ_RCVTIMEO, &timeout_ms, sizeof(timeout_ms)); zmq_setsockopt(m_zmq_cmds_socket, ZMQ_SNDTIMEO, &timeout_ms, sizeof(timeout_ms)); std::string file_suffix = ""; if (po->prefix != "") { file_suffix += "_" + po->prefix; } std::string file_path_ipc = "ipc://" + po->m_cmds_ipc_file_path + file_suffix + ".ipc"; if ( zmq_connect(m_zmq_cmds_socket, file_path_ipc.c_str()) != 0 ) { zmq_close(m_zmq_cmds_socket); zmq_ctx_term(m_zmq_ctx); m_zmq_ctx = nullptr; m_zmq_cmds_socket = nullptr; printf("Could not connect to ZMQ socket\n"); } Json::Value request; Json::Value response; request["type"] = NEW_CLIENT_REQ; send_request(request, response); } CCmdsMngr::~CCmdsMngr() { Json::Value request; Json::Value response; request["type"] = KILL_REQ; send_request(request, response); if (m_zmq_cmds_socket) { zmq_close(m_zmq_cmds_socket); m_zmq_cmds_socket=nullptr; } if (m_zmq_ctx) { zmq_ctx_term(m_zmq_ctx); m_zmq_ctx=nullptr; } } std::string CCmdsMngr::error_type_to_string(error_type_t error) { std::string error_str; switch(error) { case NONE: { error_str = "NONE"; break; } case ZMQ_ERROR: { error_str = "ZMQ_ERROR"; break; } case PARSING_ERROR: { error_str = "PARSING_ERROR"; break; } default: { error_str = "UNKNOWN_ERROR"; } } return error_str; } void CCmdsMngr::verify_field(Json::Value &value, std::string field_name, field_type_t type) { std::string err; if (value.isMember("err")) { err = value["err"].asString(); err += "; "; } if (!value.isMember(field_name)) { err += "no such field: " + field_name; value["err"] = err; value["error_type"] = PARSING_ERROR; return; } const Json::Value &field = value[field_name]; err += "expecting " + field_name + "to be "; bool rc = true; switch(type) { case FIELD_TYPE_STR: err += "'string'"; if (!field.isString()) { rc = false; } break; case FIELD_TYPE_UINT32: err += "'uint32'"; if (!field.isUInt64()) { rc = false; } else if (field.asUInt64() > 0xFFFFFFFF) { err += ",the value has size bigger than uint32."; rc = false; } break; default: rc = false; } if (!rc) { value["err"] = err; value["error_type"] = PARSING_ERROR; } } void CCmdsMngr::send_request(Json::Value &req, Json::Value &resp) { std::lock_guard<std::mutex> l(m_cmds_mutex); Json::FastWriter writer; Json::Reader reader; std::string request = writer.write(req); char resp_buffer[1024] = {0}; int ret = zmq_send(m_zmq_cmds_socket, request.c_str(), request.size(), 0); if (ret == -1) { resp["error_type"] = ZMQ_ERROR; std::string err; if (errno == EAGAIN){ err = "Could not send the request: timeout in zmq_send"; }else { err = "Could not send the request"; } resp["err"] = err; return; } ret = zmq_recv(m_zmq_cmds_socket, resp_buffer, sizeof(resp_buffer), 0); if (ret == -1) { resp["error_type"] = ZMQ_ERROR; std::string err; if (errno == EAGAIN){ err = "Could not receive the response: timeout in zmq_recv"; }else { err = "Could not receive the response"; } resp["err"] = err; return; } std::string response_str(resp_buffer); reader.parse(response_str, resp, false); verify_field(resp, "output", FIELD_TYPE_STR); verify_field(resp, "returncode", FIELD_TYPE_UINT32); } int CCmdsMngr::popen_general(const std::string &cmd, std::string &output, error_type_t& error, std::string &error_msg) { Json::Value request; Json::Value response; request["type"] = POPEN_REQ; request["cmd"] = cmd; send_request(request, response); if (response.isMember("err")) { error_msg += response["err"].asString(); error = (error_type_t) response["error_type"].asInt(); return -1; } output += response["output"].asString(); int return_code = response["returncode"].asInt(); return (return_code == 0) ? 0 : -1; }
29.402235
120
0.576667
GabrielGanne
e4fe87fe85ad1b1ee8f39ef4649ce09822f437fd
2,508
cpp
C++
trikScriptRunner/src/trikVariablesServer.cpp
thetoropov/trikRuntime
f236e441875ff4ab999803252f26075e089ae04c
[ "Apache-2.0" ]
null
null
null
trikScriptRunner/src/trikVariablesServer.cpp
thetoropov/trikRuntime
f236e441875ff4ab999803252f26075e089ae04c
[ "Apache-2.0" ]
null
null
null
trikScriptRunner/src/trikVariablesServer.cpp
thetoropov/trikRuntime
f236e441875ff4ab999803252f26075e089ae04c
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Anastasiia Kornilova, CyberTech Labs Ltd. * * 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 "trikVariablesServer.h" #include <QtCore/QJsonDocument> #include <QtCore/QRegExp> #include <QtNetwork/QTcpSocket> using namespace trikScriptRunner; TrikVariablesServer::TrikVariablesServer() : mTcpServer(new QTcpServer(this)) { connect(mTcpServer.data(), SIGNAL(newConnection()), this, SLOT(onNewConnection())); mTcpServer->listen(QHostAddress::LocalHost, port); } void TrikVariablesServer::sendHTTPResponse(const QJsonObject &json) { QByteArray jsonBytes = QJsonDocument(json).toJson(); // TODO: Create other way for endline constant, get rid of define #define NL "\r\n" QString header = "HTTP/1.0 200 OK" NL "Connection: close" NL "Content-type: text/plain, charset=us-ascii" NL "Content-length: " + QString::number(jsonBytes.size()) + NL NL; #undef NL mCurrentConnection->write(header.toLatin1()); mCurrentConnection->write(jsonBytes); mCurrentConnection->close(); } void TrikVariablesServer::onNewConnection() { // TODO: Object from nextPendingConnection is a child of QTcpServer, so it will be automatically // deleted when QTcpServer is destroyed. Maybe it may sense to call "deleteLater" explicitly, // to avoid wasting memory. mCurrentConnection = mTcpServer->nextPendingConnection(); connect(mCurrentConnection, SIGNAL(readyRead()), this, SLOT(processHTTPRequest())); } void TrikVariablesServer::processHTTPRequest() { // TODO: Make sure, that different connections aren't intersected using mutex or // support multiple connections simultaneously QStringList list; while (mCurrentConnection->canReadLine()) { QString data = QString(mCurrentConnection->readLine()); list.append(data); } const QString cleanString = list.join("").remove(QRegExp("[\\n\\t\\r]")); const QStringList words = cleanString.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (words[1] == "/web/") { emit getVariables("web"); } }
33.44
97
0.743222
thetoropov
e4fe8a0d312b24095b5737baadf86fa6c23eadb4
22
cxx
C++
src/Cxx/VisualizationAlgorithms/OfficeA.cxx
mwestphal/VTKExamples
1fdebe2c51534e4465071ea7e660cd68640d8017
[ "Apache-2.0" ]
null
null
null
src/Cxx/VisualizationAlgorithms/OfficeA.cxx
mwestphal/VTKExamples
1fdebe2c51534e4465071ea7e660cd68640d8017
[ "Apache-2.0" ]
null
null
null
src/Cxx/VisualizationAlgorithms/OfficeA.cxx
mwestphal/VTKExamples
1fdebe2c51534e4465071ea7e660cd68640d8017
[ "Apache-2.0" ]
null
null
null
#include "Office.cxx"
11
21
0.727273
mwestphal
e4ffded7f5a0cf4dadc20639d7b5f9b980892e35
1,203
hpp
C++
include/siplasplas/utility/tuple.hpp
roscopecoltran/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
182
2016-07-19T19:31:47.000Z
2022-02-22T13:54:25.000Z
include/siplasplas/utility/tuple.hpp
roscopecoltran/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
50
2016-07-13T16:49:31.000Z
2018-06-15T13:39:49.000Z
include/siplasplas/utility/tuple.hpp
GueimUCM/ceplusplus
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
[ "MIT" ]
26
2015-12-14T11:35:41.000Z
2022-02-22T19:13:48.000Z
#ifndef SIPLASPLAS_UTILITY_TUPLE_HPP #define SIPLASPLAS_UTILITY_TUPLE_HPP #include <tuple> #include "meta.hpp" namespace cpp { namespace { template<typename Function> constexpr auto tuple_call(Function function, const std::tuple<>& tuple, meta::index_sequence<>) { return function(); } template<typename Head, typename... Tail, std::size_t... Is> constexpr auto tuple_tail(const std::tuple<Head, Tail...>& tuple, std::index_sequence<Is...>) { return std::make_tuple(std::forward<std::tuple_element_t<Is+1, std::tuple<Head, Tail>>>(std::get<Is+1>(tuple))...); } } template<typename Function> constexpr auto tuple_call(Function function, const std::tuple<>& tuple) { return tuple_call(function, tuple, meta::make_index_sequence_for<>{}); } template<typename Function, typename Head, typename... Tail> constexpr auto tuple_tail(Function function, const std::tuple<Head, Tail...>& tuple) { return tuple_tail(function, tuple, std::index_sequence_for<Head, Tail...>{}); } template<typename Function, typename... Args> constexpr auto tuple_call(const std::tuple<Args...>& tuple, Function function) { return tuple_call(function, tuple); } } #endif // SIPLASPLAS_UTILITY_TUPLE_HPP
25.0625
119
0.736492
roscopecoltran
90004e8a92fba5a459375e80590161f80ef06eb2
6,481
hpp
C++
include/tile_grid.hpp
zerebubuth/osmium-history-splitter
9e2445440fc26a29d9ceeb1833937d910b28ff9c
[ "BSL-1.0" ]
null
null
null
include/tile_grid.hpp
zerebubuth/osmium-history-splitter
9e2445440fc26a29d9ceeb1833937d910b28ff9c
[ "BSL-1.0" ]
null
null
null
include/tile_grid.hpp
zerebubuth/osmium-history-splitter
9e2445440fc26a29d9ceeb1833937d910b28ff9c
[ "BSL-1.0" ]
null
null
null
#ifndef OSMIUM_HISTORY_SPLITTER_TILE_GRID_HPP #define OSMIUM_HISTORY_SPLITTER_TILE_GRID_HPP /* This file is part of the Osmium History Splitter Copyright 2015 Matt Amos <zerebubuth@gmail.com>. Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <osmium/osm/node.hpp> #include <osmium/osm/way.hpp> #include <osmium/osm/relation.hpp> #include <osmium/memory/buffer.hpp> #include <boost/format.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <memory> #include <fstream> namespace hsplitter { // TODO: remove, or make hidden by debug flag extern size_t g_evictions, g_flushes; // represents a memory buffer waiting to be written to // a particular tile file. this is buffered so that we // don't have to have a whole load of open file // descriptors. struct tile_file { typedef osmium::memory::Buffer buffer; typedef std::unique_ptr<buffer> buffer_ptr; typedef hsplitter::tile_t tile_t; tile_file() : m_id(0), m_buffer_dir(), m_buffer() { } tile_file(tile_t id, size_t capacity, const std::string &buffer_dir) : m_id(id), m_buffer_dir(buffer_dir), m_buffer(new buffer(capacity, osmium::memory::Buffer::auto_grow::yes)) { set_callback(); } tile_file(tile_file &&tf) : m_id(tf.m_id), m_buffer_dir(tf.m_buffer_dir), m_buffer() { swap_buffer(tf.m_buffer); } tile_file(const tile_file &) = delete; const tile_file &operator=(tile_file &&tf) { m_id = tf.m_id; m_buffer_dir = tf.m_buffer_dir; swap_buffer(tf.m_buffer); return *this; } const tile_file &operator=(const tile_file &) = delete; void write(const osmium::OSMObject &obj) { assert(!empty()); m_buffer->add_item(obj); m_buffer->commit(); } void flush() { assert(!empty()); static_flush(m_id, *m_buffer, m_buffer_dir); } static void static_flush(hsplitter::tile_t id, osmium::memory::Buffer &buffer, const std::string &buffer_dir) { assert(buffer); if (buffer.begin() != buffer.end()) { // TODO: configurable, default to $TMPDIR std::string filename = (boost::format("%1%/%2%.buf") % buffer_dir % id).str(); std::ofstream file(filename, std::ios::binary | std::ios::ate | std::ios::app); file.write(reinterpret_cast<const char *>(buffer.data()), buffer.committed()); buffer.clear(); std::fill(buffer.data(), buffer.data() + buffer.capacity(), 0); ++g_flushes; } } void swap(tile_file &tf) { std::swap(m_id, tf.m_id); std::swap(m_buffer_dir, tf.m_buffer_dir); swap_buffer(tf.m_buffer); } bool empty() const { return !m_buffer; } tile_t m_id; std::string m_buffer_dir; private: buffer_ptr m_buffer; void swap_buffer(buffer_ptr &other) { if (m_buffer) { m_buffer->set_full_callback([](osmium::memory::Buffer&){}); } if (other) { other->set_full_callback([](osmium::memory::Buffer&){}); } std::swap(m_buffer, other); set_callback(); } void set_callback() { const hsplitter::tile_t id = m_id; const std::string buffer_dir = m_buffer_dir; if (m_buffer) { m_buffer->set_full_callback([id, buffer_dir](osmium::memory::Buffer &b) { static_flush(id, b, buffer_dir); }); } } }; // LRU cache of buffers struct tile_grid { typedef boost::multi_index::multi_index_container< tile_file, boost::multi_index::indexed_by< boost::multi_index::sequenced<>, boost::multi_index::hashed_unique<boost::multi_index::member<tile_file, hsplitter::tile_t, &tile_file::m_id> > > > mru_tile_set; tile_grid(size_t n_tiles, size_t capacity, const std::string &buffer_dir) { m_buffer_dir = buffer_dir; for (size_t i = 0; i < n_tiles; ++i) { tile_file tf(0, capacity, m_buffer_dir); m_free_tiles.emplace_back(std::move(tf)); } } tile_file &tile(hsplitter::tile_t id) { auto &tile_idx = m_open_tiles.get<1>(); auto itr = tile_idx.find(id); if (itr == tile_idx.end()) { if (m_free_tiles.empty()) { evict_lru_tile(); } tile_file tf; tf.swap(m_free_tiles.front()); m_free_tiles.pop_front(); tf.m_id = id; tf.m_buffer_dir = m_buffer_dir; auto pair = tile_idx.emplace(std::move(tf)); itr = pair.first; } m_open_tiles.relocate(m_open_tiles.begin(), m_open_tiles.project<0>(itr)); assert(itr->m_id == id); return const_cast<tile_file &>(*itr); } void evict_lru_tile() { assert(m_open_tiles.size() > 0); auto &tile = const_cast<tile_file &>(m_open_tiles.back()); tile.flush(); m_free_tiles.emplace_front(); m_free_tiles.front().swap(tile); assert(m_open_tiles.back().empty()); m_open_tiles.pop_back(); ++g_evictions; } void close() { for (auto &tile : m_open_tiles) { const_cast<tile_file &>(tile).flush(); } } private: std::list<tile_file> m_free_tiles; mru_tile_set m_open_tiles; std::string m_buffer_dir; }; } // namespace hsplitter #endif /* OSMIUM_HISTORY_SPLITTER_TILE_GRID_HPP */
29.459091
116
0.69156
zerebubuth
07e57da13a7e38a2d6726256469f26f9da43e480
6,484
hpp
C++
include/VROSC/UserProfileDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/UserProfileDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/VROSC/UserProfileDataModel.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.BaseDataModel #include "VROSC/BaseDataModel.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Type namespace: VROSC namespace VROSC { // Forward declaring type: UserProfileDataModel class UserProfileDataModel; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::UserProfileDataModel); DEFINE_IL2CPP_ARG_TYPE(::VROSC::UserProfileDataModel*, "VROSC", "UserProfileDataModel"); // Type namespace: VROSC namespace VROSC { // Size: 0x60 #pragma pack(push, 1) // Autogenerated type: VROSC.UserProfileDataModel // [TokenAttribute] Offset: FFFFFFFF class UserProfileDataModel : public ::VROSC::BaseDataModel { public: public: // public System.String Username // Size: 0x8 // Offset: 0x18 ::StringW Username; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String Email // Size: 0x8 // Offset: 0x20 ::StringW Email; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String OculusId // Size: 0x8 // Offset: 0x28 ::StringW OculusId; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String OculusUsername // Size: 0x8 // Offset: 0x30 ::StringW OculusUsername; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String SteamId // Size: 0x8 // Offset: 0x38 ::StringW SteamId; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String SteamUsername // Size: 0x8 // Offset: 0x40 ::StringW SteamUsername; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String LastLogin // Size: 0x8 // Offset: 0x48 ::StringW LastLogin; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String CreationDate // Size: 0x8 // Offset: 0x50 ::StringW CreationDate; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String AcceptedEULAVersion // Size: 0x8 // Offset: 0x58 ::StringW AcceptedEULAVersion; // Field size check static_assert(sizeof(::StringW) == 0x8); public: // Get instance field reference: public System.String Username [[deprecated("Use field access instead!")]] ::StringW& dyn_Username(); // Get instance field reference: public System.String Email [[deprecated("Use field access instead!")]] ::StringW& dyn_Email(); // Get instance field reference: public System.String OculusId [[deprecated("Use field access instead!")]] ::StringW& dyn_OculusId(); // Get instance field reference: public System.String OculusUsername [[deprecated("Use field access instead!")]] ::StringW& dyn_OculusUsername(); // Get instance field reference: public System.String SteamId [[deprecated("Use field access instead!")]] ::StringW& dyn_SteamId(); // Get instance field reference: public System.String SteamUsername [[deprecated("Use field access instead!")]] ::StringW& dyn_SteamUsername(); // Get instance field reference: public System.String LastLogin [[deprecated("Use field access instead!")]] ::StringW& dyn_LastLogin(); // Get instance field reference: public System.String CreationDate [[deprecated("Use field access instead!")]] ::StringW& dyn_CreationDate(); // Get instance field reference: public System.String AcceptedEULAVersion [[deprecated("Use field access instead!")]] ::StringW& dyn_AcceptedEULAVersion(); // public override System.String get_Key() // Offset: 0x191FAA4 // Implemented from: VROSC.BaseDataModel // Base method: System.String BaseDataModel::get_Key() ::StringW get_Key(); // public override System.Int32 get_Version() // Offset: 0x191FAE8 // Implemented from: VROSC.BaseDataModel // Base method: System.Int32 BaseDataModel::get_Version() int get_Version(); // public System.Void .ctor() // Offset: 0x191F258 // Implemented from: VROSC.BaseDataModel // Base method: System.Void BaseDataModel::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static UserProfileDataModel* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::UserProfileDataModel::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<UserProfileDataModel*, creationType>())); } }; // VROSC.UserProfileDataModel #pragma pack(pop) static check_size<sizeof(UserProfileDataModel), 88 + sizeof(::StringW)> __VROSC_UserProfileDataModelSizeCheck; static_assert(sizeof(UserProfileDataModel) == 0x60); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::UserProfileDataModel::get_Key // Il2CppName: get_Key template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (VROSC::UserProfileDataModel::*)()>(&VROSC::UserProfileDataModel::get_Key)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::UserProfileDataModel*), "get_Key", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::UserProfileDataModel::get_Version // Il2CppName: get_Version template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::UserProfileDataModel::*)()>(&VROSC::UserProfileDataModel::get_Version)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::UserProfileDataModel*), "get_Version", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::UserProfileDataModel::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
42.940397
157
0.704812
v0idp
07e60c98d31fb4840a4cd99c762a74178cab115d
715
cpp
C++
0000/10/11a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0000/10/11a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0000/10/11a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <vector> template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(unsigned v) { std::cout << v << '\n'; } void solve(std::vector<unsigned>& b, unsigned d) { const size_t n = b.size(); unsigned k = 0; for (size_t i = 1; i < n; ++i) { if (b[i] > b[i-1]) continue; const unsigned c = (b[i-1] - b[i] + d) / d; b[i] += c * d, k += c; } answer(k); } int main() { size_t n; std::cin >> n; unsigned d; std::cin >> d; std::vector<unsigned> b(n); std::cin >> b; solve(b, d); return 0; }
14.3
65
0.47972
actium
07e7885df199e0661e532d63f8df1d9f1afb6be2
81
cpp
C++
Course 202002/C++/Shape/rectangle.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
Course 202002/C++/Shape/rectangle.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
Course 202002/C++/Shape/rectangle.cpp
Seizzzz/DailyCodes
9a617fb64ee27b9f254be161850e9c9a61747cb1
[ "MIT" ]
null
null
null
#include "rectangle.h" double Rectangle::getAreaSize() { return lenA * lenB; }
11.571429
31
0.703704
Seizzzz
07e81cbb4e663e3eff0e59ecfee15c73cf2f6b33
4,251
cpp
C++
industrial_utils/src/utils.cpp
tingelst/industrial_core
a85789b6b33bd0a460c236a6b89c14dbf125e2c0
[ "BSD-3-Clause" ]
227
2021-01-20T05:34:32.000Z
2022-03-29T12:43:05.000Z
ros_advanced/ROS_Industrial/industrial_core/industrial_utils/src/utils.cpp
qifeidedasima/guyueclass
99f4a58d47a1764cc13af7ef7fe483009e830108
[ "Apache-2.0" ]
61
2021-12-17T13:03:59.000Z
2022-03-31T10:24:37.000Z
ros_advanced/ROS_Industrial/industrial_core/industrial_utils/src/utils.cpp
qifeidedasima/guyueclass
99f4a58d47a1764cc13af7ef7fe483009e830108
[ "Apache-2.0" ]
239
2021-01-28T02:59:53.000Z
2022-03-29T08:02:17.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2012, Southwest Research Institute * 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 Southwest Research Institute, 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. */ #include "industrial_utils/utils.h" #include "ros/ros.h" #include <algorithm> namespace industrial_utils { bool isSimilar(std::vector<std::string> lhs, std::vector<std::string> rhs) { bool rtn = false; if (lhs.size() != rhs.size()) { rtn = false; } else { std::sort(lhs.begin(), lhs.end()); std::sort(rhs.begin(), rhs.end()); rtn = isSame(lhs, rhs); } return rtn; } bool isSame(const std::vector<std::string> & lhs, const std::vector<std::string> & rhs) { bool rtn = false; if (lhs.size() != rhs.size()) { rtn = false; } else { rtn = std::equal(lhs.begin(), lhs.end(), rhs.begin()); } return rtn; } bool findChainJointNames(const urdf::LinkConstSharedPtr &link, bool ignore_fixed, std::vector<std::string> &joint_names) { typedef std::vector<urdf::JointSharedPtr > joint_list; typedef std::vector<urdf::LinkSharedPtr > link_list; std::string found_joint, found_link; // check for joints directly connected to this link const joint_list &joints = link->child_joints; ROS_DEBUG("Found %lu child joints:", joints.size()); for (joint_list::const_iterator it=joints.begin(); it!=joints.end(); ++it) { ROS_DEBUG_STREAM(" " << (*it)->name << ": type " << (*it)->type); if (ignore_fixed && (*it)->type == urdf::Joint::FIXED) continue; if (found_joint.empty()) { found_joint = (*it)->name; joint_names.push_back(found_joint); } else { ROS_WARN_STREAM("Unable to find chain in URDF. Branching joints: " << found_joint << " and " << (*it)->name); return false; // branching tree (multiple valid child-joints) } } // check for joints connected to children of this link const link_list &links = link->child_links; std::vector<std::string> sub_joints; ROS_DEBUG("Found %lu child links:", links.size()); for (link_list::const_iterator it=links.begin(); it!=links.end(); ++it) { ROS_DEBUG_STREAM(" " << (*it)->name); if (!findChainJointNames(*it, ignore_fixed, sub_joints)) // NOTE: recursive call return false; if (sub_joints.empty()) continue; if (found_link.empty()) { found_link = (*it)->name; joint_names.insert(joint_names.end(), sub_joints.begin(), sub_joints.end()); // append sub_joints } else { ROS_WARN_STREAM("Unable to find chain in URDF. Branching links: " << found_link << " and " << (*it)->name); return false; // branching tree (multiple valid child-joints) } } return true; } } //industrial_utils
32.953488
116
0.675606
tingelst
07f052996f4c016b69bd7c19e72bd286f6c73143
945
cpp
C++
.LHP/He10/T.Hung/1160/1160/1160.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/He10/T.Hung/1160/1160/1160.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/He10/T.Hung/1160/1160/1160.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
// AC UVa #include "pch.h" #include <iostream> #include <algorithm> #define maxN 100002 #define maxM 10000000001 #define root first #define rank second #define fin -1 typedef int maxn; typedef long long maxm; typedef std::pair <maxn, maxn> info_t; info_t info[maxN]; maxm res; void Init() { res = 0; for (maxn i = 0; i < maxN - 1; i++) { info[i].root = i; info[i].rank = 0; } } maxn Root(maxn x) { while (x != info[x].root) x = info[x].root; return x; } void Union(maxn x, maxn y) { x = Root(x); y = Root(y); if (x == y) { ++res; return; } if (info[x].rank < info[y].rank) info[x].root = y; else { info[y].root = x; if (info[y].rank == info[x].rank) ++info[x].rank; } } int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(0); Init(); maxn a, b; while (std::cin >> a) { if (a == fin) { std::cout << res << '\n'; Init(); } else { std::cin >> b; a; b; Union(a, b); } } }
13.695652
51
0.554497
sxweetlollipop2912
07f05685c2e0b0de37a0a77ffddfc75c3aaeb12d
2,877
hpp
C++
modules/core/adjacent/include/nt2/core/functions/expr/adjfun.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/adjacent/include/nt2/core/functions/expr/adjfun.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/adjacent/include/nt2/core/functions/expr/adjfun.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2011 - 2012 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CORE_FUNCTIONS_EXPR_ADJFUN_HPP_INCLUDED #define NT2_CORE_FUNCTIONS_EXPR_ADJFUN_HPP_INCLUDED #include <nt2/core/functions/adjfun.hpp> #include <nt2/include/functions/firstnonsingleton.hpp> namespace nt2 { namespace ext { /// INTERNAL ONLY BOOST_DISPATCH_IMPLEMENT ( adjfun_, tag::cpu_ , (Functor)(A0) , (unspecified_<Functor>) ((ast_<A0, nt2::container::domain>)) ) { typedef typename boost::proto:: result_of::make_expr< nt2::tag::adjfun_ , container::domain , A0 const& , std::size_t , Functor >::type result_type; BOOST_FORCEINLINE result_type operator()(Functor const& f, A0 const& a0) const { std::size_t along = nt2::firstnonsingleton(a0) - 1u; return boost::proto::make_expr< nt2::tag::adjfun_ , container::domain >( boost::cref(a0), along, f ); } }; /// INTERNAL ONLY BOOST_DISPATCH_IMPLEMENT ( adjfun_, tag::cpu_ , (Functor)(A0)(Along) , (unspecified_<Functor>) ((ast_<A0, nt2::container::domain>)) (scalar_<integer_<Along> >) ) { typedef typename boost::proto:: result_of::make_expr< nt2::tag::adjfun_ , container::domain , A0 const& , std::size_t , Functor >::type result_type; BOOST_FORCEINLINE result_type operator()(Functor const& f, A0 const& a0, Along const& d) const { std::size_t along = d-1; return boost::proto::make_expr< nt2::tag::adjfun_ , container::domain >( boost::cref(a0), along, f ); } }; } } #endif
40.521127
80
0.423705
psiha
07f0e5d3434c131b5f38eff3c277fad17ed5447c
2,914
hxx
C++
opencascade/Extrema_GenLocateExtPS.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/Extrema_GenLocateExtPS.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/Extrema_GenLocateExtPS.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1995-07-18 // Created by: Modelistation // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Extrema_GenLocateExtPS_HeaderFile #define _Extrema_GenLocateExtPS_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> #include <Extrema_POnSurf.hxx> class Standard_DomainError; class StdFail_NotDone; class gp_Pnt; class Adaptor3d_Surface; class Extrema_POnSurf; //! With a close point, it calculates the distance //! between a point and a surface. //! Criteria type is defined in "Perform" method. class Extrema_GenLocateExtPS { public: DEFINE_STANDARD_ALLOC //! Constructor. Standard_EXPORT Extrema_GenLocateExtPS(const Adaptor3d_Surface& theS, const Standard_Real theTolU = Precision::PConfusion(), const Standard_Real theTolV = Precision::PConfusion()); //! Calculates the extrema between the point and the surface using a close point. //! The close point is defined by the parameter values theU0 and theV0. //! Type of the algorithm depends on the isDistanceCriteria flag. //! If flag value is false - normal projection criteria will be used. //! If flag value is true - distance criteria will be used. Standard_EXPORT void Perform(const gp_Pnt& theP, const Standard_Real theU0, const Standard_Real theV0, const Standard_Boolean isDistanceCriteria = Standard_False); //! Returns True if the distance is found. Standard_EXPORT Standard_Boolean IsDone() const; //! Returns the value of the extremum square distance. Standard_EXPORT Standard_Real SquareDistance() const; //! Returns the point of the extremum distance. Standard_EXPORT const Extrema_POnSurf& Point() const; private: const Extrema_GenLocateExtPS& operator=(const Extrema_GenLocateExtPS&); Extrema_GenLocateExtPS(const Extrema_GenLocateExtPS&); // Input. const Adaptor3d_Surface& mySurf; Standard_Real myTolU, myTolV; // State. Standard_Boolean myDone; // Result. Standard_Real mySqDist; Extrema_POnSurf myPoint; }; #endif // _Extrema_GenLocateExtPS_HeaderFile
31.673913
96
0.729581
valgur
07f2bf2d0d9337d16ebe4be5060ea980ee525b14
5,616
cpp
C++
tests/src/map/map_tests_observers.cpp
matboivin/ft_containers
9653552ba3b8eaf215ea37315942c00aeafbf352
[ "WTFPL" ]
null
null
null
tests/src/map/map_tests_observers.cpp
matboivin/ft_containers
9653552ba3b8eaf215ea37315942c00aeafbf352
[ "WTFPL" ]
null
null
null
tests/src/map/map_tests_observers.cpp
matboivin/ft_containers
9653552ba3b8eaf215ea37315942c00aeafbf352
[ "WTFPL" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map_tests_observers.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mboivin <mboivin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/01/24 17:11:14 by mboivin #+# #+# */ /* Updated: 2022/01/24 18:27:13 by mboivin ### ########.fr */ /* */ /* ************************************************************************** */ #include <iomanip> #include <iostream> #include "utility.hpp" #include "tests.hpp" #include "map_tests.hpp" #if defined(TEST_FT) namespace ft #else namespace std #endif { typedef map<std::string,int,size_compare<std::string> > s_int_map; void test_map_key_comp(void) { std::cout << "TEST: Non-member key_comp() \n\n"; explain_test("Returns a copy of the comparison object used by the container" "to compare keys."); // create map int_s_map m1; int_s_map expected1; // get key comparison object int_s_map::key_compare less_comp = m1.key_comp(); std::cout << "map<int, std::string>\n\n"; // insert elements m1.insert(make_pair(200, "foo")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(400, "42")); m1.insert(make_pair(300, "bar")); m1.insert(make_pair(300, "bar")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(100, "qwerty")); // expected result expected1.insert(make_pair(100, "qwerty")); expected1.insert(make_pair(200, "foo")); expected1.insert(make_pair(300, "bar")); expected1.insert(make_pair(400, "42")); int highest1 = m1.rbegin()->first; int_s_map::iterator it1 = m1.begin(); do { std::cout << it1->first << " => " << it1->second << '\n'; } while (less_comp((*it1++).first, highest1)); std::cout << '\n'; // assert map meets expected result assert(m1 == expected1); // create map s_int_map m2; s_int_map expected2; // get key comparison object s_int_map::key_compare strlen_comp = m2.key_comp(); std::cout << "map<std::string, int>\n\n"; // insert elements m2.insert(make_pair("foo", 200)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("foo", 200)); m2.insert(make_pair("foo", 200)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("42", 400)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("bar", 300)); // expected result expected2.insert(make_pair("42", 400)); expected2.insert(make_pair("foo", 200)); expected2.insert(make_pair("qwerty", 100)); std::string highest2 = m2.rbegin()->first; s_int_map::iterator it2 = m2.begin(); do { std::cout << it2->first << " => " << it2->second << '\n'; } while (strlen_comp((*it2++).first, highest2)); std::cout << '\n'; // assert map meets expected result assert(m2 == expected2); } void test_map_value_comp(void) { std::cout << "TEST: Non-member value_comp() \n\n"; explain_test("Returns a copy of the comparison object used by the container" "to compare elements."); // create map int_s_map m1; int_s_map expected1; std::cout << "map<int, std::string>\n\n"; // insert elements m1.insert(make_pair(200, "foo")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(400, "42")); m1.insert(make_pair(300, "bar")); m1.insert(make_pair(300, "bar")); m1.insert(make_pair(100, "qwerty")); m1.insert(make_pair(100, "qwerty")); // expected result expected1.insert(make_pair(100, "qwerty")); expected1.insert(make_pair(200, "foo")); expected1.insert(make_pair(300, "bar")); expected1.insert(make_pair(400, "42")); pair<int,std::string> highest1 = *m1.rbegin(); int_s_map::iterator it1 = m1.begin(); do { std::cout << it1->first << " => " << it1->second << '\n'; } while (m1.value_comp()(*it1++, highest1)); std::cout << '\n'; // assert map meets expected result assert(m1 == expected1); // create map s_int_map m2; s_int_map expected2; std::cout << "map<std::string, int>\n\n"; // insert elements m2.insert(make_pair("foo", 200)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("qwerty", 100)); m2.insert(make_pair("foo", 200)); m2.insert(make_pair("foo", 200)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("42", 400)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("bar", 300)); m2.insert(make_pair("bar", 300)); // expected result expected2.insert(make_pair("42", 400)); expected2.insert(make_pair("foo", 200)); expected2.insert(make_pair("qwerty", 100)); pair<std::string,int> highest2 = *m2.rbegin(); s_int_map::iterator it2 = m2.begin(); do { std::cout << it2->first << " => " << it2->second << '\n'; } while (m2.value_comp()(*it2++, highest2)); std::cout << '\n'; // assert map meets expected result assert(m2 == expected2); } }
29.714286
80
0.552172
matboivin
07f30d7481820e476494c38c19ae0fde8cf76458
2,453
cpp
C++
sdk/boost_1_30_0/libs/spirit/test/parametric_tests.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-01-30T12:51:49.000Z
2020-08-31T08:36:49.000Z
sdk/boost_1_30_0/libs/spirit/test/parametric_tests.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/libs/spirit/test/parametric_tests.cpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
/*============================================================================= Spirit v1.6.0 Copyright (c) 2001-2003 Joel de Guzman http://spirit.sourceforge.net/ Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. =============================================================================*/ #include <iostream> #include <cassert> #include <string> using namespace std; #include "boost/spirit/core.hpp" #include "boost/spirit/attribute/parametric.hpp" #include "boost/spirit/phoenix/primitives.hpp" #include "boost/spirit/phoenix/operators.hpp" using namespace boost::spirit; using namespace phoenix; /////////////////////////////////////////////////////////////////////////////// // // Parametric tests // /////////////////////////////////////////////////////////////////////////////// void parametric_tests() { char ch; rule<> r = anychar_p[var(ch) = arg1] >> *f_ch_p(const_(ch)); parse_info<char const*> pi; pi = parse("aaaaaaaaa", r); assert(pi.hit); assert(pi.full); pi = parse("aaaaabaaa", r); assert(pi.hit); assert(!pi.full); assert(string(pi.stop) == "baaa"); char from = 'a'; char to = 'z'; rule<> r2 = *f_range_p(const_(from), const_(to)); pi = parse("abcdefghijklmnopqrstuvwxyz", r2); assert(pi.hit); assert(pi.full); pi = parse("abcdefghijklmnopqrstuvwxyz123", r2); assert(pi.hit); assert(!pi.full); assert(string(pi.stop) == "123"); char const* start = "kim"; char const* end = start + strlen(start); rule<> r3 = +f_str_p(const_(start), const_(end)); pi = parse("kimkimkimkimkimkimkimkimkim", r3); assert(pi.hit); assert(pi.full); pi = parse("kimkimkimkimkimkimkimkimkimmama", r3); assert(pi.hit); assert(!pi.full); assert(string(pi.stop) == "mama"); pi = parse("joel", r3); assert(!pi.hit); } /////////////////////////////////////////////////////////////////////////////// // // Main // /////////////////////////////////////////////////////////////////////////////// int main() { parametric_tests(); cout << "Tests concluded successfully\n"; return 0; }
27.875
80
0.49735
acidicMercury8
07f455643b86280405bd8ad44d5413901f820d16
690
cpp
C++
Source/Contrib/Libctiny/printf.cpp
Skight/wndspy
b89cc2df88ca3e58b26be491814008aaf6f11122
[ "Apache-2.0" ]
24
2017-03-16T05:32:44.000Z
2021-12-11T13:49:07.000Z
Source/Contrib/Libctiny/printf.cpp
zhen-e-liu/wndspy
b89cc2df88ca3e58b26be491814008aaf6f11122
[ "Apache-2.0" ]
null
null
null
Source/Contrib/Libctiny/printf.cpp
zhen-e-liu/wndspy
b89cc2df88ca3e58b26be491814008aaf6f11122
[ "Apache-2.0" ]
13
2017-03-16T05:26:12.000Z
2021-07-04T16:24:42.000Z
//========================================== // LIBCTINY - Matt Pietrek 2001 // MSDN Magazine, January 2001 //========================================== #include <windows.h> #include <stdio.h> #include <stdarg.h> // Force the linker to include USER32.LIB #pragma comment(linker, "/defaultlib:user32.lib") extern "C" int __cdecl printf(const char * format, ...) { char szBuff[1024]; int retValue; DWORD cbWritten; va_list argptr; va_start( argptr, format ); retValue = wvsprintf( szBuff, format, argptr ); va_end( argptr ); WriteFile( GetStdHandle(STD_OUTPUT_HANDLE), szBuff, retValue, &cbWritten, 0 ); return retValue; }
23.793103
66
0.566667
Skight
07f4b0665a7259791eaa5ca00f5e0bb9e342f08f
1,857
cc
C++
components/password_manager/content/browser/password_requirements_service_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/password_manager/content/browser/password_requirements_service_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/password_manager/content/browser/password_requirements_service_factory.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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 "components/password_manager/content/browser/password_requirements_service_factory.h" #include <map> #include <memory> #include <string> #include "base/memory/singleton.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/core/keyed_service.h" #include "components/password_manager/core/browser/password_requirements_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" namespace password_manager { // static PasswordRequirementsServiceFactory* PasswordRequirementsServiceFactory::GetInstance() { return base::Singleton<PasswordRequirementsServiceFactory>::get(); } // static PasswordRequirementsService* PasswordRequirementsServiceFactory::GetForBrowserContext( content::BrowserContext* context) { return static_cast<PasswordRequirementsService*>( GetInstance()->GetServiceForBrowserContext(context, true /* create */)); } PasswordRequirementsServiceFactory::PasswordRequirementsServiceFactory() : BrowserContextKeyedServiceFactory( "PasswordRequirementsServiceFactory", BrowserContextDependencyManager::GetInstance()) {} PasswordRequirementsServiceFactory::~PasswordRequirementsServiceFactory() {} KeyedService* PasswordRequirementsServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { if (context->IsOffTheRecord()) return nullptr; return CreatePasswordRequirementsService( content::BrowserContext::GetDefaultStoragePartition(context) ->GetURLLoaderFactoryForBrowserProcess()) .release(); } } // namespace password_manager
35.037736
94
0.796446
sarang-apps
07f506ae8a9eb021c51c373cda86f5a3eba4fde8
4,569
hpp
C++
SamSrc/sam/VertexConstraintChecker.hpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
6
2019-08-16T07:13:17.000Z
2021-06-08T21:15:52.000Z
SamSrc/sam/VertexConstraintChecker.hpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
1
2020-05-30T20:35:18.000Z
2020-05-30T20:35:18.000Z
SamSrc/sam/VertexConstraintChecker.hpp
dirkcgrunwald/SAM
0478925c506ad38fd405954cc4415a3e96e77d90
[ "MIT" ]
3
2020-02-17T18:38:14.000Z
2021-03-28T02:47:57.000Z
#ifndef SAM_VERTEX_CONSTRAINT_CHECKER_HPP #define SAM_VERTEX_CONSTRAINT_CHECKER_HPP #include <sam/FeatureMap.hpp> #include <sam/Util.hpp> #include <sam/EdgeDescription.hpp> namespace sam { class VertexConstraintCheckerException : public std::runtime_error { public: VertexConstraintCheckerException(char const * message) : std::runtime_error(message) { } VertexConstraintCheckerException(std::string message) : std::runtime_error(message) { } }; /** * A class that has the logic to check vertex constraints. * Vertex constraints are defined within subgraph queries and form * constraints on individual vertices. The currently supported * constraints are * * in - The vertex is a key in the feature map for a particular feature. * Example: * bait in Top100 * This means that the vertex variable bait has a binding that is found * as a key in the featureMap under feature Top100. * * notIn - Similar to "in", but this time the vertex should not be found * in the feature map for the specified feature. * * TODO: other vertex constraints to be defined. The class seems somewhat * specific to "in" and "notIn", so may be hard to generalize to other * types of vertex constaints. */ template <typename SubgraphQueryType> class VertexConstraintChecker { private: std::shared_ptr<const FeatureMap> featureMap; SubgraphQueryType const* subgraphQuery; public: /** * The constructor for the VertexConstraintChecker class. You provide * 1) featureMap - This is used for the "in" and "notIn" vertex * constraints. We use the featureMap to see if a vertex is found * in the featureMap for a given feature. * 2) The subgraph query itself. The only thing we use the subgraph * query for is to get the list of vertex constraints. * TODO: Might be nice to get rid of the reference to the subgraph * query. */ VertexConstraintChecker(std::shared_ptr<const FeatureMap> featureMap, SubgraphQueryType const* subgraphQuery) { this->featureMap = featureMap; this->subgraphQuery = subgraphQuery; } bool check(std::string variable, std::string vertex) const { DEBUG_PRINT("VertexConstraintChecker checking variable %s vertex %s\n", variable.c_str(), vertex.c_str()); // lambda function that checks that the auto existsVertex = [vertex](Feature const * feature)->bool { auto topKFeature = static_cast<TopKFeature const *>(feature); auto keys = topKFeature->getKeys(); auto it = std::find(keys.begin(), keys.end(), vertex); if (it != keys.end()) { return true; } return false; }; for (auto constraint : subgraphQuery->getConstraints(variable)) { std::string featureName = constraint.featureName; DEBUG_PRINT("VertexConstraintChecker variable %s vertex %s featureName" " %s\n", variable.c_str(), vertex.c_str(), featureName.c_str()); // If the feature doesn't exist, return false. if (!featureMap->exists("", featureName)) { DEBUG_PRINT("VertexConstraintChecker returning false for " "variable %s and vertex %s becaure featureName %s doesn't exist\n", variable.c_str(), vertex.c_str(), featureName.c_str()); return false; } auto feature = featureMap->at("", featureName); switch(constraint.op) { case VertexOperator::In: if (!feature->template evaluate<bool>(existsVertex)) { DEBUG_PRINT("VertexConstraintChecker(In) returning false for " "variable %s and vertex %s\n", variable.c_str(), vertex.c_str()); return false; } break; case VertexOperator::NotIn: if (feature->template evaluate<bool>(existsVertex)) { DEBUG_PRINT("VertexConstraintChecker(NotIn) returning false for" " variable %s and vertex %s\n", variable.c_str(), vertex.c_str()); return false; } break; default: throw VertexConstraintCheckerException( "Unsupported vertex constraint."); } } DEBUG_PRINT("VertexConstraintChecker returning true for variable %s and " "vertex %s\n", variable.c_str(), vertex.c_str()); return true; } /** * * \param variable The variable name of the vertex. * \param vertex The actual value of the vertex. */ bool operator()(std::string variable, std::string vertex) const { return check(variable, vertex); } }; } #endif
33.844444
80
0.664697
dirkcgrunwald
07f5430a6b96954a950a8e9861a1f1ed527049e4
2,532
hpp
C++
src/spinlock_put.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/spinlock_put.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/spinlock_put.hpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#pragma once #include "spinlock_detail.hpp" namespace rev { //! 一時的なロック解除機能を備えたSpinLock /*! あるスレッドがロック中でも一旦アンロックし、別のスレッドがロックできるようにする */ template <class T> class SpinLockPut { private: struct InnerP { SpinLockPut& _s; bool _bLocked; InnerP(InnerP&& p) noexcept: _s(p._s), _bLocked(p._bLocked) { p._bLocked = false; } InnerP(SpinLockPut& s): _s(s) { _bLocked = _s._put(); } ~InnerP() noexcept(false) { if(_bLocked) _s._put_reset(); } }; using Inner = detail::SpinInner<SpinLockPut<T>, T, detail::CallUnlock>; using CInner = detail::SpinInner<SpinLockPut<T>, const T, detail::CallUnlock>; friend struct detail::CallUnlock; using ThreadID_OP = spi::Optional<SDL_threadID>; TLS<int> _tlsCount; ThreadID_OP _lockID; int _lockCount; Mutex _mutex; T _data; void _unlock() NOEXCEPT_IF_RELEASE { D_Assert0(_lockID && *_lockID == *tls_threadID); D_Assert0(_lockCount >= 1); if(--_lockCount == 0) _lockID = spi::none; _mutex.unlock(); } template <class I> I _lock(bool bBlock) { if(bBlock) _mutex.lock(); if(bBlock || _mutex.try_lock()) { if(!_lockID) { _lockCount = 1; _lockID = *tls_threadID; } else { D_Assert0(*_lockID == *tls_threadID); ++_lockCount; } return I(*this, &_data); } return I(*this, nullptr); } void _put_reset() { _mutex.lock(); // TLS変数に対比してた回数分、再度MutexのLock関数を呼ぶ _lockID = *tls_threadID; _lockCount = _tlsCount.get()-1; *_tlsCount = -1; int tmp = _lockCount; while(--tmp != 0) _mutex.lock(); } bool _put() { // 自スレッドがロックしてたらカウンタを退避して一旦解放 if(_mutex.try_lock()) { if(_lockCount > 0) { ++_lockCount; *_tlsCount = _lockCount; // ロックしてた回数をTLS変数に退避 int tmp = _lockCount; _lockCount = 0; _lockID = spi::none; // 今までロックしてた回数分、MutexのUnlock回数を呼ぶ while(tmp-- != 0) _mutex.unlock(); return true; } _mutex.unlock(); } return false; } public: SpinLockPut(): _lockCount(0) { _tlsCount = -1; } Inner lock() { return _lock<Inner>(true); } CInner lockC() const { return const_cast<SpinLockPut*>(this)->_lock<CInner>(true); } Inner try_lock() { return _lock<Inner>(false); } CInner try_lockC() const { return const_cast<SpinLockPut*>(this)->_lock<CInner>(false); } InnerP put() { return InnerP(*this); } }; }
21.827586
81
0.592022
degarashi
07f6de5e46ad8c3c22e62e40f55d61ff9f523441
5,589
cpp
C++
UE4Cleaner/UE4Cleaner.cpp
Vaei/ue4cleaner
ee49f2f6e71f19f2449963c60ecc750b44df70b6
[ "MIT" ]
6
2019-03-01T20:47:13.000Z
2021-05-28T12:37:10.000Z
UE4Cleaner/UE4Cleaner.cpp
Vaei/ue4cleaner
ee49f2f6e71f19f2449963c60ecc750b44df70b6
[ "MIT" ]
null
null
null
UE4Cleaner/UE4Cleaner.cpp
Vaei/ue4cleaner
ee49f2f6e71f19f2449963c60ecc750b44df70b6
[ "MIT" ]
1
2021-02-18T08:32:55.000Z
2021-02-18T08:32:55.000Z
// Copyright (c) 2019 Jared Taylor / Vaei. All Rights Reserved. // UE4Cleaner.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <windows.h> #include <filesystem> using namespace std; namespace fs = std::filesystem; bool StringStartsWith(const string& inString, const string& startsWith) { return (inString.compare(0, startsWith.length(), startsWith) == 0); } bool StringEndsWith(const string& inString, const string& endsWith) { return (inString.compare(inString.length() - endsWith.length(), endsWith.length(), endsWith) == 0); } void StringRemove(string& inString, const string& delimiter) { inString = inString.erase(0, inString.find(delimiter) + delimiter.length()); } string StringReplaceAll(std::string str, const std::string& from, const std::string& to) { size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } return str; } wstring s2ws(const string& str) { if (str.empty()) return std::wstring(); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring wstrTo(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); return wstrTo; } string ws2s(const std::wstring& wstr) { if (wstr.empty()) return std::string(); int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); std::string strTo(size_needed, 0); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); return strTo; } int FatalError(const string& errorString, const int errorId) { const char *errorChar = errorString.c_str(); cout << "[Fatal] " << errorChar << ". Exiting with error code: " << to_string(errorId) << endl; return errorId; } wstring ReadRegValue(HKEY root, wstring key, wstring name) { HKEY hKey; if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS) throw "Could not open registry key"; DWORD type; DWORD cbData; if (RegQueryValueEx(hKey, name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS) { RegCloseKey(hKey); throw "Could not read registry value"; } if (type != REG_SZ) { RegCloseKey(hKey); throw "Incorrect registry value type"; } wstring value(cbData / sizeof(wchar_t), L'\0'); if (RegQueryValueEx(hKey, name.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&value[0]), &cbData) != ERROR_SUCCESS) { RegCloseKey(hKey); throw "Could not read registry value"; } RegCloseKey(hKey); size_t firstNull = value.find_first_of(L'\0'); if (firstNull != string::npos) value.resize(firstNull); return value; } /** * return: number of files or directories deleted */ uintmax_t delete_directory(const string& path) { fs::path dir = path; return fs::remove_all(path); } int main(int argc, char* argv[]) { TCHAR pwd[MAX_PATH]; GetCurrentDirectory(MAX_PATH, pwd); static const wstring regPath = s2ws("Software\\Epic Games\\Unreal Engine\\Builds"); // Path to registry entry used by UE4 when generating project files fs::path path = pwd; bool cleanonly = false; bool plugins = false; // Check if plugins flag is set or if we want to skip generation if (argc > 1) // First is application name { for (int i = 1; i < argc; i++) { if (argv[i] == "/plugins") { plugins = true; } else if (argv[i] == "/clean") { cleanonly = true; } } } // Validate args if (path.string().length() == 0) { return FatalError("Invalid path", 997); } // Check the directory exists if (fs::exists(path)) { // Delete the binaries, intermediate, sln in the project root { fs::path path_binaries = path.string() + "\\binaries"; fs::path path_intermediate = path.string() + "\\intermediate"; if (fs::exists(path_binaries)) { fs::remove_all(path_binaries); } if (fs::exists(path_intermediate)) { fs::remove_all(path_intermediate); } for (const auto& entry : fs::directory_iterator(path)) { if (StringEndsWith(entry.path().string(), ".sln")) { fs::remove_all(entry.path()); break; } } } // Delete the binaries and intermediate for each plugin (if set) if (plugins) { fs::path path_plugins = path.string() + "\\plugins"; if (fs::exists(path_plugins)) { for (const auto& entry : fs::directory_iterator(path_plugins)) { if(fs::is_directory(entry.path())) { fs::path path_binaries = entry.path().string() + "\\binaries"; fs::path path_intermediate = entry.path().string() + "\\intermediate"; if (fs::exists(path_binaries)) { fs::remove_all(path_binaries); } if (fs::exists(path_intermediate)) { fs::remove_all(path_intermediate); } } } } } } else { return FatalError("path does not exist", 995); } // Generate project files... if (!cleanonly) { for (const auto& entry : fs::directory_iterator(path)) { // Locate the .uproject if (StringEndsWith(entry.path().string(), ".uproject")) { system("setlocal"); wstring regVal2 = ReadRegValue(HKEY_CLASSES_ROOT, s2ws("Unreal.ProjectFile\\shell\\rungenproj"), s2ws("Icon")); string sysCmd = "\"" + ws2s(regVal2); sysCmd += " /projectfiles"; sysCmd += " \"" + entry.path().string() + "\""; sysCmd += "\""; system(sysCmd.c_str()); } } } }
25.289593
153
0.658078
Vaei
07f714a997b9d8844043e5114c9cd250832b98e8
10,493
cpp
C++
Firmware/Marlin/src/module/scara.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
97
2020-09-14T13:35:17.000Z
2022-03-28T20:15:49.000Z
Firmware/Marlin/src/module/scara.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
8
2020-11-11T21:01:38.000Z
2022-01-22T01:22:10.000Z
Firmware/Marlin/src/module/scara.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
49
2020-09-22T09:33:37.000Z
2022-03-19T21:23:04.000Z
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * scara.cpp */ #include "../inc/MarlinConfig.h" #if IS_SCARA #include "scara.h" #include "motion.h" #include "planner.h" #if ENABLED(AXEL_TPARA) #include "endstops.h" #include "../MarlinCore.h" #endif float segments_per_second = TERN(AXEL_TPARA, TPARA_SEGMENTS_PER_SECOND, SCARA_SEGMENTS_PER_SECOND); #if EITHER(MORGAN_SCARA, MP_SCARA) static constexpr xy_pos_t scara_offset = { SCARA_OFFSET_X, SCARA_OFFSET_Y }; /** * Morgan SCARA Forward Kinematics. Results in 'cartes'. * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void forward_kinematics(const_float_t a, const_float_t b) { const float a_sin = sin(RADIANS(a)) * L1, a_cos = cos(RADIANS(a)) * L1, b_sin = sin(RADIANS(SUM_TERN(MP_SCARA, b, a))) * L2, b_cos = cos(RADIANS(SUM_TERN(MP_SCARA, b, a))) * L2; cartes.x = a_cos + b_cos + scara_offset.x; // theta cartes.y = a_sin + b_sin + scara_offset.y; // phi /* DEBUG_ECHOLNPAIR( "SCARA FK Angle a=", a, " b=", b, " a_sin=", a_sin, " a_cos=", a_cos, " b_sin=", b_sin, " b_cos=", b_cos ); DEBUG_ECHOLNPAIR(" cartes (X,Y) = "(cartes.x, ", ", cartes.y, ")"); //*/ } #endif #if ENABLED(MORGAN_SCARA) void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { // MORGAN_SCARA uses a Cartesian XY home position xyz_pos_t homeposition = { X_HOME_POS, Y_HOME_POS, Z_HOME_POS }; //DEBUG_ECHOLNPAIR_P(PSTR("homeposition X"), homeposition.x, SP_Y_LBL, homeposition.y); delta = homeposition; forward_kinematics(delta.a, delta.b); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPAIR_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } /** * Morgan SCARA Inverse Kinematics. Results are stored in 'delta'. * * See https://reprap.org/forum/read.php?185,283327 * * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void inverse_kinematics(const xyz_pos_t &raw) { float C2, S2, SK1, SK2, THETA, PSI; // Translate SCARA to standard XY with scaling factor const xy_pos_t spos = raw - scara_offset; const float H2 = HYPOT2(spos.x, spos.y); if (L1 == L2) C2 = H2 / L1_2_2 - 1; else C2 = (H2 - (L1_2 + L2_2)) / (2.0f * L1 * L2); LIMIT(C2, -1, 1); S2 = SQRT(1.0f - sq(C2)); // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End SK1 = L1 + L2 * C2; // Rotated Arm2 gives the distance from Arm1 to Arm2 SK2 = L2 * S2; // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow THETA = ATAN2(SK1, SK2) - ATAN2(spos.x, spos.y); // Angle of Arm2 PSI = ATAN2(S2, C2); delta.set(DEGREES(THETA), DEGREES(SUM_TERN(MORGAN_SCARA, PSI, THETA)), raw.z); /* DEBUG_POS("SCARA IK", raw); DEBUG_POS("SCARA IK", delta); DEBUG_ECHOLNPAIR(" SCARA (x,y) ", sx, ",", sy, " C2=", C2, " S2=", S2, " Theta=", THETA, " Psi=", PSI); //*/ } #elif ENABLED(MP_SCARA) void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { // MP_SCARA uses arm angles for AB home position #ifndef SCARA_OFFSET_THETA1 #define SCARA_OFFSET_THETA1 12 // degrees #endif #ifndef SCARA_OFFSET_THETA2 #define SCARA_OFFSET_THETA2 131 // degrees #endif ab_float_t homeposition = { SCARA_OFFSET_THETA1, SCARA_OFFSET_THETA2 }; //DEBUG_ECHOLNPAIR("homeposition A:", homeposition.a, " B:", homeposition.b); inverse_kinematics(homeposition); forward_kinematics(delta.a, delta.b); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPAIR_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } void inverse_kinematics(const xyz_pos_t &raw) { const float x = raw.x, y = raw.y, c = HYPOT(x, y), THETA3 = ATAN2(y, x), THETA1 = THETA3 + ACOS((sq(c) + sq(L1) - sq(L2)) / (2.0f * c * L1)), THETA2 = THETA3 - ACOS((sq(c) + sq(L2) - sq(L1)) / (2.0f * c * L2)); delta.set(DEGREES(THETA1), DEGREES(THETA2), raw.z); /* DEBUG_POS("SCARA IK", raw); DEBUG_POS("SCARA IK", delta); SERIAL_ECHOLNPAIR(" SCARA (x,y) ", x, ",", y," Theta1=", THETA1, " Theta2=", THETA2); //*/ } #elif ENABLED(AXEL_TPARA) static constexpr xyz_pos_t robot_offset = { TPARA_OFFSET_X, TPARA_OFFSET_Y, TPARA_OFFSET_Z }; void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { xyz_pos_t homeposition = { X_HOME_POS, Y_HOME_POS, Z_HOME_POS }; //DEBUG_ECHOLNPAIR_P(PSTR("homeposition X"), homeposition.x, SP_Y_LBL, homeposition.y, SP_Z_LBL, homeposition.z); inverse_kinematics(homeposition); forward_kinematics(delta.a, delta.b, delta.c); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPAIR_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } // Convert ABC inputs in degrees to XYZ outputs in mm void forward_kinematics(const_float_t a, const_float_t b, const_float_t c) { const float w = c - b, r = L1 * cos(RADIANS(b)) + L2 * sin(RADIANS(w - (90 - b))), x = r * cos(RADIANS(a)), y = r * sin(RADIANS(a)), rho2 = L1_2 + L2_2 - 2.0f * L1 * L2 * cos(RADIANS(w)); cartes = robot_offset + xyz_pos_t({ x, y, SQRT(rho2 - sq(x) - sq(y)) }); } // Home YZ together, then X (or all at once). Based on quick_home_xy & home_delta void home_TPARA() { // Init the current position of all carriages to 0,0,0 current_position.reset(); destination.reset(); sync_plan_position(); // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) TERN_(X_SENSORLESS, sensorless_t stealth_states_x = start_sensorless_homing_per_axis(X_AXIS)); TERN_(Y_SENSORLESS, sensorless_t stealth_states_y = start_sensorless_homing_per_axis(Y_AXIS)); TERN_(Z_SENSORLESS, sensorless_t stealth_states_z = start_sensorless_homing_per_axis(Z_AXIS)); #endif //const int x_axis_home_dir = TOOL_X_HOME_DIR(active_extruder); //const xy_pos_t pos { max_length(X_AXIS) , max_length(Y_AXIS) }; //const float mlz = max_length(X_AXIS), // Move all carriages together linearly until an endstop is hit. //do_blocking_move_to_xy_z(pos, mlz, homing_feedrate(Z_AXIS)); current_position.x = 0 ; current_position.y = 0 ; current_position.z = max_length(Z_AXIS) ; line_to_current_position(homing_feedrate(Z_AXIS)); planner.synchronize(); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) TERN_(X_SENSORLESS, end_sensorless_homing_per_axis(X_AXIS, stealth_states_x)); TERN_(Y_SENSORLESS, end_sensorless_homing_per_axis(Y_AXIS, stealth_states_y)); TERN_(Z_SENSORLESS, end_sensorless_homing_per_axis(Z_AXIS, stealth_states_z)); #endif endstops.validate_homing_move(); // At least one motor has reached its endstop. // Now re-home each motor separately. homeaxis(A_AXIS); homeaxis(C_AXIS); homeaxis(B_AXIS); // Set all carriages to their home positions // Do this here all at once for Delta, because // XYZ isn't ABC. Applying this per-tower would // give the impression that they are the same. LOOP_LINEAR_AXES(i) set_axis_is_at_home((AxisEnum)i); sync_plan_position(); } void inverse_kinematics(const xyz_pos_t &raw) { const xyz_pos_t spos = raw - robot_offset; const float RXY = SQRT(HYPOT2(spos.x, spos.y)), RHO2 = NORMSQ(spos.x, spos.y, spos.z), //RHO = SQRT(RHO2), LSS = L1_2 + L2_2, LM = 2.0f * L1 * L2, CG = (LSS - RHO2) / LM, SG = SQRT(1 - POW(CG, 2)), // Method 2 K1 = L1 - L2 * CG, K2 = L2 * SG, // Angle of Body Joint THETA = ATAN2(spos.y, spos.x), // Angle of Elbow Joint //GAMMA = ACOS(CG), GAMMA = ATAN2(SG, CG), // Method 2 // Angle of Shoulder Joint, elevation angle measured from horizontal (r+) //PHI = asin(spos.z/RHO) + asin(L2 * sin(GAMMA) / RHO), PHI = ATAN2(spos.z, RXY) + ATAN2(K2, K1), // Method 2 // Elbow motor angle measured from horizontal, same frame as shoulder (r+) PSI = PHI + GAMMA; delta.set(DEGREES(THETA), DEGREES(PHI), DEGREES(PSI)); //SERIAL_ECHOLNPAIR(" SCARA (x,y,z) ", spos.x , ",", spos.y, ",", spos.z, " Rho=", RHO, " Rho2=", RHO2, " Theta=", THETA, " Phi=", PHI, " Psi=", PSI, " Gamma=", GAMMA); } #endif void scara_report_positions() { SERIAL_ECHOLNPAIR("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS) #if ENABLED(AXEL_TPARA) , " Phi:", planner.get_axis_position_degrees(B_AXIS) , " Psi:", planner.get_axis_position_degrees(C_AXIS) #else , " Psi" TERN_(MORGAN_SCARA, "+Theta") ":", planner.get_axis_position_degrees(B_AXIS) #endif ); SERIAL_EOL(); } #endif // IS_SCARA
33.848387
172
0.636805
jhNsXO
07fa8bf96c8e7a17d0afc8adf538f6421f13d545
1,933
cpp
C++
AdenitaCoreSE/source/ADNMixins.cpp
edellano/Adenita-SAMSON-Edition-Win-
6df8d21572ef40fe3fc49165dfaa1d4318352a69
[ "BSD-3-Clause" ]
2
2020-09-07T20:48:43.000Z
2021-09-03T05:49:59.000Z
AdenitaCoreSE/source/ADNMixins.cpp
edellano/Adenita-SAMSON-Edition-Linux
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
[ "BSD-3-Clause" ]
6
2020-04-05T18:39:28.000Z
2022-01-11T14:28:55.000Z
AdenitaCoreSE/source/ADNMixins.cpp
edellano/Adenita-SAMSON-Edition-Linux
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
[ "BSD-3-Clause" ]
2
2021-07-13T12:58:13.000Z
2022-01-11T13:52:00.000Z
#include "ADNMixins.hpp" Nameable::Nameable(const Nameable & other) { *this = other; } Nameable & Nameable::operator=(const Nameable & other) { if (&other == this) { return *this; } SetName(other.GetName()); return *this; } void Nameable::SetName(std::string name) { name_ = name; } std::string Nameable::GetName() const { return name_; } Positionable::Positionable(const Positionable & other) { *this = other; } Positionable & Positionable::operator=(const Positionable & other) { if (&other == this) { return *this; } SetPosition(other.GetPosition()); return *this; } void Positionable::SetPosition(ublas::vector<double> pos) { position_ = pos; } ublas::vector<double> Positionable::GetPosition() const { return position_; } Identifiable::Identifiable(const Identifiable & other) { *this = other; } Identifiable & Identifiable::operator=(const Identifiable & other) { if (&other == this) { return *this; } SetId(other.GetId()); return *this; } void Identifiable::SetId(int id) { id_ = id; } int Identifiable::GetId() const { return id_; } Orientable::Orientable() { e1_ = ublas::vector<double>(3, 0.0); e2_ = ublas::vector<double>(3, 0.0); e3_ = ublas::vector<double>(3, 0.0); } Orientable::Orientable(const Orientable & other) { *this = other; } Orientable & Orientable::operator=(const Orientable & other) { if (&other == this) { return *this; } SetE1(other.GetE1()); SetE2(other.GetE2()); SetE3(other.GetE3()); return *this; } void Orientable::SetE1(ublas::vector<double> e1) { e1_ = e1; } void Orientable::SetE2(ublas::vector<double> e2) { e2_ = e2; } void Orientable::SetE3(ublas::vector<double> e3) { e3_ = e3; } ublas::vector<double> Orientable::GetE1() const { return e1_; } ublas::vector<double> Orientable::GetE2() const { return e2_; } ublas::vector<double> Orientable::GetE3() const { return e3_; }
14.318519
66
0.65701
edellano
5804ce8b05c4fe8086a3c4f7d09e5810ef183624
2,271
cpp
C++
201512/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
23
2021-03-01T07:07:48.000Z
2022-03-19T12:49:14.000Z
201512/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
null
null
null
201512/3.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
2
2021-08-30T09:35:17.000Z
2021-09-10T12:26:13.000Z
#include <iostream> #include <cstring> #include <algorithm> #include <queue> #define x first #define y second using namespace std; typedef pair<int, int> pii; const int N = 110; bool visited[N][N]; char g[N][N]; int st[N][N]; int m, n, q; // st 0 : '.' 1 : '-' 2 : '|' 3 : '+' void op0(int x1, int y1, int x2, int y2) { if (y1 == y2) { int x_min = min(x1, x2), x_max = max(x1, x2); for (int i = x_min; i <= x_max; i++) { if (st[i][y1] == 0) st[i][y1] = 2; else if (st[i][y1] == 1) st[i][y1] = 3; else continue; } } else { int y_min = min(y1, y2), y_max = max(y1, y2); for (int i = y_min; i <= y_max; i++) { if (st[x1][i] == 0) st[x1][i] = 1; else if (st[x1][i] == 2) st[x1][i] = 3; else continue; } } } void op1(int sx, int sy, char ch) { int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; memset(visited, false, sizeof visited); queue<pii> q; q.push({sx, sy}); visited[sx][sy] = true; while(q.size()) { pii p = q.front(); q.pop(); int x = p.x, y = p.y; g[x][y] = ch; for (int i = 0; i < 4; i++) { int a = x + dx[i], b = y + dy[i]; if (a < 0 || a >= n || b < 0 || b >= m || visited[a][b]) continue; if (st[a][b] != 0) continue; q.push({a, b}); visited[a][b] = true; } } } int main() { cin >> m >> n >> q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { g[i][j] = '.'; } } while(q --) { int op; cin >> op; if (op == 0) { int x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; op0(n - 1 - y1, x1, n - 1 - y2, x2); } else { int x, y; char ch; cin >> x >> y >> ch; op1(n - 1 - y, x, ch); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (st[i][j] == 1) g[i][j] = '-'; if (st[i][j] == 2) g[i][j] = '|'; if (st[i][j] == 3) g[i][j] = '+'; cout << g[i][j]; } cout << endl; } return 0; }
22.048544
78
0.359313
qzylalala
5805aa0d94e61eb592d413180b2403d51b90a449
3,085
hpp
C++
external/boost_1_60_0/qsboost/preprocessor/repetition/enum_shifted_binary_params.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/preprocessor/repetition/enum_shifted_binary_params.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/preprocessor/repetition/enum_shifted_binary_params.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2005. * # * Distributed under the Boost Software License, Version 1.0. (See * # * accompanying file LICENSE_1_0.txt or copy at * # * http://www.boost.org/LICENSE_1_0.txt) * # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef QSBOOST_PREPROCESSOR_REPETITION_ENUM_SHIFTED_BINARY_PARAMS_HPP # define QSBOOST_PREPROCESSOR_REPETITION_ENUM_SHIFTED_BINARY_PARAMS_HPP # # include <qsboost/preprocessor/arithmetic/dec.hpp> # include <qsboost/preprocessor/arithmetic/inc.hpp> # include <qsboost/preprocessor/cat.hpp> # include <qsboost/preprocessor/config/config.hpp> # include <qsboost/preprocessor/punctuation/comma_if.hpp> # include <qsboost/preprocessor/repetition/repeat.hpp> # include <qsboost/preprocessor/tuple/elem.hpp> # include <qsboost/preprocessor/tuple/rem.hpp> # # /* BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS */ # # if ~QSBOOST_PP_CONFIG_FLAGS() & QSBOOST_PP_CONFIG_EDG() # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(count, p1, p2) QSBOOST_PP_REPEAT(QSBOOST_PP_DEC(count), QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2)) # else # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(count, p1, p2) QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_I(count, p1, p2) # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_I(count, p1, p2) QSBOOST_PP_REPEAT(QSBOOST_PP_DEC(count), QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2)) # endif # # if QSBOOST_PP_CONFIG_FLAGS() & QSBOOST_PP_CONFIG_STRICT() # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M(z, n, pp) QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_IM(z, n, QSBOOST_PP_TUPLE_REM_2 pp) # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_IM(z, n, im) QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, im) # else # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M(z, n, pp) QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, QSBOOST_PP_TUPLE_ELEM(2, 0, pp), QSBOOST_PP_TUPLE_ELEM(2, 1, pp)) # endif # # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, p1, p2) QSBOOST_PP_COMMA_IF(n) QSBOOST_PP_CAT(p1, QSBOOST_PP_INC(n)) QSBOOST_PP_CAT(p2, QSBOOST_PP_INC(n)) # # /* BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z */ # # if ~QSBOOST_PP_CONFIG_FLAGS() & QSBOOST_PP_CONFIG_EDG() # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z(z, count, p1, p2) QSBOOST_PP_REPEAT_ ## z(QSBOOST_PP_DEC(count), QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2)) # else # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z(z, count, p1, p2) QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z_I(z, count, p1, p2) # define QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z_I(z, count, p1, p2) QSBOOST_PP_REPEAT_ ## z(QSBOOST_PP_DEC(count), QSBOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2)) # endif # # endif
59.326923
175
0.688817
wouterboomsma
5806a5ead19491e1c86e80cb17d2578fdb96bea8
2,431
cpp
C++
src/border.cpp
Arian8j2/YourCraft
6afe4e50afe678e2d38b60e816adf0a9d320f01a
[ "MIT" ]
4
2021-03-02T21:02:51.000Z
2021-11-19T22:16:05.000Z
src/border.cpp
Arian8j2/YourCraft
6afe4e50afe678e2d38b60e816adf0a9d320f01a
[ "MIT" ]
null
null
null
src/border.cpp
Arian8j2/YourCraft
6afe4e50afe678e2d38b60e816adf0a9d320f01a
[ "MIT" ]
null
null
null
#include "border.h" #include "player.h" CBorder::CBorder(CGameContext* pGameContext): m_pGameContext(pGameContext){ glGenVertexArrays(1, &m_VAO); glBindVertexArray(m_VAO); glGenBuffers(1, &m_VBO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); float aVerticies[] = { -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f }; glBufferData(GL_ARRAY_BUFFER, sizeof(aVerticies), aVerticies, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(float)*3, 0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float)*3, 0); glEnableVertexAttribArray(1); glLineWidth(1.5f); } void CBorder::Render(glm::vec3& Pos){ glUseProgram(m_pGameContext->GetBlockProgram()); static uint32_t s_BlockPosUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uBlockPos"); static uint32_t s_PlayerViewUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uView"); static uint32_t s_ProjectionUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uProjection"); static uint32_t s_ColorUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uColor"); glm::mat4 MatPos(1.0f); MatPos[3] = glm::vec4(Pos, 1.0f); static glm::mat4 s_Projection = glm::perspective(glm::radians((float) m_pGameContext->GetSettingValue("fov").GetInt()), (float)m_pGameContext->m_Width / m_pGameContext->m_Height, 0.101f, 100.0f); glBindVertexArray(m_VAO); glUniformMatrix4fv(s_BlockPosUniform, 1, 0, glm::value_ptr(MatPos)); glUniformMatrix4fv(s_PlayerViewUniform, 1, 0, glm::value_ptr(m_pGameContext->GetPlayer()->m_View)); glUniformMatrix4fv(s_ProjectionUniform, 1, 0, glm::value_ptr(s_Projection)); glUniform3f(s_ColorUniform, 0.0f, 0.0f, 0.0f); glBindVertexArray(m_VAO); for(int i=0; i < 4; i++) glDrawArrays(GL_LINE_LOOP, i*4, 4); } CBorder::~CBorder(){ glDeleteVertexArrays(1, &m_VAO); glDeleteBuffers(1, &m_VBO); }
33.30137
199
0.640889
Arian8j2
580b0dd7cdf7930b6cb85c6e67947634df7d42a1
4,742
hpp
C++
engine/source/public/core/anton_crt.hpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
12
2019-01-02T11:13:19.000Z
2020-06-02T10:58:20.000Z
engine/source/public/core/anton_crt.hpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
null
null
null
engine/source/public/core/anton_crt.hpp
kociap/GameEngine
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
[ "MIT" ]
1
2020-04-03T11:54:53.000Z
2020-04-03T11:54:53.000Z
#pragma once #if defined(_WIN64) #define ANTON_NOEXCEPT #define ANTON_CRT_IMPORT __declspec(dllimport) #define size_t unsigned long long #else #define ANTON_NOEXCEPT noexcept #define ANTON_CRT_IMPORT #define size_t unsigned long int #endif // C Runtime Forward Declarations extern "C" { // stddef.h #ifndef offsetof #define offsetof(s,m) __builtin_offsetof(s,m) #endif // time.h struct timespec; // math.h ANTON_CRT_IMPORT float powf(float, float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float sqrtf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float cbrtf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float roundf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float floorf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float ceilf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float modff(float, float*) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float sinf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float cosf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float tanf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float asinf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float acosf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float atanf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float atan2f(float, float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float expf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float logf(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float log10f(float) ANTON_NOEXCEPT; ANTON_CRT_IMPORT float log2f(float) ANTON_NOEXCEPT; // string.h // memset, memmove, memcpy, strlen don't use dllimport on win. void* memset(void* dest, int value, size_t count); void* memcpy(void* dest, void const* src, size_t count); void* memmove(void* dest, void const* src, size_t count); int memcmp(void const* lhs, void const* rhs, size_t count); size_t strlen(char const* string); // stdlib.h ANTON_CRT_IMPORT float strtof(char const*, char**); ANTON_CRT_IMPORT double strtod(char const*, char**); ANTON_CRT_IMPORT long long strtoll(char const*, char**, int base); ANTON_CRT_IMPORT unsigned long long strtoull(char const*, char**, int base); // stdio.h #if defined(_WIN64) #ifndef _FILE_DEFINED #define _FILE_DEFINED typedef struct _iobuf { void* _Placeholder; } FILE; #endif ANTON_CRT_IMPORT FILE* __acrt_iob_func(unsigned _Ix); #define stdin (__acrt_iob_func(0)) #define stdout (__acrt_iob_func(1)) #define stderr (__acrt_iob_func(2)) #else #ifndef __FILE_defined #define __FILE_defined 1 typedef struct _IO_FILE FILE; #endif extern FILE* stdin; extern FILE* stdout; extern FILE* stderr; #endif #define SEEK_SET 0 #define SEEK_CUR 1 #define SEEK_END 2 #define EOF (-1) #if defined(_WIN64) #define ANTON_CRT_STDIO_NOEXCEPT #else #define ANTON_CRT_STDIO_NOEXCEPT noexcept #endif ANTON_CRT_IMPORT FILE* fopen(char const* filename, char const* modes); ANTON_CRT_IMPORT FILE* freopen(char const* filename, char const* mode, FILE* stream); ANTON_CRT_IMPORT int fclose(FILE* stream); ANTON_CRT_IMPORT int fflush(FILE* stream); ANTON_CRT_IMPORT void setbuf(FILE* stream, char* buffer) ANTON_CRT_STDIO_NOEXCEPT; ANTON_CRT_IMPORT int setvbuf(FILE* stream, char* buffer, int mode, size_t size) ANTON_CRT_STDIO_NOEXCEPT; ANTON_CRT_IMPORT size_t fread(void* buffer, size_t size, size_t count, FILE* stream); ANTON_CRT_IMPORT size_t fwrite(void const* buffer, size_t size, size_t count, FILE* stream); ANTON_CRT_IMPORT int fgetc(FILE* stream); ANTON_CRT_IMPORT char* fgets(char*, int count, FILE* stream); ANTON_CRT_IMPORT char* gets(char* string); ANTON_CRT_IMPORT int getchar(void); ANTON_CRT_IMPORT int fputc(int ch, FILE* stream); ANTON_CRT_IMPORT int fputs(char const* string, FILE* stream); ANTON_CRT_IMPORT int puts(char const* string); ANTON_CRT_IMPORT int putchar(int ch); ANTON_CRT_IMPORT int ungetc(int ch, FILE* stream); ANTON_CRT_IMPORT long ftell(FILE* stream); ANTON_CRT_IMPORT int fseek(FILE* stream, long offset, int origin); ANTON_CRT_IMPORT void rewind(FILE* stream); ANTON_CRT_IMPORT int ferror(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT; ANTON_CRT_IMPORT int feof(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT; ANTON_CRT_IMPORT void clearerr(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT; #undef ANTON_CRT_STDIO_NOEXCEPT } // C++ Runtime Forward Declarations void* operator new(size_t size, void*) noexcept; void operator delete(void* ptr, void* place) noexcept; #undef ANTON_CRT_IMPORT #undef size_t
34.362319
109
0.715943
kociap
580b1ef2bd4ec2ab59c00d0adbdb9f9e5d84f163
26,436
cpp
C++
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
AftermathK/Autoware
88a1f088eba5878d88e95ecb88cd9389a4bad4b3
[ "BSD-3-Clause" ]
2
2019-01-29T10:50:56.000Z
2021-12-20T07:20:13.000Z
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
ShawnSchaerer/Autoware
c2ba68b4e9f42136e6f055a9cd278dcebdcbab17
[ "BSD-3-Clause" ]
null
null
null
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
ShawnSchaerer/Autoware
c2ba68b4e9f42136e6f055a9cd278dcebdcbab17
[ "BSD-3-Clause" ]
2
2019-01-29T10:51:00.000Z
2020-09-13T04:52:44.000Z
/* * Copyright (c) 2018, Nagoya University * 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 Autoware 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************** * v1.0: amc-nu (abrahammonrroy@yahoo.com) * * range_vision_fusion_node.cpp * * Created on: July, 05th, 2018 */ #include "range_vision_fusion/range_vision_fusion.h" cv::Point3f RosRangeVisionFusionApp::TransformPoint(const geometry_msgs::Point &in_point, const tf::StampedTransform &in_transform) { tf::Vector3 tf_point(in_point.x, in_point.y, in_point.z); tf::Vector3 tf_point_t = in_transform * tf_point; return cv::Point3f(tf_point_t.x(), tf_point_t.y(), tf_point_t.z()); } cv::Point2i RosRangeVisionFusionApp::ProjectPoint(const cv::Point3f &in_point) { auto u = int(in_point.x * fx_ / in_point.z + cx_); auto v = int(in_point.y * fy_ / in_point.z + cy_); return cv::Point2i(u, v); } autoware_msgs::DetectedObject RosRangeVisionFusionApp::TransformObject(const autoware_msgs::DetectedObject &in_detection, const tf::StampedTransform& in_transform) { autoware_msgs::DetectedObject t_obj = in_detection; tf::Vector3 in_pos(in_detection.pose.position.x, in_detection.pose.position.y, in_detection.pose.position.z); tf::Quaternion in_quat(in_detection.pose.orientation.x, in_detection.pose.orientation.y, in_detection.pose.orientation.w, in_detection.pose.orientation.z); tf::Vector3 in_pos_t = in_transform * in_pos; tf::Quaternion in_quat_t = in_transform * in_quat; t_obj.pose.position.x = in_pos_t.x(); t_obj.pose.position.y = in_pos_t.y(); t_obj.pose.position.z = in_pos_t.z(); t_obj.pose.orientation.x = in_quat_t.x(); t_obj.pose.orientation.y = in_quat_t.y(); t_obj.pose.orientation.z = in_quat_t.z(); t_obj.pose.orientation.w = in_quat_t.w(); return t_obj; } bool RosRangeVisionFusionApp::IsObjectInImage(const autoware_msgs::DetectedObject &in_detection) { cv::Point3f image_space_point = TransformPoint(in_detection.pose.position, camera_lidar_tf_); cv::Point2i image_pixel = ProjectPoint(image_space_point); return (image_pixel.x >= 0) && (image_pixel.x < image_size_.width) && (image_pixel.y >= 0) && (image_pixel.y < image_size_.height) && (image_space_point.z > 0); } cv::Rect RosRangeVisionFusionApp::ProjectDetectionToRect(const autoware_msgs::DetectedObject &in_detection) { cv::Rect projected_box; Eigen::Vector3f pos; pos << in_detection.pose.position.x, in_detection.pose.position.y, in_detection.pose.position.z; Eigen::Quaternionf rot(in_detection.pose.orientation.w, in_detection.pose.orientation.x, in_detection.pose.orientation.y, in_detection.pose.orientation.z); std::vector<double> dims = {in_detection.dimensions.x, in_detection.dimensions.y, in_detection.dimensions.z}; jsk_recognition_utils::Cube cube(pos, rot, dims); Eigen::Affine3f range_vision_tf; tf::transformTFToEigen(camera_lidar_tf_, range_vision_tf); jsk_recognition_utils::Vertices vertices = cube.transformVertices(range_vision_tf); std::vector<cv::Point> polygon; for (auto &vertex : vertices) { cv::Point p = ProjectPoint(cv::Point3f(vertex.x(), vertex.y(), vertex.z())); polygon.push_back(p); } projected_box = cv::boundingRect(polygon); return projected_box; } void RosRangeVisionFusionApp::TransformRangeToVision(const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections, autoware_msgs::DetectedObjectArray &out_in_cv_range_detections, autoware_msgs::DetectedObjectArray &out_out_cv_range_detections) { out_in_cv_range_detections.header = in_range_detections->header; out_in_cv_range_detections.objects.clear(); out_out_cv_range_detections.header = in_range_detections->header; out_out_cv_range_detections.objects.clear(); for (size_t i= 0; i < in_range_detections->objects.size(); i++) { if(IsObjectInImage(in_range_detections->objects[i])) { out_in_cv_range_detections.objects.push_back(in_range_detections->objects[i]); } else { out_out_cv_range_detections.objects.push_back(in_range_detections->objects[i]); } } } void RosRangeVisionFusionApp::CalculateObjectFeatures(autoware_msgs::DetectedObject &in_out_object, bool in_estimate_pose) { float min_x=std::numeric_limits<float>::max();float max_x=-std::numeric_limits<float>::max(); float min_y=std::numeric_limits<float>::max();float max_y=-std::numeric_limits<float>::max(); float min_z=std::numeric_limits<float>::max();float max_z=-std::numeric_limits<float>::max(); float average_x = 0, average_y = 0, average_z = 0, length, width, height; pcl::PointXYZ centroid, min_point, max_point, average_point; std::vector<cv::Point2f> object_2d_points; pcl::PointCloud<pcl::PointXYZ> in_cloud; pcl::fromROSMsg(in_out_object.pointcloud, in_cloud); for (const auto &point : in_cloud.points) { average_x+=point.x; average_y+=point.y; average_z+=point.z; centroid.x += point.x; centroid.y += point.y; centroid.z += point.z; if(point.x<min_x) min_x = point.x; if(point.y<min_y) min_y = point.y; if(point.z<min_z) min_z = point.z; if(point.x>max_x) max_x = point.x; if(point.y>max_y) max_y = point.y; if(point.z>max_z) max_z = point.z; cv::Point2f pt; pt.x = point.x; pt.y = point.y; object_2d_points.push_back(pt); } min_point.x = min_x; min_point.y = min_y; min_point.z = min_z; max_point.x = max_x; max_point.y = max_y; max_point.z = max_z; if (in_cloud.points.size() > 0) { centroid.x /= in_cloud.points.size(); centroid.y /= in_cloud.points.size(); centroid.z /= in_cloud.points.size(); average_x /= in_cloud.points.size(); average_y /= in_cloud.points.size(); average_z /= in_cloud.points.size(); } average_point.x = average_x; average_point.y = average_y; average_point.z = average_z; length = max_point.x - min_point.x; width = max_point.y - min_point.y; height = max_point.z - min_point.z; geometry_msgs::PolygonStamped convex_hull; std::vector<cv::Point2f> hull_points; if (object_2d_points.size() > 0) cv::convexHull(object_2d_points, hull_points); convex_hull.header = in_out_object.header; for (size_t i = 0; i < hull_points.size() + 1 ; i++) { geometry_msgs::Point32 point; point.x = hull_points[i%hull_points.size()].x; point.y = hull_points[i%hull_points.size()].y; point.z = min_point.z; convex_hull.polygon.points.push_back(point); } for (size_t i = 0; i < hull_points.size() + 1 ; i++) { geometry_msgs::Point32 point; point.x = hull_points[i%hull_points.size()].x; point.y = hull_points[i%hull_points.size()].y; point.z = max_point.z; convex_hull.polygon.points.push_back(point); } double rz = 0; if (in_estimate_pose) { cv::RotatedRect box = cv::minAreaRect(hull_points); rz = box.angle*3.14/180; in_out_object.pose.position.x = box.center.x; in_out_object.pose.position.y = box.center.y; in_out_object.dimensions.x = box.size.width; in_out_object.dimensions.y = box.size.height; } in_out_object.convex_hull = convex_hull; in_out_object.pose.position.x = min_point.x + length/2; in_out_object.pose.position.y = min_point.y + width/2; in_out_object.pose.position.z = min_point.z + height/2; in_out_object.dimensions.x = ((length<0)?-1*length:length); in_out_object.dimensions.y = ((width<0)?-1*width:width); in_out_object.dimensions.z = ((height<0)?-1*height:height); tf::Quaternion quat = tf::createQuaternionFromRPY(0.0, 0.0, rz); tf::quaternionTFToMsg(quat, in_out_object.pose.orientation); } autoware_msgs::DetectedObject RosRangeVisionFusionApp::MergeObjects(const autoware_msgs::DetectedObject &in_object_a, const autoware_msgs::DetectedObject & in_object_b) { autoware_msgs::DetectedObject object_merged; object_merged = in_object_b; pcl::PointCloud<pcl::PointXYZ> cloud_a, cloud_b, cloud_merged; if (!in_object_a.pointcloud.data.empty()) pcl::fromROSMsg(in_object_a.pointcloud, cloud_a); if (!in_object_b.pointcloud.data.empty()) pcl::fromROSMsg(in_object_b.pointcloud, cloud_b); cloud_merged = cloud_a + cloud_b; sensor_msgs::PointCloud2 cloud_msg; pcl::toROSMsg(cloud_merged, cloud_msg); cloud_msg.header = object_merged.pointcloud.header; object_merged.pointcloud = cloud_msg; return object_merged; } double RosRangeVisionFusionApp::GetDistanceToObject(const autoware_msgs::DetectedObject &in_object) { return sqrt(in_object.dimensions.x*in_object.dimensions.x + in_object.dimensions.y*in_object.dimensions.y + in_object.dimensions.z*in_object.dimensions.z); } autoware_msgs::DetectedObjectArray RosRangeVisionFusionApp::FuseRangeVisionDetections(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections, const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections) { autoware_msgs::DetectedObjectArray range_in_cv; autoware_msgs::DetectedObjectArray range_out_cv; TransformRangeToVision(in_range_detections, range_in_cv, range_out_cv); autoware_msgs::DetectedObjectArray fused_objects; fused_objects.header = in_range_detections->header; std::vector< std::vector<size_t> > vision_range_assignments (in_vision_detections->objects.size()); std::vector< long > vision_range_closest (in_vision_detections->objects.size()); for (size_t i = 0; i < in_vision_detections->objects.size(); i++) { auto vision_object = in_vision_detections->objects[i]; cv::Rect vision_rect(vision_object.x, vision_object.y, vision_object.width, vision_object.height); int vision_rect_area = vision_rect.area(); long closest_index = -1; double closest_distance = std::numeric_limits<double>::max(); for (size_t j = 0; j < range_in_cv.objects.size(); j++) { double current_distance = GetDistanceToObject(range_in_cv.objects[j]); cv::Rect range_rect = ProjectDetectionToRect(range_in_cv.objects[j]); int range_rect_area = range_rect.area(); cv::Rect overlap = range_rect & vision_rect; if ( (overlap.area() > range_rect_area*overlap_threshold_) || (overlap.area() > vision_rect_area*overlap_threshold_) ) { vision_range_assignments[i].push_back(j); range_in_cv.objects[j].score = vision_object.score; range_in_cv.objects[j].label = vision_object.label; range_in_cv.objects[j].color = vision_object.color; range_in_cv.objects[j].image_frame = vision_object.image_frame; range_in_cv.objects[j].x = vision_object.x; range_in_cv.objects[j].y = vision_object.y; range_in_cv.objects[j].width = vision_object.width; range_in_cv.objects[j].height = vision_object.height; range_in_cv.objects[j].angle = vision_object.angle; if(current_distance < closest_distance) { closest_index = j; closest_distance = current_distance; } } } vision_range_closest[i] = closest_index; } std::vector<bool> used_range_detections(range_in_cv.objects.size(), false); //only assign the closest for(size_t i = 0; i < vision_range_assignments.size(); i++) { if(!range_in_cv.objects.empty() && vision_range_closest[i] >= 0) { used_range_detections[i] = true; fused_objects.objects.push_back(range_in_cv.objects[vision_range_closest[i]]); } } /* for(size_t i = 0; i < vision_range_assignments.size(); i++) { autoware_msgs::DetectedObject merged_object = range_in_cv.objects[0]; for(const auto& range_detection_idx: vision_range_assignments[i]) { if(merged_object.label == range_in_cv.objects[range_detection_idx].label) { used_range_detections[range_detection_idx] = true; merged_object = MergeObjects(merged_object, range_in_cv.objects[range_detection_idx]); } } if(!vision_range_assignments[i].empty()) { CalculateObjectFeatures(merged_object, true); fused_objects.objects.push_back(merged_object); } }*/ //add objects outside image for(size_t i=0; i < range_out_cv.objects.size(); i++) { fused_objects.objects.push_back(range_out_cv.objects[i]); } return fused_objects; } void RosRangeVisionFusionApp::SyncedDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections, const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections) { autoware_msgs::DetectedObjectArray fusion_objects; jsk_recognition_msgs::BoundingBoxArray fused_boxes; visualization_msgs::MarkerArray fused_objects_labels; if (nullptr == in_vision_detections || nullptr == in_range_detections) { ROS_INFO("[%s] Empty Detections, check that vision and range detectors are running and publishing.", __APP_NAME__); if (empty_frames_ > 5) { publisher_fused_objects_.publish(fusion_objects); publisher_fused_boxes_.publish(fused_boxes); publisher_fused_text_.publish(fused_objects_labels); empty_frames_++; } return; } if (!camera_lidar_tf_ok_) { camera_lidar_tf_ = FindTransform(image_frame_id_, in_range_detections->header.frame_id); } if( !camera_lidar_tf_ok_ || !camera_info_ok_) { ROS_INFO("[%s] Missing Camera-LiDAR TF or CameraInfo", __APP_NAME__); return; } fusion_objects = FuseRangeVisionDetections(in_vision_detections, in_range_detections); fused_boxes = ObjectsToBoxes(fusion_objects); fused_objects_labels = ObjectsToMarkers(fusion_objects); publisher_fused_objects_.publish(fusion_objects); publisher_fused_boxes_.publish(fused_boxes); publisher_fused_text_.publish(fused_objects_labels); empty_frames_ = 0; vision_detections_ = nullptr; range_detections_ = nullptr; } visualization_msgs::MarkerArray RosRangeVisionFusionApp::ObjectsToMarkers(const autoware_msgs::DetectedObjectArray &in_objects) { visualization_msgs::MarkerArray final_markers; for(const autoware_msgs::DetectedObject& object : in_objects.objects) { if (object.label != "unknown") { visualization_msgs::Marker marker; marker.header = in_objects.header; marker.ns = "range_vision_fusion"; marker.id = object.id; marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING; marker.scale.z = 1.0; marker.text = object.label; marker.pose.position = object.pose.position; marker.pose.position.z += 1.5; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; marker.color.a = 1.0; marker.scale.x = 1.5; marker.scale.y = 1.5; marker.scale.z = 1.5; marker.lifetime = ros::Duration(0.1); final_markers.markers.push_back(marker); } } return final_markers; } jsk_recognition_msgs::BoundingBoxArray RosRangeVisionFusionApp::ObjectsToBoxes(const autoware_msgs::DetectedObjectArray &in_objects) { jsk_recognition_msgs::BoundingBoxArray final_boxes; final_boxes.header = in_objects.header; for(const autoware_msgs::DetectedObject& object : in_objects.objects) { jsk_recognition_msgs::BoundingBox box; box.header = in_objects.header; box.label = object.id; box.dimensions = object.dimensions; box.pose = object.pose; box.value = object.score; final_boxes.boxes.push_back(box); } return final_boxes; } void RosRangeVisionFusionApp::VisionDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections) { if (!processing_ && !in_vision_detections->objects.empty()) { processing_ = true; vision_detections_ = in_vision_detections; SyncedDetectionsCallback(in_vision_detections, range_detections_); processing_ = false; } } void RosRangeVisionFusionApp::RangeDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections) { if (!processing_ && !in_range_detections->objects.empty()) { processing_ = true; range_detections_ = in_range_detections; SyncedDetectionsCallback(vision_detections_, in_range_detections); processing_ = false; } } void RosRangeVisionFusionApp::ImageCallback(const sensor_msgs::Image::ConstPtr &in_image_msg) { if(!camera_info_ok_) return; cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(in_image_msg, "bgr8"); cv::Mat in_image = cv_image->image; cv::Mat undistorted_image; cv::undistort(in_image, image_, camera_instrinsics_, distortion_coefficients_); }; void RosRangeVisionFusionApp::IntrinsicsCallback(const sensor_msgs::CameraInfo &in_message) { image_size_.height = in_message.height; image_size_.width = in_message.width; camera_instrinsics_ = cv::Mat(3, 3, CV_64F); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { camera_instrinsics_.at<double>(row, col) = in_message.K[row * 3 + col]; } } distortion_coefficients_ = cv::Mat(1, 5, CV_64F); for (int col = 0; col < 5; col++) { distortion_coefficients_.at<double>(col) = in_message.D[col]; } fx_ = static_cast<float>(in_message.P[0]); fy_ = static_cast<float>(in_message.P[5]); cx_ = static_cast<float>(in_message.P[2]); cy_ = static_cast<float>(in_message.P[6]); intrinsics_subscriber_.shutdown(); camera_info_ok_ = true; image_frame_id_ = in_message.header.frame_id; ROS_INFO("[%s] CameraIntrinsics obtained.", __APP_NAME__); } tf::StampedTransform RosRangeVisionFusionApp::FindTransform(const std::string &in_target_frame, const std::string &in_source_frame) { tf::StampedTransform transform; ROS_INFO("%s - > %s", in_source_frame.c_str(), in_target_frame.c_str()); camera_lidar_tf_ok_ = false; try { transform_listener_->lookupTransform(in_target_frame, in_source_frame, ros::Time(0), transform); camera_lidar_tf_ok_ = true; ROS_INFO("[%s] Camera-Lidar TF obtained", __APP_NAME__); } catch (tf::TransformException &ex) { ROS_ERROR("[%s] %s", __APP_NAME__, ex.what()); } return transform; } void RosRangeVisionFusionApp::InitializeRosIo(ros::NodeHandle &in_private_handle) { //get params std::string camera_info_src, detected_objects_vision; std::string detected_objects_range, fused_topic_str = "/detection/combined_objects", fused_boxes_str = "/detection/combined_objects_boxes"; std::string fused_text_str = "detection/combined_objects_labels"; std::string name_space_str = ros::this_node::getNamespace(); bool sync_topics = false; ROS_INFO("[%s] This node requires: Registered TF(Lidar-Camera), CameraInfo, Vision and Range Detections being published.", __APP_NAME__); in_private_handle.param<std::string>("detected_objects_range", detected_objects_range, "/detection/lidar_objects"); ROS_INFO("[%s] detected_objects_range: %s", __APP_NAME__, detected_objects_range.c_str()); in_private_handle.param<std::string>("detected_objects_vision", detected_objects_vision, "/detection/vision_objects"); ROS_INFO("[%s] detected_objects_vision: %s", __APP_NAME__, detected_objects_vision.c_str()); in_private_handle.param<std::string>("camera_info_src", camera_info_src, "/camera_info"); ROS_INFO("[%s] camera_info_src: %s", __APP_NAME__, camera_info_src.c_str()); in_private_handle.param<double>("overlap_threshold", overlap_threshold_, 0.5); ROS_INFO("[%s] overlap_threshold: %f", __APP_NAME__, overlap_threshold_); in_private_handle.param<bool>("sync_topics", sync_topics, false); ROS_INFO("[%s] sync_topics: %d", __APP_NAME__, sync_topics); if (name_space_str != "/") { if (name_space_str.substr(0, 2) == "//") { name_space_str.erase(name_space_str.begin()); } camera_info_src = name_space_str + camera_info_src; } //generate subscribers and sychronizers ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, camera_info_src.c_str()); intrinsics_subscriber_ = in_private_handle.subscribe(camera_info_src, 1, &RosRangeVisionFusionApp::IntrinsicsCallback, this); /*image_subscriber_ = in_private_handle.subscribe("/image_raw", 1, &RosRangeVisionFusionApp::ImageCallback, this);*/ ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, detected_objects_vision.c_str()); ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, detected_objects_range.c_str()); if (!sync_topics) { detections_range_subscriber_ = in_private_handle.subscribe(detected_objects_vision, 1, &RosRangeVisionFusionApp::VisionDetectionsCallback, this); detections_vision_subscriber_ = in_private_handle.subscribe(detected_objects_range, 1, &RosRangeVisionFusionApp::RangeDetectionsCallback, this); } else { vision_filter_subscriber_ = new message_filters::Subscriber<autoware_msgs::DetectedObjectArray>(node_handle_, detected_objects_vision, 1); range_filter_subscriber_ = new message_filters::Subscriber<autoware_msgs::DetectedObjectArray>(node_handle_, detected_objects_range, 1); detections_synchronizer_ = new message_filters::Synchronizer<SyncPolicyT>(SyncPolicyT(10), *vision_filter_subscriber_, *range_filter_subscriber_); detections_synchronizer_->registerCallback(boost::bind(&RosRangeVisionFusionApp::SyncedDetectionsCallback, this, _1, _2)); } publisher_fused_objects_ = node_handle_.advertise<autoware_msgs::DetectedObjectArray>(fused_topic_str, 1); publisher_fused_boxes_ = node_handle_.advertise<jsk_recognition_msgs::BoundingBoxArray>(fused_boxes_str, 1); publisher_fused_text_ = node_handle_.advertise<visualization_msgs::MarkerArray>(fused_text_str, 1); ROS_INFO("[%s] Publishing fused objects in %s", __APP_NAME__, fused_topic_str.c_str()); ROS_INFO("[%s] Publishing fused boxes in %s", __APP_NAME__, fused_boxes_str.c_str()); } void RosRangeVisionFusionApp::Run() { ros::NodeHandle private_node_handle("~"); tf::TransformListener transform_listener; transform_listener_ = &transform_listener; InitializeRosIo(private_node_handle); ROS_INFO("[%s] Ready. Waiting for data...", __APP_NAME__); ros::spin(); ROS_INFO("[%s] END", __APP_NAME__); } RosRangeVisionFusionApp::RosRangeVisionFusionApp() { camera_lidar_tf_ok_ = false; camera_info_ok_ = false; processing_ = false; image_frame_id_ = ""; overlap_threshold_ = 0.5; empty_frames_ = 0; }
38.536443
143
0.657475
AftermathK
580d96d471ae4f1ab07ee84077f1b55c10933cd2
1,979
cpp
C++
source/opt/feature_manager.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
source/opt/feature_manager.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
source/opt/feature_manager.cpp
iburinoc/SPIRV-Tools
48326d443e434f55eb50a7cfc9acdc968daad5e3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2017 Google 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 "feature_manager.h" #include <queue> #include <stack> #include "enum_string_mapping.h" namespace spvtools { namespace opt { void FeatureManager::Analyze(opt::Module* module) { AddExtensions(module); AddCapabilities(module); AddExtInstImportIds(module); } void FeatureManager::AddExtensions(opt::Module* module) { for (auto ext : module->extensions()) { const std::string name = reinterpret_cast<const char*>(ext.GetInOperand(0u).words.data()); Extension extension; if (GetExtensionFromString(name.c_str(), &extension)) { extensions_.Add(extension); } } } void FeatureManager::AddCapability(SpvCapability cap) { if (capabilities_.Contains(cap)) return; capabilities_.Add(cap); spv_operand_desc desc = {}; if (SPV_SUCCESS == grammar_.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc)) { CapabilitySet(desc->numCapabilities, desc->capabilities) .ForEach([this](SpvCapability c) { AddCapability(c); }); } } void FeatureManager::AddCapabilities(opt::Module* module) { for (opt::Instruction& inst : module->capabilities()) { AddCapability(static_cast<SpvCapability>(inst.GetSingleWordInOperand(0))); } } void FeatureManager::AddExtInstImportIds(opt::Module* module) { extinst_importid_GLSLstd450_ = module->GetExtInstImportId("GLSL.std.450"); } } // namespace opt } // namespace spvtools
29.984848
78
0.72663
iburinoc
580e5521d0785f546d139ffb54c95b1adb627e16
8,138
cc
C++
src/resolver/assignment_validation_test.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
src/resolver/assignment_validation_test.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
src/resolver/assignment_validation_test.cc
haocxy/mirror-googlesource-dawn-tint
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The Tint Authors. // // 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 "src/resolver/resolver.h" #include "gmock/gmock.h" #include "src/ast/struct_block_decoration.h" #include "src/resolver/resolver_test_helper.h" #include "src/sem/storage_texture_type.h" namespace tint { namespace resolver { namespace { using ResolverAssignmentValidationTest = ResolverTest; TEST_F(ResolverAssignmentValidationTest, ReadOnlyBuffer) { // [[block]] struct S { m : i32 }; // [[group(0), binding(0)]] // var<storage,read> a : S; auto* s = Structure("S", {Member("m", ty.i32())}, {create<ast::StructBlockDecoration>()}); Global(Source{{12, 34}}, "a", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::DecorationList{ create<ast::BindingDecoration>(0), create<ast::GroupDecoration>(0), }); WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("a", "m"), 1)); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "56:78 error: cannot store into a read-only type 'ref<storage, " "i32, read>'"); } TEST_F(ResolverAssignmentValidationTest, AssignIncompatibleTypes) { // { // var a : i32 = 2; // a = 2.3; // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); auto* assign = Assign(Source{{12, 34}}, "a", 2.3f); WrapInFunction(var, assign); ASSERT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypesInBlockStatement_Pass) { // { // var a : i32 = 2; // a = 2 // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); WrapInFunction(var, Assign("a", 2)); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignIncompatibleTypesInBlockStatement_Fail) { // { // var a : i32 = 2; // a = 2.3; // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2.3f)); ASSERT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignIncompatibleTypesInNestedBlockStatement_Fail) { // { // { // var a : i32 = 2; // a = 2.3; // } // } auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); auto* inner_block = Block(Decl(var), Assign(Source{{12, 34}}, "a", 2.3f)); auto* outer_block = Block(inner_block); WrapInFunction(outer_block); ASSERT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignToScalar_Fail) { // var my_var : i32 = 2; // 1 = my_var; auto* var = Var("my_var", ty.i32(), ast::StorageClass::kNone, Expr(2)); WrapInFunction(var, Assign(Expr(Source{{12, 34}}, 1), "my_var")); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign to value of type 'i32'"); } TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypes_Pass) { // var a : i32 = 2; // a = 2 auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypesThroughAlias_Pass) { // alias myint = i32; // var a : myint = 2; // a = 2 auto* myint = Alias("myint", ty.i32()); auto* var = Var("a", ty.Of(myint), ast::StorageClass::kNone, Expr(2)); WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypesInferRHSLoad_Pass) { // var a : i32 = 2; // var b : i32 = 3; // a = b; auto* var_a = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2)); auto* var_b = Var("b", ty.i32(), ast::StorageClass::kNone, Expr(3)); WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, "a", "b")); EXPECT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignThroughPointer_Pass) { // var a : i32; // let b : ptr<function,i32> = &a; // *b = 2; const auto func = ast::StorageClass::kFunction; auto* var_a = Var("a", ty.i32(), func, Expr(2)); auto* var_b = Const("b", ty.pointer<int>(func), AddressOf(Expr("a"))); WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, Deref("b"), 2)); EXPECT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverAssignmentValidationTest, AssignToConstant_Fail) { // { // let a : i32 = 2; // a = 2 // } auto* var = Const("a", ty.i32(), Expr(2)); WrapInFunction(var, Assign(Expr(Source{{12, 34}}, "a"), 2)); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign to const\nnote: 'a' is declared here:"); } TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_Handle) { // var a : texture_storage_1d<rgba8unorm, read>; // var b : texture_storage_1d<rgba8unorm, read>; // a = b; auto make_type = [&] { return ty.storage_texture(ast::TextureDimension::k1d, ast::ImageFormat::kRgba8Unorm, ast::Access::kRead); }; Global("a", make_type(), ast::StorageClass::kNone, ast::DecorationList{ create<ast::BindingDecoration>(0), create<ast::GroupDecoration>(0), }); Global("b", make_type(), ast::StorageClass::kNone, ast::DecorationList{ create<ast::BindingDecoration>(1), create<ast::GroupDecoration>(0), }); WrapInFunction(Assign(Source{{56, 78}}, "a", "b")); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "56:78 error: storage type of assignment must be constructible"); } TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_Atomic) { // [[block]] struct S { a : atomic<i32>; }; // [[group(0), binding(0)]] var<storage, read_write> v : S; // v.a = v.a; auto* s = Structure("S", {Member("a", ty.atomic(ty.i32()))}, {create<ast::StructBlockDecoration>()}); Global(Source{{12, 34}}, "v", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kReadWrite, ast::DecorationList{ create<ast::BindingDecoration>(0), create<ast::GroupDecoration>(0), }); WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("v", "a"), MemberAccessor("v", "a"))); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "56:78 error: storage type of assignment must be constructible"); } TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_RuntimeArray) { // [[block]] struct S { a : array<f32>; }; // [[group(0), binding(0)]] var<storage, read_write> v : S; // v.a = v.a; auto* s = Structure("S", {Member("a", ty.array(ty.f32()))}, {create<ast::StructBlockDecoration>()}); Global(Source{{12, 34}}, "v", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kReadWrite, ast::DecorationList{ create<ast::BindingDecoration>(0), create<ast::GroupDecoration>(0), }); WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("v", "a"), MemberAccessor("v", "a"))); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "56:78 error: storage type of assignment must be constructible"); } } // namespace } // namespace resolver } // namespace tint
31.789063
80
0.613664
haocxy
580f60d9c3c1917c611b3c85574dd8ded30a22fe
957
cpp
C++
LeetCode/RemoveLinkedListElements.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
LeetCode/RemoveLinkedListElements.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
LeetCode/RemoveLinkedListElements.cpp
SelvorWhim/competitive
b9daaf21920d6f7669dc0c525e903949f4e33b62
[ "Unlicense" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* it = head; ListNode* newHead = NULL; ListNode* lastValid = NULL; while (it != NULL) { if (it->val != val) { if (newHead == NULL) { newHead = it; } if (lastValid == NULL) { lastValid = it; } else { lastValid = lastValid->next; } } else if (it->val == val && lastValid != NULL) { lastValid->next = it->next; } // if (it->val == val && lastValid == NULL), the node is effectively skipped in the new list it = it->next; } return newHead; } };
28.147059
106
0.440961
SelvorWhim
5810aa11c2c678e2dba12e500ef70300a1a9781d
5,699
cpp
C++
tests/sshmanager_clitest.cpp
lilithean/XtalOpt
9ebc125e6014b27e72a04fb62c8820c7b9670c61
[ "BSD-3-Clause" ]
23
2017-09-01T04:35:02.000Z
2022-01-16T13:51:17.000Z
tests/sshmanager_clitest.cpp
lilithean/XtalOpt
9ebc125e6014b27e72a04fb62c8820c7b9670c61
[ "BSD-3-Clause" ]
20
2017-08-29T15:29:46.000Z
2022-01-20T09:10:59.000Z
tests/sshmanager_clitest.cpp
lilithean/XtalOpt
9ebc125e6014b27e72a04fb62c8820c7b9670c61
[ "BSD-3-Clause" ]
21
2017-06-15T03:11:34.000Z
2022-02-28T05:20:44.000Z
/********************************************************************** SSHManager - SSHManagerTest class provides unit testing for the SSHManager class Copyright (C) 2010-2011 David C. Lonie This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ #include <globalsearch/sshmanager_cli.h> #include <QString> #include <QTemporaryFile> #include <QtTest> #define NUM_CONN 5 using namespace GlobalSearch; class SSHManagerCLITest : public QObject { Q_OBJECT private: SSHManagerCLI* manager; // Create a local directory structure: // [tmp path]/sshtesttmp/ // testfile1 // newdir/ // testfile2 QStringList m_dirLayout; QDir m_localTempDir; QString m_remoteDir; QString m_localNewDir; QString m_testfile1Contents; QString m_testfile2Contents; private slots: /** * Called before the first test function is executed. */ void initTestCase(); /** * Called after the last test function is executed. */ void cleanupTestCase(); /** * Called before each test function is executed. */ void init(); /** * Called after every test function. */ void cleanup(); // Tests void lockAllAndExecute(); void copyThreads(); }; void SSHManagerCLITest::initTestCase() { // Create a local directory structure: // [tmp path]/sshtesttmp/ // testfile1 // newdir/ // testfile2 m_remoteDir = ".sshtmpdir"; m_dirLayout << m_remoteDir + "/testfile1" << m_remoteDir + "/newdir/" << m_remoteDir + "/newdir/testfile2"; m_localTempDir.mkpath(QDir::tempPath() + "/sshtesttmp"); m_localTempDir.mkpath(QDir::tempPath() + "/sshtesttmp/newdir"); m_localTempDir.setPath(QDir::tempPath() + "/sshtesttmp"); m_localNewDir = m_localTempDir.path() + ".new"; // Each testfile is ~1MB QString buffer(104857, '0'); QFile testfile1(m_localTempDir.path() + "/testfile1"); testfile1.open(QIODevice::WriteOnly); QTextStream teststream1(&testfile1); m_testfile1Contents = "This is the first file's contents.\n" + buffer; teststream1 << m_testfile1Contents; testfile1.close(); QFile testfile2(m_localTempDir.path() + "/newdir/testfile2"); testfile2.open(QIODevice::WriteOnly); QTextStream teststream2(&testfile2); m_testfile2Contents = "and these are the second's.\n" + buffer; teststream2 << m_testfile2Contents; testfile2.close(); // Open ssh connection manager = new SSHManagerCLI(); try { // Ensure that the following points to a real server, acct, and pw // combo. Do not commit any changes here! (considering using // /etc/hosts to map "testserver" to a real server with a // chroot-jailed acct/pw = "test") manager->makeConnections("testserver", "test", "test", 22); } catch (SSHConnection::SSHConnectionException) { QFAIL("Cannot connect to ssh server. Make sure that the connection opened " "in initTestCase() points to a valid account on a real host before " "debugging this failure."); } } void SSHManagerCLITest::cleanupTestCase() { QFile::remove(m_localTempDir.path() + "/testfile1"); QFile::remove(m_localTempDir.path() + "/newdir/testfile2"); m_localTempDir.rmdir(m_localTempDir.path() + "/newdir"); m_localTempDir.rmdir(m_localTempDir.path()); QFile::remove(m_localNewDir + "/testfile1"); QFile::remove(m_localNewDir + "/newdir/testfile2"); m_localTempDir.rmdir(m_localNewDir + "/newdir"); m_localTempDir.rmdir(m_localNewDir); if (manager) delete manager; manager = 0; } void SSHManagerCLITest::init() { } void SSHManagerCLITest::cleanup() { } void SSHManagerCLITest::lockAllAndExecute() { QList<SSHConnection*> list; for (int i = 0; i < NUM_CONN; i++) { list.append(manager->getFreeConnection()); } QString command = "expr 2 + 4"; QString stdout_str, stderr_str; SSHConnection* conn; int ec; for (int i = 0; i < NUM_CONN; i++) { conn = list.at(i); QVERIFY(conn->execute(command, stdout_str, stderr_str, ec)); QCOMPARE(ec, 0); QCOMPARE(stdout_str, QString("6\n")); QVERIFY(stderr_str.isEmpty()); } for (int i = 0; i < NUM_CONN; i++) { manager->unlockConnection(list.at(i)); } } class CopyThread : public QThread { public: CopyThread(SSHManager* m, const QString& f, const QString& t) : QThread(0), manager(m), from(f), to(t) { } void run() { SSHConnection* conn = manager->getFreeConnection(); conn->copyDirectoryToServer(from, to); conn->removeRemoteDirectory(to); manager->unlockConnection(conn); } private: SSHManager* manager; QString from, to; }; void SSHManagerCLITest::copyThreads() { QList<CopyThread*> list; for (int i = 0; i < NUM_CONN * 20; ++i) { CopyThread* ct = new CopyThread(manager, m_localTempDir.path(), m_remoteDir + QString::number(i + 1)); list.append(ct); } QBENCHMARK { for (int i = 0; i < list.size(); ++i) { list.at(i)->start(); } for (int i = 0; i < list.size(); ++i) { list.at(i)->wait(); qDebug() << "Thread " << i + 1 << " of " << list.size() << " finished."; } } } QTEST_MAIN(SSHManagerCLITest) #include "sshmanager_clitest.moc"
26.882075
79
0.640814
lilithean
5812d55e1d9e9bdc8296acf6f0576ecef0cc8bcc
379
cpp
C++
src/geometry/segment.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
src/geometry/segment.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
1
2019-08-24T17:31:50.000Z
2019-08-24T17:31:50.000Z
src/geometry/segment.cpp
teyrana/quadtree
4172ad2f2e36414caebf80013a3d32e6df200945
[ "MIT" ]
null
null
null
// The MIT License // (c) 2019 Daniel Williams #include <cmath> #include "geometry/point.hpp" #include "geometry/segment.hpp" using terrain::geometry::Point; using terrain::geometry::Segment; Segment::Segment() {} Segment::Segment(const Point& _start, const Point& _end): start(_start), end(_end) {} void Segment::clear(){ this->start.clear(); this->end.clear(); }
16.478261
57
0.691293
teyrana
5812ea4aec3da9e3cc16952c7e4ca4c632a044d7
19,054
cpp
C++
test/auto/ListModel/ListModelTest.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
8
2019-12-11T08:52:37.000Z
2021-08-04T03:42:55.000Z
test/auto/ListModel/ListModelTest.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
null
null
null
test/auto/ListModel/ListModelTest.cpp
ericzh86/ModelsModule
e1f263420e5e54ac280d1c61485ccb6a0a625129
[ "MIT" ]
1
2020-04-16T07:07:50.000Z
2020-04-16T07:07:50.000Z
#include "ListModelTest.h" #include <QtCore> #include <QtTest> #include "QCxxListModel.h" #include "ListModelTester.h" // Macros #define InitModel() \ QCxxListModel<QObject *> model; \ model.setCountEnabled(true); \ auto tester = new ListModelTester(&model) #define VerifyCountSignal(value) QVERIFY(tester->count() == value) #define VerifyChangedSize(value) QVERIFY(tester->changedSize() == value) #define VerifyRowsChanged(i, from, to) QVERIFY(tester->isChanged(i, from, to)) ListModelTest::ListModelTest() { for (int i = 0; i < 100; ++i) { objects.append(new QObject(this)); } } void ListModelTest::appendListCase() { InitModel(); QObjectList list1 { objects[0], objects[1] }; QObjectList list2 { objects[2], objects[3] }; model.append(list1); VerifyCountSignal(1); model.append(list2); VerifyCountSignal(2); QVERIFY(model.count() == 4); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.value(3) == objects[3]); } void ListModelTest::prependCase() { InitModel(); model.prepend(objects[0]); VerifyCountSignal(1); model.prepend(objects[1]); VerifyCountSignal(2); model.prepend(objects[2]); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[2]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[0]); } void ListModelTest::appendCase() { InitModel(); model.append(objects[0]); VerifyCountSignal(1); model.append(objects[1]); VerifyCountSignal(2); model.append(objects[2]); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); } void ListModelTest::push_frontCase() { InitModel(); model.push_front(objects[0]); VerifyCountSignal(1); model.push_front(objects[1]); VerifyCountSignal(2); model.push_front(objects[2]); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[2]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[0]); } void ListModelTest::push_backCase() { InitModel(); model.push_back(objects[0]); VerifyCountSignal(1); model.push_back(objects[1]); VerifyCountSignal(2); model.push_back(objects[2]); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); } void ListModelTest::replaceCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.replace(0, objects[3]); VerifyCountSignal(0); QVERIFY(model.value(0) == objects[3]); model.replace(1, objects[4]); VerifyCountSignal(0); QVERIFY(model.value(1) == objects[4]); model.replace(2, objects[5]); VerifyCountSignal(0); QVERIFY(model.value(2) == objects[5]); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[3]); QVERIFY(model.value(1) == objects[4]); QVERIFY(model.value(2) == objects[5]); } void ListModelTest::insertCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.insert(0, objects[3]); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[3]); model.insert(2, objects[4]); VerifyCountSignal(2); QVERIFY(model.value(2) == objects[4]); model.insert(4, objects[5]); VerifyCountSignal(3); QVERIFY(model.value(4) == objects[5]); QVERIFY(model.count() == 6); QVERIFY(model.value(0) == objects[3]); QVERIFY(model.value(1) == objects[0]); QVERIFY(model.value(2) == objects[4]); QVERIFY(model.value(3) == objects[1]); QVERIFY(model.value(4) == objects[5]); QVERIFY(model.value(5) == objects[2]); } void ListModelTest::removeOneCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); model.append(objects[i]); } tester->resetCount(); model.removeOne(objects[0]); VerifyCountSignal(1); model.removeOne(objects[2]); VerifyCountSignal(2); model.removeOne(objects[4]); VerifyCountSignal(3); QVERIFY(model.count() == 9); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[1]); QVERIFY(model.value(3) == objects[2]); QVERIFY(model.value(4) == objects[3]); QVERIFY(model.value(5) == objects[3]); QVERIFY(model.value(6) == objects[4]); QVERIFY(model.value(7) == objects[5]); QVERIFY(model.value(8) == objects[5]); } void ListModelTest::removeAllCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); } for (int i = 0; i < 6; ++i) { model.append(objects[i]); model.append(objects[i]); } for (int i = 0; i < 6; ++i) { model.append(objects[i]); model.append(objects[i]); model.append(objects[i]); } tester->resetCount(); model.removeAll(objects[0]); VerifyCountSignal(1); model.removeAll(objects[2]); VerifyCountSignal(2); model.removeAll(objects[4]); VerifyCountSignal(3); QVERIFY(model.count() == 18); QVERIFY(model.value( 0) == objects[1]); QVERIFY(model.value( 1) == objects[3]); QVERIFY(model.value( 2) == objects[5]); QVERIFY(model.value( 3) == objects[1]); QVERIFY(model.value( 4) == objects[1]); QVERIFY(model.value( 5) == objects[3]); QVERIFY(model.value( 6) == objects[3]); QVERIFY(model.value( 7) == objects[5]); QVERIFY(model.value( 8) == objects[5]); QVERIFY(model.value( 9) == objects[1]); QVERIFY(model.value(10) == objects[1]); QVERIFY(model.value(11) == objects[1]); QVERIFY(model.value(12) == objects[3]); QVERIFY(model.value(13) == objects[3]); QVERIFY(model.value(14) == objects[3]); QVERIFY(model.value(15) == objects[5]); QVERIFY(model.value(16) == objects[5]); QVERIFY(model.value(17) == objects[5]); } void ListModelTest::pop_frontCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.pop_front(); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[2]); model.pop_front(); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[2]); model.pop_front(); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::pop_backCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.pop_back(); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); model.pop_back(); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); model.pop_back(); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::removeAtCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); model.removeAt(0); VerifyCountSignal(1); model.removeAt(1); VerifyCountSignal(2); model.removeAt(2); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[3]); QVERIFY(model.value(2) == objects[5]); } void ListModelTest::removeFirstCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.removeFirst(); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[2]); model.removeFirst(); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[2]); model.removeFirst(); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::removeLastCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); model.removeLast(); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); model.removeLast(); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); model.removeLast(); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::takeAtCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); QVERIFY(model.takeAt(0) == objects[0]); VerifyCountSignal(1); QVERIFY(model.takeAt(1) == objects[2]); VerifyCountSignal(2); QVERIFY(model.takeAt(2) == objects[4]); VerifyCountSignal(3); QVERIFY(model.count() == 3); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[3]); QVERIFY(model.value(2) == objects[5]); } void ListModelTest::takeFirstCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); QVERIFY(model.takeFirst() == objects[0]); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[2]); QVERIFY(model.takeFirst() == objects[1]); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[2]); QVERIFY(model.takeFirst() == objects[2]); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::takeLastCase() { InitModel(); for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); QVERIFY(model.takeLast() == objects[2]); VerifyCountSignal(1); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.takeLast() == objects[1]); VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.takeLast() == objects[0]); VerifyCountSignal(3); QVERIFY(model.count() == 0); } void ListModelTest::swapCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); model.swap(0, 1); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[0]); model.swap(1, 2); QVERIFY(model.value(1) == objects[2]); QVERIFY(model.value(2) == objects[0]); model.swap(4, 5); QVERIFY(model.value(4) == objects[5]); QVERIFY(model.value(5) == objects[4]); VerifyCountSignal(0); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[2]); QVERIFY(model.value(2) == objects[0]); QVERIFY(model.value(3) == objects[3]); QVERIFY(model.value(4) == objects[5]); QVERIFY(model.value(5) == objects[4]); QVERIFY(model.count() == 6); } void ListModelTest::swapListCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); model.swap(list); VerifyCountSignal(1); QVERIFY(list.value(0) == objects[0]); QVERIFY(list.value(1) == objects[1]); QVERIFY(list.value(2) == objects[2]); QVERIFY(list.value(3) == objects[3]); QVERIFY(list.value(4) == objects[4]); QVERIFY(list.value(5) == objects[5]); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.count() == 3); } void ListModelTest::moveCase() { InitModel(); for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); model.move(0, 1); QVERIFY(model.value(0) == objects[1]); QVERIFY(model.value(1) == objects[0]); model.move(1, 2); QVERIFY(model.value(1) == objects[2]); QVERIFY(model.value(2) == objects[0]); model.move(4, 5); QVERIFY(model.value(4) == objects[5]); QVERIFY(model.value(5) == objects[4]); model.move(5, 4); QVERIFY(model.value(4) == objects[4]); QVERIFY(model.value(5) == objects[5]); model.move(2, 1); QVERIFY(model.value(1) == objects[0]); QVERIFY(model.value(2) == objects[2]); model.move(1, 0); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); VerifyCountSignal(0); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.value(3) == objects[3]); QVERIFY(model.value(4) == objects[4]); QVERIFY(model.value(5) == objects[5]); QVERIFY(model.count() == 6); } void ListModelTest::clearCase() { InitModel(); int destroies = 0; for (int i = 0; i < 6; ++i) { model.append(objects[i]); connect(objects[i], &QObject::destroyed, this, [&] { ++destroies; }); } tester->resetCount(); model.clear(); VerifyCountSignal(1); QTRY_COMPARE(destroies, 0); QVERIFY(model.count() == 0); } void ListModelTest::deleteAllCase() { InitModel(); int destroies = 0; for (int i = 0; i < 6; ++i) { QObject *o = new QObject(this); model.append(o); connect(o, &QObject::destroyed, this, [&] { ++destroies; }); } tester->resetCount(); model.deleteAll(); VerifyCountSignal(1); QTRY_COMPARE(destroies, 6); QVERIFY(model.count() == 0); } void ListModelTest::operatorAssignmentCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; for (int i = 0; i < 6; ++i) { model.append(objects[i]); } tester->resetCount(); model = list; VerifyCountSignal(1); QVERIFY(list.value(0) == objects[0]); QVERIFY(list.value(1) == objects[1]); QVERIFY(list.value(2) == objects[2]); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.count() == 3); } void ListModelTest::operatorAdditionCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); list = model + list; VerifyCountSignal(0); QVERIFY(list.value(0) == objects[0]); QVERIFY(list.value(1) == objects[1]); QVERIFY(list.value(2) == objects[2]); QVERIFY(list.value(3) == objects[0]); QVERIFY(list.value(4) == objects[1]); QVERIFY(list.value(5) == objects[2]); QVERIFY(list.count() == 6); } void ListModelTest::operatorEqualToCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); QVERIFY(model == list); VerifyCountSignal(0); } void ListModelTest::operatorNotEqualCase() { InitModel(); QObjectList list { objects[1], objects[1], objects[2] }; for (int i = 0; i < 3; ++i) { model.append(objects[i]); } tester->resetCount(); QVERIFY(model != list); VerifyCountSignal(0); } void ListModelTest::operatorAdditionAssignmentListCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; model += list; VerifyCountSignal(1); model += list; VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.value(3) == objects[0]); QVERIFY(model.value(4) == objects[1]); QVERIFY(model.value(5) == objects[2]); QVERIFY(model.count() == 6); } void ListModelTest::operatorLeftShiftListCase() { InitModel(); QObjectList list { objects[0], objects[1], objects[2] }; model << list; VerifyCountSignal(1); model << list; VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.value(3) == objects[0]); QVERIFY(model.value(4) == objects[1]); QVERIFY(model.value(5) == objects[2]); QVERIFY(model.count() == 6); } void ListModelTest::operatorAdditionAssignmentCase() { InitModel(); model += objects[0]; VerifyCountSignal(1); model += objects[1]; VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.count() == 2); } void ListModelTest::operatorLeftShiftCase() { InitModel(); model << objects[0]; VerifyCountSignal(1); model << objects[1]; VerifyCountSignal(2); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.count() == 2); } void ListModelTest::modelMethodsCase() { InitModel(); Q_UNUSED(tester); QObject *o = (QObject *)1; for (int i = 0; i < 3; ++i) { model.append(objects[i]); } model.append(nullptr); model.append(o); QModelIndex index0 = model.index(0, 0); QModelIndex index1 = model.index(1, 0); QModelIndex index2 = model.index(2, 0); QModelIndex index3 = model.index(3, 0); QModelIndex index4 = model.index(4, 0); QModelIndex index5 = model.index(5, 0); QVERIFY(index0.row() == 0); QVERIFY(index1.row() == 1); QVERIFY(index2.row() == 2); QVERIFY(index3.row() == 3); QVERIFY(index4.row() == 4); QVERIFY(index5.row() ==-1); QVERIFY(index0.column() == 0); QVERIFY(index1.column() == 0); QVERIFY(index2.column() == 0); QVERIFY(index3.column() == 0); QVERIFY(index4.column() == 0); QVERIFY(index5.column() ==-1); QVERIFY(model.value(index0) == objects[0]); QVERIFY(model.value(index1) == objects[1]); QVERIFY(model.value(index2) == objects[2]); QVERIFY(model.value(index3) == nullptr); QVERIFY(model.value(index4) == o); QVERIFY(model.value(index5) == nullptr); QVERIFY(model.value(index0, nullptr) == objects[0]); QVERIFY(model.value(index1, nullptr) == objects[1]); QVERIFY(model.value(index2, nullptr) == objects[2]); QVERIFY(model.value(index3, nullptr) == nullptr); QVERIFY(model.value(index4, nullptr) == o); QVERIFY(model.value(index5, nullptr) == nullptr); QVERIFY(model.value(0) == objects[0]); QVERIFY(model.value(1) == objects[1]); QVERIFY(model.value(2) == objects[2]); QVERIFY(model.value(3) == nullptr); QVERIFY(model.value(4) == o); QVERIFY(model.value(5) == nullptr); QVERIFY(model.value(0, nullptr) == objects[0]); QVERIFY(model.value(1, nullptr) == objects[1]); QVERIFY(model.value(2, nullptr) == objects[2]); QVERIFY(model.value(3, nullptr) == nullptr); QVERIFY(model.value(4, nullptr) == o); QVERIFY(model.value(5, nullptr) == nullptr); } QTEST_APPLESS_MAIN(ListModelTest)
24.118987
78
0.599139
ericzh86
58144a8de60ff911068cf63bc3e79d31ea11f2a9
1,909
cpp
C++
Sources/AGEngine/Graphic/GraphicElementManager.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Graphic/GraphicElementManager.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Graphic/GraphicElementManager.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#include "GraphicElementManager.hpp" #include "BFC/BFCCullableHandle.hpp" #include "BFC/BFCBlockManagerFactory.hpp" #include "Graphic/DRBMeshData.hpp" #include "AssetManagement/Instance/MeshInstance.hh" #include "AssetManagement/Instance/MaterialInstance.hh" #include "Utils/Profiler.hpp" namespace AGE { GraphicElementManager::GraphicElementManager(BFCBlockManagerFactory *factory) : _bfcBlockManager(factory) { AGE_ASSERT(factory != nullptr); } BFCCullableHandleGroup GraphicElementManager::addMesh(std::shared_ptr<MeshInstance> mesh, std::shared_ptr<MaterialSetInstance> materialInstance) { SCOPE_profile_cpu_function("DRB"); BFCCullableHandleGroup result; for (auto &submesh : mesh->subMeshs) { DRBMesh *drbMesh = nullptr; if (submesh.isSkinned) { auto drbMeshSkeleton = _skinnedMeshPool.create(); drbMesh = drbMeshSkeleton; } else { drbMesh = _meshPool.create(); } drbMesh->datas->setVerticesKey(submesh.vertices); drbMesh->datas->setPainterKey(submesh.painter); drbMesh->datas->setAABB(submesh.boundingBox); std::size_t materialIndex = submesh.defaultMaterialIndex < materialInstance->datas.size() ? submesh.defaultMaterialIndex : 0; auto &material = materialInstance->datas[materialIndex]; // we set the material unique id drbMesh->material = &material; BFCCullableHandle resultMesh = _bfcBlockManager->createItem(drbMesh); result.getHandles().push_back(resultMesh); } return result; } void GraphicElementManager::removeMesh(BFCCullableHandleGroup &handle) { SCOPE_profile_cpu_function("DRB"); for (auto &m : handle.getHandles()) { if (m.getPtr<DRBMesh>()->getDatas()->hadRenderMode(RenderModes::AGE_SKINNED)) { _skinnedMeshPool.destroy(m.getPtr()); } else { _meshPool.destroy(m.getPtr()); } _bfcBlockManager->deleteItem(m); } handle.getHandles().clear(); } }
25.118421
145
0.736511
Another-Game-Engine
58149e7643a81c744cd4db01b0f21e8558ce657c
11,616
cpp
C++
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
1
2020-09-08T15:30:11.000Z
2020-09-08T15:30:11.000Z
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
1
2021-01-21T12:27:39.000Z
2021-01-21T12:27:39.000Z
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
1
2020-08-17T21:07:24.000Z
2020-08-17T21:07:24.000Z
// Copyright (c) 2018-2019 Intel Corporation // // 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 "mfx_dispatch_test_main.h" #include "mfx_dispatch_test_fixtures.h" #include <gtest/gtest.h> #include <gmock/gmock.h> #include <algorithm> #include <sstream> #include "mfx_dispatch_test_mocks.h" constexpr size_t TEST_PLUGIN_COUNT = 7; TEST_F(DispatcherPluginsTest, ShouldSearchForPluginsCfgByCorrectPath) { MockCallObj& mock = *g_call_obj_ptr; EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"),_)).Times(1); mfxPluginUID uid{}; std::fill(uid.Data, uid.Data + sizeof(mfxPluginUID), MOCK_PLUGIN_UID_BYTE_BASE); MFXVideoUSER_Load(session, &uid, 0); } TEST_F(DispatcherPluginsTest, ShouldFailIfPluginIsNotFound) { MockCallObj& mock = *g_call_obj_ptr; EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(1).WillRepeatedly(Return(nullptr)); EXPECT_CALL(mock, fclose).Times(1); mfxPluginUID uid{}; std::fill(uid.Data, uid.Data + sizeof(mfxPluginUID), MOCK_PLUGIN_UID_BYTE_BASE); mfxStatus sts = MFXVideoUSER_Load(session, &uid, 0); ASSERT_EQ(sts, MFX_ERR_NOT_FOUND); } static bool successfully_parsed_at_least_once = false; // The parameter will determine the order of the plugin to be loaded. TEST_P(DispatcherPluginsTestParametrized, ShouldLoadFromGoodPluginsCfgCorrectly) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); size_t plugin_idx = GetParam(); ASSERT_TRUE(plugin_idx < m_plugin_vec.size()); const PluginParamExtended& plugin = m_plugin_vec[plugin_idx]; if (!successfully_parsed_at_least_once) { // The plugin file is only successfully parsed once by the dispatcher, // and the parsed plugin list is stored as a global variable in the // dispatcher lib. Therefore, the calls below will only be executed once. EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap))); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin)); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE))); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_NONE); EXPECT_CALL(mock, dlclose).Times(1); EXPECT_CALL(mock, MFXVideoUSER_Unregister(MOCK_SESSION_HANDLE, plugin.Type)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); sts = MFXVideoUSER_UnLoad(session, &plugin.PluginUID); ASSERT_EQ(sts, MFX_ERR_NONE); } INSTANTIATE_TEST_CASE_P(EnumeratingPlugins, DispatcherPluginsTestParametrized, ::testing::Range((size_t)0, TEST_PLUGIN_COUNT)); TEST_F(DispatcherPluginsTest, ShouldFailIfPluginHasNoSymbols) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); const PluginParamExtended& plugin = m_plugin_vec[0]; if (!successfully_parsed_at_least_once) { EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(0); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(0); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_NOT_FOUND); } TEST_F(DispatcherPluginsTest, ShouldFailIfPluginIsNotCreated) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); const PluginParamExtended& plugin = m_plugin_vec[0]; if (!successfully_parsed_at_least_once) { EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap))); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(0); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED); } TEST_F(DispatcherPluginsTest, ShouldFailIfUnknownPluginParams) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); const PluginParamExtended& plugin = m_plugin_vec[0]; if (!successfully_parsed_at_least_once) { EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap))); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin)); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED); } TEST_F(DispatcherPluginsTest, ShouldFailIfRegisterFailed) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); const PluginParamExtended& plugin = m_plugin_vec[0]; if (!successfully_parsed_at_least_once) { EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap))); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin)); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE))); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED); } TEST_F(DispatcherPluginsTest, ShouldFailIfUnregisterFailed) { MockCallObj& mock = *g_call_obj_ptr; SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT); const PluginParamExtended& plugin = m_plugin_vec[0]; if (!successfully_parsed_at_least_once) { EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR)); EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines)); EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); successfully_parsed_at_least_once = true; } EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE)); EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap))); EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin)); EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE))); EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE)); mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0); ASSERT_EQ(sts, MFX_ERR_NONE); EXPECT_CALL(mock, dlclose).Times(0); EXPECT_CALL(mock, MFXVideoUSER_Unregister(MOCK_SESSION_HANDLE, plugin.Type)).Times(1); sts = MFXVideoUSER_UnLoad(session, &plugin.PluginUID); ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED); }
51.171806
152
0.758781
me176c-dev