lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
src/BabylonCpp/src/maths/spherical_polynomial.cpp
samdauwe/BabylonCpp
eea9f761a49bb460ff1324c20e4674ef120e94f1
#include <babylon/maths/spherical_polynomial.h> #include <babylon/maths/color3.h> #include <babylon/maths/tmp_vectors.h> namespace BABYLON { SphericalPolynomial::SphericalPolynomial() : x{Vector3::Zero()} , y{Vector3::Zero()} , z{Vector3::Zero()} , xx{Vector3::Zero()} , yy{Vector3::Zero()} , zz{Vector3::Zero()} , xy{Vector3::Zero()} , yz{Vector3::Zero()} , zx{Vector3::Zero()} , _harmonics{std::nullopt} { } SphericalPolynomial::SphericalPolynomial(const SphericalPolynomial& other) = default; SphericalPolynomial::SphericalPolynomial(SphericalPolynomial&& other) = default; SphericalPolynomial& SphericalPolynomial::operator=(const SphericalPolynomial& other) = default; SphericalPolynomial& SphericalPolynomial::operator=(SphericalPolynomial&& other) = default; SphericalPolynomial::~SphericalPolynomial() = default; SphericalPolynomial SphericalPolynomial::copy() const { return SphericalPolynomial(*this); } std::unique_ptr<SphericalPolynomial> SphericalPolynomial::clone() const { return std::make_unique<SphericalPolynomial>(*this); } SphericalHarmonics& SphericalPolynomial::preScaledHarmonics() { if (!_harmonics.has_value()) { _harmonics = SphericalHarmonics::FromPolynomial(*this); } if (!_harmonics->preScaled) { _harmonics->preScaleForRendering(); } return *_harmonics; } void SphericalPolynomial::addAmbient(const Color3& color) { TmpVectors::Vector3Array[0].copyFromFloats(color.r, color.g, color.b); auto& colorVector = TmpVectors::Vector3Array[0]; xx.addInPlace(colorVector); yy.addInPlace(colorVector); zz.addInPlace(colorVector); } void SphericalPolynomial::scaleInPlace(float scale) { x.scaleInPlace(scale); y.scaleInPlace(scale); z.scaleInPlace(scale); xx.scaleInPlace(scale); yy.scaleInPlace(scale); zz.scaleInPlace(scale); yz.scaleInPlace(scale); zx.scaleInPlace(scale); xy.scaleInPlace(scale); } SphericalPolynomial& SphericalPolynomial::updateFromHarmonics(const SphericalHarmonics& harmonics) { _harmonics = harmonics; x.copyFrom(harmonics.l11); x.scaleInPlace(1.02333f).scaleInPlace(-1.f); y.copyFrom(harmonics.l1_1); y.scaleInPlace(1.02333f).scaleInPlace(-1.f); z.copyFrom(harmonics.l10); z.scaleInPlace(1.02333f); xx.copyFrom(harmonics.l00); TmpVectors::Vector3Array[0].copyFrom(harmonics.l20).scaleInPlace(0.247708f); TmpVectors::Vector3Array[1].copyFrom(harmonics.l22).scaleInPlace(0.429043f); xx.scaleInPlace(0.886277f) .subtractInPlace(TmpVectors::Vector3Array[0]) .addInPlace(TmpVectors::Vector3Array[1]); yy.copyFrom(harmonics.l00); yy.scaleInPlace(0.886277f) .subtractInPlace(TmpVectors::Vector3Array[0]) .subtractInPlace(TmpVectors::Vector3Array[1]); zz.copyFrom(harmonics.l00); TmpVectors::Vector3Array[0].copyFrom(harmonics.l20).scaleInPlace(0.495417f); zz.scaleInPlace(0.886277f).addInPlace(TmpVectors::Vector3Array[0]); yz.copyFrom(harmonics.l2_1); yz.scaleInPlace(0.858086f).scaleInPlace(-1.f); zx.copyFrom(harmonics.l21); zx.scaleInPlace(0.858086f).scaleInPlace(-1.f); xy.copyFrom(harmonics.l2_2); xy.scaleInPlace(0.858086f); scaleInPlace(1.f / Math::PI); return *this; } SphericalPolynomial SphericalPolynomial::FromHarmonics(const SphericalHarmonics& harmonics) { SphericalPolynomial result; return result.updateFromHarmonics(harmonics); } SphericalPolynomial SphericalPolynomial::FromArray(const std::vector<Float32Array>& data) { SphericalPolynomial sp; if (data.size() < 9) { return sp; } Vector3::FromArrayToRef(data[0], 0, sp.x); Vector3::FromArrayToRef(data[1], 0, sp.y); Vector3::FromArrayToRef(data[2], 0, sp.z); Vector3::FromArrayToRef(data[3], 0, sp.xx); Vector3::FromArrayToRef(data[4], 0, sp.yy); Vector3::FromArrayToRef(data[5], 0, sp.zz); Vector3::FromArrayToRef(data[6], 0, sp.yz); Vector3::FromArrayToRef(data[7], 0, sp.zx); Vector3::FromArrayToRef(data[8], 0, sp.xy); return sp; } }
#include <babylon/maths/spherical_polynomial.h> #include <babylon/maths/color3.h> #include <babylon/maths/tmp_vectors.h> namespace BABYLON { SphericalPolynomial::SphericalPolynomial() : x{Vector3::Zero()} , y{Vector3::Zero()} , z{Vector3::Zero()} , xx{Vector3::Zero()} , yy{Vector3::Zero()} , zz{Vector3::Zero()} , xy{Vector3::Zero()} , yz{Vector3::Zero()} , zx{Vector3::Zero()} , _harmonics{std::nullopt} { } SphericalPolynomial::SphericalPolynomial(const SphericalPolynomial& other) = default; SphericalPolynomial::SphericalPolynomial(SphericalPolynomial&& other) = default; SphericalPolynomial& SphericalPolynomial::operator=(const SphericalPolynomial& other) = default; SphericalPolynomial& SphericalPolynomial::operator=(SphericalPolynomial&& other) = default; SphericalPolynomial::~SphericalPolynomial() = default; SphericalPolynomial SphericalPolynomial::copy() const { return SphericalPolynomial(*this); } std::unique_ptr<SphericalPolynomial> SphericalPolynomial::clone() const { return std::make_unique<SphericalPolynomial>(*this); } SphericalHarmonics& SphericalPolynomial::preScaledHarmonics() { if (!_harmonics.has_value()) { _harmonics = SphericalHarmonics::FromPolynomial(*this); } if (!_harmonics->preScaled) { _harmonics->preScaleForRendering(); } return *_harmonics; } void SphericalPolynomial::addAmbient(const Color3& color) { TmpVectors::Vector3Array[0].copyFromFloats(color.r, color.g, color.b); auto& colorVector = TmpVectors::Vector3Array[0]; xx.addInPlace(colorVector); yy.addInPlace(colorVector); zz.addInPlace(colorVector); } void SphericalPolynomial::scaleInPlace(float scale) { x.scaleInPlace(scale); y.scaleInPlace(scale); z.scaleInPlace(scale); xx.scaleInPlace(scale); yy.scaleInPlace(scale); zz.scaleInPlace(scale); yz.scaleInPlace(scale); zx.scaleInPlace(scale); xy.scaleInPlace(scale); } SphericalPolynomial& SphericalPolynomial::updateFromHarmonics(const SphericalHarmonics& harmonics) { _harmonics = harmonics; x.copyFrom(harmonics.l11); x.scaleInPlace(1.02333f).scaleInPlace(-1.f); y.copyFrom(harmonics.l1_1); y.scaleInPlace(1.02333f).scaleInPlace(-1.f); z.copyFrom(harmonics.l10); z.scaleInPlace(1.02333f); xx.copyFrom(harmonics.l00); TmpVectors::Vector3Array[0].copyFrom(harmonics.l20).scaleInPlace(0.247708f); TmpVectors::Vector3Array[1].copyFrom(harmonics.l22).scaleInPlace(0.429043f); xx.scaleInPlace(0.886277f) .subtractInPlace(TmpVectors::Vector3Array[0]) .addInPlace(TmpVectors::Vector3Array[1]); yy.copyFrom(harmonics.l00); yy.scaleInPlace(0.886277f) .subtractInPlace(TmpVectors::Vector3Array[0]) .subtractInPlace(TmpVectors::Vector3Array[1]); zz.copyFrom(harmonics.l00); TmpVectors::Vector3Array[0].copyFrom(harmonics.l20).scaleInPlace(0.495417f); zz.scaleInPlace(0.886277f).addInPlace(TmpVectors::Vector3Array[0]); yz.copyFrom(harmonics.l2_1); yz.scaleInPlace(0.858086f).scaleInPlace(-1.f); zx.copyFrom(harmonics.l21); zx.scaleInPlace(0.858086f).scaleInPlace(-1.f); xy.copyFrom(harmonics.l2_2); xy.scaleInPlace(0.858086f); scaleInPlace(1.f / Math::PI); return *this; } SphericalPolynomial SphericalPolynomial::FromHarmonics(const SphericalHarmonics& harmonics) { SphericalPolynomial result; return result.updateFromHarmonics(harmonics); } SphericalPolynomial SphericalPolynomial::FromArray(const std::vector<Float32Array>& data) { SphericalPolynomial sp; if (data.size() <
}
9) { return sp; } Vector3::FromArrayToRef(data[0], 0, sp.x); Vector3::FromArrayToRef(data[1], 0, sp.y); Vector3::FromArrayToRef(data[2], 0, sp.z); Vector3::FromArrayToRef(data[3], 0, sp.xx); Vector3::FromArrayToRef(data[4], 0, sp.yy); Vector3::FromArrayToRef(data[5], 0, sp.zz); Vector3::FromArrayToRef(data[6], 0, sp.yz); Vector3::FromArrayToRef(data[7], 0, sp.zx); Vector3::FromArrayToRef(data[8], 0, sp.xy); return sp; }
function_block-function_prefixed
[ { "content": "class Color3;\n", "file_path": "src/BabylonCpp/include/babylon/maths/spherical_harmonics.h", "rank": 0, "score": 282209.0951003985 }, { "content": "namespace BABYLON {\n\n\n\n/**\n\n * @brief Defines One Image in the file. It requires only the position in the\n\n * file as well...
C++
examples/UseOptiXGeometryInstancedStandalone/UseOptiXGeometryInstancedStandalone.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
#include <chrono> #include <iomanip> #include <iostream> #include <cstdlib> #include <cstring> #include <sstream> #include <fstream> #include <optix_world.h> #include <optixu/optixpp_namespace.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> void getEyeUVW(const glm::vec4& ce, const unsigned width, const unsigned height, glm::vec3& eye, glm::vec3& U, glm::vec3& V, glm::vec3& W ) { glm::vec3 tr(ce.x, ce.y, ce.z); glm::vec3 sc(ce.w); glm::vec3 isc(1.f/ce.w); glm::mat4 model2world = glm::scale(glm::translate(glm::mat4(1.0), tr), sc); glm::vec4 eye_m( 0.f, 0.f, 0.1f,1.f); glm::vec4 look_m( 0.7f, 0.7f, -0.7,1.f); glm::vec4 up_m( 0.f, 0.f, 1.f,1.f); glm::vec4 gze_m( look_m - eye_m ) ; const glm::mat4& m2w = model2world ; glm::vec3 eye_ = glm::vec3( m2w * eye_m ) ; glm::vec3 up = glm::vec3( m2w * up_m ) ; glm::vec3 gaze = glm::vec3( m2w * gze_m ) ; glm::vec3 forward_ax = glm::normalize(gaze); glm::vec3 right_ax = glm::normalize(glm::cross(forward_ax,up)); glm::vec3 top_ax = glm::normalize(glm::cross(right_ax,forward_ax)); float aspect = float(width)/float(height) ; float tanYfov = 1.f ; float gazelength = glm::length( gaze ) ; float v_half_height = gazelength * tanYfov ; float u_half_width = v_half_height * aspect ; U = right_ax * u_half_width ; V = top_ax * v_half_height ; W = forward_ax * gazelength ; eye = eye_ ; } const char* PTXPath( const char* install_prefix, const char* cmake_target, const char* cu_stem, const char* cu_ext=".cu" ) { std::stringstream ss ; ss << install_prefix << "/ptx/" << cmake_target << "_generated_" << cu_stem << cu_ext << ".ptx" ; std::string path = ss.str(); return strdup(path.c_str()); } const char* PPMPath( const char* install_prefix, const char* stem, const char* ext=".ppm" ) { std::stringstream ss ; ss << install_prefix << "/ppm/" << stem << ext ; std::string path = ss.str(); return strdup(path.c_str()); } void SPPM_write( const char* filename, const unsigned char* image, int width, int height, int ncomp, bool yflip ) { FILE * fp; fp = fopen(filename, "wb"); fprintf(fp, "P6\n%d %d\n%d\n", width, height, 255); unsigned size = height*width*3 ; unsigned char* data = new unsigned char[size] ; for( int h=0; h < height ; h++ ) { int y = yflip ? height - 1 - h : h ; for( int x=0; x < width ; ++x ) { *(data + (y*width+x)*3+0) = image[(h*width+x)*ncomp+0] ; *(data + (y*width+x)*3+1) = image[(h*width+x)*ncomp+1] ; *(data + (y*width+x)*3+2) = image[(h*width+x)*ncomp+2] ; } } fwrite(data, sizeof(unsigned char)*size, 1, fp); fclose(fp); std::cout << "Wrote file (unsigned char*) " << filename << std::endl ; delete[] data; } float angle_radians(float angle_degrees) { return glm::pi<float>()*angle_degrees/180.f ; } glm::mat4 make_transform(const std::string& order, const glm::vec3& tlat, const glm::vec4& axis_angle, const glm::vec3& scal ) { glm::mat4 mat(1.f) ; float angle = angle_radians(axis_angle.w) ; for(unsigned i=0 ; i < order.length() ; i++) { switch(order[i]) { case 's': mat = glm::scale(mat, scal) ; break ; case 'r': mat = glm::rotate(mat, angle , glm::vec3(axis_angle)) ; break ; case 't': mat = glm::translate(mat, tlat ) ; break ; } } return mat ; } glm::mat4 make_transform(const std::string& order) { glm::vec3 tla(0,0,100) ; glm::vec4 rot(0,0,1,45); glm::vec3 sca(1,1,1) ; return make_transform(order, tla, rot, sca ); } struct APIError { APIError( RTresult c, const std::string& f, int l ) : code( c ), file( f ), line( l ) {} RTresult code; std::string file; int line; }; #define RT_CHECK_ERROR( func ) \ do { \ RTresult code = func; \ if( code != RT_SUCCESS ) \ throw APIError( code, __FILE__, __LINE__ ); \ } while(0) void InitRTX(int rtxmode) { if(rtxmode == -1) { } else { #if OPTIX_VERSION_MAJOR >= 6 int rtx0(-1) ; RT_CHECK_ERROR( rtGlobalGetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx0), &rtx0) ); assert( rtx0 == 0 ); int rtx = rtxmode > 0 ? 1 : 0 ; RT_CHECK_ERROR( rtGlobalSetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx), &rtx)); int rtx2(-1) ; RT_CHECK_ERROR(rtGlobalGetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx2), &rtx2)); assert( rtx2 == rtx ); #else printf("RTX requires optix version >= 6 \n"); #endif } } int main(int argc, char** argv) { const char* rtxstr = getenv("RTX"); int rtxmode = rtxstr ? atoi(rtxstr) : -1 ; assert( rtxmode == -1 || rtxmode == 0 || rtxmode == 1 ); const char* ppmstr = getenv("PPM"); int ppmsave = ppmstr ? atoi(ppmstr) : -1 ; const char* name = getenv("STANDALONE_NAME") ; assert( name && "expecting STANDALONE_NAME envvar with name of the CMake target " ); const char* prefix = getenv("STANDALONE_PREFIX"); assert( prefix && "expecting STANDALONE_PREFIX envvar pointing to writable directory" ); const char* cmake_target = name ; unsigned factor = 1u ; unsigned width = factor*1440u ; unsigned height = factor*900u ; const unsigned nu = 100u; const unsigned nv = 100u; const unsigned nw = 4u; float extent = 100.0 ; glm::vec4 ce(float(nu),float(nv), 0.f, extent ); glm::vec3 eye ; glm::vec3 U ; glm::vec3 V ; glm::vec3 W ; getEyeUVW( ce, width, height, eye, U, V, W ); InitRTX(rtxmode); optix::Context context = optix::Context::create(); context->setRayTypeCount(1); bool prnt = false ; context->setPrintEnabled(prnt); context->setPrintBufferSize(4096); context->setEntryPointCount(1); unsigned entry_point_index = 0u ; const char* ptx = PTXPath( prefix, cmake_target, name ) ; context->setRayGenerationProgram( entry_point_index, context->createProgramFromPTXFile( ptx , "raygen" )); context->setMissProgram( entry_point_index, context->createProgramFromPTXFile( ptx , "miss" )); float sz = 10.f ; unsigned nbox = 10u ; #define RUBOX 1 #ifdef RUBOX optix::Geometry rubox ; rubox = context->createGeometry(); rubox->setPrimitiveCount( nbox ); const char* rubox_ptx = PTXPath( prefix, cmake_target, "rubox" ) ; rubox->setBoundingBoxProgram( context->createProgramFromPTXFile( rubox_ptx , "rubox_bounds" ) ); rubox->setIntersectionProgram( context->createProgramFromPTXFile( rubox_ptx , "rubox_intersect" ) ) ; optix::Geometry& instance = rubox ; #else optix::Geometry box ; box = context->createGeometry(); box->setPrimitiveCount( 1u ); const char* box_ptx = PTXPath( prefix, cmake_target, "box" ) ; box->setBoundingBoxProgram( context->createProgramFromPTXFile( box_ptx , "box_bounds" ) ); box->setIntersectionProgram( context->createProgramFromPTXFile( box_ptx , "box_intersect" ) ) ; optix::Geometry& instance = box ; #endif instance["boxmin"]->setFloat( -sz/2.f, -sz/2.f, -sz/2.f ); instance["boxmax"]->setFloat( sz/2.f, sz/2.f, sz/2.f ); optix::Material mat = context->createMaterial(); mat->setClosestHitProgram( entry_point_index, context->createProgramFromPTXFile( ptx, "closest_hit_radiance0" )); optix::Group top = context->createGroup() ; top->setAcceleration( context->createAcceleration( "Trbvh" ) ); context["top_object"]->set( top ); optix::Group assembly = context->createGroup(); assembly->setChildCount( nu*nv*nw ); assembly->setAcceleration( context->createAcceleration( "Trbvh" ) ); top->addChild(assembly); optix::Acceleration instance_accel = context->createAcceleration( "Trbvh" ); unsigned ichild(0); for( unsigned u = 0; u < nu; ++u ) { for( unsigned v = 0; v < nv ; ++v ) { for( unsigned w = 0; w < nw ; ++w ) { optix::Transform xform = context->createTransform(); glm::vec4 rot( rand(), rand(), rand(), rand()*360.f ); glm::vec3 sca( 0.5 ) ; glm::vec3 tla( 10.f*u , 10.f*v , -10.f*w ) ; glm::mat4 m4 = make_transform("trs", tla, rot, sca ); bool transpose = true ; optix::Matrix4x4 m4_( glm::value_ptr(m4) ) ; xform->setMatrix(transpose, m4_.getData(), 0); assembly->setChild(ichild, xform); unsigned instance_index = ichild ; ichild++ ; optix::GeometryInstance pergi = context->createGeometryInstance() ; pergi->setMaterialCount(1); pergi->setMaterial(0, mat ); pergi->setGeometry( instance ); optix::GeometryGroup perxform = context->createGeometryGroup(); perxform->addChild(pergi); perxform->setAcceleration(instance_accel) ; xform->setChild(perxform); } } } float near = 11.f ; float scene_epsilon = near ; context[ "scene_epsilon"]->setFloat( scene_epsilon ); context[ "eye"]->setFloat( eye.x, eye.y, eye.z ); context[ "U" ]->setFloat( U.x, U.y, U.z ); context[ "V" ]->setFloat( V.x, V.y, V.z ); context[ "W" ]->setFloat( W.x, W.y, W.z ); context[ "radiance_ray_type" ]->setUint( 0u ); optix::Buffer output_buffer = context->createBuffer( RT_BUFFER_OUTPUT, RT_FORMAT_UNSIGNED_BYTE4, width, height); context["output_buffer"]->set( output_buffer ); auto t0 = std::chrono::high_resolution_clock::now(); context->launch( entry_point_index , 0, 0 ); auto t1 = std::chrono::high_resolution_clock::now(); context->launch( entry_point_index , width, height ); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> t_prelaunch = t1 - t0; std::chrono::duration<double> t_launch = t2 - t1; std::cout << " nbox " << nbox << " rtxmode " << std::setw(2) << rtxmode << " prelaunch " << std::setprecision(4) << std::fixed << std::setw(15) << t_prelaunch.count() << " launch " << std::setprecision(4) << std::fixed << std::setw(15) << t_launch.count() << std::endl ; if(ppmsave > 0) { const char* path = PPMPath( prefix, name ); bool yflip = true ; int ncomp = 4 ; void* ptr = output_buffer->map() ; SPPM_write(path, (unsigned char*)ptr , width, height, ncomp, yflip ); output_buffer->unmap(); } return 0 ; }
#include <chrono> #include <iomanip> #include <iostream> #include <cstdlib> #include <cstring> #include <sstream> #include <fstream> #include <optix_world.h> #include <optixu/optixpp_namespace.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> void getEyeUVW(const glm::vec4& ce, const unsigned width, const unsigned height, glm::vec3& eye, glm::vec3& U, glm::vec3& V, glm::vec3& W ) { glm::vec3 tr(ce.x, ce.y, ce.z); glm::vec3 sc(ce.w); glm::vec3 isc(1.f/ce.w); glm::mat4 model2world = glm::scale(glm::translate(glm::mat4(1.0), tr), sc); glm::vec4 eye_m( 0.f, 0.f, 0.1f,1.f); glm::vec4 look_m( 0.7f, 0.7f, -0.7,1.f); glm::vec4 up_m( 0.f, 0.f, 1.f,1.f); glm::vec4 gze_m( look_m - eye_m ) ; const glm::mat4& m2w = model2world ; glm::vec3 eye_ = glm::vec3( m2w * eye_m ) ; glm::vec3 up = glm::vec3( m2w * up_m ) ; glm::vec3 gaze = glm::vec3( m2w * gze_m ) ; glm::vec3 forward_ax = glm::normalize(gaze); glm::vec3 right_ax = glm::normalize(glm::cross(forward_ax,up)); glm::vec3 top_ax = glm::normalize(glm::cross(right_ax,forward_ax)); float aspect = float(width)/float(height) ; float tanYfov = 1.f ; float gazelength = glm::length( gaze ) ; float v_half_height = gazelength * tanYfov ; float u_half_width = v_half_height * aspect ; U = right_ax * u_half_width ; V = top_ax * v_half_height ; W = forward_ax * gazelength ; eye = eye_ ; } const char* PTXPath( const char* install_prefix, const char* cmake_target, const char* cu_stem, const char* cu_ext=".cu" ) { std::stringstream ss ; ss << install_prefix << "/ptx/" << cmake_target << "_generated_" << cu_stem << cu_ext << ".ptx" ; std::string path = ss.str(); return strdup(path.c_str()); } const char* PPMPath( const char* install_prefix, const char* stem, const char* ext=".ppm" ) { std::stringstream ss ; ss << install_prefix << "/ppm/" << stem << ext ; std::string path = ss.str(); return strdup(path.c_str()); } void SPPM_write( const char* filename, const unsigned char* image, int width, int height, int ncomp, bool yflip ) { FILE * fp; fp = fopen(filename, "wb"); fprintf(fp, "P6\n%d %d\n%d\n", width, height, 255); unsigned size = height*width*3 ; unsigned char* data = new unsigned char[size] ; for( int h=0; h < height ; h++ ) { int y = yflip ? height - 1 - h : h ; for( int x=0; x < width ; ++x ) { *(data + (y*width+x)*3+0) = image[(h*width+x)*ncomp+0] ; *(data + (y*width+x)*3+1) = image[(h*width+x)*ncomp+1] ; *(data + (y*width+x)*3+2) = image[(h*width+x)*ncomp+2] ; } } fwrite(data, sizeof(unsigned char)*size, 1, fp); fclose(fp); std::cout << "Wrote file (unsigned char*) " << filename << std::endl ; delete[] data; } float angle_radians(float angle_degrees) { return glm::pi<float>()*angle_degrees/180.f ; } glm::mat4 make_transform(const std::string& order, const glm::vec3& tlat, const glm::vec4& axis_angle, const glm::vec3& scal ) { glm::mat4 mat(1.f) ; float angle = angle_radians(axis_angle.w) ; for(unsigned i=0 ; i < order.length() ; i++) { switch(order[i]) { case 's': mat = glm::scale(mat, scal) ; break ; case 'r': mat = glm::rotate(mat, angle , glm::v
tion( context->createAcceleration( "Trbvh" ) ); top->addChild(assembly); optix::Acceleration instance_accel = context->createAcceleration( "Trbvh" ); unsigned ichild(0); for( unsigned u = 0; u < nu; ++u ) { for( unsigned v = 0; v < nv ; ++v ) { for( unsigned w = 0; w < nw ; ++w ) { optix::Transform xform = context->createTransform(); glm::vec4 rot( rand(), rand(), rand(), rand()*360.f ); glm::vec3 sca( 0.5 ) ; glm::vec3 tla( 10.f*u , 10.f*v , -10.f*w ) ; glm::mat4 m4 = make_transform("trs", tla, rot, sca ); bool transpose = true ; optix::Matrix4x4 m4_( glm::value_ptr(m4) ) ; xform->setMatrix(transpose, m4_.getData(), 0); assembly->setChild(ichild, xform); unsigned instance_index = ichild ; ichild++ ; optix::GeometryInstance pergi = context->createGeometryInstance() ; pergi->setMaterialCount(1); pergi->setMaterial(0, mat ); pergi->setGeometry( instance ); optix::GeometryGroup perxform = context->createGeometryGroup(); perxform->addChild(pergi); perxform->setAcceleration(instance_accel) ; xform->setChild(perxform); } } } float near = 11.f ; float scene_epsilon = near ; context[ "scene_epsilon"]->setFloat( scene_epsilon ); context[ "eye"]->setFloat( eye.x, eye.y, eye.z ); context[ "U" ]->setFloat( U.x, U.y, U.z ); context[ "V" ]->setFloat( V.x, V.y, V.z ); context[ "W" ]->setFloat( W.x, W.y, W.z ); context[ "radiance_ray_type" ]->setUint( 0u ); optix::Buffer output_buffer = context->createBuffer( RT_BUFFER_OUTPUT, RT_FORMAT_UNSIGNED_BYTE4, width, height); context["output_buffer"]->set( output_buffer ); auto t0 = std::chrono::high_resolution_clock::now(); context->launch( entry_point_index , 0, 0 ); auto t1 = std::chrono::high_resolution_clock::now(); context->launch( entry_point_index , width, height ); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> t_prelaunch = t1 - t0; std::chrono::duration<double> t_launch = t2 - t1; std::cout << " nbox " << nbox << " rtxmode " << std::setw(2) << rtxmode << " prelaunch " << std::setprecision(4) << std::fixed << std::setw(15) << t_prelaunch.count() << " launch " << std::setprecision(4) << std::fixed << std::setw(15) << t_launch.count() << std::endl ; if(ppmsave > 0) { const char* path = PPMPath( prefix, name ); bool yflip = true ; int ncomp = 4 ; void* ptr = output_buffer->map() ; SPPM_write(path, (unsigned char*)ptr , width, height, ncomp, yflip ); output_buffer->unmap(); } return 0 ; }
ec3(axis_angle)) ; break ; case 't': mat = glm::translate(mat, tlat ) ; break ; } } return mat ; } glm::mat4 make_transform(const std::string& order) { glm::vec3 tla(0,0,100) ; glm::vec4 rot(0,0,1,45); glm::vec3 sca(1,1,1) ; return make_transform(order, tla, rot, sca ); } struct APIError { APIError( RTresult c, const std::string& f, int l ) : code( c ), file( f ), line( l ) {} RTresult code; std::string file; int line; }; #define RT_CHECK_ERROR( func ) \ do { \ RTresult code = func; \ if( code != RT_SUCCESS ) \ throw APIError( code, __FILE__, __LINE__ ); \ } while(0) void InitRTX(int rtxmode) { if(rtxmode == -1) { } else { #if OPTIX_VERSION_MAJOR >= 6 int rtx0(-1) ; RT_CHECK_ERROR( rtGlobalGetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx0), &rtx0) ); assert( rtx0 == 0 ); int rtx = rtxmode > 0 ? 1 : 0 ; RT_CHECK_ERROR( rtGlobalSetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx), &rtx)); int rtx2(-1) ; RT_CHECK_ERROR(rtGlobalGetAttribute(RT_GLOBAL_ATTRIBUTE_ENABLE_RTX, sizeof(rtx2), &rtx2)); assert( rtx2 == rtx ); #else printf("RTX requires optix version >= 6 \n"); #endif } } int main(int argc, char** argv) { const char* rtxstr = getenv("RTX"); int rtxmode = rtxstr ? atoi(rtxstr) : -1 ; assert( rtxmode == -1 || rtxmode == 0 || rtxmode == 1 ); const char* ppmstr = getenv("PPM"); int ppmsave = ppmstr ? atoi(ppmstr) : -1 ; const char* name = getenv("STANDALONE_NAME") ; assert( name && "expecting STANDALONE_NAME envvar with name of the CMake target " ); const char* prefix = getenv("STANDALONE_PREFIX"); assert( prefix && "expecting STANDALONE_PREFIX envvar pointing to writable directory" ); const char* cmake_target = name ; unsigned factor = 1u ; unsigned width = factor*1440u ; unsigned height = factor*900u ; const unsigned nu = 100u; const unsigned nv = 100u; const unsigned nw = 4u; float extent = 100.0 ; glm::vec4 ce(float(nu),float(nv), 0.f, extent ); glm::vec3 eye ; glm::vec3 U ; glm::vec3 V ; glm::vec3 W ; getEyeUVW( ce, width, height, eye, U, V, W ); InitRTX(rtxmode); optix::Context context = optix::Context::create(); context->setRayTypeCount(1); bool prnt = false ; context->setPrintEnabled(prnt); context->setPrintBufferSize(4096); context->setEntryPointCount(1); unsigned entry_point_index = 0u ; const char* ptx = PTXPath( prefix, cmake_target, name ) ; context->setRayGenerationProgram( entry_point_index, context->createProgramFromPTXFile( ptx , "raygen" )); context->setMissProgram( entry_point_index, context->createProgramFromPTXFile( ptx , "miss" )); float sz = 10.f ; unsigned nbox = 10u ; #define RUBOX 1 #ifdef RUBOX optix::Geometry rubox ; rubox = context->createGeometry(); rubox->setPrimitiveCount( nbox ); const char* rubox_ptx = PTXPath( prefix, cmake_target, "rubox" ) ; rubox->setBoundingBoxProgram( context->createProgramFromPTXFile( rubox_ptx , "rubox_bounds" ) ); rubox->setIntersectionProgram( context->createProgramFromPTXFile( rubox_ptx , "rubox_intersect" ) ) ; optix::Geometry& instance = rubox ; #else optix::Geometry box ; box = context->createGeometry(); box->setPrimitiveCount( 1u ); const char* box_ptx = PTXPath( prefix, cmake_target, "box" ) ; box->setBoundingBoxProgram( context->createProgramFromPTXFile( box_ptx , "box_bounds" ) ); box->setIntersectionProgram( context->createProgramFromPTXFile( box_ptx , "box_intersect" ) ) ; optix::Geometry& instance = box ; #endif instance["boxmin"]->setFloat( -sz/2.f, -sz/2.f, -sz/2.f ); instance["boxmax"]->setFloat( sz/2.f, sz/2.f, sz/2.f ); optix::Material mat = context->createMaterial(); mat->setClosestHitProgram( entry_point_index, context->createProgramFromPTXFile( ptx, "closest_hit_radiance0" )); optix::Group top = context->createGroup() ; top->setAcceleration( context->createAcceleration( "Trbvh" ) ); context["top_object"]->set( top ); optix::Group assembly = context->createGroup(); assembly->setChildCount( nu*nv*nw ); assembly->setAccelera
random
[ { "content": "struct DescriptorDataType<unsigned int> { static const char value = 'u'; };\n\ntemplate<>\n", "file_path": "npy/numpy.hpp", "rank": 0, "score": 339528.31468513457 }, { "content": "struct DescriptorDataType<unsigned char> { static const char value = 'u'; };\n\ntemplate<>\n", ...
C++
CompareContacts/main.cpp
Sioniras/MD-Tools
df408c122dfb57100bdc976dba66b47ee03622fe
#include <iostream> #include <vector> #include <memory> #include <cstdlib> #include <algorithm> #include <sstream> #include <iomanip> #include "ContactList.h" int main(int argc,char** argv) { if(argc < 4) { std::cout << "Please specify the minimum score and at least two contacts files." << std::endl; std::cout << "compcontacts [minimum score] [file1] [file2] [optional: add more files]" << std::endl; return 0; } std::vector<std::shared_ptr<ContactList> > list; const int minscore = std::atoi(argv[1]); const int columnpadding = 8; std::cout << "Loading contact files for analysis with a minimum score of " << minscore << "." << std::endl; for(int i = 2;i < argc;i++) { std::string strargv(argv[i]); std::shared_ptr<ContactList> new_ptr(new ContactList(strargv)); if(new_ptr->IsValid()) { list.push_back(std::shared_ptr<ContactList>(new_ptr)); } else { std::cerr << "Failed to parse file \"" << strargv << "\"! Exitting program." << std::endl; std::exit(1); } } std::cout << "Finished reading the contact files." << std::endl; std::vector<Contact> FullContactList; for(auto i = list.cbegin(); i != list.cend(); i++) { std::vector<Contact> tmp(FullContactList); FullContactList.clear(); std::set_union( (*i)->List().cbegin(), (*i)->List().cend(), tmp.cbegin(), tmp.cend(), std::back_inserter(FullContactList)); } std::cout << "Found a total of " << FullContactList.size() << " unique contacts." << std::endl; std::cout << "The table contains the mean score for the trajectories containing the contact. Note that only contacts with a score of at least " << minscore << " are shown.\n" << std::endl; std::sort(FullContactList.begin(),FullContactList.end()); std::stringstream str; str << std::setw(2*columnpadding+2) << "Contacts |"; for(unsigned int i = 0;i < list.size();i++) str << " " << std::setw(columnpadding-1) << "file " << (i+1) << " |"; str << "\n" << std::string(str.str().size(),'-'); std::cout << str.str() << std::endl; std::string s[list.size()]; int cs[list.size()] = {0}; int k = 0; int k2 = 0; double m = 0.0; for(auto i = FullContactList.cbegin(); i != FullContactList.cend(); i++) { str.str(""); str << std::setw(columnpadding) << (*i).Left << " -" << std::setw(columnpadding) << (*i).Right + " |"; k = 0; k2 = 0; m = 0.0; for(auto j = list.cbegin(); j != list.cend(); j++) { auto it = std::find( (*j)->List().cbegin(), (*j)->List().cend(), (*i)); if(it != (*j)->List().cend() && (*it).Mean >= minscore) { k++; cs[k2]++; m = (m < (*it).Mean)?(*it).Mean:m; str << " " << std::setw(columnpadding) << (*it).Mean << " |"; } else { str << " " << std::setw(columnpadding) << "" << " |"; } k2++; } if(m >= minscore) s[k-1] += str.str() + "\n"; } for(unsigned int i = 0;i < list.size(); i++) std::cout << s[i]; std::cout << std::string(str.str().size(),'-') << std::endl; std::cout << std::setw(2*columnpadding+2) << "Total contacts |"; for(unsigned int i = 0;i < list.size(); i++) std::cout << " " << std::setw(columnpadding) << cs[i] << " |"; std::cout << std::endl; }
#include <iostream> #include <vector> #include <memory> #include <cstdlib> #include <algorithm> #include <sstream> #include <iomanip> #include "ContactList.h" int main(int argc,char** argv) { if(argc < 4) { std::cout << "Please specify the minimum score and at least two contacts files." << std::endl; std::cout << "compcontacts [minimum score] [file1] [file2] [optional: add more files]" << std::endl; return 0; } std::vector<std::shared_ptr<ContactList> > list; const int minscore = std::atoi(argv[1]); const int columnpadding = 8; std::cout << "Loading contact files for analysis with a minimum score of " << minscore << "." << std::endl; for(int i = 2;i < argc;i++) { std::string strargv(argv[i]); std::shared_ptr<ContactList> new_ptr(new ContactList(strargv)); if(new_ptr->IsValid()) { list.push_back(std::shared_ptr<ContactList>(new_ptr)); } else { std::cerr << "Failed to parse file \"" << strargv << "\"! Exitting program." << std::endl; std::exit(1); } } std::cout << "Finished reading the contact files." << std::endl; std::vector<Contact> FullContactList; for(auto i = list.cbegin(); i != list.cend(); i++) { std::vector<Contact> tmp(FullContactList); FullContactList.clear(); std::set_union( (*i)->List().cbegin(), (*i)->List().cend(), tmp.cbegin(), tmp.cend(), std::back_inserter(FullContactList)); } std::cout << "Found a total of " << FullContactList.size() << " unique contacts." << std::endl; std::cout << "The table contains the mean score for the trajectories containing the contact. Note that only contacts with a score of at least " << minscore << " are shown.\n" << std::endl; std::sort(FullContactList.begin(),FullContactList.end()); std::stringstream str; str << std::setw(2*columnpadding+2) << "Contacts |"; for(unsigned int i = 0;i < list.size();i++) str << " " << std::setw(columnpadding-1) << "file " << (i+1) << " |"; str << "\n" << std::string(str.str().size(),'-'); std::cout << str.str() << std::endl; std::string s[list.size()]; int cs[list.size()] = {0}; int k = 0; int k2 = 0; double m = 0.0; for(auto i = FullContactList.cbegin(); i != FullContactList.cend(); i++) { str.str(""); str << std::setw(columnpadding)
str << " " << std::setw(columnpadding) << "" << " |"; } k2++; } if(m >= minscore) s[k-1] += str.str() + "\n"; } for(unsigned int i = 0;i < list.size(); i++) std::cout << s[i]; std::cout << std::string(str.str().size(),'-') << std::endl; std::cout << std::setw(2*columnpadding+2) << "Total contacts |"; for(unsigned int i = 0;i < list.size(); i++) std::cout << " " << std::setw(columnpadding) << cs[i] << " |"; std::cout << std::endl; }
<< (*i).Left << " -" << std::setw(columnpadding) << (*i).Right + " |"; k = 0; k2 = 0; m = 0.0; for(auto j = list.cbegin(); j != list.cend(); j++) { auto it = std::find( (*j)->List().cbegin(), (*j)->List().cend(), (*i)); if(it != (*j)->List().cend() && (*it).Mean >= minscore) { k++; cs[k2]++; m = (m < (*it).Mean)?(*it).Mean:m; str << " " << std::setw(columnpadding) << (*it).Mean << " |"; } else {
random
[ { "content": "// Contact helper struct\n\nstruct Contact\n\n{\n\n\tpublic:\n\n\t\t// Data members\n\n\t\tstd::string Left;\n\n\t\tstd::string Right;\n\n\t\tstd::string Type;\n\n\t\tfloat Mean;\n\n\t\tfloat Median;\n\n\t\tfloat HBondPercentage;\n\n\t\n\n\t\t// Constructors / destructor\n\n\t\tContact() {};\n\n\t...
C++
Builds/JuceLibraryCode/modules/juce_core/native/juce_android_Network.cpp
eriser/CSL
6f4646369f0c90ea90e2c113374044818ab37ded
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \ METHOD (constructor, "<init>", "()V") \ METHOD (toString, "toString", "()Ljava/lang/String;") \ DECLARE_JNI_CLASS (StringBuffer, "java/lang/StringBuffer"); #undef JNI_CLASS_MEMBERS #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \ METHOD (release, "release", "()V") \ METHOD (read, "read", "([BI)I") \ METHOD (getPosition, "getPosition", "()J") \ METHOD (getTotalLength, "getTotalLength", "()J") \ METHOD (isExhausted, "isExhausted", "()Z") \ METHOD (setPosition, "setPosition", "(J)Z") \ DECLARE_JNI_CLASS (HTTPStream, JUCE_ANDROID_ACTIVITY_CLASSPATH "$HTTPStream"); #undef JNI_CLASS_MEMBERS void MACAddress::findAllAddresses (Array<MACAddress>& result) { } bool Process::openEmailWithAttachments (const String& targetEmailAddress, const String& emailSubject, const String& bodyText, const StringArray& filesToAttach) { return false; } class WebInputStream : public InputStream { public: WebInputStream (String address, bool isPost, const MemoryBlock& postData, URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext, const String& headers, int timeOutMs, StringPairArray* responseHeaders) { if (! address.contains ("://")) address = "http://" + address; JNIEnv* env = getEnv(); jbyteArray postDataArray = 0; if (postData.getSize() > 0) { postDataArray = env->NewByteArray (postData.getSize()); env->SetByteArrayRegion (postDataArray, 0, postData.getSize(), (const jbyte*) postData.getData()); } LocalRef<jobject> responseHeaderBuffer (env->NewObject (StringBuffer, StringBuffer.constructor)); stream = GlobalRef (env->CallStaticObjectMethod (JuceAppActivity, JuceAppActivity.createHTTPStream, javaString (address).get(), (jboolean) isPost, postDataArray, javaString (headers).get(), (jint) timeOutMs, responseHeaderBuffer.get())); if (postDataArray != 0) env->DeleteLocalRef (postDataArray); if (stream != 0) { StringArray headerLines; { LocalRef<jstring> headersString ((jstring) env->CallObjectMethod (responseHeaderBuffer.get(), StringBuffer.toString)); headerLines.addLines (juceString (env, headersString)); } if (responseHeaders != 0) { for (int i = 0; i < headerLines.size(); ++i) { const String& header = headerLines[i]; const String key (header.upToFirstOccurrenceOf (": ", false, false)); const String value (header.fromFirstOccurrenceOf (": ", false, false)); const String previousValue ((*responseHeaders) [key]); responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value)); } } } } ~WebInputStream() { if (stream != 0) stream.callVoidMethod (HTTPStream.release); } bool isExhausted() { return stream != nullptr && stream.callBooleanMethod (HTTPStream.isExhausted); } int64 getTotalLength() { return stream != nullptr ? stream.callLongMethod (HTTPStream.getTotalLength) : 0; } int64 getPosition() { return stream != nullptr ? stream.callLongMethod (HTTPStream.getPosition) : 0; } bool setPosition (int64 wantedPos) { return stream != nullptr && stream.callBooleanMethod (HTTPStream.setPosition, (jlong) wantedPos); } int read (void* buffer, int bytesToRead) { jassert (buffer != nullptr && bytesToRead >= 0); if (stream == nullptr) return 0; JNIEnv* env = getEnv(); jbyteArray javaArray = env->NewByteArray (bytesToRead); int numBytes = stream.callIntMethod (HTTPStream.read, javaArray, (jint) bytesToRead); if (numBytes > 0) env->GetByteArrayRegion (javaArray, 0, numBytes, static_cast <jbyte*> (buffer)); env->DeleteLocalRef (javaArray); return numBytes; } GlobalRef stream; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream); }; InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData, OpenStreamProgressCallback* progressCallback, void* progressCallbackContext, const String& headers, const int timeOutMs, StringPairArray* responseHeaders) { ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData, progressCallback, progressCallbackContext, headers, timeOutMs, responseHeaders)); return wi->stream != 0 ? wi.release() : nullptr; }
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \ METHOD (constructor, "<init>", "()V") \ METHOD (toString, "toString", "()Ljava/lang/String;") \ DECLARE_JNI_CLASS (StringBuffer, "java/lang/StringBuffer"); #undef JNI_CLASS_MEMBERS #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \ METHOD (release, "release", "()V") \ METHOD (read, "read", "([BI)I") \ METHOD (getPosition, "getPosition", "()J") \ METHOD (getTotalLength, "getTotalLength", "()J") \ METHOD (isExhausted, "isExhausted", "()Z") \ METHOD (setPosition, "setPosition", "(J)Z") \ DECLARE_JNI_CLASS (HTTPStream, JUCE_ANDROID_ACTIVITY_CLASSPATH "$HTTPStream"); #undef JNI_CLASS_MEMBERS void MACAddress::findAllAddresses (Array<MACAddress>& result) { } bool Process::openEmailWithAttachments (const String& targetEmailAddress, const String& emailSubject, const String& bodyText, const StringArray& filesToAttach) { return false; } class WebInputStream : public InputStream { public: WebInputStream (String address, bool isPost, const MemoryBlock& postData, URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext, const String& headers, int timeOutMs, StringPairArray* responseHeaders) { if (! address.contains ("://")) address = "http://" + address; JNIEnv* env = getEnv(); jbyteArray postDataArray = 0;
LocalRef<jobject> responseHeaderBuffer (env->NewObject (StringBuffer, StringBuffer.constructor)); stream = GlobalRef (env->CallStaticObjectMethod (JuceAppActivity, JuceAppActivity.createHTTPStream, javaString (address).get(), (jboolean) isPost, postDataArray, javaString (headers).get(), (jint) timeOutMs, responseHeaderBuffer.get())); if (postDataArray != 0) env->DeleteLocalRef (postDataArray); if (stream != 0) { StringArray headerLines; { LocalRef<jstring> headersString ((jstring) env->CallObjectMethod (responseHeaderBuffer.get(), StringBuffer.toString)); headerLines.addLines (juceString (env, headersString)); } if (responseHeaders != 0) { for (int i = 0; i < headerLines.size(); ++i) { const String& header = headerLines[i]; const String key (header.upToFirstOccurrenceOf (": ", false, false)); const String value (header.fromFirstOccurrenceOf (": ", false, false)); const String previousValue ((*responseHeaders) [key]); responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value)); } } } } ~WebInputStream() { if (stream != 0) stream.callVoidMethod (HTTPStream.release); } bool isExhausted() { return stream != nullptr && stream.callBooleanMethod (HTTPStream.isExhausted); } int64 getTotalLength() { return stream != nullptr ? stream.callLongMethod (HTTPStream.getTotalLength) : 0; } int64 getPosition() { return stream != nullptr ? stream.callLongMethod (HTTPStream.getPosition) : 0; } bool setPosition (int64 wantedPos) { return stream != nullptr && stream.callBooleanMethod (HTTPStream.setPosition, (jlong) wantedPos); } int read (void* buffer, int bytesToRead) { jassert (buffer != nullptr && bytesToRead >= 0); if (stream == nullptr) return 0; JNIEnv* env = getEnv(); jbyteArray javaArray = env->NewByteArray (bytesToRead); int numBytes = stream.callIntMethod (HTTPStream.read, javaArray, (jint) bytesToRead); if (numBytes > 0) env->GetByteArrayRegion (javaArray, 0, numBytes, static_cast <jbyte*> (buffer)); env->DeleteLocalRef (javaArray); return numBytes; } GlobalRef stream; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream); }; InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData, OpenStreamProgressCallback* progressCallback, void* progressCallbackContext, const String& headers, const int timeOutMs, StringPairArray* responseHeaders) { ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData, progressCallback, progressCallbackContext, headers, timeOutMs, responseHeaders)); return wi->stream != 0 ? wi.release() : nullptr; }
if (postData.getSize() > 0) { postDataArray = env->NewByteArray (postData.getSize()); env->SetByteArrayRegion (postDataArray, 0, postData.getSize(), (const jbyte*) postData.getData()); }
if_condition
[ { "content": "class KarplusString : public UnitGenerator, public Scalable, public Phased {\n\n\n\npublic:\n\n\tKarplusString();\n\n\tKarplusString(float frequency);\n\n\tvoid setFrequency(float frequency);\n\n\tvoid trigger();\t\t\t\t\t///< reset internal buffers to re-pluck the string.\n\n\tvoid dump();\t\t\t\...
C++
curves/include/curves/PolynomialSpline.hpp
leggedrobotics/curves
696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe
#pragma once #include <Eigen/Core> #include "curves/polynomial_splines_traits.hpp" #include <numeric> namespace curves { template <int splineOrder_> class PolynomialSpline { public: static constexpr unsigned int splineOrder = splineOrder_; static constexpr unsigned int coefficientCount = splineOrder + 1; using SplineImplementation = spline_traits::spline_rep<double, splineOrder>; using SplineCoefficients = typename SplineImplementation::SplineCoefficients; using EigenTimeVectorType = Eigen::Matrix<double, 1, coefficientCount>; using EigenCoefficientVectorType = Eigen::Matrix<double, coefficientCount, 1>; PolynomialSpline() : duration_(0.0), didEvaluateCoeffs_(false), coefficients_() { } template<typename SplineCoeff_> PolynomialSpline(SplineCoeff_&& coefficients, double duration) : duration_(duration), didEvaluateCoeffs_(true), coefficients_(std::forward<SplineCoeff_>(coefficients)) { } explicit PolynomialSpline(const SplineOptions& options) : duration_(options.tf_) { computeCoefficients(options); } explicit PolynomialSpline(SplineOptions&& options) : duration_(options.tf_) { computeCoefficients(std::move(options)); } virtual ~PolynomialSpline() = default; PolynomialSpline(PolynomialSpline &&) = default; PolynomialSpline& operator=(PolynomialSpline &&) = default; PolynomialSpline(const PolynomialSpline&) = default; PolynomialSpline& operator=(const PolynomialSpline&) = default; const SplineCoefficients& getCoefficients() const { return coefficients_; } SplineCoefficients* getCoefficientsPtr() { return &coefficients_; } template<typename SplineOptionsType_> bool computeCoefficients(SplineOptionsType_&& options) { duration_ = options.tf_; return SplineImplementation::compute(std::forward<SplineOptionsType_>(options), coefficients_); } void setCoefficientsAndDuration(const SplineCoefficients& coefficients, double duration) { coefficients_ = coefficients; duration_ = duration; } constexpr double getPositionAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::tau(tk).begin(), 0.0); } constexpr double getVelocityAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::dtau(tk).begin(), 0.0); } constexpr double getAccelerationAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::ddtau(tk).begin(), 0.0); } static inline void getTimeVector(Eigen::Ref<EigenTimeVectorType> timeVec, const double tk) { timeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::tau(tk).data()); } template<typename Derived> static inline void getTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data()); } template<typename Derived> static inline void addTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data()); } static inline void getDTimeVector(Eigen::Ref<EigenTimeVectorType> dtimeVec, const double tk) { dtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::dtau(tk).data()); } template<typename Derived> static inline void getDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } template<typename Derived> static inline void addDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } static inline void getDDTimeVector(Eigen::Ref<EigenTimeVectorType> ddtimeVec, const double tk) { ddtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::ddtau(tk).data()); } template<typename Derived> static inline void getDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } template<typename Derived> static inline void addDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtau(tk)).data()); } static inline void getTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> timeVec) { timeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } template<typename Derived> static inline void getTimeVectorAtZero( Eigen::MatrixBase<Derived> const & timeVec) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } template<typename Derived> static inline void addTimeVectorAtZero( Eigen::MatrixBase<Derived> const & timeVec) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } static inline void getDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> dtimeVec) { dtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); } template<typename Derived> static inline void getDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & dtimeVec) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); } template<typename Derived> static inline void addDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & dtimeVec) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); } static inline void getDDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> ddtimeVec) { ddtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } template<typename Derived> static inline void getDDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & ddtimeVec) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } template<typename Derived> static inline void addDDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & ddtimeVec) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } double getSplineDuration() const { return duration_; } protected: double duration_; bool didEvaluateCoeffs_; SplineCoefficients coefficients_; }; }
#pragma once #include <Eigen/Core> #include "curves/polynomial_splines_traits.hpp" #include <numeric> namespace curves { template <int splineOrder_> class PolynomialSpline { public: static constexpr unsigned int splineOrder = splineOrder_; static constexpr unsigned int coefficientCount = splineOrder + 1; using SplineImplementation = spline_traits::spline_rep<double, splineOrder>; using SplineCoefficients = typename SplineImplementation::SplineCoefficients; using EigenTimeVectorType = Eigen::Matrix<double, 1, coefficientCount>; using EigenCoefficientVectorType = Eigen::Matrix<double, coefficientCount, 1>; PolynomialSpline() : duration_(0.0), didEvaluateCoeffs_(false), coefficients_() { } template<typename SplineCoeff_> PolynomialSpline(SplineCoeff_&& coefficients, double duration) : duration_(duration), didEvaluateCoeffs_(true), coefficients_(std::forward<SplineCoeff_>(coefficients)) { } explicit PolynomialSpline(const SplineOptions& options) : duration_(options.tf_) { computeCoefficients(options); } explicit PolynomialSpline(SplineOptions&& options) : duration_(options.tf_) { computeCoefficients(std::move(options)); } virtual ~PolynomialSpline() = default; PolynomialSpline(PolynomialSpline &&) = default; PolynomialSpline& operator=(PolynomialSpline &&) = default; PolynomialSpline(const PolynomialSpline&) = default; PolynomialSpline& operator=(const PolynomialSpline&) = default; const SplineCoefficients& getCoefficients() const { return coefficients_; } SplineCoefficients* getCoefficientsPtr() { return &coefficients_; } template<typename SplineOptionsType_> bool computeCoefficients(SplineOptionsType_&& options) { duration_ = options.tf_; return SplineImplementation::compute(std::forward<SplineOptionsType_>(options), coefficients_); } void setCoefficientsAndDuration(const SplineCoefficients& coefficients, double duration) { coefficients_ = coefficients; duration_ = duration; } constexpr double getPositionAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::tau(tk).begin(), 0.0); } constexpr double getVelocityAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::dtau(tk).begin(), 0.0); } constexpr double getAccelerationAtTime(double tk) const { return std::inner_product(coefficients_.begin(), coefficients_.end(), SplineImplementation::ddtau(tk).begin(), 0.0); } static inline void getTimeVector(Eigen::Ref<EigenTimeVectorType> timeVec, const double tk) { timeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::tau(tk).data()); } template<typename
static inline void getDDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> ddtimeVec) { ddtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } template<typename Derived> static inline void getDDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & ddtimeVec) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } template<typename Derived> static inline void addDDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & ddtimeVec) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data()); } double getSplineDuration() const { return duration_; } protected: double duration_; bool didEvaluateCoeffs_; SplineCoefficients coefficients_; }; }
Derived> static inline void getTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data()); } template<typename Derived> static inline void addTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data()); } static inline void getDTimeVector(Eigen::Ref<EigenTimeVectorType> dtimeVec, const double tk) { dtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::dtau(tk).data()); } template<typename Derived> static inline void getDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } template<typename Derived> static inline void addDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } static inline void getDDTimeVector(Eigen::Ref<EigenTimeVectorType> ddtimeVec, const double tk) { ddtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::ddtau(tk).data()); } template<typename Derived> static inline void getDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data()); } template<typename Derived> static inline void addDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) { assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtau(tk)).data()); } static inline void getTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> timeVec) { timeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } template<typename Derived> static inline void getTimeVectorAtZero( Eigen::MatrixBase<Derived> const & timeVec) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } template<typename Derived> static inline void addTimeVectorAtZero( Eigen::MatrixBase<Derived> const & timeVec) { assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(timeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data()); } static inline void getDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> dtimeVec) { dtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); } template<typename Derived> static inline void getDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & dtimeVec) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); } template<typename Derived> static inline void addDiffTimeVectorAtZero( Eigen::MatrixBase<Derived> const & dtimeVec) { assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime && dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime); const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) += Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data()); }
random
[ { "content": "class LocalSupport2CoefficientManagerTest : public ::testing::Test {\n\n protected:\n\n\n\n typedef Eigen::Matrix<double,3,1> Coefficient;\n\n typedef LocalSupport2CoefficientManager<Coefficient>::CoefficientIter CoefficientIter;\n\n\n\n virtual void SetUp() {\n\n N = 50;\n\n for(size_t i...
C++
DigitalHaze-Libraries/cpp/DH_BitParser.cpp
Phytress/DigitalHaze-Libraries
a94a292da302da23851cc780cfec9d4736dcf9c4
#include "DH_BitParser.hpp" namespace DigitalHaze { BitParser::BitParser(void* buffer, size_t lenInBits) noexcept : dataPtr((unsigned char*) buffer), lengthInBits(lenInBits), startBitPos(0) { } BitParser::BitParser(const BitParser& other) noexcept : dataPtr(other.dataPtr), lengthInBits(other.lengthInBits), startBitPos(other.startBitPos) { } BitParser::BitParser(BitParser&& other) noexcept : dataPtr(other.dataPtr), lengthInBits(other.lengthInBits), startBitPos(other.startBitPos) { } BitParser::~BitParser() noexcept { } BitParser& BitParser::operator=(const BitParser& other) noexcept { dataPtr = other.dataPtr; lengthInBits = other.lengthInBits; startBitPos = other.startBitPos; return *this; } BitParser& BitParser::operator=(BitParser&& other) noexcept { dataPtr = other.dataPtr; lengthInBits = other.lengthInBits; startBitPos = other.startBitPos; return *this; } void BitParser::offsetBuffer(ptrdiff_t offsetInBits) { startBitPos = (ptrdiff_t) startBitPos + offsetInBits; if (startBitPos < 0) { dataPtr -= 1 + ((startBitPos - 1) / -8); startBitPos &= 7; } else if (startBitPos > 7) { dataPtr += startBitPos / 8; startBitPos &= 7; } lengthInBits = (ptrdiff_t) lengthInBits - offsetInBits; } SingleBitDescriptor BitParser::operator[](ptrdiff_t index) const { ptrdiff_t bytePos; int bitPos; if (index > 0) { bytePos = index / 8; bitPos = (int) ((index % 8) + startBitPos); } else if (index < 0) { bytePos = -1 + ((index + 1) / 8); bitPos = (int) ((index & 7) + startBitPos); } else { bytePos = 0; bitPos = (int) startBitPos; } if (bitPos > 7) { bitPos -= 8; bytePos++; } return SingleBitDescriptor(dataPtr + bytePos, bitPos); } SingleBitDescriptor BitParser::operator*() const { return SingleBitDescriptor(dataPtr, (unsigned char) startBitPos); } BitParser& BitParser::operator++() { offsetBuffer(1); return *this; } SingleBitDescriptor::SingleBitDescriptor(unsigned char* bptr, unsigned char bit) noexcept : bytePtr(bptr), bitPos(bit) { } SingleBitDescriptor& SingleBitDescriptor::operator=(bool rhs) { if (rhs) *bytePtr |= 1 << bitPos; else *bytePtr &= ~(1 << bitPos); return *this; } SingleBitDescriptor& SingleBitDescriptor::operator=(int rhs) { *this = (bool)!!rhs; return *this; } SingleBitDescriptor& SingleBitDescriptor::operator=(SingleBitDescriptor& rhs) noexcept { *this = (bool)rhs; } bool SingleBitDescriptor::operator==(bool rhs) const { return (bool) * this == rhs; } bool SingleBitDescriptor::operator!=(bool rhs) const { return !(*this == rhs); } SingleBitDescriptor::operator int() const { return !!(*bytePtr & (1 << bitPos)); } SingleBitDescriptor::operator bool() const { return !!(*bytePtr & (1 << bitPos)); } BitBufferIterator BitParser::begin() const { return BitBufferIterator(this, 0); } BitBufferIterator BitParser::end() const { return BitBufferIterator(this, lengthInBits); } BitBufferIterator::BitBufferIterator(const BitParser* bptr, size_t bpos) noexcept : bbPtr(bptr), pos(bpos) { } bool BitBufferIterator::operator!=(BitBufferIterator& rhs) const { return pos != rhs.pos; } SingleBitDescriptor BitBufferIterator::operator*() const { return (*bbPtr)[pos]; } BitBufferIterator& BitBufferIterator::operator++() { pos++; return *this; } }
#include "DH_BitParser.hpp" namespace DigitalHaze { BitParser::BitParser(void* buffer, size_t lenInBits) noexcept : dataPtr((unsigned char*) buffer), lengthInBits(lenInBits), startBitPos(0) { } BitParser::BitParser(const BitParser& other) noexcept : dataPtr(other.dataPtr), lengthInBits(other.lengthInBits), startBitPos(other.startBitPos) { } BitParser::BitParser(BitParser&& other) noexcept : dataPtr(other.dataPtr), lengthInBits(other.lengthInBits), startBitPos(other.startBitPos) { } BitParser::~BitParser() noexcept { } BitParser& BitParser::operator=(const BitParser& other) noexcept { dataPtr = other.dataPtr; lengthInBits = other.lengthInBits; startBitPos = other.startBitPos; return *this; } BitParser& BitParser::operator=(BitParser&& other) noexcept { dataPtr = other.dataPtr; lengthInBits = other.lengthInBits; startBitPos = other.startBitPos; return *this; } void BitParser::offsetBuffer(ptrdiff_t offsetInBits) { startBitPos = (ptrdiff_t) startBitPos + offsetInBits; if (startBitPos < 0) { dataPtr -= 1 + ((startBitPos - 1) / -8); startBitPos &= 7; } else if (startBitPos > 7) { dataPtr += startBitPos / 8; startBitPos &= 7; } lengthInBits = (ptrdiff_t) lengthInBits - offsetInBits; } SingleBitDescriptor BitParser::operator[](ptrdiff_t index) const { ptrdiff_t bytePos; int bitPos; if (index > 0) { bytePos = index / 8; bitPos = (int) ((index % 8) + startBitPos); } else if (index < 0) { bytePos = -1 + ((index + 1) / 8); bitPos = (int) ((index & 7) + startBitPos); } else { bytePos = 0; bitPos = (int) startBitPos; } if (bitPos > 7) { bitPos -= 8; bytePos++; } return SingleBitDescriptor(dataPtr + bytePos, bitPos); } SingleBitDescriptor BitParser::operator*() const { return SingleBitDescriptor(dataPtr, (unsigned char) startBitPos); } BitParser& BitParser::operator++() { offsetBuffer(1); return *this; } SingleBitDescriptor::SingleBitDescriptor(unsigned char* bptr, unsigned char bit) noexcept : bytePtr(bptr), bitPos(bit) { } SingleBitDescriptor& SingleBitDescriptor::operator=(bool rhs) { if (rhs) *bytePtr |= 1 << bitPos; else *bytePtr &= ~(1 << bitPos); return *this; } SingleBitDescriptor& SingleBitDescriptor::operator=(int rhs) { *this = (bool)!!rhs; return *this; } SingleBitDescriptor& SingleBitDescriptor::operator=(SingleBitDescriptor& rhs) noexcept { *this = (bool)rhs; } bool SingleBitDescriptor::operator==(bool rhs) const { return (bool) * thi
or::operator!=(BitBufferIterator& rhs) const { return pos != rhs.pos; } SingleBitDescriptor BitBufferIterator::operator*() const { return (*bbPtr)[pos]; } BitBufferIterator& BitBufferIterator::operator++() { pos++; return *this; } }
s == rhs; } bool SingleBitDescriptor::operator!=(bool rhs) const { return !(*this == rhs); } SingleBitDescriptor::operator int() const { return !!(*bytePtr & (1 << bitPos)); } SingleBitDescriptor::operator bool() const { return !!(*bytePtr & (1 << bitPos)); } BitBufferIterator BitParser::begin() const { return BitBufferIterator(this, 0); } BitBufferIterator BitParser::end() const { return BitBufferIterator(this, lengthInBits); } BitBufferIterator::BitBufferIterator(const BitParser* bptr, size_t bpos) noexcept : bbPtr(bptr), pos(bpos) { } bool BitBufferIterat
random
[ { "content": "\tclass BitBufferIterator {\n\n\tpublic:\n\n\t\tBitBufferIterator(const BitParser* bptr, size_t bpos) noexcept;\n\n\n\n\t\tbool operator!=(BitBufferIterator& other) const;\n\n\t\tSingleBitDescriptor operator*() const;\n\n\t\tBitBufferIterator& operator++();\n\n\tprivate:\n\n\t\tsize_t pos;\n\n\t\t...
C++
qt-creator-opensource-src-4.6.1/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
#include "itemlibraryinfo.h" #include "nodemetainfo.h" #include <QSharedData> #include <utils/fileutils.h> namespace QmlDesigner { namespace Internal { class ItemLibraryEntryData : public QSharedData { public: ItemLibraryEntryData() : majorVersion(-1), minorVersion(-1) { } QString name; TypeName typeName; QString category; int majorVersion; int minorVersion; QString libraryEntryIconPath; QIcon typeIcon; QList<PropertyContainer> properties; QString qml; QString qmlSource; QString requiredImport; QHash<QString, QString> hints; }; } ItemLibraryEntry::ItemLibraryEntry(const ItemLibraryEntry &other) : m_data(other.m_data) { } ItemLibraryEntry& ItemLibraryEntry::operator=(const ItemLibraryEntry &other) { if (this !=&other) m_data = other.m_data; return *this; } void ItemLibraryEntry::setTypeIcon(const QIcon &icon) { m_data->typeIcon = icon; } void ItemLibraryEntry::addProperty(const Property &property) { m_data->properties.append(property); } QList<ItemLibraryEntry::Property> ItemLibraryEntry::properties() const { return m_data->properties; } QHash<QString, QString> ItemLibraryEntry::hints() const { return m_data->hints; } ItemLibraryEntry::ItemLibraryEntry() : m_data(new Internal::ItemLibraryEntryData) { m_data->name.clear(); } ItemLibraryEntry::~ItemLibraryEntry() { } QString ItemLibraryEntry::name() const { return m_data->name; } TypeName ItemLibraryEntry::typeName() const { return m_data->typeName; } QString ItemLibraryEntry::qmlPath() const { return m_data->qml; } QString ItemLibraryEntry::qmlSource() const { return m_data->qmlSource; } QString ItemLibraryEntry::requiredImport() const { return m_data->requiredImport; } int ItemLibraryEntry::majorVersion() const { return m_data->majorVersion; } int ItemLibraryEntry::minorVersion() const { return m_data->minorVersion; } QString ItemLibraryEntry::category() const { return m_data->category; } void ItemLibraryEntry::setCategory(const QString &category) { m_data->category = category; } QIcon ItemLibraryEntry::typeIcon() const { return m_data->typeIcon; } QString ItemLibraryEntry::libraryEntryIconPath() const { return m_data->libraryEntryIconPath; } void ItemLibraryEntry::setName(const QString &name) { m_data->name = name; } void ItemLibraryEntry::setType(const TypeName &typeName, int majorVersion, int minorVersion) { m_data->typeName = typeName; m_data->majorVersion = majorVersion; m_data->minorVersion = minorVersion; } void ItemLibraryEntry::setLibraryEntryIconPath(const QString &iconPath) { m_data->libraryEntryIconPath = iconPath; } static QByteArray getSourceForUrl(const QString &fileURl) { Utils::FileReader fileReader; if (fileReader.fetch(fileURl)) return fileReader.data(); else return Utils::FileReader::fetchQrc(fileURl); } void ItemLibraryEntry::setQmlPath(const QString &qml) { m_data->qml = qml; m_data->qmlSource = QString::fromUtf8(getSourceForUrl(qml)); } void ItemLibraryEntry::setRequiredImport(const QString &requiredImport) { m_data->requiredImport = requiredImport; } void ItemLibraryEntry::addHints(const QHash<QString, QString> &hints) { m_data->hints.unite(hints); } void ItemLibraryEntry::addProperty(PropertyName &name, QString &type, QVariant &value) { Property property; property.set(name, type, value); addProperty(property); } QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry) { stream << itemLibraryEntry.name(); stream << itemLibraryEntry.typeName(); stream << itemLibraryEntry.majorVersion(); stream << itemLibraryEntry.minorVersion(); stream << itemLibraryEntry.typeIcon(); stream << itemLibraryEntry.libraryEntryIconPath(); stream << itemLibraryEntry.category(); stream << itemLibraryEntry.requiredImport(); stream << itemLibraryEntry.hints(); stream << itemLibraryEntry.m_data->properties; stream << itemLibraryEntry.m_data->qml; stream << itemLibraryEntry.m_data->qmlSource; return stream; } QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry) { stream >> itemLibraryEntry.m_data->name; stream >> itemLibraryEntry.m_data->typeName; stream >> itemLibraryEntry.m_data->majorVersion; stream >> itemLibraryEntry.m_data->minorVersion; stream >> itemLibraryEntry.m_data->typeIcon; stream >> itemLibraryEntry.m_data->libraryEntryIconPath; stream >> itemLibraryEntry.m_data->category; stream >> itemLibraryEntry.m_data->requiredImport; stream >> itemLibraryEntry.m_data->hints; stream >> itemLibraryEntry.m_data->properties; stream >> itemLibraryEntry.m_data->qml; stream >> itemLibraryEntry.m_data->qmlSource; return stream; } QDebug operator<<(QDebug debug, const ItemLibraryEntry &itemLibraryEntry) { debug << itemLibraryEntry.m_data->name; debug << itemLibraryEntry.m_data->typeName; debug << itemLibraryEntry.m_data->majorVersion; debug << itemLibraryEntry.m_data->minorVersion; debug << itemLibraryEntry.m_data->typeIcon; debug << itemLibraryEntry.m_data->libraryEntryIconPath; debug << itemLibraryEntry.m_data->category; debug << itemLibraryEntry.m_data->requiredImport; debug << itemLibraryEntry.m_data->hints; debug << itemLibraryEntry.m_data->properties; debug << itemLibraryEntry.m_data->qml; debug << itemLibraryEntry.m_data->qmlSource; return debug.space(); } ItemLibraryInfo::ItemLibraryInfo(QObject *parent) : QObject(parent) { } QList<ItemLibraryEntry> ItemLibraryInfo::entriesForType(const QByteArray &typeName, int majorVersion, int minorVersion) const { QList<ItemLibraryEntry> entries; foreach (const ItemLibraryEntry &entry, m_nameToEntryHash) { if (entry.typeName() == typeName) entries += entry; } if (m_baseInfo) entries += m_baseInfo->entriesForType(typeName, majorVersion, minorVersion); return entries; } ItemLibraryEntry ItemLibraryInfo::entry(const QString &name) const { if (m_nameToEntryHash.contains(name)) return m_nameToEntryHash.value(name); if (m_baseInfo) return m_baseInfo->entry(name); return ItemLibraryEntry(); } QList<ItemLibraryEntry> ItemLibraryInfo::entries() const { QList<ItemLibraryEntry> list = m_nameToEntryHash.values(); if (m_baseInfo) list += m_baseInfo->entries(); return list; } static inline QString keyForEntry(const ItemLibraryEntry &entry) { return entry.name() + entry.category() + QString::number(entry.majorVersion()); } void ItemLibraryInfo::addEntries(const QList<ItemLibraryEntry> &entries, bool overwriteDuplicate) { foreach (const ItemLibraryEntry &entry, entries) { const QString key = keyForEntry(entry); if (!overwriteDuplicate && m_nameToEntryHash.contains(key)) throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__); m_nameToEntryHash.insert(key, entry); } emit entriesChanged(); } bool ItemLibraryInfo::containsEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); return m_nameToEntryHash.contains(key); } void ItemLibraryInfo::clearEntries() { m_nameToEntryHash.clear(); emit entriesChanged(); } QStringList ItemLibraryInfo::blacklistImports() const { auto list = m_blacklistImports; if (m_baseInfo) list.append(m_baseInfo->m_blacklistImports); return list; } QStringList ItemLibraryInfo::showTagsForImports() const { auto list = m_showTagsForImports; if (m_baseInfo) list.append(m_baseInfo->m_showTagsForImports); list.removeDuplicates(); return list; } void ItemLibraryInfo::addBlacklistImports(const QStringList &list) { m_blacklistImports.append(list); } void ItemLibraryInfo::addShowTagsForImports(const QStringList &list) { m_showTagsForImports.append(list); } void ItemLibraryInfo::setBaseInfo(ItemLibraryInfo *baseInfo) { m_baseInfo = baseInfo; } }
#include "itemlibraryinfo.h" #include "nodemetainfo.h" #include <QSharedData> #include <utils/fileutils.h> namespace QmlDesigner { namespace Internal { class ItemLibraryEntryData : public QSharedData { public: ItemLibraryEntryData() : majorVersion(-1), minorVersion(-1) { } QString name; TypeName typeName; QString category; int majorVersion; int minorVersion; QString libraryEntryIconPath; QIcon typeIcon; QList<PropertyContainer> properties; QString qml; QString qmlSource; QString requiredImport; QHash<QString, QString> hints; }; } ItemLibraryEntry::ItemLibraryEntry(const ItemLibraryEntry &other) : m_data(other.m_data) { } ItemLibraryEntry& ItemLibraryEntry::operator=(const ItemLibraryEntry &other) { if (this !=&other) m_data = other.m_data; return *this; } void ItemLibraryEntry::setTypeIcon(const QIcon &icon) { m_data->typeIcon = icon; } void ItemLibraryEntry::addProperty(const Property &property) { m_data->properties.append(property); } QList<ItemLibraryEntry::Property> ItemLibraryEntry::properties() const { return m_data->properties; } QHash<QString, QString> ItemLibraryEntry::hints() const { return m_data->hints; } ItemLibraryEntry::ItemLibraryEntry() : m_data(new Internal::ItemLibraryEntryData) { m_data->name.clear(); } ItemLibraryEntry::~ItemLibraryEntry() { } QString ItemLibraryEntry::name() const { return m_data->name; } TypeName ItemLibraryEntry::typeName() const { return m_data->typeName; } QString ItemLibraryEntry::qmlPath() const { return m_data->qml; } QString ItemLibraryEntry::qmlSource() const { return m_data->qmlSource; } QString ItemLibraryEntry::requiredImport() const { return m_data->requiredImport; } int ItemLibraryEntry::majorVersion() const { return m_data->majorVersion; } int ItemLibraryEntry::minorVersion() const { return m_data->minorVersion; } QString ItemLibraryEntry::category() const { return m_data->category; } void ItemLibraryEntry::setCategory(const QString &category) { m_data->category = category; } QIcon ItemLibraryEntry::typeIcon() const { return m_data->typeIcon; } QString ItemLibraryEntry::libraryEntryIconPath() const { return m_data->libraryEntryIconPath; } void ItemLibraryEntry::setName(const QString &name) { m_data->name = name; } void ItemLibraryEntry::setType(const TypeName &typeName, int majorVersion, int minorVersion) { m_data->typeName = typeName; m_data->majorVersion = majorVersion; m_data->minorVersion = minorVersion; } void ItemLibraryEntry::setLibraryEntryIconPath(const QString &iconPath) { m_data->libraryEntryIconPath = iconPath; } static QByteArray getSourceForUrl(const QString &fileURl) { Utils::FileReader fileReader; if (fileReader.fetch(fileURl)) return fileReader.data(); else return Utils::FileReader::fetchQrc(fileURl); } void ItemLibraryEntry::setQmlPath(const QString &qml) { m_data->qml = qml; m_data->qmlSource = QString::fromUtf8(getSourceForUrl(qml)); } void ItemLibraryEntry::setRequiredImport(const QString &requiredImport) { m_data->requiredImport = requiredImport; } void ItemLibraryEntry::addHints(const QHash<QString, QString> &hints) { m_data->hints.unite(hints); } void ItemLibraryEntry::addProperty(PropertyName &name, QString &type, QVariant &value) { Property property; property.set(name, type, value); addProperty(property); }
QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry) { stream >> itemLibraryEntry.m_data->name; stream >> itemLibraryEntry.m_data->typeName; stream >> itemLibraryEntry.m_data->majorVersion; stream >> itemLibraryEntry.m_data->minorVersion; stream >> itemLibraryEntry.m_data->typeIcon; stream >> itemLibraryEntry.m_data->libraryEntryIconPath; stream >> itemLibraryEntry.m_data->category; stream >> itemLibraryEntry.m_data->requiredImport; stream >> itemLibraryEntry.m_data->hints; stream >> itemLibraryEntry.m_data->properties; stream >> itemLibraryEntry.m_data->qml; stream >> itemLibraryEntry.m_data->qmlSource; return stream; } QDebug operator<<(QDebug debug, const ItemLibraryEntry &itemLibraryEntry) { debug << itemLibraryEntry.m_data->name; debug << itemLibraryEntry.m_data->typeName; debug << itemLibraryEntry.m_data->majorVersion; debug << itemLibraryEntry.m_data->minorVersion; debug << itemLibraryEntry.m_data->typeIcon; debug << itemLibraryEntry.m_data->libraryEntryIconPath; debug << itemLibraryEntry.m_data->category; debug << itemLibraryEntry.m_data->requiredImport; debug << itemLibraryEntry.m_data->hints; debug << itemLibraryEntry.m_data->properties; debug << itemLibraryEntry.m_data->qml; debug << itemLibraryEntry.m_data->qmlSource; return debug.space(); } ItemLibraryInfo::ItemLibraryInfo(QObject *parent) : QObject(parent) { } QList<ItemLibraryEntry> ItemLibraryInfo::entriesForType(const QByteArray &typeName, int majorVersion, int minorVersion) const { QList<ItemLibraryEntry> entries; foreach (const ItemLibraryEntry &entry, m_nameToEntryHash) { if (entry.typeName() == typeName) entries += entry; } if (m_baseInfo) entries += m_baseInfo->entriesForType(typeName, majorVersion, minorVersion); return entries; } ItemLibraryEntry ItemLibraryInfo::entry(const QString &name) const { if (m_nameToEntryHash.contains(name)) return m_nameToEntryHash.value(name); if (m_baseInfo) return m_baseInfo->entry(name); return ItemLibraryEntry(); } QList<ItemLibraryEntry> ItemLibraryInfo::entries() const { QList<ItemLibraryEntry> list = m_nameToEntryHash.values(); if (m_baseInfo) list += m_baseInfo->entries(); return list; } static inline QString keyForEntry(const ItemLibraryEntry &entry) { return entry.name() + entry.category() + QString::number(entry.majorVersion()); } void ItemLibraryInfo::addEntries(const QList<ItemLibraryEntry> &entries, bool overwriteDuplicate) { foreach (const ItemLibraryEntry &entry, entries) { const QString key = keyForEntry(entry); if (!overwriteDuplicate && m_nameToEntryHash.contains(key)) throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__); m_nameToEntryHash.insert(key, entry); } emit entriesChanged(); } bool ItemLibraryInfo::containsEntry(const ItemLibraryEntry &entry) { const QString key = keyForEntry(entry); return m_nameToEntryHash.contains(key); } void ItemLibraryInfo::clearEntries() { m_nameToEntryHash.clear(); emit entriesChanged(); } QStringList ItemLibraryInfo::blacklistImports() const { auto list = m_blacklistImports; if (m_baseInfo) list.append(m_baseInfo->m_blacklistImports); return list; } QStringList ItemLibraryInfo::showTagsForImports() const { auto list = m_showTagsForImports; if (m_baseInfo) list.append(m_baseInfo->m_showTagsForImports); list.removeDuplicates(); return list; } void ItemLibraryInfo::addBlacklistImports(const QStringList &list) { m_blacklistImports.append(list); } void ItemLibraryInfo::addShowTagsForImports(const QStringList &list) { m_showTagsForImports.append(list); } void ItemLibraryInfo::setBaseInfo(ItemLibraryInfo *baseInfo) { m_baseInfo = baseInfo; } }
QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry) { stream << itemLibraryEntry.name(); stream << itemLibraryEntry.typeName(); stream << itemLibraryEntry.majorVersion(); stream << itemLibraryEntry.minorVersion(); stream << itemLibraryEntry.typeIcon(); stream << itemLibraryEntry.libraryEntryIconPath(); stream << itemLibraryEntry.category(); stream << itemLibraryEntry.requiredImport(); stream << itemLibraryEntry.hints(); stream << itemLibraryEntry.m_data->properties; stream << itemLibraryEntry.m_data->qml; stream << itemLibraryEntry.m_data->qmlSource; return stream; }
function_block-full_function
[]
C++
code_reading/oceanbase-master/src/sql/optimizer/ob_log_table_lookup.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
#define USING_LOG_PREFIX SQL_OPT #include "sql/optimizer/ob_log_table_lookup.h" #include "sql/optimizer/ob_log_table_scan.h" #include "sql/optimizer/ob_log_plan.h" using namespace oceanbase::share; namespace oceanbase { namespace sql { int ObLogTableLookup::copy_without_child(ObLogicalOperator*& out) { int ret = OB_SUCCESS; out = NULL; ObLogicalOperator* op = NULL; ObLogTableLookup* table_lookup = NULL; if (OB_FAIL(clone(op))) { LOG_WARN("failed to clone ObLogTableScan", K(ret)); } else if (OB_ISNULL(table_lookup = static_cast<ObLogTableLookup*>(op))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("failed to cast ObLogicalOpertor* to ObLogTableScan*", K(ret)); } else { table_lookup->table_id_ = table_id_; table_lookup->ref_table_id_ = ref_table_id_; table_lookup->index_id_ = index_id_; table_lookup->set_index_name(index_name_); table_lookup->set_table_name(table_name_); table_lookup->set_index_back_scan(index_back_scan_); table_lookup->calc_part_id_expr_ = calc_part_id_expr_; out = table_lookup; } return ret; } int ObLogTableLookup::transmit_op_ordering() { int ret = OB_SUCCESS; reset_op_ordering(); reset_local_ordering(); return ret; } int ObLogTableLookup::allocate_expr_post(ObAllocExprContext& ctx) { int ret = OB_SUCCESS; if (OB_ISNULL(index_back_scan_)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("null point", K(index_back_scan_), K(ret)); } else { index_back_scan_->set_branch_id(branch_id_); index_back_scan_->set_id(id_); if (OB_FAIL(index_back_scan_->allocate_expr_post(ctx))) { LOG_WARN("failed to allocate expr for children operator", K(ret)); } else if (!is_plan_root() && OB_FAIL(append(output_exprs_, index_back_scan_->get_output_exprs()))) { LOG_WARN("failed to append output exprs", K(ret)); } else if (OB_FAIL(append_not_produced_exprs(ctx.not_produced_exprs_))) { LOG_WARN("fail to append not produced exprs", K(ret)); } } return ret; } int ObLogTableLookup::allocate_exchange_post(AllocExchContext* ctx) { int ret = OB_SUCCESS; bool is_basic = false; ObLogicalOperator* child = NULL; ObExchangeInfo exch_info; if (OB_ISNULL(ctx) || OB_ISNULL(child = get_child(first_child))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("get unexpected null", K(ctx), K(child), K(ret)); } else if (OB_FAIL(compute_basic_sharding_info(ctx, is_basic))) { LOG_WARN("failed to check is basic sharing info", K(ret)); } else if (is_basic) { } else if (!get_pushdown_filter_exprs().empty() || child->get_card() > 1000) { if (OB_FAIL(get_sharding_info().copy_with_part_keys(child->get_sharding_info()))) { LOG_WARN("failed to deep copy sharding info from first child", K(ret)); } else { } } else if (OB_FAIL(child->allocate_exchange(ctx, exch_info))) { LOG_WARN("failed to allocate exchange", K(ret)); } else { sharding_info_.set_location_type(OB_TBL_LOCATION_LOCAL); } if (OB_SUCC(ret)) { get_plan()->set_location_type(ObPhyPlanType::OB_PHY_PLAN_UNCERTAIN); } return ret; } int ObLogTableLookup::compute_property(Path* path) { int ret = OB_SUCCESS; if (OB_ISNULL(path) || OB_ISNULL(path->parent_) || OB_UNLIKELY(path->path_type_ != ACCESS)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("path or join order is null", K(ret), K(path)); } else if (OB_FAIL(ObLogicalOperator::compute_property(path))) { LOG_WARN("failed to compute property", K(ret)); } else { set_card(path->parent_->get_output_rows()); set_op_cost(static_cast<const AccessPath*>(path)->index_back_cost_); set_cost(path->cost_); } return ret; } int ObLogTableLookup::re_est_cost(const ObLogicalOperator* parent, double need_row_count, bool& re_est) { int ret = OB_SUCCESS; ObLogicalOperator* child = NULL; ObLogTableScan* scan_child = NULL; double query_range_row_count = 0.0; double index_back_row_count = 0.0; UNUSED(parent); if (need_row_count >= get_card()) { } else if (OB_ISNULL(child = get_child(first_child))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("null children node", K(ret)); } else if (OB_UNLIKELY(log_op_def::LOG_TABLE_SCAN != child->get_type())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("unexpceted child type", K(child->get_type()), K(ret)); } else if (FALSE_IT(scan_child = static_cast<ObLogTableScan*>(child))) { } else if (OB_ISNULL(scan_child->get_est_cost_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("est cost info is not set", K(ret)); } else if (OB_UNLIKELY(scan_child->get_est_cost_info()->table_filter_sel_ <= 0.0 || scan_child->get_est_cost_info()->postfix_filter_sel_ <= 0.0)) { } else { index_back_row_count = need_row_count / scan_child->get_est_cost_info()->table_filter_sel_; query_range_row_count = index_back_row_count / scan_child->get_est_cost_info()->postfix_filter_sel_; if (query_range_row_count < 0.0 || index_back_row_count < 0.0 || scan_child->query_range_row_count_ < OB_DOUBLE_EPSINON) { } else { re_est = true; double cost = 0; double index_back_cost = 0; double physical_query_range_row_count = query_range_row_count * scan_child->phy_query_range_row_count_ / scan_child->query_range_row_count_; LOG_TRACE("start to re-estimate for table look up operator", K(index_back_row_count), K(query_range_row_count), K(physical_query_range_row_count)); if (OB_FAIL(ObOptEstCost::cost_table_one_batch(*scan_child->est_cost_info_, scan_child->est_cost_info_->batch_type_, true, scan_child->est_cost_info_->table_scan_param_.column_ids_.count(), query_range_row_count, physical_query_range_row_count, cost, index_back_cost))) { LOG_WARN("failed to estimate cost", K(ret)); } else { LOG_TRACE("succeed to re-estimate for table lookup operator", K(cost), K(index_back_cost)); scan_child->set_card(index_back_row_count); scan_child->set_cost(cost - index_back_cost); scan_child->set_op_cost(cost - index_back_cost); card_ = need_row_count; op_cost_ = index_back_cost; cost_ = cost; } } } return ret; } uint64_t ObLogTableLookup::hash(uint64_t seed) const { uint64_t hash_value = seed; hash_value = do_hash(table_id_, hash_value); hash_value = do_hash(ref_table_id_, hash_value); hash_value = do_hash(index_id_, hash_value); hash_value = do_hash(table_name_, hash_value); hash_value = do_hash(index_name_, hash_value); hash_value = ObLogicalOperator::hash(hash_value); return hash_value; } int ObLogTableLookup::check_output_dep_specific(ObRawExprCheckDep& checker) { int ret = OB_SUCCESS; UNUSED(checker); return ret; } int ObLogTableLookup::print_my_plan_annotation(char* buf, int64_t& buf_len, int64_t& pos, ExplainType type) { int ret = OB_SUCCESS; UNUSED(type); if (OB_ISNULL(index_back_scan_) || OB_ISNULL(index_back_scan_->get_table_partition_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("get unexpected null", K(index_back_scan_), K(ret)); } else if (OB_FAIL(BUF_PRINTF(", "))) { LOG_WARN("BUF_PRINTF fails", K(ret)); } else if (OB_FAIL(BUF_PRINTF("\n "))) { LOG_WARN("BUF_PRINTF fails", K(ret)); } else { const ObPhyPartitionLocationInfoIArray& partitions = index_back_scan_->table_partition_info_->get_phy_tbl_location_info().get_phy_part_loc_info_list(); const bool two_level = (schema::PARTITION_LEVEL_TWO == index_back_scan_->table_partition_info_->get_part_level()); ObSEArray<int64_t, 128> pids; int64_t N = partitions.count(); for (int64_t i = 0; OB_SUCC(ret) && i < N; ++i) { const ObOptPartLoc& part_loc = partitions.at(i).get_partition_location(); int64_t pid = part_loc.get_partition_id(); if (OB_FAIL(pids.push_back(pid))) { LOG_WARN("failed to add partition id", K(pid), K(i), K(ret)); } else { std::sort(pids.begin(), pids.end(), compare_partition_id); } } if (OB_SUCC(ret)) { if (OB_FAIL(ObLogicalOperator::explain_print_partitions(pids, two_level, buf, buf_len, pos))) { LOG_WARN("Failed to print partitions"); } } } return ret; } int ObLogTableLookup::inner_append_not_produced_exprs(ObRawExprUniqueSet& raw_exprs) const { int ret = OB_SUCCESS; OZ(raw_exprs.append(calc_part_id_expr_)); return ret; } int ObLogTableLookup::init_calc_part_id_expr() { int ret = OB_SUCCESS; calc_part_id_expr_ = NULL; share::schema::ObPartitionLevel part_level = share::schema::PARTITION_LEVEL_MAX; ObSQLSessionInfo* session = NULL; ObRawExpr* part_expr = NULL; ObRawExpr* subpart_expr = NULL; ObRawExpr* new_part_expr = NULL; ObRawExpr* new_subpart_expr = NULL; if (OB_ISNULL(get_plan()) || OB_INVALID_ID == ref_table_id_) { ret = OB_ERR_UNEXPECTED; } else if (OB_ISNULL(session = get_plan()->get_optimizer_context().get_session_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("session info is null"); } else if (!session->use_static_typing_engine()) { } else { share::schema::ObSchemaGetterGuard* schema_guard = NULL; const share::schema::ObTableSchema* table_schema = NULL; if (OB_ISNULL(schema_guard = get_plan()->get_optimizer_context().get_schema_guard())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret)); } else if (OB_FAIL(schema_guard->get_table_schema(ref_table_id_, table_schema))) { LOG_WARN("get table schema failed", K(ref_table_id_), K(ret)); } else if (OB_ISNULL(table_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("table schema is null", K(ret), K(table_schema)); } else { bool no_primary_key = table_schema->is_no_pk_table(); ObRawExprFactory& expr_factory = get_plan()->get_optimizer_context().get_expr_factory(); if (OB_FAIL(get_part_exprs(table_id_, ref_table_id_, part_level, part_expr, subpart_expr))) { LOG_WARN("fail to get part exprs", K(ret)); } new_part_expr = part_expr; new_subpart_expr = subpart_expr; if (OB_SUCC(ret) && !no_primary_key && NULL != part_expr) { if (OB_FAIL(replace_gen_column(part_expr, new_part_expr))) { LOG_WARN("fail to replace generate column", K(ret), K(part_expr)); } } if (OB_SUCC(ret) && !no_primary_key && NULL != subpart_expr) { if (OB_FAIL(replace_gen_column(subpart_expr, new_subpart_expr))) { LOG_WARN("fail to replace generate column", K(ret), K(subpart_expr)); } } if (OB_SUCC(ret)) { if (OB_FAIL(ObRawExprUtils::build_calc_part_id_expr(expr_factory, *session, ref_table_id_, part_level, new_part_expr, new_subpart_expr, calc_part_id_expr_))) { LOG_WARN("fail to build table location expr", K(ret)); } } } } return ret; } int ObLogTableLookup::replace_gen_column(ObRawExpr* part_expr, ObRawExpr*& new_part_expr) { int ret = OB_SUCCESS; ObSEArray<ObRawExpr*, 8> column_exprs; new_part_expr = part_expr; if (OB_ISNULL(part_expr)) { } else if (OB_ISNULL(get_plan())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(ObRawExprUtils::extract_column_exprs(part_expr, column_exprs))) { LOG_WARN("fail to extract column exprs", K(part_expr), K(ret)); } else { bool cnt_gen_columns = false; for (int64_t i = 0; !cnt_gen_columns && OB_SUCC(ret) && i < column_exprs.count(); i++) { if (OB_ISNULL(column_exprs.at(i))) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret)); } else if (static_cast<ObColumnRefRawExpr*>(column_exprs.at(i))->is_generated_column()) { cnt_gen_columns = true; } } if (OB_SUCC(ret) && cnt_gen_columns) { ObRawExprFactory& expr_factory = get_plan()->get_optimizer_context().get_expr_factory(); new_part_expr = NULL; if (OB_FAIL(ObRawExprUtils::copy_expr(expr_factory, part_expr, new_part_expr, COPY_REF_DEFAULT))) { LOG_WARN("fail to copy part expr", K(ret)); } else { for (int64_t i = 0; OB_SUCC(ret) && i < column_exprs.count(); i++) { ObColumnRefRawExpr* col_expr = static_cast<ObColumnRefRawExpr*>(column_exprs.at(i)); if (!col_expr->is_generated_column()) { } else if (OB_ISNULL(col_expr->get_dependant_expr())) { ret = OB_INVALID_ARGUMENT; LOG_WARN("generate column's dependant expr is null", K(ret)); } else if (OB_FAIL( ObRawExprUtils::replace_ref_column(new_part_expr, col_expr, col_expr->get_dependant_expr()))) { LOG_WARN("fail to replace ref column", K(ret)); } } } } } return ret; } } }
#define USING_LOG_PREFIX SQL_OPT #include "sql/optimizer/ob_log_table_lookup.h" #include "sql/optimizer/ob_log_table_scan.h" #include "sql/optimizer/ob_log_plan.h" using namespace oceanbase::share; namespace oceanbase { namespace sql { int ObLogTableLookup::copy_without_child(ObLogicalOperator*& out) { int ret = OB_SUCCESS; out = NULL; ObLogicalOperator* op = NULL; ObLogTableLookup* table_lookup = NULL; if (OB_FAIL(clone(op))) { LOG_WARN("failed to clone ObLogTableScan", K(ret)); } else if (OB_ISNULL(table_lookup = static_cast<ObLogTableLookup*>(op))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("failed to cast ObLogicalOpertor* to ObLogTableScan*", K(ret)); } else { table_lookup->table_id_ = table_id_; table_lookup->ref_table_id_ = ref_table_id_; table_lookup->index_id_ = index_id_; table_lookup->set_index_name(index_name_); table_lookup->set_table_name(table_name_); table_lookup->set_index_back_scan(index_back_scan_); table_lookup->calc_part_id_expr_ = calc_part_id_expr_; out = table_lookup; } retu
bool is_basic = false; ObLogicalOperator* child = NULL; ObExchangeInfo exch_info; if (OB_ISNULL(ctx) || OB_ISNULL(child = get_child(first_child))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("get unexpected null", K(ctx), K(child), K(ret)); } else if (OB_FAIL(compute_basic_sharding_info(ctx, is_basic))) { LOG_WARN("failed to check is basic sharing info", K(ret)); } else if (is_basic) { } else if (!get_pushdown_filter_exprs().empty() || child->get_card() > 1000) { if (OB_FAIL(get_sharding_info().copy_with_part_keys(child->get_sharding_info()))) { LOG_WARN("failed to deep copy sharding info from first child", K(ret)); } else { } } else if (OB_FAIL(child->allocate_exchange(ctx, exch_info))) { LOG_WARN("failed to allocate exchange", K(ret)); } else { sharding_info_.set_location_type(OB_TBL_LOCATION_LOCAL); } if (OB_SUCC(ret)) { get_plan()->set_location_type(ObPhyPlanType::OB_PHY_PLAN_UNCERTAIN); } return ret; } int ObLogTableLookup::compute_property(Path* path) { int ret = OB_SUCCESS; if (OB_ISNULL(path) || OB_ISNULL(path->parent_) || OB_UNLIKELY(path->path_type_ != ACCESS)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("path or join order is null", K(ret), K(path)); } else if (OB_FAIL(ObLogicalOperator::compute_property(path))) { LOG_WARN("failed to compute property", K(ret)); } else { set_card(path->parent_->get_output_rows()); set_op_cost(static_cast<const AccessPath*>(path)->index_back_cost_); set_cost(path->cost_); } return ret; } int ObLogTableLookup::re_est_cost(const ObLogicalOperator* parent, double need_row_count, bool& re_est) { int ret = OB_SUCCESS; ObLogicalOperator* child = NULL; ObLogTableScan* scan_child = NULL; double query_range_row_count = 0.0; double index_back_row_count = 0.0; UNUSED(parent); if (need_row_count >= get_card()) { } else if (OB_ISNULL(child = get_child(first_child))) { ret = OB_ERR_UNEXPECTED; LOG_WARN("null children node", K(ret)); } else if (OB_UNLIKELY(log_op_def::LOG_TABLE_SCAN != child->get_type())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("unexpceted child type", K(child->get_type()), K(ret)); } else if (FALSE_IT(scan_child = static_cast<ObLogTableScan*>(child))) { } else if (OB_ISNULL(scan_child->get_est_cost_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("est cost info is not set", K(ret)); } else if (OB_UNLIKELY(scan_child->get_est_cost_info()->table_filter_sel_ <= 0.0 || scan_child->get_est_cost_info()->postfix_filter_sel_ <= 0.0)) { } else { index_back_row_count = need_row_count / scan_child->get_est_cost_info()->table_filter_sel_; query_range_row_count = index_back_row_count / scan_child->get_est_cost_info()->postfix_filter_sel_; if (query_range_row_count < 0.0 || index_back_row_count < 0.0 || scan_child->query_range_row_count_ < OB_DOUBLE_EPSINON) { } else { re_est = true; double cost = 0; double index_back_cost = 0; double physical_query_range_row_count = query_range_row_count * scan_child->phy_query_range_row_count_ / scan_child->query_range_row_count_; LOG_TRACE("start to re-estimate for table look up operator", K(index_back_row_count), K(query_range_row_count), K(physical_query_range_row_count)); if (OB_FAIL(ObOptEstCost::cost_table_one_batch(*scan_child->est_cost_info_, scan_child->est_cost_info_->batch_type_, true, scan_child->est_cost_info_->table_scan_param_.column_ids_.count(), query_range_row_count, physical_query_range_row_count, cost, index_back_cost))) { LOG_WARN("failed to estimate cost", K(ret)); } else { LOG_TRACE("succeed to re-estimate for table lookup operator", K(cost), K(index_back_cost)); scan_child->set_card(index_back_row_count); scan_child->set_cost(cost - index_back_cost); scan_child->set_op_cost(cost - index_back_cost); card_ = need_row_count; op_cost_ = index_back_cost; cost_ = cost; } } } return ret; } uint64_t ObLogTableLookup::hash(uint64_t seed) const { uint64_t hash_value = seed; hash_value = do_hash(table_id_, hash_value); hash_value = do_hash(ref_table_id_, hash_value); hash_value = do_hash(index_id_, hash_value); hash_value = do_hash(table_name_, hash_value); hash_value = do_hash(index_name_, hash_value); hash_value = ObLogicalOperator::hash(hash_value); return hash_value; } int ObLogTableLookup::check_output_dep_specific(ObRawExprCheckDep& checker) { int ret = OB_SUCCESS; UNUSED(checker); return ret; } int ObLogTableLookup::print_my_plan_annotation(char* buf, int64_t& buf_len, int64_t& pos, ExplainType type) { int ret = OB_SUCCESS; UNUSED(type); if (OB_ISNULL(index_back_scan_) || OB_ISNULL(index_back_scan_->get_table_partition_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("get unexpected null", K(index_back_scan_), K(ret)); } else if (OB_FAIL(BUF_PRINTF(", "))) { LOG_WARN("BUF_PRINTF fails", K(ret)); } else if (OB_FAIL(BUF_PRINTF("\n "))) { LOG_WARN("BUF_PRINTF fails", K(ret)); } else { const ObPhyPartitionLocationInfoIArray& partitions = index_back_scan_->table_partition_info_->get_phy_tbl_location_info().get_phy_part_loc_info_list(); const bool two_level = (schema::PARTITION_LEVEL_TWO == index_back_scan_->table_partition_info_->get_part_level()); ObSEArray<int64_t, 128> pids; int64_t N = partitions.count(); for (int64_t i = 0; OB_SUCC(ret) && i < N; ++i) { const ObOptPartLoc& part_loc = partitions.at(i).get_partition_location(); int64_t pid = part_loc.get_partition_id(); if (OB_FAIL(pids.push_back(pid))) { LOG_WARN("failed to add partition id", K(pid), K(i), K(ret)); } else { std::sort(pids.begin(), pids.end(), compare_partition_id); } } if (OB_SUCC(ret)) { if (OB_FAIL(ObLogicalOperator::explain_print_partitions(pids, two_level, buf, buf_len, pos))) { LOG_WARN("Failed to print partitions"); } } } return ret; } int ObLogTableLookup::inner_append_not_produced_exprs(ObRawExprUniqueSet& raw_exprs) const { int ret = OB_SUCCESS; OZ(raw_exprs.append(calc_part_id_expr_)); return ret; } int ObLogTableLookup::init_calc_part_id_expr() { int ret = OB_SUCCESS; calc_part_id_expr_ = NULL; share::schema::ObPartitionLevel part_level = share::schema::PARTITION_LEVEL_MAX; ObSQLSessionInfo* session = NULL; ObRawExpr* part_expr = NULL; ObRawExpr* subpart_expr = NULL; ObRawExpr* new_part_expr = NULL; ObRawExpr* new_subpart_expr = NULL; if (OB_ISNULL(get_plan()) || OB_INVALID_ID == ref_table_id_) { ret = OB_ERR_UNEXPECTED; } else if (OB_ISNULL(session = get_plan()->get_optimizer_context().get_session_info())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("session info is null"); } else if (!session->use_static_typing_engine()) { } else { share::schema::ObSchemaGetterGuard* schema_guard = NULL; const share::schema::ObTableSchema* table_schema = NULL; if (OB_ISNULL(schema_guard = get_plan()->get_optimizer_context().get_schema_guard())) { ret = OB_ERR_UNEXPECTED; LOG_WARN("NULL ptr", K(ret)); } else if (OB_FAIL(schema_guard->get_table_schema(ref_table_id_, table_schema))) { LOG_WARN("get table schema failed", K(ref_table_id_), K(ret)); } else if (OB_ISNULL(table_schema)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("table schema is null", K(ret), K(table_schema)); } else { bool no_primary_key = table_schema->is_no_pk_table(); ObRawExprFactory& expr_factory = get_plan()->get_optimizer_context().get_expr_factory(); if (OB_FAIL(get_part_exprs(table_id_, ref_table_id_, part_level, part_expr, subpart_expr))) { LOG_WARN("fail to get part exprs", K(ret)); } new_part_expr = part_expr; new_subpart_expr = subpart_expr; if (OB_SUCC(ret) && !no_primary_key && NULL != part_expr) { if (OB_FAIL(replace_gen_column(part_expr, new_part_expr))) { LOG_WARN("fail to replace generate column", K(ret), K(part_expr)); } } if (OB_SUCC(ret) && !no_primary_key && NULL != subpart_expr) { if (OB_FAIL(replace_gen_column(subpart_expr, new_subpart_expr))) { LOG_WARN("fail to replace generate column", K(ret), K(subpart_expr)); } } if (OB_SUCC(ret)) { if (OB_FAIL(ObRawExprUtils::build_calc_part_id_expr(expr_factory, *session, ref_table_id_, part_level, new_part_expr, new_subpart_expr, calc_part_id_expr_))) { LOG_WARN("fail to build table location expr", K(ret)); } } } } return ret; } int ObLogTableLookup::replace_gen_column(ObRawExpr* part_expr, ObRawExpr*& new_part_expr) { int ret = OB_SUCCESS; ObSEArray<ObRawExpr*, 8> column_exprs; new_part_expr = part_expr; if (OB_ISNULL(part_expr)) { } else if (OB_ISNULL(get_plan())) { ret = OB_ERR_UNEXPECTED; } else if (OB_FAIL(ObRawExprUtils::extract_column_exprs(part_expr, column_exprs))) { LOG_WARN("fail to extract column exprs", K(part_expr), K(ret)); } else { bool cnt_gen_columns = false; for (int64_t i = 0; !cnt_gen_columns && OB_SUCC(ret) && i < column_exprs.count(); i++) { if (OB_ISNULL(column_exprs.at(i))) { ret = OB_INVALID_ARGUMENT; LOG_WARN("invalid argument", K(ret)); } else if (static_cast<ObColumnRefRawExpr*>(column_exprs.at(i))->is_generated_column()) { cnt_gen_columns = true; } } if (OB_SUCC(ret) && cnt_gen_columns) { ObRawExprFactory& expr_factory = get_plan()->get_optimizer_context().get_expr_factory(); new_part_expr = NULL; if (OB_FAIL(ObRawExprUtils::copy_expr(expr_factory, part_expr, new_part_expr, COPY_REF_DEFAULT))) { LOG_WARN("fail to copy part expr", K(ret)); } else { for (int64_t i = 0; OB_SUCC(ret) && i < column_exprs.count(); i++) { ObColumnRefRawExpr* col_expr = static_cast<ObColumnRefRawExpr*>(column_exprs.at(i)); if (!col_expr->is_generated_column()) { } else if (OB_ISNULL(col_expr->get_dependant_expr())) { ret = OB_INVALID_ARGUMENT; LOG_WARN("generate column's dependant expr is null", K(ret)); } else if (OB_FAIL( ObRawExprUtils::replace_ref_column(new_part_expr, col_expr, col_expr->get_dependant_expr()))) { LOG_WARN("fail to replace ref column", K(ret)); } } } } } return ret; } } }
rn ret; } int ObLogTableLookup::transmit_op_ordering() { int ret = OB_SUCCESS; reset_op_ordering(); reset_local_ordering(); return ret; } int ObLogTableLookup::allocate_expr_post(ObAllocExprContext& ctx) { int ret = OB_SUCCESS; if (OB_ISNULL(index_back_scan_)) { ret = OB_INVALID_ARGUMENT; LOG_WARN("null point", K(index_back_scan_), K(ret)); } else { index_back_scan_->set_branch_id(branch_id_); index_back_scan_->set_id(id_); if (OB_FAIL(index_back_scan_->allocate_expr_post(ctx))) { LOG_WARN("failed to allocate expr for children operator", K(ret)); } else if (!is_plan_root() && OB_FAIL(append(output_exprs_, index_back_scan_->get_output_exprs()))) { LOG_WARN("failed to append output exprs", K(ret)); } else if (OB_FAIL(append_not_produced_exprs(ctx.not_produced_exprs_))) { LOG_WARN("fail to append not produced exprs", K(ret)); } } return ret; } int ObLogTableLookup::allocate_exchange_post(AllocExchContext* ctx) { int ret = OB_SUCCESS;
random
[]
C++
Servable/DlibServable/test/TestDlibServable.cpp
bzcheeseman/BatchingRPCServer
d1130720fef6e15e129fa59cc37235537f609e36
#include <dlib/data_io.h> #include <sstream> #include "BatchingRPC.pb.h" #include "DlibServable.hpp" #include "gtest/gtest.h" namespace { using namespace dlib; using net_type = loss_multiclass_log<fc< 10, relu<fc< 84, relu<fc< 120, max_pool<2, 2, 2, 2, relu<con<16, 5, 5, 1, 1, max_pool<2, 2, 2, 2, relu<con<6, 5, 5, 1, 1, input<matrix< unsigned char>>>>>>>>>>>>>>; Serving::TensorMessage ToMessage(std::vector<matrix<unsigned char>> &&arr) { Serving::TensorMessage message; std::ostringstream buffer_stream(std::ios::binary); serialize(arr, buffer_stream); message.set_serialized_buffer(buffer_stream.str()); message.set_n(arr.size()); return message; } void TrainNetwork(const std::string &dirname) { std::vector<matrix<unsigned char>> training_images; std::vector<unsigned long> training_labels; std::vector<matrix<unsigned char>> testing_images; std::vector<unsigned long> testing_labels; load_mnist_dataset(dirname, training_images, training_labels, testing_images, testing_labels); std::ifstream f( "../../../Servable/DlibServable/test/assets/mnist_network.dat"); if (f.is_open()) { f.close(); return; } net_type net; dnn_trainer<net_type> trainer(net); trainer.set_learning_rate(0.01); trainer.set_min_learning_rate(0.0001); trainer.set_mini_batch_size(128); trainer.be_verbose(); trainer.set_synchronization_file("mnist_sync", std::chrono::seconds(20)); trainer.train(training_images, training_labels); net.clean(); serialize("../../../Servable/DlibServable/test/assets/mnist_network.dat") << net; } class TestDlibServable : public ::testing::Test { protected: void SetUp() override { TrainNetwork("../../../Servable/DlibServable/test/assets"); deserialize( "../../../Servable/DlibServable/test/assets/mnist_network.dat") >> raw_args.net; file_args.filename = "../../../Servable/DlibServable/test/assets/mnist_network.dat"; std::vector<matrix<unsigned char>> training_images; std::vector<unsigned long> training_labels; load_mnist_dataset("../../../Servable/DlibServable/test/assets", training_images, training_labels, input_, output_); } Serving::DlibRawBindArgs<net_type> raw_args; Serving::DlibFileBindArgs file_args; std::vector<matrix<unsigned char>> input_; std::vector<unsigned long> output_; }; TEST_F(TestDlibServable, Bind) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(4); EXPECT_NO_THROW(servable.Bind(raw_args)); } TEST_F(TestDlibServable, BindFile) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(4); EXPECT_NO_THROW(servable.Bind(file_args)); } TEST_F(TestDlibServable, Single) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0]}); msg.set_client_id("test"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::OK); Serving::TensorMessage output; r = servable.GetResult("test", &output); EXPECT_EQ(r, Serving::ReturnCodes::OK); std::istringstream output_buffer(output.serialized_buffer(), std::ios::binary); std::vector<unsigned long> results; deserialize(results, output_buffer); EXPECT_EQ(results[0], 7); } TEST_F(TestDlibServable, NoBind) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); Serving::TensorMessage msg = ToMessage({input_[0]}); msg.set_client_id("no_bind"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::NEED_BIND_CALL); } TEST_F(TestDlibServable, WrongSize) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(2); servable.Bind(raw_args); Serving::TensorMessage msg; std::ostringstream buffer_stream(std::ios::binary); std::vector<matrix<unsigned char>> arr; arr.push_back(input_[0]); serialize(arr, buffer_stream); msg.set_serialized_buffer(buffer_stream.str()); msg.set_n(2); msg.set_client_id("wrong_size"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::SHAPE_INCORRECT); } TEST_F(TestDlibServable, TooBig) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::BATCH_TOO_LARGE); } TEST_F(TestDlibServable, NextBatch) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(3); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::OK); msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::NEXT_BATCH); } }
#include <dlib/data_io.h> #include <sstream> #include "BatchingRPC.pb.h" #include "DlibServable.hpp" #include "gtest/gtest.h" namespace { using namespace dlib; using net_type = loss_multiclass_log<fc< 10, relu<fc< 84, relu<fc< 120, max_pool<2, 2, 2, 2, relu<con<16, 5, 5, 1, 1, max_pool<2, 2, 2, 2, relu<con<6, 5, 5, 1, 1, input<matrix< unsigned char>>>>>>>>>>>>>>; Serving::TensorMessage ToMessage(std::vector<matrix<unsigned char>> &&arr) { Serving::TensorMessage message; std::ostringstream buffer_stream(std::ios::binary); serialize(arr, buffer_stream); message.set_serialized_buffer(buffer_stream.str()); message.set_n(arr.size()); return message; } void TrainNetwork(const std::string &dirname) { std::vector<matrix<unsigned char>> training_images; std::vector<unsigned long> training_labels; std::vector<matrix<unsigned char>> testing_images; std::vector<unsigned long> testing_labels; load_mnist_dataset(dirname, training_images, training_labels, testing_images, testing_labels); std::ifstream f( "../../../Servable/DlibServable/test/assets/mnist_network.dat"); if (f.is_open()) { f.close(); return; } net_type net; dnn_trainer<net_type> trainer(net); trainer.set_learning_rate(0.01); trainer.set_min_learning_rate(0.0001); trainer.set_mini_batch_size(128); trainer.be_verbose(); trainer.set_synchronization_file("mnist_sync", std::chrono::seconds(20)); trainer.train(training_images, training_labels); net.clean(); serialize("../../../Servable/DlibServable/test/assets/mnist_network.dat") << net; } class TestDlibServable : public ::testing::Test { protected: void SetUp() override { TrainNetwork("../../../Servable/DlibServable/test/assets"); deserialize( "../../../Servable/DlibServable/test/assets/mnist_network.dat") >> raw_args.net; file_args.filename = "../../../Servable/DlibServable/test/assets/mnist_network.dat"; std::vector<matrix<unsigned char>> training_images; std::vector<unsigned long> training_labels; load_mnist_dataset("../../../Servable/DlibServable/test/assets", training_images, training_labels, input_, output_); } Serving::DlibRawBindArgs<net_type> raw_args; Serving::DlibFileBindArgs file_args; std::vector<matrix<unsigned char>> input_; std::vector<unsigned long> output_; }; TEST_F(TestDlibServable, Bind) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(4); EXPECT_NO_THROW(servable.Bind(raw_args)); } TEST_F(TestDlibServable, BindFile) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(4); EXPECT_NO_THROW(servable.Bind(file_args)); } TEST_F(TestDlibServable, Single) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0]}); msg.set_client_id("test"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::OK); Serving::TensorMessage output; r = servable.GetResult("test", &output); EXPECT_EQ(r, Serving::ReturnCodes::OK); std::istringstream output_buffer(output.serialized_buffer(), std::ios::binary); std::vector<unsigned long> results; deserialize(results, output_buffer); EXPECT_EQ(results[0], 7); } TEST_F(TestDlibServable, NoBind) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); Serving::TensorMessage msg = ToMessage({input_[0]}); msg.set_client_id("no_bind"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::NEED_BIND_CALL); } TEST_F(TestDlibServable, WrongSize) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(2); servable.Bind(raw_args); Serving::TensorMessage msg; std::ostringstream buffer_stream(std::ios::binary); std::vector<matrix<unsigned char>> arr; arr.push_back(input_[0]); serialize(arr, buffer_stream); msg.set_serialized_buffer(buffer_stream.str()); msg.set_n(2); msg.set_client_id("wrong_size"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::SHAPE_INCORRECT); } TEST_F(TestDlibServable, TooBig) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(1); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::BATCH_TOO_LARGE); }
}
TEST_F(TestDlibServable, NextBatch) { Serving::DlibServable<net_type, matrix<unsigned char>, unsigned long> servable(3); servable.Bind(raw_args); Serving::TensorMessage msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); Serving::ReturnCodes r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::OK); msg = ToMessage({input_[0], input_[1]}); msg.set_client_id("too_big"); r = servable.AddToBatch(msg); EXPECT_EQ(r, Serving::ReturnCodes::NEXT_BATCH); }
function_block-full_function
[ { "content": "class DlibServable : public Servable {\n\npublic:\n\n DlibServable(const int &batch_size);\n\n ~DlibServable() override;\n\n\n\n ReturnCodes SetBatchSize(const int &new_size) override;\n\n\n\n ReturnCodes AddToBatch(const TensorMessage &message) override;\n\n\n\n ReturnCodes GetResult(const s...
C++
src/plugins/algorithms/lda.cpp
kmoham6/phylanx
252fa5fbb84acaf6f999410e6823b9f8d6693213
#include <phylanx/config.hpp> #include <phylanx/plugins/algorithms/lda.hpp> #include <hpx/iostream.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/util.hpp> #include <hpx/errors/throw_exception.hpp> #include <cstddef> #include <cstdint> #include <iostream> #include <memory> #include <numeric> #include <string> #include <utility> #include <vector> #include <blaze/Math.h> namespace phylanx { namespace execution_tree { namespace primitives { match_pattern_type const lda_trainer::match_data = {hpx::make_tuple("lda_trainer", std::vector<std::string>{ "lda_trainer(_1, _2, _3, _4, _5)"}, &create_lda_trainer, &create_primitive<lda_trainer>, "n_topics, alpha, beta, iters, word_doc_matrix\n" "Args:\n" "\n" " n_topics (integer): number of topics to compute\n" " alpha (float): alpha parameter\n" " beta (float): beta parameter\n" " iters (integer): the number of iterations\n" " word_doc_matrix (2x2 matrix float): word-document histogram,\n" " words are columns, documents are rows\n" "\n" "Returns:\n" "\n" "The algorithm returns a list of two matrices:\n" " [word_topic, document_topic] :\n" "\n" "word_topic: document-topic assignment matrix\n" "document_topic: document-topic assignment matrix\n" "\n" )}; lda_trainer::lda_trainer(primitive_arguments_type && operands, std::string const& name, std::string const& codename) : primitive_component_base(std::move(operands), name, codename) { } primitive_argument_type lda_trainer::calculate_lda_trainer( primitive_arguments_type && args) const { auto arg1 = extract_numeric_value(args[0], name_, codename_); if (arg1.num_dimensions() != 2) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the first " "argument ('n_topics') to represent a matrix")); } auto topics = arg1.scalar(); auto arg2 = extract_numeric_value(args[1], name_, codename_); if (arg2.num_dimensions() != 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('alpha') to represent a scalar")); } auto alpha = arg2.scalar(); auto arg3 = extract_numeric_value(args[2], name_, codename_); if (arg3.num_dimensions() != 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('beta') to represent a scalar")); } auto beta = arg3.scalar(); auto iterations = extract_scalar_integer_value(args[3], name_, codename_); using namespace execution_tree; auto arg5 = extract_numeric_value(args[4], name_, codename_); if (arg5.num_dimensions() > 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('word_doc_mat') to represent a matrix")); } auto word_doc_mat = arg5.matrix(); using lda_trainer_t = phylanx::execution_tree::primitives::lda_trainer_impl; lda_trainer_t trainer(alpha, beta); auto result = trainer(word_doc_mat, topics, iterations); return primitive_argument_type { primitive_arguments_type{ ir::node_data<double>{std::move(std::get<0>(result))}, ir::node_data<double>{std::move(std::get<1>(result))} } }; } hpx::future<primitive_argument_type> lda_trainer::eval( primitive_arguments_type const& operands, primitive_arguments_type const& args) const { if (operands.size() != 5) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message("the lda_trainer algorithm primitive " "requires exactly " "five operands")); } bool arguments_valid = true; for (std::size_t i = 0; i != operands.size(); ++i) { if (!valid(operands[i])) { arguments_valid = false; } } if (!arguments_valid) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires that the " "arguments given by the operands array are valid")); } auto this_ = this->shared_from_this(); return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping( [this_ = std::move(this_)](primitive_arguments_type&& args) -> primitive_argument_type { return this_->calculate_lda_trainer(std::move(args)); }), detail::map_operands( operands, functional::value_operand{}, args, name_, codename_)); } }}}
#include <phylanx/config.hpp> #include <phylanx/plugins/algorithms/lda.hpp> #include <hpx/iostream.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/util.hpp> #include <hpx/errors/throw_exception.hpp> #include <cstddef> #include <cstdint> #include <iostream> #include <memory> #include <numeric> #include <string> #include <utility> #include <vector> #include <blaze/Math.h> namespace phylanx { namespace execution_tree { namespace primitives { match_pattern_type const lda_trainer::match_data = {hpx::make_tuple("lda_trainer", std::vector<std::string>{ "lda_trainer(_1, _2, _3, _4, _5)"}, &create_lda_trainer, &create_primitive<lda_trainer>, "n_topics, alpha, beta, iters, word_doc_matrix\n" "Args:\n" "\n" " n_topics (integer): number of topics to compute\n" " alpha (float): alpha parameter\n" " beta (float): beta parameter\n" " iters (integer): the number of iterations\n" " word_doc_matrix (2x2 matrix float): word-document histogram,\n" " words are columns, documents are rows\n" "\n" "Returns:\n" "\n" "The algorithm returns a li
d_doc_mat') to represent a matrix")); } auto word_doc_mat = arg5.matrix(); using lda_trainer_t = phylanx::execution_tree::primitives::lda_trainer_impl; lda_trainer_t trainer(alpha, beta); auto result = trainer(word_doc_mat, topics, iterations); return primitive_argument_type { primitive_arguments_type{ ir::node_data<double>{std::move(std::get<0>(result))}, ir::node_data<double>{std::move(std::get<1>(result))} } }; } hpx::future<primitive_argument_type> lda_trainer::eval( primitive_arguments_type const& operands, primitive_arguments_type const& args) const { if (operands.size() != 5) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message("the lda_trainer algorithm primitive " "requires exactly " "five operands")); } bool arguments_valid = true; for (std::size_t i = 0; i != operands.size(); ++i) { if (!valid(operands[i])) { arguments_valid = false; } } if (!arguments_valid) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires that the " "arguments given by the operands array are valid")); } auto this_ = this->shared_from_this(); return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping( [this_ = std::move(this_)](primitive_arguments_type&& args) -> primitive_argument_type { return this_->calculate_lda_trainer(std::move(args)); }), detail::map_operands( operands, functional::value_operand{}, args, name_, codename_)); } }}}
st of two matrices:\n" " [word_topic, document_topic] :\n" "\n" "word_topic: document-topic assignment matrix\n" "document_topic: document-topic assignment matrix\n" "\n" )}; lda_trainer::lda_trainer(primitive_arguments_type && operands, std::string const& name, std::string const& codename) : primitive_component_base(std::move(operands), name, codename) { } primitive_argument_type lda_trainer::calculate_lda_trainer( primitive_arguments_type && args) const { auto arg1 = extract_numeric_value(args[0], name_, codename_); if (arg1.num_dimensions() != 2) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the first " "argument ('n_topics') to represent a matrix")); } auto topics = arg1.scalar(); auto arg2 = extract_numeric_value(args[1], name_, codename_); if (arg2.num_dimensions() != 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('alpha') to represent a scalar")); } auto alpha = arg2.scalar(); auto arg3 = extract_numeric_value(args[2], name_, codename_); if (arg3.num_dimensions() != 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('beta') to represent a scalar")); } auto beta = arg3.scalar(); auto iterations = extract_scalar_integer_value(args[3], name_, codename_); using namespace execution_tree; auto arg5 = extract_numeric_value(args[4], name_, codename_); if (arg5.num_dimensions() > 0) { HPX_THROW_EXCEPTION(hpx::bad_parameter, "lda_trainer::eval", generate_error_message( "the lda_trainer algorithm primitive requires for the second " "argument ('wor
random
[ { "content": " class matrix_column_iterator\n\n : public hpx::util::iterator_facade<matrix_column_iterator<T>,\n\n blaze::Column<T>, std::random_access_iterator_tag, blaze::Column<T>>\n\n {\n\n public:\n\n explicit matrix_column_iterator(T& t, const std::size_t index = 0)\n\n ...
C++
src/backend/gporca/libgpopt/src/search/CJobGroupOptimization.cpp
Viocalpan/gpdb
3cf72f6cbed32cc5e5aeea645beeb4c82db9ac1a
#include "gpopt/engine/CEngine.h" #include "gpopt/search/CGroup.h" #include "gpopt/search/CGroupExpression.h" #include "gpopt/search/CGroupProxy.h" #include "gpopt/search/CJobFactory.h" #include "gpopt/search/CJobGroupImplementation.h" #include "gpopt/search/CJobGroupOptimization.h" #include "gpopt/search/CJobGroupExpressionOptimization.h" #include "gpopt/search/CJobQueue.h" #include "gpopt/search/CSchedulerContext.h" #include "gpopt/search/CScheduler.h" #include "naucrates/traceflags/traceflags.h" using namespace gpopt; const CJobGroupOptimization::EEvent rgeev[CJobGroupOptimization::estSentinel] [CJobGroupOptimization::estSentinel] = { { CJobGroupOptimization::eevImplementing, CJobGroupOptimization::eevImplemented, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimized}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimizing, CJobGroupOptimization::eevOptimizedCurrentLevel, CJobGroupOptimization::eevSentinel}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimizing, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimized}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel}, }; #ifdef GPOS_DEBUG const WCHAR rgwszStates[CJobGroupOptimization::estSentinel][GPOPT_FSM_NAME_LENGTH] = { GPOS_WSZ_LIT("initialized"), GPOS_WSZ_LIT("optimizing children"), GPOS_WSZ_LIT("damping optimization level"), GPOS_WSZ_LIT("completed")}; const WCHAR rgwszEvents[CJobGroupOptimization::eevSentinel] [GPOPT_FSM_NAME_LENGTH] = { GPOS_WSZ_LIT("ongoing implementation"), GPOS_WSZ_LIT("done implementation"), GPOS_WSZ_LIT("ongoing optimization"), GPOS_WSZ_LIT("optimization level complete"), GPOS_WSZ_LIT("finalizing")}; #endif CJobGroupOptimization::CJobGroupOptimization() = default; CJobGroupOptimization::~CJobGroupOptimization() = default; void CJobGroupOptimization::Init( CGroup *pgroup, CGroupExpression *pgexprOrigin, COptimizationContext *poc) { GPOS_ASSERT(NULL != poc); GPOS_ASSERT(pgroup == poc->Pgroup()); CJobGroup::Init(pgroup); m_jsm.Init(rgeev #ifdef GPOS_DEBUG , rgwszStates, rgwszEvents #endif ); m_jsm.SetAction(estInitialized, EevtStartOptimization); m_jsm.SetAction(estOptimizingChildren, EevtOptimizeChildren); m_jsm.SetAction(estDampingOptimizationLevel, EevtCompleteOptimization); m_pgexprOrigin = pgexprOrigin; m_poc = m_pgroup->PocInsert(poc); if (poc == m_poc) { m_poc->AddRef(); } SetJobQueue(m_poc->PjqOptimization()); m_eolCurrent = EolLow; CJob::SetInit(); } BOOL CJobGroupOptimization::FScheduleGroupExpressions(CSchedulerContext *psc) { CGroupExpression *pgexprLast = m_pgexprLastScheduled; CGroupExpression *pgexpr = PgexprFirstUnsched(); while (NULL != pgexpr) { if (psc->Peng()->FOptimizeChild(m_pgexprOrigin, pgexpr, m_poc, EolCurrent())) { const ULONG ulOptRequests = CPhysical::PopConvert(pgexpr->Pop())->UlOptRequests(); for (ULONG ul = 0; ul < ulOptRequests; ul++) { CJobGroupExpressionOptimization::ScheduleJob(psc, pgexpr, m_poc, ul, this); } } pgexprLast = pgexpr; { CGroupProxy gp(m_pgroup); pgexpr = gp.PgexprSkipLogical(pgexpr); } } BOOL fNewJobs = (m_pgexprLastScheduled != pgexprLast); m_pgexprLastScheduled = pgexprLast; return fNewJobs; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtStartOptimization(CSchedulerContext *psc, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); CGroup *pgroup = pjgo->m_pgroup; GPOS_ASSERT(COptimizationContext::estUnoptimized == pjgo->m_poc->Est() && "Group is already optimized under this context"); if (!pgroup->FImplemented()) { CJobGroupImplementation::ScheduleJob(psc, pgroup, pjgo); return eevImplementing; } pjgo->m_poc->SetState(COptimizationContext::estOptimizing); if (psc->Peng()->FRoot(pgroup)) { psc->Pjf()->Truncate(EjtGroupImplementation); psc->Pjf()->Truncate(EjtGroupExpressionImplementation); } pjgo->m_eolCurrent = pgroup->EolMax(); return eevImplemented; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtOptimizeChildren(CSchedulerContext *psc, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); if (pjgo->FScheduleGroupExpressions(psc)) { return eevOptimizing; } return eevOptimizedCurrentLevel; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtCompleteOptimization(CSchedulerContext *, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); pjgo->DampOptimizationLevel(); if (EolSentinel != pjgo->EolCurrent()) { pjgo->m_pgexprLastScheduled = NULL; return eevOptimizing; } pjgo->m_poc->SetState(COptimizationContext::estOptimized); return eevOptimized; } BOOL CJobGroupOptimization::FExecute(CSchedulerContext *psc) { GPOS_ASSERT(FInit()); return m_jsm.FRun(psc, this); } void CJobGroupOptimization::ScheduleJob(CSchedulerContext *psc, CGroup *pgroup, CGroupExpression *pgexprOrigin, COptimizationContext *poc, CJob *pjParent) { CJob *pj = psc->Pjf()->PjCreate(CJob::EjtGroupOptimization); CJobGroupOptimization *pjgo = PjConvert(pj); pjgo->Init(pgroup, pgexprOrigin, poc); psc->Psched()->Add(pjgo, pjParent); } #ifdef GPOS_DEBUG IOstream & CJobGroupOptimization::OsPrint(IOstream &os) { return m_jsm.OsHistory(os); } #endif
#include "gpopt/engine/CEngine.h" #include "gpopt/search/CGroup.h" #include "gpopt/search/CGroupExpression.h" #include "gpopt/search/CGroupProxy.h" #include "gpopt/search/CJobFactory.h" #include "gpopt/search/CJobGroupImplementation.h" #include "gpopt/search/CJobGroupOptimization.h" #include "gpopt/search/CJobGroupExpressionOptimization.h" #include "gpopt/search/CJobQueue.h" #include "gpopt/search/CSchedulerContext.h" #include "gpopt/search/CScheduler.h" #include "naucrates/traceflags/traceflags.h" using namespace gpopt; const CJobGroupOptimization::EEvent rgeev[CJobGroupOptimization::estSentinel] [CJobGroupOptimization::estSentinel] = { { CJobGroupOptimization::eevImplementing, CJobGroupOptimization::eevImplemented, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimized}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimizing, CJobGroupOptimization::eevOptimizedCurrentLevel, CJobGroupOptimization::eevSentinel}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimizing, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevOptimized}, { CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel, CJobGroupOptimization::eevSentinel}, }; #ifdef GPOS_DEBUG const WCHAR rgwszStates[CJobGroupOptimization::estSentinel][GPOPT_FSM_NAME_LENGTH] = { GPOS_WSZ_LIT("initialized"), GPOS_WSZ_LIT("optimizing children"), GPOS_WSZ_LIT("damping optimization level"), GPOS_WSZ_LIT("completed")}; const WCHAR rgwszEvents[CJobGroupOptimization::eevSentinel] [GPOPT_FSM_NAME_LENGTH] = { GPOS_WSZ_LIT("ongoing implementation"), GPOS_WSZ_LIT("done implementation"), GPOS_WSZ_LIT("ongoing optimization"), GPOS_WSZ_LIT("optimization level complete"), GPOS_WSZ_LIT("finalizing")}; #endif CJobGroupOptimization::CJobGroupOptimization() = default; CJobGroupOptimization::~CJobGroupOptimization() = default; void CJobGroupOptimization::Init( CGroup *pgroup, CGroupExpression *pgexprOrigin, COptimizationContext *poc) { GPOS_ASSERT(NULL != poc); GPOS_ASSERT(pgroup == poc->Pgroup()); CJobGroup::Init(pgroup); m_jsm.Init(rgeev #ifdef GPOS_DEBUG , rgwszStates, rgwszEvents #endif ); m_jsm.SetAction(estInitialized, EevtStartOptimization); m_jsm.SetAction(estOptimizingChildren, EevtOptimizeChildren); m_jsm.SetAction(estDampingOptimizationLevel, EevtCompleteOptimization); m_pgex
ed; CGroupExpression *pgexpr = PgexprFirstUnsched(); while (NULL != pgexpr) { if (psc->Peng()->FOptimizeChild(m_pgexprOrigin, pgexpr, m_poc, EolCurrent())) { const ULONG ulOptRequests = CPhysical::PopConvert(pgexpr->Pop())->UlOptRequests(); for (ULONG ul = 0; ul < ulOptRequests; ul++) { CJobGroupExpressionOptimization::ScheduleJob(psc, pgexpr, m_poc, ul, this); } } pgexprLast = pgexpr; { CGroupProxy gp(m_pgroup); pgexpr = gp.PgexprSkipLogical(pgexpr); } } BOOL fNewJobs = (m_pgexprLastScheduled != pgexprLast); m_pgexprLastScheduled = pgexprLast; return fNewJobs; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtStartOptimization(CSchedulerContext *psc, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); CGroup *pgroup = pjgo->m_pgroup; GPOS_ASSERT(COptimizationContext::estUnoptimized == pjgo->m_poc->Est() && "Group is already optimized under this context"); if (!pgroup->FImplemented()) { CJobGroupImplementation::ScheduleJob(psc, pgroup, pjgo); return eevImplementing; } pjgo->m_poc->SetState(COptimizationContext::estOptimizing); if (psc->Peng()->FRoot(pgroup)) { psc->Pjf()->Truncate(EjtGroupImplementation); psc->Pjf()->Truncate(EjtGroupExpressionImplementation); } pjgo->m_eolCurrent = pgroup->EolMax(); return eevImplemented; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtOptimizeChildren(CSchedulerContext *psc, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); if (pjgo->FScheduleGroupExpressions(psc)) { return eevOptimizing; } return eevOptimizedCurrentLevel; } CJobGroupOptimization::EEvent CJobGroupOptimization::EevtCompleteOptimization(CSchedulerContext *, CJob *pjOwner) { CJobGroupOptimization *pjgo = PjConvert(pjOwner); pjgo->DampOptimizationLevel(); if (EolSentinel != pjgo->EolCurrent()) { pjgo->m_pgexprLastScheduled = NULL; return eevOptimizing; } pjgo->m_poc->SetState(COptimizationContext::estOptimized); return eevOptimized; } BOOL CJobGroupOptimization::FExecute(CSchedulerContext *psc) { GPOS_ASSERT(FInit()); return m_jsm.FRun(psc, this); } void CJobGroupOptimization::ScheduleJob(CSchedulerContext *psc, CGroup *pgroup, CGroupExpression *pgexprOrigin, COptimizationContext *poc, CJob *pjParent) { CJob *pj = psc->Pjf()->PjCreate(CJob::EjtGroupOptimization); CJobGroupOptimization *pjgo = PjConvert(pj); pjgo->Init(pgroup, pgexprOrigin, poc); psc->Psched()->Add(pjgo, pjParent); } #ifdef GPOS_DEBUG IOstream & CJobGroupOptimization::OsPrint(IOstream &os) { return m_jsm.OsHistory(os); } #endif
prOrigin = pgexprOrigin; m_poc = m_pgroup->PocInsert(poc); if (poc == m_poc) { m_poc->AddRef(); } SetJobQueue(m_poc->PjqOptimization()); m_eolCurrent = EolLow; CJob::SetInit(); } BOOL CJobGroupOptimization::FScheduleGroupExpressions(CSchedulerContext *psc) { CGroupExpression *pgexprLast = m_pgexprLastSchedul
random
[]
C++
modules/remote_bitrate_estimator/mimd_rate_control.cc
yuxw75/temp
ab2fd478821e6c98ff10f2976ce43f617250cff6
#include "webrtc/modules/remote_bitrate_estimator/mimd_rate_control.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> namespace webrtc { const int64_t kDefaultRttMs = 200; const int64_t kLogIntervalMs = 1000; MimdRateControl::MimdRateControl(uint32_t min_bitrate_bps) : min_configured_bit_rate_(min_bitrate_bps), max_configured_bit_rate_(30000000), current_bit_rate_(max_configured_bit_rate_), max_hold_rate_(0), avg_max_bit_rate_(-1.0f), var_max_bit_rate_(0.4f), rate_control_state_(kRcHold), came_from_state_(kRcDecrease), rate_control_region_(kRcMaxUnknown), last_bit_rate_change_(-1), current_input_(kBwNormal, 0, 1.0), updated_(false), time_first_incoming_estimate_(-1), initialized_bit_rate_(false), avg_change_period_(1000.0f), last_change_ms_(-1), beta_(0.9f), rtt_(kDefaultRttMs), time_of_last_log_(-1) { } RateControlType MimdRateControl::GetControlType() const { return kMimdControl; } uint32_t MimdRateControl::GetMinBitrate() const { return min_configured_bit_rate_; } bool MimdRateControl::ValidEstimate() const { return initialized_bit_rate_; } int64_t MimdRateControl::GetFeedbackInterval() const { return kMaxFeedbackIntervalMs; } bool MimdRateControl::TimeToReduceFurther(int64_t time_now, uint32_t incoming_bitrate_bps) const { const int64_t bitrate_reduction_interval = std::max<int64_t>(std::min<int64_t>(rtt_, 200), 10); if (time_now - last_bit_rate_change_ >= bitrate_reduction_interval) { return true; } if (ValidEstimate()) { const int threshold = static_cast<int>(1.05 * incoming_bitrate_bps); const int bitrate_difference = LatestEstimate() - incoming_bitrate_bps; return bitrate_difference > threshold; } return false; } uint32_t MimdRateControl::LatestEstimate() const { return current_bit_rate_; } uint32_t MimdRateControl::UpdateBandwidthEstimate(int64_t now_ms) { current_bit_rate_ = ChangeBitRate(current_bit_rate_, current_input_._incomingBitRate, current_input_._noiseVar, now_ms); if (now_ms - time_of_last_log_ > kLogIntervalMs) { time_of_last_log_ = now_ms; } return current_bit_rate_; } void MimdRateControl::SetRtt(int64_t rtt) { rtt_ = rtt; } RateControlRegion MimdRateControl::Update(const RateControlInput* input, int64_t now_ms) { assert(input); if (!initialized_bit_rate_) { if (time_first_incoming_estimate_ < 0) { if (input->_incomingBitRate > 0) { time_first_incoming_estimate_ = now_ms; } } else if (now_ms - time_first_incoming_estimate_ > 500 && input->_incomingBitRate > 0) { current_bit_rate_ = input->_incomingBitRate; initialized_bit_rate_ = true; } } if (updated_ && current_input_._bwState == kBwOverusing) { current_input_._noiseVar = input->_noiseVar; current_input_._incomingBitRate = input->_incomingBitRate; return rate_control_region_; } updated_ = true; current_input_ = *input; return rate_control_region_; } void MimdRateControl::SetEstimate(int bitrate_bps, int64_t now_ms) { } uint32_t MimdRateControl::ChangeBitRate(uint32_t current_bit_rate, uint32_t incoming_bit_rate, double noise_var, int64_t now_ms) { if (!updated_) { return current_bit_rate_; } updated_ = false; UpdateChangePeriod(now_ms); ChangeState(current_input_, now_ms); const float incoming_bit_rate_kbps = incoming_bit_rate / 1000.0f; const float std_max_bit_rate = sqrt(var_max_bit_rate_ * avg_max_bit_rate_); bool recovery = false; switch (rate_control_state_) { case kRcHold: { max_hold_rate_ = std::max(max_hold_rate_, incoming_bit_rate); break; } case kRcIncrease: { if (avg_max_bit_rate_ >= 0) { if (incoming_bit_rate_kbps > avg_max_bit_rate_ + 3 * std_max_bit_rate) { ChangeRegion(kRcMaxUnknown); avg_max_bit_rate_ = -1.0; } else if (incoming_bit_rate_kbps > avg_max_bit_rate_ + 2.5 * std_max_bit_rate) { ChangeRegion(kRcAboveMax); } } const int64_t response_time = static_cast<int64_t>(avg_change_period_ + 0.5f) + rtt_ + 300; double alpha = RateIncreaseFactor(now_ms, last_bit_rate_change_, response_time, noise_var); current_bit_rate = static_cast<uint32_t>(current_bit_rate * alpha) + 1000; if (max_hold_rate_ > 0 && beta_ * max_hold_rate_ > current_bit_rate) { current_bit_rate = static_cast<uint32_t>(beta_ * max_hold_rate_); avg_max_bit_rate_ = beta_ * max_hold_rate_ / 1000.0f; ChangeRegion(kRcNearMax); recovery = true; } max_hold_rate_ = 0; last_bit_rate_change_ = now_ms; break; } case kRcDecrease: { if (incoming_bit_rate < min_configured_bit_rate_) { current_bit_rate = min_configured_bit_rate_; } else { current_bit_rate = static_cast<uint32_t>(beta_ * incoming_bit_rate + 0.5); if (current_bit_rate > current_bit_rate_) { if (rate_control_region_ != kRcMaxUnknown) { current_bit_rate = static_cast<uint32_t>(beta_ * avg_max_bit_rate_ * 1000 + 0.5f); } current_bit_rate = std::min(current_bit_rate, current_bit_rate_); } ChangeRegion(kRcNearMax); if (incoming_bit_rate_kbps < avg_max_bit_rate_ - 3 * std_max_bit_rate) { avg_max_bit_rate_ = -1.0f; } UpdateMaxBitRateEstimate(incoming_bit_rate_kbps); } ChangeState(kRcHold); last_bit_rate_change_ = now_ms; break; } default: assert(false); } if (!recovery && (incoming_bit_rate > 100000 || current_bit_rate > 150000) && current_bit_rate > 1.5 * incoming_bit_rate) { current_bit_rate = current_bit_rate_; last_bit_rate_change_ = now_ms; } return current_bit_rate; } double MimdRateControl::RateIncreaseFactor(int64_t now_ms, int64_t last_ms, int64_t reaction_time_ms, double noise_var) const { const double B = 0.0407; const double b = 0.0025; const double c1 = -6700.0 / (33 * 33); const double c2 = 800.0; const double d = 0.85; double alpha = 1.005 + B / (1 + exp( b * (d * reaction_time_ms - (c1 * noise_var + c2)))); if (alpha < 1.005) { alpha = 1.005; } else if (alpha > 1.3) { alpha = 1.3; } if (last_ms > -1) { alpha = pow(alpha, (now_ms - last_ms) / 1000.0); } if (rate_control_region_ == kRcNearMax) { alpha = alpha - (alpha - 1.0) / 2.0; } else if (rate_control_region_ == kRcMaxUnknown) { alpha = alpha + (alpha - 1.0) * 2.0; } return alpha; } void MimdRateControl::UpdateChangePeriod(int64_t now_ms) { int64_t change_period = 0; if (last_change_ms_ > -1) { change_period = now_ms - last_change_ms_; } last_change_ms_ = now_ms; avg_change_period_ = 0.9f * avg_change_period_ + 0.1f * change_period; } void MimdRateControl::UpdateMaxBitRateEstimate(float incoming_bit_rate_kbps) { const float alpha = 0.05f; if (avg_max_bit_rate_ == -1.0f) { avg_max_bit_rate_ = incoming_bit_rate_kbps; } else { avg_max_bit_rate_ = (1 - alpha) * avg_max_bit_rate_ + alpha * incoming_bit_rate_kbps; } const float norm = std::max(avg_max_bit_rate_, 1.0f); var_max_bit_rate_ = (1 - alpha) * var_max_bit_rate_ + alpha * (avg_max_bit_rate_ - incoming_bit_rate_kbps) * (avg_max_bit_rate_ - incoming_bit_rate_kbps) / norm; if (var_max_bit_rate_ < 0.4f) { var_max_bit_rate_ = 0.4f; } if (var_max_bit_rate_ > 2.5f) { var_max_bit_rate_ = 2.5f; } } void MimdRateControl::ChangeState(const RateControlInput& input, int64_t now_ms) { switch (current_input_._bwState) { case kBwNormal: if (rate_control_state_ == kRcHold) { last_bit_rate_change_ = now_ms; ChangeState(kRcIncrease); } break; case kBwOverusing: if (rate_control_state_ != kRcDecrease) { ChangeState(kRcDecrease); } break; case kBwUnderusing: ChangeState(kRcHold); break; default: assert(false); } } void MimdRateControl::ChangeRegion(RateControlRegion region) { rate_control_region_ = region; switch (rate_control_region_) { case kRcAboveMax: case kRcMaxUnknown: beta_ = 0.9f; break; case kRcNearMax: beta_ = 0.95f; break; default: assert(false); } } void MimdRateControl::ChangeState(RateControlState new_state) { came_from_state_ = rate_control_state_; rate_control_state_ = new_state; } }
#include "webrtc/modules/remote_bitrate_estimator/mimd_rate_control.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> namespace webrtc { const int64_t kDefaultRttMs = 200; const int64_t kLogIntervalMs = 1000; MimdRateControl::MimdRateControl(uint32_t min_bitrate_bps) : min_configured_bit_rate_(min_bitrate_bps), max_configured_bit_rate_(30000000), current_bit_rate_(max_configured_bit_rate_), max_hold_rate_(0), avg_max_bit_rate_(-1.0f), var_max_bit_rate_(0.4f), rate_control_state_(kRcHold), came_from_state_(kRcDecrease), rate_control_region_(kRcMaxUnknown), last_bit_rate_change_(-1), current_input_(kBwNormal, 0, 1.0), updated_(false), time_first_incoming_estimate_(-1), initialized_bit_rate_(false), avg_change_period_(1000.0f), last_change_ms_(-1), beta_(0.9f), rtt_(kDefaultRttMs), time_of_last_log_(-1) { } RateControlType MimdRateControl::GetControlType() const { return kMimdControl; } uint32_t MimdRateControl::GetMinBitrate() const { return min_configured_bit_rate_; } bool MimdRateControl::ValidEstimate() const { return initialized_bit_rate_; } int64_t MimdRateControl::GetFeedbackInterval() const { return kMaxFeedbackIntervalMs; } bool MimdRateControl::TimeToReduceFurther(int64_t time_now,
); const int bitrate_difference = LatestEstimate() - incoming_bitrate_bps; return bitrate_difference > threshold; } return false; } uint32_t MimdRateControl::LatestEstimate() const { return current_bit_rate_; } uint32_t MimdRateControl::UpdateBandwidthEstimate(int64_t now_ms) { current_bit_rate_ = ChangeBitRate(current_bit_rate_, current_input_._incomingBitRate, current_input_._noiseVar, now_ms); if (now_ms - time_of_last_log_ > kLogIntervalMs) { time_of_last_log_ = now_ms; } return current_bit_rate_; } void MimdRateControl::SetRtt(int64_t rtt) { rtt_ = rtt; } RateControlRegion MimdRateControl::Update(const RateControlInput* input, int64_t now_ms) { assert(input); if (!initialized_bit_rate_) { if (time_first_incoming_estimate_ < 0) { if (input->_incomingBitRate > 0) { time_first_incoming_estimate_ = now_ms; } } else if (now_ms - time_first_incoming_estimate_ > 500 && input->_incomingBitRate > 0) { current_bit_rate_ = input->_incomingBitRate; initialized_bit_rate_ = true; } } if (updated_ && current_input_._bwState == kBwOverusing) { current_input_._noiseVar = input->_noiseVar; current_input_._incomingBitRate = input->_incomingBitRate; return rate_control_region_; } updated_ = true; current_input_ = *input; return rate_control_region_; } void MimdRateControl::SetEstimate(int bitrate_bps, int64_t now_ms) { } uint32_t MimdRateControl::ChangeBitRate(uint32_t current_bit_rate, uint32_t incoming_bit_rate, double noise_var, int64_t now_ms) { if (!updated_) { return current_bit_rate_; } updated_ = false; UpdateChangePeriod(now_ms); ChangeState(current_input_, now_ms); const float incoming_bit_rate_kbps = incoming_bit_rate / 1000.0f; const float std_max_bit_rate = sqrt(var_max_bit_rate_ * avg_max_bit_rate_); bool recovery = false; switch (rate_control_state_) { case kRcHold: { max_hold_rate_ = std::max(max_hold_rate_, incoming_bit_rate); break; } case kRcIncrease: { if (avg_max_bit_rate_ >= 0) { if (incoming_bit_rate_kbps > avg_max_bit_rate_ + 3 * std_max_bit_rate) { ChangeRegion(kRcMaxUnknown); avg_max_bit_rate_ = -1.0; } else if (incoming_bit_rate_kbps > avg_max_bit_rate_ + 2.5 * std_max_bit_rate) { ChangeRegion(kRcAboveMax); } } const int64_t response_time = static_cast<int64_t>(avg_change_period_ + 0.5f) + rtt_ + 300; double alpha = RateIncreaseFactor(now_ms, last_bit_rate_change_, response_time, noise_var); current_bit_rate = static_cast<uint32_t>(current_bit_rate * alpha) + 1000; if (max_hold_rate_ > 0 && beta_ * max_hold_rate_ > current_bit_rate) { current_bit_rate = static_cast<uint32_t>(beta_ * max_hold_rate_); avg_max_bit_rate_ = beta_ * max_hold_rate_ / 1000.0f; ChangeRegion(kRcNearMax); recovery = true; } max_hold_rate_ = 0; last_bit_rate_change_ = now_ms; break; } case kRcDecrease: { if (incoming_bit_rate < min_configured_bit_rate_) { current_bit_rate = min_configured_bit_rate_; } else { current_bit_rate = static_cast<uint32_t>(beta_ * incoming_bit_rate + 0.5); if (current_bit_rate > current_bit_rate_) { if (rate_control_region_ != kRcMaxUnknown) { current_bit_rate = static_cast<uint32_t>(beta_ * avg_max_bit_rate_ * 1000 + 0.5f); } current_bit_rate = std::min(current_bit_rate, current_bit_rate_); } ChangeRegion(kRcNearMax); if (incoming_bit_rate_kbps < avg_max_bit_rate_ - 3 * std_max_bit_rate) { avg_max_bit_rate_ = -1.0f; } UpdateMaxBitRateEstimate(incoming_bit_rate_kbps); } ChangeState(kRcHold); last_bit_rate_change_ = now_ms; break; } default: assert(false); } if (!recovery && (incoming_bit_rate > 100000 || current_bit_rate > 150000) && current_bit_rate > 1.5 * incoming_bit_rate) { current_bit_rate = current_bit_rate_; last_bit_rate_change_ = now_ms; } return current_bit_rate; } double MimdRateControl::RateIncreaseFactor(int64_t now_ms, int64_t last_ms, int64_t reaction_time_ms, double noise_var) const { const double B = 0.0407; const double b = 0.0025; const double c1 = -6700.0 / (33 * 33); const double c2 = 800.0; const double d = 0.85; double alpha = 1.005 + B / (1 + exp( b * (d * reaction_time_ms - (c1 * noise_var + c2)))); if (alpha < 1.005) { alpha = 1.005; } else if (alpha > 1.3) { alpha = 1.3; } if (last_ms > -1) { alpha = pow(alpha, (now_ms - last_ms) / 1000.0); } if (rate_control_region_ == kRcNearMax) { alpha = alpha - (alpha - 1.0) / 2.0; } else if (rate_control_region_ == kRcMaxUnknown) { alpha = alpha + (alpha - 1.0) * 2.0; } return alpha; } void MimdRateControl::UpdateChangePeriod(int64_t now_ms) { int64_t change_period = 0; if (last_change_ms_ > -1) { change_period = now_ms - last_change_ms_; } last_change_ms_ = now_ms; avg_change_period_ = 0.9f * avg_change_period_ + 0.1f * change_period; } void MimdRateControl::UpdateMaxBitRateEstimate(float incoming_bit_rate_kbps) { const float alpha = 0.05f; if (avg_max_bit_rate_ == -1.0f) { avg_max_bit_rate_ = incoming_bit_rate_kbps; } else { avg_max_bit_rate_ = (1 - alpha) * avg_max_bit_rate_ + alpha * incoming_bit_rate_kbps; } const float norm = std::max(avg_max_bit_rate_, 1.0f); var_max_bit_rate_ = (1 - alpha) * var_max_bit_rate_ + alpha * (avg_max_bit_rate_ - incoming_bit_rate_kbps) * (avg_max_bit_rate_ - incoming_bit_rate_kbps) / norm; if (var_max_bit_rate_ < 0.4f) { var_max_bit_rate_ = 0.4f; } if (var_max_bit_rate_ > 2.5f) { var_max_bit_rate_ = 2.5f; } } void MimdRateControl::ChangeState(const RateControlInput& input, int64_t now_ms) { switch (current_input_._bwState) { case kBwNormal: if (rate_control_state_ == kRcHold) { last_bit_rate_change_ = now_ms; ChangeState(kRcIncrease); } break; case kBwOverusing: if (rate_control_state_ != kRcDecrease) { ChangeState(kRcDecrease); } break; case kBwUnderusing: ChangeState(kRcHold); break; default: assert(false); } } void MimdRateControl::ChangeRegion(RateControlRegion region) { rate_control_region_ = region; switch (rate_control_region_) { case kRcAboveMax: case kRcMaxUnknown: beta_ = 0.9f; break; case kRcNearMax: beta_ = 0.95f; break; default: assert(false); } } void MimdRateControl::ChangeState(RateControlState new_state) { came_from_state_ = rate_control_state_; rate_control_state_ = new_state; } }
uint32_t incoming_bitrate_bps) const { const int64_t bitrate_reduction_interval = std::max<int64_t>(std::min<int64_t>(rtt_, 200), 10); if (time_now - last_bit_rate_change_ >= bitrate_reduction_interval) { return true; } if (ValidEstimate()) { const int threshold = static_cast<int>(1.05 * incoming_bitrate_bps
function_block-random_span
[ { "content": "namespace webrtc {\n\n\n\n// Supported video types.\n\nenum VideoType {\n\n kUnknown,\n\n kI420,\n\n kIYUV,\n\n kRGB24,\n\n kABGR,\n\n kARGB,\n\n kARGB4444,\n\n kRGB565,\n\n kARGB1555,\n\n kYUY2,\n\n kYV12,\n\n kUYVY,\n\n kMJPG,\n\n kNV21,\n\n kNV12,\n\n kBGRA,\n\n};\n\n\n\n// This...
C++
src/hir/path.cpp
nabijaczleweli/mrustc
c3565612a003fbc2f87aa55250fe3f5218cb99aa
#include <hir/path.hpp> #include <hir/type.hpp> ::HIR::SimplePath HIR::SimplePath::operator+(const RcString& s) const { ::HIR::SimplePath ret(m_crate_name); ret.m_components = m_components; ret.m_components.push_back( s ); return ret; } namespace HIR { ::std::ostream& operator<<(::std::ostream& os, const ::HIR::SimplePath& x) { if( x.m_crate_name != "" ) { os << "::\"" << x.m_crate_name << "\""; } else if( x.m_components.size() == 0 ) { os << "::"; } else { } for(const auto& n : x.m_components) { os << "::" << n; } return os; } ::std::ostream& operator<<(::std::ostream& os, const PathParams& x) { bool has_args = ( x.m_types.size() > 0 || x.m_values.size() > 0 ); if(has_args) { os << "<"; } for(const auto& ty : x.m_types) { os << ty << ","; } for(const auto& v : x.m_values) { os << "{" << v << "},"; } if(has_args) { os << ">"; } return os; } ::std::ostream& operator<<(::std::ostream& os, const GenericPath& x) { os << x.m_path << x.m_params; return os; } ::std::ostream& operator<<(::std::ostream& os, const TraitPath& x) { if( x.m_hrls.size() > 0 ) { os << "for<"; for(const auto& lft : x.m_hrls) os << "'" << lft << ","; os << "> "; } os << x.m_path.m_path; bool has_args = ( x.m_path.m_params.m_types.size() > 0 || x.m_type_bounds.size() > 0 ); if(has_args) { os << "<"; } for(const auto& ty : x.m_path.m_params.m_types) { os << ty << ","; } for(const auto& assoc : x.m_type_bounds) { os << assoc.first << "=" << assoc.second << ","; } if(has_args) { os << ">"; } return os; } ::std::ostream& operator<<(::std::ostream& os, const Path& x) { TU_MATCH(::HIR::Path::Data, (x.m_data), (e), (Generic, return os << e; ), (UfcsInherent, return os << "<" << e.type << " /*- " << e.impl_params << "*/>::" << e.item << e.params; ), (UfcsKnown, return os << "<" << e.type << " as " << e.trait << ">::" << e.item << e.params; ), (UfcsUnknown, return os << "<" << e.type << " as _>::" << e.item << e.params; ) ) return os; } } ::HIR::SimplePath HIR::SimplePath::clone() const { return SimplePath( m_crate_name, m_components ); } ::HIR::PathParams::PathParams() { } ::HIR::PathParams::PathParams(::HIR::TypeRef ty0) { m_types.push_back( mv$(ty0) ); } ::HIR::PathParams HIR::PathParams::clone() const { PathParams rv; for( const auto& t : m_types ) rv.m_types.push_back( t.clone() ); for( const auto& t : m_values ) rv.m_values.push_back( t.clone() ); return rv; } bool ::HIR::PathParams::operator==(const ::HIR::PathParams& x) const { if( m_types.size() != x.m_types.size() ) return false; for( unsigned int i = 0; i < m_types.size(); i ++ ) if( !(m_types[i] == x.m_types[i]) ) return false; if( m_values.size() != x.m_values.size() ) return false; for( unsigned int i = 0; i < m_values.size(); i ++ ) if( !(m_values[i] == x.m_values[i]) ) return false; return true; } ::HIR::GenericPath::GenericPath() { } ::HIR::GenericPath::GenericPath(::HIR::SimplePath sp): m_path( mv$(sp) ) { } ::HIR::GenericPath::GenericPath(::HIR::SimplePath sp, ::HIR::PathParams params): m_path( mv$(sp) ), m_params( mv$(params) ) { } ::HIR::GenericPath HIR::GenericPath::clone() const { return GenericPath(m_path.clone(), m_params.clone()); } bool ::HIR::GenericPath::operator==(const GenericPath& x) const { if( m_path != x.m_path ) return false; return m_params == x.m_params; } ::HIR::TraitPath HIR::TraitPath::clone() const { ::HIR::TraitPath rv { m_path.clone(), m_hrls, {}, m_trait_ptr }; for( const auto& assoc : m_type_bounds ) rv.m_type_bounds.insert(::std::make_pair( assoc.first, assoc.second.clone() )); return rv; } bool ::HIR::TraitPath::operator==(const ::HIR::TraitPath& x) const { if( m_path != x.m_path ) return false; if( m_hrls != x.m_hrls ) return false; if( m_type_bounds.size() != x.m_type_bounds.size() ) return false; for(auto it_l = m_type_bounds.begin(), it_r = x.m_type_bounds.begin(); it_l != m_type_bounds.end(); it_l++, it_r++ ) { if( it_l->first != it_r->first ) return false; if( it_l->second != it_r->second ) return false; } return true; } ::HIR::Path::Path(::HIR::GenericPath gp): m_data( ::HIR::Path::Data::make_Generic( mv$(gp) ) ) { } ::HIR::Path::Path(::HIR::SimplePath sp): m_data( ::HIR::Path::Data::make_Generic(::HIR::GenericPath(mv$(sp))) ) { } ::HIR::Path::Path(TypeRef ty, RcString item, PathParams item_params): m_data(Data::make_UfcsInherent({ mv$(ty), mv$(item), mv$(item_params) })) { } ::HIR::Path::Path(TypeRef ty, GenericPath trait, RcString item, PathParams item_params): m_data( Data::make_UfcsKnown({ mv$(ty), mv$(trait), mv$(item), mv$(item_params) }) ) { } ::HIR::Path HIR::Path::clone() const { TU_MATCH_HDRA((m_data), {) TU_ARMA(Generic, e) { return Path( Data::make_Generic(e.clone()) ); } TU_ARMA(UfcsInherent, e) { return Path(Data::make_UfcsInherent({ e.type.clone(), e.item, e.params.clone(), e.impl_params.clone() })); } TU_ARMA(UfcsKnown, e) { return Path(Data::make_UfcsKnown({ e.type.clone(), e.trait.clone(), e.item, e.params.clone() })); } TU_ARMA(UfcsUnknown, e) { return Path(Data::make_UfcsUnknown({ e.type.clone(), e.item, e.params.clone() })); } } throw ""; } ::HIR::Compare HIR::PathParams::compare_with_placeholders(const Span& sp, const ::HIR::PathParams& x, ::HIR::t_cb_resolve_type resolve_placeholder) const { using ::HIR::Compare; auto rv = Compare::Equal; if( this->m_types.size() > 0 || x.m_types.size() > 0 ) { if( this->m_types.size() != x.m_types.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_types.size(); i ++ ) { auto rv2 = this->m_types[i].compare_with_placeholders( sp, x.m_types[i], resolve_placeholder ); if( rv2 == Compare::Unequal ) return Compare::Unequal; if( rv2 == Compare::Fuzzy ) rv = Compare::Fuzzy; } } return rv; } ::HIR::Compare HIR::PathParams::match_test_generics_fuzz(const Span& sp, const PathParams& x, t_cb_resolve_type resolve_placeholder, ::HIR::MatchGenerics& match) const { using ::HIR::Compare; auto rv = Compare::Equal; TRACE_FUNCTION_F(*this << " with " << x); if( this->m_types.size() != x.m_types.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_types.size(); i ++ ) { rv &= this->m_types[i].match_test_generics_fuzz( sp, x.m_types[i], resolve_placeholder, match ); if( rv == Compare::Unequal ) return Compare::Unequal; } if( this->m_values.size() != x.m_values.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_values.size(); i ++ ) { if( const auto* ge = this->m_values[i].opt_Generic() ) { auto rv = match.match_val(*ge, x.m_values[i]); if(rv == Compare::Unequal) return Compare::Unequal; } else { if( this->m_values[i] != x.m_values[i] ) { return Compare::Unequal; } } } return rv; } ::HIR::Compare HIR::GenericPath::compare_with_placeholders(const Span& sp, const ::HIR::GenericPath& x, ::HIR::t_cb_resolve_type resolve_placeholder) const { using ::HIR::Compare; if( this->m_path.m_crate_name != x.m_path.m_crate_name ) return Compare::Unequal; if( this->m_path.m_components.size() != x.m_path.m_components.size() ) return Compare::Unequal; for(unsigned int i = 0; i < this->m_path.m_components.size(); i ++ ) { if( this->m_path.m_components[i] != x.m_path.m_components[i] ) return Compare::Unequal; } return this->m_params. compare_with_placeholders(sp, x.m_params, resolve_placeholder); } namespace { ::HIR::Compare compare_with_placeholders( const Span& sp, const ::HIR::PathParams& l, const ::HIR::PathParams& r, ::HIR::t_cb_resolve_type resolve_placeholder ) { return l.compare_with_placeholders(sp, r, resolve_placeholder); } ::HIR::Compare compare_with_placeholders( const Span& sp, const ::HIR::GenericPath& l, const ::HIR::GenericPath& r, ::HIR::t_cb_resolve_type resolve_placeholder ) { return l.compare_with_placeholders(sp, r, resolve_placeholder); } } #define CMP(rv, cmp) do { \ switch(cmp) {\ case ::HIR::Compare::Unequal: return ::HIR::Compare::Unequal; \ case ::HIR::Compare::Fuzzy: rv = ::HIR::Compare::Fuzzy; break; \ case ::HIR::Compare::Equal: break; \ }\ } while(0) ::HIR::Compare HIR::TraitPath::compare_with_placeholders(const Span& sp, const TraitPath& x, t_cb_resolve_type resolve_placeholder) const { auto rv = m_path .compare_with_placeholders(sp, x.m_path, resolve_placeholder); if( rv == Compare::Unequal ) return rv; auto it_l = m_type_bounds.begin(); auto it_r = x.m_type_bounds.begin(); while( it_l != m_type_bounds.end() && it_r != x.m_type_bounds.end() ) { if( it_l->first != it_r->first ) { return Compare::Unequal; } CMP( rv, it_l->second .compare_with_placeholders( sp, it_r->second, resolve_placeholder ) ); ++ it_l; ++ it_r; } if( it_l != m_type_bounds.end() || it_r != x.m_type_bounds.end() ) { return Compare::Unequal; } return rv; } ::HIR::Compare HIR::Path::compare_with_placeholders(const Span& sp, const Path& x, t_cb_resolve_type resolve_placeholder) const { if( this->m_data.tag() != x.m_data.tag() ) return Compare::Unequal; TU_MATCH_HDRA( (this->m_data, x.m_data), {) TU_ARMA(Generic, ple, pre) { return ::compare_with_placeholders(sp, ple, pre, resolve_placeholder); } TU_ARMA(UfcsUnknown, ple, pre) { if( ple.item != pre.item) return Compare::Unequal; TODO(sp, "Path::compare_with_placeholders - UfcsUnknown"); } TU_ARMA(UfcsInherent, ple, pre) { if( ple.item != pre.item) return Compare::Unequal; ::HIR::Compare rv = ::HIR::Compare::Equal; CMP(rv, ple.type.compare_with_placeholders(sp, pre.type, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.params, pre.params, resolve_placeholder)); return rv; } TU_ARMA(UfcsKnown, ple, pre) { if( ple.item != pre.item) return Compare::Unequal; ::HIR::Compare rv = ::HIR::Compare::Equal; CMP(rv, ple.type.compare_with_placeholders(sp, pre.type, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.trait, pre.trait, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.params, pre.params, resolve_placeholder)); return rv; } } throw ""; } Ordering HIR::Path::ord(const ::HIR::Path& x) const { ORD( (unsigned)m_data.tag(), (unsigned)x.m_data.tag() ); TU_MATCH(::HIR::Path::Data, (this->m_data, x.m_data), (tpe, xpe), (Generic, return ::ord(tpe, xpe); ), (UfcsInherent, ORD(tpe.type, xpe.type); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ), (UfcsKnown, ORD(tpe.type, xpe.type); ORD(tpe.trait, xpe.trait); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ), (UfcsUnknown, ORD(tpe.type, xpe.type); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ) ) throw ""; } bool ::HIR::Path::operator==(const Path& x) const { return this->ord(x) == ::OrdEqual; }
#include <hir/path.hpp> #include <hir/type.hpp> ::HIR::SimplePath HIR::SimplePath::operator+(const RcString& s) const { ::HIR::SimplePath ret(m_crate_name); ret.m_components = m_components; ret.m_components.push_back( s ); return ret; } namespace HIR { ::std::ostream& operator<<(::std::ostream& os, const ::HIR::SimplePath& x) { if( x.m_crate_name != "" ) { os << "::\"" << x.m_crate_name << "\""; } else if( x.m_components.size() == 0 ) { os << "::"; } else { } for(const auto& n : x.m_components) { os << "::" << n; } return os; } ::std::ostream& operator<<(::std::ostream& os, const PathParams& x) { bool has_args = ( x.m_types.size() > 0 || x.m_values.size() > 0 ); if(has_args) { os << "<"; } for(const auto& ty : x.m_types) { os << ty << ","; } for(const auto& v : x.m_values) { os << "{" << v << "},"; } if(has_args) { os << ">"; } return os; } ::std::ostream& operator<<(::std::ostream& os, const GenericPath& x) { os << x.m_path << x.m_params; return os; } ::std::ostream& operator<<(::std::ostream& os, const TraitPath& x) { if( x.m_hrls.size() > 0 ) { os << "for<"; for(const auto& lft : x.m_hrls) os << "'" << lft << ","; os << "> "; } os << x.m_path.m_path; bool has_args = ( x.m_path.m_params.m_types.size() > 0 || x.m_type_bounds.size() > 0 ); if(has_args) { os << "<"; } for(const auto& ty : x.m_path.m_params.m_types) { os << ty << ","; } for(const auto& assoc : x.m_type_bounds) { os << assoc.first << "=" << assoc.second << ","; } if(has_args) { os << ">"; } return os; } ::std::ostream& operator<<(::std::ostream& os, const Path& x) { TU_MATCH(::HIR::Path::Data, (x.m_data), (e), (Generic, return os << e; ), (UfcsInherent, return os << "<" << e.type << " /*- " << e.impl_params << "*/>::" << e.item << e.params; ), (UfcsKnown, return os << "<" << e.type << " as " << e.trait << ">::" << e.item << e.params; ), (UfcsUnknown, return os << "<" << e.type << " as _>::" << e.item << e.params; ) ) return os; } } ::HIR::SimplePath HIR::SimplePath::clone() const { return SimplePath( m_crate_name, m_components ); } ::HIR::PathParams::PathParams() { } ::HIR::PathParams::PathParams(::HIR::TypeRef ty0) { m_types.push_back( mv$(ty0) ); } ::HIR::PathParams HIR::PathParams::clone() const { PathParams rv; for( const auto& t : m_types ) rv.m_types.push_back( t.clone() ); for( const auto& t : m_values ) rv.m_values.push_back( t.clone() ); return rv; } bool ::HIR::PathParams::operator==(const ::HIR::PathParams& x) const { if( m_types.size() != x.m_types.size() ) return false; for( unsigned int i = 0; i < m_types.size(); i ++ ) if( !(m_types[i] == x.m_types[i]) ) return false; if( m_values.size() != x.m_values.size() ) return false; for( unsigned int i = 0; i < m_values.size(); i ++ ) if( !(m_values[i] == x.m_values[i]) ) return false; return true; } ::HIR::GenericPath::GenericPath() { } ::HIR::GenericPath::GenericPath(::HIR::SimplePath sp): m_path( mv$(sp) ) { } ::HIR::GenericPath::GenericPath(::HIR::SimplePath sp, ::HIR::PathParams params): m_path( mv$(sp) ), m_params( mv$(params) ) { } ::HIR::GenericPath HIR::GenericPath::clone() const { return GenericPath(m_path.clone(), m_params.clone()); } bool ::HIR::GenericPath::operator==(const GenericPath& x) const { if( m_path != x.m_path ) return false; return m_params == x.m_params; } ::HIR::TraitPath HIR::TraitPath::clone() const { ::HIR::TraitPath rv { m_path.clone(), m_hrls, {}, m_trait_ptr }; for( const auto& assoc : m_type_bounds ) rv.m_type_bounds.insert(::std::make_pair( assoc.first, assoc.second.clone() )); return rv; } bool ::HIR::TraitPath::operator==(const ::HIR::TraitPath& x) const { if( m_path != x.m_path ) return false; if( m_hrls != x.m_hrls ) return false; if( m_type_bounds.size() != x.m_type_bounds.size() ) return false; for(auto it_l = m_type_bounds.begin(), it_r = x.m_type_bounds.begin(); it_l != m_type_bounds.end(); it_l++, it_r++ ) { if( it_l->first != it_r->first ) return false; if( it_l->second != it_r->second ) return false; } return true; } ::HIR::Path::Path(::HIR::GenericPath gp): m_data( ::HIR::Path::Data::make_Generic( mv$(gp) ) ) { } ::HIR::Path::Path(::HIR::SimplePath sp): m_data( ::HIR::Path::Data::make_Generic(::HIR::GenericPath(mv$(sp))) ) { } ::HIR::Path::Path(TypeRef ty, RcString item, PathParams item_params): m_data(Data::make_UfcsInherent({ mv$(ty), mv$(item), mv$(item_params) })) { } ::HIR::Path::Path(TypeRef ty, GenericPath trait, RcString item, PathParams item_params): m_data( Data::make_UfcsKnown({ mv$(ty), mv$(trait), mv$(item), mv$(item_params) }) ) { } ::HIR::Path HIR::Path::clone() const { TU_MATCH_HDRA((m_data), {) TU_ARMA(Generic, e) { return Path( Data::make_Generic(e.clone()) ); } TU_ARMA(UfcsInherent, e) { return Path(Data::make_UfcsInherent({ e.type.clone(), e.item, e.params.clone(), e.impl_params.clone() })); } TU_ARMA(UfcsKnown, e) { return Path(Data::make_UfcsKnown({ e.type.clone(), e.trait.clone(), e.item, e.params.clone() })); } TU_ARMA(UfcsUnknown, e) { return Path(Data::make_UfcsUnknown({ e.type.clone(), e.item, e.params.clone() })); } } throw ""; } ::HIR::Compare HIR::PathParams::compare_with_placeholders(const Span& sp, const ::HIR::PathParams& x, ::HIR::t_cb_resolve_type resolve_placeholder) const { using ::HIR::Compare; auto rv = Compare::Equal; if( this->m_types.size() > 0 || x.m_types.size() > 0 ) { if( this->m_types.size() != x.m_types.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_types.size(); i ++ ) { auto rv2 = this->m_types[i].compare_with_placeholders( sp, x.m_types[i], resolve_placeholder ); if( rv2 == Compare::Unequal ) return Compare::Unequal; if( rv2 == Compare::Fuzzy ) rv = Compare::Fuzzy; } } return rv; } ::HIR::Compare HIR::PathParams::match_test_generics_fuzz(const Span& sp, const PathParams& x, t_cb_resolve_type resolve_placeholder, ::HIR::MatchGenerics& match) const { using ::HIR::Compare; auto rv = Compare::Equal; TRACE_FUNCTION_F(*this << " with " << x); if( this->m_types.size() != x.m_types.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_types.size(); i ++ ) { rv &= this->m_types[i].match_test_generics_fuzz( sp, x.m_types[i], resolve_placeholder, match ); if( rv == Compare::Unequal ) return Compare::Unequal; } if( this->m_values.size() != x.m_values.size() ) { return Compare::Unequal; } for( unsigned int i = 0; i < x.m_values.size(); i ++ ) { if( const auto* ge = this->m_values[i].opt_Generic() ) { auto rv = match.match_val(*ge, x.m_values[i]); if(rv == Compare::Unequal) return Compare::Unequal; } else { if( this->m_values[i] != x.m_values[i] ) { return Compare::Unequal; } } } return rv; } ::HIR::Compare HIR::GenericPath::compare_with_placeholders(const Span& sp, const ::HIR::GenericPath& x, ::HIR::t_cb_resolve_type resolve_placeholder) const { using ::HIR::Compare; if( this->m_path.m_crate_name != x.m_path.m_crate_name ) return Compare::Unequal; if( this->m_path.m_components.size() != x.m_path.m_components.size() ) return Compare::Unequal; for(unsigned int i = 0; i < this->m_path.m_components.size(); i ++ ) { if( this->m_path.m_components[i] != x.m_path.m_components[i] ) return Compare::Unequal; } return this->m_params. compare_with_placeholders(sp, x.m_params, resolve_placeholder); } namespace { ::HIR::Compare compare_with_placeholders( const Span& sp, const ::HIR::PathParams& l, const ::HIR::PathParams& r, ::HIR::t_cb_resolve_type resolve_placeholder ) { return l.compare_with_placeholders(sp, r, resolve_placeholder); } ::HIR::Compare compare_with_placeholders( const Span& sp, const ::HIR::GenericPath& l, const ::HIR::GenericPath& r, ::HIR::t_cb_resolve_type resolve_placeholder ) { return l.compare_with_placeholders(sp, r, resolve_placeholder); } } #define CMP(rv, cmp) do { \ switch(cmp) {\ case ::HIR::Compare::Unequal: return ::HIR::Compare::Unequal; \ case ::HIR::Compare::Fuzzy: rv = ::HIR::Compare::Fuzzy; break; \ case ::HIR::Compare::Equal: break; \ }\ } while(0) ::HIR::Compare HIR::TraitPath::compare_with_placeholders(const Span& sp, const TraitPath& x, t_cb_resolve_type resolve_placeholder) const { auto rv = m_path .compare_with_placeholders(sp, x.m_path, resolve_placeholder); if( rv == Compare::Unequal ) return rv; auto it_l = m_type_bounds.begin(); auto it_r = x.m_type_bounds.begin(); while( it_l != m_type_bounds.end() && it_r != x.m_type_bounds.end() ) { if( it_l->first != it_r->first ) { return Compare::Unequal; } CMP( rv, it_l->second .compare_with_placeholders( sp, it_r->second, resolve_placeholder ) ); ++ it_l; ++ it_r; } if( it_l != m_type_bounds.end() || it_r != x.m_type_bounds.end() ) { return Compare::Unequal; } return rv; } ::HIR::Compare HIR::Path::compare_with_placeholders(const Span& sp, const Path& x, t_cb_resolve_type resolve_placeholder) const { if( this->m_data.tag() != x.m_data.tag() ) return Compare::Unequal; TU_MATCH_HDRA( (this->m_data, x.m_data), {) TU_ARMA(Generic, ple, pre) { return ::compare_with_placeholders(sp, ple, pre, resolve_placeholder); } TU_ARMA(UfcsUnknown, ple, pre) { if( ple.item != pre.item) return Compare::Unequal; TODO(sp, "Path::compare_with_placeholders - UfcsUnknown"); } TU_ARMA(UfcsInherent, ple, pre) { if( ple.item != pre.item) return Compare::Unequal; ::HIR::Compare rv = ::HIR::Compare::Equal; CMP(rv, ple.type.compare_with_placeholders(sp, pre.type, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.params, pre.params, resolve_placeholder)); return rv; } TU_ARMA(UfcsKnown, ple, pre) { if( ple.item != pre.item) retur
} throw ""; } Ordering HIR::Path::ord(const ::HIR::Path& x) const { ORD( (unsigned)m_data.tag(), (unsigned)x.m_data.tag() ); TU_MATCH(::HIR::Path::Data, (this->m_data, x.m_data), (tpe, xpe), (Generic, return ::ord(tpe, xpe); ), (UfcsInherent, ORD(tpe.type, xpe.type); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ), (UfcsKnown, ORD(tpe.type, xpe.type); ORD(tpe.trait, xpe.trait); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ), (UfcsUnknown, ORD(tpe.type, xpe.type); ORD(tpe.item, xpe.item); return ::ord(tpe.params, xpe.params); ) ) throw ""; } bool ::HIR::Path::operator==(const Path& x) const { return this->ord(x) == ::OrdEqual; }
n Compare::Unequal; ::HIR::Compare rv = ::HIR::Compare::Equal; CMP(rv, ple.type.compare_with_placeholders(sp, pre.type, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.trait, pre.trait, resolve_placeholder)); CMP(rv, ::compare_with_placeholders(sp, ple.params, pre.params, resolve_placeholder)); return rv; }
function_block-function_prefixed
[]
C++
analysis/EnergyDepVSIntialEnergy.cpp
suerfu/TesseractSim
406a469f864726386afc2df7133f07df625cd4b9
#include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> #include <functional> #include <map> #include <stdlib.h> #include "TSystem.h" #include "TCanvas.h" #include "TH1.h" #include "TRint.h" #include "TStyle.h" #include "THStack.h" #include "TTreeReader.h" #include "TTreeReaderValue.h" #include "TFile.h" #include "TTree.h" using namespace std; template<typename T> T strTo(const char* str) { T t; std::stringstream converter(str); converter >> t; return t; } template<typename T> T strTo(const std::string& str) { return strTo<T>(str.c_str()); } bool CmdOptionExists(int argc, char** argv, const std::string& option) { char** begin = argv; char** end = argv + argc; return std::find(begin, end, option) != end; } template<typename T = std::string> T GetCmdOption(int argc, char** argv, const std::string& option, int optionNum = 1) { if(!CmdOptionExists(argc, argv, option)) { abort(); } char** begin = argv; char** end = argv + argc; char ** itr = std::find(begin, end, option); for(int iOpt = 0; iOpt < optionNum; ++iOpt) { if(itr != end && ++itr != end && ((*itr)[0] != '-' || std::isdigit((*itr)[1]))) { if(iOpt + 1 == optionNum) return strTo<T>(*itr); } else { std::string pos = "nth"; if(iOpt == 0) pos = "1st"; else if(iOpt == 1) pos = "2nd"; else if(iOpt == 2) pos = "3rd"; else pos = std::to_string(iOpt + 1) + "th"; exit(EXIT_FAILURE); return 0; } } return 0; } template<typename T = std::string> std::vector<T> GetCmdOptionArray(int argc, char** argv, const std::string& option) { if(!CmdOptionExists(argc, argv, option)) { printf("Missing option %s \n",option.c_str()); abort(); } std::vector<std::string> options; char** begin = argv; char** end = argv + argc; char ** itr = std::find(begin, end, option); while(itr++, itr != end && ((*itr)[0] != '-' || std::isdigit((*itr)[1]))) { if(itr != end) { options.push_back(strTo<T>(*itr)); } } if(options.size() == 0) { printf("Missing parameter for option %s \n",option.c_str()); exit(EXIT_FAILURE); } return options; } void Usage() { cout << endl; cout << "Usage: EnergyDepVSIntialEnergy -p <ProcessedFile name> -o <ouput_filename>" << endl; cout << endl; } int main(int argc, char* argv[]) { if(CmdOptionExists(argc, argv, "-h") || argc==1 ) { Usage(); return EXIT_SUCCESS; } string outputFilename = "output.root"; if(CmdOptionExists(argc, argv, "-o")) { outputFilename = GetCmdOption<string>(argc, argv, "-o"); } else { cout<<"Output Filename not specified, default option is set to output.root "<<endl; } string ProcessedFiles; if(CmdOptionExists(argc, argv, "-p")) { ProcessedFiles = GetCmdOption<string>(argc, argv, "-p"); } else { return EXIT_FAILURE; } Double_t Edep,IntialE,rx,ry,rz,px,py,pz; TFile *outputfile = new TFile(outputFilename.c_str(),"RECREATE"); TTree *events= new TTree("events","simple tree"); events->Branch("Edep",&Edep,"Edep/D"); events->Branch("IntialE",&IntialE,"IntialE/D"); events->Branch("rx",&rx,"rx/D"); events->Branch("ry",&ry,"ry/D"); events->Branch("rz",&rz,"rz/D"); events->Branch("px",&px,"px/D"); events->Branch("py",&py,"py/D"); events->Branch("pz",&pz,"pz/D"); TFile* f = new TFile(ProcessedFiles.c_str()); if( !f->IsOpen() ){ cout<< "Error opening " << ProcessedFiles.c_str() <<endl; } else { if(f->IsZombie()) { cout<<"The file "<<ProcessedFiles.c_str()<<"is corrupted"<<endl; } else{ TTree *t = (TTree*)f->Get("events"); Int_t nentries = (Int_t)t->GetEntries(); Double_t E_dep; Int_t Event_ID; char name_file[200]; t->SetBranchAddress("edep_virtualDetector",&E_dep); t->SetBranchAddress("file",name_file); t->SetBranchAddress("eventID",&Event_ID); for (Int_t i=0;i<nentries;i++){ t->GetEntry(i); std::string filename(name_file); if (E_dep<1000.0) { cout<<filename<<" "<<Event_ID<<endl; TFile* f1 = new TFile(filename.c_str()); TTree *t1 = (TTree*)f1->Get("events"); Int_t nentries = (Int_t)t1->GetEntries(); Double_t X_pos,Y_pos,Z_pos,X_mom,Y_mom,Z_mom, Intial_E; Int_t event_ID, step_ID, parent_ID; char Process_ID[16]; t1->SetBranchAddress("eventID",&event_ID); t1->SetBranchAddress("parentID",&parent_ID); t1->SetBranchAddress("stepID",&step_ID); t1->SetBranchAddress("rx",&X_pos); t1->SetBranchAddress("ry",&Y_pos); t1->SetBranchAddress("rz",&Z_pos); t1->SetBranchAddress("px",&X_mom); t1->SetBranchAddress("py",&Y_mom); t1->SetBranchAddress("pz",&Z_mom); t1->SetBranchAddress("Eki",&Intial_E); t1->SetBranchAddress("process",Process_ID); for(Int_t q=0;q<nentries;q++){ t1->GetEntry(q); std::string Process(Process_ID); if ( (event_ID==Event_ID && parent_ID==0 && step_ID==0 && Process=="initStep") ) { rx=X_pos; ry=Y_pos; rz=Z_pos; px=X_mom; py=Y_mom; pz=Z_mom; IntialE=Intial_E; Edep=E_dep; cout<<event_ID<<" "<<step_ID<<" "<<Process<<" "<<Edep<<" "<<IntialE<<endl; events->Fill(); } } f1->Close(); } } f->Close(); } } outputfile->Write(); outputfile->Close(); }
#include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> #include <functional> #include <map> #include <stdlib.h> #include "TSystem.h" #include "TCanvas.h" #include "TH1.h" #include "TRint.h" #include "TStyle.h" #include "THStack.h" #include "TTreeReader.h" #include "TTreeReaderValue.h" #include "TFile.h" #include "TTree.h" using namespace std; template<typename T> T strTo(const char* str) { T t; std::stringstream converter(str); converter >> t; return t; } template<typename T> T strTo(const std::string& str) { return strTo<T>(str.c_str()); } bool CmdOptionExists(int argc, char** argv, const std::string& option) { char** begin = argv; char** end = argv + argc; return std::find(begin, end, option) != end; } template<typename T = std::string> T GetCmdOption(int argc, char** argv, const std::string& op
pt + 1 == optionNum) return strTo<T>(*itr); } else { std::string pos = "nth"; if(iOpt == 0) pos = "1st"; else if(iOpt == 1) pos = "2nd"; else if(iOpt == 2) pos = "3rd"; else pos = std::to_string(iOpt + 1) + "th"; exit(EXIT_FAILURE); return 0; } } return 0; } template<typename T = std::string> std::vector<T> GetCmdOptionArray(int argc, char** argv, const std::string& option) { if(!CmdOptionExists(argc, argv, option)) { printf("Missing option %s \n",option.c_str()); abort(); } std::vector<std::string> options; char** begin = argv; char** end = argv + argc; char ** itr = std::find(begin, end, option); while(itr++, itr != end && ((*itr)[0] != '-' || std::isdigit((*itr)[1]))) { if(itr != end) { options.push_back(strTo<T>(*itr)); } } if(options.size() == 0) { printf("Missing parameter for option %s \n",option.c_str()); exit(EXIT_FAILURE); } return options; } void Usage() { cout << endl; cout << "Usage: EnergyDepVSIntialEnergy -p <ProcessedFile name> -o <ouput_filename>" << endl; cout << endl; } int main(int argc, char* argv[]) { if(CmdOptionExists(argc, argv, "-h") || argc==1 ) { Usage(); return EXIT_SUCCESS; } string outputFilename = "output.root"; if(CmdOptionExists(argc, argv, "-o")) { outputFilename = GetCmdOption<string>(argc, argv, "-o"); } else { cout<<"Output Filename not specified, default option is set to output.root "<<endl; } string ProcessedFiles; if(CmdOptionExists(argc, argv, "-p")) { ProcessedFiles = GetCmdOption<string>(argc, argv, "-p"); } else { return EXIT_FAILURE; } Double_t Edep,IntialE,rx,ry,rz,px,py,pz; TFile *outputfile = new TFile(outputFilename.c_str(),"RECREATE"); TTree *events= new TTree("events","simple tree"); events->Branch("Edep",&Edep,"Edep/D"); events->Branch("IntialE",&IntialE,"IntialE/D"); events->Branch("rx",&rx,"rx/D"); events->Branch("ry",&ry,"ry/D"); events->Branch("rz",&rz,"rz/D"); events->Branch("px",&px,"px/D"); events->Branch("py",&py,"py/D"); events->Branch("pz",&pz,"pz/D"); TFile* f = new TFile(ProcessedFiles.c_str()); if( !f->IsOpen() ){ cout<< "Error opening " << ProcessedFiles.c_str() <<endl; } else { if(f->IsZombie()) { cout<<"The file "<<ProcessedFiles.c_str()<<"is corrupted"<<endl; } else{ TTree *t = (TTree*)f->Get("events"); Int_t nentries = (Int_t)t->GetEntries(); Double_t E_dep; Int_t Event_ID; char name_file[200]; t->SetBranchAddress("edep_virtualDetector",&E_dep); t->SetBranchAddress("file",name_file); t->SetBranchAddress("eventID",&Event_ID); for (Int_t i=0;i<nentries;i++){ t->GetEntry(i); std::string filename(name_file); if (E_dep<1000.0) { cout<<filename<<" "<<Event_ID<<endl; TFile* f1 = new TFile(filename.c_str()); TTree *t1 = (TTree*)f1->Get("events"); Int_t nentries = (Int_t)t1->GetEntries(); Double_t X_pos,Y_pos,Z_pos,X_mom,Y_mom,Z_mom, Intial_E; Int_t event_ID, step_ID, parent_ID; char Process_ID[16]; t1->SetBranchAddress("eventID",&event_ID); t1->SetBranchAddress("parentID",&parent_ID); t1->SetBranchAddress("stepID",&step_ID); t1->SetBranchAddress("rx",&X_pos); t1->SetBranchAddress("ry",&Y_pos); t1->SetBranchAddress("rz",&Z_pos); t1->SetBranchAddress("px",&X_mom); t1->SetBranchAddress("py",&Y_mom); t1->SetBranchAddress("pz",&Z_mom); t1->SetBranchAddress("Eki",&Intial_E); t1->SetBranchAddress("process",Process_ID); for(Int_t q=0;q<nentries;q++){ t1->GetEntry(q); std::string Process(Process_ID); if ( (event_ID==Event_ID && parent_ID==0 && step_ID==0 && Process=="initStep") ) { rx=X_pos; ry=Y_pos; rz=Z_pos; px=X_mom; py=Y_mom; pz=Z_mom; IntialE=Intial_E; Edep=E_dep; cout<<event_ID<<" "<<step_ID<<" "<<Process<<" "<<Edep<<" "<<IntialE<<endl; events->Fill(); } } f1->Close(); } } f->Close(); } } outputfile->Write(); outputfile->Close(); }
tion, int optionNum = 1) { if(!CmdOptionExists(argc, argv, option)) { abort(); } char** begin = argv; char** end = argv + argc; char ** itr = std::find(begin, end, option); for(int iOpt = 0; iOpt < optionNum; ++iOpt) { if(itr != end && ++itr != end && ((*itr)[0] != '-' || std::isdigit((*itr)[1]))) { if(iO
function_block-random_span
[]
C++
include/lsFromMesh.hpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
#ifndef LS_FROM_MESH_HPP #define LS_FROM_MESH_HPP #include <lsPreCompileMacros.hpp> #include <lsDomain.hpp> #include <lsMesh.hpp> template <class T, int D> class lsFromMesh { typedef typename lsDomain<T, D>::DomainType hrleDomainType; lsSmartPointer<lsDomain<T, D>> levelSet = nullptr; lsSmartPointer<lsMesh<T>> mesh = nullptr; bool sortPointList = true; public: lsFromMesh(){}; lsFromMesh(lsSmartPointer<lsDomain<T, D>> passedLevelSet, const lsSmartPointer<lsMesh<T>> passedMesh) : levelSet(passedLevelSet), mesh(passedMesh) {} void setLevelSet(lsSmartPointer<lsDomain<T, D>> passedlsDomain) { levelSet = passedlsDomain; } void setMesh(const lsSmartPointer<lsMesh<T>> passedMesh) { mesh = passedMesh; } void setSortPointList(bool passedSortPointList) { sortPointList = passedSortPointList; } void apply() { if (levelSet == nullptr) { lsMessage::getInstance() .addWarning("No level set was passed to lsFromMesh.") .print(); return; } if (mesh == nullptr) { lsMessage::getInstance() .addWarning("No lsMesh<> was supplied to lsFromMesh.") .print(); return; } auto &domain = levelSet->getDomain(); auto &nodes = mesh->getNodes(); auto values = mesh->cellData.getScalarData("LSValues"); if (values == nullptr) { lsMessage::getInstance() .addWarning("Mesh does not contain level set values (\"LSValues\").") .print(); return; } domain.initialize(); if (nodes.empty()) { return; } const hrleGrid<D> &grid = domain.getGrid(); const T gridDelta = grid.getGridDelta(); if (hrleVectorType<T, D>(nodes.front()) != grid.getMinGridPoint()) { domain.insertNextUndefinedPoint(0, grid.getMinGridPoint(), (values->front() < 0) ? lsDomain<T, D>::NEG_VALUE : lsDomain<T, D>::POS_VALUE); } hrleVectorType<hrleIndexType, D> lastIndex(nodes.front()); for (unsigned i = 0; i < D; ++i) { lastIndex[i] = nodes.front()[i] / gridDelta; } auto pointDataIt = nodes.begin(); auto pointDataEnd = nodes.end(); auto valueIt = values->begin(); auto valueEnd = values->end(); hrleVectorType<bool, D> signs(values->front() <= -std::numeric_limits<T>::epsilon()); while (pointDataIt != pointDataEnd && valueIt != valueEnd) { if (std::abs(*valueIt) > 2.5) { ++pointDataIt; ++valueIt; continue; } bool setPoint = true; hrleVectorType<hrleIndexType, D> currentIndex; for (unsigned i = 0; i < D; ++i) { currentIndex[i] = std::round(pointDataIt->at(i) / gridDelta); } for (unsigned i = 0; i < D; ++i) { if (grid.getBoundaryConditions(i) != hrleGrid<D>::INFINITE_BOUNDARY) { if (currentIndex[i] > grid.getMaxBounds(i) || currentIndex[i] < grid.getMinBounds(i)) { setPoint = false; } } } if (setPoint) { domain.insertNextDefinedPoint(0, currentIndex, *valueIt); { bool changeSign = false; for (int i = D - 1; i >= 0; --i) { changeSign = changeSign || (currentIndex[i] > lastIndex[i]); if (changeSign) { signs[i] = *valueIt <= -std::numeric_limits<T>::epsilon(); lastIndex[i] = currentIndex[i]; } } } } hrleVectorType<hrleIndexType, D> nextIndex; ++pointDataIt; ++valueIt; if (pointDataIt == pointDataEnd) { nextIndex = grid.getMaxGridPoint(); nextIndex[D - 1]++; } else { for (unsigned i = 0; i < D; ++i) { nextIndex[i] = std::round(pointDataIt->at(i) / gridDelta); } } for (int q = 0; q < D; q++) { hrleVectorType<hrleIndexType, D> tmp = currentIndex; tmp[q]++; if (tmp[q] > grid.getMaxGridPoint(q)) continue; for (int r = 0; r < q; ++r) tmp[r] = grid.getMinGridPoint(r); if (tmp >= nextIndex) break; domain.insertNextUndefinedPoint(0, tmp, signs[q] ? lsDomain<T, D>::NEG_VALUE : lsDomain<T, D>::POS_VALUE); } } domain.finalize(); } }; PRECOMPILE_PRECISION_DIMENSION(lsFromMesh) #endif
#ifndef LS_FROM_MESH_HPP #define LS_FROM_MESH_HPP #include <lsPreCompileMacros.hpp> #include <lsDomain.hpp> #include <lsMesh.hpp> template <class T, int D> class lsFromMesh { typedef typename lsDomain<T, D>::DomainType hrleDomainType; lsSmartPointer<lsDomain<T, D>> levelSet = nullptr; lsSmartPointer<lsMesh<T>> mesh = nullptr; bool sortPointList = true; public: lsFromMesh(){}; lsFromMesh(lsSmartPointer<lsDomain<T, D>> passedLevelSet, const lsSmartPointer<lsMesh<T>> passedMesh) : levelSet(passedLevelSet), mesh(passedMesh) {} void setLevelSet(lsSmartPointer<lsDomain<T, D>> passedlsDomain) { levelSet = passedlsDomain; } void setMesh(const lsSmartPointer<lsMesh<T>> passedMesh) { mesh = passedMesh; } void setSortPointList(bool passedSortPointList) { sortPointList = passedSortPointList; } void apply() { if (levelSet == nullptr) { lsMessage::getInstance() .addWarning("No level set was passed to lsFromMesh.") .print(); return; } if (mesh == nullptr) { lsMessage::getInstance() .addWarning("No lsMesh<> was supplied to lsFromMesh.") .print(); return; } auto &domain = levelSet->getDomain(); auto &nodes = mesh->getNodes(); auto values = mesh->cellData.getScalarData("LSValues"); if (values == nullptr) { lsMessage::getInstance() .addWarning("Mesh does not contain level set values (\"LSValues\").") .print(); return; } domain.initialize(); if (nodes.empty()) { return; } const hrleGrid<D> &grid = domain.getGrid(); const T gridDelta = grid.getGridDelta(); if (hrleVectorType<T, D>(nodes.front()) != grid.getMinGridPoint()) { domain.insertNextUndefinedPoint(0, grid.getMinGridPoint(), (values->front() < 0) ? lsDomain<T, D>::NEG_VALUE : lsDomain<T, D>::POS_VALUE); } hrleVectorType<hrleIndexType, D> lastIndex(nodes.front()); for (unsigned i = 0; i < D; ++i) { lastIndex[i] = nodes.front()[i] / gridDelta; } auto pointDataIt = nodes.begin(); auto pointDataEnd = nodes.end(); auto valueIt = values->begin(); auto valueEnd = values->end(); hrleVectorType<bool, D> signs(values->front() <= -std::numeric_limits<T>::epsilon()); while (pointDataIt != pointDataEnd && valueIt != valueEnd) { if (std::abs(*valueIt) > 2.5) { ++pointDataIt; ++valueIt; continue; } bool setPoint = true; hrleVectorType<hrleIndexType, D> currentIndex; for (unsigned i = 0; i < D; ++i) { currentIndex[i] = std::round(pointDataIt->at(i) / gridDelta); } for (unsigned i = 0; i < D; ++i) { if (grid.getBoundaryConditions(i) != hrleGrid<D>::INFINITE_BOUNDARY) { if (currentIndex[i] > grid.getMaxBounds(i) || currentIndex[i] < grid.getMinBounds(i)) { setPoint = false; } } } if (setPoint) { domain.insertNextDefinedPoint(0, currentIndex, *valueIt); { bool changeSign = false; for (int i = D - 1; i >= 0; --i) { changeSign = changeSign || (currentIndex[i] > lastIndex[i]);
for (unsigned i = 0; i < D; ++i) { nextIndex[i] = std::round(pointDataIt->at(i) / gridDelta); } } for (int q = 0; q < D; q++) { hrleVectorType<hrleIndexType, D> tmp = currentIndex; tmp[q]++; if (tmp[q] > grid.getMaxGridPoint(q)) continue; for (int r = 0; r < q; ++r) tmp[r] = grid.getMinGridPoint(r); if (tmp >= nextIndex) break; domain.insertNextUndefinedPoint(0, tmp, signs[q] ? lsDomain<T, D>::NEG_VALUE : lsDomain<T, D>::POS_VALUE); } } domain.finalize(); } }; PRECOMPILE_PRECISION_DIMENSION(lsFromMesh) #endif
if (changeSign) { signs[i] = *valueIt <= -std::numeric_limits<T>::epsilon(); lastIndex[i] = currentIndex[i]; } } } } hrleVectorType<hrleIndexType, D> nextIndex; ++pointDataIt; ++valueIt; if (pointDataIt == pointDataEnd) { nextIndex = grid.getMaxGridPoint(); nextIndex[D - 1]++; } else {
random
[ { "content": "// implement own velocity field\n\nclass velocityField : public lsVelocityField<double> {\n\npublic:\n\n double getScalarVelocity(const std::array<double, 3> & /*coordinate*/,\n\n int /*material*/,\n\n const std::array<double, 3> & /*normalVecto...
C++
qt/QtXdagWallet/pwddialog.cpp
sgaragagghu/QtXdagWallet
850fac4c6714edde4d91e58a8ca5a2d4602b9937
#include "PwdDialog.h" #include "ui_pwddialog.h" #include <QKeyEvent> PwdDialog::PwdDialog(QWidget *parent, PWD_DLG_TYPE type) : QDialog(parent), mDlgType(type), ui(new Ui::PwdDialog) { ui->setupUi(this); m_pLable = new QLabel; m_pLEPwd = new PwdLineEdit; m_pPBOK = new QPushButton(tr("OK")); m_pLable->setFixedSize(100,25); m_pLEPwd->setFixedSize(200,25); m_pPBOK->setFixedSize(60,25); m_pLable->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pHBLInputPwd = new QHBoxLayout; m_pHBLInputPwd->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pHBLInputPwd->addWidget(m_pLable); m_pHBLInputPwd->addWidget(m_pLEPwd); m_pHBLButton = new QHBoxLayout; m_pHBLButton->addWidget(m_pPBOK,Qt::AlignHCenter); m_pVBLGlobal = new QVBoxLayout; m_pVBLGlobal->setAlignment(Qt::AlignHCenter); m_pVBLGlobal->addLayout(m_pHBLInputPwd); m_pVBLGlobal->addLayout(m_pHBLButton); this->setLayout(m_pVBLGlobal); m_pLEPwd->installEventFilter(this); m_pPBOK->installEventFilter(this); setWindowIcon(QIcon(":/icon/xdagwallet.ico")); setWindowTitle(tr("Dagger Wallet(XDAG)")); setFixedSize(320,70); switch(type){ case DLG_TYPE_PWD: m_pLable->setText(tr("input password")); break; case DLG_SET_PWD: m_pLable->setText(tr("set password")); break; case DLG_RETYPE_PWD: m_pLable->setText(tr("confirm password")); break; case DLG_TYPE_RDM: m_pLable->setText(tr("set random keys")); break; } if(type == DLG_SET_PWD || type == DLG_RETYPE_PWD){ mPwdRegExp.setPatternSyntax(QRegExp::RegExp); mPwdRegExp.setCaseSensitivity(Qt::CaseSensitive); mPwdRegExp.setPattern(QString("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$")); } connect(m_pPBOK,SIGNAL(clicked(bool)),this,SLOT(onBtnOKClicked())); } PwdDialog::~PwdDialog() { delete ui; } void PwdDialog::closeDialog() { this->close(); } void PwdDialog::onBtnOKClicked() { QString str = m_pLEPwd->text(); switch(mDlgType){ case DLG_TYPE_PWD: emit sendTypePwd(str); break; case DLG_SET_PWD: if(!mPwdRegExp.exactMatch(str)){ m_pErrDlg = new ErrorDialog(0,en_event_pwd_format_error); m_pErrDlg->exec(); return; } emit sendSetPwd(str); break; case DLG_RETYPE_PWD: if(!mPwdRegExp.exactMatch(str)){ m_pErrDlg = new ErrorDialog(0,en_event_pwd_format_error); m_pErrDlg->exec(); return; } emit sendRetypePwd(str); break; case DLG_TYPE_RDM: emit sendRdm(str); break; } this->accept(); } bool PwdDialog::eventFilter(QObject *obj, QEvent *event) { if(obj == m_pLEPwd || obj == m_pPBOK){ switch (event->type()) { case QEvent::MouseMove: case QEvent::MouseButtonDblClick: break; case QEvent::KeyPress: { QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(event); if(pKeyEvent->matches(QKeySequence::SelectAll) || pKeyEvent->matches(QKeySequence::Copy) || pKeyEvent->matches(QKeySequence::Paste)) { return true; } if(pKeyEvent->key() == Qt::Key_Tab || pKeyEvent->key() == Qt::Key_Left || pKeyEvent->key() == Qt::Key_Right || pKeyEvent->key() == Qt::Key_Up || pKeyEvent->key() == Qt::Key_Down){ return true; } } default: break; } } return QDialog::eventFilter(obj, event); } void PwdDialog::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Tab: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Down: break; default: QDialog::keyPressEvent(event); } }
#include "PwdDialog.h" #include "ui_pwddialog.h" #include <QKeyEvent> PwdDialog::PwdDialog(QWidget *parent, PWD_DLG_TYPE type) : QDialog(parent), mDlgType(type), ui(new Ui::PwdDialog) { ui->setupUi(this); m_pLable = new QLabel; m_pLEPwd = new PwdLineEdit; m_pPBOK = new QPushButton(tr("OK")); m_pLable->setFixedSize(100,25); m_pLEPwd->setFixedSize(200,25); m_pPBOK->setFixedSize(60,25); m_pLable->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pHBLInputPwd = new QHBoxLayout; m_pHBLInputPwd->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_pHBLInputPwd->addWidget(m_pLable); m_pHBLInputPwd->addWidget(m_pLEPwd); m_pHBLButton = new QHBoxLayout; m_pHBLButton->addWidget(m_pPBOK,Qt::AlignHCenter); m_pVBLGlobal = new QVBoxLayout; m_pVBLGlobal->setAlignment(Qt::AlignHCenter); m_pVBLGlobal->addLayout(m_pHBLInputPwd); m_pVBLGlobal->addLayout(m_pHBLButton); this->setLayout(m_pVBLGlobal); m_pLEPwd->installEventFilter(this); m_pPBOK->installEventFilter(this); setWindowIcon(QIcon(":/icon/xdagwallet.ico")); setWindowTitle(tr("Dagger Wallet(XDAG)")); setFixedSize(320,70); switch(type){ case DLG_TYPE_PWD: m_pLable->setText(tr("input password")); break; case DLG_SET_PWD: m_pLable->setText(tr("set password")); break; case DLG_RETYPE_PWD: m_pLable->setText(tr("confirm password")); break; case DLG_TYPE_RDM: m_pLable->setText(tr("set random keys")); break; } if(type == DLG_SET_PWD || type == DLG_RETYPE_PWD){ mPwdRegExp.setPatternSyntax(QRegExp::RegExp); mPwdRegExp.setCaseSensitivity(Qt::CaseSensitive); mPwdRegExp.setPattern(QString("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$")); } connect(m_pPBOK,SIGNAL(clicked(bool)),this,SLOT(onBtnOKClicked())); } PwdDialog::~PwdDialog() { delete ui; } void PwdDialog::closeDialog() { this->close(); } void PwdDialog::onBtnOKClicked() { QString str = m_pLEPwd->text(); switch(mDlgType){ case DLG_TYPE_PWD: emit sendTypePwd(str); break; case DLG_SET_PWD: if(!mPwdRegExp.exactMatch(str)){ m_pErrDlg = new ErrorDialog(0,en_event_pwd_format_error); m_pErrDlg->exec(); return; } emit sendSetPwd(str); break; case DLG_RETYPE_PWD: if(!mPwdRegExp.exactMatch(str)){ m_pErrDlg = new ErrorDialog(0,en_event_pwd_format_error); m_pErrDlg->exec(); return; } emit sendRetypePwd(str); break; case DLG_TYPE_RDM: emit sendRdm(str); break; } this->accept(); } bool PwdDialog::eventFilter(QObject *obj, QEvent *event) { if(obj == m_pLEPwd || obj == m_pPBOK){ switch (event->type()) { case QEvent::MouseMove: case QEvent::MouseButtonDblClick: break; case QEvent::KeyPress: { QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(event);
void PwdDialog::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Tab: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Up: case Qt::Key_Down: break; default: QDialog::keyPressEvent(event); } }
if(pKeyEvent->matches(QKeySequence::SelectAll) || pKeyEvent->matches(QKeySequence::Copy) || pKeyEvent->matches(QKeySequence::Paste)) { return true; } if(pKeyEvent->key() == Qt::Key_Tab || pKeyEvent->key() == Qt::Key_Left || pKeyEvent->key() == Qt::Key_Right || pKeyEvent->key() == Qt::Key_Up || pKeyEvent->key() == Qt::Key_Down){ return true; } } default: break; } } return QDialog::eventFilter(obj, event); }
function_block-function_prefix_line
[ { "content": "#define OBJ_id_it_encKeyPairTypes OBJ_id_it,3L\n\n\n", "file_path": "qt/QtXdagWallet/win64_dependency/include/openssl/obj_mac.h", "rank": 0, "score": 156120.08268075265 }, { "content": "#define OBJ_id_it_signKeyPairTypes OBJ_id_it,2L\n\n\n", "file...
C++
extlib/include/xyginext/ecs/systems/DynamicTreeSystem.hpp
fallahn/speljongen
57cb5e09eec7db8c21ee7b3e7943fa0a76738c51
#pragma once #include "xyginext/ecs/System.hpp" #include <SFML/Graphics/Rect.hpp> #include <vector> #include <limits> #include <cstdint> #include <array> namespace xy { struct TreeNode final { static constexpr std::int32_t Null = -1; bool isLeaf() const { return childA == Null; } sf::FloatRect fatBounds; xy::Entity entity; union { std::int32_t parent; std::int32_t next; }; std::int32_t childA = Null; std::int32_t childB = Null; std::int32_t height = Null; }; class XY_EXPORT_API DynamicTreeSystem final : public xy::System { public: explicit DynamicTreeSystem(xy::MessageBus&); void process(float) override; void onEntityAdded(xy::Entity) override; void onEntityRemoved(xy::Entity) override; std::vector<xy::Entity> query(sf::FloatRect area, std::uint64_t filter = std::numeric_limits<std::uint64_t>::max()) const; private: std::int32_t addToTree(xy::Entity); void removeFromTree(std::int32_t); bool moveNode(std::int32_t, sf::FloatRect, sf::Vector2f); sf::FloatRect getFatAABB(std::int32_t) const; std::int32_t getMaxBalance() const; float getAreaRatio() const; std::int32_t allocateNode(); void freeNode(std::int32_t); void insertLeaf(std::int32_t); void removeLeaf(std::int32_t); std::int32_t balance(std::int32_t); std::int32_t computeHeight() const; std::int32_t computeHeight(std::int32_t) const; void validateStructure(std::int32_t) const; void validateMetrics(std::int32_t) const; std::int32_t m_root; std::size_t m_nodeCount; std::size_t m_nodeCapacity; std::vector<TreeNode> m_nodes; std::int32_t m_freeList; std::size_t m_path; std::size_t m_insertionCount; }; namespace Detail { template <typename T, std::size_t SIZE> class FixedStack final { public: T pop() { XY_ASSERT(m_size != 0, "Stack is empty!"); m_size--; return m_data[m_size]; } void push(T data) { XY_ASSERT(m_size < m_data.size(), "Stack is full!"); m_data[m_size++] = data; } std::size_t size() const { return m_size; } private: std::array<T, SIZE> m_data; std::size_t m_size = 0; }; } }
#pragma once #include "xyginext/ecs/System.hpp" #include <SFML/Graphics/Rect.hpp> #include <vector> #include <limits> #include <cstdint> #include <array> namespace xy { struct TreeNode final { static constexpr std::int32_t Null = -1; bool isLeaf() const { return childA == Null; } sf::FloatRect fatBounds; xy::Entity entity; union { std::int32_t parent;
: public xy::System { public: explicit DynamicTreeSystem(xy::MessageBus&); void process(float) override; void onEntityAdded(xy::Entity) override; void onEntityRemoved(xy::Entity) override; std::vector<xy::Entity> query(sf::FloatRect area, std::uint64_t filter = std::numeric_limits<std::uint64_t>::max()) const; private: std::int32_t addToTree(xy::Entity); void removeFromTree(std::int32_t); bool moveNode(std::int32_t, sf::FloatRect, sf::Vector2f); sf::FloatRect getFatAABB(std::int32_t) const; std::int32_t getMaxBalance() const; float getAreaRatio() const; std::int32_t allocateNode(); void freeNode(std::int32_t); void insertLeaf(std::int32_t); void removeLeaf(std::int32_t); std::int32_t balance(std::int32_t); std::int32_t computeHeight() const; std::int32_t computeHeight(std::int32_t) const; void validateStructure(std::int32_t) const; void validateMetrics(std::int32_t) const; std::int32_t m_root; std::size_t m_nodeCount; std::size_t m_nodeCapacity; std::vector<TreeNode> m_nodes; std::int32_t m_freeList; std::size_t m_path; std::size_t m_insertionCount; }; namespace Detail { template <typename T, std::size_t SIZE> class FixedStack final { public: T pop() { XY_ASSERT(m_size != 0, "Stack is empty!"); m_size--; return m_data[m_size]; } void push(T data) { XY_ASSERT(m_size < m_data.size(), "Stack is full!"); m_data[m_size++] = data; } std::size_t size() const { return m_size; } private: std::array<T, SIZE> m_data; std::size_t m_size = 0; }; } }
std::int32_t next; }; std::int32_t childA = Null; std::int32_t childB = Null; std::int32_t height = Null; }; class XY_EXPORT_API DynamicTreeSystem final
random
[]
C++
src/platform/shm_win.cpp
nickhuangxinyu/cpp-ipc
64f4104b741b6f283906d01177d4e70bcdb8d6a0
#include "shm.h" #include <Windows.h> #include <string> #include <utility> #include "def.h" #include "log.h" #include "pool_alloc.h" #include "platform/to_tchar.h" #include "platform/get_sa.h" #include "memory/resource.h" namespace { struct id_info_t { HANDLE h_ = NULL; void* mem_ = nullptr; std::size_t size_ = 0; }; } namespace ipc { namespace shm { id_t acquire(char const * name, std::size_t size, unsigned mode) { if (name == nullptr || name[0] == '\0') { ipc::error("fail acquire: name is empty\n"); return nullptr; } HANDLE h; auto fmt_name = ipc::detail::to_tchar(ipc::string{"__IPC_SHM__"} + name); if (mode == open) { h = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, fmt_name.c_str()); } else { h = ::CreateFileMapping(INVALID_HANDLE_VALUE, detail::get_sa(), PAGE_READWRITE | SEC_COMMIT, 0, static_cast<DWORD>(size), fmt_name.c_str()); if ((mode == create) && (::GetLastError() == ERROR_ALREADY_EXISTS)) { ::CloseHandle(h); h = NULL; } } if (h == NULL) { ipc::error("fail CreateFileMapping/OpenFileMapping[%d]: %s\n", static_cast<int>(::GetLastError()), name); return nullptr; } auto ii = mem::alloc<id_info_t>(); ii->h_ = h; ii->size_ = size; return ii; } void * get_mem(id_t id, std::size_t * size) { if (id == nullptr) { ipc::error("fail get_mem: invalid id (null)\n"); return nullptr; } auto ii = static_cast<id_info_t*>(id); if (ii->mem_ != nullptr) { if (size != nullptr) *size = ii->size_; return ii->mem_; } if (ii->h_ == NULL) { ipc::error("fail to_mem: invalid id (h = null)\n"); return nullptr; } LPVOID mem = ::MapViewOfFile(ii->h_, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (mem == NULL) { ipc::error("fail MapViewOfFile[%d]\n", static_cast<int>(::GetLastError())); return nullptr; } MEMORY_BASIC_INFORMATION mem_info; if (::VirtualQuery(mem, &mem_info, sizeof(mem_info)) == 0) { ipc::error("fail VirtualQuery[%d]\n", static_cast<int>(::GetLastError())); return nullptr; } ii->mem_ = mem; ii->size_ = static_cast<std::size_t>(mem_info.RegionSize); if (size != nullptr) *size = ii->size_; return static_cast<void *>(mem); } void release(id_t id) { if (id == nullptr) { ipc::error("fail release: invalid id (null)\n"); return; } auto ii = static_cast<id_info_t*>(id); if (ii->mem_ == nullptr || ii->size_ == 0) { ipc::error("fail release: invalid id (mem = %p, size = %zd)\n", ii->mem_, ii->size_); } else ::UnmapViewOfFile(static_cast<LPCVOID>(ii->mem_)); if (ii->h_ == NULL) { ipc::error("fail release: invalid id (h = null)\n"); } else ::CloseHandle(ii->h_); mem::free(ii); } void remove(id_t id) { if (id == nullptr) { ipc::error("fail release: invalid id (null)\n"); return; } release(id); } void remove(char const * name) { if (name == nullptr || name[0] == '\0') { ipc::error("fail remove: name is empty\n"); return; } } } }
#include "shm.h" #include <Windows.h> #include <string> #include <utility> #include "def.h" #include "log.h" #include "pool_alloc.h" #include "platform/to_tchar.h" #include "platform/get_sa.h" #include "memory/resource.h" namespace { struct id_info_t { HANDLE h_ = NULL; void* mem_ = nullptr; std::size_t size_ = 0; }; } namespace ipc { namespace shm { id_t acquire(char const * name, std::size_t size, unsigned mode) { if (name == nullptr || name[0] == '\0') { ipc::error("fail acquire: name is empty\n"); return nullptr; } HANDLE h; auto fmt_name = ipc::detail::to_tchar(ipc::string{"__IPC_SHM__"} + name); if (mode == open) { h = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, fmt_name.c_str()); } else { h = ::CreateFileMapping(INVALID_HANDLE_VALUE, detail::get_sa(), PAGE_READWRITE | SEC_COMMIT, 0, static_cast<DWORD>(size), fmt_name.c_str()); if ((mode == create) && (::GetLastError() == ERROR_ALREADY_EXISTS)) { ::CloseHandle(h); h = NULL; } } if (h == NULL) { ipc::error("fail CreateFileMapping/OpenFileMapping[%d]: %s\n", static_cast<int>(::GetLastError()), name); return nullptr; } auto ii = mem::alloc<id_info_t>(); ii->h_ = h; ii->size_ = size; return ii; } void * get_mem(id_t id, std::size_t * size) { if (id == nullptr) { ipc::error("fail get_mem: invalid id (null)\n"); return nullptr; } auto ii = static_cast<id_info_t*>(id); if (ii->mem_ != nullptr) { if (size != nullptr) *size = ii->size_; return ii->mem_; } if (ii->h_ == NULL) { ipc::error("fail to_mem: invalid id (h = null)\n"); return nullptr; } LPVOID mem = ::MapViewOfFile(ii->h_, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (mem == NULL) { ipc::error("fail MapViewOfFile[%d]\n", static_cast<int>(::GetLastError())); return nullptr; } MEMORY_BASIC_INFORMATION mem_info; if (::VirtualQuery(mem, &mem_info, sizeof(mem_info)) == 0) { ipc::error("fail VirtualQuery[%d]\n", static_cast<int>(::GetLastError())); return nullptr; }
void release(id_t id) { if (id == nullptr) { ipc::error("fail release: invalid id (null)\n"); return; } auto ii = static_cast<id_info_t*>(id); if (ii->mem_ == nullptr || ii->size_ == 0) { ipc::error("fail release: invalid id (mem = %p, size = %zd)\n", ii->mem_, ii->size_); } else ::UnmapViewOfFile(static_cast<LPCVOID>(ii->mem_)); if (ii->h_ == NULL) { ipc::error("fail release: invalid id (h = null)\n"); } else ::CloseHandle(ii->h_); mem::free(ii); } void remove(id_t id) { if (id == nullptr) { ipc::error("fail release: invalid id (null)\n"); return; } release(id); } void remove(char const * name) { if (name == nullptr || name[0] == '\0') { ipc::error("fail remove: name is empty\n"); return; } } } }
ii->mem_ = mem; ii->size_ = static_cast<std::size_t>(mem_info.RegionSize); if (size != nullptr) *size = ii->size_; return static_cast<void *>(mem); }
function_block-function_prefix_line
[ { "content": "// A builtin parameterized test name generator which returns the result of\n\n// testing::PrintToString.\n\nstruct PrintToStringParamName {\n\n template <class ParamType>\n\n std::string operator()(const TestParamInfo<ParamType>& info) const {\n\n return PrintToString(info.param);\n\n }\n\n}...
C++
test/api/union/hyperloglog_test.cpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <unordered_set> #include <vector> #include <fstream> #include <iostream> #include <chopper/union/hyperloglog.hpp> #include <seqan3/io/sequence_file/input.hpp> #include <seqan3/test/tmp_filename.hpp> struct input_traits : public seqan3::sequence_file_input_default_traits_dna { using sequence_alphabet = char; using sequence_legal_alphabet = char; using sequence_contianer = std::vector<sequence_alphabet>; }; using sequence_file_type = seqan3::sequence_file_input<input_traits, seqan3::fields<seqan3::field::seq>>; TEST(hyperloglog_test, initialization) { size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); EXPECT_EQ(sketch.registerSize(), m); EXPECT_EQ(sketch.estimate(), 0.0); } TEST(hyperloglog_test, add_and_estimate_small) { size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); sketch.add("bla", 3); sketch.add("bli", 3); sketch.add("blub", 4); sketch.add("bloink", 6); sketch.add("blubba", 6); sketch.add("blumpf", 6); sketch.add("blarkse", 7); sketch.add("bladuzel", 8); EXPECT_NEAR(sketch.estimate(), 9.205826318, 0.0000001); } TEST(hyperloglog_test, add_and_estimate_large) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); std::unordered_set<std::string> control; sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { control.insert(std::string(c_seq_it, k)); sketch.add(c_seq_it, k); ++c_seq_it; } } EXPECT_NEAR(sketch.estimate(), control.size(), control.size() * 1.04 / 4); } TEST(hyperloglog_test, merge_and_merge_SIMD) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 5; size_t const m = 1 << b; hyperloglog full_sketch(b); hyperloglog merge_sketch(b); hyperloglog merge_SIMD_sketch(b); std::vector<hyperloglog> partial_sketches; sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { partial_sketches.emplace_back(b); char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { partial_sketches.back().add(c_seq_it, k); full_sketch.add(c_seq_it, k); ++c_seq_it; } } double merge_SIMD_estimate; for (auto & partial_sketch : partial_sketches) { merge_sketch.merge(partial_sketch); merge_SIMD_estimate = merge_SIMD_sketch.merge_and_estimate_SIMD(partial_sketch); } EXPECT_EQ(full_sketch.estimate(), merge_sketch.estimate()); EXPECT_EQ(full_sketch.estimate(), merge_SIMD_sketch.estimate()); } TEST(hyperloglog_test, dump_and_restore) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 4; size_t const m = 1 << b; hyperloglog dump_sketch(b); hyperloglog restore_sketch(b); sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { dump_sketch.add(c_seq_it, k); ++c_seq_it; } } seqan3::test::tmp_filename dump_filename{"dump.hll"}; std::ofstream ostrm(dump_filename.get_path(), std::ios::binary); dump_sketch.dump(ostrm); std::ifstream istrm(dump_filename.get_path(), std::ios::binary); restore_sketch.restore(istrm); EXPECT_EQ(dump_sketch.estimate(), restore_sketch.estimate()); }
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <unordered_set> #include <vector> #include <fstream> #include <iostream> #include <chopper/union/hyperloglog.hpp> #include <seqan3/io/sequence_file/input.hpp> #include <seqan3/test/tmp_filename.hpp> struct input_traits : public seqan3::sequence_file_input_default_traits_dna { using sequence_alphabet = char; using sequence_legal_alphabet = char; using sequence_contianer = std::vector<sequence_alphabet>; }; using sequence_file_type = seqan3::sequence_file_input<input_traits, seqan3::fields<seqan3::field::seq>>; TEST(hyperloglog_test, initialization) { size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); EXPECT_EQ(sketch.registerSize(), m); EXPECT_EQ(sketch.estimate(), 0.0); } TEST(hyperloglog_test, add_and_estimate_small) { size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); sketch.add("bla", 3); sketch.add("bli", 3); sketch.add("blub", 4); sketch.add("bloink", 6); sketch.add("blubba", 6); sketch.add("blumpf", 6); sketch.add("blarkse", 7); sketch.add("bladuzel", 8); EXPECT_NEAR(sketch.estimate(), 9.205826318, 0.0000001); }
TEST(hyperloglog_test, merge_and_merge_SIMD) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 5; size_t const m = 1 << b; hyperloglog full_sketch(b); hyperloglog merge_sketch(b); hyperloglog merge_SIMD_sketch(b); std::vector<hyperloglog> partial_sketches; sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { partial_sketches.emplace_back(b); char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { partial_sketches.back().add(c_seq_it, k); full_sketch.add(c_seq_it, k); ++c_seq_it; } } double merge_SIMD_estimate; for (auto & partial_sketch : partial_sketches) { merge_sketch.merge(partial_sketch); merge_SIMD_estimate = merge_SIMD_sketch.merge_and_estimate_SIMD(partial_sketch); } EXPECT_EQ(full_sketch.estimate(), merge_sketch.estimate()); EXPECT_EQ(full_sketch.estimate(), merge_SIMD_sketch.estimate()); } TEST(hyperloglog_test, dump_and_restore) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 4; size_t const m = 1 << b; hyperloglog dump_sketch(b); hyperloglog restore_sketch(b); sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { dump_sketch.add(c_seq_it, k); ++c_seq_it; } } seqan3::test::tmp_filename dump_filename{"dump.hll"}; std::ofstream ostrm(dump_filename.get_path(), std::ios::binary); dump_sketch.dump(ostrm); std::ifstream istrm(dump_filename.get_path(), std::ios::binary); restore_sketch.restore(istrm); EXPECT_EQ(dump_sketch.estimate(), restore_sketch.estimate()); }
TEST(hyperloglog_test, add_and_estimate_large) { std::string input_file = DATADIR"small.fa"; size_t const k = 16; size_t const b = 4; size_t const m = 1 << b; hyperloglog sketch(b); std::unordered_set<std::string> control; sequence_file_type seq_file{input_file}; for (auto && [seq] : seq_file) { char* c_seq_it = &*seq.begin(); char* end = c_seq_it + seq.size(); while(c_seq_it + k <= end) { control.insert(std::string(c_seq_it, k)); sketch.add(c_seq_it, k); ++c_seq_it; } } EXPECT_NEAR(sketch.estimate(), control.size(), control.size() * 1.04 / 4); }
function_block-full_function
[ { "content": "struct input_traits : public seqan3::sequence_file_input_default_traits_dna\n\n{\n\n using sequence_alphabet = seqan3::dna4;\n\n};\n\n\n\nint main(int argc, const char *argv [])\n\n{\n\n seqan3::argument_parser parser{\"measure_hyperloglog\", argc, argv,\n\n ...
C++
02Segundo/Estructura_de_Datos_ED/PracticaFinal/src/prueba.cpp
elsudano/Facultad
8ff2c5904f0a38a3a0682e040da4439f2bc872f2
#include <fstream> #include <iostream> #include <cstdlib> #include <ctime> #include <sstream> #include "ArbolGeneral.h" #include "Personas.h" #include "QuitaComentarios.h" #include "Preguntas.h" using namespace std; void imprime_arbol_con_formato(string nom, ArbolGeneral<int> &ab){ ArbolGeneral<int>::iter_preorden it_tree = ab.begin(); cout << "Arbol " << nom << ": " << ab << endl; cout << "Etiquetas ordenadas de " << nom << ": "; for (; it_tree != ab.end(); ++it_tree) cout << (*it_tree) << " "; cout << (*it_tree) << endl; } int main(int argc, char *argv[]) { fstream f,fdp,resultado; f.open (argv[1], fstream::in | fstream::out); if (!f.is_open()) { cout << "No puedo abrir el fichero: " << argv[1]<< endl; exit(1); } fdp.open (argv[2], fstream::in | fstream::out); if (!fdp.is_open()) { cout << "No puedo abrir el fichero: " << argv[2]<< endl; exit(1); } ArbolGeneral<int> ab1, ab2, ab3; cout << "Voy a leer los dos arboles" << endl << endl; f>>ab1; fdp>>ab2; f.close(); fdp.close(); ArbolGeneral<int>::iter_preorden it_tree = ab1.begin(); cout << "He leido los dos arboles correctamente" << endl; imprime_arbol_con_formato("AB1",ab1); imprime_arbol_con_formato("AB2",ab2); cout << endl; cout << "Pruebo que se pueden copiar los arboles del AB2 al AB3" << endl; ab3 = ab2; imprime_arbol_con_formato("AB3",ab3); cout << endl; cout << "Voy a poner el AB2 como subarbol de AB1 en el nodo 5 (cuando tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 5; ++it_tree); cout << "Encuentro el nodo: " << (*it_tree) << endl; ab1.asignar_subarbol(ab2, it_tree.GetNodo()); cout << "Arbol AB1 despúes de asignar subarbol AB2: " << endl; imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Voy a poner el AB3 como subarbol de AB1 en el nodo 10 (cuando NO tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 10; ++it_tree); cout << "Encuentro el nodo: " << (*it_tree) << endl; ab1.asignar_subarbol(ab3, it_tree.GetNodo()); cout << "Arbol AB1 despúes de asignar subarbol AB3: " << endl; imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Voy a podar el subarbol izquierdo del nodo 6 del árbol AB1" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 6; ++it_tree); ab1.podar_hijomasizquierda(it_tree.GetNodo(), ab2); imprime_arbol_con_formato("AB1",ab1); cout << "Este es el árbol que hemos podado" << endl; imprime_arbol_con_formato("AB2",ab2); cout << endl; cout << "Voy a podar el subarbol derecho del nodo 7 del árbol AB1" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 7; ++it_tree); ab1.podar_hermanoderecha(it_tree.GetNodo(), ab3); imprime_arbol_con_formato("AB1",ab1); cout << "Este es el árbol que hemos podado" << endl; imprime_arbol_con_formato("AB3",ab3); cout << endl; cout << "Insertamos en el nodo 200 del árbol AB1 el árbol AB3 (cuando tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 200; ++it_tree); ab1.insertar_hijomasizquierda(it_tree.GetNodo(),ab3); imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Insertamos en el nodo 9 del árbol AB1 el árbol AB2 (cuando NO tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 9; ++it_tree); ab1.insertar_hermanoderecha(it_tree.GetNodo(),ab2); imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Por ultimo guardamos en el fichero: resultado.tree el árbol AB1" << endl; string contenido; resultado.open (argv[3], fstream::in | fstream::out); if (!resultado.is_open()) { cout << "No puedo abrir el fichero: " << argv[3]<< endl; exit(1); } resultado<<ab1; resultado.seekp(0); getline(resultado,contenido); cout << contenido << endl; resultado.close(); }
#include <fstream> #include <iostream> #include <cstdlib> #include <ctime> #include <sstream> #include "ArbolGeneral.h" #include "Personas.h" #include "QuitaComentarios.h" #include "Preguntas.h" using namespace std; void imprime_arbol_con_formato(string nom, ArbolGeneral<int> &ab){ ArbolGeneral<int>::iter_preorden it_tree = ab.begin(); cout << "Arbol " << nom << ": " << ab << endl; cout << "Etiquetas ordenadas de " << nom << ": "; for (; it_tree != ab.end(); ++it_tree) cout << (*it_tree) << " "; cout << (*it_tree) << endl; } int main(int argc, char *argv[]) { fstream f,fdp,resultado; f.open (argv[1], fstream::in | fstream::out); if (!f.is_open()) { cout << "No puedo abrir el fichero: " << argv[1]<< endl; exit(1); } fdp.open (argv[2], fstream::in | fstream::out); if (!fdp.is_open()) { cout << "No puedo abrir el fichero: " << argv[2]<< endl; exit(1); } ArbolGeneral<int> ab1, ab2, ab3; cout << "Voy a leer los dos arboles" << endl << endl; f>>ab1; fdp>>ab2; f.close(); fdp.close(); ArbolGeneral<int>::iter_preorden it_tree = ab1.begin(); cout << "He leido los dos arboles correctamente" << endl; imprime_arbol_con_formato("AB1",ab1); imprime_arbol_con_formato("AB2",ab2); cout << endl; cout << "Pruebo que se pueden copiar los arboles del AB2 al AB3" << endl; ab3 = ab2; imprime_arbol_con_formato("AB3",ab3); cout << endl; cout << "Voy a poner el AB2 como subarbol de AB1 en el nodo 5 (cuando tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 5; ++it_tree); cout << "Encuentro el nodo: " << (*it_tree) << endl; ab1.asignar_subarbol(ab2, it_tree.GetNodo()); cout << "Arbol AB1 despúes de asignar subarbol AB2: " << endl; imprime_arbol_con_formato("AB1",ab1); cout << endl; co
ut << "Voy a poner el AB3 como subarbol de AB1 en el nodo 10 (cuando NO tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 10; ++it_tree); cout << "Encuentro el nodo: " << (*it_tree) << endl; ab1.asignar_subarbol(ab3, it_tree.GetNodo()); cout << "Arbol AB1 despúes de asignar subarbol AB3: " << endl; imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Voy a podar el subarbol izquierdo del nodo 6 del árbol AB1" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 6; ++it_tree); ab1.podar_hijomasizquierda(it_tree.GetNodo(), ab2); imprime_arbol_con_formato("AB1",ab1); cout << "Este es el árbol que hemos podado" << endl; imprime_arbol_con_formato("AB2",ab2); cout << endl; cout << "Voy a podar el subarbol derecho del nodo 7 del árbol AB1" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 7; ++it_tree); ab1.podar_hermanoderecha(it_tree.GetNodo(), ab3); imprime_arbol_con_formato("AB1",ab1); cout << "Este es el árbol que hemos podado" << endl; imprime_arbol_con_formato("AB3",ab3); cout << endl; cout << "Insertamos en el nodo 200 del árbol AB1 el árbol AB3 (cuando tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 200; ++it_tree); ab1.insertar_hijomasizquierda(it_tree.GetNodo(),ab3); imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Insertamos en el nodo 9 del árbol AB1 el árbol AB2 (cuando NO tiene hijos)" << endl; it_tree = ab1.begin(); for (; (*it_tree) != 9; ++it_tree); ab1.insertar_hermanoderecha(it_tree.GetNodo(),ab2); imprime_arbol_con_formato("AB1",ab1); cout << endl; cout << "Por ultimo guardamos en el fichero: resultado.tree el árbol AB1" << endl; string contenido; resultado.open (argv[3], fstream::in | fstream::out); if (!resultado.is_open()) { cout << "No puedo abrir el fichero: " << argv[3]<< endl; exit(1); } resultado<<ab1; resultado.seekp(0); getline(resultado,contenido); cout << contenido << endl; resultado.close(); }
function_block-function_prefixed
[]
C++
HybridRenderer/HybridRenderer/Camera.cpp
lbondi7/HybridRenderer
592ff5c4ea9039bc79a99e20c848f11e2669f885
#include "Camera.h" #include "Initilizers.h" #include "ImGUI_.h" #include <algorithm> Camera::~Camera() { } void Camera::init(DeviceContext* deviceContext, const VkExtent2D& _extent) { viewport = { 0, 0, 1, 1 }; scissor = { 0, 0, 1, 1 }; vkViewport = Initialisers::viewport(viewport.x, viewport.y, static_cast<float>(_extent.width) * viewport.z, static_cast<float>(_extent.height) * viewport.w); vkScissor = Initialisers::scissor(_extent); vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = _extent.width * scissor.z; vkScissor.extent.height = _extent.height * scissor.w; auto imageCount = deviceContext->imageCount; buffers.resize(imageCount); for (size_t i = 0; i < imageCount; i++) { VkDeviceSize bufferSize = sizeof(CameraGPU); buffers[i].Allocate(deviceContext, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } std::string sceneShader = (deviceContext->validGPU == 2 ? "sceneRQ" : "scene"); DescriptorSetRequest request({ { sceneShader, 0 } }); request.AddDescriptorBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT); request.AddDescriptorBufferData(0, buffers.data()); deviceContext->GetDescriptors(descriptor, &request); gpuData.rayCullDistance = 0.0f; adaptiveDistance = true; transform.position.y = 4.0f; widget.enabled = true; lookAtPlace = true; lookAt = glm::vec3(0.0f, 1.0f, 0.0f); transform.position = glm::vec3(0.0f, 5.0f, 10.0f); update(_extent.width, _extent.height); float length = 60.0f; positions = {glm::vec3(50, 25, 80), glm::vec3(0, 1, 45), glm::vec3(-30, 1, 0), glm::vec3(-45, 15, 20)}; auto d1 = glm::distance(positions[0], positions[1]); auto d2 = glm::distance(positions[1], positions[2]); auto d3 = glm::distance(positions[2], positions[3]); auto total = d1 + d2 + d3; timings.emplace_back(length * (d1 / total)); timings.emplace_back(length * (d2 / total)); timings.emplace_back(length * (d3 / total)); } void Camera::update(float windowWidth, float windowHeight) { if (!valuesUpdated(windowWidth, windowHeight)) { transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), windowWidth / windowHeight, nearPlane, farPlane); } } void Camera::update(const VkExtent2D& _extent) { if (!valuesUpdated(_extent)) { extent = _extent; vkViewport.x = viewport.x; vkViewport.y = viewport.y; vkViewport.width = _extent.width * viewport.z; vkViewport.height = _extent.height * viewport.w; vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = _extent.width * scissor.z; vkScissor.extent.height = _extent.height * scissor.w; transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), vkViewport.width / vkViewport.height, nearPlane, farPlane); projection[1][1] *= -1; gpuData.viewProjection = projection * view; updateValues(extent); } } void Camera::update(float dt) { angle += speed * dt; transform.position = lookAt + glm::vec3(distance * std::sin(angle), distance * 0.65f, distance * std::cos(angle)); if (!valuesUpdated(extent)) { transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), vkViewport.width / vkViewport.height, nearPlane, farPlane); projection[1][1] *= -1; gpuData.viewProjection = projection * view; gpuData.position = transform.position; updateValues(extent); } if (ImGUI::enabled) { widget.Text("Camera"); widget.Slider("Camera FOV", &FOV, 1.0f, 179.0f); widget.Slider("Distance", &distance, 1.0f, 100.0f); widget.Slider("Speed", &speed, 0.0f, 5.0f); } } bool Camera::valuesUpdated(const VkExtent2D& _extent) { return prevTransform == transform && prevLookAt == lookAt && prevUp == worldUp && lookAtPlace == prevLookAtPlace && prevFOV == FOV && prevNearPlane == nearPlane && prevFarPlane == farPlane && vkViewport.width == _extent.width && vkViewport.height == _extent.height; } void Camera::vkSetViewport(VkCommandBuffer cmdBuffer) { vkCmdSetViewport(cmdBuffer, 0, 1, &vkViewport); vkCmdSetScissor(cmdBuffer, 0, 1, &vkScissor); } void Camera::setViewport(glm::vec2 size, glm::vec2 offset) { viewport = {offset.x, offset.y, size.x, size.y}; vkViewport.x = viewport.x; vkViewport.y = viewport.y; vkViewport.width = windowWidth * viewport.z; vkViewport.height = windowHeight * viewport.w; } void Camera::setScissor(glm::vec2 size, glm::vec2 offset) { scissor = { offset.x, offset.y, size.x, size.y }; vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = extent.width * scissor.z; vkScissor.extent.height = extent.height * scissor.w; } void Camera::SetCullDistance(float cullDistance) { gpuData.rayCullDistance = std::clamp(cullDistance, 5.0f, 100.0f); } bool Camera::valuesUpdated(float windowWidth, float windowHeight) { return prevTransform == transform && prevLookAt == lookAt && prevUp == worldUp && lookAtPlace == prevLookAtPlace && prevFOV == FOV && prevNearPlane == nearPlane && prevFarPlane == farPlane && prevWindowWidth == windowWidth && prevWindowHeight == windowHeight; } void Camera::updateValues(const VkExtent2D& _extent) { prevTransform = transform; prevLookAt == lookAt; prevUp = worldUp; prevFOV = FOV; prevNearPlane = nearPlane; prevFarPlane = farPlane; extent = _extent; prevLookAtPlace = lookAtPlace; prevViewport = viewport; prevScissor = scissor; } void Camera::updateWindow(float _windowWidth, float _windowHeight) { } void Camera::ResetPan() { currentIndex = 0; pan = true; time = 0.0f; }
#include "Camera.h" #include "Initilizers.h" #include "ImGUI_.h" #include <algorithm> Camera::~Camera() { } void Camera::init(DeviceContext* deviceContext, const VkExtent2D& _extent) { viewport = { 0, 0, 1, 1 }; scissor = { 0, 0, 1, 1 }; vkViewport = Initialisers::viewport(viewport.x, viewport.y, static_cast<float>(_extent.width) * viewport.z, static_cast<float>(_extent.height) * viewport.w); vkScissor = Initialisers::scissor(_extent); vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = _extent.width * scissor.z; vkScissor.extent.height = _extent.height * scissor.w; auto imageCount = deviceContext->imageCount; buffers.resize(imageCount); for (size_t i = 0; i < imageCount; i++) { VkDeviceSize bufferSize = sizeof(CameraGPU); buffers[i].Allocate(deviceContext, bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); } std::string sceneShader = (deviceContext->validGPU == 2 ? "sceneRQ" : "scene"); DescriptorSetRequest request({ { sceneShader, 0 } }); request.AddDescriptorBinding(0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT); request.AddDescriptorBufferData(0, buffers.data()); deviceContext->GetDescriptors(descriptor, &request); gpuData.rayCullDistance = 0.0f; adaptiveDistance = true; transform.position.y = 4.0f; widget.enabled = true; lookAtPlace = true; lookAt = glm::vec3(0.0f, 1.0f, 0.0f); transform.position = glm::vec3(0.0f, 5.0f, 10.0f); update(_extent.width, _extent.height); float length = 60.0f; positions = {glm::vec3(50, 25, 80), glm::vec3(0, 1, 45), glm::vec3(-30, 1, 0), glm::vec3(-45, 15, 20)}; auto d1 = glm::distance(positions[0], positions[1]); auto d2 = glm::distance(positions[1], positions[2]); auto d3 = glm::distance(positions[2], positions[3]); auto total = d1 + d2 + d3; timings.emplace_back(length * (d1 / total)); timings.emplace_back(length * (d2 / total)); timings.emplace_back(length * (d3 / total)); } void Camera::update(float windowWidth, float windowHeight) { if (!valuesUpdated(windowWidth, windowHeight)) { transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), windowWidth / windowHeight, nearPlane, farPlane); } } void Camera::update(const VkExtent2D& _extent) { if (!valuesUpdated(_extent)) { extent = _extent; vkViewport.x = viewport.x; vkViewport.y = viewport.y; vkViewport.width = _extent.width * viewport.z; vkViewport.height = _extent.height * viewport.w; vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = _extent.width * scissor.z; vkScissor.extent.height = _extent.height * scissor.w; transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), vkViewport.width / vkViewport.height, nearPlane, farPlane); projection[1][1] *= -1; gpuData.viewProjection = projection * view; updateValues(extent); } } void Camera::update(float dt) { angle += speed * dt; transform.position = lookAt + glm::vec3(distance * std::sin(angle), distance * 0.65f, distance * std::cos(angle)); if (!valuesUpdated(extent)) { transform.getMatrix(model); auto view = glm::lookAt(transform.position, lookAtPlace ? lookAt : transform.position + transform.forward, worldUp); auto projection = glm::perspective(glm::radians(FOV), vkViewport.width / vkViewport.height, nearPlane, farPlane); projection[1][1] *= -1; gpuData.viewProjection = projection * view; gpuData.position = transform.position; updateValues(extent); } if (ImGUI::enabled) { widget.Text("Camera"); widget.Slider("Camera FOV", &FOV, 1.0f, 179.0f); widget.Slider("Distance", &distance, 1.0f, 100.0f); widget.Slider("Speed", &speed, 0.0f, 5.0f); } } bool Camera::valuesUpdated(const VkExtent2D& _extent) { return prevTransform == transform && prevLookAt == lookAt && prevUp == worldUp && lookAtPlace == prevLookAtPlace && prevFOV == FOV && prevNearPlane == nearPlane && prevFarPlane == farPlane && vkViewport.width == _extent.width && vkViewport.height == _extent.height; } void Camera::vkSetViewport(VkCommandBuffer cmdBuffer) { vkCmdSetViewport(cmdBuffer, 0, 1, &vkViewport); vkCmdSetScissor(cmdBuffer, 0, 1, &vkScissor); } void Camera::setViewport(glm::vec2 size, glm::vec2 offset) { viewport = {offset.x, offset.y, size.x, size.y}; vkViewport.x = viewport.x; vkViewport.y = viewport.y; vkViewport.width = windowWidth * viewport.z; vkViewport.height = windowHeight * viewport.w; } void Camera::setScissor(glm::vec2 size, glm::vec2 offset) { scissor = { offset.x, offset.y, size.x, size.y }; vkScissor.offset.x = static_cast<int32_t>(scissor.x); vkScissor.offset.y = static_cast<int32_t>(scissor.y); vkScissor.extent.width = extent.width * scissor.z; vkScissor.extent.height = extent.height * scissor.w; } void Camera::SetCullDistance(float cullDistance) { gpuData.rayCullDistance = std::clamp(cullDistance, 5.0f, 100.0f); } bool Camera::valuesUpdated(float windowWidth, float windowHeight) { return prevTransform == transform && prevLookAt == lookAt && prevUp == worldUp && lookAtPlace == prevLookAtPlace && prevFOV == FOV && prevNearPlane == nearPlane && prevFarPlane == farPlane && prevWindowWidth == windowWidth && prevWindowHeight == windowHeight; } void Camera::updateValues(const VkExtent2D& _
void Camera::updateWindow(float _windowWidth, float _windowHeight) { } void Camera::ResetPan() { currentIndex = 0; pan = true; time = 0.0f; }
extent) { prevTransform = transform; prevLookAt == lookAt; prevUp = worldUp; prevFOV = FOV; prevNearPlane = nearPlane; prevFarPlane = farPlane; extent = _extent; prevLookAtPlace = lookAtPlace; prevViewport = viewport; prevScissor = scissor; }
function_block-function_prefixed
[ { "content": "struct Transform {\n\n\n\n\tglm::vec3 position = glm::vec3(0);\n\n\tglm::vec3 rotation = glm::vec3(0);\n\n\tglm::vec3 scale = glm::vec3(1);\n\n\n\n\tglm::vec3 right = glm::vec3(1, 0, 0);\n\n\tglm::vec3 up = glm::vec3(0, 1, 0);\n\n\tglm::vec3 forward = glm::vec3(0, 0, 1);\n\n\n\n\n\n\tbool operator...
C++
samples/snippets/cpp/VS_Snippets_CLR_System/system.Collections.Specialized.IOrderedDictionary_Implementation/cpp/remarks.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
#using <System.dll> using namespace System; using namespace System::Collections; using namespace System::Collections::Specialized; public ref class ODEnum : IDictionaryEnumerator { private: int position; ArrayList^ itemlist; public: ODEnum(ArrayList^ list) { this->Reset(); itemlist = list; } virtual bool MoveNext() { position++; return (position < itemlist->Count); } virtual void Reset() { position = -1; } virtual property Object^ Current { Object^ get() { try { return itemlist[position]; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } virtual property DictionaryEntry Entry { DictionaryEntry get() { return (DictionaryEntry)(Current); } } virtual property Object^ Key { Object^ get() { try { return ((DictionaryEntry^)itemlist[position])->Key; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } virtual property Object^ Value { Object^ get() { try { return ((DictionaryEntry^)itemlist[position])->Value; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } }; public ref class SimpleOD : IOrderedDictionary { private: ArrayList^ itemlist; public: SimpleOD(int numItems) { itemlist = gcnew ArrayList(numItems); } int IndexOfKey(Object^ key) { for (int i = 0; i < itemlist->Count; i++) { if (((DictionaryEntry^)itemlist[i])->Key == key) return i; } return -1; } virtual property Object^ default[Object^] { Object^ get(Object^ key) { return ((DictionaryEntry^)itemlist[IndexOfKey(key)])->Value; } void set(Object^ key, Object^ value) { itemlist[IndexOfKey(key)] = gcnew DictionaryEntry(key, value); } } virtual IDictionaryEnumerator^ GetEnumerator() { return gcnew ODEnum(itemlist); } virtual void Insert(int index, Object^ key, Object^ value) { if (IndexOfKey(key) != -1) { throw gcnew ArgumentException("An element with the same key already exists in the collection."); } itemlist->Insert(index, gcnew DictionaryEntry(key, value)); } virtual void RemoveAt(int index) { itemlist->RemoveAt(index); } virtual property Object^ default[int] { Object^ get(int index) { return ((DictionaryEntry^)itemlist[index])->Value; } void set(int index, Object^ value) { Object^ key = ((DictionaryEntry^)itemlist[index])->Key; itemlist[index] = gcnew DictionaryEntry(Keys, value); } } virtual void Add(Object^ key, Object^ value) { if (IndexOfKey(key) != -1) { throw gcnew ArgumentException("An element with the same key already exists in the collection."); } itemlist->Add(gcnew DictionaryEntry(key, value)); } virtual void Clear() { itemlist->Clear(); } virtual bool Contains(Object^ key) { if (IndexOfKey(key) == -1) { return false; } else { return true; } } virtual property bool IsFixedSize { bool get() { return false; } } virtual property bool IsReadOnly { bool get() { return false; } } virtual property ICollection^ Keys { ICollection^ get() { ArrayList^ KeyCollection = gcnew ArrayList(itemlist->Count); for (int i = 0; i < itemlist->Count; i++) { KeyCollection[i] = ((DictionaryEntry^)itemlist[i])->Key; } return KeyCollection; } } virtual void Remove(Object^ key) { itemlist->RemoveAt(IndexOfKey(key)); } virtual property ICollection^ Values { ICollection ^get() { ArrayList^ ValueCollection = gcnew ArrayList(itemlist->Count); for (int i = 0; i < itemlist->Count; i++) { ValueCollection[i] = ((DictionaryEntry^)itemlist[i])->Value; } return ValueCollection; } } virtual void CopyTo(Array^ array, int index) { itemlist->CopyTo(array, index); } virtual property int Count { int get() { return itemlist->Count; } } virtual property bool IsSynchronized { bool get() { return itemlist->IsSynchronized; } } virtual property Object^ SyncRoot { Object^ get() { return itemlist->SyncRoot; } } virtual IEnumerator^ IfcGetEnumerator() = IEnumerable::GetEnumerator { return (IEnumerator^) gcnew ODEnum(itemlist); } }; class App { public: static void Main() { int index = 1; SimpleOD^ myOrderedDictionary = gcnew SimpleOD(2); myOrderedDictionary->Add("Way", "ToGo"); myOrderedDictionary->Add("Far", "Out"); Object^ obj; obj = myOrderedDictionary[index]; for each (DictionaryEntry de in myOrderedDictionary) { } } }; int main() { App::Main(); }
#using <System.dll> using namespace System; using namespace System::Collections; using namespace System::Collections::Specialized; public ref class ODEnum : IDictionaryEnumerator { private: int position; ArrayList^ itemlist; public: ODEnum(ArrayList^ list) { this->Reset(); itemlist = list; } virtual bool MoveNext() { position++; return (position < itemlist->Count); } virtual void Reset() { position = -1; } virtual property Object^ Current { Object^ get() { try { return itemlist[position]; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } virtual property DictionaryEntry Entry { DictionaryEntry get() { return (DictionaryEntry)(Current); } } virtual property Object^ Key { Object^ get() { try { return ((DictionaryEntry^)itemlist[position])->Key; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } virtual property Object^ Value { Object^ get() { try { return ((DictionaryEntry^)itemlist[position])->Value; } catch (IndexOutOfRangeException^) { throw gcnew InvalidOperationException(); } } } }; public ref class SimpleOD : IOrderedDictionary { private: ArrayList^ itemlist; public: SimpleOD(int numItems) { itemlist = gcnew ArrayList(numItems); } int IndexOfKey(Object^ key) { for (int i = 0; i < itemlist->Count; i++) { if (((DictionaryEntry^)itemlist[i])->Key == key) return i; } return -1; } virtual property Object^ default[Object^] { Object^ get(Object^ key) { return ((DictionaryEntry^)itemlist[IndexOfKey(key)])->Value; } void set(Object^ key, Object^ value) { itemlist[IndexOfKey(key)] = gcnew DictionaryEntry(key, value); } } virtual IDictionaryEnumerator^ GetEnumerator() { return gcnew ODEnum(itemlist); } virtual void Insert(int index, Object^ key, Object^ value) { if (IndexOfKey(key) != -1) { throw gcnew ArgumentException("An element with the same key already exists in the collection."); } itemlist->Insert(index, gcnew DictionaryEntry(key, value)); } virtual void RemoveAt(int index) { itemlist->RemoveAt(index); } virtual property Object^ default[int] { Object^ get(int index) { return ((DictionaryEntry^)itemlist[index])->Value; } void set(int index, Object^ value) { Object^ key = ((DictionaryEntry^)itemlist[index])->Key; itemlist[index] = gcnew DictionaryEntry(Keys, value); } } virtual void Add(Object^ key, Object^ value) { if (IndexOfKey(key) != -1) { throw gcnew ArgumentException("An element with the same key already exists in the collection."); } itemlist->Add(gcnew DictionaryEntry(key, value)); } virtual void Clear() { itemlist->Clear(); } virtual bool Contains(Object^ key) { if (IndexOfKey(key) == -1) { return false; } else { return true; } } virtual property bool IsFixedSize { bool get() { return false; } } virtual property bool IsReadOnly { bool get() { return false; } } virtual property ICollection^ Keys { ICollection^ get() { ArrayList^ KeyCollection = gcnew ArrayList(itemlist->Count); for (int i = 0; i < itemlist->Count; i++) { KeyCollection[i] = ((DictionaryEntry^)itemlist[i])->Key; } return KeyCollection; } } virtual void Remove(Object^ key) { itemlist->RemoveAt(IndexOfKey(key)); } virtual property ICollection^ Values { ICollection ^get() { ArrayList^ ValueCollection = gcnew ArrayList(itemlist->Count); for (int i = 0; i < itemlist->Count; i++) { ValueCollection[i] = ((DictionaryEntry^)itemlist[i])->Value; } return ValueCollection; } } virtual void CopyTo(Array^ array, int index) { itemlist->CopyTo(array, index); } virtual property int Count { int get() { return itemlist->Count; } }
virtual property Object^ SyncRoot { Object^ get() { return itemlist->SyncRoot; } } virtual IEnumerator^ IfcGetEnumerator() = IEnumerable::GetEnumerator { return (IEnumerator^) gcnew ODEnum(itemlist); } }; class App { public: static void Main() { int index = 1; SimpleOD^ myOrderedDictionary = gcnew SimpleOD(2); myOrderedDictionary->Add("Way", "ToGo"); myOrderedDictionary->Add("Far", "Out"); Object^ obj; obj = myOrderedDictionary[index]; for each (DictionaryEntry de in myOrderedDictionary) { } } }; int main() { App::Main(); }
virtual property bool IsSynchronized { bool get() { return itemlist->IsSynchronized; } }
function_block-function_prefix_line
[]
C++
tutorial/lesson_15_generators.cpp
pelikan/Halide
5b4eac0f810dbd8dc8d224cb322d5b1215ea224d
#include "Halide.h" #include <stdio.h> using namespace Halide; class MyFirstGenerator : public Halide::Generator<MyFirstGenerator> { public: Input<uint8_t> offset{"offset"}; Input<Buffer<uint8_t>> input{"input", 2}; Output<Buffer<uint8_t>> brighter{"brighter", 2}; Var x, y; void generate() { brighter(x, y) = input(x, y) + offset; brighter.vectorize(x, 16).parallel(y); } }; HALIDE_REGISTER_GENERATOR(MyFirstGenerator, my_first_generator) class MySecondGenerator : public Halide::Generator<MySecondGenerator> { public: GeneratorParam<bool> parallel{"parallel", true}; GeneratorParam<float> scale{"scale", 1.0f , 0.0f , 100.0f }; enum class Rotation { None, Clockwise, CounterClockwise }; GeneratorParam<Rotation> rotation{"rotation", Rotation::None, {{"none", Rotation::None}, {"cw", Rotation::Clockwise}, {"ccw", Rotation::CounterClockwise}}}; Input<uint8_t> offset{"offset"}; Input<Buffer<uint8_t>> input{"input", 2}; Output<Buffer<>> output{"output", 2}; Var x, y; void generate() { Func brighter; brighter(x, y) = scale * (input(x, y) + offset); Func rotated; switch ((Rotation)rotation) { case Rotation::None: rotated(x, y) = brighter(x, y); break; case Rotation::Clockwise: rotated(x, y) = brighter(y, 100 - x); break; case Rotation::CounterClockwise: rotated(x, y) = brighter(100 - y, x); break; } output(x, y) = cast(output.type(), rotated(x, y)); output.vectorize(x, natural_vector_size(output.type())); if (parallel) { output.parallel(y); } if (rotation != Rotation::None) { rotated .compute_at(output, y) .vectorize(x, natural_vector_size(rotated.output_types()[0])); } } }; HALIDE_REGISTER_GENERATOR(MySecondGenerator, my_second_generator)
#include "Halide.h" #include <stdio.h> using namespace Halide; class MyFirstGenerator : public Halide::Generator<MyFirstGenerator> { public: Input<uint8_t> offset{"offset"}; Input<Buffer<uint8_t>> input{"input", 2}; Output<Buffer<uint8_t>> brighter{"brighter", 2}; Var x, y;
}; HALIDE_REGISTER_GENERATOR(MyFirstGenerator, my_first_generator) class MySecondGenerator : public Halide::Generator<MySecondGenerator> { public: GeneratorParam<bool> parallel{"parallel", true}; GeneratorParam<float> scale{"scale", 1.0f , 0.0f , 100.0f }; enum class Rotation { None, Clockwise, CounterClockwise }; GeneratorParam<Rotation> rotation{"rotation", Rotation::None, {{"none", Rotation::None}, {"cw", Rotation::Clockwise}, {"ccw", Rotation::CounterClockwise}}}; Input<uint8_t> offset{"offset"}; Input<Buffer<uint8_t>> input{"input", 2}; Output<Buffer<>> output{"output", 2}; Var x, y; void generate() { Func brighter; brighter(x, y) = scale * (input(x, y) + offset); Func rotated; switch ((Rotation)rotation) { case Rotation::None: rotated(x, y) = brighter(x, y); break; case Rotation::Clockwise: rotated(x, y) = brighter(y, 100 - x); break; case Rotation::CounterClockwise: rotated(x, y) = brighter(100 - y, x); break; } output(x, y) = cast(output.type(), rotated(x, y)); output.vectorize(x, natural_vector_size(output.type())); if (parallel) { output.parallel(y); } if (rotation != Rotation::None) { rotated .compute_at(output, y) .vectorize(x, natural_vector_size(rotated.output_types()[0])); } } }; HALIDE_REGISTER_GENERATOR(MySecondGenerator, my_second_generator)
void generate() { brighter(x, y) = input(x, y) + offset; brighter.vectorize(x, 16).parallel(y); }
function_block-full_function
[ { "content": "class ExprUsesVars : public IRGraphVisitor {\n\n using IRGraphVisitor::visit;\n\n\n\n const Scope<T> &vars;\n\n Scope<Expr> scope;\n\n\n\n void include(const Expr &e) override {\n\n if (result) return;\n\n IRGraphVisitor::include(e);\n\n }\n\n\n\n void include(const...
C++
tests/rwops/customRWops/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
#include <iostream> #include <sstream> #include <string> #include <ios> #include <SDL.h> #include "rwops.hpp" const int ERR_SDL_INIT = -1; const int BUFFER_SIZE = 4; const int CHAR_SKIP = 2; bool init(Uint32 sdlInitFlags) { if(SDL_Init(sdlInitFlags) < 0) { return false; } return true; } void quit() { SDL_Quit(); } Sint64 stringstreamSize(SDL_RWops *rwops) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); return ss == NULL ? -1 : ss->str().size(); } Sint64 stringstreamSeek(SDL_RWops *rwops, Sint64 offset, int whence) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return -1; } std::ios_base::seekdir direction; switch(whence) { case RW_SEEK_SET: direction = ss->beg; break; case RW_SEEK_CUR: direction = ss->cur; break; case RW_SEEK_END: direction = ss->end; break; default: return -1; } ss->seekg(offset, direction); ss->seekp(offset, direction); return ss->tellp(); } size_t stringstreamRead(SDL_RWops *rwops, void *ptr, size_t size, size_t maxnum) { size_t byteCount = size * maxnum; auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return 0; } ss->read(static_cast<char*>(ptr), byteCount); return ss->gcount(); } size_t stringstreamWrite(SDL_RWops *rwops, const void *ptr, size_t size, size_t num) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return 0; } size_t oldSize = ss->str().size(); ss->write(static_cast<const char*>(ptr), size * num); size_t newSize = ss->str().size(); return newSize - oldSize; } int stringstreamClose(SDL_RWops *rwops) { if(rwops != NULL) { SDL_FreeRW(rwops); } return 0; } void test() { std::stringstream ss; SDL::RWops custom(stringstreamSize, stringstreamSeek, stringstreamRead, stringstreamWrite, stringstreamClose, SDL_RWOPS_UNKNOWN, &ss); std::string str = "abcdefghijklmnopqrstuvwxyz"; char buffer[BUFFER_SIZE]; custom.write(str.c_str(), sizeof(char), str.size()); std::cout << "output buffer position after writing: " << custom.tell() << std::endl; custom.seek(0, RW_SEEK_SET); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " first characters: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(CHAR_SKIP, RW_SEEK_CUR); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " characters after skipping " << CHAR_SKIP << " characters from the previous position: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(-BUFFER_SIZE, RW_SEEK_END); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " last characters: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(0, RW_SEEK_SET); } int main(int argc, char **argv) { Uint32 sdlFlags = SDL_INIT_VIDEO; if(!init(sdlFlags)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL\n"); return ERR_SDL_INIT; } test(); quit(); return 0; }
#include <iostream> #include <sstream> #include <string> #include <ios> #include <SDL.h> #include "rwops.hpp" const int ERR_SDL_INIT = -1; const int BUFFER_SIZE = 4; const int CHAR_SKIP = 2; bool init(Uint32 sdlInitFlags) { if(SDL_Init(sdlInitFlags) < 0) { return false; } return true; } void quit() { SDL_Quit(); } Sint64 stringstreamSize(SDL_RWops *rwops) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); return ss == NULL ? -1 : ss->str().size(); } Sint64 stringstreamSeek(SDL_RWops *rwops, Sint64 offset, int whence) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return -1; } std::ios_base::seekdir direction; switch(whence) { case RW_SEEK_SET: direction = ss->beg; break; case RW_SEEK_CUR: direction = ss->cur; break; case RW_SEEK_END: direction = ss->end; break; default: return -1; } ss->seekg(offset, direction); ss->seekp(offset, direction); return ss->tellp(); } size_t stringstreamRead(SDL_RWops *rwops, void *ptr, size_t size, size_t maxnum) { size_t byteCount = size * maxnum; auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return 0; } ss->read(static_cast<char*>(ptr), byteCount); return ss->gcount(); } size_t stringstreamWrite(SDL_RWops *rwops, const void *ptr, size_t size, size_t num) { auto ss = static_cast<std::stringstream*>(rwops->hidden.unknown.data1); if(ss == NULL) { return 0; } size_t oldSize = ss->str().size(); ss->write(static_cast<const char*>(ptr), size * num); size_t newSize = ss->str().size(); return newSize - oldSize; } int stringstreamClose(SDL_RWops *rwops) { if(rwops != NULL) { SDL_FreeRW(rwops); } return 0; } void test() { std::stringstream ss; SDL::RWops custom(stringstreamSize, stringstreamSeek, stringstreamRead, stringstreamWrite, stringstreamClose, SDL_RWOPS_UNKNOWN, &ss); std::string str = "abcdefghijklmnopqrstuvwxyz"; char buffer[BUFFER_SIZE]; custom.write(str.c_str(), sizeof(char), str.size()); std::cout << "output buffer position after writing: " << custom.tell() <<
FER_SIZE, RW_SEEK_END); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " last characters: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(0, RW_SEEK_SET); } int main(int argc, char **argv) { Uint32 sdlFlags = SDL_INIT_VIDEO; if(!init(sdlFlags)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL\n"); return ERR_SDL_INIT; } test(); quit(); return 0; }
std::endl; custom.seek(0, RW_SEEK_SET); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " first characters: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(CHAR_SKIP, RW_SEEK_CUR); custom.read(buffer, sizeof(char), BUFFER_SIZE); std::cout << BUFFER_SIZE << " characters after skipping " << CHAR_SKIP << " characters from the previous position: "; std::cout.write(buffer, BUFFER_SIZE); std::cout << std::endl; custom.seek(-BUF
random
[ { "content": "\tstd::cout << \"byte 0x\" << std::setbase(16)\n\n\t\t<< (static_cast<int>(c) & 0xff) << std::setbase(10)\n\n\t\t<< \" at position \" << pos << std::endl;\n\n\tconstMem.seek(0, RW_SEEK_SET);\n\n}\n\n\n\nvoid test()\n\n{\n\n\tSDL::RWops constMem(memory, sizeof(memory));\n\n\n\n\t// read. Positions ...
C++
xdl/ps-plus/ps-plus/common/test/hashmap_test.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
#include <iostream> #include "gtest/gtest.h" #include "ps-plus/common/hashmap.h" #include "ps-plus/common/thread_pool.h" using ps::Hash128Key; using ps::HashMap; using ps::Range; using ps::Status; using std::vector; TEST(HashMap64Test, Get) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<int64_t>(1)); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 4ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(4, max); EXPECT_EQ(4u, ids.size()); size_t total = 0; for (size_t i = 0; i < 4; i++) { total += ids[i]; } EXPECT_EQ(6ul, total); EXPECT_EQ(0ul, reused_ids.size()); int64_t keys1[] = {4, 3, 2, 1, 13, 14}; max = hashmap->Get((const int64_t*)keys1, 6ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(6, max); EXPECT_EQ(6u, ids.size()); total = 0; for (size_t i = 0; i < 4; i++) { total += ids[i]; } EXPECT_EQ(6ul, total); total = 0; for (size_t i = 4; i < 6; i++) { total += ids[i]; } EXPECT_EQ(9u, total); EXPECT_EQ(0u, reused_ids.size()); } TEST(HashMap128Test, Get) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(2, max); EXPECT_EQ(2u, ids.size()); size_t total = 0; for (size_t i = 0; i < 2; i++) { total += ids[i]; } EXPECT_EQ(1, total); EXPECT_EQ(0u, reused_ids.size()); int64_t keys1[] = {4, 3, 2, 1, 13, 14}; max = hashmap->Get((const int64_t*)keys1, 3ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(5, max); EXPECT_EQ(3u, ids.size()); total = 0; for (size_t i = 0; i < 3; i++) { total += ids[i]; } EXPECT_EQ(9, total); EXPECT_EQ(0u, reused_ids.size()); } TEST(HashMap128Test, BloomFilter) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); hashmap->SetBloomFilterThrethold(2); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(max, 0); max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(max, 2); } TEST(HashMap128Test, Erase) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); int64_t keys[] = {1, 2}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get(keys, 1ul, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(1, max); ASSERT_EQ(1, ids.size()); ASSERT_EQ(0, ids[0]); ASSERT_EQ(0, reused_ids.size()); int64_t keys2[] = {3, 4}; max = hashmap->Get(keys2, 1ul, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(2, max); ASSERT_EQ(1, ids.size()); ASSERT_EQ(1, ids[0]); ASSERT_EQ(0, reused_ids.size()); int64_t del_keys[] = {3, 4}; hashmap->Erase(del_keys, 1); int64_t keys3[] = {1, 2, 5, 6}; max = hashmap->Get(keys3, 2, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(2, max); EXPECT_EQ(2u, ids.size()); EXPECT_EQ(0, ids[0]); EXPECT_EQ(1, ids[1]); EXPECT_EQ(1u, reused_ids.size()); EXPECT_EQ(1, reused_ids[0]); int64_t del_keys1[] = {1, 2}; hashmap->Erase(del_keys1, 1); int64_t keys4[] = {5, 6, 1, 2, 3, 4, 7, 8}; max = hashmap->Get(keys4, 4, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(4u, max); EXPECT_EQ(4u, ids.size()); EXPECT_EQ(1, ids[0]); size_t total = 0; for (size_t i = 0; i < 3; i++) { total += ids[i+1]; } EXPECT_EQ(5, total); } TEST(HashMap128Test, MultiThread) { int thread_count = 10; size_t key_count = 20000l; std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(key_count)); int64_t* keys = new int64_t[key_count]; for (size_t i = 0; i < key_count; i++) { keys[i] = i; } std::atomic<size_t> total(0); auto start = std::chrono::system_clock::now(); ps::MultiThreadDoTBB(thread_count, [&](const Range& r) { for (size_t i = r.begin; i < r.end; i++) { vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; hashmap->Get(keys + i* key_count/thread_count, key_count/2/thread_count, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(key_count/2/thread_count, ids.size()); size_t sub_total = 0; for (size_t j = 0; j < ids.size(); j++) { sub_total += ids[j]; } total.fetch_add(sub_total); } return Status::Ok(); }); EXPECT_EQ(49995000, total); auto end = std::chrono::system_clock::now(); std::cout << "insert " << key_count/2 << " keys, takes " << (end-start).count()/1000000 << "ms" <<std::endl; delete [] keys; }
#include <iostream> #include "gtest/gtest.h" #include "ps-plus/common/hashmap.h" #include "ps-plus/common/thread_pool.h" using ps::Hash128Key; using ps::HashMap; using ps::Range; using ps::Status; using std::vector; TEST(HashMap64Test, Get) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<int64_t>(1)); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 4ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(4, max); EXPECT_EQ(4u, ids.size()); size_t total = 0; for (size_t i = 0; i < 4; i++) { total += ids[i]; } EXPECT_EQ(6ul, total); EXPECT_EQ(0ul, reused_ids.size()); int64_t keys1[] = {4, 3, 2, 1, 13, 14}; max = hashmap->Get((const int64_t*)keys1, 6ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(6, max); EXPECT_EQ(6u, ids.size()); total = 0; for (size_t i = 0; i < 4; i++) { total += ids[i]; } EXPECT_EQ(6ul, total); total = 0; for (size_t i = 4; i < 6; i++) { total += ids[i]; } EXPECT_EQ(9u, total); EXPECT_EQ(0u, reused_ids.size()); } TEST(HashMap128Test, Get) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(2, max); EXPECT_EQ(2u, ids.size()); size_t total = 0; for (size_t i = 0; i < 2; i++) { total += ids[i]; } EXPECT_EQ(1, total); EXPECT_EQ(0u, reused_ids.size()); int64_t keys1[] = {4, 3, 2, 1, 13, 14}; max = hashmap->Get((const int64_t*)keys1, 3ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(5, max); EXPECT_EQ(3u, ids.size()); total = 0; for (size_t i = 0; i < 3; i++) { total += ids[i]; } EXPECT_EQ(9, total); EXPECT_EQ(0u, reused_ids.size()); } TEST(HashMap128Test, BloomFilter) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); hashmap->SetBloomFilterThrethold(2); int64_t keys[] = {1, 2, 3, 4}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(max, 0); max = hashmap->Get((const int64_t*)keys, 2ul, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(max, 2); } TEST(HashMap128Test, Erase) { std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(1)); int64_t keys[] = {1, 2}; vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; int64_t max = hashmap->Get(keys, 1ul, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(1, max); ASSERT_EQ(1, ids.size()); ASSERT_EQ(0, ids[0]); ASSERT_EQ(0, reused_ids.size()); int64_t keys2[] = {3, 4}; max = hashmap->Get(keys2, 1ul, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(2, max); ASSERT_EQ(1, ids.size()); ASSERT_EQ(1, ids[0]); ASSERT_EQ(0, reused_ids.size()); int64_t del_keys[] = {3, 4}; hashmap->Erase(del_keys, 1); int64_t keys3[] = {1, 2, 5, 6}; max = hashmap->Get(keys3, 2, false, 1.0, &ids, &reused_ids, &filtered); ASSERT_EQ(2, max); EXPECT_EQ(2u, ids.size()); EXPECT_EQ(0, ids[0]); EXPECT_EQ(1, ids[1]); EXPECT_EQ(1u, reused_ids.size()); EXPECT_EQ(1, reused_ids[0]); int64_t del_keys1[] = {1, 2}; hashmap->Erase(del_keys1, 1); int64_t keys4[] = {5, 6, 1, 2, 3, 4, 7, 8}; max = hashmap->Get(keys4, 4, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(4u, max); EXPECT_EQ(4u, ids.size()); EXPECT_EQ(1, ids[0]); size_t total = 0; for (size_t i = 0; i < 3; i++) { total += ids[i+1]; } EXPECT_EQ(5, total); } TEST(HashMap128Test, MultiThread) { int thread_count = 10; size_t key_count = 20000l; std::unique_ptr<HashMap> hashmap(new ps::HashMapImpl<Hash128Key>(key_count)); int64_t* keys = new int64_t[key_count]; for (size_t i = 0; i < key_count; i++) { keys[i] = i; } std::atomic<size_t> total(0); auto start = std::chrono::system_clock::now();
; EXPECT_EQ(49995000, total); auto end = std::chrono::system_clock::now(); std::cout << "insert " << key_count/2 << " keys, takes " << (end-start).count()/1000000 << "ms" <<std::endl; delete [] keys; }
ps::MultiThreadDoTBB(thread_count, [&](const Range& r) { for (size_t i = r.begin; i < r.end; i++) { vector<size_t> ids; tbb::concurrent_vector<size_t> reused_ids; size_t filtered; hashmap->Get(keys + i* key_count/thread_count, key_count/2/thread_count, false, 1.0, &ids, &reused_ids, &filtered); EXPECT_EQ(key_count/2/thread_count, ids.size()); size_t sub_total = 0; for (size_t j = 0; j < ids.size(); j++) { sub_total += ids[j]; } total.fetch_add(sub_total); } return Status::Ok(); })
call_expression
[]
C++
Mesh.cpp
nvpro-samples/gl_vk_chopper
e7ffdd0b0277843fc14af7ba110538089efb459e
#include "Mesh.h" #include <stdlib.h> Mesh::Mesh() : m_vertices(NULL) , m_indices(NULL) , m_normals(NULL) , m_max_vertices(0) , m_max_indices(0) , m_vertex_count(0) , m_index_count(0) , m_material_id(-1) { } Mesh::Mesh(const Mesh::ID& inID) : m_id(inID) , m_vertices(NULL) , m_indices(NULL) , m_normals(NULL) , m_max_vertices(0) , m_max_indices(0) , m_vertex_count(0) , m_index_count(0) , m_material_id(-1) { } void Mesh::allocate(uint32_t inMaxVerts, uint32_t inMaxIdx) { dispose(); m_max_vertices = inMaxVerts; m_max_indices = inMaxIdx; m_vertices = new Vec4f[m_max_vertices]; m_normals = new Vec4f[m_max_vertices]; m_indices = new uint32_t[m_max_indices]; m_uvs = new Vec2f[m_max_vertices]; } Vec4f*& Mesh::getVertices() { return m_vertices; } Vec4f*& Mesh::getNormals() { return m_normals; } uint32_t*& Mesh::getIndices() { return m_indices; } Vec2f*& Mesh::getUVs() { return m_uvs; } void Mesh::addVertex(const Vec4f& inVertex) { Vec4f normal = {0.0, 0.0, 0.0, 1.0}; addVertex(inVertex, normal); } void Mesh::addVertex(const Vec4f& inVertex, const Vec4f& inNormal) { if(m_vertex_count >= m_max_vertices) return; m_normals[m_vertex_count] = inNormal; m_vertices[m_vertex_count++] = inVertex; } void Mesh::addIndex(const uint32_t& inIndex) { if(m_index_count >= m_max_indices) return; m_indices[m_index_count++] = inIndex; m_triangle_count = m_index_count / 3; } Triangle4f Mesh::getTriangle(const uint32_t inIndex) { uint32_t startIndex = inIndex * 3; Triangle4f out = {m_vertices[m_indices[startIndex]], m_vertices[m_indices[startIndex + 1]], m_vertices[m_indices[startIndex + 2]], m_normals[m_indices[startIndex]], m_normals[m_indices[startIndex + 1]], m_normals[m_indices[startIndex + 2]]}; return out; } Triangle4f Mesh::getTransformedTriangle(Mat4x4f& inTransform, const uint32_t inIndex) { uint32_t startIndex = inIndex * 3; Triangle4f out = { inTransform(m_vertices[m_indices[startIndex]]), inTransform(m_vertices[m_indices[startIndex + 1]]), inTransform(m_vertices[m_indices[startIndex + 2]]), inTransform(m_normals[m_indices[startIndex]]), inTransform(m_normals[m_indices[startIndex + 1]]), inTransform(m_normals[m_indices[startIndex + 2]])}; return out; } void Mesh::dispose() { if(m_vertices) { delete[] m_vertices; m_vertices = NULL; } if(m_indices) { delete[] m_indices; m_indices = NULL; } if(m_normals) { delete[] m_normals; m_normals = NULL; } m_max_indices = 0; m_max_vertices = 0; m_index_count = 0; m_vertex_count = 0; m_triangle_count = 0; } void Mesh::getTransformedTriangles(Mat4x4f& inTransform, TriangleList4f& outTriangles) { for(uint32_t i = 0; i < m_triangle_count; ++i) { Triangle4f tri = getTransformedTriangle(inTransform, i); outTriangles.push_back(tri); } } Mesh::~Mesh() {}
#include "Mesh.h" #include <stdlib.h> Mesh::Mesh() : m_vertices(NULL) , m_indices(NULL) , m_normals(NULL) , m_max_vertices(0) , m_max_indices(0) , m_vertex_count(0) , m_index_count(0) , m_material_id(-1) { } Mesh::Mesh(const Mesh::ID& inID) : m_id(inID) , m_vertices(NULL) , m_indices(NULL) , m_normals(NULL) , m_max_vertices(0) , m_max_indices(0) , m_vertex_count(0) , m_index_count(0) , m_material_id(-1) { } void Mesh::allocate(uint32_t inMaxVerts, uint32_t inMaxIdx) { dispose(); m_max_vertices = inMaxVerts; m_max_indices = inMaxIdx; m_vertices =
Vec4f*& Mesh::getVertices() { return m_vertices; } Vec4f*& Mesh::getNormals() { return m_normals; } uint32_t*& Mesh::getIndices() { return m_indices; } Vec2f*& Mesh::getUVs() { return m_uvs; } void Mesh::addVertex(const Vec4f& inVertex) { Vec4f normal = {0.0, 0.0, 0.0, 1.0}; addVertex(inVertex, normal); } void Mesh::addVertex(const Vec4f& inVertex, const Vec4f& inNormal) { if(m_vertex_count >= m_max_vertices) return; m_normals[m_vertex_count] = inNormal; m_vertices[m_vertex_count++] = inVertex; } void Mesh::addIndex(const uint32_t& inIndex) { if(m_index_count >= m_max_indices) return; m_indices[m_index_count++] = inIndex; m_triangle_count = m_index_count / 3; } Triangle4f Mesh::getTriangle(const uint32_t inIndex) { uint32_t startIndex = inIndex * 3; Triangle4f out = {m_vertices[m_indices[startIndex]], m_vertices[m_indices[startIndex + 1]], m_vertices[m_indices[startIndex + 2]], m_normals[m_indices[startIndex]], m_normals[m_indices[startIndex + 1]], m_normals[m_indices[startIndex + 2]]}; return out; } Triangle4f Mesh::getTransformedTriangle(Mat4x4f& inTransform, const uint32_t inIndex) { uint32_t startIndex = inIndex * 3; Triangle4f out = { inTransform(m_vertices[m_indices[startIndex]]), inTransform(m_vertices[m_indices[startIndex + 1]]), inTransform(m_vertices[m_indices[startIndex + 2]]), inTransform(m_normals[m_indices[startIndex]]), inTransform(m_normals[m_indices[startIndex + 1]]), inTransform(m_normals[m_indices[startIndex + 2]])}; return out; } void Mesh::dispose() { if(m_vertices) { delete[] m_vertices; m_vertices = NULL; } if(m_indices) { delete[] m_indices; m_indices = NULL; } if(m_normals) { delete[] m_normals; m_normals = NULL; } m_max_indices = 0; m_max_vertices = 0; m_index_count = 0; m_vertex_count = 0; m_triangle_count = 0; } void Mesh::getTransformedTriangles(Mat4x4f& inTransform, TriangleList4f& outTriangles) { for(uint32_t i = 0; i < m_triangle_count; ++i) { Triangle4f tri = getTransformedTriangle(inTransform, i); outTriangles.push_back(tri); } } Mesh::~Mesh() {}
new Vec4f[m_max_vertices]; m_normals = new Vec4f[m_max_vertices]; m_indices = new uint32_t[m_max_indices]; m_uvs = new Vec2f[m_max_vertices]; }
function_block-function_prefixed
[ { "content": "class VkeIBO : public VkeBuffer<uint32_t>\n\n{\n\npublic:\n\n VkeIBO();\n\n ~VkeIBO();\n\n\n\n void bind(VkCommandBuffer* inCmd);\n\n};\n\n\n\n#endif", "file_path": "VkeIBO.h", "rank": 0, "score": 14104.936708526924 }, { "content": "\n\n#include \"VKSFile.h\"\n\n#include \"n...
C++
src/carnot/end_to_end_join_test.cc
hangqiu/pixie
1dd4af47d40ff856c4d52a1d6de81f78a76ff31e
#include <google/protobuf/text_format.h> #include <algorithm> #include <map> #include <tuple> #include <unordered_map> #include <vector> #include <pypa/parser/parser.hh> #include "src/carnot/carnot.h" #include "src/carnot/exec/local_grpc_result_server.h" #include "src/carnot/exec/test_utils.h" #include "src/carnot/udf_exporter/udf_exporter.h" #include "src/common/testing/testing.h" #include "src/table_store/table_store.h" namespace px { namespace carnot { using exec::CarnotTestUtils; class JoinTest : public ::testing::Test { protected: void SetUp() override { Test::SetUp(); table_store_ = std::make_shared<table_store::TableStore>(); result_server_ = std::make_unique<exec::LocalGRPCResultSinkServer>(); carnot_ = Carnot::Create(sole::uuid4(), table_store_, std::bind(&exec::LocalGRPCResultSinkServer::StubGenerator, result_server_.get(), std::placeholders::_1)) .ConsumeValueOrDie(); auto left_table = CarnotTestUtils::TestTable(); table_store_->AddTable("left_table", left_table); auto right_table = CarnotTestUtils::TestTable(); table_store_->AddTable("right_table", right_table); } std::shared_ptr<table_store::TableStore> table_store_; std::unique_ptr<exec::LocalGRPCResultSinkServer> result_server_; std::unique_ptr<Carnot> carnot_; }; TEST_F(JoinTest, basic) { std::string queryString = "import px\n" "src1 = px.DataFrame(table='left_table', select=['col1', 'col2'])\n" "src2 = px.DataFrame(table='right_table', select=['col1', 'col2'])\n" "join = src1.merge(src2, how='inner', left_on=['col1', 'col2'], right_on=['col1', 'col2'], " "suffixes=['', '_x'])\n" "join['left_col1'] = join['col1']\n" "join['right_col2'] = join['col2']\n" "df = join[['left_col1', 'right_col2']]\n" "px.display(df, 'joined')"; auto query = absl::StrJoin({queryString}, "\n"); auto query_id = sole::uuid4(); auto s = carnot_->ExecuteQuery(query, query_id, 0); ASSERT_OK(s); auto exec_stats = result_server_->exec_stats().ConsumeValueOrDie(); EXPECT_EQ(10, exec_stats.execution_stats().records_processed()); EXPECT_EQ(10 * sizeof(double) + 10 * sizeof(int64_t), exec_stats.execution_stats().bytes_processed()); EXPECT_LT(0, exec_stats.execution_stats().timing().execution_time_ns()); EXPECT_THAT(result_server_->output_tables(), ::testing::UnorderedElementsAre("joined")); auto output_batches = result_server_->query_results("joined"); EXPECT_EQ(1, output_batches.size()); auto rb1 = output_batches[0]; std::vector<types::Float64Value> expected_col1 = {0.5, 1.2, 5.3, 0.1, 5.1}; std::vector<types::Int64Value> expected_col2 = {1, 2, 3, 5, 6}; EXPECT_TRUE(rb1.ColumnAt(0)->Equals(types::ToArrow(expected_col1, arrow::default_memory_pool()))); EXPECT_TRUE(rb1.ColumnAt(1)->Equals(types::ToArrow(expected_col2, arrow::default_memory_pool()))); } TEST_F(JoinTest, self_join) { std::string queryString = "import px\n" "src1 = px.DataFrame(table='left_table', select=['col1', 'col2'])\n" "join = src1.merge(src1, how='inner', left_on=['col1'], right_on=['col1'], " "suffixes=['', '_x'])\n" "join['left_col1'] = join['col1']\n" "join['right_col2'] = join['col2_x']\n" "output = join[['left_col1', 'right_col2']]\n" "px.display(output, 'joined')"; auto query = absl::StrJoin({queryString}, "\n"); auto query_id = sole::uuid4(); auto s = carnot_->ExecuteQuery(query, query_id, 0); ASSERT_OK(s); auto exec_stats = result_server_->exec_stats().ConsumeValueOrDie(); EXPECT_EQ(5, exec_stats.execution_stats().records_processed()); EXPECT_EQ(5 * sizeof(double) + 5 * sizeof(int64_t), exec_stats.execution_stats().bytes_processed()); EXPECT_LT(0, exec_stats.execution_stats().timing().execution_time_ns()); EXPECT_THAT(result_server_->output_tables(), ::testing::UnorderedElementsAre("joined")); auto output_batches = result_server_->query_results("joined"); EXPECT_EQ(1, output_batches.size()); auto rb1 = output_batches[0]; std::vector<types::Float64Value> expected_col1 = {0.5, 1.2, 5.3, 0.1, 5.1}; std::vector<types::Int64Value> expected_col2 = {1, 2, 3, 5, 6}; EXPECT_TRUE(rb1.ColumnAt(0)->Equals(types::ToArrow(expected_col1, arrow::default_memory_pool()))); EXPECT_TRUE(rb1.ColumnAt(1)->Equals(types::ToArrow(expected_col2, arrow::default_memory_pool()))); } } }
#include <google/protobuf/text_format.h> #include <algorithm> #include <map> #include <tuple> #include <unordered_map> #include <vector> #include <pypa/parser/parser.hh> #include "src/carnot/carnot.h" #include "src/carnot/exec/local_grpc_result_server.h" #include "src/carnot/exec/test_utils.h" #include "src/carnot/udf_exporter/udf_exporter.h" #include "src/common/testing/testing.h" #include "src/table_store/table_store.h" namespace px { namespace carnot { using exec::CarnotTestUtils; class JoinTest : public ::testing::Test { protected: void SetUp() override { Test::SetUp(); table_store_ = std::make_shared<table_store::TableStore>(); result_server_ = std::make_unique<exec::LocalGRPCResultSinkServer>(); carnot_ = Carnot::Create(sole::uuid4(), table_store_, std::bind(&exec::LocalGRPCResultSinkServer::StubGenerator, result_server_.get(), std::placeholders::_1)) .ConsumeValueOrDie(); auto left_table = CarnotTestUtils::TestTable(); table_store_->AddTable("left_table", left_table); auto right_table = CarnotTestUtils::TestTable(); table_store_->AddTable("right_table", right_table); } std::shared_ptr<table_store::TableStore> table_store_; std::unique_ptr<exec::LocalGRPCResultSinkServer> result_server_; std::unique_ptr<Carnot> carnot_; }; TEST_F(JoinTest, basic) { std::string queryString = "import px\n" "src1 = px.DataFrame(table='left_table', select=['col1', 'col2'])\n" "src2 = px.DataFrame(table='right_table', select=['col1', 'col2'])\n" "join = src1.merge(src2, how='inner', left_on=['col1', 'col2'], right_on=['col1', 'col2'], " "suffixes=['', '_x'])\n" "join['left_col1'] = join['col1']\n" "join['right_col2'] = join['col2']\n" "df = join[['left_col1', 'right_col2']]\n" "px.display(df, 'joined')"; auto query = absl::StrJoin({queryString}, "\n"); auto query_id = sole::uuid4(); auto s = carnot_->ExecuteQuery(query, query_id, 0); ASSERT_OK(s); auto exec_stats = result_server_->exec_stats().ConsumeValueOrDie(); EXPECT_EQ(10, exec_stats.execution_stats().records_processed()); EXPECT_EQ(10 * sizeof(double) + 10 * sizeof(int64_t), exec_stats.execution_stats().bytes_processed()); EXPECT_LT(0, exec_stats.execution_stats().timing().execution_time_ns()); EXPECT_THAT(result_server_->output_tables(), ::testing::UnorderedElementsAre("joined")); auto output_batches = result_server_->query_results("joined"); EXPECT_EQ(1, output_batches.size()); auto rb1 = output_batches[0]; std::vector<types::Float64Value> expected_col1 = {0.5, 1.2, 5.3, 0.
auto query = absl::StrJoin({queryString}, "\n"); auto query_id = sole::uuid4(); auto s = carnot_->ExecuteQuery(query, query_id, 0); ASSERT_OK(s); auto exec_stats = result_server_->exec_stats().ConsumeValueOrDie(); EXPECT_EQ(5, exec_stats.execution_stats().records_processed()); EXPECT_EQ(5 * sizeof(double) + 5 * sizeof(int64_t), exec_stats.execution_stats().bytes_processed()); EXPECT_LT(0, exec_stats.execution_stats().timing().execution_time_ns()); EXPECT_THAT(result_server_->output_tables(), ::testing::UnorderedElementsAre("joined")); auto output_batches = result_server_->query_results("joined"); EXPECT_EQ(1, output_batches.size()); auto rb1 = output_batches[0]; std::vector<types::Float64Value> expected_col1 = {0.5, 1.2, 5.3, 0.1, 5.1}; std::vector<types::Int64Value> expected_col2 = {1, 2, 3, 5, 6}; EXPECT_TRUE(rb1.ColumnAt(0)->Equals(types::ToArrow(expected_col1, arrow::default_memory_pool()))); EXPECT_TRUE(rb1.ColumnAt(1)->Equals(types::ToArrow(expected_col2, arrow::default_memory_pool()))); } } }
1, 5.1}; std::vector<types::Int64Value> expected_col2 = {1, 2, 3, 5, 6}; EXPECT_TRUE(rb1.ColumnAt(0)->Equals(types::ToArrow(expected_col1, arrow::default_memory_pool()))); EXPECT_TRUE(rb1.ColumnAt(1)->Equals(types::ToArrow(expected_col2, arrow::default_memory_pool()))); } TEST_F(JoinTest, self_join) { std::string queryString = "import px\n" "src1 = px.DataFrame(table='left_table', select=['col1', 'col2'])\n" "join = src1.merge(src1, how='inner', left_on=['col1'], right_on=['col1'], " "suffixes=['', '_x'])\n" "join['left_col1'] = join['col1']\n" "join['right_col2'] = join['col2_x']\n" "output = join[['left_col1', 'right_col2']]\n" "px.display(output, 'joined')";
random
[ { "content": "class SetupJoinTypeRule : public Rule {\n\n /**\n\n * @brief Converts a right join into a left join.\n\n *\n\n */\n\n public:\n\n SetupJoinTypeRule()\n\n : Rule(nullptr, /*use_topo*/ false, /*reverse_topological_execution*/ false) {}\n\n\n\n protected:\n\n StatusOr<bool> Apply(IRNode...
C++
GLAC/observables/latticeactionchargedensity.cpp
hmvege/GluonicLQCD
9bb7466fce408bf51cb98d65f639acd37d034d62
#include "latticeactionchargedensity.h" #include <cmath> #include "parallelization/communicator.h" #include "config/parameters.h" #include "io/fieldio.h" LatticeActionChargeDensity::LatticeActionChargeDensity(const bool flow) : Correlator() { initializeObservableStorer(flow); m_plaqMultiplicationFactor = 1.0/(18.0*double(m_latticeSize)); m_topcMultiplicationFactor = 1.0/(16*16*M_PI*M_PI); m_energyMultiplicationFactor = 1.0/double(Parameters::getLatticeSize()); m_clov1.allocate(m_N); m_clov2.allocate(m_N); m_U2Temp.allocate(m_N); m_U3Temp.allocate(m_N); m_temp.allocate(m_N); m_tempDiag.allocate(m_N); m_topCharge.allocate(m_N); m_energy.allocate(m_N); m_samplingFrequency = Parameters::getSamplingFrequency(); } LatticeActionChargeDensity::~LatticeActionChargeDensity() { delete m_plaqObservable; delete m_topcObservable; delete m_energyObservable; } void LatticeActionChargeDensity::initializeObservableStorer(const bool storeFlowObservable) { m_storeFlowObservable = storeFlowObservable; if (m_storeFlowObservable) { m_plaqObservable = new ObservableStorer(Parameters::getNFlows() + 1); m_topcObservable = new ObservableStorer(Parameters::getNFlows() + 1); m_energyObservable = new ObservableStorer(Parameters::getNFlows() + 1); } else { if (Parameters::getStoreThermalizationObservables()) { m_plaqObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); m_topcObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); m_energyObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); } else { m_plaqObservable = new ObservableStorer(Parameters::getNCf()); m_topcObservable = new ObservableStorer(Parameters::getNCf()); m_energyObservable = new ObservableStorer(Parameters::getNCf()); } } m_plaqObservable->setNormalizeObservableByProcessor(true); m_plaqObservable->setObservableName("plaq"); m_topcObservable->setObservableName("topc"); m_energyObservable->setObservableName("energy"); } void LatticeActionChargeDensity::writeFlowObservablesToFile(const unsigned int iFlow) { m_plaqObservable->gatherResults(); m_plaqObservable->writeFlowObservableToFile(iFlow); m_topcObservable->gatherResults(); m_topcObservable->writeFlowObservableToFile(iFlow); m_energyObservable->gatherResults(); m_energyObservable->writeFlowObservableToFile(iFlow); } void LatticeActionChargeDensity::writeObservableToFile(const double acceptanceRatio) { m_plaqObservable->writeObservableToFile(acceptanceRatio); m_topcObservable->writeObservableToFile(acceptanceRatio); m_energyObservable->writeObservableToFile(acceptanceRatio); } void LatticeActionChargeDensity::reset() { m_plaqObservable->reset(); m_topcObservable->reset(); m_energyObservable->reset(); } void LatticeActionChargeDensity::runStatistics() { m_plaqObservable->runStatistics(); m_topcObservable->runStatistics(); m_energyObservable->runStatistics(); } void LatticeActionChargeDensity::printHeader() { if (!m_storeFlowObservable) { printf("%-*s %-*s %-*s", m_headerWidth,m_plaqObservable->getObservableName().c_str(), m_headerWidth,m_topcObservable->getObservableName().c_str(), m_headerWidth,m_energyObservable->getObservableName().c_str()); } else { printf("\ni t %-*s %-*s %-*s", m_headerWidth,m_plaqObservable->getObservableName().c_str(), m_headerWidth,m_topcObservable->getObservableName().c_str(), m_headerWidth,m_energyObservable->getObservableName().c_str()); } } void LatticeActionChargeDensity::printObservable(const unsigned int iObs) { if (!m_storeFlowObservable) { if (Parallel::Communicator::getProcessRank() == 0) { printf("%-*.8f %-*.8f %-*.8f", m_headerWidth,m_plaqObservable->getObservable(iObs), m_headerWidth,m_topcObservable->getObservable(iObs), m_headerWidth,m_energyObservable->getObservable(iObs)); } } else { double plaqObs = m_plaqObservable->getObservable(iObs); double topcObs = m_topcObservable->getObservable(iObs); double energyObs = m_energyObservable->getObservable(iObs); Parallel::Communicator::gatherDoubleResults(&plaqObs,1); Parallel::Communicator::gatherDoubleResults(&topcObs,1); Parallel::Communicator::gatherDoubleResults(&energyObs,1); if (Parallel::Communicator::getProcessRank() == 0) { printf("\n%-4d %-3.3f %-*.15f %-*.15f %-*.15f", iObs, double(iObs)*Parameters::getFlowEpsilon(), m_headerWidth,plaqObs/double(Parallel::Communicator::getNumProc()), m_headerWidth,topcObs, m_headerWidth,energyObs); } } } void LatticeActionChargeDensity::printStatistics() { m_plaqObservable->printStatistics(); m_topcObservable->printStatistics(); m_energyObservable->printStatistics(); } void LatticeActionChargeDensity::copyObservable(const unsigned int iObs, const std::vector<double> &obs) { (*m_plaqObservable)[iObs] = obs[0]; (*m_topcObservable)[iObs] = obs[1]; (*m_energyObservable)[iObs] = obs[2]; } std::vector<double> LatticeActionChargeDensity::getObservablesVector(const unsigned int iObs) { std::vector<double> obs(3); obs[0] = (*m_plaqObservable)[iObs]; obs[1] = (*m_topcObservable)[iObs]; obs[2] = (*m_energyObservable)[iObs]; return obs; } void LatticeActionChargeDensity::calculate(Lattice<SU3> *lattice, const unsigned int iObs) { m_topCharge.zeros(); m_energy.zeros(); m_plaquette = 0; mu = 0; for (int nu = 1; nu < 4; nu++) { m_temp = lattice[mu]; m_temp *= shift(lattice[nu],FORWARDS,mu); m_temp *= inv(shift(lattice[mu],FORWARDS,nu)); m_temp *= inv(lattice[nu]); m_clov1 = m_temp; m_plaquette += sumRealTrace(m_clov1); m_U2Temp = shift(lattice[nu],BACKWARDS,nu); m_U3Temp = inv(shift(lattice[mu],BACKWARDS,mu)); m_temp = lattice[mu]; m_temp *= inv(shift(shift(lattice[nu],FORWARDS,mu),BACKWARDS,nu)); m_temp *= inv(shift(lattice[mu],BACKWARDS,nu)); m_temp *= m_U2Temp; m_clov1 -= m_temp; m_temp = m_U3Temp; m_temp *= inv(shift(shift(lattice[nu],BACKWARDS,mu),BACKWARDS,nu)); m_temp *= shift(shift(lattice[mu],BACKWARDS,mu),BACKWARDS,nu); m_temp *= m_U2Temp; m_clov1 += m_temp; m_temp = m_U3Temp; m_temp *= shift(lattice[nu],BACKWARDS,mu); m_temp *= shift(shift(lattice[mu],FORWARDS,nu),BACKWARDS,mu); m_temp *= inv(lattice[nu]); m_clov1 -= m_temp; rho = nu % 3; rho++; sigma = rho % 3; sigma++; m_temp = lattice[rho]; m_temp *= shift(lattice[sigma],FORWARDS,rho); m_temp *= inv(shift(lattice[rho],FORWARDS,sigma)); m_temp *= inv(lattice[sigma]); m_clov2 = m_temp; m_U2Temp = shift(lattice[sigma],BACKWARDS,sigma); m_U3Temp = inv(shift(lattice[rho],BACKWARDS,rho)); m_plaquette += sumRealTrace(m_clov2); m_temp = lattice[rho]; m_temp *= inv(shift(shift(lattice[sigma],FORWARDS,rho),BACKWARDS,sigma)); m_temp *= inv(shift(lattice[rho],BACKWARDS,sigma)); m_temp *= m_U2Temp; m_clov2 -= m_temp; m_temp = m_U3Temp; m_temp *= inv(shift(shift(lattice[sigma],BACKWARDS,rho),BACKWARDS,sigma)); m_temp *= shift(shift(lattice[rho],BACKWARDS,rho),BACKWARDS,sigma); m_temp *= m_U2Temp; m_clov2 += m_temp; m_temp = m_U3Temp; m_temp *= shift(lattice[sigma],BACKWARDS,rho); m_temp *= shift(shift(lattice[rho],FORWARDS,sigma),BACKWARDS,rho); m_temp *= inv(lattice[sigma]); m_clov2 -= m_temp; m_temp = inv(m_clov1); m_clov1 -= m_temp; m_tempDiag = imagTrace(m_clov1)/3.0; m_clov1 = subtractImag(m_clov1,m_tempDiag); m_temp = inv(m_clov2); m_clov2 -= m_temp; m_tempDiag = imagTrace(m_clov2)/3.0; m_clov2 = subtractImag(m_clov2,m_tempDiag); m_topCharge -= realTraceMultiplication(m_clov1,m_clov2); m_energy += realTraceMultiplication(m_clov1,m_clov1); m_energy += realTraceMultiplication(m_clov2,m_clov2); } m_plaquette *= m_plaqMultiplicationFactor; (*m_plaqObservable)[iObs] = m_plaquette; m_topCharge *= m_topcMultiplicationFactor; if (m_storeFlowObservable && (iObs % m_samplingFrequency) == 0) { IO::FieldIO::writeDoublesFieldToFile(m_topCharge, iObs, m_topcObservable->getObservableName()); } if (!m_storeFlowObservable) { IO::FieldIO::writeDoublesFieldToFile(m_topCharge, iObs, m_topcObservable->getObservableName()); } (*m_topcObservable)[iObs] = sum(m_topCharge); if (m_storeFlowObservable && (iObs % m_samplingFrequency) == 0) { IO::FieldIO::writeDoublesFieldToFile(m_energy, iObs, m_energyObservable->getObservableName()); } if (!m_storeFlowObservable) { IO::FieldIO::writeDoublesFieldToFile(m_energy, iObs, m_energyObservable->getObservableName()); } (*m_energyObservable)[iObs] = m_energyMultiplicationFactor * sum(m_energy); }
#include "latticeactionchargedensity.h" #include <cmath> #include "parallelization/communicator.h" #include "config/parameters.h" #include "io/fieldio.h" LatticeActionChargeDensity::LatticeActionChargeDensity(const bool flow) : Correlator() { initializeObservableStorer(flow); m_plaqMultiplicationFactor = 1.0/(18.0*double(m_latticeSize)); m_topcMultiplicationFactor = 1.0/(16*16*M_PI*M_PI); m_energyMultiplicationFactor = 1.0/double(Parameters::getLatticeSize()); m_clov1.allocate(m_N); m_clov2.allocate(m_N); m_U2Temp.allocate(m_N); m_U3Temp.allocate(m_N); m_temp.allocate(m_N); m_tempDiag.allocate(m_N); m_topCharge.allocate(m_N); m_energy.allocate(m_N); m_samplingFrequency = Parameters::getSamplingFrequency(); } LatticeActionChargeDensity::~LatticeActionChargeDensity() { delete m_plaqObservable; delete m_topcObservable; delete m_energyObservable; } void LatticeActionChargeDensity::initializeObservableStorer(const bool storeFlowObservable) { m_storeFlowObservable = storeFlowObservable; if (m_storeFlowObservable) { m_plaqObservable = new ObservableStorer(Parameters::getNFlows() + 1); m_topcObservable = new ObservableStorer(Parameters::getNFlows() + 1); m_energyObservable = new ObservableStorer(Parameters::getNFlows() + 1); } else { if (Parameters::getStoreThermalizationObservables()) { m_plaqObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); m_topcObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); m_energyObservable = new ObservableStorer(Parameters::getNCf() + Parameters::getNTherm() + 1); } else { m_plaqObservable = new ObservableStorer(Parameters::getNCf()); m_topcObservable = new ObservableStorer(Parameters::getNCf()); m_energyObservable = new ObservableStorer(Parameters::getNCf()); } } m_plaqObservable->setNormalizeObservableByProcessor(true); m_plaqObservable->setObservableName("plaq"); m_topcObservable->setObservableName("topc"); m_energyObservable->setObservableName("energy"); } void LatticeActionChargeDensity::writeFlowObservablesToFile(const unsigned int iFlow) { m_plaqObservable->gatherResults(); m_plaqObservable->writeFlowObservableToFile(iFlow); m_topcObservable->gatherResults(); m_topcObservable->writeFlowObservableToFile(iFlow); m_energyObservable->gatherResults(); m_energyObservable->writeFlowObservableToFile(iFlow); } void LatticeActionChargeDensity::writeObservableToFile(const double acceptanceRatio) { m_plaqObservable->writeObservableToFile(acceptanceRatio); m_topcObservable->writeObservableToFile(acceptanceRatio); m_energyObservable->writeObservableToFile(acceptanceRatio); } void LatticeActionChargeDensity::reset() { m_plaqObservable->reset(); m_topcObservable->reset(); m_energyObservable->reset(); } void LatticeActionChargeDensity::runStatistics() { m_plaqObservable->runStatistics(); m_topcObservable->runStatistics(); m_energyObservable->runStatistics(); } void LatticeActionChargeDensity::printHeader() { if (!m_storeFlowObservable) { printf("%-*s %-*s %-*s", m_headerWidth,m_plaqObservable->getObservableName().c_str(), m_headerWidth,m_topcObservable->getObservableName().c_str(), m_headerWidth,m_energyObservable->getObservableName().c_str()); } else { printf("\ni t %-*s %-*s %-*s", m_headerWidth,m_plaqObservable->getObservableName().c_str(), m_headerWidth,m_topcObservable->getObservableName().c_str(), m_headerWidth,m_energyObservable->getObservableName().c_str()); } } void LatticeActionChargeDensity::printObservable(const unsigned int iObs) { if (!m_storeFlowObservable) { if (Parallel::Communicator::getProcessRank() == 0) { printf("%-*.8f %-*.8f %-*.8f", m_headerWidth,m_plaqObservable->getObservable(iObs), m_headerWidth,m_topcObservable->getObservable(iObs), m_headerWidth,m_energyObservable->getObservable(iObs)); } } else { double plaqObs = m_plaqObservable->getObservable(iObs); double topcObs = m_topcObservable->getObservable(iObs); double energyObs = m_energyObservable->getObservable(iObs); Parallel::Communicator::gatherDoubleResults(&plaqObs,1); Parallel::Communicator::gatherDoubleResults(&topcObs,1); Parallel::Communicator::gatherDoubleResults(&energyObs,1); if (Parallel::Communicator::getProcessRank() == 0) { printf("\n%-4d %-3.3f %-*.15f %-*.15f %-*.15f", iObs, double(iObs)*Parameters::getFlowEpsilon(), m_headerWidth,plaqObs/double(Parallel::Communicator::getNumProc()), m_headerWidth,topcObs, m_headerWidth,energyObs); } } } void LatticeActio
void LatticeActionChargeDensity::copyObservable(const unsigned int iObs, const std::vector<double> &obs) { (*m_plaqObservable)[iObs] = obs[0]; (*m_topcObservable)[iObs] = obs[1]; (*m_energyObservable)[iObs] = obs[2]; } std::vector<double> LatticeActionChargeDensity::getObservablesVector(const unsigned int iObs) { std::vector<double> obs(3); obs[0] = (*m_plaqObservable)[iObs]; obs[1] = (*m_topcObservable)[iObs]; obs[2] = (*m_energyObservable)[iObs]; return obs; } void LatticeActionChargeDensity::calculate(Lattice<SU3> *lattice, const unsigned int iObs) { m_topCharge.zeros(); m_energy.zeros(); m_plaquette = 0; mu = 0; for (int nu = 1; nu < 4; nu++) { m_temp = lattice[mu]; m_temp *= shift(lattice[nu],FORWARDS,mu); m_temp *= inv(shift(lattice[mu],FORWARDS,nu)); m_temp *= inv(lattice[nu]); m_clov1 = m_temp; m_plaquette += sumRealTrace(m_clov1); m_U2Temp = shift(lattice[nu],BACKWARDS,nu); m_U3Temp = inv(shift(lattice[mu],BACKWARDS,mu)); m_temp = lattice[mu]; m_temp *= inv(shift(shift(lattice[nu],FORWARDS,mu),BACKWARDS,nu)); m_temp *= inv(shift(lattice[mu],BACKWARDS,nu)); m_temp *= m_U2Temp; m_clov1 -= m_temp; m_temp = m_U3Temp; m_temp *= inv(shift(shift(lattice[nu],BACKWARDS,mu),BACKWARDS,nu)); m_temp *= shift(shift(lattice[mu],BACKWARDS,mu),BACKWARDS,nu); m_temp *= m_U2Temp; m_clov1 += m_temp; m_temp = m_U3Temp; m_temp *= shift(lattice[nu],BACKWARDS,mu); m_temp *= shift(shift(lattice[mu],FORWARDS,nu),BACKWARDS,mu); m_temp *= inv(lattice[nu]); m_clov1 -= m_temp; rho = nu % 3; rho++; sigma = rho % 3; sigma++; m_temp = lattice[rho]; m_temp *= shift(lattice[sigma],FORWARDS,rho); m_temp *= inv(shift(lattice[rho],FORWARDS,sigma)); m_temp *= inv(lattice[sigma]); m_clov2 = m_temp; m_U2Temp = shift(lattice[sigma],BACKWARDS,sigma); m_U3Temp = inv(shift(lattice[rho],BACKWARDS,rho)); m_plaquette += sumRealTrace(m_clov2); m_temp = lattice[rho]; m_temp *= inv(shift(shift(lattice[sigma],FORWARDS,rho),BACKWARDS,sigma)); m_temp *= inv(shift(lattice[rho],BACKWARDS,sigma)); m_temp *= m_U2Temp; m_clov2 -= m_temp; m_temp = m_U3Temp; m_temp *= inv(shift(shift(lattice[sigma],BACKWARDS,rho),BACKWARDS,sigma)); m_temp *= shift(shift(lattice[rho],BACKWARDS,rho),BACKWARDS,sigma); m_temp *= m_U2Temp; m_clov2 += m_temp; m_temp = m_U3Temp; m_temp *= shift(lattice[sigma],BACKWARDS,rho); m_temp *= shift(shift(lattice[rho],FORWARDS,sigma),BACKWARDS,rho); m_temp *= inv(lattice[sigma]); m_clov2 -= m_temp; m_temp = inv(m_clov1); m_clov1 -= m_temp; m_tempDiag = imagTrace(m_clov1)/3.0; m_clov1 = subtractImag(m_clov1,m_tempDiag); m_temp = inv(m_clov2); m_clov2 -= m_temp; m_tempDiag = imagTrace(m_clov2)/3.0; m_clov2 = subtractImag(m_clov2,m_tempDiag); m_topCharge -= realTraceMultiplication(m_clov1,m_clov2); m_energy += realTraceMultiplication(m_clov1,m_clov1); m_energy += realTraceMultiplication(m_clov2,m_clov2); } m_plaquette *= m_plaqMultiplicationFactor; (*m_plaqObservable)[iObs] = m_plaquette; m_topCharge *= m_topcMultiplicationFactor; if (m_storeFlowObservable && (iObs % m_samplingFrequency) == 0) { IO::FieldIO::writeDoublesFieldToFile(m_topCharge, iObs, m_topcObservable->getObservableName()); } if (!m_storeFlowObservable) { IO::FieldIO::writeDoublesFieldToFile(m_topCharge, iObs, m_topcObservable->getObservableName()); } (*m_topcObservable)[iObs] = sum(m_topCharge); if (m_storeFlowObservable && (iObs % m_samplingFrequency) == 0) { IO::FieldIO::writeDoublesFieldToFile(m_energy, iObs, m_energyObservable->getObservableName()); } if (!m_storeFlowObservable) { IO::FieldIO::writeDoublesFieldToFile(m_energy, iObs, m_energyObservable->getObservableName()); } (*m_energyObservable)[iObs] = m_energyMultiplicationFactor * sum(m_energy); }
nChargeDensity::printStatistics() { m_plaqObservable->printStatistics(); m_topcObservable->printStatistics(); m_energyObservable->printStatistics(); }
function_block-function_prefixed
[ { "content": "class Flow\n\n{\n\nprivate:\n\n // Flow update step\n\n double m_epsilon = 0.02;\n\n // Lattice constants\n\n std::vector<unsigned int> m_N;\n\n unsigned long int m_subLatticeSize;\n\n // Temporary lattice to use when flowing\n\n Lattice<SU3> *m_tempLattice;\n\n Lattice<SU3...
C++
src/Cluster/ClusterMain.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
#include "Generic/common/leak_detection.h" #include "Generic/common/limits.h" #include "Generic/common/ParamReader.h" #include "Generic/common/UnrecoverableException.h" #include "Generic/common/UTF8InputStream.h" #include "Generic/common/UTF8OutputStream.h" #include "Generic/common/UTF8Token.h" #include "ReplaceLowFreq/ReplaceLowFreq.h" #include "ExtractBigrams/ExtractBigrams.h" #include "ExtractBigrams/WSTokenizer.h" #include "Cluster/MICluster.h" #include <vector> #if defined (_WIN32) #include <direct.h> #include <process.h> #endif #include <ctime> #include <boost/scoped_ptr.hpp> using namespace std; const int max_token_sequences = 1; void printDot(time_t &t) { time_t cur_time; time(&cur_time); if (cur_time - t >= 60) { cout << "."; t = cur_time; } } void printPercentage(int cur_count, int &prev_percentage, int total_count) { int percentage = static_cast<int>((cur_count / float(total_count)) * 100); if (percentage > prev_percentage) { if (percentage > 0) cout << "\b\b"; if (percentage > 10) cout << "\b"; cout << percentage << "%"; prev_percentage = percentage; } } void print100Percent(int percentage) { if (percentage < 100) { cout << "\b\b\b100%"; } } void runTokenizer(const char* param_file, const char* input_file, const char* output_file, const wchar_t* debug_filename) { static const std::string standaloneTokenizerBin = ParamReader::getParam("standalone_tokenizer_bin", "StandaloneTokenizer.exe "); string command = standaloneTokenizerBin+" "; command.append("\""); command.append(param_file); command.append("\""); command.append(" \""); command.append(input_file); command.append("\" \""); command.append(output_file); command.append("\" 1"); cout << "The tokenizer cmd is: " << command.c_str() << "\n"; if (system(command.c_str()) != 0) { cerr << "The tokenizer has failed on " << debug_filename << "\n"; } } int main(int argc, char **argv) { if (argc != 2) { cerr << "Cluster.exe should be invoked with a single argument, which provides a\n" << "path to the parameter file.\n"; return -1; } const int MAX_TOKEN_COUNT = 1000000; char tokens_file[500]; char temp_file[500]; try { time_t cur_time; time(&cur_time); cout << ctime(&cur_time); cout << "Initializing...\n"; const char* param_file = argv[1]; ParamReader::readParamFile(param_file); char document_filelist[500]; if(!ParamReader::getParam("cluster_document_filelist",document_filelist, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: cluster-document-filelist"); } bool skip_tokenization = ParamReader::isParamTrue("skip_tokenization"); bool make_lowercase = ParamReader::isParamTrue("make_tokens_lowercase"); if (make_lowercase && !skip_tokenization) { throw UnexpectedInputException( "Cluster::Main()", "make-tokens-lowercase can only be 'true' when skip-tokenization is also 'true'"); } if(!ParamReader::getParam("tokens_file", tokens_file, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: tokens-file"); } UTF8OutputStream tokenStream; if (skip_tokenization) { tokenStream.open(tokens_file); } else { if(!ParamReader::getParam("temp_file",temp_file, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: temp-file"); } } char outfile[500]; if(!ParamReader::getParam("cluster_outfile",outfile, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: cluster-outfile"); } char threshold_str[10]; if(!ParamReader::getParam("prune_threshold",threshold_str, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: prune-threshold"); } int threshold = atoi(threshold_str); char output_rare_words[10]; if(!ParamReader::getParam("output_rare_words",output_rare_words, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: output-rare-words"); } char rare_words_file[500]; if (strcmp(output_rare_words, "true") == 0) { if(!ParamReader::getParam("rare_words_file",rare_words_file, 500)){ throw UnexpectedInputException("Cluster::Main()", "Missing Parameter: rare-words-file"); } } char serif_style_cluster_output[10]; if(!ParamReader::getParam("serif_style_cluster_output", serif_style_cluster_output, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: serif-style-cluster-output"); } boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& uis(*uis_scoped_ptr); char msg[1000]; if(uis.fail()){ strcpy(msg, "Couldn't open document file list: "); strcat(msg, document_filelist); throw UnexpectedInputException( "Cluster::Main()", msg); } wstring path; UTF8Token token; int token_counter = 0; int batch_counter = 0; uis.open(document_filelist); while (!uis.eof()) { uis.getLine(path); if (path.size() == 0) continue; Symbol path_sym = Symbol(path.c_str()); boost::scoped_ptr<UTF8InputStream> in_scoped_ptr(UTF8InputStream::build(path.c_str())); UTF8InputStream& in(*in_scoped_ptr); if (skip_tokenization) { wstring line; while (!in.eof()) { in.getLine(line); if (make_lowercase) { std::wstring::size_type length = line.length(); for (size_t i = 0; i < length; ++i) { line[i] = towlower(line[i]); } } tokenStream << line << L"\n"; } in.close(); } else { UTF8OutputStream temp(temp_file); batch_counter = 0; while (!in.eof()) { if (token_counter > MAX_TOKEN_COUNT) { temp.close(); batch_counter++; time(&cur_time); cout << ctime(&cur_time); cout << "Running Tokenizer on " << path_sym.to_debug_string() << ", batch # " << batch_counter << " consisting of 1 million words...\n"; runTokenizer(param_file, temp_file, tokens_file, path_sym.to_string()); token_counter = 0; temp.open(temp_file); } token_counter++; in >> token; if (token_counter > 1) temp << L" "; temp << token.chars(); } in.close(); temp.close(); if (token_counter > 0) { batch_counter++; time(&cur_time); cout << ctime(&cur_time); cout << "Running Tokenizer on " << path_sym.to_debug_string() << ", batch # " << batch_counter << " consisting of " << token_counter << " words...\n"; runTokenizer(param_file, temp_file, tokens_file, path_sym.to_string()); } } } uis.close(); if (skip_tokenization) tokenStream.close(); else remove(temp_file); int prev_percentage = -1; int cur_count = 0; int token_count = 0; time(&cur_time); cout << ctime(&cur_time); cout << "Counting the total number of words..."; uis.close(); boost::scoped_ptr<UTF8InputStream> tokensIn_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn(*tokensIn_scoped_ptr); tokensIn.open(tokens_file); if(tokensIn.fail()){ strcpy(msg, "Couldn't open tokens file: "); strcat(msg, document_filelist); throw UnexpectedInputException( "Cluster::Main()", msg); } while (!tokensIn.eof()) { tokensIn >> token; token_count++; } tokensIn.close(); cout << token_count << "\n"; time(&cur_time); cout << ctime(&cur_time); cout << "Adding counts..."; ReplaceLowFreq * replaceLowFreq = _new ReplaceLowFreq(); boost::scoped_ptr<UTF8InputStream> tokensIn2_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn2(*tokensIn2_scoped_ptr); tokensIn2.open(tokens_file); while (!tokensIn2.eof()) { tokensIn2 >> token; replaceLowFreq->addCounts(token.symValue()); cur_count++; printPercentage(cur_count, prev_percentage, token_count); } tokensIn2.close(); print100Percent(prev_percentage); cout << endl; time(&cur_time); cout << ctime(&cur_time); cout << "Pruning...\n"; if (strcmp(output_rare_words, "true") == 0) replaceLowFreq->pruneToThreshold(threshold, rare_words_file); else replaceLowFreq->pruneToThreshold(threshold); time(&cur_time); cout << ctime(&cur_time); cout << "Replacing low frequency words and Extracting Bigrams..."; cur_count = 0; prev_percentage = -1; ExtractBigrams * extractor = _new ExtractBigrams(); boost::scoped_ptr<UTF8InputStream> tokensIn3_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn3(*tokensIn3_scoped_ptr); tokensIn3.open(tokens_file); while (!tokensIn3.eof()) { wstring tokenized_sent; tokensIn3.getLine(tokenized_sent); vector<wstring> tokens; WSTokenizer::tokenize(tokenized_sent, tokens); vector <wstring> results = replaceLowFreq->doReplaceLowFreq(tokens); extractor->extractBigrams(results); cur_count = cur_count + static_cast<int>(tokens.size()); printPercentage(cur_count, prev_percentage, token_count); } tokensIn3.close(); print100Percent(prev_percentage); cout << endl; delete replaceLowFreq; time(&cur_time); cout << ctime(&cur_time); cout << "Loading bigrams..."; MICluster * cluster = _new MICluster(); cluster->loadVocabulary(extractor->getVocabulary()); ExtractBigrams::BigramCount * bigramCount = extractor->getBigrams(); for (ExtractBigrams::BigramCount::iterator iter = bigramCount->begin(); iter != bigramCount->end(); ++iter) { cluster->loadBigram((*iter).first._h, (*iter).first._f, (*iter).second); printDot(cur_time); } cout << endl; delete extractor; time(&cur_time); cout << ctime(&cur_time); cout << "Clustering...\n"; cluster->doClusters(outfile); delete cluster; remove(tokens_file); } catch (UnexpectedInputException& e){ cout<<e.getMessage()<<" in "<<e.getSource()<<endl; return -1; } catch (char * err) { cout << "Internal error.\n" << err << "\nExiting...\n"; remove(tokens_file); return -1; } catch (char const* err) { cout << "Internal error.\n" << err << "\nExiting...\n"; remove(tokens_file); return -1; } #ifdef ENABLE_LEAK_DETECTION ParamReader::finalize(); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtDumpMemoryLeaks(); #endif #if defined(_DEBUG) || defined(_UNOPTIMIZED) printf("Press enter to exit....\n"); getchar(); #endif return 0; }
#include "Generic/common/leak_detection.h" #include "Generic/common/limits.h" #include "Generic/common/ParamReader.h" #include "Generic/common/UnrecoverableException.h" #include "Generic/common/UTF8InputStream.h" #include "Generic/common/UTF8OutputStream.h" #include "Generic/common/UTF8Token.h" #include "ReplaceLowFreq/ReplaceLowFreq.h" #include "ExtractBigrams/ExtractBigrams.h" #include "ExtractBigrams/WSTokenizer.h" #include "Cluster/MICluster.h" #include <vector> #if defined (_WIN32) #include <direct.h> #include <process.h> #endif #include <ctime> #include <boost/scoped_ptr.hpp> using namespace std; const int max_token_sequences = 1; void printDot(time_t &t) { time_t cur_time; time(&cur_time); if (cur_time - t >= 60) { cout << "."; t = cur_time; } } void printPercentage(int cur_count, int &prev_percentage, int total_count) { int percentage = static_cast<int>((cur_count / float(total_count)) * 100); if (percentage > prev_percentage) { if (percentage > 0) cout << "\b\b"; if (percentage > 10) cout << "\b"; cout << percentage << "%"; prev_percentage = percentage; } } void print100Percent(int percentage) { if (percentage < 100) { cout << "\b\b\b100%"; } } void runTokenizer(const char* param_file, const char* input_file, const char* output_file, const wchar_t* debug_filename) { static const std::string standaloneTokenizerBin = ParamReader::getParam("standalone_tokenizer_bin", "StandaloneTokenizer.exe "); string command = standaloneTokenizerBin+" "; command.append("\""); command.append(param_file); command.append("\""); command.append(" \""); command.append(input_file); command.append("\" \""); command.append(output_file); command.append("\" 1"); cout << "The tokenizer cmd is: " << command.c_str() << "\n"; if (system(command.c_str()) != 0) { cerr << "The tokenizer has failed on " << debug_filename << "\n"; } } int main(int argc, char **argv) { if (argc != 2) { cerr << "Cluster.exe should be invoked with a single argument, which provides a\n" << "path to the parameter file.\n"; return -1; } const int MAX_TOKEN_COUNT = 1000000; char tokens_file[500]; char temp_file[500]; try { time_t cur_time; time(&cur_time); cout << ctime(&cur_time); cout << "Initializing...\n"; const char* param_file = argv[1]; ParamReader::readParamFile(param_file); char document_filelist[500]; if(!ParamReader::getParam("cluster_document_filelist",document_filelist, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: cluster-document-filelist"); } bool skip_tokenization = ParamReader::isParamTrue("skip_tokenization"); bool make_lowercase = ParamReader::isParamTrue("make_tokens_lowercase"); if (make_lowercase && !skip_tokenization) { throw UnexpectedInputException( "Cluster::Main()", "make-tokens-lowercase can only be 'true' when skip-tokenization is also 'true'"); } if(!ParamReader::getParam("tokens_file", tokens_file, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: tokens-file"); } UTF8OutputStream tokenStream; if (skip_tokenization) { tokenStream.open(tokens_file); } else { if(!ParamReader::getParam("temp_file",temp_file, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: temp-file"); } } char outfile[500]; if(!ParamReader::getParam("cluster_outfile",outfile, 500)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: cluster-outfile"); } char threshold_str[10]; if(!ParamReader::getParam("prune_threshold",threshold_str, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: prune-threshold"); } int threshold = atoi(threshold_str); char output_rare_words[10];
char rare_words_file[500]; if (strcmp(output_rare_words, "true") == 0) { if(!ParamReader::getParam("rare_words_file",rare_words_file, 500)){ throw UnexpectedInputException("Cluster::Main()", "Missing Parameter: rare-words-file"); } } char serif_style_cluster_output[10]; if(!ParamReader::getParam("serif_style_cluster_output", serif_style_cluster_output, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: serif-style-cluster-output"); } boost::scoped_ptr<UTF8InputStream> uis_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& uis(*uis_scoped_ptr); char msg[1000]; if(uis.fail()){ strcpy(msg, "Couldn't open document file list: "); strcat(msg, document_filelist); throw UnexpectedInputException( "Cluster::Main()", msg); } wstring path; UTF8Token token; int token_counter = 0; int batch_counter = 0; uis.open(document_filelist); while (!uis.eof()) { uis.getLine(path); if (path.size() == 0) continue; Symbol path_sym = Symbol(path.c_str()); boost::scoped_ptr<UTF8InputStream> in_scoped_ptr(UTF8InputStream::build(path.c_str())); UTF8InputStream& in(*in_scoped_ptr); if (skip_tokenization) { wstring line; while (!in.eof()) { in.getLine(line); if (make_lowercase) { std::wstring::size_type length = line.length(); for (size_t i = 0; i < length; ++i) { line[i] = towlower(line[i]); } } tokenStream << line << L"\n"; } in.close(); } else { UTF8OutputStream temp(temp_file); batch_counter = 0; while (!in.eof()) { if (token_counter > MAX_TOKEN_COUNT) { temp.close(); batch_counter++; time(&cur_time); cout << ctime(&cur_time); cout << "Running Tokenizer on " << path_sym.to_debug_string() << ", batch # " << batch_counter << " consisting of 1 million words...\n"; runTokenizer(param_file, temp_file, tokens_file, path_sym.to_string()); token_counter = 0; temp.open(temp_file); } token_counter++; in >> token; if (token_counter > 1) temp << L" "; temp << token.chars(); } in.close(); temp.close(); if (token_counter > 0) { batch_counter++; time(&cur_time); cout << ctime(&cur_time); cout << "Running Tokenizer on " << path_sym.to_debug_string() << ", batch # " << batch_counter << " consisting of " << token_counter << " words...\n"; runTokenizer(param_file, temp_file, tokens_file, path_sym.to_string()); } } } uis.close(); if (skip_tokenization) tokenStream.close(); else remove(temp_file); int prev_percentage = -1; int cur_count = 0; int token_count = 0; time(&cur_time); cout << ctime(&cur_time); cout << "Counting the total number of words..."; uis.close(); boost::scoped_ptr<UTF8InputStream> tokensIn_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn(*tokensIn_scoped_ptr); tokensIn.open(tokens_file); if(tokensIn.fail()){ strcpy(msg, "Couldn't open tokens file: "); strcat(msg, document_filelist); throw UnexpectedInputException( "Cluster::Main()", msg); } while (!tokensIn.eof()) { tokensIn >> token; token_count++; } tokensIn.close(); cout << token_count << "\n"; time(&cur_time); cout << ctime(&cur_time); cout << "Adding counts..."; ReplaceLowFreq * replaceLowFreq = _new ReplaceLowFreq(); boost::scoped_ptr<UTF8InputStream> tokensIn2_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn2(*tokensIn2_scoped_ptr); tokensIn2.open(tokens_file); while (!tokensIn2.eof()) { tokensIn2 >> token; replaceLowFreq->addCounts(token.symValue()); cur_count++; printPercentage(cur_count, prev_percentage, token_count); } tokensIn2.close(); print100Percent(prev_percentage); cout << endl; time(&cur_time); cout << ctime(&cur_time); cout << "Pruning...\n"; if (strcmp(output_rare_words, "true") == 0) replaceLowFreq->pruneToThreshold(threshold, rare_words_file); else replaceLowFreq->pruneToThreshold(threshold); time(&cur_time); cout << ctime(&cur_time); cout << "Replacing low frequency words and Extracting Bigrams..."; cur_count = 0; prev_percentage = -1; ExtractBigrams * extractor = _new ExtractBigrams(); boost::scoped_ptr<UTF8InputStream> tokensIn3_scoped_ptr(UTF8InputStream::build()); UTF8InputStream& tokensIn3(*tokensIn3_scoped_ptr); tokensIn3.open(tokens_file); while (!tokensIn3.eof()) { wstring tokenized_sent; tokensIn3.getLine(tokenized_sent); vector<wstring> tokens; WSTokenizer::tokenize(tokenized_sent, tokens); vector <wstring> results = replaceLowFreq->doReplaceLowFreq(tokens); extractor->extractBigrams(results); cur_count = cur_count + static_cast<int>(tokens.size()); printPercentage(cur_count, prev_percentage, token_count); } tokensIn3.close(); print100Percent(prev_percentage); cout << endl; delete replaceLowFreq; time(&cur_time); cout << ctime(&cur_time); cout << "Loading bigrams..."; MICluster * cluster = _new MICluster(); cluster->loadVocabulary(extractor->getVocabulary()); ExtractBigrams::BigramCount * bigramCount = extractor->getBigrams(); for (ExtractBigrams::BigramCount::iterator iter = bigramCount->begin(); iter != bigramCount->end(); ++iter) { cluster->loadBigram((*iter).first._h, (*iter).first._f, (*iter).second); printDot(cur_time); } cout << endl; delete extractor; time(&cur_time); cout << ctime(&cur_time); cout << "Clustering...\n"; cluster->doClusters(outfile); delete cluster; remove(tokens_file); } catch (UnexpectedInputException& e){ cout<<e.getMessage()<<" in "<<e.getSource()<<endl; return -1; } catch (char * err) { cout << "Internal error.\n" << err << "\nExiting...\n"; remove(tokens_file); return -1; } catch (char const* err) { cout << "Internal error.\n" << err << "\nExiting...\n"; remove(tokens_file); return -1; } #ifdef ENABLE_LEAK_DETECTION ParamReader::finalize(); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtDumpMemoryLeaks(); #endif #if defined(_DEBUG) || defined(_UNOPTIMIZED) printf("Press enter to exit....\n"); getchar(); #endif return 0; }
if(!ParamReader::getParam("output_rare_words",output_rare_words, 10)){ throw UnexpectedInputException( "Cluster::Main()", "Missing Parameter: output-rare-words"); }
if_condition
[ { "content": "\tclass const_iterator: public boost::iterator_facade<const_iterator, std::vector<ActorMention_ptr> const, boost::forward_traversal_tag> {\n\n\tprivate:\n\n\t\tfriend class boost::iterator_core_access;\n\n\t\tfriend class ActorMentionSet;\n\n\t\texplicit const_iterator(ActorMentionMap::const_itera...
C++
src/bustools_extract.cpp
johan-gson/bustools
b0df3edef7e0df53d6461cd76572ae38280c4a94
#include <iostream> #include <fstream> #include <zlib.h> #include "kseq.h" #include "Common.hpp" #include "BUSData.h" #include "bustools_extract.h" KSEQ_INIT(gzFile, gzread); inline bool open_fastqs( std::vector<gzFile> &outFastq, std::vector<gzFile> &inFastq, std::vector<kseq_t *> &seq, const Bustools_opt &opt, size_t &iFastq) { for (int i = 0; i < opt.nFastqs; ++i) { gzclose(outFastq[i]); outFastq[i] = gzopen(std::string(opt.output + "/" + std::to_string(iFastq + 1) + ".fastq.gz").c_str(), "w"); gzclose(inFastq[i]); inFastq[i] = gzopen(opt.fastq[iFastq].c_str(), "r"); if (seq[i]) { kseq_destroy(seq[i]); } seq[i] = kseq_init(inFastq[i]); if (kseq_read(seq[i]) < 0) { return false; } ++iFastq; } return true; } void bustools_extract(const Bustools_opt &opt) { BUSHeader h; size_t nr = 0; size_t N = 100000; BUSData *p = new BUSData[N]; char *buf = new char[N]; buf[0] = '@'; std::streambuf *inbuf; std::ifstream inf; if (!opt.stream_in) { inf.open(opt.files[0].c_str(), std::ios::binary); inbuf = inf.rdbuf(); } else { inbuf = std::cin.rdbuf(); } std::istream in(inbuf); parseHeader(in, h); std::vector<gzFile> outFastq(opt.nFastqs); std::vector<gzFile> inFastq(opt.nFastqs); std::vector<kseq_t *> seq(opt.nFastqs, nullptr); uint32_t iRead = 0; size_t iFastq = 0; if (!open_fastqs(outFastq, inFastq, seq, opt, iFastq)) { std::cerr << "Error reading FASTQ " << opt.fastq[iFastq] << std::endl; goto end_extract; } while (true) { in.read((char *) p, N * sizeof(BUSData)); size_t rc = in.gcount() / sizeof(BUSData); if (rc == 0) { break; } nr += rc; for (size_t i = 0; i < rc; ++i) { while (iRead < p[i].flags) { for (const auto &s : seq) { int err_kseq_read = kseq_read(s); if (err_kseq_read == -1) { if (iFastq == opt.fastq.size()) { std::cerr << "Warning: number of reads in FASTQs was less than number of reads in BUS file" << std::endl; goto end_extract; } else { if (!open_fastqs(outFastq, inFastq, seq, opt, iFastq)) { std::cerr << "Error: cannot read FASTQ " << opt.fastq[iFastq] << std::endl; goto end_extract; } } } else if (err_kseq_read == -2) { std::cerr << "Error: truncated FASTQ" << std::endl; goto end_extract; } } ++iRead; } if (iRead > p[i].flags) { std::cerr << "BUS file not sorted by flag" << std::endl; goto end_extract; } for (int i = 0; i < opt.nFastqs; ++i) { int bufLen = 1; memcpy(buf + bufLen, seq[i]->name.s, seq[i]->name.l); bufLen += seq[i]->name.l; memcpy(buf + bufLen, seq[i]->comment.s, seq[i]->comment.l); bufLen += seq[i]->comment.l; buf[bufLen++] = '\n'; memcpy(buf + bufLen, seq[i]->seq.s, seq[i]->seq.l); bufLen += seq[i]->seq.l; buf[bufLen++] = '\n'; buf[bufLen++] = '+'; memcpy(buf + bufLen, seq[i]->name.s, seq[i]->name.l); bufLen += seq[i]->name.l; memcpy(buf + bufLen, seq[i]->comment.s, seq[i]->comment.l); bufLen += seq[i]->comment.l; buf[bufLen++] = '\n'; memcpy(buf + bufLen, seq[i]->qual.s, seq[i]->qual.l); bufLen += seq[i]->qual.l; buf[bufLen++] = '\n'; if (gzwrite(outFastq[i], buf, bufLen) != bufLen) { std::cerr << "Error writing to FASTQ" << std::endl; goto end_extract; } } } } std::cout << "Read in " << nr << " BUS records" << std::endl; end_extract: delete[] p; delete[] buf; for (auto &elt : outFastq) { gzclose(elt); } for (auto &elt : inFastq) { gzclose(elt); } for (auto &elt : seq) { if (elt) { kseq_destroy(elt); } } }
#include <iostream> #include <fstream> #include <zlib.h> #include "kseq.h" #include "Common.hpp" #include "BUSData.h" #include "bustools_extract.h" KSEQ_INIT(gzFile, gzread); inline bool open_fastqs( std::vector<gzFile> &outFastq, std::vector<gzFile> &inFastq, std::vector<kseq_t *> &seq, const Bustools_opt &opt, size_t &iFastq) { for (int i = 0; i < opt.nFastqs; ++i) { gzclose(outFastq[i]); outFastq[i] = gzopen(std::string(opt.output + "/" + std::to_string(iFastq + 1) + ".fastq.gz").c_str(), "w"); gzclose(inFastq[i]); inFastq[i] = gzopen(opt.fastq[iFastq].c_str(), "r"); if (seq[i]) { kseq_destroy(seq[i]); } seq[i] = kseq_init(inFastq[i]); if (kseq_read(seq[i]) < 0) { return false; } ++iFastq; } return true; } void bustools_extract(const Bustools_opt &opt) { BUSHeader h; size_t nr = 0; size_t N = 100000; BUSData *p = new BUSData[N]; char *buf = new char[N]; buf[0] = '@'; std::streambuf *inbuf; std::ifstream inf; if (!opt.stream_in) { inf.open(opt.files[0].c_str(), std::ios::binary); inbuf = inf.rdbuf(); } else { inbuf = std::cin.rdbuf(); } std::istream in(inbuf); parseHeader(in, h); std::vector<gzFile> outFastq(opt.nFastqs); std::vector<gzFile> inFastq(opt.nFastqs); std::vector<kseq_t *> seq(opt.nFastqs, nullptr); uint32_t iRead = 0; size_t iFastq = 0; if (!open_fastqs(outFastq, inFastq, seq, opt, iFastq)) { std::cerr << "Error reading FASTQ " << opt.fastq[iFastq] << std::endl; goto end_extract; } while (true) { in.read((char *) p, N * sizeof(BUSData)); size_t rc = in.gcount() / sizeof(BUSData); if (rc == 0) { break; } nr += rc; for (size_t i = 0; i < rc; ++i) { while (iRead < p[i].flags) { for (const auto &s : seq) { int err_kseq_read = kseq_read(s); if (err_kseq_read == -1) { if (iFastq == opt.fastq.size()) { std::cerr << "Warning: number of reads in FASTQs was less than number of reads in BUS file" << std::endl; goto end_extract; } else { if (!open_fastqs(outFastq, inFastq, seq, opt, iFastq)) { std::cerr << "Error: cannot read FASTQ " << opt.fastq[iFastq] << std::endl; goto end_extract; } } } else if (err_kseq_read == -2) { std::cerr << "Error: truncated FASTQ" << std::endl; goto end_extract; } } ++iRead; } if (iRead > p[i].flags) { std::cerr << "BUS file not sorted by flag" << std::endl; goto end_extract; } for (int i = 0; i < opt.nFastqs; ++i) { int bufLen = 1; memcpy(buf + bufLen, seq[i]->name.s, seq[i]->name.l); bufLen += seq[i]->name.l; memcpy(buf + bufLen, seq[i]->comment.s, seq[i]->comment.l); bufLen += seq[i]->comment.l; buf[bufLen++] = '\n'; memcpy(buf + bufLen, seq[i]->seq.s, seq[i]->seq.l); bufLen += seq[i]->seq.l; buf[bufLen++] = '\n'; buf[bufLen++] = '+'; memcpy(buf + bufLen, seq[i]->name.s, seq[i]->name.l); bufLen += seq[i]->name.l; memcpy(buf + bufLen, seq[i]->comment.s, seq[i]->comment.l); bufLen += seq[i]->comment.l; buf[bufLen++] = '\n'; memcpy(buf + bufLen, seq[i]->qual.s, seq[i]->qual.l); bufLen += seq[i]->qual.l;
buf[bufLen++] = '\n'; if (gzwrite(outFastq[i], buf, bufLen) != bufLen) { std::cerr << "Error writing to FASTQ" << std::endl; goto end_extract; } } } } std::cout << "Read in " << nr << " BUS records" << std::endl; end_extract: delete[] p; delete[] buf; for (auto &elt : outFastq) { gzclose(elt); } for (auto &elt : inFastq) { gzclose(elt); } for (auto &elt : seq) { if (elt) { kseq_destroy(elt); } } }
function_block-function_prefix_line
[ { "content": "enum SORT_TYPE : char {SORT_BC = 0, SORT_UMI, SORT_F, SORT_COUNT};\n", "file_path": "src/Common.hpp", "rank": 0, "score": 97682.47177461298 }, { "content": " function returns true and set element to the element of given rank.\n\n Otherwise, it returns false.\n\n ...
C++
TAO/orbsvcs/Logging_Service/RTEvent_Logging_Service/RTEvent_Logging_Service.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
#include "orbsvcs/Log_Macros.h" #include "RTEvent_Logging_Service.h" #include "tao/IORTable/IORTable.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_unistd.h" RTEvent_Logging_Service::RTEvent_Logging_Service (void) : service_name_ ("RTEventLogFactory"), ior_file_name_ (0), pid_file_name_ (0), bind_to_naming_service_ (true), nthreads_ (0) { } RTEvent_Logging_Service::~RTEvent_Logging_Service (void) { } void RTEvent_Logging_Service::init_ORB (int& argc, ACE_TCHAR *argv[]) { this->orb_ = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = this->orb_->resolve_initial_references("RootPOA"); this->poa_ = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = this->poa_->the_POAManager (); poa_manager->activate (); } int RTEvent_Logging_Service::parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("n:o:p:t:x")); int opt; while ((opt = get_opt ()) != EOF) { switch (opt) { case 'n': this->service_name_ = ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()); break; case 'o': this->ior_file_name_ = get_opt.opt_arg (); break; case 'p': this->pid_file_name_ = get_opt.opt_arg (); break; case 't': this->nthreads_ = ACE_OS::atoi (get_opt.opt_arg ()); break; case 'x': this->bind_to_naming_service_ = false; break; case '?': default: ORBSVCS_DEBUG ((LM_DEBUG, "Usage: %s " "-n service_name " "-o ior_file_name " "-p pid_file_name " "-t threads " "-x [disable naming service bind] " "\n", argv[0])); return -1; } } return 0; } int RTEvent_Logging_Service::init (int argc, ACE_TCHAR* argv[]) { this->init_ORB (argc, argv); if (this->parse_args (argc, argv) == -1) return -1; ACE_NEW_THROW_EX (this->rtevent_log_factory_, TAO_RTEventLogFactory_i (), CORBA::NO_MEMORY ()); if (this->rtevent_log_factory_->init (orb_.in (), poa_.in ()) != 0) { ORBSVCS_ERROR_RETURN ((LM_ERROR, "(%P|%t) Unable to initialize " "the factory.\n"), -1); } RTEventLogAdmin::EventLogFactory_var obj = this->rtevent_log_factory_->activate (); CORBA::String_var ior = this->orb_->object_to_string (obj.in ()); if (true) { CORBA::Object_var table_object = this->orb_->resolve_initial_references ("IORTable"); IORTable::Table_var adapter = IORTable::Table::_narrow (table_object.in ()); adapter->bind("RTEventLogService", ior.in ()); } if (this->ior_file_name_ != 0) { FILE* iorf = ACE_OS::fopen (this->ior_file_name_, ACE_TEXT("w")); if (iorf == 0) { ORBSVCS_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", this->ior_file_name_), -1); } ACE_OS::fprintf (iorf, "%s\n", ior.in ()); ACE_OS::fclose (iorf); } if (this->pid_file_name_ != 0) { FILE* pidf = ACE_OS::fopen (this->pid_file_name_, ACE_TEXT("w")); if (pidf != 0) { ACE_OS::fprintf (pidf, "%ld\n", static_cast<long> (ACE_OS::getpid ())); ACE_OS::fclose (pidf); } } if (this->bind_to_naming_service_) { this->resolve_naming_service (); CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup (this->service_name_.c_str ()); this->naming_->rebind (name, obj.in ()); } return 0; } void RTEvent_Logging_Service::resolve_naming_service (void) { CORBA::Object_var naming_obj = this->orb_->resolve_initial_references ("NameService"); if (CORBA::is_nil (naming_obj.in ())) throw CORBA::UNKNOWN (); this->naming_ = CosNaming::NamingContext::_narrow (naming_obj.in ()); } int RTEvent_Logging_Service::run (void) { if (this->nthreads_ > 0) { if (this->activate ((THR_NEW_LWP | THR_JOINABLE), this->nthreads_) != 0) return -1; this->thr_mgr ()->wait (); return 0; } this->orb_->run (); return 0; } int RTEvent_Logging_Service::svc (void) { try { this->orb_->run (); } catch (const CORBA::Exception&) { return -1; } return 0; } void RTEvent_Logging_Service::shutdown (void) { if (this->bind_to_naming_service_) { CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup (this->service_name_.c_str ()); this->naming_->unbind (name); } if (!CORBA::is_nil (this->orb_.in ())) this->orb_->shutdown (); }
#include "orbsvcs/Log_Macros.h" #include "RTEvent_Logging_Service.h" #include "tao/IORTable/IORTable.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_NS_unistd.h" RTEvent_Logging_Service::RTEvent_Logging_Service (void) : service_name_ ("RTEventLogFactory"), ior_file_name_ (0), pid_file_name_ (0), bind_to_naming_service_ (true), nthreads_ (0) { } RTEvent_Logging_Service::~RTEvent_Logging_Service (void) { } void RTEvent_Logging_Service::init_ORB (int& argc, ACE_TCHAR *argv[]) { this->orb_ = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = this->orb_->resolve_initial_references("RootPOA"); this->poa_ = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = this->poa_->the_POAManager (); poa_manager->activate (); } int RTEvent_Logging_Service::parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("n:o:p:t:x")); int opt; while ((opt = get_opt ()) != EOF) { switch (opt) { case 'n': this->service_name_ = ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()); break; case 'o': this->ior_file_name_ = get_opt.opt_arg (); break; case 'p': this->pid_file_name_ = get_opt.opt_arg (); break; case 't': this->nthreads_ = ACE_OS::atoi (get_opt.opt_arg ()); break; case 'x': this->bind_to_naming_service_ = false; break; case '?': default: ORBSVCS_DEBUG ((LM_DEBUG, "Usage: %s " "-n service_name " "-o ior_file_name " "-p pid_file_name " "-t threads " "-x [disable naming service bind] " "\n", argv[0])); return -1; } } return 0; } int RTEvent_Logging_Service::init (int argc, ACE_TCHAR* argv[]) { this->init_ORB (argc, argv); if (this->parse_args (argc, argv) == -1) return -1; ACE_NEW_THROW_EX (this->rtevent_log_factory_, TAO_RTEventLogFactory_i (), CORBA::NO_MEMORY ()); if (this->rtevent_log_factory_->init (orb_.in (), poa_.in ()) != 0) { ORBSVCS_ERROR_RETURN ((LM_ERROR, "(%P|%t) Unable to initialize " "the factory.\n"), -1); } RTEventLogAdmin::EventLogFactory_var obj = this->rtevent_log_factory_->activate (); CORBA::String_var ior = this->orb_->object_to_string (obj.in ()); if (true) { CORBA::Object_var table_object = this->orb_->resolve_initial_references ("IORTable"); IORTable::Table_var adapter = IORTable::Table::_narrow (table_object.in ()); adapter->bind("RTEventLogService", ior.in ()); } if (this->ior_file_name_ != 0) { FILE* iorf = ACE_OS::fopen (this->ior_file_name_, ACE_TEXT("w")); if (iorf == 0) { ORBSVCS_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", this->ior_file_name_), -1); } ACE_OS::fprintf (iorf, "%s\n", ior.in ()); ACE_OS::fclose (iorf); } if (this->pid_file_name_ != 0) { FILE* pidf = ACE_OS::fopen (this->pid_file_name_, ACE_TEXT("w")); if (pidf != 0) { ACE_OS::fprintf (pidf, "%ld\n", static_cast<long> (ACE_OS::getpid ())); ACE_OS::fclose (pidf); } } if (this->bind_to_naming_service_) { this->resolve_naming_service (); CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup (this->service_name_.c_str ()); this->naming_->rebind (name, obj.in ()); } return 0; } void RTEvent_Logging_Service::resolve_naming_service (void) { CORBA::Object_var naming_obj = this->orb_->resolve_initial_references ("NameService"); if (CORBA::is_nil (naming_obj.in ())) throw CORBA::UNKNOWN (); this->naming_ = CosNaming::NamingContext::_narrow (naming_obj.in ()); } int RTEvent_Logging_Service::run (void) { if (this->nthreads_ > 0) { if (this->activate ((THR_NEW_LWP | THR_JOINABLE), this->nthreads_) != 0) return -1; this->thr_mgr ()->wait (); return 0; } this->orb_->run (); return 0; } int RTEvent_Logging_Service::svc (void) { try { this->orb_->run (); } catch (const CORBA::Exception&) { return -1; } return 0; }
void RTEvent_Logging_Service::shutdown (void) { if (this->bind_to_naming_service_) { CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup (this->service_name_.c_str ()); this->naming_->unbind (name); } if (!CORBA::is_nil (this->orb_.in ())) this->orb_->shutdown (); }
function_block-full_function
[]
C++
mediapipe/calculators/video/tracked_detection_manager_calculator.cc
nodamu/sign-langage-recogntion
41a22d4f28cc94d6eb14d2c89456eba874c7f05b
#include <memory> #include <string> #include <unordered_map> #include <vector> #include "absl/container/node_hash_map.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/formats/rect.pb.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/util/tracking/box_tracker.h" #include "mediapipe/util/tracking/tracked_detection.h" #include "mediapipe/util/tracking/tracked_detection_manager.h" #include "mediapipe/util/tracking/tracking.h" namespace mediapipe { namespace { constexpr int kDetectionUpdateTimeOutMS = 5000; constexpr char kDetectionsTag[] = "DETECTIONS"; constexpr char kDetectionBoxesTag[] = "DETECTION_BOXES"; constexpr char kDetectionListTag[] = "DETECTION_LIST"; constexpr char kTrackingBoxesTag[] = "TRACKING_BOXES"; constexpr char kCancelObjectIdTag[] = "CANCEL_OBJECT_ID"; void MoveIds(std::vector<int>* dst, std::vector<int> src) { dst->insert(dst->end(), std::make_move_iterator(src.begin()), std::make_move_iterator(src.end())); } int64 GetInputTimestampMs(::mediapipe::CalculatorContext* cc) { return cc->InputTimestamp().Microseconds() / 1000; } std::unique_ptr<TrackedDetection> GetTrackedDetectionFromDetection( const Detection& detection, int64 timestamp) { std::unique_ptr<TrackedDetection> tracked_detection = absl::make_unique<TrackedDetection>(detection.detection_id(), timestamp); const float top = detection.location_data().relative_bounding_box().ymin(); const float bottom = detection.location_data().relative_bounding_box().ymin() + detection.location_data().relative_bounding_box().height(); const float left = detection.location_data().relative_bounding_box().xmin(); const float right = detection.location_data().relative_bounding_box().xmin() + detection.location_data().relative_bounding_box().width(); NormalizedRect bounding_box; bounding_box.set_x_center((left + right) / 2.f); bounding_box.set_y_center((top + bottom) / 2.f); bounding_box.set_height(bottom - top); bounding_box.set_width(right - left); tracked_detection->set_bounding_box(bounding_box); for (int i = 0; i < detection.label_size(); ++i) { tracked_detection->AddLabel(detection.label(i), detection.score(i)); } return tracked_detection; } Detection GetAxisAlignedDetectionFromTrackedDetection( const TrackedDetection& tracked_detection) { Detection detection; LocationData* location_data = detection.mutable_location_data(); auto corners = tracked_detection.GetCorners(); float x_min = std::numeric_limits<float>::max(); float x_max = std::numeric_limits<float>::min(); float y_min = std::numeric_limits<float>::max(); float y_max = std::numeric_limits<float>::min(); for (int i = 0; i < 4; ++i) { x_min = std::min(x_min, corners[i].x()); x_max = std::max(x_max, corners[i].x()); y_min = std::min(y_min, corners[i].y()); y_max = std::max(y_max, corners[i].y()); } location_data->set_format(LocationData::RELATIVE_BOUNDING_BOX); LocationData::RelativeBoundingBox* relative_bbox = location_data->mutable_relative_bounding_box(); relative_bbox->set_xmin(x_min); relative_bbox->set_ymin(y_min); relative_bbox->set_width(x_max - x_min); relative_bbox->set_height(y_max - y_min); if (tracked_detection.previous_id() > 0) { detection.set_detection_id(tracked_detection.previous_id()); } else { detection.set_detection_id(tracked_detection.unique_id()); } for (const auto& label_and_score : tracked_detection.label_to_score_map()) { detection.add_label(label_and_score.first); detection.add_score(label_and_score.second); } return detection; } } class TrackedDetectionManagerCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Process(CalculatorContext* cc) override; private: void AddDetectionList(const DetectionList& detection_list, CalculatorContext* cc); void AddDetections(const std::vector<Detection>& detections, CalculatorContext* cc); TrackedDetectionManager tracked_detection_manager_; absl::node_hash_map<int, std::unique_ptr<TrackedDetection>> waiting_for_update_detections_; }; REGISTER_CALCULATOR(TrackedDetectionManagerCalculator); ::mediapipe::Status TrackedDetectionManagerCalculator::GetContract( CalculatorContract* cc) { if (cc->Inputs().HasTag(kDetectionsTag)) { cc->Inputs().Tag(kDetectionsTag).Set<std::vector<Detection>>(); } if (cc->Inputs().HasTag(kDetectionListTag)) { cc->Inputs().Tag(kDetectionListTag).Set<DetectionList>(); } if (cc->Inputs().HasTag(kTrackingBoxesTag)) { cc->Inputs().Tag(kTrackingBoxesTag).Set<TimedBoxProtoList>(); } if (cc->Outputs().HasTag(kCancelObjectIdTag)) { cc->Outputs().Tag(kCancelObjectIdTag).Set<int>(); } if (cc->Outputs().HasTag(kDetectionsTag)) { cc->Outputs().Tag(kDetectionsTag).Set<std::vector<Detection>>(); } if (cc->Outputs().HasTag(kDetectionBoxesTag)) { cc->Outputs().Tag(kDetectionBoxesTag).Set<std::vector<NormalizedRect>>(); } return ::mediapipe::OkStatus(); } ::mediapipe::Status TrackedDetectionManagerCalculator::Process( CalculatorContext* cc) { if (cc->Inputs().HasTag("TRACKING_BOXES")) { if (!cc->Inputs().Tag("TRACKING_BOXES").IsEmpty()) { const TimedBoxProtoList& tracked_boxes = cc->Inputs().Tag("TRACKING_BOXES").Get<TimedBoxProtoList>(); auto removed_detection_ids = absl::make_unique<std::vector<int>>(); for (const TimedBoxProto& tracked_box : tracked_boxes.box()) { NormalizedRect bounding_box; bounding_box.set_x_center((tracked_box.left() + tracked_box.right()) / 2.f); bounding_box.set_y_center((tracked_box.bottom() + tracked_box.top()) / 2.f); bounding_box.set_height(tracked_box.bottom() - tracked_box.top()); bounding_box.set_width(tracked_box.right() - tracked_box.left()); bounding_box.set_rotation(tracked_box.rotation()); auto waiting_for_update_detectoin_ptr = waiting_for_update_detections_.find(tracked_box.id()); if (waiting_for_update_detectoin_ptr != waiting_for_update_detections_.end()) { auto removed_ids = tracked_detection_manager_.AddDetection( std::move(waiting_for_update_detectoin_ptr->second)); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); waiting_for_update_detections_.erase( waiting_for_update_detectoin_ptr); } auto removed_ids = tracked_detection_manager_.UpdateDetectionLocation( tracked_box.id(), bounding_box, tracked_box.time_msec()); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); } auto removed_ids = tracked_detection_manager_.RemoveObsoleteDetections( GetInputTimestampMs(cc) - kDetectionUpdateTimeOutMS); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); removed_ids = tracked_detection_manager_.RemoveOutOfViewDetections(); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); if (!removed_detection_ids->empty() && cc->Outputs().HasTag(kCancelObjectIdTag)) { auto timestamp = cc->InputTimestamp(); for (int box_id : *removed_detection_ids) { cc->Outputs() .Tag(kCancelObjectIdTag) .AddPacket(mediapipe::MakePacket<int>(box_id).At(timestamp++)); } } const auto& all_detections = tracked_detection_manager_.GetAllTrackedDetections(); auto output_detections = absl::make_unique<std::vector<Detection>>(); auto output_boxes = absl::make_unique<std::vector<NormalizedRect>>(); for (const auto& detection_ptr : all_detections) { const auto& detection = *detection_ptr.second; if (detection.last_updated_timestamp() < cc->InputTimestamp().Microseconds() / 1000) { continue; } output_detections->emplace_back( GetAxisAlignedDetectionFromTrackedDetection(detection)); output_boxes->emplace_back(detection.bounding_box()); } if (cc->Outputs().HasTag(kDetectionsTag)) { cc->Outputs() .Tag(kDetectionsTag) .Add(output_detections.release(), cc->InputTimestamp()); } if (cc->Outputs().HasTag(kDetectionBoxesTag)) { cc->Outputs() .Tag(kDetectionBoxesTag) .Add(output_boxes.release(), cc->InputTimestamp()); } } } if (cc->Inputs().HasTag(kDetectionsTag) && !cc->Inputs().Tag(kDetectionsTag).IsEmpty()) { const auto detections = cc->Inputs().Tag(kDetectionsTag).Get<std::vector<Detection>>(); AddDetections(detections, cc); } if (cc->Inputs().HasTag(kDetectionListTag) && !cc->Inputs().Tag(kDetectionListTag).IsEmpty()) { const auto detection_list = cc->Inputs().Tag(kDetectionListTag).Get<DetectionList>(); AddDetectionList(detection_list, cc); } return ::mediapipe::OkStatus(); } void TrackedDetectionManagerCalculator::AddDetectionList( const DetectionList& detection_list, CalculatorContext* cc) { for (const auto& detection : detection_list.detection()) { std::unique_ptr<TrackedDetection> new_detection = GetTrackedDetectionFromDetection( detection, cc->InputTimestamp().Microseconds() / 1000); const int id = new_detection->unique_id(); waiting_for_update_detections_[id] = std::move(new_detection); } } void TrackedDetectionManagerCalculator::AddDetections( const std::vector<Detection>& detections, CalculatorContext* cc) { for (const auto& detection : detections) { std::unique_ptr<TrackedDetection> new_detection = GetTrackedDetectionFromDetection( detection, cc->InputTimestamp().Microseconds() / 1000); const int id = new_detection->unique_id(); waiting_for_update_detections_[id] = std::move(new_detection); } } }
#include <memory> #include <string> #include <unordered_map> #include <vector> #include "absl/container/node_hash_map.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/formats/rect.pb.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/util/tracking/box_tracker.h" #include "mediapipe/util/tracking/tracked_detection.h" #include "mediapipe/util/tracking/tracked_detection_manager.h" #include "mediapipe/util/tracking/tracking.h" namespace mediapipe { namespace { constexpr int kDetectionUpdateTimeOutMS = 5000; constexpr char kDetectionsTag[] = "DETECTIONS"; constexpr char kDetectionBoxesTag[] = "DETECTION_BOXES"; constexpr char kDetectionListTag[] = "DETECTION_LIST"; constexpr char kTrackingBoxesTag[] = "TRACKING_BOXES"; constexpr char kCancelObjectIdTag[] = "CANCEL_OBJECT_ID"; void MoveIds(std::vector<int>* dst, std::vector<int> src) { dst->insert(dst->end(), std::make_move_iterator(src.begin()), std::make_move_iterator(src.end())); } int64 GetInputTimestampMs(::mediapipe::CalculatorContext* cc) { return cc->InputTimestamp().Microseconds() / 1000; } std::unique_ptr<TrackedDetection> GetTrackedDetectionFromDetection( const Detection& detection, int64 timestamp) { std::unique_ptr<TrackedDetection> tracked_detection = absl::make_unique<TrackedDetection>(detection.detection_id(), timestamp); const float top = detection.location_data().relative_bounding_box().ymin(); const float bottom = detection.location_data().relative_bounding_box().ymin() + detection.location_data().relative_bounding_box().height(); const float left = detection.location_data().relative_bounding_box().xmin(); const float right = detection.location_data().relative_bounding_box().xmin() + detection.location_data().relative_bounding_box().width(); NormalizedRect bounding_box; bounding_box.set_x_center((left + right) / 2.f); bounding_box.set_y_center((top + bottom) / 2.f); bounding_box.set_height(bottom - top); bounding_box.set_width(right - left); tracked_detection->set_bounding_box(bounding_box); for (int i = 0; i < detection.label_size(); ++i) { tracked_detection->AddLabel(detection.label(i), detection.score(i)); } return tracked_detection; } Detection GetAxisAlignedDetectionFromTrackedDetection( const TrackedDetection& tracked_detection) { Detection detection; LocationData* location_data = detection.mutable_location_data(); auto corners = tracked_detection.GetCorners(); float x_min = std::numeric_limits<float>::max(); float x_max = std::numeric_limits<float>::min(); float y_min = std::numeric_limits<float>::max(); float y_max = std::numeric_limits<float>::min(); for (int i = 0; i < 4; ++i) { x_min = std::min(x_min, corners[i].x()); x_max = std::max(x_max, corners[i].x()); y_min = std::min(y_min, corners[i].y()); y_max = std::max(y_max, corners[i].y()); } location_data->set_format(LocationData::RELATIVE_BOUNDING_BOX); LocationData::RelativeBoundingBox* relative_bbox = location_data->mutable_relative_bounding_box(); relative_bbox->set_xmin(x_min); relative_bbox->set_ymin(y_min); relative_bbox->set_width(x_max - x_min); relative_bbox->set_height(y_max - y_min); if (tracked_detection.previous_id() > 0) { detection.set_detection_id(tracked_detection.previous_id()); } else { detection.set_detection_id(tracked_detection.unique_id()); } for (const auto& label_and_score : tracked_detection.label_to_score_map()) { detection.add_label(label_and_score.first); detection.add_score(label_and_score.second); } return detection; } } class TrackedDetectionManagerCalculator : public CalculatorBase { public: static ::mediapipe::Status GetContract(CalculatorContract* cc); ::mediapipe::Status Process(CalculatorContext* cc) override; private: void AddDetectionList(const DetectionList& detection_list, CalculatorContext* cc); void AddDetections(const std::vector<Detection>& detections, CalculatorContext* cc); TrackedDetectionManager tracked_detection_manager_; absl::node_hash_map<int, std::unique_ptr<TrackedDetection>> waiting_for_update_detections_; }; REGISTER_CALCULATOR(TrackedDetectionManagerCalculator); ::mediapipe::Status TrackedDetectionManagerCalculator::GetContract( CalculatorContract* cc) { if (cc->Inputs().HasTag(kDetectionsTag)) { cc->Inputs().Tag(kDetectionsTag).Set<std::vector<Detection>>(); } if (cc->Inputs().HasTag(kDetectionListTag)) { cc->Inputs().Tag(kDetectionListTag).Set<DetectionList>(); } if (cc->Inputs().HasTag(kTrackingBoxesTag)) { cc->Inputs().Tag(kTrackingBoxesTag).Set<TimedBoxProtoList>(); } if (cc->Outputs().HasTag(kCancelObjectIdTag)) { cc->Outputs().Tag(kCancelObjectIdTag).Set<int>(); } if (cc->Outputs().HasTag(kDetectionsTag)) { cc->Outputs().Tag(kDetectionsTag).Set<std::vector<Detection>>(); } if (cc->Outputs().HasTag(kDetectionBoxesTag)) { cc->Outputs().Tag(kDetectionBoxesTag).Set<std::vector<NormalizedRect>>(); } return ::mediapipe::OkStatus(); } ::mediapipe::Status TrackedDetectionManagerCalculator::Process( CalculatorContext* cc) { if (cc->Inputs().HasTag("TRACKING_BOXES")) { if (!cc->Inputs().Tag("TRACKING_BOXES").IsEmpty()) { const TimedBoxProtoList& tracked_boxes = cc->Inputs().Tag("TRACKING_BOXES").Get<TimedBoxProtoList>(); auto removed_detection_ids = absl::make_unique<std::vector<int>>(); for (const TimedBoxProto& tracked_box : tracked_boxes.box()) { NormalizedRect bounding_box; bounding_box.set_x_center((tracked_box.left() + tracked_box.right()) / 2.f); bounding_box.set_y_center((tracked_box.bottom() + tracked_box.top()) / 2.f); bounding_box.set_height(tracked_box.bottom() - tracked_box.top()); bounding_box.set_width(tracked_box.right() - tracked_box.left()); bounding_box.set_rotation(tracked_box.rotation()); auto waiting_for_update_detectoin_ptr = waiting_for_update_detections_.find(tracked_box.id()); if (waiting_for_update_detectoin_ptr != waiting_for_update_detections_.end()) { auto removed_ids = tracked_detection_manager_.AddDetection( std::move(waiting_for_update_detectoin_ptr->second)); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); waiting_for_update_detections_.erase( waiting_for_update_detectoin_ptr); } auto removed_ids = tracked_detection_manager_.UpdateDetectionLocation( tracked_box.id(), bounding_box, tracked_box.time_msec()); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); } auto removed_ids = tracked_detection_manager_.RemoveObsoleteDetections( GetInputTimestampMs(cc) - kDetectionUpdateTimeOutMS); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); removed_ids = tracked_detection_manager_.RemoveOutOfViewDetections(); MoveIds(removed_detection_ids.get(), std::move(removed_ids)); if (!removed_detection_ids->empty() && cc->Outputs().HasTag(kCancelObjectIdTag)) { auto timestamp = cc->InputTimestamp(); for (int box_id : *removed_detection_ids) { cc->Outputs() .Tag(kCancelObjectIdTag) .AddPacket(mediapipe::MakePacket<int>(box_id).At(timestamp++)); } } const auto& all_detections = tracked_detection_manager_.GetAllTrackedDetections(); auto output_detections = absl::make_unique<std::vector<Detection>>(); auto output_boxes = absl::make_unique<std::vector<NormalizedRect>>(); for (const auto& detection_ptr : all_detections) { const auto& detection = *detection_ptr.second; if (detection.last_updated_timestamp() < cc->InputTimestamp().Microseconds() / 1000) { continue; } output_detections->emplace_back( GetAxisAlignedDetectionFromTrackedDetection(detection)); output_boxes->emplace_back(detection.bounding_box()); } if (cc->Outputs().HasTag(kDetectionsTag)) { cc->Outputs() .Tag(kDetectionsTag) .Add(output_detections.release(), cc->InputTimestamp()); } if (cc->Outputs().HasTag(kDetectionBoxesTag)) { cc->Outputs() .Tag(kDetectionBoxesTag) .Add(output_boxes.release(), cc->InputTimestamp()); } } } if (cc->Inputs().HasTag(kDetectionsTag) && !cc->Inputs().Tag(kDetectionsTag).IsEmpty()) { const auto detections = cc->Inputs().Tag(kDetectionsTag).Get<std::vector<Detection>>(); AddDetections(detections, cc); } if (cc->Inputs().HasTag(kDetectionListTag) && !cc->Inputs().Tag(kDetectionListTag).IsEmpty()) { const auto detection_list = cc->Inputs().Tag(kDetectionListTag).Get<DetectionList>(); AddDetectionList(detection_list, cc); } return ::mediapipe::OkStatus(); }
void TrackedDetectionManagerCalculator::AddDetections( const std::vector<Detection>& detections, CalculatorContext* cc) { for (const auto& detection : detections) { std::unique_ptr<TrackedDetection> new_detection = GetTrackedDetectionFromDetection( detection, cc->InputTimestamp().Microseconds() / 1000); const int id = new_detection->unique_id(); waiting_for_update_detections_[id] = std::move(new_detection); } } }
void TrackedDetectionManagerCalculator::AddDetectionList( const DetectionList& detection_list, CalculatorContext* cc) { for (const auto& detection : detection_list.detection()) { std::unique_ptr<TrackedDetection> new_detection = GetTrackedDetectionFromDetection( detection, cc->InputTimestamp().Microseconds() / 1000); const int id = new_detection->unique_id(); waiting_for_update_detections_[id] = std::move(new_detection); } }
function_block-full_function
[ { "content": "class StringToIntCalculatorTemplate : public CalculatorBase {\n\n public:\n\n static ::mediapipe::Status GetContract(CalculatorContract* cc) {\n\n cc->InputSidePackets().Index(0).Set<std::string>();\n\n cc->OutputSidePackets().Index(0).Set<IntType>();\n\n return ::mediapipe::OkStatus();\...
C++
Examples/ReadWriteExample/ReadWriteExample.cpp
scaredyfish/MPCDI
1ddbc9abf99d39d4464afa2005934c325443cf28
#include "mpcdiDisplay.h" #include "mpcdiWriter.h" #include "mpcdiReader.h" #include "CreateSampleProfile.h" #include "VerboseCompareProfile.h" #include <iostream> #include <algorithm> #define DO_PAUSE #ifdef DO_PAUSE # define PAUSE {std::cout<< "Press enter to continue....";std::cin.ignore();} #else # definE PAUSE #endif mpcdi::MPCDI_Error WriteTest(const std::string &FileName, mpcdi::Profile *profile); mpcdi::MPCDI_Error ReadTest(const std::string &FileName, mpcdi::Profile * &profileIn); int main( int argc, const char ** argv ) { bool DoWriteTest = true; bool DoReadTest = true; mpcdi::MPCDI_Error mpcdi_err = mpcdi::MPCDI_SUCCESS; std::string profileName= "SampleMPCDI.mpcdi"; mpcdi::Profile *profileOut = NULL; if (MPCDI_FAILED(mpcdi_err = CreateSampleProfile(std::cout, profileOut))) { PAUSE; return mpcdi_err; } if (DoWriteTest) { if(MPCDI_FAILED(WriteTest(profileName,profileOut))) { delete profileOut; PAUSE; return mpcdi::MPCDI_FAILURE; } } mpcdi::Profile *profileIn = NULL; if (DoReadTest) { if (MPCDI_FAILED(ReadTest(profileName,profileIn))) { delete profileOut; PAUSE; return mpcdi::MPCDI_FAILURE; } } if(DoReadTest && DoWriteTest) { if (MPCDI_FAILED(VerboseCompareProfile(std::cout,profileIn,profileOut))) { std::cout << "Error on Read/Write Test: " << std::endl; PAUSE; delete profileOut; delete profileIn; return mpcdi_err; } std::cout << "Success on Read/Write Test. " << std::endl; } if (profileOut) delete profileOut; if (profileIn) delete profileIn; PAUSE; return mpcdi::MPCDI_SUCCESS; } mpcdi::MPCDI_Error WriteTest(const std::string &FileName, mpcdi::Profile *profile) { mpcdi::Writer *writer = mpcdi::Writer::CreateWriter(); writer->SetOverwriteExistingFile(true); bool test = writer->GetOverwriteExistingFile(); mpcdi::MPCDI_Error mpcdi_err = writer->Write(FileName, *profile); delete writer; if (MPCDI_FAILED(mpcdi_err)) { std::cout << "Error writing: " << mpcdi_err << mpcdi::ErrorHelper::GetLastError() << std::endl; } return mpcdi_err; } mpcdi::MPCDI_Error ReadTest(const std::string &FileName, mpcdi::Profile * &profileIn) { profileIn = new mpcdi::Profile(); mpcdi::Reader *Reader = mpcdi::Reader::CreateReader(); std::cout << Reader->GetSupportedVersions() << std::endl; mpcdi::MPCDI_Error mpcdi_err = Reader->Read(FileName, profileIn); if (MPCDI_FAILED(mpcdi_err)) { std::cout << "Error encountered while reading: " << mpcdi_err << ": " << mpcdi::ErrorHelper::GetLastError() << std::endl; delete profileIn; profileIn = NULL; } delete Reader; return mpcdi_err; }
#include "mpcdiDisplay.h" #include "mpcdiWriter.h" #include "mpcdiReader.h" #include "CreateSampleProfile.h" #include "VerboseCompareProfile.h" #include <iostream> #include <algorithm> #define DO_PAUSE #ifdef DO_PAUSE # define PAUSE {std::cout<< "Press enter to continue....";std::cin.ignore();} #else # definE PAUSE #endif mpcdi::MPCDI_Error WriteTest(const std::string &FileName, mpcdi::Profile *profile); mpcdi::MPCDI_Error ReadTest(const std::string &FileName, mpcdi::Profile * &profileIn); int main( int argc, const char ** argv ) { bool DoWriteTest = true; bool DoReadTest = true; mpcdi::MPCDI_Error mpcdi_err = mpcdi::MPCDI_SUCCESS; std::string profileName= "SampleMPCDI.mpcdi"; mpcdi::Profile *profileOut = NULL; if (MPCDI_FAILED(mpcdi_err = CreateSampleProfile(std::cout, profileOut))) { PAUSE; return mpcdi_err; } if (DoWriteTes
mpcdi::MPCDI_Error WriteTest(const std::string &FileName, mpcdi::Profile *profile) { mpcdi::Writer *writer = mpcdi::Writer::CreateWriter(); writer->SetOverwriteExistingFile(true); bool test = writer->GetOverwriteExistingFile(); mpcdi::MPCDI_Error mpcdi_err = writer->Write(FileName, *profile); delete writer; if (MPCDI_FAILED(mpcdi_err)) { std::cout << "Error writing: " << mpcdi_err << mpcdi::ErrorHelper::GetLastError() << std::endl; } return mpcdi_err; } mpcdi::MPCDI_Error ReadTest(const std::string &FileName, mpcdi::Profile * &profileIn) { profileIn = new mpcdi::Profile(); mpcdi::Reader *Reader = mpcdi::Reader::CreateReader(); std::cout << Reader->GetSupportedVersions() << std::endl; mpcdi::MPCDI_Error mpcdi_err = Reader->Read(FileName, profileIn); if (MPCDI_FAILED(mpcdi_err)) { std::cout << "Error encountered while reading: " << mpcdi_err << ": " << mpcdi::ErrorHelper::GetLastError() << std::endl; delete profileIn; profileIn = NULL; } delete Reader; return mpcdi_err; }
t) { if(MPCDI_FAILED(WriteTest(profileName,profileOut))) { delete profileOut; PAUSE; return mpcdi::MPCDI_FAILURE; } } mpcdi::Profile *profileIn = NULL; if (DoReadTest) { if (MPCDI_FAILED(ReadTest(profileName,profileIn))) { delete profileOut; PAUSE; return mpcdi::MPCDI_FAILURE; } } if(DoReadTest && DoWriteTest) { if (MPCDI_FAILED(VerboseCompareProfile(std::cout,profileIn,profileOut))) { std::cout << "Error on Read/Write Test: " << std::endl; PAUSE; delete profileOut; delete profileIn; return mpcdi_err; } std::cout << "Success on Read/Write Test. " << std::endl; } if (profileOut) delete profileOut; if (profileIn) delete profileIn; PAUSE; return mpcdi::MPCDI_SUCCESS; }
function_block-function_prefixed
[ { "content": "local int gz_decomp(state)\n", "file_path": "ThirdParty/zlib-1.2.7/gzread.c", "rank": 0, "score": 99229.37633994885 }, { "content": "local int build_bl_tree(s)\n", "file_path": "ThirdParty/zlib-1.2.7/trees.c", "rank": 1, "score": 99229.01503971723 }, { "cont...
C++
visual/gl/univtrans_sse2.cpp
wtnbgo/krkrz
d9bcf1b08b694385e1fab68fe56501c7fbbd9332
#include "tjsCommHead.h" #include "simd_def_x86x64.h" #include "tvpgl.h" #include "tvpgl_ia32_intf.h" extern "C" { extern unsigned char TVPOpacityOnOpacityTable[256*256]; extern unsigned char TVPNegativeMulTable[256*256]; } struct sse2_univ_trans_blend_func { const __m128i zero_; const tjs_uint32 *table_; inline sse2_univ_trans_blend_func(const tjs_uint32 *t) : zero_( _mm_setzero_si128() ), table_(t) {} inline tjs_uint32 operator()( tjs_uint32 s1, tjs_uint32 s2, tjs_uint8 rule) const { __m128i ms1 = _mm_cvtsi32_si128( s1 ); __m128i ms2 = _mm_cvtsi32_si128( s2 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule] ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms2 = _mm_sub_epi16( ms2, ms1 ); ms2 = _mm_mullo_epi16( ms2, mopa ); ms2 = _mm_srli_epi16( ms2, 8 ); ms1 = _mm_add_epi8( ms1, ms2 ); ms1 = _mm_packus_epi16( ms1, zero_ ); return _mm_cvtsi128_si32( ms1 ); } inline __m128i operator()( __m128i ms11, __m128i ms21, const tjs_uint8 *rule ) const { __m128i ms12 = ms11; __m128i ms22 = ms21; __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms21 = _mm_unpacklo_epi8( ms21, zero_ ); ms11 = _mm_unpacklo_epi8( ms11, zero_ ); ms21 = _mm_sub_epi16( ms21, ms11 ); ms21 = _mm_mullo_epi16( ms21, mopa ); ms21 = _mm_srli_epi16( ms21, 8 ); ms11 = _mm_add_epi8( ms11, ms21 ); mopa = _mm_cvtsi32_si128( table_[rule[2]] ); mopa2 = _mm_cvtsi32_si128( table_[rule[3]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms22 = _mm_unpackhi_epi8( ms22, zero_ ); ms12 = _mm_unpackhi_epi8( ms12, zero_ ); ms22 = _mm_sub_epi16( ms22, ms12 ); ms22 = _mm_mullo_epi16( ms22, mopa ); ms22 = _mm_srli_epi16( ms22, 8 ); ms12 = _mm_add_epi8( ms12, ms22 ); return _mm_packus_epi16( ms11, ms12 ); } #if 0 inline void operator()( tjs_uint32 *d, const tjs_uint32 *s1, const tjs_uint32 *s2, const tjs_uint8 *rule ) const { __m128i ms1 = _mm_loadl_epi64( (const __m128i*)s1 ); __m128i ms2 = _mm_loadl_epi64( (const __m128i*)s2 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms1 = _mm_sub_epi16( ms1, ms2 ); ms1 = _mm_mulhi_epi16( ms1, mopa ); ms1 = _mm_slli_epi16( ms1, 1 ); ms2 = _mm_add_epi16( ms2, ms1 ); ms2 = _mm_packus_epi16( ms2, zero_ ); _mm_storel_epi64((__m128i*)d, ms2); } #endif }; struct sse2_univ_trans_d_blend_func { const __m128i zero_; const tjs_uint32 *table_; inline sse2_univ_trans_d_blend_func(const tjs_uint32 *t) : zero_( _mm_setzero_si128() ), table_(t) {} inline tjs_uint32 operator()( tjs_uint32 s1, tjs_uint32 s2, tjs_uint8 rule) const { tjs_uint32 a1 = s1 >> 24; tjs_uint32 a2 = s2 >> 24; tjs_int opa = table_[rule]; tjs_uint32 addr = (a2*opa & 0xff00) + (a1*(256-opa) >> 8); tjs_int alpha = TVPOpacityOnOpacityTable[addr]; __m128i mopa = _mm_cvtsi32_si128( alpha ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); __m128i ms1 = _mm_cvtsi32_si128( s1 ); __m128i ms2 = _mm_cvtsi32_si128( s2 ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms2 = _mm_sub_epi16( ms2, ms1 ); ms2 = _mm_mullo_epi16( ms2, mopa ); ms2 = _mm_srli_epi16( ms2, 8 ); ms1 = _mm_add_epi8( ms1, ms2 ); ms1 = _mm_packus_epi16( ms1, zero_ ); tjs_uint32 dst_alpha = TVPNegativeMulTable[addr]<<24; return (_mm_cvtsi128_si32( ms1 )&0x00ffffff) | dst_alpha; } inline __m128i operator()( __m128i ms11, __m128i ms21, const tjs_uint8 *rule ) const { __m128i a1 = ms11; a1 = _mm_srli_epi32( a1, 24 ); __m128i a2 = ms21; a2 = _mm_srli_epi32( a2, 24 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa2 = _mm_cvtsi32_si128( table_[rule[2]] ); __m128i mopa3 = _mm_cvtsi32_si128( table_[rule[3]] ); mopa2 = _mm_unpacklo_epi32( mopa2, mopa3 ); mopa = _mm_unpacklo_epi64( mopa, mopa2 ); a2 = _mm_mullo_epi16( a2, mopa ); __m128i mask = _mm_set1_epi32( 0x0000ff00 ); a2 = _mm_and_si128( a2, mask ); #if 0 mask = _mm_srli_epi32( mask, 8 ); mopa = _mm_xor_si128( mopa, mask ); a1 = _mm_mullo_epi16( a1, mopa ); #else __m128i invopa = _mm_set1_epi32( 256 ); invopa = _mm_sub_epi16( invopa, mopa ); a1 = _mm_mullo_epi16( a1, invopa ); #endif a1 = _mm_srli_epi32( a1, 8 ); a1 = _mm_or_si128( a1, a2 ); tjs_uint32 addr = _mm_cvtsi128_si32( a1 ); tjs_uint32 opa = TVPOpacityOnOpacityTable[addr]; mopa = _mm_cvtsi32_si128( opa ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa2 = _mm_cvtsi32_si128( opa ); mopa = _mm_unpacklo_epi16( mopa, mopa2 ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); __m128i ms12 = ms11; __m128i ms22 = ms21; ms21 = _mm_unpacklo_epi8( ms21, zero_ ); ms11 = _mm_unpacklo_epi8( ms11, zero_ ); ms21 = _mm_sub_epi16( ms21, ms11 ); ms21 = _mm_mullo_epi16( ms21, mopa ); ms21 = _mm_srli_epi16( ms21, 8 ); ms11 = _mm_add_epi8( ms11, ms21 ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa = _mm_cvtsi32_si128( opa ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa2 = _mm_cvtsi32_si128( opa ); mopa = _mm_unpacklo_epi16( mopa, mopa2 ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); ms22 = _mm_unpackhi_epi8( ms22, zero_ ); ms12 = _mm_unpackhi_epi8( ms12, zero_ ); ms22 = _mm_sub_epi16( ms22, ms12 ); ms22 = _mm_mullo_epi16( ms22, mopa ); ms22 = _mm_srli_epi16( ms22, 8 ); ms12 = _mm_add_epi8( ms12, ms22 ); ms11 = _mm_packus_epi16( ms11, ms12 ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); mask = _mm_set1_epi32( 0x0000ffff ); a1 = _mm_xor_si128( a1, mask ); __m128i mtmp = a1; a1 = _mm_slli_epi32( a1, 8 ); mtmp = _mm_slli_epi16( mtmp, 8 ); mtmp = _mm_slli_epi32( mtmp, 8 ); a1 = _mm_mullo_epi16( a1, mtmp ); a1 = _mm_srli_epi32( a1, 16 ); a1 = _mm_andnot_si128( a1, mask ); a1 = _mm_srli_epi16( a1, 8 ); a1 = _mm_slli_epi32( a1, 24 ); const __m128i colormask = _mm_set1_epi32(0x00ffffff); ms11 = _mm_and_si128( ms11, colormask ); return _mm_or_si128( ms11, a1 ); } }; void TVPInitUnivTransBlendTable_sse2_c(tjs_uint32 *table, tjs_int phase, tjs_int vague) { tjs_int i = 0; tjs_int phasemax = phase; phase -= vague; for(; i < phase; i++ ) table[i] = (255<<16)|(255); if( phasemax > 256 ) phasemax = 256; for(;i < phasemax; i++ ) { short tmp = (255-(( i - phase )*255 / vague)); if(tmp<0) tmp = 0; if(tmp>255) tmp = 255; table[i] = (tmp << 16) | (tmp & 0xffff); } for(;i < 256; i++ ) table[i] = 0; } void TVPInitUnivTransBlendTable_d_sse2_c(tjs_uint32 *table, tjs_int phase, tjs_int vague) { tjs_int i = 0; tjs_int phasemax = phase; phase -= vague; for(; i < phase; i++ ) table[i] = 255; if( phasemax > 256 ) phasemax = 256; for(;i < phasemax; i++ ) { short tmp = (255-(( i - phase )*255 / vague)); if(tmp<0) tmp = 0; if(tmp>255) tmp = 255; table[i] = tmp & 0xffff; } for(;i < 256; i++ ) table[i] = 0; } template<typename func_t> static inline void sse2_univ_trans(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { if( len <= 0 ) return; func_t func(table); tjs_int count = (tjs_int)(((unsigned)dest)&0xF); if( count ) { count = (16 - count)>>2; count = count > len ? len : count; tjs_uint32* limit = dest + count; while( dest < limit ) { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } len -= count; } tjs_uint32 rem = (len>>2)<<2; tjs_uint32* limit = dest + rem; if( ((((unsigned)src1)&0xF) == 0) && (((unsigned)src2)&0xF) == 0 ) { while( dest < limit ) { __m128i ms11 = _mm_load_si128( (__m128i const*)src1 ); __m128i ms21 = _mm_load_si128( (__m128i const*)src2 ); _mm_store_si128( (__m128i*)dest, func(ms11, ms21, rule) ); src1 += 4; src2 += 4; rule += 4; dest += 4; } } else { while( dest < limit ) { __m128i ms11 = _mm_loadu_si128( (__m128i const*)src1 ); __m128i ms21 = _mm_loadu_si128( (__m128i const*)src2 ); _mm_store_si128( (__m128i*)dest, func(ms11, ms21, rule) ); src1 += 4; src2 += 4; rule += 4; dest += 4; } } limit += (len-rem); while( dest < limit ) { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } } template<typename func_t> static inline void sse2_univ_trans_switch(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { if( len <= 0 ) return; func_t func(table); tjs_int count = (tjs_int)(((unsigned)dest)&0xF); if( count ) { count = (16 - count)>>2; count = count > len ? len : count; tjs_uint32* limit = dest + count; while( dest < limit ) { tjs_int opa = *rule; if( opa >= src1lv ) { *dest = *src1; rule++; src1++; src2++; dest++; } else if(opa < src2lv) { *dest = *src2; rule++; src1++; src2++; dest++; } else { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } } len -= count; } tjs_uint32 rem = (len>>2)<<2; tjs_uint32* limit = dest + rem; const __m128i msrc1lv = _mm_set1_epi32(src1lv); const __m128i msrc2lv = _mm_set1_epi32(src2lv); const __m128i not = _mm_set1_epi32(0xffffffff); while( dest < limit ) { tjs_uint32 r = *(tjs_uint32*)rule; __m128i mr = _mm_cvtsi32_si128( r ); mr = _mm_unpacklo_epi8( mr, func.zero_ ); mr = _mm_unpacklo_epi16( mr, func.zero_ ); __m128i opa1 = mr; opa1 = _mm_cmplt_epi32( opa1, msrc1lv ); __m128i md = opa1; __m128i ms11 = _mm_loadu_si128( (__m128i const*)src1 ); md = _mm_andnot_si128( md, ms11 ); if( _mm_movemask_epi8(opa1) != 0 ) { __m128i ms21 = _mm_loadu_si128( (__m128i const*)src2 ); opa1 = _mm_xor_si128( opa1, not ); __m128i opa2 = mr; opa2 = _mm_cmplt_epi32( mr, msrc2lv ); opa1 = _mm_or_si128( opa1, opa2 ); opa2 = _mm_and_si128( opa2, ms21 ); md = _mm_or_si128( md, opa2 ); if( _mm_movemask_epi8(opa1) != 0xffff ) { __m128i blend = func(ms11, ms21, rule); opa1 = _mm_andnot_si128( opa1, blend ); md = _mm_or_si128( md, opa1 ); } } _mm_store_si128( (__m128i*)dest, md ); src1 += 4; src2 += 4; rule += 4; dest += 4; } limit += (len-rem); while( dest < limit ) { tjs_int opa = *rule; if( opa >= src1lv ) { *dest = *src1; rule++; src1++; src2++; dest++; } else if(opa < src2lv) { *dest = *src2; rule++; src1++; src2++; dest++; } else { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } } } void TVPUnivTransBlend_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { sse2_univ_trans<sse2_univ_trans_blend_func>(dest,src1,src2,rule,table,len); } void TVPUnivTransBlend_switch_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { sse2_univ_trans_switch<sse2_univ_trans_blend_func>(dest,src1,src2,rule,table,len,src1lv,src2lv); } void TVPUnivTransBlend_d_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { sse2_univ_trans<sse2_univ_trans_d_blend_func>(dest,src1,src2,rule,table,len); } void TVPUnivTransBlend_switch_d_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { sse2_univ_trans_switch<sse2_univ_trans_d_blend_func>(dest,src1,src2,rule,table,len,src1lv,src2lv); }
#include "tjsCommHead.h" #include "simd_def_x86x64.h" #include "tvpgl.h" #include "tvpgl_ia32_intf.h" extern "C" { extern unsigned char TVPOpacityOnOpacityTable[256*256]; extern unsigned char TVPNegativeMulTable[256*256]; } struct sse2_univ_trans_blend_func { const __m128i zero_; const tjs_uint32 *table_; inline sse2_univ_trans_blend_func(const tjs_uint32 *t) : zero_( _mm_setzero_si128() ), table_(t) {} inline tjs_uint32 operator()( tjs_uint32 s1, tjs_uint32 s2, tjs_uint8 rule) const { __m128i ms1 = _mm_cvtsi32_si128( s1 ); __m128i ms2 = _mm_cvtsi32_si128( s2 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule] ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms2 = _mm_sub_epi16( ms2, ms1 ); ms2 = _mm_mullo_epi16( ms2, mopa ); ms2 = _mm_srli_epi16( ms2, 8 ); ms1 = _mm_add_epi8( ms1, ms2 ); ms1 = _mm_packus_epi16( ms1, zero_ ); return _mm_cvtsi128_si32( ms1 ); } inline __m128i operator()( __m128i ms11, __m128i ms21, const tjs_uint8 *rule ) const { __m128i ms12 = ms11; __m128i ms22 = ms21; __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms21 = _mm_unpacklo_epi8( ms21, zero_ ); ms11 = _mm_unpacklo_epi8( ms11, zero_ ); ms21 = _mm_sub_epi16( ms21, ms11 ); ms21 = _mm_mullo_epi16( ms21, mopa ); ms21 = _mm_srli_epi16( ms21, 8 ); ms11 = _mm_add_epi8( ms11, ms21 ); mopa = _mm_cvtsi32_si128( table_[rule[2]] ); mopa2 = _mm_cvtsi32_si128( table_[rule[3]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms22 = _mm_unpackhi_epi8( ms22, zero_ ); ms12 = _mm_unpackhi_epi8( ms12, zero_ ); ms22 = _mm_sub_epi16( ms22, ms12 ); ms22 = _mm_mullo_epi16( ms22, mopa ); ms22 = _mm_srli_epi16( ms22, 8 ); ms12 = _mm_add_epi8( ms12, ms22 ); return _mm_packus_epi16( ms11, ms12 ); } #if 0 inline void operator()( tjs_uint32 *d, const tjs_uint32 *s1, const tjs_uint32 *s2, const tjs_uint8 *rule ) const { __m128i ms1 = _mm_loadl_epi64( (const __m128i*)s1 ); __m128i ms2 = _mm_loadl_epi64( (const __m128i*)s2 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa = _mm_unpacklo_epi32( mopa, mopa ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms1 = _mm_sub_epi16( ms1, ms2 ); ms1 = _mm_mulhi_epi16( ms1, mopa ); ms1 = _mm_slli_epi16( ms1, 1 ); ms2 = _mm_add_epi16( ms2, ms1 ); ms2 = _mm_packus_epi16( ms2, zero_ ); _mm_storel_epi64((__m128i*)d, ms2); } #endif }; struct sse2_univ_trans_d_blend_func { const __m128i zero_; const tjs_uint32 *table_; inline sse2_univ_trans_d_blend_func(const tjs_uint32 *t) : zero_( _mm_setzero_si128() ), table_(t) {} inline tjs_uint32 operator()( tjs_uint32 s1, tjs_uint32 s2, tjs_uint8 rule) const { tjs_uint32 a1 = s1 >> 24; tjs_uint32 a2 = s2 >> 24; tjs_int opa = table_[rule]; tjs_uint32 addr = (a2*opa & 0xff00) + (a1*(256-opa) >> 8); tjs_int alpha = TVPOpacityOnOpacityTable[addr]; __m128i mopa = _mm_cvtsi32_si128( alpha ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); __m128i ms1 = _mm_cvtsi32_si128( s1 ); __m128i ms2 = _mm_cvtsi32_si128( s2 ); ms1 = _mm_unpacklo_epi8( ms1, zero_ ); ms2 = _mm_unpacklo_epi8( ms2, zero_ ); ms2 = _mm_sub_epi16( ms2, ms1 ); ms2 = _mm_mullo_epi16( ms2, mopa ); ms2 = _mm_srli_epi16( ms2, 8 ); ms1 = _mm_add_epi8( ms1, ms2 ); ms1 = _mm_packus_epi16( ms1, zero_ ); tjs_uint32 dst_alpha = TVPNegativeMulTable[addr]<<24; return (_mm_cvtsi128_si32( ms1 )&0x00ffffff) | dst_alpha; } inline __m128i operator()( __m128i ms11, __m128i ms21, const tjs_uint8 *rule ) const { __m128i a1 = ms11; a1 = _mm_srli_epi32( a1, 24 ); __m128i a2 = ms21; a2 = _mm_srli_epi32( a2, 24 ); __m128i mopa = _mm_cvtsi32_si128( table_[rule[0]] ); __m128i mopa2 = _mm_cvtsi32_si128( table_[rule[1]] ); mopa = _mm_unpacklo_epi32( mopa, mopa2 ); mopa2 = _mm_cvtsi32_si128( table_[rule[2]] ); __m128i mopa3 = _mm_cvtsi32_si128( table_[rule[3]] ); mopa2 = _mm_unpacklo_epi32( mopa2, mopa3 ); mopa = _mm_unpacklo_epi64( mopa, mopa2 ); a2 = _mm_mullo_epi16( a2, mopa ); __m128i mask = _mm_set1_epi32( 0x0000ff00 ); a2 = _mm_and_si128( a2, mask ); #if 0 mask = _mm_srli_epi32( mask, 8 ); mopa = _mm_xor_si128( mopa, mask ); a1 = _mm_mullo_epi16( a1, mopa ); #else __m128i invopa = _mm_set1_epi32( 256 ); invopa = _mm_sub_epi16( invopa, mopa ); a1 = _mm_mullo_epi16( a1, invopa ); #endif a1 = _mm_srli_epi32( a1, 8 ); a1 = _mm_or_si128( a1, a2 ); tjs_uint32 addr = _mm_cvtsi128_si32( a1 ); tjs_uint32 opa = TVPOpacityOnOpacityTable[addr]; mopa = _mm_cvtsi32_si128( opa ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa2 = _mm_cvtsi32_si128( opa ); mopa = _mm_unpacklo_epi16( mopa, mopa2 ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); __m128i ms12 = ms11; __m128i ms22 = ms21; ms21 = _mm_unpacklo_epi8( ms21, zero_ ); ms11 = _mm_unpacklo_epi8( ms11, zero_ ); ms21 = _mm_sub_epi16( ms21, ms11 ); ms21 = _mm_mullo_epi16( ms21, mopa ); ms21 = _mm_srli_epi16( ms21, 8 ); ms11 = _mm_add_epi8( ms11, ms21 ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa = _mm_cvtsi32_si128( opa ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); addr = _mm_cvtsi128_si32( a1 ); opa = TVPOpacityOnOpacityTable[addr]; mopa2 = _mm_cvtsi32_si128( opa ); mopa = _mm_unpacklo_epi16( mopa, mopa2 ); mopa = _mm_unpacklo_epi16( mopa, mopa ); mopa = _mm_unpacklo_epi16( mopa, mopa ); ms22 = _mm_unpackhi_epi8( ms22, zero_ ); ms12 = _mm_unpackhi_epi8( ms12, zero_ ); ms22 = _mm_sub_epi16( ms22, ms12 ); ms22 = _mm_mullo_epi16( ms22, mopa ); ms22 = _mm_srli_epi16( ms22, 8 ); ms12 = _mm_add_epi8( ms12, ms22 ); ms11 = _mm_packus_epi16( ms11, ms12 ); a1 = _mm_shuffle_epi32( a1, _MM_SHUFFLE( 0, 3, 2, 1 ) ); mask = _mm_set1_epi32( 0x0000ffff ); a1 = _mm_xor_si128( a1, mask ); __m128i mtmp = a1; a1 = _mm_slli_epi32( a1, 8 ); mtmp = _mm_slli_epi16( mtmp, 8 ); mtmp = _mm_slli_epi32( mtmp, 8 ); a1 = _mm_mullo_epi16( a1, mtmp ); a1 = _mm_srli_epi32( a1, 16 ); a1 = _mm_andnot_si128( a1, mask ); a1 = _mm_srli_epi16( a1, 8 ); a1 = _mm_slli_epi32( a1, 24 ); const __m128i colormask = _mm_set1_epi32(0x00ffffff); ms11 = _mm_and_si128( ms11, colormask ); return _mm_or_si128( ms11, a1 ); } }; void TVPInitUnivTransBlendTable_sse2_c(tjs_uint32 *table, tjs_int phase, tjs_int vague) { tjs_int i = 0; tjs_int phasemax = phase; phase -= vague; for(; i < phase; i++ ) table[i] = (255<<16)|(255); if( phasemax > 256 ) phasemax = 256; for(;i < phasemax; i++ ) { short tmp = (255-(( i - phase )*255 / vague)); if(tmp<0) tmp = 0; if(tmp>255) tmp = 255; table[i] = (tmp << 16) | (tmp & 0xffff); } for(;i < 256; i++ ) table[i] = 0; } void TVPInitUnivTransBlendTable_d_sse2_c(tjs_uint32 *table, tjs_int phase, tjs_int vague) { tjs_int i = 0; tjs_int phasemax = phase; phase -= vague; for(; i < phase; i++ ) table[i] = 255; if( phasemax > 256 ) phasemax = 256; for(;i < phasemax; i++ ) { short tmp = (255-(( i - phase )*255 / vague)); if(tmp<0) tmp = 0; if(tmp>255) tmp = 255; table[i] = tmp & 0xffff; } for(;i < 256; i++ ) table[i] = 0; } template<typename func_t> static inline void sse2_univ_trans(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { if( len <= 0 ) return; func_t func(table); tjs_int count = (tjs_int)(((unsigned)dest)&0xF); if( count ) { count = (16 - count)>>2; count = count > len ? len : count; tjs_uint32* limit = dest + count; while( dest < limit ) { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } len -= count; } tjs_uint32 rem = (len>>2)<<2; tjs_uint32* limit = dest + rem; if( ((((unsigned)src1)&0xF) == 0) && (((unsigned)src2)&0xF) == 0 ) { while( dest < limit ) { __m128i ms11 = _mm_load_si128( (__m128i const*)src1 ); __m128i ms21 = _mm_load_si128( (__m128i const*)src2 ); _mm_store_si128( (__m128i*)dest, func(ms11, ms21, rule) ); src1 += 4; src2 += 4; rule += 4; dest += 4; } } else { while( dest < limit ) { __m128i ms11 = _mm_loadu_si128( (__m128i const*)src1 ); __m128i ms21 = _mm_loadu_si128( (__m128i const*)src2 ); _mm_store_si128( (__m128i*)dest, func(ms11, ms21, rule) ); src1 += 4; src2 += 4; rule += 4; dest += 4; } } limit += (len-rem); while( dest < limit ) { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } } template<typename func_t> static inline void sse2_univ_trans_switch(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { if( len <= 0 ) return; func_t func(table); tjs_int count = (tjs_int)(((unsigned)dest)&0xF); if( count ) { count = (16 - count)>>2; count = count > len ? len : count; tjs_uint32* limit = dest + count; while( dest < limit ) { tjs_int opa = *rule; if( opa >= src1lv ) { *dest = *src1; rule++; src1++; src2++; dest++; } else
} len -= count; } tjs_uint32 rem = (len>>2)<<2; tjs_uint32* limit = dest + rem; const __m128i msrc1lv = _mm_set1_epi32(src1lv); const __m128i msrc2lv = _mm_set1_epi32(src2lv); const __m128i not = _mm_set1_epi32(0xffffffff); while( dest < limit ) { tjs_uint32 r = *(tjs_uint32*)rule; __m128i mr = _mm_cvtsi32_si128( r ); mr = _mm_unpacklo_epi8( mr, func.zero_ ); mr = _mm_unpacklo_epi16( mr, func.zero_ ); __m128i opa1 = mr; opa1 = _mm_cmplt_epi32( opa1, msrc1lv ); __m128i md = opa1; __m128i ms11 = _mm_loadu_si128( (__m128i const*)src1 ); md = _mm_andnot_si128( md, ms11 ); if( _mm_movemask_epi8(opa1) != 0 ) { __m128i ms21 = _mm_loadu_si128( (__m128i const*)src2 ); opa1 = _mm_xor_si128( opa1, not ); __m128i opa2 = mr; opa2 = _mm_cmplt_epi32( mr, msrc2lv ); opa1 = _mm_or_si128( opa1, opa2 ); opa2 = _mm_and_si128( opa2, ms21 ); md = _mm_or_si128( md, opa2 ); if( _mm_movemask_epi8(opa1) != 0xffff ) { __m128i blend = func(ms11, ms21, rule); opa1 = _mm_andnot_si128( opa1, blend ); md = _mm_or_si128( md, opa1 ); } } _mm_store_si128( (__m128i*)dest, md ); src1 += 4; src2 += 4; rule += 4; dest += 4; } limit += (len-rem); while( dest < limit ) { tjs_int opa = *rule; if( opa >= src1lv ) { *dest = *src1; rule++; src1++; src2++; dest++; } else if(opa < src2lv) { *dest = *src2; rule++; src1++; src2++; dest++; } else { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; } } } void TVPUnivTransBlend_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { sse2_univ_trans<sse2_univ_trans_blend_func>(dest,src1,src2,rule,table,len); } void TVPUnivTransBlend_switch_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { sse2_univ_trans_switch<sse2_univ_trans_blend_func>(dest,src1,src2,rule,table,len,src1lv,src2lv); } void TVPUnivTransBlend_d_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len) { sse2_univ_trans<sse2_univ_trans_d_blend_func>(dest,src1,src2,rule,table,len); } void TVPUnivTransBlend_switch_d_sse2_c(tjs_uint32 *dest, const tjs_uint32 *src1, const tjs_uint32 *src2, const tjs_uint8 *rule, const tjs_uint32 *table, tjs_int len, tjs_int src1lv, tjs_int src2lv) { sse2_univ_trans_switch<sse2_univ_trans_d_blend_func>(dest,src1,src2,rule,table,len,src1lv,src2lv); }
if(opa < src2lv) { *dest = *src2; rule++; src1++; src2++; dest++; } else { *dest = func( *src1, *src2, *rule ); dest++; src1++; src2++, rule++; }
if_condition
[ { "content": "struct sse2_const_alpha_copy_functor {\n\n\tconst tjs_uint32 alpha32_;\n\n\tconst __m128i alpha_;\n\n\tconst __m128i colormask_;\n\n\tinline sse2_const_alpha_copy_functor( tjs_uint32 mask )\n\n\t: alpha32_(mask<<24), alpha_(_mm_set1_epi32(mask<<24)), colormask_(_mm_set1_epi32(0x00ffffff)) {}\n\n\t...
C++
framework/data/cfg_loader.inl
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
#include "cfg_loader.h" template<> inline int gdm::Config::Get<int>(const std::string& name) const { return ints_.at(name); } template<> inline float gdm::Config::Get<float>(const std::string& name) const { return floats_.at(name); } template<> inline bool gdm::Config::Get<bool>(const std::string& name) const { return bools_.at(name); } template<> inline const std::string& gdm::Config::Get<const std::string&>(const std::string& name) const { static std::string s_dummy {""}; return strings_.count(name) ? strings_.at(name) : s_dummy; } template<> inline std::string gdm::Config::Get<std::string>(const std::string& name) const { return strings_.count(name) ? strings_.at(name) : ""; } template<> inline gdm::Vec3f gdm::Config::Get<gdm::Vec3f>(const std::string& name) const { return vectors3f_.at(name); } template<> inline gdm::Vec4f gdm::Config::Get<gdm::Vec4f>(const std::string& name) const { return vectors4f_.at(name); } template<> inline std::vector<float> gdm::Config::Get<std::vector<float>>(const std::string& name) const { return vectorsf_.at(name); } template<> inline std::vector<std::string> gdm::Config::GetAllVals<std::string>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(strings_.begin(), strings_.end(), [&name, &result](const std::pair<std::string, std::string>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<float> gdm::Config::GetAllVals<float>(const std::string& name) const { std::vector<float> result {}; std::for_each(floats_.begin(), floats_.end(), [&name, &result](const std::pair<std::string, float>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<gdm::Vec3f> gdm::Config::GetAllVals<gdm::Vec3f>(const std::string& name) const { std::vector<Vec3f> result {}; std::for_each(vectors3f_.begin(), vectors3f_.end(), [&name, &result](const std::pair<std::string, Vec3f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<gdm::Vec4f> gdm::Config::GetAllVals<gdm::Vec4f>(const std::string& name) const { std::vector<Vec4f> result {}; std::for_each(vectors4f_.begin(), vectors4f_.end(), [&name, &result](const std::pair<std::string, Vec4f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<std::string>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(strings_.begin(), strings_.end(), [&name, &result](const std::pair<std::string, std::string>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<gdm::Vec3f>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(vectors3f_.begin(), vectors3f_.end(), [&name, &result](const std::pair<std::string, gdm::Vec3f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<gdm::Vec4f>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(vectors4f_.begin(), vectors4f_.end(), [&name, &result](const std::pair<std::string, gdm::Vec4f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline bool gdm::Config::Has<int>(const std::string& name) const { return ints_.count(name); } template<> inline bool gdm::Config::Has<float>(const std::string& name) const { return floats_.count(name); } template<> inline bool gdm::Config::Has<bool>(const std::string& name) const { return bools_.count(name); } template<> inline bool gdm::Config::Has<std::string>(const std::string& name) const { return strings_.count(name); } template<> inline bool gdm::Config::Has<gdm::Vec3f>(const std::string& name) const { return vectors3f_.count(name); } template<> inline bool gdm::Config::Has<gdm::Vec4f>(const std::string& name) const { return vectors4f_.count(name); } template<> inline bool gdm::Config::Has<std::vector<float>>(const std::string& name) const { return vectorsf_.count(name); }
#include "cfg_loader.h" template<> inline int gdm::Config::Get<int>(const std::string& name) const { return ints_.at(name); } template<> inline float gdm::Config::Get<float>(const std::string& name) const { return floats_.at(name); } template<> inline bool gdm::Config::Get<bool>(const std::string& name) const { return bools_.at(name); } template<> inline const std::string& gdm::Config::Get<const std::string&>(const std::string& name) const { static std::string s_dummy {""}; return strings_.count(name) ? strings_.at(name) : s_dummy; } template<> inline std::string gdm::Config::Get<std::string>(const std::string& name) const { return strings_.count(name) ? strings_.at(name) : ""; } template<> inline gdm::Vec3f gdm::Config::Get<gdm::Vec3f>(const std::string& name) const { return vectors3f_.at(name); } template<> inline gdm::Vec4f gdm::Config::Get<gdm::Vec4f>(const std::string& name) const { return vectors4f_.at(name); } template<> inline std::vector<float> gdm::Config::Get<std::vector<float>>(const std::string& name) const { return vectorsf_.at(name); } template<> inline std::vector<std::string> gdm::Config::GetAllVals<std::string>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(strings_.begin(), strings_.end(), [&name, &result](const std::pair<std::string, std::string>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<>
template<> inline std::vector<gdm::Vec3f> gdm::Config::GetAllVals<gdm::Vec3f>(const std::string& name) const { std::vector<Vec3f> result {}; std::for_each(vectors3f_.begin(), vectors3f_.end(), [&name, &result](const std::pair<std::string, Vec3f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<gdm::Vec4f> gdm::Config::GetAllVals<gdm::Vec4f>(const std::string& name) const { std::vector<Vec4f> result {}; std::for_each(vectors4f_.begin(), vectors4f_.end(), [&name, &result](const std::pair<std::string, Vec4f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<std::string>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(strings_.begin(), strings_.end(), [&name, &result](const std::pair<std::string, std::string>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<gdm::Vec3f>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(vectors3f_.begin(), vectors3f_.end(), [&name, &result](const std::pair<std::string, gdm::Vec3f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline std::vector<std::string> gdm::Config::GetAllKeys<gdm::Vec4f>(const std::string& name) const { std::vector<std::string> result {}; std::for_each(vectors4f_.begin(), vectors4f_.end(), [&name, &result](const std::pair<std::string, gdm::Vec4f>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.first); }); return result; } template<> inline bool gdm::Config::Has<int>(const std::string& name) const { return ints_.count(name); } template<> inline bool gdm::Config::Has<float>(const std::string& name) const { return floats_.count(name); } template<> inline bool gdm::Config::Has<bool>(const std::string& name) const { return bools_.count(name); } template<> inline bool gdm::Config::Has<std::string>(const std::string& name) const { return strings_.count(name); } template<> inline bool gdm::Config::Has<gdm::Vec3f>(const std::string& name) const { return vectors3f_.count(name); } template<> inline bool gdm::Config::Has<gdm::Vec4f>(const std::string& name) const { return vectors4f_.count(name); } template<> inline bool gdm::Config::Has<std::vector<float>>(const std::string& name) const { return vectorsf_.count(name); }
inline std::vector<float> gdm::Config::GetAllVals<float>(const std::string& name) const { std::vector<float> result {}; std::for_each(floats_.begin(), floats_.end(), [&name, &result](const std::pair<std::string, float>& pair) { if (pair.first.find(name) == 0) result.push_back(pair.second); }); return result; }
function_block-full_function
[ { "content": "class TMap : public std::map<K, D, CMP, pool_allocator<std::pair<K const, D> > > {\n\n};\n\n\n\ntemplate <class K, class D, class HASH = std::hash<K>, class PRED = std::equal_to<K> >\n", "file_path": "3rdparty/vulkan_sdk/1.2.170.0/Include/glslang/Include/Common.h", "rank": 0, "score": ...
C++
Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/rtp_rtcp/source/byte_io_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
#include <limits> #include "modules/rtp_rtcp/source/byte_io.h" #include BOSS_WEBRTC_U_test__gtest_h namespace webrtc { namespace { class ByteIoTest : public ::testing::Test { protected: ByteIoTest() {} virtual ~ByteIoTest() {} enum { kAlignments = sizeof(uint64_t) - 1 }; template <typename T> T CreateTestValue(bool negative, uint8_t num_bytes) { T val = 0; for (uint8_t i = 0; i != num_bytes; ++i) { val = (val << 8) + (negative ? (0xFF - i) : (i + 1)); } if (std::numeric_limits<T>::is_signed && negative && num_bytes < sizeof(T)) { T mask = static_cast<T>(-1); const T neg_byte = static_cast<T>(0xFF); for (int i = 0; i < num_bytes; ++i) { mask &= ~(neg_byte << (i * 8)); } val |= mask; } return val; } template <typename T> void PopulateTestData(uint8_t* data, T value, int num_bytes, bool bigendian) { if (bigendian) { for (int i = 0; i < num_bytes; ++i) { data[i] = (value >> ((num_bytes - i - 1) * 8)) & 0xFF; } } else { for (int i = 0; i < num_bytes; ++i) { data[i] = (value >> (i * 8)) & 0xFF; } } } template <typename T, T (*RM)(const uint8_t*), int B> void TestRead(bool big_endian) { for (int neg = 0; neg < 2; ++neg) { bool negative = neg > 0; T test_value = CreateTestValue<T>(negative, B); uint8_t bytes[B + kAlignments]; for (int i = 0; i < kAlignments; ++i) { PopulateTestData(bytes + i, test_value, B, big_endian); EXPECT_EQ(test_value, RM(bytes + i)); } } } template <typename T, void (*WM)(uint8_t*, T), int B> void TestWrite(bool big_endian) { for (int neg = 0; neg < 2; ++neg) { bool negative = neg > 0; T test_value = CreateTestValue<T>(negative, B); uint8_t expected_bytes[B + kAlignments]; uint8_t bytes[B + kAlignments]; for (int i = 0; i < kAlignments; ++i) { PopulateTestData(expected_bytes + i, test_value, B, big_endian); memset(bytes, 0, B + kAlignments); WM(bytes + i, test_value); for (int j = 0; j < B; ++j) { EXPECT_EQ(expected_bytes[i + j], bytes[i + j]); } } } } }; TEST_F(ByteIoTest, Test16UBitBigEndian) { TestRead<uint16_t, ByteReader<uint16_t>::ReadBigEndian, sizeof(uint16_t)>(true); TestWrite<uint16_t, ByteWriter<uint16_t>::WriteBigEndian, sizeof(uint16_t)>(true); } TEST_F(ByteIoTest, Test24UBitBigEndian) { TestRead<uint32_t, ByteReader<uint32_t, 3>::ReadBigEndian, 3>(true); TestWrite<uint32_t, ByteWriter<uint32_t, 3>::WriteBigEndian, 3>(true); } TEST_F(ByteIoTest, Test32UBitBigEndian) { TestRead<uint32_t, ByteReader<uint32_t>::ReadBigEndian, sizeof(uint32_t)>(true); TestWrite<uint32_t, ByteWriter<uint32_t>::WriteBigEndian, sizeof(uint32_t)>(true); } TEST_F(ByteIoTest, Test64UBitBigEndian) { TestRead<uint64_t, ByteReader<uint64_t>::ReadBigEndian, sizeof(uint64_t)>(true); TestWrite<uint64_t, ByteWriter<uint64_t>::WriteBigEndian, sizeof(uint64_t)>(true); } TEST_F(ByteIoTest, Test16SBitBigEndian) { TestRead<int16_t, ByteReader<int16_t>::ReadBigEndian, sizeof(int16_t)>(true); TestWrite<int16_t, ByteWriter<int16_t>::WriteBigEndian, sizeof(int16_t)>(true); } TEST_F(ByteIoTest, Test24SBitBigEndian) { TestRead<int32_t, ByteReader<int32_t, 3>::ReadBigEndian, 3>(true); TestWrite<int32_t, ByteWriter<int32_t, 3>::WriteBigEndian, 3>(true); } TEST_F(ByteIoTest, Test32SBitBigEndian) { TestRead<int32_t, ByteReader<int32_t>::ReadBigEndian, sizeof(int32_t)>(true); TestWrite<int32_t, ByteWriter<int32_t>::WriteBigEndian, sizeof(int32_t)>(true); } TEST_F(ByteIoTest, Test64SBitBigEndian) { TestRead<int64_t, ByteReader<int64_t>::ReadBigEndian, sizeof(int64_t)>(true); TestWrite<int64_t, ByteWriter<int64_t>::WriteBigEndian, sizeof(int64_t)>(true); } TEST_F(ByteIoTest, Test16UBitLittleEndian) { TestRead<uint16_t, ByteReader<uint16_t>::ReadLittleEndian, sizeof(uint16_t)>(false); TestWrite<uint16_t, ByteWriter<uint16_t>::WriteLittleEndian, sizeof(uint16_t)>(false); } TEST_F(ByteIoTest, Test24UBitLittleEndian) { TestRead<uint32_t, ByteReader<uint32_t, 3>::ReadLittleEndian, 3>(false); TestWrite<uint32_t, ByteWriter<uint32_t, 3>::WriteLittleEndian, 3>(false); } TEST_F(ByteIoTest, Test32UBitLittleEndian) { TestRead<uint32_t, ByteReader<uint32_t>::ReadLittleEndian, sizeof(uint32_t)>(false); TestWrite<uint32_t, ByteWriter<uint32_t>::WriteLittleEndian, sizeof(uint32_t)>(false); } TEST_F(ByteIoTest, Test64UBitLittleEndian) { TestRead<uint64_t, ByteReader<uint64_t>::ReadLittleEndian, sizeof(uint64_t)>(false); TestWrite<uint64_t, ByteWriter<uint64_t>::WriteLittleEndian, sizeof(uint64_t)>(false); } TEST_F(ByteIoTest, Test16SBitLittleEndian) { TestRead<int16_t, ByteReader<int16_t>::ReadLittleEndian, sizeof(int16_t)>(false); TestWrite<int16_t, ByteWriter<int16_t>::WriteLittleEndian, sizeof(int16_t)>(false); } TEST_F(ByteIoTest, Test24SBitLittleEndian) { TestRead<int32_t, ByteReader<int32_t, 3>::ReadLittleEndian, 3>(false); TestWrite<int32_t, ByteWriter<int32_t, 3>::WriteLittleEndian, 3>(false); } TEST_F(ByteIoTest, Test32SBitLittleEndian) { TestRead<int32_t, ByteReader<int32_t>::ReadLittleEndian, sizeof(int32_t)>(false); TestWrite<int32_t, ByteWriter<int32_t>::WriteLittleEndian, sizeof(int32_t)>(false); } TEST_F(ByteIoTest, Test64SBitLittleEndian) { TestRead<int64_t, ByteReader<int64_t>::ReadLittleEndian, sizeof(int64_t)>(false); TestWrite<int64_t, ByteWriter<int64_t>::WriteLittleEndian, sizeof(int64_t)>(false); } TEST(ByteIo, SanityCheckFixedByteArrayUnsignedReadBigEndian) { uint8_t data[8] = {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; uint64_t value = ByteReader<uint64_t, 2>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEE), value); value = ByteReader<uint64_t, 3>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDD), value); value = ByteReader<uint64_t, 4>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCC), value); value = ByteReader<uint64_t, 5>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBB), value); value = ByteReader<uint64_t, 6>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA), value); value = ByteReader<uint64_t, 7>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA99), value); value = ByteReader<uint64_t, 8>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA9988), value); } TEST(ByteIo, SanityCheckFixedByteArrayUnsignedReadLittleEndian) { uint8_t data[8] = {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; uint64_t value = ByteReader<uint64_t, 2>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xEEFF), value); value = ByteReader<uint64_t, 3>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xDDEEFF), value); value = ByteReader<uint64_t, 4>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xCCDDEEFF), value); value = ByteReader<uint64_t, 5>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xBBCCDDEEFF), value); value = ByteReader<uint64_t, 6>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xAABBCCDDEEFF), value); value = ByteReader<uint64_t, 7>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0x99AABBCCDDEEFF), value); value = ByteReader<uint64_t, 8>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0x8899AABBCCDDEEFF), value); } } }
#include <limits> #include "modules/rtp_rtcp/source/byte_io.h" #include BOSS_WEBRTC_U_test__gtest_h namespace webrtc { namespace { class ByteIoTest : public ::testing::Test { protected: ByteIoTest() {} virtual ~ByteIoTest() {} enum { kAlignments = sizeof(uint64_t) - 1 }; template <typename T> T CreateTestValue(bool negative, uint8_t num_bytes) { T val = 0; for (uint8_t i = 0; i != num_bytes; ++i) { val = (val << 8) + (negative ? (0xFF - i) : (i + 1)); } if (std::numeric_limits<T>::is_signed && negative && num_bytes < sizeof(T)) { T mask = static_cast<T>(-1); const T neg_byte = static_cast<T>(0xFF); for (int i = 0; i < num_bytes; ++i) { mask &= ~(neg_byte << (i * 8)); } val |= mask; } return val; } template <typename T> void PopulateTestData(uint8_t* data, T value, int num_bytes, bool bigendian) { if (bigendian) { for (int i = 0; i < num_bytes; ++i) { data[i] = (value >> ((num_bytes - i - 1) * 8)) & 0xFF; } } else { for (int i = 0; i < num_bytes; ++i) { data[i] = (value >> (i * 8)) & 0xFF; } } } template <typename T, T (*RM)(const uint8_t*), int B> void TestRead(bool big_endian) { for (int neg = 0; neg < 2; ++neg) { bool negative = neg > 0; T test_value = CreateTestValue<T>(negative, B); uint8_t bytes[B + kAlignments]; for (int i = 0; i < kAlignments; ++i) { PopulateTestData(bytes + i, test_value, B, big_endian); EXPECT_EQ(test_value, RM(bytes + i)); } } } template <typename T, void (*WM)(uint8_t*, T), int B> void TestWrite(bool big_endian) { for (int neg = 0; neg < 2; ++neg) { bool negative = neg > 0; T test_value = CreateTestValue<T>(negative, B); uint8_t expected_bytes[B + kAlignments]; uint8_t bytes[B + kAlignments]; for (int i = 0; i < kAlignments; ++i) { PopulateTestData(expected_bytes + i, test_value, B, big_endian); memset(bytes, 0, B + kAlignments); WM(bytes + i, test_value); for (int j = 0; j < B; ++j) { EXPECT_EQ(expected_bytes[i + j], bytes[i + j]); } } } } }; TEST_F(ByteIoTest, Test16UBitBigEndian) { TestRead<uint16_t, ByteReader<uint16_t>::ReadBigEndian, sizeof(uint16_t)>(true); TestWrite<uint16_t, ByteWriter<uint16_t>::WriteBigEndian, sizeof(uint16_t)>(true); } TEST_F(ByteIoTest, Test24UBitBigEndian) { TestRead<uint32_t, ByteReader<uint32_t, 3>::ReadBigEndian, 3>(true); TestWrite<uint32_t, ByteWriter<uint32_t, 3>::WriteBigEndian, 3>(true); } TEST_F(ByteIoTest, Test32UBitBigEndian) { TestRead<uint32_t, ByteReader<uint32_t>::ReadBigEndian, sizeof(uint32_t)>(true); TestWrite<uint32_t, ByteWriter<uint32_t>::WriteBigEndian, sizeof(uint32_t)>(true); } TEST_F(ByteIoTest, Test64UBitBigEndian) { TestRead<uint64_t, ByteReader<uint64_t>::ReadBigEndian, sizeof(uint64_t)>(true); TestWrite<uint64_t, ByteWriter<uint64_t>::WriteBigEndian, sizeof(uint64_t)>(true); } TEST_F(ByteIoTest, Test16SBitBigEndian) { TestRead<int16_t, ByteReader<int16_t>::ReadBigEndian, sizeof(int16_t)>(true); TestWrite<int16_t, ByteWriter<int16_t>::WriteBigEndian, sizeof(int16_t)>(true); } TEST_F(ByteIoTest, Test24SBitBigEndian) { TestRead<int32_t, ByteReader<int32_t, 3>::ReadBigEndian, 3>(true); TestWrite<int32_t, ByteWriter<int32_t, 3>::WriteBigEndian, 3>(true); } TEST_F(ByteIoTest, Test32SBitBigEndian) { TestRead<int32_t, ByteReader<int32_t>::ReadBigEndian, sizeof(int32_t)>(true); TestWrite<int32_t, ByteWriter<int32_t
4_t, ByteWriter<uint64_t>::WriteLittleEndian, sizeof(uint64_t)>(false); } TEST_F(ByteIoTest, Test16SBitLittleEndian) { TestRead<int16_t, ByteReader<int16_t>::ReadLittleEndian, sizeof(int16_t)>(false); TestWrite<int16_t, ByteWriter<int16_t>::WriteLittleEndian, sizeof(int16_t)>(false); } TEST_F(ByteIoTest, Test24SBitLittleEndian) { TestRead<int32_t, ByteReader<int32_t, 3>::ReadLittleEndian, 3>(false); TestWrite<int32_t, ByteWriter<int32_t, 3>::WriteLittleEndian, 3>(false); } TEST_F(ByteIoTest, Test32SBitLittleEndian) { TestRead<int32_t, ByteReader<int32_t>::ReadLittleEndian, sizeof(int32_t)>(false); TestWrite<int32_t, ByteWriter<int32_t>::WriteLittleEndian, sizeof(int32_t)>(false); } TEST_F(ByteIoTest, Test64SBitLittleEndian) { TestRead<int64_t, ByteReader<int64_t>::ReadLittleEndian, sizeof(int64_t)>(false); TestWrite<int64_t, ByteWriter<int64_t>::WriteLittleEndian, sizeof(int64_t)>(false); } TEST(ByteIo, SanityCheckFixedByteArrayUnsignedReadBigEndian) { uint8_t data[8] = {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; uint64_t value = ByteReader<uint64_t, 2>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEE), value); value = ByteReader<uint64_t, 3>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDD), value); value = ByteReader<uint64_t, 4>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCC), value); value = ByteReader<uint64_t, 5>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBB), value); value = ByteReader<uint64_t, 6>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA), value); value = ByteReader<uint64_t, 7>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA99), value); value = ByteReader<uint64_t, 8>::ReadBigEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xFFEEDDCCBBAA9988), value); } TEST(ByteIo, SanityCheckFixedByteArrayUnsignedReadLittleEndian) { uint8_t data[8] = {0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; uint64_t value = ByteReader<uint64_t, 2>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xEEFF), value); value = ByteReader<uint64_t, 3>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xDDEEFF), value); value = ByteReader<uint64_t, 4>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xCCDDEEFF), value); value = ByteReader<uint64_t, 5>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xBBCCDDEEFF), value); value = ByteReader<uint64_t, 6>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0xAABBCCDDEEFF), value); value = ByteReader<uint64_t, 7>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0x99AABBCCDDEEFF), value); value = ByteReader<uint64_t, 8>::ReadLittleEndian(data); EXPECT_EQ(static_cast<uint64_t>(0x8899AABBCCDDEEFF), value); } } }
>::WriteBigEndian, sizeof(int32_t)>(true); } TEST_F(ByteIoTest, Test64SBitBigEndian) { TestRead<int64_t, ByteReader<int64_t>::ReadBigEndian, sizeof(int64_t)>(true); TestWrite<int64_t, ByteWriter<int64_t>::WriteBigEndian, sizeof(int64_t)>(true); } TEST_F(ByteIoTest, Test16UBitLittleEndian) { TestRead<uint16_t, ByteReader<uint16_t>::ReadLittleEndian, sizeof(uint16_t)>(false); TestWrite<uint16_t, ByteWriter<uint16_t>::WriteLittleEndian, sizeof(uint16_t)>(false); } TEST_F(ByteIoTest, Test24UBitLittleEndian) { TestRead<uint32_t, ByteReader<uint32_t, 3>::ReadLittleEndian, 3>(false); TestWrite<uint32_t, ByteWriter<uint32_t, 3>::WriteLittleEndian, 3>(false); } TEST_F(ByteIoTest, Test32UBitLittleEndian) { TestRead<uint32_t, ByteReader<uint32_t>::ReadLittleEndian, sizeof(uint32_t)>(false); TestWrite<uint32_t, ByteWriter<uint32_t>::WriteLittleEndian, sizeof(uint32_t)>(false); } TEST_F(ByteIoTest, Test64UBitLittleEndian) { TestRead<uint64_t, ByteReader<uint64_t>::ReadLittleEndian, sizeof(uint64_t)>(false); TestWrite<uint6
random
[]
C++
ErrorPrintout.cpp
dascenzo/MyDictionary
f258f987f05d58be0c0df6eec58eec6be0b441dc
#include "ErrorPrintout.h" #include "Options.h" #include "Error.h" #include "CommandLine.h" #include "StringViewOutput.h" template<typename T> class GeneratorBase { public: GeneratorBase(const CommandLine& commandLine, const T& error) noexcept : commandLine(commandLine), error(error) { } protected: ~GeneratorBase() = default; const CommandLine& commandLine; const T& error; }; template<typename T> class ErrorLineGenerator; template<> class ErrorLineGenerator<EnvironmentSetupError> : public GeneratorBase<EnvironmentSetupError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const BadEnvVar& e) const noexcept { std::fprintf(stderr, "%.*s: invalid env var: %s\n", C_STR(commandLine.programName), e.variable()); } void operator()(const SetEnvFailed& e) const noexcept { std::fprintf(stderr, "%.*s: failed to set environment: %s\n", C_STR(commandLine.programName), std::strerror(e.errNo())); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<UsageError> : public GeneratorBase<UsageError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const GeneralActionMisuse& ) const noexcept { std::fprintf(stderr, "%.*s: invalid usage\n", C_STR(commandLine.programName)); } void operator()(const MissingArgument& e) const noexcept { std::fprintf(stderr, "%.*s: missing argument for %s\n", C_STR(commandLine.programName), e.option()); } void operator()(const InvalidArgument& e) const noexcept { std::fprintf(stderr, "%.*s: invalid argument for %s\n", C_STR(commandLine.programName), e.option()); } void operator()(const MultipleFormats& ) const noexcept { std::fprintf(stderr, "%.*s: multiple formats given\n", C_STR(commandLine.programName)); } void operator()(const NoAction& ) const noexcept { std::fprintf(stderr, "%.*s: no action given\n", C_STR(commandLine.programName)); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<DataStateError> : public GeneratorBase<DataStateError> { public: void operator()() const noexcept { try { std::visit(*this, error.data()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const DataStateError::WordData& data) const noexcept { std::fprintf(stderr, "%.*s: operation failed: word (%s) %s\n", C_STR(commandLine.programName), data.value(), problem()); } void operator()(const DataStateError::TagData& data) const noexcept { std::fprintf(stderr, "%.*s: operation failed: tag (%s) %s\n", C_STR(commandLine.programName), data.value(), problem()); } void operator()(const DataStateError::WordTagData& data) const noexcept { std::fprintf(stderr, "%.*s: operation failed: word/tag combination (%s/%s) %s\n", C_STR(commandLine.programName), data.first.value(), data.second.value(), problem()); } using GeneratorBase::GeneratorBase; private: const char* problem() const noexcept { switch (error.type()) { case DataStateError::MISSING: return "doesn't exist"; case DataStateError::ALREADY_PRESENT: return "already exists"; } } }; template<> class ErrorLineGenerator<pqxx::failure> : public GeneratorBase<pqxx::failure> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: database runtime error: %s\n", C_STR(commandLine.programName), error.what()); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<std::exception> : public GeneratorBase<std::exception> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: internal error: %s\n", C_STR(commandLine.programName), error.what()); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<UnknownException> : public GeneratorBase<UnknownException> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: unknown internal error\n", C_STR(commandLine.programName)); } using GeneratorBase::GeneratorBase; }; template<typename T> class SuggestionLineGenerator : public GeneratorBase<T> { public: using GeneratorBase<T>::GeneratorBase; void operator()() const noexcept { } }; template<> class SuggestionLineGenerator<UsageError> : public GeneratorBase<UsageError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const GeneralActionMisuse& e) const noexcept { try { std::visit(PrintActionHelp(*this), e.action()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const MissingArgument& e) const noexcept { try { std::visit(PrintActionHelp(*this), e.action()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const InvalidArgument& e) const noexcept { std::fprintf(stderr, "try: %s -- %s\n", e.option(), e.argument()); } void operator()(const MultipleFormats& ) const noexcept { std::fprintf(stderr, "try: zero or one of -f, -ff, -fff\n"); } void operator()(const NoAction& ) const noexcept { printGeneralHelp(); } using GeneratorBase::GeneratorBase; private: void printGeneralHelp() const noexcept { std::fprintf(stderr, "try: %.*s help\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedAdd&) const noexcept { std::fprintf(stderr, ADD_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedRm&) const noexcept { std::fprintf(stderr, RM_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedFind&) const noexcept { std::fprintf(stderr, FIND_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedTags&) const noexcept { std::fprintf(stderr, TAGS_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedEdit&) const noexcept { std::fprintf(stderr, EDIT_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedShorthandFind&) const noexcept { printGeneralHelp(); } class PrintActionHelp { public: PrintActionHelp(const SuggestionLineGenerator& generator) noexcept : m_generator(generator) {} template<typename FailedAction> void operator()(const FailedAction& failedAction) const noexcept { m_generator.printActionHelp(failedAction); } private: const SuggestionLineGenerator& m_generator; }; }; template<typename T> static void doPrintout(const CommandLine& commandLine, const T& e) noexcept { ErrorLineGenerator<T>{commandLine, e}(); SuggestionLineGenerator<T>{commandLine, e}(); } void ErrorPrintout::handle(const CommandLine& commandLine, const EnvironmentSetupError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const UsageError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const DataStateError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const pqxx::failure& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const std::exception& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const UnknownException& e) noexcept { doPrintout(commandLine, e); }
#include "ErrorPrintout.h" #include "Options.h" #include "Error.h" #include "CommandLine.h" #include "StringViewOutput.h" template<typename T> class GeneratorBase { public: GeneratorBase(const CommandLine& commandLine, const T& error) noexcept : commandLine(commandLine), error(error) { } protected: ~GeneratorBase() = default; const CommandLine& commandLine; const T& error; }; template<typename T> class ErrorLineGenerator; template<> class ErrorLineGenerator<EnvironmentSetupError> : public GeneratorBase<EnvironmentSetupError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const BadEnvVar& e) const noexcept { std::fprintf(stderr, "%.*s: invalid env var: %s\n", C_STR(commandLine.programName), e.variable()); } void operator()(const SetEnvFailed& e) const noexcept { std::fprintf(stderr, "%.*s: failed to set environment: %s\n", C_STR(commandLine.programName), std::strerror(e.errNo())); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<UsageError> : public GeneratorBase<UsageError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const GeneralActionMisuse& ) const noexcept { std::fprintf(stderr, "%.*s: invalid usage\n", C_STR(commandLine.programName)); } void operator()(const MissingArgument& e) const noexcept { std::fprintf(stderr, "%.*s: missing argument for %s\n", C_STR(commandLine.programName), e.option()); } void operator()(const InvalidArgument& e) const noexcept {
failed: word (%s) %s\n", C_STR(commandLine.programName), data.value(), problem()); } void operator()(const DataStateError::TagData& data) const noexcept { std::fprintf(stderr, "%.*s: operation failed: tag (%s) %s\n", C_STR(commandLine.programName), data.value(), problem()); } void operator()(const DataStateError::WordTagData& data) const noexcept { std::fprintf(stderr, "%.*s: operation failed: word/tag combination (%s/%s) %s\n", C_STR(commandLine.programName), data.first.value(), data.second.value(), problem()); } using GeneratorBase::GeneratorBase; private: const char* problem() const noexcept { switch (error.type()) { case DataStateError::MISSING: return "doesn't exist"; case DataStateError::ALREADY_PRESENT: return "already exists"; } } }; template<> class ErrorLineGenerator<pqxx::failure> : public GeneratorBase<pqxx::failure> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: database runtime error: %s\n", C_STR(commandLine.programName), error.what()); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<std::exception> : public GeneratorBase<std::exception> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: internal error: %s\n", C_STR(commandLine.programName), error.what()); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<UnknownException> : public GeneratorBase<UnknownException> { public: void operator()() const noexcept { std::fprintf(stderr, "%.*s: unknown internal error\n", C_STR(commandLine.programName)); } using GeneratorBase::GeneratorBase; }; template<typename T> class SuggestionLineGenerator : public GeneratorBase<T> { public: using GeneratorBase<T>::GeneratorBase; void operator()() const noexcept { } }; template<> class SuggestionLineGenerator<UsageError> : public GeneratorBase<UsageError> { public: void operator()() const noexcept { try { std::visit(*this, error.variant()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const GeneralActionMisuse& e) const noexcept { try { std::visit(PrintActionHelp(*this), e.action()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const MissingArgument& e) const noexcept { try { std::visit(PrintActionHelp(*this), e.action()); } catch (const std::bad_variant_access& ) { printGeneralHelp(); } } void operator()(const InvalidArgument& e) const noexcept { std::fprintf(stderr, "try: %s -- %s\n", e.option(), e.argument()); } void operator()(const MultipleFormats& ) const noexcept { std::fprintf(stderr, "try: zero or one of -f, -ff, -fff\n"); } void operator()(const NoAction& ) const noexcept { printGeneralHelp(); } using GeneratorBase::GeneratorBase; private: void printGeneralHelp() const noexcept { std::fprintf(stderr, "try: %.*s help\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedAdd&) const noexcept { std::fprintf(stderr, ADD_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedRm&) const noexcept { std::fprintf(stderr, RM_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedFind&) const noexcept { std::fprintf(stderr, FIND_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedTags&) const noexcept { std::fprintf(stderr, TAGS_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedEdit&) const noexcept { std::fprintf(stderr, EDIT_USAGE "\n", C_STR(commandLine.baseProgramName)); } void printActionHelp(const FailedShorthandFind&) const noexcept { printGeneralHelp(); } class PrintActionHelp { public: PrintActionHelp(const SuggestionLineGenerator& generator) noexcept : m_generator(generator) {} template<typename FailedAction> void operator()(const FailedAction& failedAction) const noexcept { m_generator.printActionHelp(failedAction); } private: const SuggestionLineGenerator& m_generator; }; }; template<typename T> static void doPrintout(const CommandLine& commandLine, const T& e) noexcept { ErrorLineGenerator<T>{commandLine, e}(); SuggestionLineGenerator<T>{commandLine, e}(); } void ErrorPrintout::handle(const CommandLine& commandLine, const EnvironmentSetupError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const UsageError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const DataStateError& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const pqxx::failure& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const std::exception& e) noexcept { doPrintout(commandLine, e); } void ErrorPrintout::handle(const CommandLine& commandLine, const UnknownException& e) noexcept { doPrintout(commandLine, e); }
std::fprintf(stderr, "%.*s: invalid argument for %s\n", C_STR(commandLine.programName), e.option()); } void operator()(const MultipleFormats& ) const noexcept { std::fprintf(stderr, "%.*s: multiple formats given\n", C_STR(commandLine.programName)); } void operator()(const NoAction& ) const noexcept { std::fprintf(stderr, "%.*s: no action given\n", C_STR(commandLine.programName)); } using GeneratorBase::GeneratorBase; }; template<> class ErrorLineGenerator<DataStateError> : public GeneratorBase<DataStateError> { public: void operator()() const noexcept { try { std::visit(*this, error.data()); } catch (const std::bad_variant_access& ) { std::fprintf(stderr, "%.*s: %s\n", C_STR(commandLine.programName), error.what()); } } void operator()(const DataStateError::WordData& data) const noexcept { std::fprintf(stderr, "%.*s: operation
random
[ { "content": "class SetEnvFailed {\n\npublic:\n\n SetEnvFailed(int errNo) noexcept;\n\n int errNo() const noexcept;\n\nprivate:\n\n int m_errNo;\n\n};\n", "file_path": "Error.h", "rank": 0, "score": 156967.1348443014 }, { "content": "// === EnvironmentSetupError ===\n\nclass BadEnvVar {\n...
C++
AltTabber/Gui.cpp
alzwded/AltTabber
9da50d23f5e132e9133ecea0093fe1b02ed01fc6
#include "stdafx.h" #include "AltTabber.h" #include <WinUser.h> extern ProgramState_t g_programState; extern void log(LPTSTR fmt, ...); extern MonitorGeom_t GetMonitorGeometry(); static inline BOOL IsAltTabWindow(HWND hwnd) { if(!IsWindowVisible(hwnd)) return FALSE; TCHAR str[MAX_PATH + 1]; GetWindowText(hwnd, str, MAX_PATH); log(_T("window %ls has style %lX and exstyle %lX\n"), str, GetWindowLong(hwnd, GWL_STYLE), GetWindowLong(hwnd, GWL_EXSTYLE)); log(_T("parent: %p\n"), GetParent(hwnd)); HWND hwndTry, hwndWalk = NULL; hwndTry = GetAncestor(hwnd, GA_ROOTOWNER); while(hwndTry != hwndWalk) { hwndWalk = hwndTry; hwndTry = GetLastActivePopup(hwndWalk); if(IsWindowVisible(hwndTry)) break; } if(hwndWalk != hwnd) return FALSE; #if 0 TITLEBARINFO ti; ti.cbSize = sizeof(ti); GetTitleBarInfo(hwnd, &ti); if(ti.rgstate[0] & STATE_SYSTEM_INVISIBLE) return FALSE; #endif if(GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) return FALSE; if(GetWindowLong(hwnd, GWL_STYLE) & WS_CHILD) return FALSE; #if 0 LONG style = GetWindowLong(hwnd, GWL_EXSTYLE); if((style & (WS_VISIBLE | WS_EX_TOOLWINDOW | WS_POPUP | WS_CAPTION | WS_DLGFRAME | WS_OVERLAPPED | WS_TILED | WS_SYSMENU | WS_THICKFRAME )) == 0) { return FALSE; } #endif return TRUE; } static BOOL GetImagePathName(HWND hwnd, std::wstring& imagePathName) { BOOL hr = 0; TCHAR str2[MAX_PATH + 1]; DWORD procId; if(GetWindowThreadProcessId(hwnd, &procId) > 0) { auto hnd = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, procId); if(hnd != NULL) { UINT len; if((len = GetModuleFileNameEx(hnd, NULL, str2, MAX_PATH)) > 0) { imagePathName.assign(&str2[0], &str2[len]); hr = 1; } else { log(_T("GetModuleFileNameEx failed: %u errno %d\n"), len, GetLastError()); } CloseHandle(hnd); } } return hr; } static BOOL CALLBACK enumWindows(HWND hwnd, LPARAM lParam) { if(hwnd == g_programState.hWnd) return TRUE; if(!IsAltTabWindow(hwnd)) return TRUE; std::wstring filter = *((std::wstring const*)lParam); TCHAR str[257]; GetWindowText(hwnd, str, 256); std::wstring title(str); std::wstring imagePathName; if(GetImagePathName(hwnd, imagePathName)) { std::wstringstream wss; wss << imagePathName << std::wstring(L" // ") << title; title = wss.str(); } log(_T("the label is: %ls\n"), title.c_str()); std::transform(title.begin(), title.end(), title.begin(), ::tolower); std::transform(filter.begin(), filter.end(), filter.begin(), ::tolower); if(!filter.empty() && title.find(filter) == std::wstring::npos) { return TRUE; } HMONITOR hMonitor = NULL; if(g_programState.compatHacks & JAT_HACK_DEXPOT) { hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL); if(!hMonitor) return TRUE; } else { hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); } HTHUMBNAIL hThumb = NULL; auto hr = DwmRegisterThumbnail(g_programState.hWnd, hwnd, &hThumb); log(_T("register thumbnail for %p on monitor %p: %d\n"), (void*)hwnd, (void*)hMonitor, hr); if(hr == S_OK) { AppThumb_t at = { APP_THUMB_AERO, hwnd, }; at.thumb = hThumb; g_programState.thumbnails[hMonitor].push_back(at); } else { AppThumb_t at = { APP_THUMB_COMPAT, hwnd, }; HICON hIcon = NULL; hIcon = (HICON)GetClassLongPtr(hwnd, GCLP_HICON); if(!hIcon) { DWORD_PTR lresult; UINT sleepAmount = (g_programState.sleptThroughNWindows < 5) ? 50 : (g_programState.sleptThroughNWindows < 10) ? 25 : (g_programState.sleptThroughNWindows < 20) ? 10 : 5; auto hr = SendMessageTimeout(hwnd, WM_GETICON, ICON_BIG, 0, SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT, sleepAmount , &lresult); if(hr) { g_programState.sleptThroughNWindows++; hIcon = (HICON)lresult; } else { log(_T("Sending WM_GETICON to %ld failed; lresult %ld errno %d\n"), hwnd, lresult, GetLastError()); } } at.icon = hIcon; g_programState.thumbnails[hMonitor].push_back(at); } return TRUE; } void PurgeThumbnails() { for(auto i = g_programState.thumbnails.begin(); i != g_programState.thumbnails.end(); ++i) { auto thumbs = i->second; decltype(thumbs) rest(thumbs.size()); std::remove_copy_if( thumbs.begin(), thumbs.end(), std::inserter(rest, rest.end()), [](AppThumb_t const& thumb) -> bool { return thumb.type != APP_THUMB_AERO; }); std::for_each(rest.begin(), rest.end(), [](AppThumb_t const& thumb) { DwmUnregisterThumbnail(thumb.thumb); }); } g_programState.thumbnails.clear(); } void CreateThumbnails(std::wstring const& filter) { PurgeThumbnails(); auto hDesktop = OpenInputDesktop(0, FALSE, GENERIC_READ); if(!hDesktop) { log(_T("open desktop failed; errno = %d\n"), GetLastError()); return; } g_programState.sleptThroughNWindows = 0; auto hr = EnumDesktopWindows(hDesktop, enumWindows, (LPARAM)&filter); CloseDesktop(hDesktop); log(_T("enum desktop windows: %d\n"), hr); } template<typename F> void PerformSlotting(F&& functor) { auto mis = GetMonitorGeometry(); for(size_t i = 0; i < mis.monitors.size(); ++i) { auto& mi = mis.monitors[i]; auto& thumbs = g_programState.thumbnails[mi.hMonitor]; auto nWindows = thumbs.size(); unsigned int nTiles = 1; while(nTiles < nWindows) nTiles <<= 1; if(nTiles != nWindows) nTiles = max(1, nTiles >> 1); long lala = (long)(sqrt((double)nTiles) + 0.5); long l1 = lala; long l2 = lala; while(((unsigned)l1) * ((unsigned)l2) < nWindows) l1++; lala = l1 * l2; long ws = (mi.extent.right - mi.extent.left) / l1; long hs = (mi.extent.bottom - mi.extent.top) / l2; for(size_t j = 0; j < thumbs.size(); ++j) { functor(mi, j, l1, l2, hs, ws); } } } void SetThumbnails() { g_programState.activeSlot = -1; g_programState.slots.clear(); size_t nthSlot = 0; MonitorGeom_t mis = GetMonitorGeometry(); PerformSlotting([&](MonitorInfo_t& mi, size_t j, long l1, long, long hs, long ws) { AppThumb_t& thumb = g_programState.thumbnails[mi.hMonitor][j]; long x = ((long)j % l1) * ws + 3; long y = ((long)j / l1) * hs + hs / 3 + 3; long x1 = x + ws - 6; long y1 = y + hs - hs / 3 - 6; RECT r; r.left = mi.extent.left - mis.r.left + x; r.right = mi.extent.left - mis.r.left + x1; r.top = mi.extent.top - mis.r.top + y; r.bottom = mi.extent.top - mis.r.top + y1; if(thumb.type == APP_THUMB_AERO) { DWM_THUMBNAIL_PROPERTIES thProps; thProps.dwFlags = DWM_TNP_RECTDESTINATION | DWM_TNP_VISIBLE; SIZE ws; HRESULT haveThumbSize = DwmQueryThumbnailSourceSize(thumb.thumb, &ws); if(haveThumbSize == S_OK) { SIZE rs; rs.cx = r.right - r.left; rs.cy = r.bottom - r.top; RECT dRect; dRect.left = r.left; dRect.top = r.top; float rRap = (float)rs.cx / (float)rs.cy; float sRap = (float)ws.cx / (float)ws.cy; if(sRap > rRap) { dRect.right = r.right; LONG h = (LONG)(rs.cx / sRap); LONG delta = (rs.cy - h) / 2; dRect.top += delta; dRect.bottom = dRect.top + h; } else { dRect.bottom = r.bottom; LONG w = (LONG)(rs.cy * sRap); LONG delta = (rs.cx - w) / 2; dRect.left += delta; dRect.right = dRect.left + w; } thProps.rcDestination = dRect; } else { thProps.rcDestination = r; log(_T("DwmQueryThumbnailSourceSize failed %d: errno %d\n"), haveThumbSize, GetLastError()); } thProps.fVisible = TRUE; DwmUpdateThumbnailProperties(thumb.thumb, &thProps); } if(thumb.hwnd == g_programState.prevActiveWindow) { g_programState.activeSlot = (long)nthSlot; } SlotThing_t st; st.hwnd = thumb.hwnd; st.r.left = mi.extent.left - mis.r.left + (j % l1) * ws; st.r.top = mi.extent.top - mis.r.top + ((long)j / l1) * hs; st.r.right = st.r.left + ws; st.r.bottom = st.r.top + hs; st.moveUpDownAmount = l1; g_programState.slots.push_back(st); ++nthSlot; }); if(g_programState.activeSlot < 0 && g_programState.slots.size() > 0) { g_programState.activeSlot = 0; } } void OnPaint(HDC hdc) { HGDIOBJ original = NULL; original = SelectObject(hdc, GetStockObject(DC_PEN)); auto originalBrush = SelectObject(hdc, GetStockObject(DC_BRUSH)); SelectObject(hdc, GetStockObject(DC_BRUSH)); LONG fSize = 12l; fSize = MulDiv(fSize, GetDeviceCaps(hdc, LOGPIXELSY), 72); if(fSize != 12l) log(_T("font size scaled to %ld\n"), fSize); HFONT font = CreateFont( fSize, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Courier New")); HFONT originalFont = (HFONT)SelectObject(hdc, font); auto mis = GetMonitorGeometry(); SetDCBrushColor(hdc, RGB(0, 0, 0)); log(_T("rectangle is %ld %ld %ld %ld\n"), mis.r.left, mis.r.top, mis.r.right, mis.r.bottom); RECT winRect; GetWindowRect(g_programState.hWnd, &winRect); log(_T("window rect %ld %ld %ld %ld\n"), winRect.left, winRect.top, winRect.right, winRect.bottom); auto hrRectangle = Rectangle(hdc, 0, 0, winRect.right - winRect.left, winRect.bottom - winRect.top); log(_T("rectangle returned %d: errno %d\n"), hrRectangle, GetLastError()); SetDCBrushColor(hdc, RGB(255, 0, 0)); if(g_programState.activeSlot >= 0) { RECT r = (g_programState.slots[g_programState.activeSlot]).r; Rectangle(hdc, r.left, r.top, r.right, r.bottom); } SelectObject(hdc, GetStockObject(WHITE_BRUSH)); SelectObject(hdc, GetStockObject(BLACK_PEN)); int prevBkMode = SetBkMode(hdc, TRANSPARENT); PerformSlotting([&](MonitorInfo_t& mi, size_t j, long l1, long, long hs, long ws) { AppThumb_t& thumb = g_programState.thumbnails[mi.hMonitor][j]; HWND hwnd = thumb.hwnd; long x = ((long)j % l1) * ws + 3; long y = ((long)j / l1) * hs + 3; long x1 = x + ws - 6; long y1 = y + hs - 2 * hs / 3 - 6; RECT r; r.left = mi.extent.left - mis.r.left + x; r.right = mi.extent.left - mis.r.left + x1; r.top = mi.extent.top - mis.r.top + y; r.bottom = mi.extent.top - mis.r.top + y1; TCHAR str[257]; GetWindowText(hwnd, str, 256); std::wstring title(str); Rectangle(hdc, r.left, r.top, r.right, r.bottom); r.left += 3; r.right -= 6; r.top += 3; r.bottom -= 6; DrawText(hdc, str, -1, &r, DT_BOTTOM | DT_LEFT | DT_WORDBREAK); if(thumb.type == APP_THUMB_COMPAT) { ICONINFO iconInfo; auto hr = GetIconInfo(thumb.icon, &iconInfo); if(!hr) { log(_T("GetIconInfo failed; errno %d\n"), GetLastError()); DrawIcon(hdc, r.left + 3, r.bottom + 6, thumb.icon); } else { BITMAP bmp; ZeroMemory(&bmp, sizeof(BITMAP)); auto nBytes = GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bmp); if(nBytes != sizeof(BITMAP)) { log(_T("failed to retrieve bitmap from hicon for %p; errno %d\n"), (void*)thumb.hwnd, GetLastError()); } SIZE size = { bmp.bmWidth, bmp.bmHeight, }; if(iconInfo.hbmColor != NULL) { size.cy /= 2; } log(_T("bitmap %p size: %ld x %ld\n"), (void*)thumb.icon, size.cx, size.cy); POINT location = { (r.right + r.left) / 2 - size.cx / 2, r.top + 2 * hs / 3 - size.cy, }; DeleteBitmap(iconInfo.hbmColor); DeleteBitmap(iconInfo.hbmMask); DrawIcon(hdc, location.x, location.y, thumb.icon); } } }); DeleteObject(font); SetBkMode(hdc, prevBkMode); SelectObject(hdc, originalFont); SelectObject(hdc, originalBrush); SelectObject(hdc, original); }
#include "stdafx.h" #include "AltTabber.h" #include <WinUser.h> extern ProgramState_t g_programState; extern void log(LPTSTR fmt, ...); extern MonitorGeom_t GetMonitorGeometry(); static inline BOOL IsAltTabWindow(HWND hwnd) { if(!IsWindowVisible(hwnd)) return FALSE; TCHAR str[MAX_PATH + 1]; GetWindowText(hwnd, str, MAX_PATH); log(_T("window %ls has style %lX and exstyle %lX\n"), str, GetWindowLong(hwnd, GWL_STYLE), GetWindowLong(hwnd, GWL_EXSTYLE)); log(_T("parent: %p\n"), GetParent(hwnd)); HWND hwndTry, hwndWalk = NULL; hwndTry = GetAncestor(hwnd, GA_ROOTOWNER); while(hwndTry != hwndWalk) { hwndWalk = hwndTry; hwndTry = GetLastActivePopup(hwndWalk); if(IsWindowVisible(hwndTry)) break; } if(hwndWalk != hwnd) return FALSE; #if 0 TITLEBARINFO ti; ti.cbSize = sizeof(ti); GetTitleBarInfo(hwnd, &ti); if(ti.rgstate[0] & STATE_SYSTEM_INVISIBLE) return FALSE; #endif if(GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) return FALSE; if(GetWindowLong(hwnd, GWL_STYLE) & WS_CHILD) return FALSE; #if 0 LONG style = GetWindowLong(hwnd, GWL_EXSTYLE); if((style & (WS_VISIBLE | WS_EX_TOOLWINDOW | WS_POPUP | WS_CAPTION | WS_DLGFRAME | WS_OVERLAPPED | WS_TILED | WS_SYSMENU | WS_THICKFRAME )) == 0) { return FALSE; } #endif return TRUE; } static BOOL GetImagePathName(HWND hwnd, std::wstring& imagePathName) { BOOL hr = 0; TCHAR str2[MAX_PATH + 1]; DWORD procId; if(GetWindowThreadProcessId(hwnd, &procId) > 0) { auto hnd = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, procId); if(hnd != NULL) { UINT len; if((len = GetModuleFileNameEx(hnd, NULL, str2, MAX_PATH)) > 0) { imagePathName.assign(&str2[0], &str2[len]); hr = 1; } else { log(_T("GetModuleFileNameEx failed: %u errno %d\n"), len, GetLastError()); } CloseHandle(hnd); } } return hr; } static BOOL CALLBACK enumWindows(HWND hwnd, LPARAM lParam) { if(hwnd == g_programState.hWnd) return TRUE; if(!IsAltTabWindow(hwnd)) return TRUE; std::wstring filter = *((std::wstring const*)lParam); TCHAR str[257]; GetWindowText(hwnd, str, 256); std::wstring title(str); std::wstring imagePathName; if(GetImagePathName(hwnd, imagePathName)) { std::wstringstream wss; wss << imagePathName << std::wstring(L" // ") << title; title = wss.str(); } log(_T("the label is: %ls\n"), title.c_str()); std::transform(title.begin(), title.end(), title.begin(), ::tolower); std::transform(filter.begin(), filter.end(), filter.begin(), ::tolower); if(!filter.empty() && title.find(filter) == std::wstring::npos) { return TRUE; } HMONITOR hMonitor = NULL; if(g_programState.compatHacks & JAT_HACK_DEXPOT) { hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL); if(!hMonitor) return TRUE; } else { hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); } HTHUMBNAIL hThumb = NULL; auto hr = DwmRegisterThumbnail(g_programState.hWnd, hwnd, &hThumb); log(_T("register thumbnail for %p on monitor %p: %d\n"), (void*)hwnd, (void*)hMonitor, hr); if(hr == S_OK) { AppThumb_t at = { APP_THUMB_AERO, hwnd, }; at.thumb = hThumb; g_programState.thumbnails[hMonitor].push_back(at); } else { AppThumb_t at = { APP_THUMB_COMPAT, hwnd, }; HICON hIcon = NULL; hIcon = (HICON)GetClassLongPtr(hwnd, GCLP_HICON); if(!hIcon) { DWORD_PTR lresult; UINT sleepAmount = (g_programState.sleptThroughNWindows < 5) ? 50 : (g_programState.sleptThroughNWindows < 10) ? 25 : (g_programState.sleptThroughNWindows < 20) ? 10 : 5; auto hr = SendMessageTimeout(hwnd, WM_GETICON, ICON_BIG, 0, SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT, sleepAmount , &lresult); if(hr) { g_programState.sleptThroughNWindows++; hIcon = (HICON)lresult; } else { log(_T("Sending WM_GETICON to %ld failed; lresult %ld errno %d\n"), hwnd, lresult, GetLastError()); } } at.icon = hIcon; g_programState.thumbnails[hMonitor].push_back(at); } return TRUE; } void PurgeThumbnails() { for(auto i = g_programState.thumbnails.begin(); i != g_programState.thumbnails.end(); ++i) { auto thumbs = i->second; decltype(thumbs) rest(thumbs.size()); std::remove_copy_if( thumbs.begin(), thumbs.end(), std::inserter(rest, rest.end()), [](AppThumb_t const& thumb) -> bool { return thumb.type != APP_THUMB_AERO; }); std::for_each(rest.begin(), rest.end(), [](AppThumb_t const& thumb) { DwmUnregisterThumbnail(thumb.thumb); }); } g_programState.thumbnails.clear(); } void CreateThumbnails(std::wstring const& filter) { PurgeThumbnails(); auto hDesktop = OpenInputDesktop(0, FALSE, GENERIC_READ); if(!hDesktop) { log(_T("open desktop failed; errno = %d\n"), GetLastError()); return; } g_programState.sleptThroughNWindows = 0; auto hr = EnumDesktopWindows(hDesktop, enumWindows, (LPARAM)&filter); CloseDesktop(hDesktop); log(_T("enum desktop windows: %d\n"), hr); } template<typename F> void PerformSlotting(F&& functor) { auto mis = GetMonitorGeometry(); for(size_t i = 0; i < mis.monitors.size(); ++i) { auto& mi = mis.monitors[i]; auto& thumbs = g_programState.thumbnails[mi.hMonitor]; auto nWindows = thumbs.size(); unsigned int nTiles = 1; while(nTiles < nWindows) nTiles <<= 1; if(nTiles != nWindows) nTiles = max(1, nTiles >> 1); long lala = (long)(sqrt((double)nTiles) + 0.5); long l1 = lala; long l2 = lala; while(((unsigned)l1) * ((unsigned)l2) < nWindows) l1++; lala = l1 * l2; long ws = (mi.extent.right - mi.extent.left) / l1; long hs = (mi.extent.bottom - mi.extent.top) / l2; for(size_t j = 0; j < thumbs.size(); ++j) { functor(mi, j, l1, l2, hs, ws); } } } void SetThumbnails() { g_programState.activeSlot = -1; g_programState.slots.clear(); size_t nthSlot = 0; MonitorGeom_t mis = GetMonitorGeometry(); PerformSlotting([&](MonitorInfo_t& mi, size_t j, long l1, long, long hs, long ws) { AppThumb_t& thumb = g_programState.thumbnails[mi.hMonitor][j]; long x = ((long)j % l1) * ws + 3; long y = ((long)j / l1) * hs + hs / 3 + 3; long x1 = x + ws - 6; long y1 = y + hs - hs / 3 - 6; RECT r; r.left = mi.extent.left - mis.r.left + x; r.right = mi.extent.left - mis.r.left + x1; r.top = mi.extent.top - mis.r.top + y; r.bottom = mi.extent.top - mis.r.top + y1; if(thumb.type == APP_THUMB_AERO) { DWM_THUMBNAIL_PROPERTIES thProps; thProps.dwFlags = DWM_TNP_RECTDESTINATION | DWM_TNP_VISIBLE; SIZE ws; HRESULT haveThumbSize = DwmQueryThumbnailSourceSize(thumb.thumb, &ws); if(haveThumbSize == S_OK) { SIZE rs; rs.cx = r.right - r.left; rs.cy = r.bottom - r.top; RECT dRect; dRect.left = r.left; dRect.top = r.top; float rRap = (float)rs.cx / (float)rs.cy; float sRap = (float)ws.cx / (float)ws.cy; if(sRap > rRap) { dRect.right = r.right; LONG h = (LONG)(rs.cx / sRap); LONG delta = (rs.cy - h) / 2; dRect.top += de
rogramState.activeSlot >= 0) { RECT r = (g_programState.slots[g_programState.activeSlot]).r; Rectangle(hdc, r.left, r.top, r.right, r.bottom); } SelectObject(hdc, GetStockObject(WHITE_BRUSH)); SelectObject(hdc, GetStockObject(BLACK_PEN)); int prevBkMode = SetBkMode(hdc, TRANSPARENT); PerformSlotting([&](MonitorInfo_t& mi, size_t j, long l1, long, long hs, long ws) { AppThumb_t& thumb = g_programState.thumbnails[mi.hMonitor][j]; HWND hwnd = thumb.hwnd; long x = ((long)j % l1) * ws + 3; long y = ((long)j / l1) * hs + 3; long x1 = x + ws - 6; long y1 = y + hs - 2 * hs / 3 - 6; RECT r; r.left = mi.extent.left - mis.r.left + x; r.right = mi.extent.left - mis.r.left + x1; r.top = mi.extent.top - mis.r.top + y; r.bottom = mi.extent.top - mis.r.top + y1; TCHAR str[257]; GetWindowText(hwnd, str, 256); std::wstring title(str); Rectangle(hdc, r.left, r.top, r.right, r.bottom); r.left += 3; r.right -= 6; r.top += 3; r.bottom -= 6; DrawText(hdc, str, -1, &r, DT_BOTTOM | DT_LEFT | DT_WORDBREAK); if(thumb.type == APP_THUMB_COMPAT) { ICONINFO iconInfo; auto hr = GetIconInfo(thumb.icon, &iconInfo); if(!hr) { log(_T("GetIconInfo failed; errno %d\n"), GetLastError()); DrawIcon(hdc, r.left + 3, r.bottom + 6, thumb.icon); } else { BITMAP bmp; ZeroMemory(&bmp, sizeof(BITMAP)); auto nBytes = GetObject(iconInfo.hbmMask, sizeof(BITMAP), &bmp); if(nBytes != sizeof(BITMAP)) { log(_T("failed to retrieve bitmap from hicon for %p; errno %d\n"), (void*)thumb.hwnd, GetLastError()); } SIZE size = { bmp.bmWidth, bmp.bmHeight, }; if(iconInfo.hbmColor != NULL) { size.cy /= 2; } log(_T("bitmap %p size: %ld x %ld\n"), (void*)thumb.icon, size.cx, size.cy); POINT location = { (r.right + r.left) / 2 - size.cx / 2, r.top + 2 * hs / 3 - size.cy, }; DeleteBitmap(iconInfo.hbmColor); DeleteBitmap(iconInfo.hbmMask); DrawIcon(hdc, location.x, location.y, thumb.icon); } } }); DeleteObject(font); SetBkMode(hdc, prevBkMode); SelectObject(hdc, originalFont); SelectObject(hdc, originalBrush); SelectObject(hdc, original); }
lta; dRect.bottom = dRect.top + h; } else { dRect.bottom = r.bottom; LONG w = (LONG)(rs.cy * sRap); LONG delta = (rs.cx - w) / 2; dRect.left += delta; dRect.right = dRect.left + w; } thProps.rcDestination = dRect; } else { thProps.rcDestination = r; log(_T("DwmQueryThumbnailSourceSize failed %d: errno %d\n"), haveThumbSize, GetLastError()); } thProps.fVisible = TRUE; DwmUpdateThumbnailProperties(thumb.thumb, &thProps); } if(thumb.hwnd == g_programState.prevActiveWindow) { g_programState.activeSlot = (long)nthSlot; } SlotThing_t st; st.hwnd = thumb.hwnd; st.r.left = mi.extent.left - mis.r.left + (j % l1) * ws; st.r.top = mi.extent.top - mis.r.top + ((long)j / l1) * hs; st.r.right = st.r.left + ws; st.r.bottom = st.r.top + hs; st.moveUpDownAmount = l1; g_programState.slots.push_back(st); ++nthSlot; }); if(g_programState.activeSlot < 0 && g_programState.slots.size() > 0) { g_programState.activeSlot = 0; } } void OnPaint(HDC hdc) { HGDIOBJ original = NULL; original = SelectObject(hdc, GetStockObject(DC_PEN)); auto originalBrush = SelectObject(hdc, GetStockObject(DC_BRUSH)); SelectObject(hdc, GetStockObject(DC_BRUSH)); LONG fSize = 12l; fSize = MulDiv(fSize, GetDeviceCaps(hdc, LOGPIXELSY), 72); if(fSize != 12l) log(_T("font size scaled to %ld\n"), fSize); HFONT font = CreateFont( fSize, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, _T("Courier New")); HFONT originalFont = (HFONT)SelectObject(hdc, font); auto mis = GetMonitorGeometry(); SetDCBrushColor(hdc, RGB(0, 0, 0)); log(_T("rectangle is %ld %ld %ld %ld\n"), mis.r.left, mis.r.top, mis.r.right, mis.r.bottom); RECT winRect; GetWindowRect(g_programState.hWnd, &winRect); log(_T("window rect %ld %ld %ld %ld\n"), winRect.left, winRect.top, winRect.right, winRect.bottom); auto hrRectangle = Rectangle(hdc, 0, 0, winRect.right - winRect.left, winRect.bottom - winRect.top); log(_T("rectangle returned %d: errno %d\n"), hrRectangle, GetLastError()); SetDCBrushColor(hdc, RGB(255, 0, 0)); if(g_p
random
[ { "content": " HMONITOR hMonitor;\n", "file_path": "AltTabber/AltTabber.h", "rank": 0, "score": 29164.660110498233 }, { "content": " HWND hwnd;\n", "file_path": "AltTabber/AltTabber.h", "rank": 1, "score": 29068.905048625373 }, { "content": "#include \"stdafx.h\"\n\...
C++
Battleships/Source/System/FSystem.cpp
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
#include "FSystem.h" #include "..\Core\Sprite\FSprite.h" #include "..\Core\Video\FShaderBase.h" #include "..\Core\Time\FTime.h" #include "..\Core\Entity\IEntity.h" #include "..\Core\Renderable\IRenderable.h" #include "..\Core\Resource\IResource.h" #include "..\Core\Widget\IWidget.h" #include "..\Core\Entity\Actor\FActorController.h" #include "..\Core\Font\FFontLoader.h" #include "Engine\Widget\Text\FWidText.h" FWidText* s_FpsText; FWidText* s_FrameTime; FSystem::FSystem() { m_GraphicContext = nullptr; m_Player = nullptr; } FSystem::FSystem(const FSystem& other) { } FSystem::~FSystem() { } bool FSystem::Initialize() { bool bResult; m_GraphicContext = new FGraphic; if (!m_GraphicContext) { return false; } bResult = m_GraphicContext->Initialize(WVector2(1600, 900), false); if (!bResult) { return false; } bResult = IResource::InitializeResourceSystem("teste"); if (!bResult) { return false; } bResult = FFontLoader::InitializeFontSystem(); if (!bResult) { return false; } bResult = IWidget::InitializeWidgetSystem(m_GraphicContext); if (!bResult) { return false; } m_Player = new FPlayer; if (!m_Player) { return false; } bResult = m_Player->Initialize(m_GraphicContext); if (!bResult) { return false; } FTime::GetTimeElapsed(true); s_FpsText = IWidget::Create<FWidText>(); s_FpsText->SetLayout(IWidget::LayoutLocationHeight::Bottom, IWidget::LayoutLocationWidth::Left, IWidget::LayoutSize::Absolute, WVector2(0, 64)); s_FpsText->SetSize(WVector2(512, 64)); s_FpsText->SetFont(FHashedString("arial.ttf"), 32); s_FpsText->SetTextFormat(FWidText::TextFormat::Left); s_FrameTime = IWidget::Create<FWidText>(); s_FrameTime->SetLayout(IWidget::LayoutLocationHeight::Bottom, IWidget::LayoutLocationWidth::Left, IWidget::LayoutSize::Absolute, WVector2(0, 32)); s_FrameTime->SetSize(WVector2(512, 64)); s_FrameTime->SetFont(FHashedString("arial.ttf"), 32); s_FrameTime->SetTextFormat(FWidText::TextFormat::Left); return true; } void FSystem::StartEngine() { while (!glfwWindowShouldClose(m_GraphicContext->GetWindowReference())) { float elapsedTime = FTime::GetTimeElapsed(); Update(elapsedTime); Render(elapsedTime); glfwSwapBuffers(m_GraphicContext->GetWindowReference()); glfwPollEvents(); } } void FSystem::Shutdown() { } #include <Windows.h> void ClearConsole() { COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); SetConsoleCursorPosition(console, topLeft); } void FSystem::Update(float _timeElapsed) { static float logTime = 0; static int frameCount = 0; IEntity::UpdateEntities(_timeElapsed); IRenderable::UpdateRenderables(_timeElapsed); IResource::UpdateResourceSystem(_timeElapsed); IWidget::UpdateWidgets(_timeElapsed); m_Player->Update(_timeElapsed); logTime += _timeElapsed; frameCount++; if (logTime >= 1) { ClearConsole(); std::cout << "////////////////////////////////////////////////////////////////////////////////"; std::cout << "// //"; std::cout << "// | Console log | //"; std::cout << "// //"; std::cout << "////////////////////////////////////////////////////////////////////////////////" << std::endl; LEntityLog::PrintNumberEntities(); LRenderableLog::PrintNumberRenderables(); LResourceLog::PrintNumberResources(); std::cout << std::endl; std::cout << "FPS: " << frameCount << std::endl; std::cout << "Frame time: " << 1.0 / frameCount << std::endl; s_FpsText->SetText("FPS: 1414", 32); s_FrameTime->SetText("Frame time: 0.00068736", 32); unsigned int actorCounter; FActor** pickedActors = FActorController::PickAllActorsInRange<FNormalShip>(WVector2(0, 0), 300, actorCounter); std::cout << "Total picked actors: " << actorCounter << std::endl; std::cout << std::endl << "////////////////////////////////////////////////////////////////////////////////" << std::endl; logTime = 0; frameCount = 0; } } void FSystem::Render(float _timeElapsed) { IRenderable::RenderRenderables(); IWidget::RenderWidgets(); m_GraphicContext->BindDeferredFramebuffer(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); FShaderBase::RenderDeferredShaders(_timeElapsed, m_Player->Camera(), m_GraphicContext); m_GraphicContext->UnbindDeferredFramebuffer(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); FShaderBase::RenderShaders(_timeElapsed, m_Player->Camera(), m_GraphicContext); }
#include "FSystem.h" #include "..\Core\Sprite\FSprite.h" #include "..\Core\Video\FShaderBase.h" #include "..\Core\Time\FTime.h" #include "..\Core\Entity\IEntity.h" #include "..\Core\Renderable\IRenderable.h" #include "..\Core\Resource\IResource.h" #include "..\Core\Widget\IWidget.h" #include "..\Core\Entity\Actor\FActorController.h" #include "..\Core\Font\FFontLoader.h" #include "Engine\Widget\Text\FWidText.h" FWidText* s_FpsText; FWidText* s_FrameTime; FSystem::FSystem() { m_GraphicContext = nullptr; m_Player = nullptr; } FSystem::FSystem(const FSystem& other) { } FSystem::~FSystem() { } bool FSystem::Initialize() { bool bResult; m_GraphicContext = new FGraphic; if (!m_GraphicContext) { return false; } bResult = m_GraphicContext->Initialize(WVector2(1600, 900), false); if (!bResult) { return false; } bResult = IResource::InitializeResourceSystem("teste"); if (!bResult) { return false; } bResult = FFontLoader::InitializeFontSystem(); if (!bResult) { return false; } bResult = IWidget::InitializeWidgetSystem(m_GraphicContext); if (!bResult) { return false; } m_Player = new FPlayer; if (!m_Player) { return false; } bResult = m_Player->Initialize(m_GraphicContext); if (!bResult) { return false; } FTime::GetTimeElapsed(true); s_FpsText = IWidget::Create<FWidText>(); s_FpsText->SetLayout(IWidget::LayoutLocationHeight::Bottom, IWidget::LayoutLocationWidth::Left, IWidget::LayoutSize::Absolute, WVector2(0, 64)); s_FpsText->SetSize(WVector2(512, 64)); s_FpsText->SetFont(FHashedString("arial.ttf"), 32); s_FpsText->SetTextFormat(FWidText::TextFormat::Left); s_FrameTime = IWidget::Create<FWidText>(); s_FrameTime->SetLayout(IWidget::LayoutLocationHeight::Bottom, IWidget::LayoutLocationWidth::Left, IWidget::LayoutSize::Absolute, WVector2(0, 32)); s_FrameTime->SetSize(WVector2(512, 64)); s_FrameTime->SetFont(FHashedString("arial.ttf"), 32); s_FrameTime->SetTextFormat(FWidText::TextFormat::Left); return true; }
void FSystem::Shutdown() { } #include <Windows.h> void ClearConsole() { COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); SetConsoleCursorPosition(console, topLeft); } void FSystem::Update(float _timeElapsed) { static float logTime = 0; static int frameCount = 0; IEntity::UpdateEntities(_timeElapsed); IRenderable::UpdateRenderables(_timeElapsed); IResource::UpdateResourceSystem(_timeElapsed); IWidget::UpdateWidgets(_timeElapsed); m_Player->Update(_timeElapsed); logTime += _timeElapsed; frameCount++; if (logTime >= 1) { ClearConsole(); std::cout << "////////////////////////////////////////////////////////////////////////////////"; std::cout << "// //"; std::cout << "// | Console log | //"; std::cout << "// //"; std::cout << "////////////////////////////////////////////////////////////////////////////////" << std::endl; LEntityLog::PrintNumberEntities(); LRenderableLog::PrintNumberRenderables(); LResourceLog::PrintNumberResources(); std::cout << std::endl; std::cout << "FPS: " << frameCount << std::endl; std::cout << "Frame time: " << 1.0 / frameCount << std::endl; s_FpsText->SetText("FPS: 1414", 32); s_FrameTime->SetText("Frame time: 0.00068736", 32); unsigned int actorCounter; FActor** pickedActors = FActorController::PickAllActorsInRange<FNormalShip>(WVector2(0, 0), 300, actorCounter); std::cout << "Total picked actors: " << actorCounter << std::endl; std::cout << std::endl << "////////////////////////////////////////////////////////////////////////////////" << std::endl; logTime = 0; frameCount = 0; } } void FSystem::Render(float _timeElapsed) { IRenderable::RenderRenderables(); IWidget::RenderWidgets(); m_GraphicContext->BindDeferredFramebuffer(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); FShaderBase::RenderDeferredShaders(_timeElapsed, m_Player->Camera(), m_GraphicContext); m_GraphicContext->UnbindDeferredFramebuffer(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); FShaderBase::RenderShaders(_timeElapsed, m_Player->Camera(), m_GraphicContext); }
void FSystem::StartEngine() { while (!glfwWindowShouldClose(m_GraphicContext->GetWindowReference())) { float elapsedTime = FTime::GetTimeElapsed(); Update(elapsedTime); Render(elapsedTime); glfwSwapBuffers(m_GraphicContext->GetWindowReference()); glfwPollEvents(); } }
function_block-full_function
[ { "content": "function with a return - the return value is simply ignored.\n\n(See ethel example below)\n\n\n\nAll the correct virtual function behavior is preserved. (see ricky\n\nexample below).\n\n\n\nIf you somehow try to create something in violation\n\nof the type system you will get a compile-time or tem...
C++
windows/advcore/gdiplus/engine/text/otls/gpos.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
#include "pch.h" long DesignToPP ( USHORT cFUnits, USHORT cPPEm, long lFValue ) { long lHalf; long lNegHalf; long lCorrect; lHalf = (long)cFUnits >> 1; lNegHalf = -lHalf + 1; if (lFValue >= 0) { lCorrect = lHalf; } else { lCorrect = lNegHalf; } if (cFUnits==0) return lFValue; return (lFValue * (long)cPPEm + lCorrect) / (long)cFUnits; } void otlValueRecord::adjustPos ( const otlMetrics& metr, otlPlacement* pplcGlyphPalcement, long* pduDAdvance, otlSecurityData sec ) const { if (!isValid()) return; assert(!isNull()); assert(pplcGlyphPalcement != NULL); assert(pduDAdvance != NULL); const BYTE* pbTableBrowser = pbTable; if (grfValueFormat & otlValueXPlacement) { pplcGlyphPalcement->dx += DesignToPP(metr.cFUnits, metr.cPPEmX, SShort(pbTableBrowser)); pbTableBrowser += 2; } if (grfValueFormat & otlValueYPlacement) { pplcGlyphPalcement->dy += DesignToPP(metr.cFUnits, metr.cPPEmY, SShort(pbTableBrowser)); pbTableBrowser += 2; } if (grfValueFormat & otlValueXAdvance) { if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { *pduDAdvance += DesignToPP(metr.cFUnits, metr.cPPEmX, SShort(pbTableBrowser)); } pbTableBrowser += 2; } if (grfValueFormat & otlValueYAdvance) { if (metr.layout == otlRunTTB || metr.layout == otlRunBTT) { *pduDAdvance += DesignToPP(metr.cFUnits, metr.cPPEmY, SShort(pbTableBrowser)); } pbTableBrowser += 2; } if (grfValueFormat & otlValueXPlaDevice) { if (Offset(pbTableBrowser) != 0) { pplcGlyphPalcement->dx += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmX); } pbTableBrowser += 2; } if (grfValueFormat & otlValueYPlaDevice) { if (Offset(pbTableBrowser) != 0) { pplcGlyphPalcement->dx += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmY); } pbTableBrowser += 2; } if (grfValueFormat & otlValueXAdvDevice) { if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { if (Offset(pbTableBrowser) != 0) { *pduDAdvance += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmX); } } pbTableBrowser += 2; } if (grfValueFormat & otlValueYAdvDevice) { if (metr.layout == otlRunTTB || metr.layout == otlRunBTT) { if (Offset(pbTableBrowser) != 0) { *pduDAdvance += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmY); } } pbTableBrowser += 2; } assert((pbTableBrowser-pbTable)==size(grfValueFormat)); return; } bool otlAnchor::getAnchor ( USHORT cFUnits, USHORT cPPEmX, USHORT cPPEmY, otlPlacement* rgPointCoords, otlPlacement* pplcAnchorPoint, otlSecurityData sec ) const { if (!isValid()) return false; assert(!isNull()); assert(pplcAnchorPoint != NULL); switch(format()) { case(1): { otlSimpleAnchorTable simpleAnchor = otlSimpleAnchorTable(pbTable,sec); if (!simpleAnchor.isValid()) return false; pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, simpleAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, simpleAnchor.yCoordinate()); return true; } case(2): { otlContourAnchorTable contourAnchor = otlContourAnchorTable(pbTable,sec); if (!contourAnchor.isValid()) return false; if (rgPointCoords != NULL) { *pplcAnchorPoint = rgPointCoords[ contourAnchor.anchorPoint() ]; } else { pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, contourAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, contourAnchor.yCoordinate()); } return true; } case(3): { otlDeviceAnchorTable deviceAnchor = otlDeviceAnchorTable(pbTable,sec); if (!deviceAnchor.isValid()) return false; pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, deviceAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, deviceAnchor.yCoordinate()); otlDeviceTable deviceX = deviceAnchor.xDeviceTable(sec); otlDeviceTable deviceY = deviceAnchor.yDeviceTable(sec); if (!deviceX.isNull()) { pplcAnchorPoint->dx += deviceX.value(cPPEmX); } if (!deviceY.isNull()) { pplcAnchorPoint->dy += deviceY.value(cPPEmY); } return true; } default: return false; } } void AlignAnchors ( const otlList* pliGlyphInfo, otlList* pliPlacement, otlList* pliduDAdv, USHORT iglStatic, USHORT iglMobile, const otlAnchor& anchorStatic, const otlAnchor& anchorMobile, otlResourceMgr& resourceMgr, const otlMetrics& metr, USHORT grfOptions, otlSecurityData sec ) { assert(pliGlyphInfo->dataSize() == sizeof(otlGlyphInfo)); assert(pliPlacement->dataSize() == sizeof(otlPlacement)); assert(pliduDAdv->dataSize() == sizeof(long)); assert(pliGlyphInfo->length() == pliPlacement->length()); assert(pliPlacement->length() == pliduDAdv->length()); assert(iglStatic < pliGlyphInfo->length()); assert(iglMobile < pliGlyphInfo->length()); assert(!anchorStatic.isNull()); assert(!anchorMobile.isNull()); const otlGlyphInfo* pglinfStatic = readOtlGlyphInfo(pliGlyphInfo, iglStatic); const otlGlyphInfo* pglinfMobile = readOtlGlyphInfo(pliGlyphInfo, iglMobile); otlPlacement* pplcStatic = getOtlPlacement(pliPlacement, iglStatic); otlPlacement* pplcMobile = getOtlPlacement(pliPlacement, iglMobile); long* pduDAdvStatic = getOtlAdvance(pliduDAdv, iglStatic); long* pduDAdvMobile = getOtlAdvance(pliduDAdv, iglMobile); otlPlacement plcStaticAnchor; if (!anchorStatic.getAnchor(metr.cFUnits, metr.cPPEmX, metr.cPPEmY, resourceMgr.getPointCoords(pglinfStatic->glyph), &plcStaticAnchor,sec)) return; otlPlacement plcMobileAnchor; if (!anchorMobile.getAnchor(metr.cFUnits, metr.cPPEmX, metr.cPPEmY, resourceMgr.getPointCoords(pglinfMobile->glyph), &plcMobileAnchor,sec)) return; long duAdvanceInBetween = 0; for (USHORT igl = MIN(iglStatic, iglMobile) + 1; igl < MAX(iglStatic, iglMobile); ++igl) { duAdvanceInBetween += *getOtlAdvance(pliduDAdv, igl); } if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { pplcMobile->dy = pplcStatic->dy + plcStaticAnchor.dy - plcMobileAnchor.dy; if ((metr.layout == otlRunLTR) == (iglStatic < iglMobile)) { long dx = pplcStatic->dx - *pduDAdvStatic + plcStaticAnchor.dx - duAdvanceInBetween - plcMobileAnchor.dx; if (grfOptions & otlUseAdvances) { *pduDAdvStatic += dx; } else { pplcMobile->dx = dx; } } else { long dx = pplcStatic->dx + *pduDAdvMobile + plcStaticAnchor.dx + duAdvanceInBetween - plcMobileAnchor.dx; if (grfOptions & otlUseAdvances) { *pduDAdvMobile -= dx; } else { pplcMobile->dx = dx; } } } else { pplcMobile->dx = pplcStatic->dx + plcStaticAnchor.dx - plcMobileAnchor.dx; if ((metr.layout == otlRunTTB) == (iglStatic < iglMobile)) { long dy = pplcStatic->dy - *pduDAdvStatic + plcStaticAnchor.dy - duAdvanceInBetween - plcMobileAnchor.dy; if (grfOptions & otlUseAdvances) { *pduDAdvStatic += dy; } else { pplcMobile->dy = dy; } } else { long dy = pplcStatic->dy + *pduDAdvMobile + plcStaticAnchor.dy + duAdvanceInBetween - plcMobileAnchor.dy; if (grfOptions & otlUseAdvances) { *pduDAdvMobile -= dy; } else { pplcMobile->dy = dy; } } } }
#include "pch.h" long DesignToPP ( USHORT cFUnits, USHORT cPPEm, long lFValue ) { long lHalf; long lNegHalf; long lCorrect; lHalf = (long)cFUnits >> 1; lNegHalf = -lHalf + 1; if (lFValue >= 0) { lCorrect = lHalf; } else { lCorrect = lNegHalf; } if (cFUnits==0) return lFValue; return (lFValue * (long)cPPEm + lCorrect) / (long)cFUnits; } void otlValueRecord::adjustPos ( const otlMetrics& metr, otlPlacement* pplcGlyphPalcement, long* pduDAdvance, otlSecurityData sec ) const { if (!isValid()) return; assert(!isNull()); assert(pplcGlyphPalcement != NULL); assert(pduDAdvance != NULL); const BYTE* pbTableBrowser = pbTable; if (grfValueFormat & otlValueXPlacement) { pplcGlyphPalcement->dx += DesignToPP(metr.cFUnits, metr.cPPEmX, SShort(pbTableBrowser)); pbTableBrowser += 2; } if (grfValueFormat & otlValueYPlacement) { pplcGlyphPalcement->dy += DesignToPP(metr.cFUnits, metr.cPPEmY, SShort(pbTableBrowser)); pbTableBrowser += 2; } if (grfValueFormat & otlValueXAdvance) { if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { *pduDAdvance += DesignToPP(metr.cFUnits, metr.cPPEmX, SShort(pbTableBrowser)); } pbTableBrowser += 2; } if (grfValueFormat & otlValueYAdvance) { if (metr.layout == otlRunTTB || metr.layout == otlRunBTT) { *pduDAdvance += DesignToPP(metr.cFUnits, metr.cPPEmY, SShort(pbTableBrowser)); } pbTableBrowser += 2; } if (grfValueFormat & otlValueXPlaDevice) { if (Offset(pbTableBrowser) != 0) { pplcGlyphPalcement->dx += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmX); } pbTableBrowser += 2; } if (grfValueFormat & otlValueYPlaDevice) { if (Offset(pbTableBrowser) != 0) { pplcGlyphPalcement->dx += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmY); } pbTableBrowser += 2; } if (grfValueFormat & otlValueXAdvDevice) { if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { if (Offset(pbTableBrowser) != 0) { *pduDAdvance += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmX); } } pbTableBrowser += 2; } if (grfValueFormat & otlValueYAdvDevice) { if (metr.layout == otlRunTTB || metr.layout == otlRunBTT) { if (Offset(pbTableBrowser) != 0) { *pduDAdvance += otlDeviceTable(pbMainTable + Offset(pbTableBrowser),sec) .value(metr.cPPEmY); } } pbTableBrowser += 2; } assert((pbTableBrowser-pbTable)==size(grfValueFormat)); return; } bool otlAnchor::getAnchor ( USHORT cFUnits, USHORT cPPEmX, USHORT cPPEmY, otlPlacement* rgPointCoords, otlPlacement* pplcAnchorPoint, otlSecurityData sec ) const { if (!isValid()) return false; assert(!isNull()); assert(pplcAnchorPoint != NULL); switch(format()) { case(1): { otlSimpleAnchorTable simpleAnchor = otlSimpleAnchorTable(pbTable,sec); if (!simpleAnchor.isValid()) return false; pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, simpleAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, simpleAnchor.yCoordinate()); return true; } case(2): { otlContourAnchorTable contourAnchor = otlContourAnchorTable(pbTable,sec); if (!contourAnchor.isValid()) return false; if (rgPointCoords != NULL) { *pplcAnchorPoint = rgPointCoords[ contourAnchor.anchorPoint() ]; } else { pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, contourAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, contourAnchor.yCoordinate()); } return true; } case(3): { otlDeviceAnchorTable deviceAnchor = otlDeviceAnchorTable(pbTable,sec); if (!deviceAnchor.isValid()) return false; pplcAnchorPoint->dx = DesignToPP(cFUnits, cPPEmX, deviceAnchor.xCoordinate()); pplcAnchorPoint->dy = DesignToPP(cFUnits, cPPEmY, deviceAnchor.yCoordinate()); otlDeviceTable deviceX = deviceAnchor.xDeviceTable(sec); otlDeviceTable deviceY = deviceAnchor.yDeviceTable(sec); if (!deviceX.isNull()) { pplcAnchorPoint->dx += deviceX.value(cPPEmX); } if (!deviceY.isNull()) { pplcAnchorPoint->dy += deviceY.value(cPPEmY); } return true; } default: return false; } } void AlignAnchors ( const otlList* pliGlyphInfo, otlList* pliPlacement, otlList* pliduDAdv, USHORT iglStatic, USHORT iglMobile, const otlAnchor& anchorStatic, const otlAnchor& anchorMobile, otlResourceMgr& resourceMgr, const otlMetrics& metr, USHORT grfOptions, otlSecurityData sec ) { assert(pliGlyphInfo->dataSize() == sizeof(otlGlyphInfo)); assert(pliPlacement->dataSize() == sizeof(otlPlacement)); assert(pliduDAdv->dataSize() == sizeof(long)); assert(pliGlyphInfo->length() == pliPlacement->length()); assert(pliPlacement->length() == pliduDAdv->length()); assert(iglStatic < pliGlyphInfo->length()); assert(iglMobile < pliGlyphInfo->length()); assert(!anchorStatic.isNull()); assert(!anchorMobile.isNull()); const otlGlyphInfo* pglinfStatic = readOtlGlyphInfo(pliGlyphInfo, iglStatic); const otlGlyphInfo* pglinfMobile = readOtlGlyphInfo(pliGlyphInfo, iglMobile); otlPlacement* pplcStatic = getOtlPlacement(pliPlacement, iglStatic); otlPlacement* pplcMobile = getOtlPlacement(pliPlacement, iglMobile); long* pduDAdvStatic = getOtlAdvance(pliduDAdv, iglStatic); long* pduDAdvMobile = getOtlAdvance(pliduDAdv, iglMobile); otlPlacement plcStaticAnchor; if (!anchorStatic.getAnchor(metr.cFUnits, metr.cPPEmX, metr.cPPEmY, resourceMgr.getPointCoords(pglinfStatic->glyph), &plcStaticAnchor,sec)) return; otlPlacement plcMobileAnchor; if (!
) return; long duAdvanceInBetween = 0; for (USHORT igl = MIN(iglStatic, iglMobile) + 1; igl < MAX(iglStatic, iglMobile); ++igl) { duAdvanceInBetween += *getOtlAdvance(pliduDAdv, igl); } if (metr.layout == otlRunLTR || metr.layout == otlRunRTL) { pplcMobile->dy = pplcStatic->dy + plcStaticAnchor.dy - plcMobileAnchor.dy; if ((metr.layout == otlRunLTR) == (iglStatic < iglMobile)) { long dx = pplcStatic->dx - *pduDAdvStatic + plcStaticAnchor.dx - duAdvanceInBetween - plcMobileAnchor.dx; if (grfOptions & otlUseAdvances) { *pduDAdvStatic += dx; } else { pplcMobile->dx = dx; } } else { long dx = pplcStatic->dx + *pduDAdvMobile + plcStaticAnchor.dx + duAdvanceInBetween - plcMobileAnchor.dx; if (grfOptions & otlUseAdvances) { *pduDAdvMobile -= dx; } else { pplcMobile->dx = dx; } } } else { pplcMobile->dx = pplcStatic->dx + plcStaticAnchor.dx - plcMobileAnchor.dx; if ((metr.layout == otlRunTTB) == (iglStatic < iglMobile)) { long dy = pplcStatic->dy - *pduDAdvStatic + plcStaticAnchor.dy - duAdvanceInBetween - plcMobileAnchor.dy; if (grfOptions & otlUseAdvances) { *pduDAdvStatic += dy; } else { pplcMobile->dy = dy; } } else { long dy = pplcStatic->dy + *pduDAdvMobile + plcStaticAnchor.dy + duAdvanceInBetween - plcMobileAnchor.dy; if (grfOptions & otlUseAdvances) { *pduDAdvMobile -= dy; } else { pplcMobile->dy = dy; } } } }
anchorMobile.getAnchor(metr.cFUnits, metr.cPPEmX, metr.cPPEmY, resourceMgr.getPointCoords(pglinfMobile->glyph), &plcMobileAnchor,sec)
call_expression
[]
C++
components/variations/field_trial_config/field_trial_util.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
#include "components/variations/field_trial_config/field_trial_util.h" #include <stddef.h> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/optional.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "components/variations/client_filterable_state.h" #include "components/variations/field_trial_config/fieldtrial_testing_config.h" #include "components/variations/variations_seed_processor.h" #include "net/base/escape.h" #include "ui/base/device_form_factor.h" namespace variations { namespace { bool HasPlatform(const FieldTrialTestingExperiment& experiment, Study::Platform platform) { for (size_t i = 0; i < experiment.platforms_size; ++i) { if (experiment.platforms[i] == platform) return true; } return false; } bool HasDeviceLevelMismatch(const FieldTrialTestingExperiment& experiment) { if (!experiment.is_low_end_device.has_value()) { return false; } return experiment.is_low_end_device.value() != base::SysInfo::IsLowEndDevice(); } bool HasFormFactor(const FieldTrialTestingExperiment& experiment, Study::FormFactor current_form_factor) { for (size_t i = 0; i < experiment.form_factors_size; ++i) { if (experiment.form_factors[i] == current_form_factor) return true; } return experiment.form_factors_size == 0; } bool HasMinOSVersion(const FieldTrialTestingExperiment& experiment) { if (!experiment.min_os_version) return true; return base::Version(experiment.min_os_version) <= ClientFilterableState::GetOSVersion(); } void ApplyUIStringOverrides( const FieldTrialTestingExperiment& experiment, const VariationsSeedProcessor::UIStringOverrideCallback& callback) { for (size_t i = 0; i < experiment.override_ui_string_size; ++i) { callback.Run(experiment.override_ui_string[i].name_hash, base::UTF8ToUTF16(experiment.override_ui_string[i].value)); } } void AssociateParamsFromExperiment( const std::string& study_name, const FieldTrialTestingExperiment& experiment, const VariationsSeedProcessor::UIStringOverrideCallback& callback, base::FeatureList* feature_list) { if (experiment.params_size != 0) { base::FieldTrialParams params; for (size_t i = 0; i < experiment.params_size; ++i) { const FieldTrialTestingExperimentParams& param = experiment.params[i]; params[param.key] = param.value; } base::AssociateFieldTrialParams(study_name, experiment.name, params); } base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial(study_name, experiment.name); if (!trial) { DLOG(WARNING) << "Field trial config study skipped: " << study_name << "." << experiment.name << " (it is overridden from chrome://flags)"; return; } for (size_t i = 0; i < experiment.enable_features_size; ++i) { feature_list->RegisterFieldTrialOverride( experiment.enable_features[i], base::FeatureList::OVERRIDE_ENABLE_FEATURE, trial); } for (size_t i = 0; i < experiment.disable_features_size; ++i) { feature_list->RegisterFieldTrialOverride( experiment.disable_features[i], base::FeatureList::OVERRIDE_DISABLE_FEATURE, trial); } ApplyUIStringOverrides(experiment, callback); } void ChooseExperiment( const FieldTrialTestingStudy& study, const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { const auto& command_line = *base::CommandLine::ForCurrentProcess(); const FieldTrialTestingExperiment* chosen_experiment = nullptr; for (size_t i = 0; i < study.experiments_size; ++i) { const FieldTrialTestingExperiment* experiment = study.experiments + i; if (HasPlatform(*experiment, platform)) { if (!chosen_experiment && !HasDeviceLevelMismatch(*experiment) && HasFormFactor(*experiment, current_form_factor) && HasMinOSVersion(*experiment)) { chosen_experiment = experiment; } if (experiment->forcing_flag && command_line.HasSwitch(experiment->forcing_flag)) { chosen_experiment = experiment; break; } } } if (chosen_experiment) { AssociateParamsFromExperiment(study.name, *chosen_experiment, callback, feature_list); } } } std::string EscapeValue(const std::string& value) { std::string net_escaped_str = net::EscapeQueryParamValue(value, true ); std::string escaped_str; escaped_str.reserve(net_escaped_str.length()); for (const char ch : net_escaped_str) { if (ch == '.') escaped_str.append("%2E"); else if (ch == '*') escaped_str.append("%2A"); else escaped_str.push_back(ch); } return escaped_str; } bool AssociateParamsFromString(const std::string& varations_string) { return base::AssociateFieldTrialParamsFromString(varations_string, &base::UnescapeValue); } void AssociateParamsFromFieldTrialConfig( const FieldTrialTestingConfig& config, const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { for (size_t i = 0; i < config.studies_size; ++i) { const FieldTrialTestingStudy& study = config.studies[i]; if (study.experiments_size > 0) { ChooseExperiment(study, callback, platform, current_form_factor, feature_list); } else { DLOG(ERROR) << "Unexpected empty study: " << study.name; } } } void AssociateDefaultFieldTrialConfig( const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { AssociateParamsFromFieldTrialConfig(kFieldTrialConfig, callback, platform, current_form_factor, feature_list); } }
#include "components/variations/field_trial_config/field_trial_util.h" #include <stddef.h> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/optional.h" #include "base/strings/utf_string_conversions.h" #include "base/system/sys_info.h" #include "components/variations/client_filterable_state.h" #include "components/variations/field_trial_config/fieldtrial_testing_config.h" #include "components/variations/variations_seed_processor.h" #include "net/base/escape.h" #include "ui/base/device_form_factor.h" namespace variations { namespace { bool HasPlatform(const FieldTrialTestingExperiment& experiment, Study::Platform platform) { for (size_t i = 0; i < experiment.platforms_size; ++i) { if (experiment.platforms[i] == platform) return true; } return false; } bool HasDeviceLevelMismatch(const FieldTrialTestingExperiment& experiment) { if (!experiment.is_low_end_device.has_value()) { return false; } return experiment.is_low_end_device.value() != base::SysInfo::IsLowEndDevice(); } bool HasFormFactor(const FieldTrialTestingExperiment& experiment, Study::FormFactor current_form_factor) { for (size_t i = 0; i < experiment.form_factors_size; ++i) { if (experiment.form_factors[i] == current_form_factor) return true; } return experiment.form_factors_size == 0; } bool HasMinOSVersion(const FieldTrialTestingExperiment& experiment) { if (!experiment.min_os_version) return true; return base::Version(experiment.min_os_version) <= ClientFilterableState::GetOSVersion(); } void ApplyUIStringOverrides( const FieldTrialTestingExperiment& experiment, const VariationsSeedProcessor::UIStringOverrideCallback& callback) { for (size_t i = 0; i < experiment.override_ui_string_size; ++i) { callback.Run(experiment.override_ui_string[i].name_hash, base::UTF8ToUTF16(experiment.override_ui_string[i].value)); } } void AssociateParamsFromExperiment( const std::string& study_name, const FieldTrialTestingExperiment& experiment, const VariationsSeedProcessor::UIStringOverrideCallback& callback, base::FeatureList* feature_list) { if (experiment.params_size != 0) { base::FieldTrialParams params; for (size_t i = 0; i < experiment.params_size; ++i) { const FieldTrialTestingExperimentParams& param = experiment.params[i]; params[param.key] = param.value; } base::AssociateFieldTrialParams(study_name, experiment.name, params); } base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial(study_name, experiment.name); if (!trial) { DLOG(WARNING) << "Field trial config study skipped: " << study_name << "." << experiment.name << " (it is overridden from chrome://flags)"; return; } for (size_t i = 0; i < experiment.enable_features_size; ++i) { feature_list->RegisterFieldTrialOverride( experiment.enable_features[i], base::FeatureList::OVERRIDE_ENABLE_FEATURE, trial); } for (size_t i = 0; i < experiment.disable_features_size; ++i) { feature_list->RegisterFieldTrialOverride( experiment.disable_features[i], base::FeatureList::OVERRIDE_DISABLE_FEATURE, trial); } ApplyUIStringOverrides(experiment, callback); }
} std::string EscapeValue(const std::string& value) { std::string net_escaped_str = net::EscapeQueryParamValue(value, true ); std::string escaped_str; escaped_str.reserve(net_escaped_str.length()); for (const char ch : net_escaped_str) { if (ch == '.') escaped_str.append("%2E"); else if (ch == '*') escaped_str.append("%2A"); else escaped_str.push_back(ch); } return escaped_str; } bool AssociateParamsFromString(const std::string& varations_string) { return base::AssociateFieldTrialParamsFromString(varations_string, &base::UnescapeValue); } void AssociateParamsFromFieldTrialConfig( const FieldTrialTestingConfig& config, const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { for (size_t i = 0; i < config.studies_size; ++i) { const FieldTrialTestingStudy& study = config.studies[i]; if (study.experiments_size > 0) { ChooseExperiment(study, callback, platform, current_form_factor, feature_list); } else { DLOG(ERROR) << "Unexpected empty study: " << study.name; } } } void AssociateDefaultFieldTrialConfig( const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { AssociateParamsFromFieldTrialConfig(kFieldTrialConfig, callback, platform, current_form_factor, feature_list); } }
void ChooseExperiment( const FieldTrialTestingStudy& study, const VariationsSeedProcessor::UIStringOverrideCallback& callback, Study::Platform platform, Study::FormFactor current_form_factor, base::FeatureList* feature_list) { const auto& command_line = *base::CommandLine::ForCurrentProcess(); const FieldTrialTestingExperiment* chosen_experiment = nullptr; for (size_t i = 0; i < study.experiments_size; ++i) { const FieldTrialTestingExperiment* experiment = study.experiments + i; if (HasPlatform(*experiment, platform)) { if (!chosen_experiment && !HasDeviceLevelMismatch(*experiment) && HasFormFactor(*experiment, current_form_factor) && HasMinOSVersion(*experiment)) { chosen_experiment = experiment; } if (experiment->forcing_flag && command_line.HasSwitch(experiment->forcing_flag)) { chosen_experiment = experiment; break; } } } if (chosen_experiment) { AssociateParamsFromExperiment(study.name, *chosen_experiment, callback, feature_list); } }
function_block-full_function
[]
C++
test/range/test-transform.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
#define BOOST_TEST_MODULE test_range_transform #include "utility/test/boost_unit_test.hpp" #include "range/transform.hpp" #include <type_traits> #include <vector> #include <list> #include <tuple> #include <boost/mpl/assert.hpp> #include "range/std.hpp" #include "range/for_each_macro.hpp" #include "rime/check/check_equal.hpp" #include "weird_count.hpp" #include "unique_range.hpp" struct simple_count { int i; simple_count() : i (0) {} rime::false_type empty (direction::front) const { return rime::false_; } int chop_in_place (direction::front) { return i ++; } }; struct simple_count_tag {}; namespace range { template <> struct tag_of_qualified <simple_count> { typedef simple_count_tag type; }; } BOOST_AUTO_TEST_SUITE(test_range_transform) using range::transform; using range::front; using range::back; using range::default_direction; using range::empty; using range::size; using range::first; using range::drop; using range::chop; using range::chop_in_place; using range::second; using range::at; using range::is_homogeneous; struct callable_twice { template <class Argument> Argument operator() (Argument const & argument) const { return argument + argument; } }; callable_twice twice; struct callable_duplicate { template <class Argument> std::tuple <Argument, Argument> operator() (Argument const & argument) const { return std::make_tuple (argument, argument); } }; callable_duplicate duplicate; struct callable_point { template <class Argument> typename std::add_pointer <Argument>::type operator() (Argument && argument) const { return &argument; } }; callable_point point; BOOST_AUTO_TEST_CASE (example) { std::vector <int> v; v.push_back (5); v.push_back (7); { int count = 0; RANGE_FOR_EACH (i, v) count += i; BOOST_CHECK_EQUAL (count, 12); } { int count = 0; RANGE_FOR_EACH (i, transform (v, twice)) count += i; BOOST_CHECK_EQUAL (count, 24); } } BOOST_AUTO_TEST_CASE (test_range_transform) { { std::tuple <> t; auto v = transform (t, duplicate); auto direction = default_direction (v); BOOST_MPL_ASSERT (( std::is_same <decltype (direction), direction::front>)); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::true_); RIME_CHECK_EQUAL (size (v), rime::size_t <0u>()); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::chop (decltype (v))>)); } { std::tuple <int> t (7); auto v = transform (t, duplicate); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::false_); RIME_CHECK_EQUAL (size (v), rime::size_t <1u>()); BOOST_MPL_ASSERT ((range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT ((range::has <range::callable::drop (decltype (v))>)); auto f = range::first (v); BOOST_MPL_ASSERT ((std::is_same <decltype (f), std::tuple <int, int>>)); BOOST_CHECK_EQUAL (first (f), 7); BOOST_CHECK_EQUAL (second (f), 7); RIME_CHECK_EQUAL (empty (drop (v)), rime::true_); auto chopped = chop (v); static_assert (std::is_same <decltype (chopped.first()), std::tuple <int, int> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped.first()), 7); BOOST_CHECK_EQUAL (second (chopped.first()), 7); RIME_CHECK_EQUAL (empty (chopped.rest()), rime::true_); } { std::tuple <int, char, double> t (7, 'a', 9.25); { auto v = transform (t, duplicate); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::false_); RIME_CHECK_EQUAL (size (v), rime::size_t <3u>()); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); auto e1 = range::first (v); BOOST_MPL_ASSERT (( std::is_same <decltype (e1), std::tuple <int, int>>)); BOOST_CHECK_EQUAL (first (e1), 7); BOOST_CHECK_EQUAL (second (e1), 7); auto e2 = range::first (drop (v)); BOOST_MPL_ASSERT (( std::is_same <decltype (e2), std::tuple <char, char>>)); BOOST_CHECK_EQUAL (first (e2), 'a'); BOOST_CHECK_EQUAL (second (e2), 'a'); auto e3 = range::first (drop (v, rime::size_t <2>())); BOOST_MPL_ASSERT (( std::is_same <decltype (e3), std::tuple <double, double>>)); BOOST_CHECK_EQUAL (first (e3), 9.25); BOOST_CHECK_EQUAL (second (e3), 9.25); RIME_CHECK_EQUAL ( empty (drop (v, rime::size_t <3>())), rime::true_); auto chopped1 = chop (v); static_assert (std::is_same <decltype (chopped1.first()), std::tuple <int, int> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped1.first()), 7); BOOST_CHECK_EQUAL (second (chopped1.first()), 7); RIME_CHECK_EQUAL (empty (chopped1.rest()), rime::false_); auto chopped2 = chop (chopped1.rest()); static_assert (std::is_same <decltype (chopped2.first()), std::tuple <char, char> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped2.first()), 'a'); BOOST_CHECK_EQUAL (second (chopped2.first()), 'a'); RIME_CHECK_EQUAL (empty (chopped2.rest()), rime::false_); auto chopped3 = chop (chopped2.rest()); static_assert (std::is_same <decltype (chopped3.first()), std::tuple <double, double> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped3.first()), 9.25); BOOST_CHECK_EQUAL (second (chopped3.first()), 9.25); RIME_CHECK_EQUAL (empty (chopped3.rest()), rime::true_); } { auto v = transform (t, point); BOOST_CHECK_EQUAL (first (v), &first (t)); *at (v, rime::size_t <2>()) = 4.5; BOOST_CHECK_EQUAL (first (t, back), 4.5); } } } BOOST_AUTO_TEST_CASE (test_range_transform_homogeneous) { { std::vector <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); { auto v = transform (c, twice); BOOST_MPL_ASSERT ((is_homogeneous <decltype (v)>)); BOOST_MPL_ASSERT (( range::has <range::callable::empty (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::size (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v), int)>)); BOOST_CHECK (!empty (v)); BOOST_CHECK_EQUAL (size (v), 3u); BOOST_CHECK_EQUAL (first (v), 12.); BOOST_CHECK_EQUAL (at (v, 1), 21.); BOOST_CHECK_EQUAL (at (v, 2), -16.); BOOST_CHECK_EQUAL (first (v, back), -16.); BOOST_CHECK_EQUAL (at (v, 1, back), 21.); BOOST_CHECK_EQUAL (at (v, 2, back), 12.); auto chopped1 = chop (v); BOOST_CHECK_EQUAL (chopped1.first(), 12); auto chopped2 = chop (chopped1.rest()); BOOST_CHECK_EQUAL (chopped2.first(), 21); auto chopped3 = chop (chopped2.rest()); BOOST_CHECK_EQUAL (chopped3.first(), -16); BOOST_CHECK (empty (chopped3.rest())); v = drop (v); BOOST_CHECK_EQUAL (first (v), 21.); v = drop (v); BOOST_CHECK_EQUAL (first (v), -16.); v = drop (v); BOOST_CHECK (empty (v)); } { auto v = transform (c, point); BOOST_CHECK_EQUAL (first (v), &first (c)); BOOST_CHECK_EQUAL (at (v, 1), &at (c, 1)); *first (v) = 27.5; BOOST_CHECK_EQUAL (first (c), 27.5); } } { std::list <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); { auto v = transform (c, twice); BOOST_MPL_ASSERT ((is_homogeneous <decltype (v)>)); BOOST_MPL_ASSERT (( range::has <range::callable::empty (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::size (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::drop (decltype (v), int)>)); BOOST_CHECK (!empty (v)); BOOST_CHECK_EQUAL (first (v), 12.); BOOST_CHECK_EQUAL (first (drop (v)), 21.); BOOST_CHECK_EQUAL (first (drop (drop (v))), -16.); BOOST_CHECK_EQUAL (first (v, back), -16.); BOOST_CHECK_EQUAL (first (drop (v, back), back), 21.); BOOST_CHECK_EQUAL (first (drop (drop (v, back), back), back), 12.); } } { std::vector <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); auto v = transform (transform (c, twice), duplicate); BOOST_CHECK_EQUAL (size (v), 3u); BOOST_CHECK (first (v) == std::make_tuple (12., 12.)); BOOST_CHECK (first (drop (v)) == std::make_tuple (21., 21.)); BOOST_CHECK (first (v, back) == std::make_tuple (-16., -16.)); auto chopped1 = chop (v); BOOST_CHECK (chopped1.first() == std::make_tuple (12., 12.)); auto chopped2 = chop (chopped1.rest()); BOOST_CHECK (chopped2.first() == std::make_tuple (21., 21.)); auto chopped3 = chop (chopped2.rest()); BOOST_CHECK (chopped3.first() == std::make_tuple (-16., -16.)); BOOST_CHECK (empty (chopped3.rest())); } } BOOST_AUTO_TEST_CASE (test_range_transform_weird_count) { { weird_count w; weird_direction direction (7); auto v = transform (w, twice, weird_direction (7)); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::default_direction (decltype (v))>::type, forgotten_to_define_direction>)); BOOST_CHECK (!empty (v, direction)); BOOST_MPL_ASSERT_NOT ((range::has < range::callable::size (weird_direction, decltype (v))>)); BOOST_CHECK_EQUAL (first (v, direction), 0); BOOST_CHECK_EQUAL (first (drop (v, direction), direction), 2); BOOST_CHECK_EQUAL (first (drop (v, 5, direction), direction), 10); } { weird_count w; weird_direction direction (7); auto view = range::view (w, direction); auto transformed = transform (view, duplicate, direction); BOOST_CHECK (!empty (transformed, direction)); BOOST_CHECK (first (transformed, direction) == std::make_tuple (0, 0)); BOOST_CHECK (first (drop (transformed, 2, direction), direction) == std::make_tuple (2, 2)); } } template <class Type> struct show_type; BOOST_AUTO_TEST_CASE (unique_underlying) { std::vector <int> v; v.push_back (6); v.push_back (20); v.push_back (-5); { auto t = transform (unique_view (v), twice); BOOST_CHECK_EQUAL (first (t), 12); t = drop (std::move (t)); BOOST_CHECK_EQUAL (first (t), 40); t = drop (std::move (t)); BOOST_CHECK_EQUAL (first (t), -10); t = drop (std::move (t)); BOOST_CHECK (empty (t)); } { auto t = transform (one_time_view (v), twice); static_assert (range::has <range::callable::chop (decltype (t)) >::value, ""); static_assert (!range::has <range::callable::chop (decltype (t) const &) >::value, ""); auto chopped1 = chop (std::move (t)); BOOST_CHECK_EQUAL (chopped1.first(), 12); auto chopped2 = chop (chopped1.move_rest()); BOOST_CHECK_EQUAL (chopped2.first(), 40); BOOST_CHECK_EQUAL (first (chopped2.move_rest()), -10); } } BOOST_AUTO_TEST_CASE (only_chop_in_place) { { simple_count c; int zero = chop_in_place (c); BOOST_CHECK_EQUAL (zero, 0); int one = chop_in_place (c); BOOST_CHECK_EQUAL (one, 1); } { auto even = transform (simple_count(), twice); int zero = chop_in_place (even); BOOST_CHECK_EQUAL (zero, 0); int two = chop_in_place (even); BOOST_CHECK_EQUAL (two, 2); int four = chop_in_place (even); BOOST_CHECK_EQUAL (four, 4); int six = chop_in_place (even); BOOST_CHECK_EQUAL (six, 6); } } class round_up { int const & step; public: round_up (int const & step) : step (step) {} int operator() (int n) const { return ((n + (step - 1)) / step) * step; } }; BOOST_AUTO_TEST_CASE (function_with_reference) { int step = 5; round_up round (step); BOOST_CHECK_EQUAL (round (0), 0); BOOST_CHECK_EQUAL (round (1), 5); BOOST_CHECK_EQUAL (round (4), 5); BOOST_CHECK_EQUAL (round (5), 5); BOOST_CHECK_EQUAL (round (23), 25); step = 3; BOOST_CHECK_EQUAL (round (7), 9); std::vector <int> v; v.push_back (1); v.push_back (5); v.push_back (10); v.push_back (27); { auto rounded = transform (v, round); BOOST_CHECK_EQUAL (first (rounded), 3); rounded = drop (rounded); BOOST_CHECK_EQUAL (first (rounded), 6); rounded = drop (rounded); step = 7; int fourteen = chop_in_place (rounded); BOOST_CHECK_EQUAL (fourteen, 14); auto chopped = chop (rounded); BOOST_CHECK_EQUAL (chopped.first(), 28); BOOST_CHECK (empty (chopped.rest())); } { auto rounded = transform (one_time_view (v), round); step = 4; auto four = chop_in_place (rounded); BOOST_CHECK_EQUAL (four, 4); auto chopped = chop (std::move (rounded)); BOOST_CHECK_EQUAL (chopped.first(), 8); } } BOOST_AUTO_TEST_SUITE_END()
#define BOOST_TEST_MODULE test_range_transform #include "utility/test/boost_unit_test.hpp" #include "range/transform.hpp" #include <type_traits> #include <vector> #include <list> #include <tuple> #include <boost/mpl/assert.hpp> #include "range/std.hpp" #include "range/for_each_macro.hpp" #include "rime/check/check_equal.hpp" #include "weird_count.hpp" #include "unique_range.hpp" struct simple_count { int i; simple_count() : i (0) {} rime::false_type empty (direction::front) const { return rime::false_; } int chop_in_place (direction::front) { return i ++; } }; struct simple_count_tag {}; namespace range { template <> struct tag_of_qualified <simple_count> { typedef simple_count_tag type; }; } BOOST_AUTO_TEST_SUITE(test_range_transform) using range::transform; using range::front; using range::back; using range::default_direction; using range::empty; using range::size; using range::first; using range::drop; using range::chop; using range::chop_in_place; using range::second; using range::at; using range::is_homogeneous; struct callable_twice { template <class Argument> Argument operator() (Argument const & argument) const { return argument + argument; } }; callable_twice twice; struct callable_duplicate { template <class Argument> std::tuple <Argument, Argument> operator() (Argument const & argument) const { return std::make_tuple (argument, argument); } }; callable_duplicate duplicate; struct callable_point { template <class Argument> typename std::add_pointer <Argument>::type operator() (Argument && argument) const { return &argument; } }; callable_point point; BOOST_AUTO_TEST_CASE (example) { std::vector <int> v; v.push_back (5); v.push_back (7); { int count = 0; RANGE_FOR_EACH (i, v) count += i; BOOST_CHECK_EQUAL (count, 12); } { int count = 0; RANGE_FOR_EACH (i, transform (v, twice)) count += i; BOOST_CHECK_EQUAL (count, 24); } } BOOST_AUTO_TEST_CASE (test_range_transform) { { std::tuple <> t; auto v = transform (t, duplicate); auto direction = default_direction (v); BOOST_MPL_ASSERT (( std::is_same <decltype (direction), direction::front>)); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::true_); RIME_CHECK_EQUAL (size (v), rime::size_t <0u>()); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::chop (decltype (v))>)); } { std::tuple <int> t (7); auto v = transform (t, duplicate); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::false_); RIME_CHECK_EQUAL (size (v), rime::size_t <1u>()); BOOST_MPL_ASSERT ((range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT ((range::has <range::callable::drop (decltype (v))>)); auto f = range::first (v); BOOST_MPL_ASSERT ((std::is_same <decltype (f), std::tuple <int, int>>)); BOOST_CHECK_EQUAL (first (f), 7); BOOST_CHECK_EQUAL (second (f), 7); RIME_CHECK_EQUAL (empty (drop (v)), rime::true_); auto chopped = chop (v); static_assert (std::is_same <decltype (chopped.first()),
L (empty (chopped3.rest()), rime::true_); } { auto v = transform (t, point); BOOST_CHECK_EQUAL (first (v), &first (t)); *at (v, rime::size_t <2>()) = 4.5; BOOST_CHECK_EQUAL (first (t, back), 4.5); } } } BOOST_AUTO_TEST_CASE (test_range_transform_homogeneous) { { std::vector <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); { auto v = transform (c, twice); BOOST_MPL_ASSERT ((is_homogeneous <decltype (v)>)); BOOST_MPL_ASSERT (( range::has <range::callable::empty (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::size (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v), int)>)); BOOST_CHECK (!empty (v)); BOOST_CHECK_EQUAL (size (v), 3u); BOOST_CHECK_EQUAL (first (v), 12.); BOOST_CHECK_EQUAL (at (v, 1), 21.); BOOST_CHECK_EQUAL (at (v, 2), -16.); BOOST_CHECK_EQUAL (first (v, back), -16.); BOOST_CHECK_EQUAL (at (v, 1, back), 21.); BOOST_CHECK_EQUAL (at (v, 2, back), 12.); auto chopped1 = chop (v); BOOST_CHECK_EQUAL (chopped1.first(), 12); auto chopped2 = chop (chopped1.rest()); BOOST_CHECK_EQUAL (chopped2.first(), 21); auto chopped3 = chop (chopped2.rest()); BOOST_CHECK_EQUAL (chopped3.first(), -16); BOOST_CHECK (empty (chopped3.rest())); v = drop (v); BOOST_CHECK_EQUAL (first (v), 21.); v = drop (v); BOOST_CHECK_EQUAL (first (v), -16.); v = drop (v); BOOST_CHECK (empty (v)); } { auto v = transform (c, point); BOOST_CHECK_EQUAL (first (v), &first (c)); BOOST_CHECK_EQUAL (at (v, 1), &at (c, 1)); *first (v) = 27.5; BOOST_CHECK_EQUAL (first (c), 27.5); } } { std::list <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); { auto v = transform (c, twice); BOOST_MPL_ASSERT ((is_homogeneous <decltype (v)>)); BOOST_MPL_ASSERT (( range::has <range::callable::empty (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::size (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); BOOST_MPL_ASSERT_NOT (( range::has <range::callable::drop (decltype (v), int)>)); BOOST_CHECK (!empty (v)); BOOST_CHECK_EQUAL (first (v), 12.); BOOST_CHECK_EQUAL (first (drop (v)), 21.); BOOST_CHECK_EQUAL (first (drop (drop (v))), -16.); BOOST_CHECK_EQUAL (first (v, back), -16.); BOOST_CHECK_EQUAL (first (drop (v, back), back), 21.); BOOST_CHECK_EQUAL (first (drop (drop (v, back), back), back), 12.); } } { std::vector <double> c; c.push_back (6); c.push_back (10.5); c.push_back (-8); auto v = transform (transform (c, twice), duplicate); BOOST_CHECK_EQUAL (size (v), 3u); BOOST_CHECK (first (v) == std::make_tuple (12., 12.)); BOOST_CHECK (first (drop (v)) == std::make_tuple (21., 21.)); BOOST_CHECK (first (v, back) == std::make_tuple (-16., -16.)); auto chopped1 = chop (v); BOOST_CHECK (chopped1.first() == std::make_tuple (12., 12.)); auto chopped2 = chop (chopped1.rest()); BOOST_CHECK (chopped2.first() == std::make_tuple (21., 21.)); auto chopped3 = chop (chopped2.rest()); BOOST_CHECK (chopped3.first() == std::make_tuple (-16., -16.)); BOOST_CHECK (empty (chopped3.rest())); } } BOOST_AUTO_TEST_CASE (test_range_transform_weird_count) { { weird_count w; weird_direction direction (7); auto v = transform (w, twice, weird_direction (7)); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::default_direction (decltype (v))>::type, forgotten_to_define_direction>)); BOOST_CHECK (!empty (v, direction)); BOOST_MPL_ASSERT_NOT ((range::has < range::callable::size (weird_direction, decltype (v))>)); BOOST_CHECK_EQUAL (first (v, direction), 0); BOOST_CHECK_EQUAL (first (drop (v, direction), direction), 2); BOOST_CHECK_EQUAL (first (drop (v, 5, direction), direction), 10); } { weird_count w; weird_direction direction (7); auto view = range::view (w, direction); auto transformed = transform (view, duplicate, direction); BOOST_CHECK (!empty (transformed, direction)); BOOST_CHECK (first (transformed, direction) == std::make_tuple (0, 0)); BOOST_CHECK (first (drop (transformed, 2, direction), direction) == std::make_tuple (2, 2)); } } template <class Type> struct show_type; BOOST_AUTO_TEST_CASE (unique_underlying) { std::vector <int> v; v.push_back (6); v.push_back (20); v.push_back (-5); { auto t = transform (unique_view (v), twice); BOOST_CHECK_EQUAL (first (t), 12); t = drop (std::move (t)); BOOST_CHECK_EQUAL (first (t), 40); t = drop (std::move (t)); BOOST_CHECK_EQUAL (first (t), -10); t = drop (std::move (t)); BOOST_CHECK (empty (t)); } { auto t = transform (one_time_view (v), twice); static_assert (range::has <range::callable::chop (decltype (t)) >::value, ""); static_assert (!range::has <range::callable::chop (decltype (t) const &) >::value, ""); auto chopped1 = chop (std::move (t)); BOOST_CHECK_EQUAL (chopped1.first(), 12); auto chopped2 = chop (chopped1.move_rest()); BOOST_CHECK_EQUAL (chopped2.first(), 40); BOOST_CHECK_EQUAL (first (chopped2.move_rest()), -10); } } BOOST_AUTO_TEST_CASE (only_chop_in_place) { { simple_count c; int zero = chop_in_place (c); BOOST_CHECK_EQUAL (zero, 0); int one = chop_in_place (c); BOOST_CHECK_EQUAL (one, 1); } { auto even = transform (simple_count(), twice); int zero = chop_in_place (even); BOOST_CHECK_EQUAL (zero, 0); int two = chop_in_place (even); BOOST_CHECK_EQUAL (two, 2); int four = chop_in_place (even); BOOST_CHECK_EQUAL (four, 4); int six = chop_in_place (even); BOOST_CHECK_EQUAL (six, 6); } } class round_up { int const & step; public: round_up (int const & step) : step (step) {} int operator() (int n) const { return ((n + (step - 1)) / step) * step; } }; BOOST_AUTO_TEST_CASE (function_with_reference) { int step = 5; round_up round (step); BOOST_CHECK_EQUAL (round (0), 0); BOOST_CHECK_EQUAL (round (1), 5); BOOST_CHECK_EQUAL (round (4), 5); BOOST_CHECK_EQUAL (round (5), 5); BOOST_CHECK_EQUAL (round (23), 25); step = 3; BOOST_CHECK_EQUAL (round (7), 9); std::vector <int> v; v.push_back (1); v.push_back (5); v.push_back (10); v.push_back (27); { auto rounded = transform (v, round); BOOST_CHECK_EQUAL (first (rounded), 3); rounded = drop (rounded); BOOST_CHECK_EQUAL (first (rounded), 6); rounded = drop (rounded); step = 7; int fourteen = chop_in_place (rounded); BOOST_CHECK_EQUAL (fourteen, 14); auto chopped = chop (rounded); BOOST_CHECK_EQUAL (chopped.first(), 28); BOOST_CHECK (empty (chopped.rest())); } { auto rounded = transform (one_time_view (v), round); step = 4; auto four = chop_in_place (rounded); BOOST_CHECK_EQUAL (four, 4); auto chopped = chop (std::move (rounded)); BOOST_CHECK_EQUAL (chopped.first(), 8); } } BOOST_AUTO_TEST_SUITE_END()
std::tuple <int, int> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped.first()), 7); BOOST_CHECK_EQUAL (second (chopped.first()), 7); RIME_CHECK_EQUAL (empty (chopped.rest()), rime::true_); } { std::tuple <int, char, double> t (7, 'a', 9.25); { auto v = transform (t, duplicate); BOOST_MPL_ASSERT_NOT ((is_homogeneous <decltype (v)>)); RIME_CHECK_EQUAL (empty (v), rime::false_); RIME_CHECK_EQUAL (size (v), rime::size_t <3u>()); BOOST_MPL_ASSERT (( range::has <range::callable::first (decltype (v))>)); BOOST_MPL_ASSERT (( range::has <range::callable::drop (decltype (v))>)); auto e1 = range::first (v); BOOST_MPL_ASSERT (( std::is_same <decltype (e1), std::tuple <int, int>>)); BOOST_CHECK_EQUAL (first (e1), 7); BOOST_CHECK_EQUAL (second (e1), 7); auto e2 = range::first (drop (v)); BOOST_MPL_ASSERT (( std::is_same <decltype (e2), std::tuple <char, char>>)); BOOST_CHECK_EQUAL (first (e2), 'a'); BOOST_CHECK_EQUAL (second (e2), 'a'); auto e3 = range::first (drop (v, rime::size_t <2>())); BOOST_MPL_ASSERT (( std::is_same <decltype (e3), std::tuple <double, double>>)); BOOST_CHECK_EQUAL (first (e3), 9.25); BOOST_CHECK_EQUAL (second (e3), 9.25); RIME_CHECK_EQUAL ( empty (drop (v, rime::size_t <3>())), rime::true_); auto chopped1 = chop (v); static_assert (std::is_same <decltype (chopped1.first()), std::tuple <int, int> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped1.first()), 7); BOOST_CHECK_EQUAL (second (chopped1.first()), 7); RIME_CHECK_EQUAL (empty (chopped1.rest()), rime::false_); auto chopped2 = chop (chopped1.rest()); static_assert (std::is_same <decltype (chopped2.first()), std::tuple <char, char> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped2.first()), 'a'); BOOST_CHECK_EQUAL (second (chopped2.first()), 'a'); RIME_CHECK_EQUAL (empty (chopped2.rest()), rime::false_); auto chopped3 = chop (chopped2.rest()); static_assert (std::is_same <decltype (chopped3.first()), std::tuple <double, double> const &>::value, ""); BOOST_CHECK_EQUAL (first (chopped3.first()), 9.25); BOOST_CHECK_EQUAL (second (chopped3.first()), 9.25); RIME_CHECK_EQUA
random
[ { "content": "struct negate { int operator() (int i) const { return -i; } };\n\n\n\nBOOST_AUTO_TEST_SUITE(range_less_lexicographical_homogeneous)\n\n\n\n#define CHECK_range_less_lexicographical(r1, r2, value) \\\n\n RIME_CHECK_EQUAL (range::less_lexicographical (r1, r2), value); \\\n\n RIME_CHECK_EQUAL (r...
C++
src/apply-supervised-mvdr.cc
unanan/setk
e1248c6d40806c3fff251f3971a585c6ec09d949
#include "include/stft.h" #include "include/beamformer.h" using namespace kaldi; void ParseInputRspecifier(const std::string &input_rspecifier, std::vector<std::string> *rspecifiers) { size_t found = input_rspecifier.find_first_of(":", 0); if (found == std::string::npos) KALDI_ERR << "Wrong input-rspecifier format: " << input_rspecifier; const std::string &decorator = input_rspecifier.substr(0, found); std::vector<std::string> tmp; SplitStringToVector(input_rspecifier.substr(found + 1), ",", false, &tmp); for (std::string &s : tmp) rspecifiers->push_back(decorator + ":" + s); } int main(int argc, char *argv[]) { try { const char *usage = "Do minimum variance distortionless response (MVDR) beamformer, " "depending on TF mask\n" "\n" "Usage: apply-supervised-mvdr [options...] <mask-rspecifier> " "<input-rspecifier> <target-wav-wspecifier>\n" "\n" "e.g.:\n" " apply-supervised-mvdr --config=mask.conf scp:mask.scp " "scp:CH1.scp,CH2.scp,CH3.scp scp:dst.scp\n"; ParseOptions po(usage); ShortTimeFTOptions stft_options; bool track_volumn = true, normalize_input = true; std::string window = "hamming"; BaseFloat frame_shift = 256, frame_length = 1024; int32 update_periods = 0, minimum_update_periods = 20; po.Register("frame-shift", &frame_shift, "Frame shift in number of samples"); po.Register("frame-length", &frame_length, "Frame length in number of samples"); po.Register( "window", &window, "Type of window(\"hamming\"|\"hanning\"|\"blackman\"|\"rectangular\")"); po.Register("track-volumn", &track_volumn, "If true, using average volumn of input channels as target's"); po.Register( "normalize-input", &normalize_input, "Scale samples into float in range [-1, 1], like MATLAB or librosa"); po.Register( "update-periods", &update_periods, "Number of frames to use for estimating psd of noise or target, " "if zero, do beamforming offline"); po.Read(argc, argv); int32 num_args = po.NumArgs(); if (num_args != 3) { po.PrintUsage(); exit(1); } KALDI_ASSERT(update_periods >= 0); if (update_periods < minimum_update_periods && update_periods > 0) { KALDI_WARN << "Value of update_periods may be too small, ignore it"; } std::string mask_rspecifier = po.GetArg(1), input_rspecifier = po.GetArg(2), enhan_wspecifier = po.GetArg(3); std::vector<std::string> rspecifiers; ParseInputRspecifier(input_rspecifier, &rspecifiers); int32 num_channels = rspecifiers.size(); std::vector<RandomAccessTableReader<WaveHolder> > wav_reader(num_channels); for (int32 c = 0; c < num_channels; c++) { std::string &cur_ch = rspecifiers[c]; if (ClassifyRspecifier(cur_ch, NULL, NULL) == kNoRspecifier) KALDI_ERR << cur_ch << " is not a rspecifier"; KALDI_ASSERT(wav_reader[c].Open(cur_ch)); } stft_options.window = window; stft_options.normalize_input = normalize_input; stft_options.frame_shift = frame_shift; stft_options.frame_length = frame_length; ShortTimeFTComputer stft_computer(stft_options); SequentialBaseFloatMatrixReader mask_reader(mask_rspecifier); TableWriter<WaveHolder> wav_writer(enhan_wspecifier); int32 num_done = 0, num_miss = 0, num_utts = 0; for (; !mask_reader.Done(); mask_reader.Next()) { std::string utt_key = mask_reader.Key(); const Matrix<BaseFloat> &target_mask = mask_reader.Value(); std::vector<Matrix<BaseFloat> > mstft(num_channels); std::vector<BaseFloat> mfreq(num_channels); BaseFloat range = 0.0; num_utts++; int32 cur_ch = 0; for (int32 c = 0; c < num_channels; c++) { if (wav_reader[c].HasKey(utt_key)) { const WaveData &wave_data = wav_reader[c].Value(utt_key); const Matrix<BaseFloat> &wave_samp = wave_data.Data(); if (track_volumn) range += wave_samp.LargestAbsElem(); mfreq[cur_ch] = wave_data.SampFreq(); stft_computer.Compute(wave_samp, &mstft[cur_ch], NULL, NULL); cur_ch++; } } KALDI_VLOG(2) << "Processing " << cur_ch << " channels for " << utt_key; if (cur_ch <= 1) { num_miss++; continue; } int32 num_frames = mstft[0].NumRows(), num_bins = mstft[0].NumCols() / 2 + 1; BaseFloat target_freq = mfreq[0]; bool problem = false; for (int32 c = 1; c < cur_ch; c++) { if (mstft[c].NumCols() != (num_bins - 1) * 2 || mstft[c].NumRows() != num_frames) { KALDI_WARN << "There is obvious length difference between" << "multiple channels, please check, skip for " << utt_key; problem = true; break; } if (target_freq != mfreq[c]) { KALDI_WARN << "Sample frequency may be difference between" << "multiple channels, please check, skip for " << utt_key; problem = true; break; } } if (problem) { num_miss++; continue; } if (target_mask.NumRows() != num_frames || target_mask.NumCols() != num_bins) { KALDI_WARN << "Utterance " << utt_key << ": The shape of target mask is different from stft" << " (" << target_mask.NumRows() << " x " << target_mask.NumCols() << ") vs" << " (" << num_frames << " x " << num_bins << ")"; num_miss++; continue; } CMatrix<BaseFloat> stft_reshape(num_frames, num_bins * cur_ch), src_stft; for (int32 c = 0; c < cur_ch; c++) { stft_reshape.ColRange(c * num_bins, num_bins).CopyFromRealfft(mstft[c]); } CMatrix<BaseFloat> noise_psd, target_psd, steer_vector, beam_weights, enh_stft; int32 num_segments = (num_frames - minimum_update_periods) / update_periods + 1; if (update_periods >= minimum_update_periods && num_segments > 1) { KALDI_VLOG(1) << "Do mvdr beamforming, update power spectrum matrix " "estimation per " << update_periods << " frames"; int32 duration = 0, start_from = 0; CMatrix<BaseFloat> enh_stft_segment; enh_stft.Resize(num_frames, num_bins); for (int32 i = 0; i < num_segments; i++) { start_from = i * update_periods; duration = (i == num_segments - 1 ? num_frames - start_from : update_periods); TrimStft(num_bins, cur_ch, stft_reshape.RowRange(start_from, duration), &src_stft); EstimatePsd(src_stft, target_mask.RowRange(start_from, duration), &target_psd, &noise_psd); EstimateSteerVector(target_psd, &steer_vector); ComputeMvdrBeamWeights(noise_psd, steer_vector, &beam_weights); Beamform(src_stft, beam_weights, &enh_stft_segment); enh_stft.RowRange(start_from, duration).CopyFromMat(enh_stft_segment); } } else { KALDI_VLOG(1) << "Do mvdr beamforming offline"; TrimStft(num_bins, cur_ch, stft_reshape, &src_stft); EstimatePsd(src_stft, target_mask, &target_psd, &noise_psd); EstimateSteerVector(target_psd, &steer_vector); ComputeMvdrBeamWeights(noise_psd, steer_vector, &beam_weights); Beamform(src_stft, beam_weights, &enh_stft); } Matrix<BaseFloat> rstft, enhan_speech; CastIntoRealfft(enh_stft, &rstft); stft_computer.InverseShortTimeFT(rstft, &enhan_speech, range / cur_ch - 1); WaveData target_data(target_freq, enhan_speech); wav_writer.Write(utt_key, target_data); num_done++; if (num_done % 100 == 0) KALDI_LOG << "Processed " << num_utts << " utterances."; KALDI_VLOG(2) << "Do mvdr beamforming for utterance-id " << utt_key << " done."; } KALDI_LOG << "Done " << num_done << " utterances out of " << num_utts << ", " << num_miss << " missing cause of some problems."; return num_done == 0 ? 1 : 0; } catch (const std::exception &e) { std::cerr << e.what(); return -1; } return 0; }
#include "include/stft.h" #include "include/beamformer.h" using namespace kaldi;
int main(int argc, char *argv[]) { try { const char *usage = "Do minimum variance distortionless response (MVDR) beamformer, " "depending on TF mask\n" "\n" "Usage: apply-supervised-mvdr [options...] <mask-rspecifier> " "<input-rspecifier> <target-wav-wspecifier>\n" "\n" "e.g.:\n" " apply-supervised-mvdr --config=mask.conf scp:mask.scp " "scp:CH1.scp,CH2.scp,CH3.scp scp:dst.scp\n"; ParseOptions po(usage); ShortTimeFTOptions stft_options; bool track_volumn = true, normalize_input = true; std::string window = "hamming"; BaseFloat frame_shift = 256, frame_length = 1024; int32 update_periods = 0, minimum_update_periods = 20; po.Register("frame-shift", &frame_shift, "Frame shift in number of samples"); po.Register("frame-length", &frame_length, "Frame length in number of samples"); po.Register( "window", &window, "Type of window(\"hamming\"|\"hanning\"|\"blackman\"|\"rectangular\")"); po.Register("track-volumn", &track_volumn, "If true, using average volumn of input channels as target's"); po.Register( "normalize-input", &normalize_input, "Scale samples into float in range [-1, 1], like MATLAB or librosa"); po.Register( "update-periods", &update_periods, "Number of frames to use for estimating psd of noise or target, " "if zero, do beamforming offline"); po.Read(argc, argv); int32 num_args = po.NumArgs(); if (num_args != 3) { po.PrintUsage(); exit(1); } KALDI_ASSERT(update_periods >= 0); if (update_periods < minimum_update_periods && update_periods > 0) { KALDI_WARN << "Value of update_periods may be too small, ignore it"; } std::string mask_rspecifier = po.GetArg(1), input_rspecifier = po.GetArg(2), enhan_wspecifier = po.GetArg(3); std::vector<std::string> rspecifiers; ParseInputRspecifier(input_rspecifier, &rspecifiers); int32 num_channels = rspecifiers.size(); std::vector<RandomAccessTableReader<WaveHolder> > wav_reader(num_channels); for (int32 c = 0; c < num_channels; c++) { std::string &cur_ch = rspecifiers[c]; if (ClassifyRspecifier(cur_ch, NULL, NULL) == kNoRspecifier) KALDI_ERR << cur_ch << " is not a rspecifier"; KALDI_ASSERT(wav_reader[c].Open(cur_ch)); } stft_options.window = window; stft_options.normalize_input = normalize_input; stft_options.frame_shift = frame_shift; stft_options.frame_length = frame_length; ShortTimeFTComputer stft_computer(stft_options); SequentialBaseFloatMatrixReader mask_reader(mask_rspecifier); TableWriter<WaveHolder> wav_writer(enhan_wspecifier); int32 num_done = 0, num_miss = 0, num_utts = 0; for (; !mask_reader.Done(); mask_reader.Next()) { std::string utt_key = mask_reader.Key(); const Matrix<BaseFloat> &target_mask = mask_reader.Value(); std::vector<Matrix<BaseFloat> > mstft(num_channels); std::vector<BaseFloat> mfreq(num_channels); BaseFloat range = 0.0; num_utts++; int32 cur_ch = 0; for (int32 c = 0; c < num_channels; c++) { if (wav_reader[c].HasKey(utt_key)) { const WaveData &wave_data = wav_reader[c].Value(utt_key); const Matrix<BaseFloat> &wave_samp = wave_data.Data(); if (track_volumn) range += wave_samp.LargestAbsElem(); mfreq[cur_ch] = wave_data.SampFreq(); stft_computer.Compute(wave_samp, &mstft[cur_ch], NULL, NULL); cur_ch++; } } KALDI_VLOG(2) << "Processing " << cur_ch << " channels for " << utt_key; if (cur_ch <= 1) { num_miss++; continue; } int32 num_frames = mstft[0].NumRows(), num_bins = mstft[0].NumCols() / 2 + 1; BaseFloat target_freq = mfreq[0]; bool problem = false; for (int32 c = 1; c < cur_ch; c++) { if (mstft[c].NumCols() != (num_bins - 1) * 2 || mstft[c].NumRows() != num_frames) { KALDI_WARN << "There is obvious length difference between" << "multiple channels, please check, skip for " << utt_key; problem = true; break; } if (target_freq != mfreq[c]) { KALDI_WARN << "Sample frequency may be difference between" << "multiple channels, please check, skip for " << utt_key; problem = true; break; } } if (problem) { num_miss++; continue; } if (target_mask.NumRows() != num_frames || target_mask.NumCols() != num_bins) { KALDI_WARN << "Utterance " << utt_key << ": The shape of target mask is different from stft" << " (" << target_mask.NumRows() << " x " << target_mask.NumCols() << ") vs" << " (" << num_frames << " x " << num_bins << ")"; num_miss++; continue; } CMatrix<BaseFloat> stft_reshape(num_frames, num_bins * cur_ch), src_stft; for (int32 c = 0; c < cur_ch; c++) { stft_reshape.ColRange(c * num_bins, num_bins).CopyFromRealfft(mstft[c]); } CMatrix<BaseFloat> noise_psd, target_psd, steer_vector, beam_weights, enh_stft; int32 num_segments = (num_frames - minimum_update_periods) / update_periods + 1; if (update_periods >= minimum_update_periods && num_segments > 1) { KALDI_VLOG(1) << "Do mvdr beamforming, update power spectrum matrix " "estimation per " << update_periods << " frames"; int32 duration = 0, start_from = 0; CMatrix<BaseFloat> enh_stft_segment; enh_stft.Resize(num_frames, num_bins); for (int32 i = 0; i < num_segments; i++) { start_from = i * update_periods; duration = (i == num_segments - 1 ? num_frames - start_from : update_periods); TrimStft(num_bins, cur_ch, stft_reshape.RowRange(start_from, duration), &src_stft); EstimatePsd(src_stft, target_mask.RowRange(start_from, duration), &target_psd, &noise_psd); EstimateSteerVector(target_psd, &steer_vector); ComputeMvdrBeamWeights(noise_psd, steer_vector, &beam_weights); Beamform(src_stft, beam_weights, &enh_stft_segment); enh_stft.RowRange(start_from, duration).CopyFromMat(enh_stft_segment); } } else { KALDI_VLOG(1) << "Do mvdr beamforming offline"; TrimStft(num_bins, cur_ch, stft_reshape, &src_stft); EstimatePsd(src_stft, target_mask, &target_psd, &noise_psd); EstimateSteerVector(target_psd, &steer_vector); ComputeMvdrBeamWeights(noise_psd, steer_vector, &beam_weights); Beamform(src_stft, beam_weights, &enh_stft); } Matrix<BaseFloat> rstft, enhan_speech; CastIntoRealfft(enh_stft, &rstft); stft_computer.InverseShortTimeFT(rstft, &enhan_speech, range / cur_ch - 1); WaveData target_data(target_freq, enhan_speech); wav_writer.Write(utt_key, target_data); num_done++; if (num_done % 100 == 0) KALDI_LOG << "Processed " << num_utts << " utterances."; KALDI_VLOG(2) << "Do mvdr beamforming for utterance-id " << utt_key << " done."; } KALDI_LOG << "Done " << num_done << " utterances out of " << num_utts << ", " << num_miss << " missing cause of some problems."; return num_done == 0 ? 1 : 0; } catch (const std::exception &e) { std::cerr << e.what(); return -1; } return 0; }
void ParseInputRspecifier(const std::string &input_rspecifier, std::vector<std::string> *rspecifiers) { size_t found = input_rspecifier.find_first_of(":", 0); if (found == std::string::npos) KALDI_ERR << "Wrong input-rspecifier format: " << input_rspecifier; const std::string &decorator = input_rspecifier.substr(0, found); std::vector<std::string> tmp; SplitStringToVector(input_rspecifier.substr(found + 1), ",", false, &tmp); for (std::string &s : tmp) rspecifiers->push_back(decorator + ":" + s); }
function_block-full_function
[ { "content": "namespace kaldi {\n\n\n\n// Cast CMatrix into Matrix, in Realfft format, to reconstruct speech\n\n// The Realfft format is space efficient, so I refused to use CMatrix in stft.h\n\nvoid CastIntoRealfft(const CMatrixBase<BaseFloat> &cstft,\n\n Matrix<BaseFloat> *rstft);\n\n\n\n/...
C++
security/keystore-engine/rsa_meth.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
#include <UniquePtr.h> #define LOG_TAG "OpenSSL-keystore-rsa" #include <cutils/log.h> #include <binder/IServiceManager.h> #include <keystore/IKeystoreService.h> #include <openssl/rsa.h> #include <openssl/engine.h> #include "methods.h" using namespace android; int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { ALOGV("keystore_rsa_priv_enc(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); int num = RSA_size(rsa); UniquePtr<uint8_t> padded(new uint8_t[num]); if (padded.get() == NULL) { ALOGE("could not allocate padded signature"); return 0; } switch (padding) { case RSA_PKCS1_PADDING: if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) { return 0; } break; case RSA_X931_PADDING: if (!RSA_padding_add_X931(padded.get(), num, from, flen)) { return 0; } break; case RSA_NO_PADDING: if (!RSA_padding_add_none(padded.get(), num, from, flen)) { return 0; } break; default: ALOGE("Unknown padding type: %d", padding); return 0; } uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); if (key_id == NULL) { ALOGE("key had no key_id!"); return 0; } sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("android.security.keystore")); sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); if (service == NULL) { ALOGE("could not contact keystore"); return 0; } uint8_t* reply = NULL; size_t replyLen; int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(), num, &reply, &replyLen); if (ret < 0) { ALOGW("There was an error during signing: could not connect"); free(reply); return 0; } else if (ret != 0) { ALOGW("Error during signing from keystore: %d", ret); free(reply); return 0; } else if (replyLen <= 0) { ALOGW("No valid signature returned"); return 0; } memcpy(to, reply, replyLen); free(reply); ALOGV("rsa=%p keystore_rsa_priv_enc => returning %p len %llu", rsa, to, (unsigned long long) replyLen); return static_cast<int>(replyLen); } int keystore_rsa_priv_dec(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { ALOGV("keystore_rsa_priv_dec(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); if (key_id == NULL) { ALOGE("key had no key_id!"); return 0; } sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("android.security.keystore")); sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); if (service == NULL) { ALOGE("could not contact keystore"); return 0; } int num = RSA_size(rsa); uint8_t* reply = NULL; size_t replyLen; int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), from, flen, &reply, &replyLen); if (ret < 0) { ALOGW("There was an error during rsa_mod_exp: could not connect"); return 0; } else if (ret != 0) { ALOGW("Error during sign from keystore: %d", ret); return 0; } else if (replyLen <= 0) { ALOGW("No valid signature returned"); return 0; } uint8_t* alignedReply; if (*reply == 0x00) { alignedReply = reply + 1; replyLen--; } else { alignedReply = reply; } int outSize; switch (padding) { case RSA_PKCS1_PADDING: outSize = RSA_padding_check_PKCS1_type_2(to, num, alignedReply, replyLen, num); break; case RSA_X931_PADDING: outSize = RSA_padding_check_X931(to, num, alignedReply, replyLen, num); break; case RSA_NO_PADDING: outSize = RSA_padding_check_none(to, num, alignedReply, replyLen, num); break; default: ALOGE("Unknown padding type: %d", padding); outSize = -1; break; } free(reply); ALOGV("rsa=%p keystore_rsa_priv_dec => returning %p len %d", rsa, to, outSize); return outSize; } static RSA_METHOD keystore_rsa_meth = { kKeystoreEngineId, NULL, NULL, keystore_rsa_priv_enc, keystore_rsa_priv_dec, NULL, NULL, NULL, NULL, RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, NULL, NULL, NULL, NULL, }; static int register_rsa_methods() { const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay(); keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc; keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec; keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp; keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp; return 1; } int rsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) { Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { ALOGW("Could not set ex_data for loaded RSA key"); return 0; } RSA_set_method(rsa.get(), &keystore_rsa_meth); RSA_blinding_off(rsa.get()); ENGINE_init(e); rsa->engine = e; rsa->flags |= RSA_FLAG_EXT_PKEY; return 1; } int rsa_register(ENGINE* e) { if (!ENGINE_set_RSA(e, &keystore_rsa_meth) || !register_rsa_methods()) { ALOGE("Could not set up keystore RSA methods"); return 0; } return 1; }
#include <UniquePtr.h> #define LOG_TAG "OpenSSL-keystore-rsa" #include <cutils/log.h> #include <binder/IServiceManager.h> #include <keystore/IKeystoreService.h> #include <openssl/rsa.h> #include <openssl/engine.h> #include "methods.h" using namespace android; int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { ALOGV("keystore_rsa_priv_enc(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); int num = RSA_size(rsa); UniquePtr<uint8_t> padded(new uint8_t[num]); if (padded.get() == NULL) { ALOGE("could not allocate padded signature"); return 0; } switch (padding) { case RSA_PKCS1_PADDING: if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) { return 0; } break; case RSA_X931_PADDING: if (!RSA_padding_add_X931(padded.get(), num, from, flen)) { return 0; } break; case RSA_NO_PADDING: if (!RSA_padding_add_none(padded.get(), num, from, flen)) { return 0; } break; default: ALOGE("Unknown padding type: %d", padding); return 0; } uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); if (key_id == NULL) { ALOGE("key had no key_id!"); return 0; } sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("android.security.keystore")); sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); if (service == NULL) { ALOGE("could not contact keystore"); return 0; } uint8_t* reply = NULL; size_t replyLen; int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(), num, &reply, &replyLen); if (ret < 0) { ALOGW("There was an error during signing: could not connect"); free(reply); return 0; } else if (ret != 0) { ALOGW("Error during signing from keystore: %d", ret); free(reply); return 0; } else if (replyLen <= 0) { ALOGW("No valid signature returned"); return 0; } memcpy(to, reply, replyLen); free(reply); ALOGV("rsa=%p keystore_rsa_priv_enc => returning %p len %llu", rsa, to, (unsigned long long) replyLen); return static_cast<int>(replyLen); } int keystore_rsa_priv_dec(int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { ALOGV("keystore_rsa_priv_dec(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding); uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle)); if (key_id == NULL) { ALOGE("key had no key_id!"); return 0; } sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("android.security.keystore")); sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder); if (service == NULL) { ALOGE("could not contact keystore"); return 0; } int num = RSA_size(rsa); uint8_t* reply = NULL; size_t replyLen; int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), from, flen, &reply, &replyLen); if (ret < 0) { ALOGW("There was an error during rsa_mod_exp: could not connect"); return 0; } else if (ret != 0) { ALOGW("Error during sign from keystore: %d", ret); return 0; } else if (replyLen <= 0) { ALOGW("No valid signature returned"); return 0; } uint8_t* alignedReply; if (*reply == 0x00) { alignedReply = reply + 1; replyLen--; } else { alignedReply = reply; } int outSize; switch (padding) { case RSA_PKCS1_PADDING: outSize = RSA_padding_check_PKCS1_type_2(to, num, alignedReply, replyLen, num); break; case RSA_X931_PADDING: outSize = RSA_padding_check_X931(to, num, alignedReply, replyLen, num); break; case RSA_NO_PADDING: outSize = RSA_padding_check_none(to, num, alignedReply, replyLen, num); break; default: ALOGE("Unknown padding type: %d", padding); outSize = -1; break; } free(reply); ALOGV("rsa=%p keystore_rsa_priv_dec => returning %p len %d", rsa, to, outSize); return outSize; }
static int register_rsa_methods() { const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay(); keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc; keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec; keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp; keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp; return 1; } int rsa_pkey_setup(ENGINE *e, EVP_PKEY *pkey, const char *key_id) { Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey)); if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) { ALOGW("Could not set ex_data for loaded RSA key"); return 0; } RSA_set_method(rsa.get(), &keystore_rsa_meth); RSA_blinding_off(rsa.get()); ENGINE_init(e); rsa->engine = e; rsa->flags |= RSA_FLAG_EXT_PKEY; return 1; } int rsa_register(ENGINE* e) { if (!ENGINE_set_RSA(e, &keystore_rsa_meth) || !register_rsa_methods()) { ALOGE("Could not set up keystore RSA methods"); return 0; } return 1; }
static RSA_METHOD keystore_rsa_meth = { kKeystoreEngineId, NULL, NULL, keystore_rsa_priv_enc, keystore_rsa_priv_dec, NULL, NULL, NULL, NULL, RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, NULL, NULL, NULL, NULL, };
assignment_statement
[ { "content": "class TypeNamespace : public ::android::aidl::LanguageTypeNamespace<Type> {\n\n public:\n\n TypeNamespace() = default;\n\n virtual ~TypeNamespace() = default;\n\n\n\n void Init() override;\n\n bool AddParcelableType(const AidlParcelable& p,\n\n const std::string& filena...
C++
cpp/knapsack/tools.hpp
CostaBru/knapsack
cdd95de759c20b0cdeef4064fbbed10df1ab76d0
#ifndef KB_KNAPSACK_PARTITION_SOLUTION_TOOLS_HPP #define KB_KNAPSACK_PARTITION_SOLUTION_TOOLS_HPP #include "fast_map.h" #include "defines.h" #include "w_point_dim1.hpp" #include "w_point_dimN.hpp" #include "w_point.hpp" #include "source_link.hpp" #include <vector> #include <tuple> #include <cmath> #include <deque> #include <numeric> #include <ranges> namespace kb_knapsack { namespace tools { template<typename T, typename W> void sortReverse(std::vector<T> &dimensions, std::vector<W> &values, std::vector<int> &indexes) { std::vector<size_t> p(dimensions.size(), 0); std::iota(p.begin(), p.end(), 0); std::sort(p.begin(), p.end(), [&](size_t i, size_t j) { return dimensions[i] > dimensions[j]; }); applySort3<T, W, int>(dimensions, values, indexes, p.size(), p); } template<class K, class T1, class T2> void applySort3(std::vector<K> &keys, std::vector<T1> &data1, std::vector<T2> &data2, size_t size, std::vector<size_t> p) { std::vector<size_t> rp(size); std::vector<bool> sorted(size, false); size_t i = 0; for (i = 0; i < size; ++i) { rp[p[i]] = i; } i = 0; K savedKey; T1 savedData1; T2 savedData2; while (i < size) { size_t pos = i; if (!sorted[pos]) { savedKey = keys[p[pos]]; savedData1 = data1[p[pos]]; savedData2 = data2[p[pos]]; } while (!sorted[pos]) { K heldKey = keys[pos]; T1 heldData1 = data1[pos]; T2 heldData2 = data2[pos]; size_t heldPos = rp[pos]; keys[pos] = savedKey; data1[pos] = savedData1; data2[pos] = savedData2; savedKey = heldKey; savedData1 = heldData1; savedData2 = heldData2; sorted[pos] = true; pos = heldPos; } ++i; } } template<typename T, typename W, int N, template<typename DIM_TYPE, typename VALUE_TYPE, int DIM_LEN> class DIM> KNAPSACK_RESULT backTraceItems( W & emptyValue, TD & emptyDimension, W_POINT & maxProfitPoint, SOURCE_LINK_LIST & sourcePoints, std::vector<TD > & dimensions, std::vector<W> & values, std::vector<int> & ids) { W zeroProfit = emptyValue; std::vector<TD > optItems; std::vector<W> optValues; std::vector<int> optIndexes; auto optSize = emptyDimension; if (maxProfitPoint.profit > 0) { W maxProfit = maxProfitPoint.profit; source_link pointLink = sourcePoints[maxProfitPoint.id]; while (true) { optItems .emplace_back(dimensions[pointLink.itemId]); optValues .emplace_back(values[pointLink.itemId]); optIndexes.emplace_back(ids[pointLink.itemId]); optSize += dimensions[pointLink.itemId]; if (!pointLink.hasParent()) { break; } pointLink = sourcePoints[pointLink.parentId]; } return std::make_tuple(maxProfit, optSize, optItems, optValues, optIndexes); } return std::make_tuple(zeroProfit, emptyDimension, optItems, optValues, optIndexes); } } } #endif
#ifndef KB_KNAPSACK_PARTITION_SOLUTION_TOOLS_HPP #define KB_KNAPSACK_PARTITION_SOLUTION_TOOLS_HPP #include "fast_map.h" #include "defines.h" #include "w_point_dim1.hpp" #include "w_point_dimN.hpp" #include "w_point.hpp" #include "source_link.hpp" #include <vector> #include <tuple> #include <cmath> #include <deque> #include <numeric> #include <ranges> namespace kb_knapsack { namespace tools { template<typename T, typename W> void sortReverse(std::vector<T> &dimensions, std::vector<W> &values, std::vector<int> &indexes) { std::vector<size_t> p(dimensions.size(), 0); std::iota(p.begin(), p.end(), 0); std::sort(p.begin(), p.end(), [&](size_t i, size_t j) { return dimensions[i] > dimensions[j]; }); applySort3<T, W, int>(dimensions, values, indexes, p.size(), p); } template<class K, class T1, class T2> void applySort3(std::vector<K> &keys, std::vector<T1> &data1, std::vector<T2> &data2, size_t size, std::vector<size_t> p) { std::vector<size_t> rp(size); std::vector<bool> sorted(size, false); size_t i = 0; for (i = 0; i < size; ++i) { rp[p[i]] = i; } i = 0; K savedKey; T1 savedData1; T2 savedData2; while (i < size) { size_t pos = i;
while (!sorted[pos]) { K heldKey = keys[pos]; T1 heldData1 = data1[pos]; T2 heldData2 = data2[pos]; size_t heldPos = rp[pos]; keys[pos] = savedKey; data1[pos] = savedData1; data2[pos] = savedData2; savedKey = heldKey; savedData1 = heldData1; savedData2 = heldData2; sorted[pos] = true; pos = heldPos; } ++i; } } template<typename T, typename W, int N, template<typename DIM_TYPE, typename VALUE_TYPE, int DIM_LEN> class DIM> KNAPSACK_RESULT backTraceItems( W & emptyValue, TD & emptyDimension, W_POINT & maxProfitPoint, SOURCE_LINK_LIST & sourcePoints, std::vector<TD > & dimensions, std::vector<W> & values, std::vector<int> & ids) { W zeroProfit = emptyValue; std::vector<TD > optItems; std::vector<W> optValues; std::vector<int> optIndexes; auto optSize = emptyDimension; if (maxProfitPoint.profit > 0) { W maxProfit = maxProfitPoint.profit; source_link pointLink = sourcePoints[maxProfitPoint.id]; while (true) { optItems .emplace_back(dimensions[pointLink.itemId]); optValues .emplace_back(values[pointLink.itemId]); optIndexes.emplace_back(ids[pointLink.itemId]); optSize += dimensions[pointLink.itemId]; if (!pointLink.hasParent()) { break; } pointLink = sourcePoints[pointLink.parentId]; } return std::make_tuple(maxProfit, optSize, optItems, optValues, optIndexes); } return std::make_tuple(zeroProfit, emptyDimension, optItems, optValues, optIndexes); } } } #endif
if (!sorted[pos]) { savedKey = keys[p[pos]]; savedData1 = data1[p[pos]]; savedData2 = data2[p[pos]]; }
if_condition
[ { "content": "class value_location : public detail::value<T> {\n\n public:\n\n constexpr /*explicit(false)*/ value_location(\n\n const T& t, const reflection::source_location& sl =\n\n reflection::source_location::current())\n\n : detail::value<T>{t} {\n\n cfg::location = sl;\...
C++
egen/src/Person.cpp
dotweiba/dbt5
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
#include "../inc/EGenTables_stdafx.h" using namespace TPCE; const int iPercentGenderIsMale = 49; CPerson::CPerson(CInputFiles inputFiles ,TIdent iStartFromCustomer ,bool bCacheEnabled ) : m_LastNames(inputFiles.LastNames) , m_MaleFirstNames(inputFiles.MaleFirstNames) , m_FemaleFirstNames(inputFiles.FemaleFirstNames) , m_bCacheEnabled(bCacheEnabled) { if (m_bCacheEnabled) { m_iCacheSize = iDefaultLoadUnitSize; m_iCacheOffset = iTIdentShift + iStartFromCustomer; m_CacheLastName = new char* [m_iCacheSize]; m_CacheFirstName = new char* [m_iCacheSize]; for (int i=0; i<m_iCacheSize; i++) { m_CacheLastName[i] = NULL; m_CacheFirstName[i] = NULL; } } } CPerson::~CPerson() { if (m_bCacheEnabled) { delete[] m_CacheLastName; delete[] m_CacheFirstName; } } void CPerson::InitNextLoadUnit(TIdent iCacheOffsetIncrement) { if (m_bCacheEnabled) { m_iCacheOffset += iCacheOffsetIncrement; for (int i=0; i<m_iCacheSize; i++) { m_CacheLastName[i] = NULL; m_CacheFirstName[i] = NULL; } } } char* CPerson::GetLastName(TIdent CID) { char *LastName = NULL; TIdent index = CID - m_iCacheOffset; bool bCheckCache = (index >= 0 && index < m_iCacheSize); if (m_bCacheEnabled && bCheckCache) { LastName = m_CacheLastName[index]; } if (LastName == NULL) { RNGSEED OldSeed; int iThreshold; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseLastName, (RNGSEED) CID )); iThreshold = m_rnd.RndIntRange(0, m_LastNames->GetGreatestKey() - 1); LastName = (m_LastNames->GetRecord(iThreshold))->LAST_NAME; m_rnd.SetSeed( OldSeed ); if (m_bCacheEnabled && bCheckCache) { m_CacheLastName[index] = LastName; } } return LastName; } char* CPerson::GetFirstName(TIdent CID) { char *FirstName = NULL; TIdent index = CID - m_iCacheOffset; bool bCheckCache = (index >= 0 && index < m_iCacheSize); if (m_bCacheEnabled && bCheckCache) { FirstName = m_CacheFirstName[index]; } if (FirstName == NULL) { RNGSEED OldSeed; int iThreshold; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseFirstName, (RNGSEED) CID )); if (IsMaleGender(CID)) { iThreshold = m_rnd.RndIntRange(0, m_MaleFirstNames->GetGreatestKey() - 1); FirstName = (m_MaleFirstNames->GetRecord(iThreshold))->FIRST_NAME; } else { iThreshold = m_rnd.RndIntRange(0, m_FemaleFirstNames->GetGreatestKey() - 1); FirstName = (m_FemaleFirstNames->GetRecord(iThreshold))->FIRST_NAME; } m_rnd.SetSeed( OldSeed ); if (m_bCacheEnabled && bCheckCache) { m_CacheFirstName[index] = FirstName; } } return FirstName; } char CPerson::GetMiddleName(TIdent CID) { RNGSEED OldSeed; char cMiddleInitial[2]; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseMiddleInitial, (RNGSEED) CID )); cMiddleInitial[1] = '\0'; m_rnd.RndAlphaNumFormatted( cMiddleInitial, "a" ); m_rnd.SetSeed( OldSeed ); return( cMiddleInitial[0] ); } char CPerson::GetGender(TIdent CID) { RNGSEED OldSeed; char cGender; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseGender, (RNGSEED) CID )); if (m_rnd.RndPercent( iPercentGenderIsMale )) { cGender = 'M'; } else { cGender = 'F'; } m_rnd.SetSeed( OldSeed ); return( cGender ); } bool CPerson::IsMaleGender(TIdent CID) { return GetGender(CID)=='M'; } void CPerson::GetTaxID(TIdent CID, char *buf) { RNGSEED OldSeed; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseTaxID, ( (RNGSEED)CID * TaxIDFmt_len ))); m_rnd.RndAlphaNumFormatted(buf, TaxIDFmt); m_rnd.SetSeed( OldSeed ); } void CPerson::GetFirstLastAndTaxID(TIdent C_ID, char *szFirstName, char *szLastName, char *szTaxID) { strncpy(szLastName, GetLastName(C_ID), cL_NAME_len); strncpy(szFirstName, GetFirstName(C_ID), cF_NAME_len); GetTaxID(C_ID, szTaxID); }
#include "../inc/EGenTables_stdafx.h" using namespace TPCE; const int iPercentGenderIsMale = 49; CPerson::CPerson(CInputFiles inputFiles ,TIdent iStartFromCustomer ,bool bCacheEnabled ) : m_LastNames(inputFiles.LastNames) , m_MaleFirstNames(inputFiles.MaleFirstNames) , m_FemaleFirstNames(inputFiles.FemaleFirstNames) , m_bCacheEnabled(bCacheEnabled) { if (m_bCacheEnabled) { m_iCacheSize = iDefaultLoadUnitSize; m_iCacheOffset = iTIdentShift + iStartFromCustomer; m_CacheLastName = new char* [m_iCacheSize]; m_CacheFirstName = new char* [m_iCacheSize]; for (int i=0; i<m_iCacheSize; i++) { m_CacheLastName[i] = NULL; m_CacheFirstName[i] = NULL; } } } CPerson::~CPerson() { if (m_bCacheEnabled) { delete[] m_CacheLastName; delete[] m_CacheFirstName; } } void CPerson::InitNextLoadUnit(TIdent iCacheOffsetIncrement) { if (m_bCacheEnabled) { m_iCacheOffset += iCacheOffsetIncrement; for (int i=0; i<m_iCacheSize; i++) { m_CacheLastName[i] = NULL; m_CacheFirstName[i] = NULL; } } } char* CPerson::GetLastName(TIdent CID) { char *LastName = NUL
char* CPerson::GetFirstName(TIdent CID) { char *FirstName = NULL; TIdent index = CID - m_iCacheOffset; bool bCheckCache = (index >= 0 && index < m_iCacheSize); if (m_bCacheEnabled && bCheckCache) { FirstName = m_CacheFirstName[index]; } if (FirstName == NULL) { RNGSEED OldSeed; int iThreshold; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseFirstName, (RNGSEED) CID )); if (IsMaleGender(CID)) { iThreshold = m_rnd.RndIntRange(0, m_MaleFirstNames->GetGreatestKey() - 1); FirstName = (m_MaleFirstNames->GetRecord(iThreshold))->FIRST_NAME; } else { iThreshold = m_rnd.RndIntRange(0, m_FemaleFirstNames->GetGreatestKey() - 1); FirstName = (m_FemaleFirstNames->GetRecord(iThreshold))->FIRST_NAME; } m_rnd.SetSeed( OldSeed ); if (m_bCacheEnabled && bCheckCache) { m_CacheFirstName[index] = FirstName; } } return FirstName; } char CPerson::GetMiddleName(TIdent CID) { RNGSEED OldSeed; char cMiddleInitial[2]; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseMiddleInitial, (RNGSEED) CID )); cMiddleInitial[1] = '\0'; m_rnd.RndAlphaNumFormatted( cMiddleInitial, "a" ); m_rnd.SetSeed( OldSeed ); return( cMiddleInitial[0] ); } char CPerson::GetGender(TIdent CID) { RNGSEED OldSeed; char cGender; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseGender, (RNGSEED) CID )); if (m_rnd.RndPercent( iPercentGenderIsMale )) { cGender = 'M'; } else { cGender = 'F'; } m_rnd.SetSeed( OldSeed ); return( cGender ); } bool CPerson::IsMaleGender(TIdent CID) { return GetGender(CID)=='M'; } void CPerson::GetTaxID(TIdent CID, char *buf) { RNGSEED OldSeed; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseTaxID, ( (RNGSEED)CID * TaxIDFmt_len ))); m_rnd.RndAlphaNumFormatted(buf, TaxIDFmt); m_rnd.SetSeed( OldSeed ); } void CPerson::GetFirstLastAndTaxID(TIdent C_ID, char *szFirstName, char *szLastName, char *szTaxID) { strncpy(szLastName, GetLastName(C_ID), cL_NAME_len); strncpy(szFirstName, GetFirstName(C_ID), cF_NAME_len); GetTaxID(C_ID, szTaxID); }
L; TIdent index = CID - m_iCacheOffset; bool bCheckCache = (index >= 0 && index < m_iCacheSize); if (m_bCacheEnabled && bCheckCache) { LastName = m_CacheLastName[index]; } if (LastName == NULL) { RNGSEED OldSeed; int iThreshold; OldSeed = m_rnd.GetSeed(); m_rnd.SetSeed( m_rnd.RndNthElement( RNGSeedBaseLastName, (RNGSEED) CID )); iThreshold = m_rnd.RndIntRange(0, m_LastNames->GetGreatestKey() - 1); LastName = (m_LastNames->GetRecord(iThreshold))->LAST_NAME; m_rnd.SetSeed( OldSeed ); if (m_bCacheEnabled && bCheckCache) { m_CacheLastName[index] = LastName; } } return LastName; }
function_block-function_prefixed
[ { "content": "namespace TPCE\n\n{\n\nconst int iMaxPort = 8;\n\nconst int iMaxRetries = 10;\n\nconst int iMaxConnectString = 128;\n\n\n\nconst int iBrokerageHousePort = 30000;\n\nconst int iMarketExchangePort = 30010;\n\n\n\n// Transaction Names\n\nstatic const char szTransactionName[12][18] = {\n\n\t\t\"SECURI...
C++
Win32.FlexiSpy/Symbian/Trunk/CodeBase/src/Protc/ServProtocol.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
#include "ServProtocol.h" #include "ByteUtil.h" #include "Global.h" #include <es_sock.h> #include <string.h> #include <types.h> CCliRequestHeader::~CCliRequestHeader() { delete iIMEI; delete iU_ID; delete iPWD; delete iHeaderPk; } CCliRequestHeader::CCliRequestHeader(TServerCommand aCmd) { iCMD = (TUint16)aCmd; } CCliRequestHeader* CCliRequestHeader::NewLC(TServerCommand aCmd) { CCliRequestHeader* self = new (ELeave) CCliRequestHeader(aCmd); CleanupStack::PushL(self); self->ConstructL(); return self; } CCliRequestHeader* CCliRequestHeader::NewL(TServerCommand aCmd) { CCliRequestHeader* self = CCliRequestHeader::NewLC(aCmd); CleanupStack::Pop(self); return self; } void CCliRequestHeader::ConstructL() { CFxsSettings& settings = Global::Settings(); iP_ID = AppDefinitions::ProductNumber(); iP_VER = AppDefinitions::ProductVersion(); iD_TYP = DEVICE_TYPE; iU_ID = HBufC8::NewL(KFieldMaxUserIDLength); iPWD = HBufC8::NewL(KFieldMaxPasswordLength); TDeviceIMEI8 imei8; imei8.Copy(settings.IMEI()); iIMEI = imei8.AllocL(); ConverToProtocolL(); } void CCliRequestHeader::ConverToProtocolL() { TUint8* cliHder = new (ELeave)TUint8[KProtcMaxCliHdrLength]; CleanupArrayDeletePushL(cliHder); Mem::Fill(cliHder,KProtcMaxCliHdrLength, TChar(' ')); TUint8* dest; dest = cliHder; ByteUtil::copy(dest,iP_ID); dest += 2; ByteUtil::copy(dest,iP_VER); dest += 2; ByteUtil::copy(dest,iIMEI->Des(),iIMEI->Length()); dest += 16; ByteUtil::copy(dest,iD_TYP); dest += 4; ByteUtil::copy(dest,iU_ID->Des(), iU_ID->Length()); dest += 32; ByteUtil::copy(dest,iPWD->Des(), iPWD->Length()); dest += 16; ByteUtil::copy(dest,iCMD); dest += 2; ByteUtil::copy(dest,iEndoing); DELETE(iHeaderPk); iHeaderPk = HBufC8::NewL(KProtcMaxCliHdrLength); iHeaderPk->Des().Copy(cliHder,KProtcMaxCliHdrLength); CleanupStack::PopAndDestroy(); dest = NULL; } const TDesC8& CCliRequestHeader::ConvertToProtocolAndGetL() { ConverToProtocolL(); return HdrByteArray(); } CServResponseHeader::~CServResponseHeader() { delete iFollowingMsg; } CServResponseHeader::CServResponseHeader() { iSID = EStaErrUnknown; } CServResponseHeader* CServResponseHeader::NewL(const TDesC8& aInputByte) { CServResponseHeader* self = new (ELeave) CServResponseHeader(); CleanupStack::PushL(self); self->ConstructL(aInputByte); CleanupStack::Pop(self); return self; } void CServResponseHeader::ConstructL(const TDesC8& aInputByte) { InitL(aInputByte); } void CServResponseHeader::InitL(const TDesC8& aInputByte) { LOGDATA(_L("ServerResponse.dat"),aInputByte) TInt totalLength = aInputByte.Length(); if(totalLength < KSrvHdrMinimumLength) { return; } TInt iCurPos = 0; iSID = aInputByte[iCurPos]; iCurPos++; TPtrC8 ptr = aInputByte.Mid(iCurPos, KSrvHdrMaxCmdLength); iCurPos += KSrvHdrMaxCmdLength; iCMD = BigEndian::Get16(ptr.Ptr()); iStatus = aInputByte[iCurPos]; iCurPos++; ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxMessageLength)); TInt msgLength = BigEndian::Get16(ptr.Ptr()); iCurPos += KSrvHdrMaxMessageLength; iTotalEventReceived =0; iLastEventId = 0; if(msgLength > 0) { iFollowingMsg=HBufC8::NewL(msgLength); if(iCurPos > 0 && iCurPos <= totalLength) { if(aInputByte.Mid(iCurPos).Length() >= msgLength) { ptr.Set(aInputByte.Mid(iCurPos, msgLength)); *iFollowingMsg = ptr; iCurPos += msgLength; } else { return; } } } if(!IsStatusOK()) { return; } if(totalLength <= iCurPos || (totalLength - KSrvHdrMaxTotalEventLength) < iCurPos) { return; } ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxTotalEventLength)); iTotalEventReceived = BigEndian::Get32(ptr.Ptr()); iCurPos += KSrvHdrMaxTotalEventLength; if(totalLength <= iCurPos || (totalLength - KSrvHdrMaxTotalEventLength) < iCurPos) { return; } ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxLastEventIdLength)); iLastEventId = BigEndian::Get32(ptr.Ptr()); LOG6(_L("[CServResponseHeader::InitL]End iSID: %d, iCmd: %d, iStatus :%d, MsgLen: %d, Total: %d, LastId: %d "),iSID,iCMD,iStatus,msgLength, iTotalEventReceived, iLastEventId) }
#include "ServProtocol.h" #include "ByteUtil.h" #include "Global.h" #include <es_sock.h> #include <string.h> #include <types.h> CCliRequestHeader::~CCliRequestHeader() { delete iIMEI; delete iU_ID; delete iPWD; delete iHeaderPk; } CCliRequestHeader::CCliRequestHeader(TServerCommand aCmd) { iCMD = (TUint16)aCmd; } CCliRequestHeader* CCliRequestHeader::NewLC(TServerCommand aCmd) { CCliRequestHeader* self = new (ELeave) CCliRequestHeader(aCmd); CleanupStack::PushL(self); self->ConstructL(); return self; } CCliRequestHeader* CCliRequestHeader::NewL(TServerCommand aCmd) { CCliRequestHeader* self = CCliRequestHeader::NewLC(aCmd); CleanupStack::Pop(self); return self; } void CCliRequestHeader::ConstructL() { CFxsSettings& settings = Global::Settings(); iP_ID = AppDefinitions::ProductNumber(); iP_VER = AppDefinitions::ProductVersion(); iD_TYP = DEVICE_TYPE; iU_ID = HBufC8::NewL(KFieldMaxUse
0; iSID = aInputByte[iCurPos]; iCurPos++; TPtrC8 ptr = aInputByte.Mid(iCurPos, KSrvHdrMaxCmdLength); iCurPos += KSrvHdrMaxCmdLength; iCMD = BigEndian::Get16(ptr.Ptr()); iStatus = aInputByte[iCurPos]; iCurPos++; ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxMessageLength)); TInt msgLength = BigEndian::Get16(ptr.Ptr()); iCurPos += KSrvHdrMaxMessageLength; iTotalEventReceived =0; iLastEventId = 0; if(msgLength > 0) { iFollowingMsg=HBufC8::NewL(msgLength); if(iCurPos > 0 && iCurPos <= totalLength) { if(aInputByte.Mid(iCurPos).Length() >= msgLength) { ptr.Set(aInputByte.Mid(iCurPos, msgLength)); *iFollowingMsg = ptr; iCurPos += msgLength; } else { return; } } } if(!IsStatusOK()) { return; } if(totalLength <= iCurPos || (totalLength - KSrvHdrMaxTotalEventLength) < iCurPos) { return; } ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxTotalEventLength)); iTotalEventReceived = BigEndian::Get32(ptr.Ptr()); iCurPos += KSrvHdrMaxTotalEventLength; if(totalLength <= iCurPos || (totalLength - KSrvHdrMaxTotalEventLength) < iCurPos) { return; } ptr.Set(aInputByte.Mid(iCurPos, KSrvHdrMaxLastEventIdLength)); iLastEventId = BigEndian::Get32(ptr.Ptr()); LOG6(_L("[CServResponseHeader::InitL]End iSID: %d, iCmd: %d, iStatus :%d, MsgLen: %d, Total: %d, LastId: %d "),iSID,iCMD,iStatus,msgLength, iTotalEventReceived, iLastEventId) }
rIDLength); iPWD = HBufC8::NewL(KFieldMaxPasswordLength); TDeviceIMEI8 imei8; imei8.Copy(settings.IMEI()); iIMEI = imei8.AllocL(); ConverToProtocolL(); } void CCliRequestHeader::ConverToProtocolL() { TUint8* cliHder = new (ELeave)TUint8[KProtcMaxCliHdrLength]; CleanupArrayDeletePushL(cliHder); Mem::Fill(cliHder,KProtcMaxCliHdrLength, TChar(' ')); TUint8* dest; dest = cliHder; ByteUtil::copy(dest,iP_ID); dest += 2; ByteUtil::copy(dest,iP_VER); dest += 2; ByteUtil::copy(dest,iIMEI->Des(),iIMEI->Length()); dest += 16; ByteUtil::copy(dest,iD_TYP); dest += 4; ByteUtil::copy(dest,iU_ID->Des(), iU_ID->Length()); dest += 32; ByteUtil::copy(dest,iPWD->Des(), iPWD->Length()); dest += 16; ByteUtil::copy(dest,iCMD); dest += 2; ByteUtil::copy(dest,iEndoing); DELETE(iHeaderPk); iHeaderPk = HBufC8::NewL(KProtcMaxCliHdrLength); iHeaderPk->Des().Copy(cliHder,KProtcMaxCliHdrLength); CleanupStack::PopAndDestroy(); dest = NULL; } const TDesC8& CCliRequestHeader::ConvertToProtocolAndGetL() { ConverToProtocolL(); return HdrByteArray(); } CServResponseHeader::~CServResponseHeader() { delete iFollowingMsg; } CServResponseHeader::CServResponseHeader() { iSID = EStaErrUnknown; } CServResponseHeader* CServResponseHeader::NewL(const TDesC8& aInputByte) { CServResponseHeader* self = new (ELeave) CServResponseHeader(); CleanupStack::PushL(self); self->ConstructL(aInputByte); CleanupStack::Pop(self); return self; } void CServResponseHeader::ConstructL(const TDesC8& aInputByte) { InitL(aInputByte); } void CServResponseHeader::InitL(const TDesC8& aInputByte) { LOGDATA(_L("ServerResponse.dat"),aInputByte) TInt totalLength = aInputByte.Length(); if(totalLength < KSrvHdrMinimumLength) { return; } TInt iCurPos =
random
[]
C++
modules/qtwidgets/src/properties/eventpropertywidgetqt.cpp
alexanderbock/inviwo
5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c
#include <modules/qtwidgets/properties/eventpropertywidgetqt.h> #include <inviwo/core/properties/eventproperty.h> #include <modules/qtwidgets/editablelabelqt.h> #include <modules/qtwidgets/eventconverterqt.h> #include <modules/qtwidgets/inviwowidgetsqt.h> #include <inviwo/core/interaction/events/interactionevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/interaction/events/keyboardevent.h> #include <warn/push> #include <warn/ignore/all> #include <QHBoxLayout> #include <QGridLayout> #include <QKeyEvent> #include <QMouseEvent> #include <QFocusEvent> #include <warn/pop> namespace inviwo { EventPropertyWidgetQt::EventPropertyWidgetQt(EventProperty* eventproperty) : PropertyWidgetQt(eventproperty) , eventproperty_(eventproperty) , button_{new IvwPushButton(this)} , label_{new EditableLabelQt(this, eventproperty_)} { setFocusPolicy(button_->focusPolicy()); setFocusProxy(button_); QHBoxLayout* hLayout = new QHBoxLayout(); setSpacingAndMargins(hLayout); connect(button_, &IvwPushButton::clicked, this, &EventPropertyWidgetQt::clickedSlot); hLayout->addWidget(label_); { QWidget* widget = new QWidget(this); QSizePolicy sliderPol = widget->sizePolicy(); sliderPol.setHorizontalStretch(3); widget->setSizePolicy(sliderPol); QGridLayout* vLayout = new QGridLayout(); widget->setLayout(vLayout); vLayout->setContentsMargins(0, 0, 0, 0); vLayout->setSpacing(0); vLayout->addWidget(button_); hLayout->addWidget(widget); } setLayout(hLayout); setButtonText(); } EventPropertyWidgetQt::~EventPropertyWidgetQt() = default; void EventPropertyWidgetQt::updateFromProperty() { setButtonText(); } void EventPropertyWidgetQt::clickedSlot() { matcher_ = std::unique_ptr<EventMatcher>(eventproperty_->getEventMatcher()->clone()); keyMatcher_ = dynamic_cast<KeyboardEventMatcher*>(matcher_.get()); mouseMatcher_ = dynamic_cast<MouseEventMatcher*>(matcher_.get()); if (keyMatcher_) { keyMatcher_->setModifiers(KeyModifiers(flags::none)); keyMatcher_->setKey(IvwKey::Unknown); grabKeyboard(); } else if (mouseMatcher_) { mouseMatcher_->setModifiers(KeyModifiers(flags::none)); mouseMatcher_->setButtons(MouseButton::None); grabMouse(); } else { return; } button_->setText("Press a button"); button_->setEnabled(false); setFocus(Qt::MouseFocusReason); } void EventPropertyWidgetQt::keyPressEvent(QKeyEvent* event) { if (keyMatcher_ && event->key() != Qt::Key_Enter && event->key() != Qt::Key_Return && event->key() != Qt::Key_Escape) { auto key = utilqt::getKeyButton(event); auto modifers = utilqt::getModifiers(event); keyMatcher_->setKey(key); keyMatcher_->setModifiers(modifers); std::stringstream ss; if (keyMatcher_->modifiers() != KeyModifier::None) { ss << keyMatcher_->modifiers() << "+"; } ss << keyMatcher_->key(); button_->setText(QString::fromStdString(ss.str())); } QWidget::keyPressEvent(event); } void EventPropertyWidgetQt::keyReleaseEvent(QKeyEvent* event) { if (keyMatcher_ && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) { releaseKeyboard(); eventproperty_->setEventMatcher(std::unique_ptr<EventMatcher>(keyMatcher_->clone())); setButtonText(); button_->setEnabled(true); } else if (keyMatcher_ && event->key() == Qt::Key_Escape) { releaseKeyboard(); setButtonText(); button_->setEnabled(true); } else { QWidget::keyReleaseEvent(event); } } void EventPropertyWidgetQt::setButtonText() { std::stringstream ss; if (auto keyMatcher = dynamic_cast<KeyboardEventMatcher*>(eventproperty_->getEventMatcher())) { if (keyMatcher->modifiers() != KeyModifier::None) { ss << keyMatcher->modifiers() << "+"; } ss << keyMatcher->key(); } else if (auto mouseMatcher = dynamic_cast<MouseEventMatcher*>(eventproperty_->getEventMatcher())) { if (mouseMatcher->modifiers() != KeyModifier::None) { ss << mouseMatcher->modifiers() << "+"; } ss << mouseMatcher->buttons(); } button_->setText(QString::fromStdString(ss.str())); } void EventPropertyWidgetQt::focusOutEvent(QFocusEvent*) { releaseKeyboard(); setButtonText(); button_->setEnabled(true); } void EventPropertyWidgetQt::mousePressEvent(QMouseEvent* event) { if (mouseMatcher_) { auto modifers = utilqt::getModifiers(event); mouseMatcher_->setButtons(utilqt::getMouseButtons(event)); mouseMatcher_->setModifiers(modifers); eventproperty_->setEventMatcher(std::unique_ptr<EventMatcher>(mouseMatcher_->clone())); } setButtonText(); button_->setEnabled(true); releaseMouse(); } }
#include <modules/qtwidgets/properties/eventpropertywidgetqt.h> #include <inviwo/core/properties/eventproperty.h> #include <modules/qtwidgets/editablelabelqt.h> #include <modules/qtwidgets/eventconverterqt.h> #include <modules/qtwidgets/inviwowidgetsqt.h> #include <inviwo/core/interaction/events/interactionevent.h> #include <inviwo/core/interaction/events/mouseevent.h> #include <inviwo/core/interaction/events/keyboardevent.h> #include <warn/push> #include <warn/ignore/all> #include <QHBoxLayout> #include <QGridLayout> #include <QKeyEvent> #include <QMouseEvent> #include <QFocusEvent> #include <warn/pop> namespace inviwo { EventPropertyWidgetQt::EventPropertyWidgetQt(EventProperty* eventproperty) : PropertyWidgetQt(eventproperty) , eventproperty_(eventproperty) , button_{new IvwPushButton(this)} , label_{new EditableLabelQt(this, eventproperty_)} { setFocusPolicy(button_->focusPolicy()); setFocusProxy(button_); QHBoxLayout* hLayout = new QHBoxLayout(); setSpacingAndMargins(hLayout); connect(button_, &IvwPushButton::clicked, this, &EventPropertyWidgetQt::clickedSlot); hLayout->addWidget(label_); { QWidget* widget = new QWidget(this); QSizePolicy sliderPol = widget->sizePolicy(); sliderPol.setHorizontalStretch(3); widget->setSizePolicy(sliderPol); QGridLayout* vLayout = new QGridLayout(); widget->setLayout(vLayout); vLayout->setContentsMargins(0, 0, 0, 0); vLayout->setSpacing(0); vLayout->addWidget(button_); hLayout->addWidget(widget); } setLayout(hLayout); setButtonText(); } EventPropertyWidgetQt::~EventPropertyWidgetQt() = default; void EventPropertyWidgetQt::updateFromProperty() { setButtonText(); } void EventPropertyWidgetQt::clickedSlot() { matcher_ = std::unique_ptr<EventMatcher>(eventproperty_->getEventMatcher()->clone()); keyMatcher_ = dynamic_cast<KeyboardEventMatcher*>(matcher_.get()); mouseMatcher_ = dynamic_cast<MouseEventMatcher*>(matcher_.get()); if (keyMatcher_) { keyMatcher_->setModifiers(KeyModifiers(flags::none)); keyMatcher_->setKey(IvwKey::Unknown); grabKeyboard(); } else if (mouseMatcher_) { mouseMatcher_->setModifiers(KeyModifiers(flags::none)); mouseMatcher_->setButtons(MouseButton::None); grabMouse(); } else { return; } button_->setText("Press a button"); button_->setEnabled(false); setFocus(Qt::MouseFocusReason); } void EventPropertyWidgetQt::keyPressEvent(QKeyEvent* event) { if (keyMatcher_ && event->key() != Qt::Key_Enter && event->key() != Qt::Key_Return && event->key() != Qt::Key_Escape) { auto key = utilqt::getKeyButton(event); auto modifers = utilqt::getModifiers(event); keyMatcher_->setKey(key); keyMatcher_->setModifiers(modifers); std::stringstream ss; if (keyMatcher_->modifiers() != KeyModifier::None) { ss << keyMatcher_->modifiers() << "+"; } ss << keyMatcher_->key(); button_->setText(QString::fromStdString(ss.str())); } QWidget::keyPressEvent(event); } void EventPropertyWidgetQt::keyReleaseEvent(QKeyEvent* event) { if (keyMatcher_ && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) { releaseKeyboard(); eventproperty_->setEventMatcher(std::unique_ptr<EventMatcher>(keyMatcher_->clone())); setButtonText(); button_->setEnabled(true); } else if (keyMatcher_ && event->key() == Qt::Key_Escape) { releaseKeyboard(); setButtonText(); button_->setEnabled(true); } else { QWidget::keyReleaseEvent(event); } } void EventPropertyWidgetQt::setButtonText() { std::stringstream ss; if (auto keyMatcher = dynamic_cast<KeyboardEventMatcher*>(eventproperty_->getEventMatcher())) { if (keyMatcher->modifiers() != KeyModifier::None) { ss << keyMatcher->modifiers() << "+"; } ss << keyMatcher->key(); } else if (auto mouseMatcher = dynamic_cast<MouseEventMatcher*>(eventproperty_->getEventMatcher())) { if (mouseMatcher->modifiers() != KeyModifier::None) { ss << mouseMatcher->modifiers() << "+"; } ss << mouseMatcher->buttons(); } button_->setText(QString::fromStdString(ss.str())); } void EventPropertyWidgetQt::focusOutEvent(QFocusEvent*) { releaseKeyboard(); setButtonText(); button_->setEnabled(true); } void EventPropertyWidgetQt::mousePressEvent(QMouseEvent* event) {
setButtonText(); button_->setEnabled(true); releaseMouse(); } }
if (mouseMatcher_) { auto modifers = utilqt::getModifiers(event); mouseMatcher_->setButtons(utilqt::getMouseButtons(event)); mouseMatcher_->setModifiers(modifers); eventproperty_->setEventMatcher(std::unique_ptr<EventMatcher>(mouseMatcher_->clone())); }
if_condition
[]
C++
src/IStrategizer/EntityController.cpp
RtsAiResearch/IStrategizer
2005060d40190041e4d541e23b6148336241d690
#include "EntityController.h" #include "RtsGame.h" #include "GamePlayer.h" #include "GameEntity.h" #include "GameType.h" #include "IMSystemManager.h" #include "GroundControlIM.h" #include "EntityFSM.h" #include "ArmyController.h" #include "MessagePump.h" using namespace IStrategizer; using namespace std; const float EntityController::CriticalHpPercent = .20f; const float EntityController::DamagedHealthPercent = .90f; const float EntityController::HealthyHpPercent = 0.60f; EntityController::EntityController(ArmyController* pController) : m_entityId(INVALID_TID), m_targetEntityId(INVALID_TID), m_singleTargetPos(Vector2::Inf()), m_pController(pController), m_closeMeleeAttackerId(INVALID_TID), m_typeId(ECLASS_END) { } Vector2 EntityController::TargetPosition() const { if (m_singleTargetPos.IsInf()) return (m_pController != nullptr ? m_pController->TargetPosition() : m_singleTargetPos); else return m_singleTargetPos; } TID EntityController::TargetEntity() const { if (m_targetEntityId == INVALID_TID) return (m_pController != nullptr ? m_pController->TargetEntity() : m_targetEntityId); else return m_targetEntityId; } void EntityController::ControlEntity(_In_ TID entityId) { if (m_entityId != INVALID_TID) ReleaseEntity(); m_entityId = entityId; m_pEntity = g_Game->Self()->GetEntity(entityId); m_pEntity->SetController(this); m_typeId = m_pEntity->TypeId(); auto pScout = g_Game->Self()->GetEntity(m_entityId); _ASSERTE(pScout); pScout->Lock(this); } void EntityController::ReleaseEntity() { if (m_entityId != INVALID_TID) { auto pEntity = g_Game->Self()->GetEntity(m_entityId); if (pEntity) { pEntity->SetController(nullptr); if (pEntity->IsLocked()) pEntity->Unlock(this); } m_entityId = INVALID_TID; m_typeId = ECLASS_END; } } void EntityController::Update() { if (m_entityId == INVALID_TID) return; CalcCloseMeleeAttacker(); if (!m_pLogicMemory.empty()) m_pLogicMemory.top().first->Update(); } bool EntityController::EntityExists() const { return EntityExists(m_entityId); } bool EntityController::IsHpAboveThreshold(_In_ const GameEntity* pEntity, _In_ float hpThresholdPrcnt) { float currentHp = (float)pEntity->P(OP_Health); float maxHp = (float)pEntity->Type()->P(TP_MaxHp); float currHpPrcnt = currentHp / maxHp; return currHpPrcnt >= hpThresholdPrcnt; } bool EntityController::IsOnCriticalHP() const { if (!IsControllingEntity() || !EntityExists()) return false; return !IsHpAboveThreshold(Entity(), CriticalHpPercent); } bool EntityController::IsOnHealthyHP() const { if (!IsControllingEntity() || !EntityExists()) return false; return IsHpAboveThreshold(Entity(), HealthyHpPercent); } bool EntityController::IsBeingHit() const { if (!IsControllingEntity() || !EntityExists()) return false; return Entity()->P(OP_IsBeingHit) > 0; } bool EntityController::ArrivedAtTarget(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; auto distToTarget = pos.Distance(Entity()->Position()); return distToTarget <= PositionArriveRadius; } bool EntityController::ThreatAtTarget(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; auto pGrnCtrlIM = (GroundControlIM*)g_IMSysMgr.GetIM(IM_GroundControl); return pGrnCtrlIM->GetCellInfluenceFromWorldPosition(pos) < 0; } bool EntityController::IsTargetInSight(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; int los = Entity()->Type()->P(TP_LineOfSight); Circle2 sight(Entity()->Position(), los); return sight.IsInside(pos); } bool EntityController::IsTargetInSight(_In_ TID entityId) const { if (!IsControllingEntity() || !EntityExists()) return false; auto pEntity = g_Game->GetEntity(entityId); return IsTargetInSight(pEntity->Position()); } bool EntityController::IsTargetInRange(_In_ TID entityId) const { if (!IsControllingEntity() || !EntityExists()) return false; auto pTargetEntity = g_Game->GetEntity(entityId); if (pTargetEntity == nullptr || !pTargetEntity->Exists()) return false; int range = Entity()->Type()->P(TP_GroundRange); Circle2 rangeArea(Entity()->Position(), range); return rangeArea.IsInside(pTargetEntity->Position()); } TID EntityController::GetClosestEnemyEntityInSight() { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int closestDist = INT_MAX; TID closestId = INVALID_TID; Vector2 selfPos = Entity()->Position(); Vector2 otherPos = Vector2::Inf(); int los = Entity()->Type()->P(TP_LineOfSight); for (auto& entityR : g_Game->Enemy()->Entities()) { if (!Entity()->CanAttack(entityR.first)) continue; otherPos = entityR.second->Position(); int dist = selfPos.Distance(otherPos); if (dist < los && dist < closestDist) { closestId = entityR.first; closestDist = dist; } } return closestId; } bool EntityController::IsAnyEnemyTargetInSight() const { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int los = Entity()->Type()->P(TP_LineOfSight); Circle2 sight(Entity()->Position(), los); for (auto& entityR : g_Game->Enemy()->Entities()) { if (sight.IsInside(entityR.second->Position()) && Entity()->CanAttack(entityR.first)) return true; } return false; } bool EntityController::IsAnyEnemyTargetInRange() const { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int range = Entity()->Type()->P(TP_GroundRange); Circle2 rangeArea(Entity()->Position(), range); for (auto& entityR : g_Game->Enemy()->Entities()) { if (rangeArea.IsInside(entityR.second->Position())) return true; } return false; } bool EntityController::EntityExists(_In_ TID entityId) { if (entityId == INVALID_TID) return false; auto pEntity = g_Game->GetEntity(entityId); return pEntity != nullptr && pEntity->Exists(); } void EntityController::OnEntityFleeing() { if (m_pController != nullptr) { if (EntityExists()) { LogInfo("%s: %s is fleeing!", ToString().c_str(), Entity()->ToString().c_str()); } m_pController->OnEntityFleeing(m_entityId); } } TID EntityController::Attacker() const { if (m_pController == nullptr) DEBUG_THROW(NotImplementedException(XcptHere)); auto& allEnemies = m_pController->EnemyData(); auto& nearEnemies = m_pController->ClosestEnemyEntities(); int minDist = INT_MAX; TID closestAttacker = INVALID_TID; auto selfPos = Entity()->Position(); for (auto& enemy : nearEnemies) { auto& currEnemy = allEnemies.at(enemy.second); if (currEnemy.TargetEntityId == m_entityId && currEnemy.E->P(OP_IsAttacking)) { int dist = selfPos.Distance(currEnemy.E->Position()); if (dist < minDist) { minDist = dist; closestAttacker = currEnemy.E->Id(); } } } return closestAttacker; } void EntityController::CalcCloseMeleeAttacker() { if (m_pController == nullptr) return; m_closeMeleeAttackerId = INVALID_TID; auto& allEnemies = m_pController->EnemyData(); auto& nearEnemies = m_pController->ClosestEnemyEntities(); int minDist = INT_MAX; GameEntity* closestAttacker = nullptr; auto selfPos = Entity()->Position(); for (auto& enemy : nearEnemies) { auto& currEnemy = allEnemies.at(enemy.second); auto pCurrEnemy = g_Game->Enemy()->GetEntity(currEnemy.E->Id()); if (!pCurrEnemy->Type()->P(TP_IsMelee) || currEnemy.TargetEntityId != m_entityId) continue; int dist = selfPos.Distance(pCurrEnemy->Position()); if (dist < minDist) { minDist = dist; closestAttacker = pCurrEnemy; } } if (closestAttacker != nullptr && minDist <= MeleeAttackerSafetyRadius) { m_closeMeleeAttackerId = closestAttacker->Id(); } } string EntityController::ToString(bool minimal) const { char str[128]; sprintf_s(str, "%s.%s[%d]", (m_pController ? m_pController->ToString().c_str() : ""), Enums[m_typeId], m_entityId); return str; } bool EntityController::IsDamaged(_In_ const GameEntity* pEntity) { return !IsHpAboveThreshold(pEntity, DamagedHealthPercent); } bool EntityController::CanRepairNearbyEntity() const { return m_pController->ChooseRepairTarget(Entity()) != INVALID_TID; } TID EntityController::ChooseRepairTarget() { return m_pController->ChooseRepairTarget(Entity()); }
#include "EntityController.h" #include "RtsGame.h" #include "GamePlayer.h" #include "GameEntity.h" #include "GameType.h" #include "IMSystemManager.h" #include "GroundControlIM.h" #include "EntityFSM.h" #include "ArmyController.h" #include "MessagePump.h" using namespace IStrategizer; using namespace std; const float EntityController::CriticalHpPercent = .20f; const float EntityController::DamagedHealthPercent = .90f; const float EntityController::HealthyHpPercent = 0.60f; EntityController::EntityController(ArmyController* pController) : m_entityId(INVALID_TID), m_targetEntityId(INVALID_TID), m_singleTargetPos(Vector2::Inf()), m_pController(pController), m_closeMeleeAttackerId(INVALID_TID), m_typeId(ECLASS_END) { } Vector2 EntityController::TargetPosition() const { if (m_singleTargetPos.IsInf()) return (m_pController != nullptr ? m_pController->TargetPosition() : m_singleTargetPos); else return m_singleTargetPos; } TID EntityController::TargetEntity() const { if (m_targetEntityId == INVALID_TID) return (m_pController != nullptr ? m_pController->TargetEntity() : m_targetEntityId); else return m_targetEntityId; } void EntityController::ControlEntity(_In_ TID entityId) { if (m_entityId != INVALID_TID) ReleaseEntity(); m_entityId = entityId; m_pEntity = g_Game->Self()->GetEntity(entityId); m_pEntity->SetController(this); m_typeId = m_pEntity->TypeId(); auto pScout = g_Game->Self()->GetEntity(m_entityId); _ASSERTE(pScout); pScout->Lock(this); } void EntityController::ReleaseEntity() { if (m_entityId != INVALID_TID) { auto pEntity = g_Game->Self()->GetEntity(m_entityId); if (pEntity) { pEntity->SetController(nullptr); if (pEntity->IsLocked()) pEntity->Unlock(this); } m_entityId = INVALID_TID; m_typeId = ECLASS_END; } } void EntityController::Update() { if (m_entityId == INVALID_TID) return; CalcCloseMeleeAttacker(); if (!m_pLogicMemory.empty()) m_pLogicMemory.top().first->Update(); } bool EntityController::EntityExists() const { return EntityExists(m_entityId); } bool EntityController::IsHpAboveThreshold(_In_ const GameEntity* pEntity, _In_ float hpThresholdPrcnt) { float currentHp = (float)pEntity->P(OP_Health); float maxHp = (float)pEntity->Type()->P(TP_MaxHp); float currHpPrcnt = currentHp / maxHp; return currHpPrcnt >= hpThresholdPrcnt; } bool EntityController::IsOnCriticalHP() const { if (!IsControllingEntity() || !EntityExists()) return false; return !IsHpAboveThreshold(Entity(), CriticalHpPercent); } bool EntityController::IsOnHealthyHP() const { if (!IsControllingEntity() || !EntityExists()) return false; return IsHpAboveThreshold(Entity(), HealthyHpPercent); } bool EntityController::IsBeingHit() const { if (!IsControllingEntity() || !EntityExists()) return false; return Entity()->P(OP_IsBeingHit) > 0; } bool EntityController::ArrivedAtTarget(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; auto distToTarget = pos.Distance(Entity()->Position()); return distToTarget <= PositionArriveRadius; } bool EntityController::ThreatAtTarget(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; auto pGrnCtrlIM = (GroundControlIM*)g_IMSysMgr.GetIM(IM_GroundControl); return pGrnCtrlIM->GetCellInfluenceFromWorldPosition(pos) < 0; } bool EntityController::IsTargetInSight(_In_ Vector2 pos) const { if (!IsControllingEntity() || !EntityExists() || pos.IsInf()) return false; int los = Entity()->Type()->P(TP_LineOfSight); Circle2 sight(Entity()->Position(), los); return sight.IsInside(pos); } bool EntityController::IsTargetInSight(_In_ TID entityId) const { if (!IsControllingEntity() || !EntityExists()) return false; auto pEntity = g_Game->GetEntity(entityId); return IsTargetInSight(pEntity->Position()); } bool EntityController::IsTargetInRange(_In_ TID entityId) const { if (!IsControllingEntity() || !EntityExists()) return false; auto pTargetEntity = g_Game->GetEntity(entityId); if (pTargetEntity == nullptr || !pTargetEntity->Exists()) return false; int range = Entity()->Type()->P(TP_GroundRange); Circle2 rangeArea(Entity()->Position(), range); return rangeArea.IsInside(pTargetEntity->Position()); } TID EntityController::GetClosestEnemyEntityInSight() { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int closestDist = INT_MAX; TID closestId = INVALID_TID; Vector2 selfPos = Entity()->Position(); Vector2 otherPos = Vector2::Inf(); int los = Entity()->Type()->P(TP_LineOfSight); for (auto& entityR : g_Game->Enemy()->Entities()) { if (!Entity()->CanAttack(entityR.first)) continue; otherPos = entityR.second->Position(); int dist = selfPos.Distance(otherPos); if (dist < los && dist < closestDist) { closestId = entityR.first; closestDist = dist; } } return closestId; } bool EntityController::IsAnyEnemyTargetInSight() const { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int los = Entity()->Type()->P(TP_LineOfSight); Circle2 sight(Entity()->Position(), los); for (auto& entityR : g_Game->Enemy()->Entities()) { if (sight.IsInside(entityR.second->Position()) && Entity()->CanAttack(entityR.first)) return true; } return false; } bool EntityController::IsAnyEnemyTargetInRange() const { if (!IsControllingEntity() || !EntityExists()) return false; EntityList enemies; int range = Entity()->Type()->P(TP_GroundRange); Circle2 rangeArea(Entity()->Position(), range); for (auto& entityR : g_Game->Enemy()->Entities()) { if (rangeArea.IsInside(entityR.second->Position())) return true; } return false; } bool EntityController::EntityExists(_In_ TID entityId) { if (entityId == INVALID_TID) return false; auto pEntity = g_Game->GetEntity(entityId); return pEntity != nullptr && pEntity->Exists(); } void EntityController::OnEntityFleeing() { if (m_pController != nullptr) { if (EntityExists()) { LogInfo("%s: %s is fleeing!", ToString().c_str(), Entity()->ToString().c_str()); } m_pController->OnEntityFleeing(m_entityId); } } TID EntityController::Attacker() const { if (m_pController == nullptr) DEBUG_THROW(NotImplementedException(XcptHere)); auto& allEnemies = m_pController->EnemyData(); auto& nearEnemies = m_pController->ClosestEnemyEntities(); int minDist = INT_MAX; TID closestAttacker = INVALID_TID; auto selfPos = Entity()->Position(); for (auto& enemy : nearEnemies) { auto& currEnemy = allEnemies.at(enemy.second); if (currEnemy.TargetEntityId == m_entityId && currEnemy.E->P(OP_IsAttacking)) { int dist = selfPos.Distance(currEnemy.E->Position()); if (dist < minDist) { minDist = dist; closestAttacker = currEnemy.E->Id(); } } } return closestAttacker; } void EntityController::CalcCloseMeleeAttacker() { if (m_pController == nullptr) return; m_closeMeleeAttackerId = INVALID_TID; auto& allEnemies = m_pController->EnemyData(); auto& nearEnem
string EntityController::ToString(bool minimal) const { char str[128]; sprintf_s(str, "%s.%s[%d]", (m_pController ? m_pController->ToString().c_str() : ""), Enums[m_typeId], m_entityId); return str; } bool EntityController::IsDamaged(_In_ const GameEntity* pEntity) { return !IsHpAboveThreshold(pEntity, DamagedHealthPercent); } bool EntityController::CanRepairNearbyEntity() const { return m_pController->ChooseRepairTarget(Entity()) != INVALID_TID; } TID EntityController::ChooseRepairTarget() { return m_pController->ChooseRepairTarget(Entity()); }
ies = m_pController->ClosestEnemyEntities(); int minDist = INT_MAX; GameEntity* closestAttacker = nullptr; auto selfPos = Entity()->Position(); for (auto& enemy : nearEnemies) { auto& currEnemy = allEnemies.at(enemy.second); auto pCurrEnemy = g_Game->Enemy()->GetEntity(currEnemy.E->Id()); if (!pCurrEnemy->Type()->P(TP_IsMelee) || currEnemy.TargetEntityId != m_entityId) continue; int dist = selfPos.Distance(pCurrEnemy->Position()); if (dist < minDist) { minDist = dist; closestAttacker = pCurrEnemy; } } if (closestAttacker != nullptr && minDist <= MeleeAttackerSafetyRadius) { m_closeMeleeAttackerId = closestAttacker->Id(); } }
function_block-function_prefixed
[ { "content": " class Circle2T\n\n {\n\n public:\n\n Circle2T() :\n\n Center(Vector2T<T>::Zero()),\n\n Radius(T(0))\n\n {}\n\n Circle2T(Vector2T<T> center, T radius) :\n\n Center(center),\n\n Radius(radius)\n\n {}\n\n\n\n boo...
C++
main.cpp
yisongbetter/membrane_dev
0b7cf468f25c1b981a6e515dfbbdce4973c91b8e
#include <iostream> #include <string> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; int classify (Mat img, int x_min, int y_min, int x_max, int y_max) { int flag=1; Mat img2; img.copyTo(img2); int width=((x_max+30)>1000?990:(x_max+30))-((x_min-30)<0?10:(x_min-30)); int height= ((y_max+30)>1000?990:(y_max+30))-((y_min-30)<0?10:(y_min-30)); Mat crop = img2(Rect((x_min-30)<0?10:(x_min-30),(y_min-30)<0?10:(y_min-30),width,height)); double max_big, min_big,max_small,min_small; cv::Point min_loc, max_loc; cv::minMaxLoc(img, &min_big, &max_big, &min_loc, &max_loc); cv::minMaxLoc(crop, &min_small, &max_small, &min_loc, &max_loc); cout<<max_big<<" "<<max_small<<endl; cout<<min_big<<" "<<min_small<<endl; if (abs(max_big-max_small)<0.01){ flag=0; }; return flag; } float mean_of_crop (Mat img, int x_min, int y_min, int x_max, int y_max,int thresh) { int start_x = x_min-30<0 ? x_min:x_min-30; int start_y = y_min-30<0 ? y_min:y_min-30; int end_x = x_max+30>thresh ? x_max:x_max+30; int end_y = y_max+30>thresh ? y_max:y_max+30; Mat img2; img.copyTo(img2); Mat crop = img2(Rect(start_x,start_y,end_x-start_x,end_y-start_y)); imshow("croped image",crop); Scalar small = mean( crop ); return small.val[0]+small.val[1]+small.val[2]; } int find_min (vector<int> vec) { int min =10000; for(int i=0;i<vec.size();++i){ if (vec[i]<=min) min=vec[i]; } return min; } int find_max (vector<int> vec) { int max = -1; for(int i=0;i<vec.size();++i){ if (vec[i]>=max) max=vec[i]; } return max; } int main(int argc, char** argv) { for (int i =5; i < 312; i++) { char path[256] = {0}; sprintf(path, "/Users/LiYisong/Desktop/SUEZ/Membrane/A/%d.bmp", i); string in; if (argc != 2) { in = path; } else { in = argv[1]; } cout<<in<<endl; Mat src = imread(in); Mat show_image=src; resize(show_image,show_image,Size(1000,1000),0,0); cvtColor(src,src,COLOR_BGR2GRAY); Mat src1 = src,src2 = src,src3 = src; Mat dst1, dst2, dst3; Mat image1,image2,image3; resize(src1,image1,Size(1000,1000),0,0); resize(src2,image2,Size(3000,3000),0,0); resize(src3,image3,Size(200,200),0,0); int flag; #if 0 Canny(image, image, 50, 200, 3); #endif #if 1 Ptr<LineSegmentDetector> ls1 = createLineSegmentDetector(LSD_REFINE_ADV); Ptr<LineSegmentDetector> ls2 = createLineSegmentDetector(LSD_REFINE_ADV); Ptr<LineSegmentDetector> ls3 = createLineSegmentDetector(LSD_REFINE_ADV); #else Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_NONE); #endif double start = double(getTickCount()); vector<Vec4f> lines_std1; vector<Vec4f> lines_std2; vector<Vec4f> lines_std3; vector<int> x_min,y_min,x_max,y_max; int x_min_f,y_min_f,x_max_f,y_max_f; ls1->detect(image1, lines_std1); ls2->detect(image2, lines_std2); ls3->detect(image3, lines_std3); int max1_x=-1,max1_y=-1,min1_x=10000,min1_y=10000; int max2_x=-1,max2_y=-1,min2_x=10000,min2_y=10000; int max3_x=-1,max3_y=-1,min3_x=10000,min3_y=10000; int count1 = lines_std1.size(); if (count1!=0) { for (int i = 0; i < count1; i++) { Vec4f p = lines_std1[i]; if (p[0] >= max1_x) { max1_x = p[0]; } if (p[2] >= max1_x) { max1_x = p[2]; } if (p[0] <= min1_x) { min1_x = p[0]; } if (p[2] <= min1_x) { min1_x = p[2]; } if (p[1] >= max1_y) { max1_y = p[1]; } if (p[3] >= max1_y) { max1_y = p[3]; } if (p[1] <= min1_y) { min1_y = p[1]; } if (p[3] <= min1_y) { min1_y = p[3]; } } } int count2 = lines_std2.size(); if (count2!=0) { for (int i = 0; i < count2; i++) { Vec4f p = lines_std2[i]; if (p[0] >= max2_x) { max2_x = p[0]; } if (p[2] >= max2_x) { max2_x = p[2]; } if (p[0] <= min2_x) { min2_x = p[0]; } if (p[2] <= min2_x) { min2_x = p[2]; } if (p[1] >= max2_y) { max2_y = p[1]; } if (p[3] >= max2_y) { max2_y = p[3]; } if (p[1] <= min2_y) { min2_y = p[1]; } if (p[3] <= min2_y) { min2_y = p[3]; } } } int count3 = lines_std3.size(); if (count3!=0) { for (int i = 0; i < count3; i++) { Vec4f p = lines_std3[i]; if (p[0] >= max3_x) { max3_x = p[0]; } if (p[2] >= max3_x) { max3_x = p[2]; } if (p[0] <= min3_x) { min3_x = p[0]; } if (p[2] <= min3_x) { min3_x = p[2]; } if (p[1] >= max3_y) { max3_y = p[1]; } if (p[3] >= max3_y) { max3_y = p[3]; } if (p[1] <= min3_y) { min3_y = p[1]; } if (p[3] <= min3_y) { min3_y = p[3]; } } } double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency(); std::cout << "It took " << duration_ms << " ms." << std::endl; Mat test; show_image.copyTo(test); if (max1_x!=-1){ x_min.push_back(min1_x); y_min.push_back(min1_y); x_max.push_back(max1_x); y_max.push_back(max1_y); } if (max2_x!=-1){ max2_x=max2_x/3.0;max2_y=max2_y/3.0;min2_x=min2_x/3.0;min2_y=min2_y/3.0; x_min.push_back(min2_x); y_min.push_back(min2_y); x_max.push_back(max2_x); y_max.push_back(max2_y); } if (max3_x!=-1){ max3_x=max3_x*5.0;max3_y=max3_y*5.0;min3_x=min3_x*5.0;min3_y=min3_y*5.0; x_min.push_back(min3_x); y_min.push_back(min3_y); x_max.push_back(max3_x); y_max.push_back(max3_y); } if (max1_x==-1 && max2_x==-1 && max3_x==-1){ cout<<"This image has no defect~~~~~~~~~~"<<endl; resize(image1,dst1,Size(500,500),0,0); putText(dst1,"No Defect",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); imshow("Result", dst1); } else{ cout<<"This image has defects!!!!!!!!"<<endl; x_min_f = find_min(x_min); y_min_f = find_min(y_min); x_max_f = find_max(x_max); y_max_f = find_max(y_max); flag = classify(image1,x_min_f,y_min_f,x_max_f,y_max_f); rectangle(test, Point((x_min_f-30)<0?10:(x_min_f-30),(y_min_f-30)<0?10:(y_min_f-30)), Point((x_max_f+30)>1000?990:(x_max_f+30),(y_max_f+30)>1000?990:(y_max_f+30)), Scalar(0, 0, 255), 2); resize(test,dst2,Size(700,700),0,0); if (flag==0){ if (max3_x!=-1){ putText(dst2,"scratch",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); } else { putText(dst2, "light leak", Point(50, 60), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 23, 0), 4, 8); } imshow("Result", dst2); } if (flag==1){ putText(dst2,"stain",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); imshow("Result", dst2); } } waitKey(0); destroyAllWindows(); } return 0; }
#include <iostream> #include <string> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv;
float mean_of_crop (Mat img, int x_min, int y_min, int x_max, int y_max,int thresh) { int start_x = x_min-30<0 ? x_min:x_min-30; int start_y = y_min-30<0 ? y_min:y_min-30; int end_x = x_max+30>thresh ? x_max:x_max+30; int end_y = y_max+30>thresh ? y_max:y_max+30; Mat img2; img.copyTo(img2); Mat crop = img2(Rect(start_x,start_y,end_x-start_x,end_y-start_y)); imshow("croped image",crop); Scalar small = mean( crop ); return small.val[0]+small.val[1]+small.val[2]; } int find_min (vector<int> vec) { int min =10000; for(int i=0;i<vec.size();++i){ if (vec[i]<=min) min=vec[i]; } return min; } int find_max (vector<int> vec) { int max = -1; for(int i=0;i<vec.size();++i){ if (vec[i]>=max) max=vec[i]; } return max; } int main(int argc, char** argv) { for (int i =5; i < 312; i++) { char path[256] = {0}; sprintf(path, "/Users/LiYisong/Desktop/SUEZ/Membrane/A/%d.bmp", i); string in; if (argc != 2) { in = path; } else { in = argv[1]; } cout<<in<<endl; Mat src = imread(in); Mat show_image=src; resize(show_image,show_image,Size(1000,1000),0,0); cvtColor(src,src,COLOR_BGR2GRAY); Mat src1 = src,src2 = src,src3 = src; Mat dst1, dst2, dst3; Mat image1,image2,image3; resize(src1,image1,Size(1000,1000),0,0); resize(src2,image2,Size(3000,3000),0,0); resize(src3,image3,Size(200,200),0,0); int flag; #if 0 Canny(image, image, 50, 200, 3); #endif #if 1 Ptr<LineSegmentDetector> ls1 = createLineSegmentDetector(LSD_REFINE_ADV); Ptr<LineSegmentDetector> ls2 = createLineSegmentDetector(LSD_REFINE_ADV); Ptr<LineSegmentDetector> ls3 = createLineSegmentDetector(LSD_REFINE_ADV); #else Ptr<LineSegmentDetector> ls = createLineSegmentDetector(LSD_REFINE_NONE); #endif double start = double(getTickCount()); vector<Vec4f> lines_std1; vector<Vec4f> lines_std2; vector<Vec4f> lines_std3; vector<int> x_min,y_min,x_max,y_max; int x_min_f,y_min_f,x_max_f,y_max_f; ls1->detect(image1, lines_std1); ls2->detect(image2, lines_std2); ls3->detect(image3, lines_std3); int max1_x=-1,max1_y=-1,min1_x=10000,min1_y=10000; int max2_x=-1,max2_y=-1,min2_x=10000,min2_y=10000; int max3_x=-1,max3_y=-1,min3_x=10000,min3_y=10000; int count1 = lines_std1.size(); if (count1!=0) { for (int i = 0; i < count1; i++) { Vec4f p = lines_std1[i]; if (p[0] >= max1_x) { max1_x = p[0]; } if (p[2] >= max1_x) { max1_x = p[2]; } if (p[0] <= min1_x) { min1_x = p[0]; } if (p[2] <= min1_x) { min1_x = p[2]; } if (p[1] >= max1_y) { max1_y = p[1]; } if (p[3] >= max1_y) { max1_y = p[3]; } if (p[1] <= min1_y) { min1_y = p[1]; } if (p[3] <= min1_y) { min1_y = p[3]; } } } int count2 = lines_std2.size(); if (count2!=0) { for (int i = 0; i < count2; i++) { Vec4f p = lines_std2[i]; if (p[0] >= max2_x) { max2_x = p[0]; } if (p[2] >= max2_x) { max2_x = p[2]; } if (p[0] <= min2_x) { min2_x = p[0]; } if (p[2] <= min2_x) { min2_x = p[2]; } if (p[1] >= max2_y) { max2_y = p[1]; } if (p[3] >= max2_y) { max2_y = p[3]; } if (p[1] <= min2_y) { min2_y = p[1]; } if (p[3] <= min2_y) { min2_y = p[3]; } } } int count3 = lines_std3.size(); if (count3!=0) { for (int i = 0; i < count3; i++) { Vec4f p = lines_std3[i]; if (p[0] >= max3_x) { max3_x = p[0]; } if (p[2] >= max3_x) { max3_x = p[2]; } if (p[0] <= min3_x) { min3_x = p[0]; } if (p[2] <= min3_x) { min3_x = p[2]; } if (p[1] >= max3_y) { max3_y = p[1]; } if (p[3] >= max3_y) { max3_y = p[3]; } if (p[1] <= min3_y) { min3_y = p[1]; } if (p[3] <= min3_y) { min3_y = p[3]; } } } double duration_ms = (double(getTickCount()) - start) * 1000 / getTickFrequency(); std::cout << "It took " << duration_ms << " ms." << std::endl; Mat test; show_image.copyTo(test); if (max1_x!=-1){ x_min.push_back(min1_x); y_min.push_back(min1_y); x_max.push_back(max1_x); y_max.push_back(max1_y); } if (max2_x!=-1){ max2_x=max2_x/3.0;max2_y=max2_y/3.0;min2_x=min2_x/3.0;min2_y=min2_y/3.0; x_min.push_back(min2_x); y_min.push_back(min2_y); x_max.push_back(max2_x); y_max.push_back(max2_y); } if (max3_x!=-1){ max3_x=max3_x*5.0;max3_y=max3_y*5.0;min3_x=min3_x*5.0;min3_y=min3_y*5.0; x_min.push_back(min3_x); y_min.push_back(min3_y); x_max.push_back(max3_x); y_max.push_back(max3_y); } if (max1_x==-1 && max2_x==-1 && max3_x==-1){ cout<<"This image has no defect~~~~~~~~~~"<<endl; resize(image1,dst1,Size(500,500),0,0); putText(dst1,"No Defect",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); imshow("Result", dst1); } else{ cout<<"This image has defects!!!!!!!!"<<endl; x_min_f = find_min(x_min); y_min_f = find_min(y_min); x_max_f = find_max(x_max); y_max_f = find_max(y_max); flag = classify(image1,x_min_f,y_min_f,x_max_f,y_max_f); rectangle(test, Point((x_min_f-30)<0?10:(x_min_f-30),(y_min_f-30)<0?10:(y_min_f-30)), Point((x_max_f+30)>1000?990:(x_max_f+30),(y_max_f+30)>1000?990:(y_max_f+30)), Scalar(0, 0, 255), 2); resize(test,dst2,Size(700,700),0,0); if (flag==0){ if (max3_x!=-1){ putText(dst2,"scratch",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); } else { putText(dst2, "light leak", Point(50, 60), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 23, 0), 4, 8); } imshow("Result", dst2); } if (flag==1){ putText(dst2,"stain",Point(50,60),FONT_HERSHEY_SIMPLEX,1,Scalar(255,23,0),4,8); imshow("Result", dst2); } } waitKey(0); destroyAllWindows(); } return 0; }
int classify (Mat img, int x_min, int y_min, int x_max, int y_max) { int flag=1; Mat img2; img.copyTo(img2); int width=((x_max+30)>1000?990:(x_max+30))-((x_min-30)<0?10:(x_min-30)); int height= ((y_max+30)>1000?990:(y_max+30))-((y_min-30)<0?10:(y_min-30)); Mat crop = img2(Rect((x_min-30)<0?10:(x_min-30),(y_min-30)<0?10:(y_min-30),width,height)); double max_big, min_big,max_small,min_small; cv::Point min_loc, max_loc; cv::minMaxLoc(img, &min_big, &max_big, &min_loc, &max_loc); cv::minMaxLoc(crop, &min_small, &max_small, &min_loc, &max_loc); cout<<max_big<<" "<<max_small<<endl; cout<<min_big<<" "<<min_small<<endl; if (abs(max_big-max_small)<0.01){ flag=0; }; return flag; }
function_block-full_function
[ { "content": "\n\n#endif\n\n\n\n/* For windows compilers MSVC and Intel we can determine\n\n the architecture of the compiler being used. This is because\n\n the compilers do not have flags that can change the architecture,\n\n but rather depend on which compiler is being used\n\n*/\n\n#if defined(_WIN32...
C++
Software/GoTender/Display.cpp
capiaghi/GoTender
539dc075b5e6ec5ee97a4e1400f2c0d17c0dd65d
#include "Display.h" static TFT TFTscreen = TFT(SPI_CS_LCD_PIN, DC_LCD_PIN, RESET_LCD_PIN); #define CHAR_ARRAY_LENGTH_TITLE ( 10 ) // Title length #define CHAR_ARRAY_LENGTH ( 30 ) #define XPOS_OVEN ( 40 ) #define XPOS_MEAT ( XPOS_OVEN + 40 ) #define XPOS_SMOKER ( XPOS_MEAT + 40 ) #define YPOS_LABELS ( 80 ) #define YPOS_SPACE ( 10 ) static uint8_t first = 1; static char charArray[CHAR_ARRAY_LENGTH]; static char charArrayTitle[CHAR_ARRAY_LENGTH_TITLE]; static char oldCharArray[CHAR_ARRAY_LENGTH] = ""; static uint16_t oldValue = -1; static uint8_t oldHour = -1; static uint8_t oldMin = -1; static int16_t oldTemperatureOven = -1; static int16_t oldTemperatureMeat = -1; static int16_t oldTemperatureOvenSetPoint = -1; static int16_t oldTemperatureMeatSetPoint = -1; static String oldCmd = ""; void initDisplay() { TFTscreen.begin(); TFTscreen.background(LCD_BACKGROUND_COLOR); } void displayTitle(String stateStr) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.background(LCD_BACKGROUND_COLOR); TFTscreen.setTextSize(MEDIUM_FONT_SIZE); stateStr.toCharArray(charArrayTitle, CHAR_ARRAY_LENGTH); TFTscreen.text(charArrayTitle, 0, 0); displayRefresh(); } void testDisplayOutput(uint16_t value) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(value), String(oldValue), 0, 50); oldValue = value; } void displayTime() { uint8_t hour = getTimeHour(); uint8_t min = getTimeMin(); if(hour != oldHour || min != oldMin) { String hourStr; String minStr; String oldHourStr; String oldMinStr; if( hour < 10) { hourStr = "0" + String(hour); oldHourStr = "0" + String(oldHour); } else { hourStr = String(hour); oldHourStr = String(oldHour); } if( min < 10) { minStr = "0" + String(min); oldMinStr = "0" + String(oldMin); } else { minStr = String(min); oldMinStr = String(oldMin); } String timeStr = hourStr + ":" + minStr; String oldTimeStr = oldHourStr + ":" + oldMinStr; TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(timeStr), String(oldTimeStr), 125, 0); oldHour = hour; oldMin = min; } } void displayDate() { uint8_t day = getTimeDay(); uint8_t month = getTimeMonth(); uint16_t year = getTimeYear(); String dateStr; String dayStr; String monthStr; if ( day < 10) { dayStr = "0" + String(day); } else { dayStr = String(day); } if ( month < 10) { monthStr = "0" + String(month); } else { monthStr = String(month); } dateStr = dayStr + "." + monthStr + "." + String(year); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(dateStr), String(""), 100, 120); } void displayCommand(String cmd) { TFTscreen.setTextSize(MEDIUM_FONT_SIZE); writeString(cmd, oldCmd, 0, 25); oldCmd = cmd.substring(0); } void displayCommandSmall1(String cmd) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(cmd, oldCmd, 0, 50); oldCmd = cmd.substring(0); } void displayCommandSmall2(String cmd) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(cmd, oldCmd, 0, 60); oldCmd = cmd.substring(0); } static void displayActualTemperature() { int16_t temperatureOven = getTemperatureOven(); int16_t temperatureMeat = getTemperatureMeat(); if((temperatureOven != oldTemperatureOven)) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureOven) + " C", String(oldTemperatureOven) + " C", XPOS_OVEN, YPOS_LABELS + YPOS_SPACE); oldTemperatureOven = temperatureOven; } if((temperatureMeat != oldTemperatureMeat)) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureMeat)+ " C", String(oldTemperatureMeat)+ " C", XPOS_MEAT, YPOS_LABELS + YPOS_SPACE); oldTemperatureMeat = temperatureMeat; } } static void displaySetPointTemperature() { int16_t temperatureOvenSetPoint = getTemperatureOvenSetPoint(); int16_t temperatureMeatSetPoint = getTemperatureMeatSetPoint(); if((temperatureOvenSetPoint != oldTemperatureOvenSetPoint)) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureOvenSetPoint)+ " C", String(oldTemperatureOvenSetPoint)+ " C", XPOS_OVEN, YPOS_LABELS + 2*YPOS_SPACE); oldTemperatureOvenSetPoint = temperatureOvenSetPoint; } if((temperatureMeatSetPoint != oldTemperatureMeatSetPoint)) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureMeatSetPoint)+ " C", String(oldTemperatureMeatSetPoint)+ " C", XPOS_MEAT, YPOS_LABELS + 2*YPOS_SPACE); oldTemperatureMeatSetPoint = temperatureMeatSetPoint; } } void displayRefresh() { first = 1; oldValue = -1; oldHour = -1; oldMin = -1; oldTemperatureOven = -1; oldTemperatureMeat = -1; oldTemperatureOvenSetPoint = -1; oldTemperatureMeatSetPoint = -1; oldCmd = ""; displaySmokerState(); displayDate(); displayTemperatures(); } void displayTemperatures() { if (first == 1) { TFTscreen.setTextSize(SMALL_FONT_SIZE); TFTscreen.text("Oven", XPOS_OVEN, YPOS_LABELS); TFTscreen.text("Meat", XPOS_MEAT, YPOS_LABELS); TFTscreen.text("Smoker", XPOS_SMOKER, YPOS_LABELS); TFTscreen.text("Now:", 0, YPOS_LABELS + YPOS_SPACE); TFTscreen.text("Set:", 0, YPOS_LABELS + 2*YPOS_SPACE); first = 0; } displayActualTemperature(); displaySetPointTemperature(); } void displaySmokerState() { if(getSmokerState()) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.fill(LCD_SMOKER_STATE_COLOR); TFTscreen.circle(XPOS_SMOKER + 10, YPOS_LABELS + 2*YPOS_SPACE, CIRCLE_RADIUS); } else { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.fill(LCD_BACKGROUND_COLOR); TFTscreen.circle(XPOS_SMOKER + 10, YPOS_LABELS + 2*YPOS_SPACE, CIRCLE_RADIUS); } } static void writeString(String text, String oldText, uint8_t xPos, uint8_t yPos) { text.toCharArray(charArray, CHAR_ARRAY_LENGTH); oldText.toCharArray(oldCharArray, CHAR_ARRAY_LENGTH); TFTscreen.stroke(INVERSE_LCD_FONT_COLOR); TFTscreen.text(oldCharArray, xPos, yPos); TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.text(charArray, xPos, yPos); }
#include "Display.h" static TFT TFTscreen = TFT(SPI_CS_LCD_PIN, DC_LCD_PIN, RESET_LCD_PIN); #define CHAR_ARRAY_LENGTH_TITLE ( 10 ) // Title length #define CHAR_ARRAY_LENGTH ( 30 ) #define XPOS_OVEN ( 40 ) #define XPOS_MEAT ( XPOS_OVEN + 40 ) #define XPOS_SMOKER ( XPOS_MEAT + 40 ) #define YPOS_LABELS ( 80 ) #define YPOS_SPACE ( 10 ) static uint8_t first = 1; static char charArray[CHAR_ARRAY_LENGTH]; static char charArrayTitle[CHAR_ARRAY_LENGTH_TITLE]; static char oldCharArray[CHAR_ARRAY_LENGTH] = ""; static uint16_t oldValue = -1; static uint8_t oldHour = -1; static uint8_t oldMin = -1; static int16_t oldTemperatureOven = -1; static int16_t oldTemperatureMeat = -1; static int16_t oldTemperatureOvenSetPoint = -1; static int16_t oldTemperatureMeatSetPoint = -1; static String oldCmd = ""; void initDisplay() { TFTscreen.begin(); TFTscreen.background(LCD_BACKGROUND_COLOR); } void displayTitle(String stateStr) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.background(LCD_BACKGROUND_COLOR); TFTscreen.setTextSize(MEDIUM_FONT_SIZE); stateStr.toCharArray(charArrayTitle, CHAR_ARRAY_LENGTH); TFTscreen.text(charArrayTitle, 0, 0); displayRefresh(); } void testDisplayOutput(uint16_t value) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(value), String(oldValue), 0, 50); oldValue = value; } void displayTime() { uint8_t hour = getTimeHour(); uint8_t min = getTimeMin(); if(hour != oldHour || min != oldMin) { String hourStr; String minStr; String oldHourStr; String oldMinStr; if( hour < 10) { hourStr = "0" + String(hour); oldHourStr = "0" + String(oldHour); } else { hourStr = String(hour); oldHourStr = String(oldHour); } if( min < 10) { minStr = "0" + String(min); oldMinStr = "0" + String(oldMin); } else { minStr = String(min); oldMinStr = String(oldMin); } String timeStr = hourStr + ":" + minStr; String oldTimeStr = oldHourStr + ":" + oldMinStr; TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(timeStr), String(oldTimeStr), 125, 0); oldHour = hour; oldMin = min; } } void displayDate() { uint8_t day = getTimeDay(); uint8_t month = getTimeMonth(); uint16_t year = getTimeYear(); String dateStr; String dayStr; String monthStr; if ( day < 10) { dayStr = "0" + String(day); } else { dayStr = String(day); } if ( month < 10) { monthStr = "0" + String(month); } else { monthStr = String(month); } dateStr = dayStr + "." + monthStr + "." + String(year); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(dateStr), String(""), 100, 120); } void displayCommand(String cmd) { TFTscreen.setTextSize(MEDIUM_FONT_SIZE); writeString(cmd, oldCmd, 0, 25); oldCmd = cmd.substring(0); } void displayCommandSmall1(String cmd) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(cmd, oldCmd, 0, 50); oldCmd = cmd.substring(0); } void displayCommandSmall2(String cmd) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(cmd, oldCmd, 0, 60); oldCmd = cmd.substring(0); } static void displayActualTemperature() { int16_t temperatureOven = getTemperatureOven(); int16_t temperatureMeat = getTemperatureMeat(); if((temperatureOven != oldTemperatureOven)) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureOven) + " C", String(oldTemperatureOven) + " C", XPOS_OVEN, YPOS_LABELS + YPOS_SPACE); oldTemperatureOven = temperatureOven; } if((temperatureMeat != oldTemperatureMeat)) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureMeat)+ " C", String(oldTemperatureMeat)+ " C", XPOS_MEAT, YPOS_LABELS + YPOS_SPACE); oldTemperatureMeat = temperatureMeat; } } static void displaySetPointTemperature() { int16_t temperatureOvenSetPoin
void displayRefresh() { first = 1; oldValue = -1; oldHour = -1; oldMin = -1; oldTemperatureOven = -1; oldTemperatureMeat = -1; oldTemperatureOvenSetPoint = -1; oldTemperatureMeatSetPoint = -1; oldCmd = ""; displaySmokerState(); displayDate(); displayTemperatures(); } void displayTemperatures() { if (first == 1) { TFTscreen.setTextSize(SMALL_FONT_SIZE); TFTscreen.text("Oven", XPOS_OVEN, YPOS_LABELS); TFTscreen.text("Meat", XPOS_MEAT, YPOS_LABELS); TFTscreen.text("Smoker", XPOS_SMOKER, YPOS_LABELS); TFTscreen.text("Now:", 0, YPOS_LABELS + YPOS_SPACE); TFTscreen.text("Set:", 0, YPOS_LABELS + 2*YPOS_SPACE); first = 0; } displayActualTemperature(); displaySetPointTemperature(); } void displaySmokerState() { if(getSmokerState()) { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.fill(LCD_SMOKER_STATE_COLOR); TFTscreen.circle(XPOS_SMOKER + 10, YPOS_LABELS + 2*YPOS_SPACE, CIRCLE_RADIUS); } else { TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.fill(LCD_BACKGROUND_COLOR); TFTscreen.circle(XPOS_SMOKER + 10, YPOS_LABELS + 2*YPOS_SPACE, CIRCLE_RADIUS); } } static void writeString(String text, String oldText, uint8_t xPos, uint8_t yPos) { text.toCharArray(charArray, CHAR_ARRAY_LENGTH); oldText.toCharArray(oldCharArray, CHAR_ARRAY_LENGTH); TFTscreen.stroke(INVERSE_LCD_FONT_COLOR); TFTscreen.text(oldCharArray, xPos, yPos); TFTscreen.stroke(LCD_FONT_COLOR); TFTscreen.text(charArray, xPos, yPos); }
t = getTemperatureOvenSetPoint(); int16_t temperatureMeatSetPoint = getTemperatureMeatSetPoint(); if((temperatureOvenSetPoint != oldTemperatureOvenSetPoint)) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureOvenSetPoint)+ " C", String(oldTemperatureOvenSetPoint)+ " C", XPOS_OVEN, YPOS_LABELS + 2*YPOS_SPACE); oldTemperatureOvenSetPoint = temperatureOvenSetPoint; } if((temperatureMeatSetPoint != oldTemperatureMeatSetPoint)) { TFTscreen.setTextSize(SMALL_FONT_SIZE); writeString(String(temperatureMeatSetPoint)+ " C", String(oldTemperatureMeatSetPoint)+ " C", XPOS_MEAT, YPOS_LABELS + 2*YPOS_SPACE); oldTemperatureMeatSetPoint = temperatureMeatSetPoint; } }
function_block-function_prefixed
[ { "content": "uint8_t getTimeMonth();\n", "file_path": "TimeControl.h", "rank": 0, "score": 59184.004231301966 }, { "content": "uint8_t getTimeDay();\n", "file_path": "TimeControl.h", "rank": 1, "score": 59184.004231301966 }, { "content": "uint16_t getTimeYear();\n", ...
C++
drivers/clock/rtc.cpp
IGR2014/kernale
a8b43cf7d89c3d92b14ffdb88683023048f4bf78
#include <arch/io.hpp> #include <drivers/clock/rtc.hpp> #include <klib/kprint.hpp> namespace igros::arch { constexpr auto CMOS_COMMAND = static_cast<io::port_t>(0x0070); constexpr auto CMOS_DATA = static_cast<io::port_t>(CMOS_COMMAND + 1U); void clockFromRTC(const rtcDateTime_t &rtcDateTime, const dword_t century, clockDateTime_t &dateTime) noexcept { dateTime.year = rtcDateTime.date.year + century; dateTime.month = rtcDateTime.date.month; dateTime.day = rtcDateTime.date.day; dateTime.weekday = rtcDateTime.weekday; dateTime.hour = rtcDateTime.time.hour; dateTime.minute = rtcDateTime.time.minute; dateTime.second = rtcDateTime.time.second; } constexpr auto RTC_YEAR = 0x09; constexpr auto RTC_MONTH = 0x08; constexpr auto RTC_DAY = 0x07; constexpr auto RTC_WEEKDAY = 0x06; constexpr auto RTC_HOUR = 0x04; constexpr auto RTC_MINUTE = 0x02; constexpr auto RTC_SECOND = 0x00; constexpr auto RTC_CENTURY = 0x32; constexpr auto RTC_REGISTER_A = 0x0A; constexpr auto RTC_REGISTER_B = 0x0B; constexpr auto RTC_IS_TIME_24 = 0x02; constexpr auto RTC_IS_BINARY = 0x04; byte_t rtcRead(const byte_t cmd) noexcept { io::get().writePort8(CMOS_COMMAND, cmd); return io::get().readPort8(CMOS_DATA); } void rtcReadDate(rtcDate_t &date) noexcept { date.year = rtcRead(RTC_YEAR); date.month = rtcRead(RTC_MONTH); date.day = rtcRead(RTC_DAY); } void rtcReadTime(rtcTime_t &time) noexcept { time.hour = rtcRead(RTC_HOUR); time.minute = rtcRead(RTC_MINUTE); time.second = rtcRead(RTC_SECOND); } void rtcReadDateTime(rtcDateTime_t &dateTime) noexcept { rtcReadDate(dateTime.date); rtcReadTime(dateTime.time); dateTime.weekday = rtcRead(RTC_WEEKDAY); } byte_t rtcFromBCD(const byte_t bcd) noexcept { return (bcd & 0x0F) + ((bcd >> 4) & 0x0F) * 10; } void rtcDateFromBCD(rtcDate_t &date) noexcept { date.year = rtcFromBCD(date.year); date.month = rtcFromBCD(date.month); date.day = rtcFromBCD(date.day); } void rtcTimeFromBCD(rtcTime_t &time) noexcept { time.hour = rtcFromBCD(time.hour); time.minute = rtcFromBCD(time.minute); time.second = rtcFromBCD(time.second); } void rtcDateTimeFromBCD(rtcDateTime_t &dateTime) noexcept { rtcDateFromBCD(dateTime.date); rtcTimeFromBCD(dateTime.time); } clockDateTime_t clockGetCurrentDateTime() noexcept { while (0x00 != (0x80 & rtcRead(RTC_REGISTER_A))); rtcDateTime_t rtcDateTime {}; rtcReadDateTime(rtcDateTime); const auto flags = rtcRead(RTC_REGISTER_B); auto century = rtcRead(RTC_CENTURY); if (0x00 == (flags & RTC_IS_BINARY)) { const auto hourModeBit = static_cast<byte_t>(rtcDateTime.time.hour & 0x80); rtcDateTime.time.hour &= 0x7F; rtcDateTimeFromBCD(rtcDateTime); rtcDateTime.time.hour |= hourModeBit; century = rtcFromBCD(century); } if ( (0x00 == (flags & RTC_IS_TIME_24)) && (0x00 != (0x80 & rtcDateTime.time.hour)) ) { rtcDateTime.time.hour = ((rtcDateTime.time.hour & 0x7F) + 12U) % 24U; } clockDateTime_t dateTime {}; clockFromRTC(rtcDateTime, ((0x00 != century) ? (century * 100U) : 2000U), dateTime); return dateTime; } void rtcSetup() noexcept { auto dateTime = clockGetCurrentDateTime(); klib::kprintf( "RTC date/time:\t%02d.%02d.%04d %02d:%02d:%02d\r\n", dateTime.day, dateTime.month, dateTime.year, dateTime.hour, dateTime.minute, dateTime.second ); } }
#include <arch/io.hpp> #include <drivers/clock/rtc.hpp> #include <klib/kprint.hpp> namespace igros::arch { constexpr auto CMOS_COMMAND = static_cast<io::port_t>(0x0070); constexpr auto CMOS_DATA = static_cast<io::port_t>(CMOS_COMMAND + 1U); void clockFromRTC(const rtcDateTime_t &rtcDateTime, const dword_t century, clockDateTime_t &dateTime) noexcept { dateTime.year = rtcDateTime.date.year + century; dateTime.month = rtcDateTime.date.month; dateTime.day = rtcDateTime.date.day; dateTime.weekday = rtcDateTime.weekday; dateTime.hour = rtcDateTime.time.hour; dateTime.minute = rtcDateTime.time.minute; dateTime.second = rtcDateTime.time.second; } constexpr auto RTC_YEAR = 0x09; constexpr auto RTC_MONTH = 0x08; constexpr auto RTC_DAY = 0x07; constexpr auto RTC_WEEKDAY = 0x06; constexpr auto RTC_HOUR = 0x04; constexpr auto RTC_MINUTE = 0x02; constexpr auto RTC_SECOND = 0x00; constexpr auto RTC_CENTURY = 0x32; constexpr auto RTC_REGISTER_A = 0x0A; constexpr auto RTC_REGISTER_B = 0x0B; constexpr auto RTC_IS_TIME_24 = 0x02; constexpr auto RTC_IS_BINARY = 0x04; byte_t rtcRead(const byte_t cmd) noexcept { io::get().writePort8(CMOS_COMMAND, cmd); return io::get().readPort8(CMOS_DATA); } void rtcReadDate(rtcDate_t &date) noexcept { date.year = rtcRead(RTC_YEAR); date.month = rtcRead(RTC_MONTH); date.day = rtcRead(RTC_DAY); } void rtcReadTime(rtcTime_t &time) noexcept { time.hour = rtcRead(RTC_HOUR); time.minute = rtcRead(RTC_MINUTE); time.second = rtcRead(RTC_SECOND); } void rtcReadDateTime(rtcDateTime_t &dateTime) noexcept { rtcReadDate(dateTime.date); rtcReadTime(dateTime.time); dateTime.weekday = rtcRead(RTC_WEEKDAY); } byte_t rtcFromBCD(const byte_t bcd) noexcept { return (bcd & 0x0F) + ((bcd >> 4) & 0x0F) * 10; } void rtcDateFromBCD(rtcDate_t &date) noexcept { date.year = rtcFromBCD(date.year); date.month = rtcFromBCD(date.month); date.day = rtcFromBCD(date.day); } void rtcTimeFromBCD(rtcTime_t &time) noexcept { time.hour = rtcFromBCD(time.hour); time.minute = rtcFromBCD(time.minute); time.second = rtcFromBCD(time.second); } void rtcDateTimeFromBCD(rtcDateTime_t &dateTime) noexcept { rtcDateFromBCD(dateTime.date); rtcTimeFromBCD(dateTime.time); } clockDateTime_t clockGetCurrentDateTime() noexcept { while (0x00 != (0x80 & rtcRead(RTC_REGISTER_A))); rtcDateTime_t rtcDateTime {}; rtcReadDateTime(rtcDateTime); const auto flags = rtcRead(RTC_REGISTER_B); auto century = rtcRead(RTC_CENTURY);
if ( (0x00 == (flags & RTC_IS_TIME_24)) && (0x00 != (0x80 & rtcDateTime.time.hour)) ) { rtcDateTime.time.hour = ((rtcDateTime.time.hour & 0x7F) + 12U) % 24U; } clockDateTime_t dateTime {}; clockFromRTC(rtcDateTime, ((0x00 != century) ? (century * 100U) : 2000U), dateTime); return dateTime; } void rtcSetup() noexcept { auto dateTime = clockGetCurrentDateTime(); klib::kprintf( "RTC date/time:\t%02d.%02d.%04d %02d:%02d:%02d\r\n", dateTime.day, dateTime.month, dateTime.year, dateTime.hour, dateTime.minute, dateTime.second ); } }
if (0x00 == (flags & RTC_IS_BINARY)) { const auto hourModeBit = static_cast<byte_t>(rtcDateTime.time.hour & 0x80); rtcDateTime.time.hour &= 0x7F; rtcDateTimeFromBCD(rtcDateTime); rtcDateTime.time.hour |= hourModeBit; century = rtcFromBCD(century); }
if_condition
[ { "content": "\t// Multiboot header flags enumeration\n\n\tenum class flags_t : dword_t {\n\n\t\tMEM\t\t= (1U << 0),\t\t\t// Memory info available\n\n\t\tBOOT_DEV\t= (1U << 1),\t\t\t// Boot device info available\n\n\t\tCMD\t\t= (1U << 2),\t\t\t// Kernel command line available\n\n\t\tMODULES\t\t= (1U << 3),\t\t\...
C++
Source/PsData/Private/Types/PsData_FPsDataBigInteger.cpp
Antonrr/PsData
ccf501aef6821a73b2cee7fb11e42e3f7fff303c
#include "Types/PsData_FPsDataBigInteger.h" #define ZERO_DIVIDE_PROTECTION(Dividend, Divisor) \ if (Divisor == 0) \ { \ FFrame::KismetExecutionMessage(*FString::Printf(TEXT("Divide by zero detected: %s / 0\n%s"), *Dividend.ToString(), *FFrame::GetScriptCallstack()), ELogVerbosity::Warning); \ return 0; \ } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigInteger(int64 Value) { return {Value}; } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigIntegerFromInt(int32 Value) { return {Value}; } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigIntegerFromString(FString Value, EPsDataBigIntegerConvertionType ConvertionType) { return FPsDataBigInteger::FromString(Value, ConvertionType); } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply(FPsDataBigInteger A, FPsDataBigInteger B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide(FPsDataBigInteger A, FPsDataBigInteger B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add(FPsDataBigInteger A, FPsDataBigInteger B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract(FPsDataBigInteger A, FPsDataBigInteger B) { return A - B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Modulo(FPsDataBigInteger A, FPsDataBigInteger B) { ZERO_DIVIDE_PROTECTION(A, B); return A % B; } bool UPsDataBigIntegerLibrary::Less(FPsDataBigInteger A, FPsDataBigInteger B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater(FPsDataBigInteger A, FPsDataBigInteger B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal(FPsDataBigInteger A, FPsDataBigInteger B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And(FPsDataBigInteger A, FPsDataBigInteger B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor(FPsDataBigInteger A, FPsDataBigInteger B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or(FPsDataBigInteger A, FPsDataBigInteger B) { return A | B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Not(FPsDataBigInteger A) { return ~A; } FPsDataBigInteger UPsDataBigIntegerLibrary::Sign(FPsDataBigInteger A) { if (A.IsZero()) { return FPsDataBigInteger::Zero; } return A.GetSign(); } FPsDataBigInteger UPsDataBigIntegerLibrary::Min(FPsDataBigInteger A, FPsDataBigInteger B) { if (A < B) { return A; } return B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Max(FPsDataBigInteger A, FPsDataBigInteger B) { if (A > B) { return A; } return B; } bool UPsDataBigIntegerLibrary::InRange(FPsDataBigInteger Value, FPsDataBigInteger Min, FPsDataBigInteger Max, bool InclusiveMin, bool InclusiveMax) { const auto CompMin = FPsDataBigInteger::Compare(Min, Value); const auto CompMax = FPsDataBigInteger::Compare(Value, Max); if (CompMin < 0 && CompMax > 0) { return true; } if (InclusiveMin && CompMin == 0) { return true; } if (InclusiveMax && CompMax == 0) { return true; } return false; } FPsDataBigInteger UPsDataBigIntegerLibrary::Clamp(FPsDataBigInteger Value, FPsDataBigInteger Min, FPsDataBigInteger Max) { if (Min > Value) { return Min; } if (Max < Value) { return Max; } return Value; } FPsDataBigInteger UPsDataBigIntegerLibrary::Abs(FPsDataBigInteger A) { A.Abs(); return A; } bool UPsDataBigIntegerLibrary::Bit(FPsDataBigInteger A, int32 BitIndex) { return A.GetBit(BitIndex); } FPsDataShortBigInteger UPsDataBigIntegerLibrary::ToShortBigInteger(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToShortBigInteger(18); } int32 UPsDataBigIntegerLibrary::ToInt(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToInt32(); } int32 UPsDataBigIntegerLibrary::ToInt64(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToInt64(); } FPsDataBigInteger UPsDataBigIntegerLibrary::Int32ToBigInteger(const int32& InInt) { return {InInt}; } FPsDataBigInteger UPsDataBigIntegerLibrary::Int64ToBigInteger(const int64& InInt) { return {InInt}; } FString UPsDataBigIntegerLibrary::ToString(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToString(); } FPsDataBigInteger UPsDataBigIntegerLibrary::StringToBigInteger(const FString& InString) { return FPsDataBigInteger::FromString(InString); } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply_Int32(FPsDataBigInteger A, int32 B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide_Int32(FPsDataBigInteger A, int32 B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add_Int32(FPsDataBigInteger A, int32 B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract_Int32(FPsDataBigInteger A, int32 B) { return A - B; } int32 UPsDataBigIntegerLibrary::Modulo_Int32(FPsDataBigInteger A, int32 B) { ZERO_DIVIDE_PROTECTION(A, B); return (A % B).ToInt32(); } bool UPsDataBigIntegerLibrary::Less_Int32(FPsDataBigInteger A, int32 B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater_Int32(FPsDataBigInteger A, int32 B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual_Int32(FPsDataBigInteger A, int32 B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual_Int32(FPsDataBigInteger A, int32 B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal_Int32(FPsDataBigInteger A, int32 B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual_Int32(FPsDataBigInteger A, int32 B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And_Int32(FPsDataBigInteger A, int32 B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor_Int32(FPsDataBigInteger A, int32 B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or_Int32(FPsDataBigInteger A, int32 B) { return A | B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply_Int64(FPsDataBigInteger A, int64 B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide_Int64(FPsDataBigInteger A, int64 B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add_Int64(FPsDataBigInteger A, int64 B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract_Int64(FPsDataBigInteger A, int64 B) { return A - B; } int64 UPsDataBigIntegerLibrary::Modulo_Int64(FPsDataBigInteger A, int64 B) { ZERO_DIVIDE_PROTECTION(A, B); return (A % B).ToInt64(); } bool UPsDataBigIntegerLibrary::Less_Int64(FPsDataBigInteger A, int64 B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater_Int64(FPsDataBigInteger A, int64 B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual_Int64(FPsDataBigInteger A, int64 B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual_Int64(FPsDataBigInteger A, int64 B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal_Int64(FPsDataBigInteger A, int64 B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual_Int64(FPsDataBigInteger A, int64 B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And_Int64(FPsDataBigInteger A, int64 B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor_Int64(FPsDataBigInteger A, int64 B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or_Int64(FPsDataBigInteger A, int64 B) { return A | B; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetMapProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TMAP_REF(FString, FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<TMap<FString, FPsDataBigInteger>>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetMapProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TMAP_REF(FString, FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; TMap<FString, FPsDataBigInteger>* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetArrayProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TARRAY_REF(FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<TArray<FPsDataBigInteger>>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetArrayProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TARRAY_REF(FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; TArray<FPsDataBigInteger>* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_STRUCT_REF(FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<FPsDataBigInteger>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_STRUCT_REF(FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; FPsDataBigInteger* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; } void UPsDataBigIntegerLibrary::TypeSerialize(const UPsData* const Instance, const TSharedPtr<const FDataField>& Field, FPsDataSerializer* Serializer, const FPsDataBigInteger& Value) { Serializer->WriteValue(Value.ToString()); } FPsDataBigInteger UPsDataBigIntegerLibrary::TypeDeserialize(const UPsData* const Instance, const TSharedPtr<const FDataField>& Field, FPsDataDeserializer* Deserializer, const FPsDataBigInteger& Value) { FString StringValue; if (Deserializer->ReadValue(StringValue)) { auto a = FPsDataBigInteger(StringValue); return a; } int64 Int64Value = 0; if (Deserializer->ReadValue(Int64Value)) { return Int64Value; } int32 Int32Value = 0; if (Deserializer->ReadValue(Int32Value)) { return Int32Value; } UE_LOG(LogData, Warning, TEXT("Can't deserialize \"%s::%s\" as \"%s\""), *Instance->GetClass()->GetName(), *Field->Name, *PsDataTools::FType<FPsDataBigInteger>::Type()); return Value; }
#include "Types/PsData_FPsDataBigInteger.h" #define ZERO_DIVIDE_PROTECTION(Dividend, Divisor) \ if (Divisor == 0) \ { \ FFrame::KismetExecutionMessage(*FString::Printf(TEXT("Divide by zero detected: %s / 0\n%s"), *Dividend.ToString(), *FFrame::GetScriptCallstack()), ELogVerbosity::Warning); \ return 0; \ } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigInteger(int64 Value) { return {Value}; } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigIntegerFromInt(int32 Value) { return {Value}; } FPsDataBigInteger UPsDataBigIntegerLibrary::MakeLiteralBigIntegerFromString(FString Value, EPsDataBigIntegerConvertionType ConvertionType) { return FPsDataBigInteger::FromString(Value, ConvertionType); } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply(FPsDataBigInteger A, FPsDataBigInteger B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide(FPsDataBigInteger A, FPsDataBigInteger B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add(FPsDataBigInteger A, FPsDataBigInteger B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract(FPsDataBigInteger A, FPsDataBigInteger B) { return A - B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Modulo(FPsDataBigInteger A, FPsDataBigInteger B) { ZERO_DIVIDE_PROTECTION(A, B); return A % B; } bool UPsDataBigIntegerLibrary::Less(FPsDataBigInteger A, FPsDataBigInteger B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater(FPsDataBigInteger A, FPsDataBigInteger B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal(FPsDataBigInteger A, FPsDataBigInteger B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual(FPsDataBigInteger A, FPsDataBigInteger B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And(FPsDataBigInteger A, FPsDataBigInteger B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor(FPsDataBigInteger A, FPsDataBigInteger B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or(FPsDataBigInteger A, FPsDataBigInteger B) { return A | B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Not(FPsDataBigInteger A) { return ~A; } FPsDataBigInteger UPsDataBigIntegerLibrary::Sign(FPsDataBigInteger A) { if (A.IsZero()) { return FPsDataBigInteger::Zero; } return A.GetSign(); } FPsDataBigInteger UPsDataBigIntegerLibrary::Min(FPsDataBigInteger A, FPsDataBigInteger B) { if (A < B) { return A; } return B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Max(FPsDataBigInteger A, FPsDataBigInteger B) { if (A > B) { return A; } return B; } bool UPsDataBigIntegerLibrary::InRange(FPsDataBigInteger Value, FPsDataBigInteger Min, FPsDataBigInteger Max, bool InclusiveMin, bool InclusiveMax) { const auto CompMin = FPsDataBigInteger::Compare(Min, Value); const auto CompMax = FPsDataBigInteger::Compare(Value, Max); if (CompMin < 0 && CompMax > 0) { return true; } if (InclusiveMin && CompMin == 0) { return true; } if (InclusiveMax && CompMax == 0) { return true; } return false; } FPsDataBigInteger UPsDataBigIntegerLibrary::Clamp(FPsDataBigInteger Value, FPsDataBigInteger Min, FPsDataBigInteger Max) { if (Min > Value) { return Min; } if (Max < Value) { return Max; } return Value; } FPsDataBigInteger UPsDataBigIntegerLibrary::Abs(FPsDataBigInteger A) { A.Abs(); return A; } bool UPsDataBigIntegerLibrary::Bit(FPsDataBigInteger A, int32 BitIndex) { return A.GetBit(BitIndex); } FPsDataShortBigInteger UPsDataBigIntegerLibrary::ToShortBigInteger(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToShortBigInteger(18); } int32 UPsDataBigIntegerLibrary::ToInt(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToInt32(); } int32 UPsDataBigIntegerLibrary::ToInt64(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToInt64(); } FPsDataBigInteger UPsDataBigIntegerLibrary::Int32ToBigInteger(const int32& InInt) { return {InInt}; } FPsDataBigInteger UPsDataBigIntegerLibrary::Int64ToBigInteger(const int64& InInt) { return {InInt}; } FString UPsDataBigIntegerLibrary::ToString(const FPsDataBigInteger& InBigInteger) { return InBigInteger.ToString(); } FPsDataBigInteger UPsDataBigIntegerLibrary::StringToBigInteger(const FString& InString) { return FPsDataBigInteger::FromString(InString); } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply_Int32(FPsDataBigInteger A, int32 B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide_Int32(FPsDataBigInteger A, int32 B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add_Int32(FPsDataBigInteger A, int32 B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract_Int32(FPsDataBigInteger A, int32 B) { return A - B; } int32 UPsDataBigIntegerLibrary::Modulo_Int32(FPsDataBigInteger A, int32 B) { ZERO_DIVIDE_PROTECTION(A, B); return (A % B).ToInt32(); } bool UPsDataBigIntegerLibrary::Less_Int32(FPsDataBigInteger A, int32 B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater_Int32(FPsDataBigInteger A, int32 B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual_Int32(FPsDataBigInteger A, int32 B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual_Int32(FPsDataBigInteger A, int32 B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal_Int32(FPsDataBigInteger A, int32 B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual_Int32(FPsDataBigInteger A, int32 B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And_Int32(FPsDataBigInteger A, int32 B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor_Int32(FPsDataBigInteger A, int32 B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or_Int32(FPsDataBigInteger A, int32 B) { return A | B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Multiply_Int64(FPsDataBigInteger A, int64 B) { return A * B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Divide_Int64(FPsDataBigInteger A, int64 B) { ZERO_DIVIDE_PROTECTION(A, B); return A / B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Add_Int64(FPsDataBigInteger A, int64 B) { return A + B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Subtract_Int64(FPsDataBigInteger A, int64 B) { return A - B; } int64 UPsDataBigIntegerLibrary::Modulo_Int64(FPsDataBigInteger A, int64 B) { ZERO_DIVIDE_PROTECTION(A, B); return (A % B).ToInt64(); } bool UPsDataBigIntegerLibrary::Less_Int64(FPsDataBigInteger A, int64 B) { return A < B; } bool UPsDataBigIntegerLibrary::Greater_Int64(FPsDataBigInteger A, int64 B) { return A > B; } bool UPsDataBigIntegerLibrary::LessEqual_Int64(FPsDataBigInteger A, int64 B) { return A <= B; } bool UPsDataBigIntegerLibrary::GreaterEqual_Int64(FPsDataBigInteger A, int64 B) { return A >= B; } bool UPsDataBigIntegerLibrary::Equal_Int64(FPsDataBigInteger A, int64 B) { return A == B; } bool UPsDataBigIntegerLibrary::NotEqual_Int64(FPsDataBigInteger A, int64 B) { return A != B; } FPsDataBigInteger UPsDataBigIntegerLibrary::And_Int64(FPsDataBigInteger A, int64 B) { return A & B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Xor_Int64(FPsDataBigInteger A, int64 B) { return A ^ B; } FPsDataBigInteger UPsDataBigIntegerLibrary::Or_Int64(FPsDataBigInteger A, int64 B) { return A | B; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetMapProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TMAP_REF(FString, FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<TMap<FString, FPsDataBigInteger>>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetMapProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index);
DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetArrayProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TARRAY_REF(FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<TArray<FPsDataBigInteger>>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetArrayProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_TARRAY_REF(FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; TArray<FPsDataBigInteger>* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execSetProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_STRUCT_REF(FPsDataBigInteger, Value); P_FINISH; P_NATIVE_BEGIN; PsDataTools::UnsafeSetByIndex<FPsDataBigInteger>(Target, Index, Value); P_NATIVE_END; } DEFINE_FUNCTION(UPsDataBigIntegerLibrary::execGetProperty) { P_GET_OBJECT(UPsData, Target); P_GET_PROPERTY(FIntProperty, Index); P_GET_STRUCT_REF(FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; FPsDataBigInteger* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; } void UPsDataBigIntegerLibrary::TypeSerialize(const UPsData* const Instance, const TSharedPtr<const FDataField>& Field, FPsDataSerializer* Serializer, const FPsDataBigInteger& Value) { Serializer->WriteValue(Value.ToString()); } FPsDataBigInteger UPsDataBigIntegerLibrary::TypeDeserialize(const UPsData* const Instance, const TSharedPtr<const FDataField>& Field, FPsDataDeserializer* Deserializer, const FPsDataBigInteger& Value) { FString StringValue; if (Deserializer->ReadValue(StringValue)) { auto a = FPsDataBigInteger(StringValue); return a; } int64 Int64Value = 0; if (Deserializer->ReadValue(Int64Value)) { return Int64Value; } int32 Int32Value = 0; if (Deserializer->ReadValue(Int32Value)) { return Int32Value; } UE_LOG(LogData, Warning, TEXT("Can't deserialize \"%s::%s\" as \"%s\""), *Instance->GetClass()->GetName(), *Field->Name, *PsDataTools::FType<FPsDataBigInteger>::Type()); return Value; }
P_GET_TMAP_REF(FString, FPsDataBigInteger, Out); P_FINISH; P_NATIVE_BEGIN; TMap<FString, FPsDataBigInteger>* Result = nullptr; PsDataTools::UnsafeGetByIndex(Target, Index, Result); Out = *Result; P_NATIVE_END; }
function_block-function_prefix_line
[ { "content": "struct FDataTypeContext<TMap<FString, int64>> : public FDataTypeContextExtended<TMap<FString, int64>, UPsDataInt64Library>\n\n{\n\n};\n\n\n\ntemplate <>\n", "file_path": "Source/PsData/Public/Types/PsData_int64.h", "rank": 0, "score": 119259.96767205576 }, { "content": "struct ...
C++
include/natpp/detail/impl/natpmp_service.ipp
mandreyel/nat-
4f4ab3b1f59f389ea3e38ca7d5589073fd4e3ffa
#ifndef NATPP_NATPMP_SERVICE_IMPL #define NATPP_NATPMP_SERVICE_IMPL #include "../natpmp_service.hpp" #include "../../gateway.hpp" #include <cassert> #include <endian/endian.hpp> #include <asio/socket_base.hpp> #include <asio/buffer.hpp> namespace nat { namespace detail { enum opcode { public_address = 0, udp_mapping = 1, tcp_mapping = 2, }; natpmp_service::natpmp_service(asio::io_context& ios) : asio::io_context::service(ios) , socket_(ios) { error_code ec; auto gateway_address = default_gateway_address(ec); gateway_endpoint_ = asio::ip::udp::endpoint(gateway_address, 5351); socket_.connect(gateway_endpoint_, ec); if(ec) { socket_.close(ec); return; } socket_.set_option(asio::ip::udp::socket::reuse_address(true), ec); if(ec) { socket_.close(ec); return; } } void natpmp_service::shutdown() { } inline asio::const_buffer prep_public_address_request_message(char* buffer) { buffer[0] = 0; buffer[1] = 0; return asio::buffer(buffer, 2); } inline void verify_response_header(const char* buffer, int opcode, error_code& error) { const auto errc = endian::read<endian::order::network, uint16_t>(&buffer[2]); if(errc > 5) { error = make_error_code(error::natpmp::unknown_error); } else { error = make_error_code(static_cast<error::natpmp>(errc)); } if(error) { return; } if(buffer[0] != 0) { error = make_error_code(error::natpmp::unsupported_version); return; } if(static_cast<uint8_t>(buffer[1]) != 128 + opcode) { error = make_error_code(error::natpmp::invalid_opcode); return; } } inline asio::ip::address parse_public_address_response( const char* buffer, error_code& error) { verify_response_header(buffer, opcode::public_address, error); if(error) { return {}; } return asio::ip::address_v4(endian::read<endian::order::network, uint32_t>(&buffer[8])); } asio::ip::address natpmp_service::public_address( implementation_type& impl, error_code& error) { error = error_code(); if(public_address_ != asio::ip::address()) { return public_address_; } if(pending_requests_.empty()) { const auto num_sent = socket_.send( prep_public_address_request_message(send_buffer_.data()), 0, error); if(error) { return {}; } if(num_sent < 2) { error = std::make_error_code(std::errc::bad_message); return {}; } const auto num_received = socket_.receive(asio::buffer(receive_buffer_), 0, error); if(error) { return {}; } if(num_received < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } error = error_code(); return parse_public_address_response(receive_buffer_.data(), error); } else { error = make_error_code(asio::error::try_again); return {}; } } void natpmp_service::async_public_address_impl() { socket_.async_send(prep_public_address_request_message(send_buffer_.data()), [this](const auto& error, const auto num_sent) { if(!error && num_sent == 2) { return; } auto request = pop_current_request<address_request>(); if(error) { request.handler(error, {}); } else if(num_sent != 2) { request.handler(std::make_error_code(std::errc::bad_message), {}); } if(!pending_requests_.empty()) { execute_request(); } }); socket_.async_receive(asio::buffer(receive_buffer_), [this](auto error, const auto num_received) { auto request = pop_current_request<address_request>(); if(error) { request.handler(error, {}); return; } else if(num_received < 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); return; } request.handler(error, parse_public_address_response( receive_buffer_.data(), error)); if(!pending_requests_.empty()) { execute_request(); } }); } template<typename Handler> void natpmp_service::async_public_address(implementation_type& impl, Handler handler) { if(public_address_ != asio::ip::address()) { asio::post(socket_.get_executor(), [handler = std::move(handler), addr = public_address_] { handler({}, addr); }); } else { pending_requests_.emplace_back(pending_request{ address_request{std::move(handler)}, impl}); if(pending_requests_.size() == 1) { async_public_address_impl(); } } } inline asio::const_buffer prep_mapping_request_message( char* buffer, const port_mapping& mapping) { buffer[0] = 0; if(mapping.type == port_mapping::udp) { buffer[1] = opcode::udp_mapping; } else { buffer[1] = opcode::tcp_mapping; } buffer[2] = 0; buffer[3] = 0; endian::write<endian::order::network, uint16_t>(mapping.private_port, &buffer[4]); endian::write<endian::order::network, uint16_t>(mapping.public_port, &buffer[6]); endian::write<endian::order::network, uint32_t>(mapping.duration.count(), &buffer[8]); return asio::buffer(buffer, 12); } inline port_mapping parse_mapping_response(const char* buffer, int opcode, error_code& error) { verify_response_header(buffer, opcode, error); if(error) { return {}; } port_mapping mapping; mapping.private_port = endian::read<endian::order::network, uint16_t>(&buffer[8]); mapping.public_port = endian::read<endian::order::network, uint16_t>(&buffer[10]); mapping.duration = std::chrono::seconds( endian::read<endian::order::network, uint32_t>(&buffer[12])); return mapping; } port_mapping natpmp_service::request_mapping(implementation_type& impl, const port_mapping& request, error_code& error) { if(pending_requests_.empty()) { error = error_code(); const auto num_sent = socket_.send(prep_mapping_request_message( send_buffer_.data(), request), 0, error); if(error) { return {}; } if(num_sent < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } const auto num_received = socket_.receive(asio::buffer(receive_buffer_), 0, error); if(error) { return {}; } if(num_received < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } auto mapping = parse_mapping_response(receive_buffer_.data(), request.type == port_mapping::udp ? opcode::udp_mapping : opcode::tcp_mapping, error); if(!error) { impl.mappings.push_back(mapping); } return mapping; } else { error = make_error_code(asio::error::try_again); return {}; } } void natpmp_service::async_request_mapping_impl() { assert(!pending_requests_.empty()); assert(std::holds_alternative<mapping_request>(pending_requests_.front().data)); const auto& request = std::get<mapping_request>(pending_requests_.front().data); socket_.async_send(prep_mapping_request_message( send_buffer_.data(), request.mapping), [this](const auto& error, const auto num_sent) { if(!error && num_sent == 12) { return; } auto request = pop_current_request<mapping_request>(); if(error) { request.handler(error, {}); } else if(num_sent != 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); } if(!pending_requests_.empty()) { execute_request(); } }); socket_.async_receive(asio::buffer(receive_buffer_), [this](auto error, const auto num_received) { assert(!pending_requests_.empty()); auto& impl = pending_requests_.front().impl; auto request = pop_current_request<mapping_request>(); if(error) { request.handler(error, {}); return; } else if(num_received < 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); return; } auto mapping = parse_mapping_response(receive_buffer_.data(), request.mapping.type == port_mapping::udp ? opcode::udp_mapping : opcode::tcp_mapping, error); if(!error) { impl.mappings.push_back(mapping); } request.handler(error, mapping); if(!pending_requests_.empty()) { execute_request(); } }); } template<typename Handler> void natpmp_service::async_request_mapping(implementation_type& impl, const port_mapping& mapping, Handler handler) { pending_requests_.emplace_back(pending_request{mapping_request{mapping, std::move(handler)}, impl}); if(pending_requests_.size() == 1) { async_public_address_impl(); } } void natpmp_service::async_remove_mapping_impl() { async_request_mapping_impl(); } void natpmp_service::remove_mapping(implementation_type& impl, const port_mapping& mapping, error_code& error) { auto request = mapping; request.duration = std::chrono::seconds(0); request.public_port = 0; request_mapping(impl, request, error); } template<typename Handler> void natpmp_service::async_remove_mapping(implementation_type& impl, const port_mapping& mapping, Handler handler) { auto request = mapping; request.duration = std::chrono::seconds(0); request.public_port = 0; async_request_mapping(impl, request, std::move(handler)); } void natpmp_service::execute_request() { assert(!pending_requests_.empty()); const auto& curr_req = pending_requests_.front(); if(std::holds_alternative<address_request>(curr_req.data)) { async_public_address_impl(); } else { const auto& request = std::get<mapping_request>(curr_req.data); if(is_remove_mapping_request(request.mapping)) { async_remove_mapping_impl(); } else { async_request_mapping_impl(); } } } template<typename Request> Request natpmp_service::pop_current_request() { assert(!pending_requests_.empty()); auto curr_req = std::move(pending_requests_.front()); pending_requests_.pop_front(); assert(std::holds_alternative<Request>(curr_req.data)); return std::move(std::get<Request>(curr_req.data)); } } } #endif
#ifndef NATPP_NATPMP_SERVICE_IMPL #define NATPP_NATPMP_SERVICE_IMPL #include "../natpmp_service.hpp" #include "../../gateway.hpp" #include <cassert> #include <endian/endian.hpp> #include <asio/socket_base.hpp> #include <asio/buffer.hpp> namespace nat { namespace detail { enum opcode { public_address = 0, udp_mapping = 1, tcp_mapping = 2, }; natpmp_service::natpmp_service(asio::io_context& ios) : asio::io_context::service(ios) , socket_(ios) { error_code ec; auto gateway_address = default_gateway_address(ec); gateway_endpoint_ = asio::ip::udp::endpoint(gateway_address, 5351); socket_.connect(gateway_endpoint_, ec); if(ec) { socket_.close(ec); return; } socket_.set_option(asio::ip::udp::socket::reuse_address(true), ec); if(ec) { socket_.close(ec); return; } } void natpmp_service::shutdown() { } inline asio::const_buffer prep_public_address_request_message(char* buffer) { buffer[0] = 0; buffer[1] = 0; return asio::buffer(buffer, 2); } inline void verify_response_header(const char* buffer, int opcode, error_code& error) { const auto errc = endian::read<endian::order::network, uint16_t>(&buffer[2]); if(errc > 5) { error = make_error_code(error::natpmp::unknown_error); } else { error = make_error_code(static_cast<error::natpmp>(errc)); } if(error) { return; } if(buffer[0] != 0) { error = make_error_code(error::natpmp::unsupported_version); return; }
} inline asio::ip::address parse_public_address_response( const char* buffer, error_code& error) { verify_response_header(buffer, opcode::public_address, error); if(error) { return {}; } return asio::ip::address_v4(endian::read<endian::order::network, uint32_t>(&buffer[8])); } asio::ip::address natpmp_service::public_address( implementation_type& impl, error_code& error) { error = error_code(); if(public_address_ != asio::ip::address()) { return public_address_; } if(pending_requests_.empty()) { const auto num_sent = socket_.send( prep_public_address_request_message(send_buffer_.data()), 0, error); if(error) { return {}; } if(num_sent < 2) { error = std::make_error_code(std::errc::bad_message); return {}; } const auto num_received = socket_.receive(asio::buffer(receive_buffer_), 0, error); if(error) { return {}; } if(num_received < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } error = error_code(); return parse_public_address_response(receive_buffer_.data(), error); } else { error = make_error_code(asio::error::try_again); return {}; } } void natpmp_service::async_public_address_impl() { socket_.async_send(prep_public_address_request_message(send_buffer_.data()), [this](const auto& error, const auto num_sent) { if(!error && num_sent == 2) { return; } auto request = pop_current_request<address_request>(); if(error) { request.handler(error, {}); } else if(num_sent != 2) { request.handler(std::make_error_code(std::errc::bad_message), {}); } if(!pending_requests_.empty()) { execute_request(); } }); socket_.async_receive(asio::buffer(receive_buffer_), [this](auto error, const auto num_received) { auto request = pop_current_request<address_request>(); if(error) { request.handler(error, {}); return; } else if(num_received < 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); return; } request.handler(error, parse_public_address_response( receive_buffer_.data(), error)); if(!pending_requests_.empty()) { execute_request(); } }); } template<typename Handler> void natpmp_service::async_public_address(implementation_type& impl, Handler handler) { if(public_address_ != asio::ip::address()) { asio::post(socket_.get_executor(), [handler = std::move(handler), addr = public_address_] { handler({}, addr); }); } else { pending_requests_.emplace_back(pending_request{ address_request{std::move(handler)}, impl}); if(pending_requests_.size() == 1) { async_public_address_impl(); } } } inline asio::const_buffer prep_mapping_request_message( char* buffer, const port_mapping& mapping) { buffer[0] = 0; if(mapping.type == port_mapping::udp) { buffer[1] = opcode::udp_mapping; } else { buffer[1] = opcode::tcp_mapping; } buffer[2] = 0; buffer[3] = 0; endian::write<endian::order::network, uint16_t>(mapping.private_port, &buffer[4]); endian::write<endian::order::network, uint16_t>(mapping.public_port, &buffer[6]); endian::write<endian::order::network, uint32_t>(mapping.duration.count(), &buffer[8]); return asio::buffer(buffer, 12); } inline port_mapping parse_mapping_response(const char* buffer, int opcode, error_code& error) { verify_response_header(buffer, opcode, error); if(error) { return {}; } port_mapping mapping; mapping.private_port = endian::read<endian::order::network, uint16_t>(&buffer[8]); mapping.public_port = endian::read<endian::order::network, uint16_t>(&buffer[10]); mapping.duration = std::chrono::seconds( endian::read<endian::order::network, uint32_t>(&buffer[12])); return mapping; } port_mapping natpmp_service::request_mapping(implementation_type& impl, const port_mapping& request, error_code& error) { if(pending_requests_.empty()) { error = error_code(); const auto num_sent = socket_.send(prep_mapping_request_message( send_buffer_.data(), request), 0, error); if(error) { return {}; } if(num_sent < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } const auto num_received = socket_.receive(asio::buffer(receive_buffer_), 0, error); if(error) { return {}; } if(num_received < 12) { error = std::make_error_code(std::errc::bad_message); return {}; } auto mapping = parse_mapping_response(receive_buffer_.data(), request.type == port_mapping::udp ? opcode::udp_mapping : opcode::tcp_mapping, error); if(!error) { impl.mappings.push_back(mapping); } return mapping; } else { error = make_error_code(asio::error::try_again); return {}; } } void natpmp_service::async_request_mapping_impl() { assert(!pending_requests_.empty()); assert(std::holds_alternative<mapping_request>(pending_requests_.front().data)); const auto& request = std::get<mapping_request>(pending_requests_.front().data); socket_.async_send(prep_mapping_request_message( send_buffer_.data(), request.mapping), [this](const auto& error, const auto num_sent) { if(!error && num_sent == 12) { return; } auto request = pop_current_request<mapping_request>(); if(error) { request.handler(error, {}); } else if(num_sent != 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); } if(!pending_requests_.empty()) { execute_request(); } }); socket_.async_receive(asio::buffer(receive_buffer_), [this](auto error, const auto num_received) { assert(!pending_requests_.empty()); auto& impl = pending_requests_.front().impl; auto request = pop_current_request<mapping_request>(); if(error) { request.handler(error, {}); return; } else if(num_received < 12) { request.handler(std::make_error_code(std::errc::bad_message), {}); return; } auto mapping = parse_mapping_response(receive_buffer_.data(), request.mapping.type == port_mapping::udp ? opcode::udp_mapping : opcode::tcp_mapping, error); if(!error) { impl.mappings.push_back(mapping); } request.handler(error, mapping); if(!pending_requests_.empty()) { execute_request(); } }); } template<typename Handler> void natpmp_service::async_request_mapping(implementation_type& impl, const port_mapping& mapping, Handler handler) { pending_requests_.emplace_back(pending_request{mapping_request{mapping, std::move(handler)}, impl}); if(pending_requests_.size() == 1) { async_public_address_impl(); } } void natpmp_service::async_remove_mapping_impl() { async_request_mapping_impl(); } void natpmp_service::remove_mapping(implementation_type& impl, const port_mapping& mapping, error_code& error) { auto request = mapping; request.duration = std::chrono::seconds(0); request.public_port = 0; request_mapping(impl, request, error); } template<typename Handler> void natpmp_service::async_remove_mapping(implementation_type& impl, const port_mapping& mapping, Handler handler) { auto request = mapping; request.duration = std::chrono::seconds(0); request.public_port = 0; async_request_mapping(impl, request, std::move(handler)); } void natpmp_service::execute_request() { assert(!pending_requests_.empty()); const auto& curr_req = pending_requests_.front(); if(std::holds_alternative<address_request>(curr_req.data)) { async_public_address_impl(); } else { const auto& request = std::get<mapping_request>(curr_req.data); if(is_remove_mapping_request(request.mapping)) { async_remove_mapping_impl(); } else { async_request_mapping_impl(); } } } template<typename Request> Request natpmp_service::pop_current_request() { assert(!pending_requests_.empty()); auto curr_req = std::move(pending_requests_.front()); pending_requests_.pop_front(); assert(std::holds_alternative<Request>(curr_req.data)); return std::move(std::get<Request>(curr_req.data)); } } } #endif
if(static_cast<uint8_t>(buffer[1]) != 128 + opcode) { error = make_error_code(error::natpmp::invalid_opcode); return; }
if_condition
[ { "content": "enum class natpmp\n\n{\n\n unsupported_version = 1,\n\n // E.g. box supports mapping but user has turned feature off.\n\n unauthorized = 2,\n\n // E.g. box hasn't obtained a DHCP lease.\n\n network_failure = 3,\n\n // Box cannot create any more mappings at this time.\n\n out_o...
C++
test/cctest/test-typing-reset.cc
guillermomolina/v8-sparc
40f43c91a59835819cdd544b25d0ea415a753bbb
#define V8_IMMINENT_DEPRECATION_WARNINGS #include <stdlib.h> #include "src/v8.h" #include "src/ast.h" #include "src/ast-expression-visitor.h" #include "src/parser.h" #include "src/rewriter.h" #include "src/scopes.h" #include "src/typing-reset.h" #include "test/cctest/cctest.h" #include "test/cctest/compiler/function-tester.h" #include "test/cctest/expression-type-collector.h" #include "test/cctest/expression-type-collector-macros.h" #define INT32_TYPE Bounds(Type::Signed32(), Type::Signed32()) using namespace v8::internal; namespace { class TypeSetter : public AstExpressionVisitor { public: TypeSetter(Isolate* isolate, FunctionLiteral* root) : AstExpressionVisitor(isolate, root) {} protected: void VisitExpression(Expression* expression) { expression->set_bounds(INT32_TYPE); } }; void CheckAllSame(ZoneVector<ExpressionTypeEntry>& types, Bounds expected_type) { CHECK_TYPES_BEGIN { CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(CompareOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(log, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_VAR(values, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(exp, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(logSum, expected_type); CHECK_VAR(start, expected_type); CHECK_VAR(end, expected_type); } CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_VAR(start, expected_type); } CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Literal, expected_type); CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(exp, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(log, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(values, expected_type); CHECK_EXPR(CallNew, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_VAR(buffer, expected_type); } } CHECK_EXPR(ObjectLiteral, expected_type) { CHECK_VAR(geometricMean, expected_type); } } } CHECK_TYPES_END } } TEST(ResetTypingInfo) { const char test_function[] = "function GeometricMean(stdlib, foreign, buffer) {\n" " \"use asm\";\n" "\n" " var exp = stdlib.Math.exp;\n" " var log = stdlib.Math.log;\n" " var values = new stdlib.Float64Array(buffer);\n" "\n" " function logSum(start, end) {\n" " start = start|0;\n" " end = end|0;\n" "\n" " var sum = 0.0, p = 0, q = 0;\n" "\n" " // asm.js forces byte addressing of the heap by requiring shifting " "by 3\n" " for (p = start << 3, q = end << 3; (p|0) < (q|0); p = (p + 8)|0) {\n" " sum = sum + +log(values[p>>3]);\n" " }\n" "\n" " return +sum;\n" " }\n" "\n" " function geometricMean(start, end) {\n" " start = start|0;\n" " end = end|0;\n" "\n" " return +exp(+logSum(start, end) / +((end - start)|0));\n" " }\n" "\n" " return { geometricMean: geometricMean };\n" "}\n"; v8::V8::Initialize(); HandleAndZoneScope handles; i::Isolate* isolate = CcTest::i_isolate(); i::Factory* factory = isolate->factory(); i::Handle<i::String> source_code = factory->NewStringFromUtf8(i::CStrVector(test_function)) .ToHandleChecked(); i::Handle<i::Script> script = factory->NewScript(source_code); i::ParseInfo info(handles.main_zone(), script); i::Parser parser(&info); parser.set_allow_harmony_sloppy(true); info.set_global(); info.set_lazy(false); info.set_allow_lazy_parsing(false); info.set_toplevel(true); CHECK(i::Compiler::ParseAndAnalyze(&info)); FunctionLiteral* root = info.scope()->declarations()->at(0)->AsFunctionDeclaration()->fun(); ZoneVector<ExpressionTypeEntry> types(handles.main_zone()); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, Bounds::Unbounded()); TypeSetter(isolate, root).Run(); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, INT32_TYPE); TypingReseter(isolate, root).Run(); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, Bounds::Unbounded()); }
#define V8_IMMINENT_DEPRECATION_WARNINGS #include <stdlib.h> #include "src/v8.h" #include "src/ast.h" #include "src/ast-expression-visitor.h" #include "src/parser.h" #include "src/rewriter.h" #include "src/scopes.h" #include "src/typing-reset.h" #include "test/cctest/cctest.h" #include "test/cctest/compiler/function-tester.h" #include "test/cctest/expression-type-collector.h" #include "test/cctest/expression-type-collector-macros.h" #define INT32_TYPE Bounds(Type::Signed32(), Type::Signed32()) using namespace v8::internal; namespace { class TypeSetter : public AstExpressionVisitor { public: TypeSetter(Isolate* isolate, FunctionLiteral* root) : AstExpressionVisitor(isolate, root) {} protected: void VisitExpression(Expression* expression) { expression->set_bounds(INT32_TYPE); } }; void CheckAllSame(ZoneVector<ExpressionTypeEntry>& types, Bounds expected_type) { CHECK_TYPES_BEGIN { CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(CompareOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(q, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, exp
e); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(values, expected_type); CHECK_EXPR(CallNew, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_VAR(buffer, expected_type); } } CHECK_EXPR(ObjectLiteral, expected_type) { CHECK_VAR(geometricMean, expected_type); } } } CHECK_TYPES_END } } TEST(ResetTypingInfo) { const char test_function[] = "function GeometricMean(stdlib, foreign, buffer) {\n" " \"use asm\";\n" "\n" " var exp = stdlib.Math.exp;\n" " var log = stdlib.Math.log;\n" " var values = new stdlib.Float64Array(buffer);\n" "\n" " function logSum(start, end) {\n" " start = start|0;\n" " end = end|0;\n" "\n" " var sum = 0.0, p = 0, q = 0;\n" "\n" " // asm.js forces byte addressing of the heap by requiring shifting " "by 3\n" " for (p = start << 3, q = end << 3; (p|0) < (q|0); p = (p + 8)|0) {\n" " sum = sum + +log(values[p>>3]);\n" " }\n" "\n" " return +sum;\n" " }\n" "\n" " function geometricMean(start, end) {\n" " start = start|0;\n" " end = end|0;\n" "\n" " return +exp(+logSum(start, end) / +((end - start)|0));\n" " }\n" "\n" " return { geometricMean: geometricMean };\n" "}\n"; v8::V8::Initialize(); HandleAndZoneScope handles; i::Isolate* isolate = CcTest::i_isolate(); i::Factory* factory = isolate->factory(); i::Handle<i::String> source_code = factory->NewStringFromUtf8(i::CStrVector(test_function)) .ToHandleChecked(); i::Handle<i::Script> script = factory->NewScript(source_code); i::ParseInfo info(handles.main_zone(), script); i::Parser parser(&info); parser.set_allow_harmony_sloppy(true); info.set_global(); info.set_lazy(false); info.set_allow_lazy_parsing(false); info.set_toplevel(true); CHECK(i::Compiler::ParseAndAnalyze(&info)); FunctionLiteral* root = info.scope()->declarations()->at(0)->AsFunctionDeclaration()->fun(); ZoneVector<ExpressionTypeEntry> types(handles.main_zone()); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, Bounds::Unbounded()); TypeSetter(isolate, root).Run(); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, INT32_TYPE); TypingReseter(isolate, root).Run(); ExpressionTypeCollector(isolate, root, &types).Run(); CheckAllSame(types, Bounds::Unbounded()); }
ected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(log, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_VAR(values, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(p, expected_type); CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(sum, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(FunctionLiteral, expected_type) { CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(start, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(exp, expected_type); CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(Call, expected_type) { CHECK_VAR(logSum, expected_type); CHECK_VAR(start, expected_type); CHECK_VAR(end, expected_type); } CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_EXPR(BinaryOperation, expected_type) { CHECK_VAR(end, expected_type); CHECK_VAR(start, expected_type); } CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Literal, expected_type); CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(exp, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_type); } } CHECK_EXPR(Assignment, expected_type) { CHECK_VAR(log, expected_type); CHECK_EXPR(Property, expected_type) { CHECK_EXPR(Property, expected_type) { CHECK_VAR(stdlib, expected_type); CHECK_EXPR(Literal, expected_type); } CHECK_EXPR(Literal, expected_typ
random
[]
C++
core/utility/error.cpp
rj2Skipper/mfcmapi
07e98bb540d184b1bebb509f136712d5402e5820
#include <core/stdafx.h> #include <core/utility/error.h> #include <core/interpret/errorArray.h> #include <core/utility/strings.h> #include <core/utility/output.h> #include <core/utility/registry.h> #include <core/interpret/proptags.h> namespace error { std::function<void(const std::wstring& errString)> displayError; void LogFunctionCall( HRESULT hRes, HRESULT hrIgnore, bool bShowDialog, bool bMAPICall, bool bSystemCall, UINT uidErrorMsg, _In_opt_z_ LPCSTR szFunction, _In_z_ LPCSTR szFile, int iLine) { if (fIsSet(output::dbgLevel::MAPIFunctions) && bMAPICall) { const auto szFunctionString = strings::formatmessage(IDS_FUNCTION, szFile, iLine, szFunction); output::Output(output::dbgLevel::MAPIFunctions, nullptr, true, szFunctionString); output::Output(output::dbgLevel::MAPIFunctions, nullptr, false, L"\n"); } if (hRes == S_OK || hRes == hrIgnore) return; if (!(bShowDialog && displayError) && !fIsSet(output::dbgLevel::HRes)) return; const auto szErrorMsg = bSystemCall ? strings::formatmessagesys(uidErrorMsg) : uidErrorMsg ? strings::loadstring(uidErrorMsg) : L""; const auto szErrString = strings::formatmessage( FAILED(hRes) ? IDS_ERRFORMATSTRING : IDS_WARNFORMATSTRING, szErrorMsg.c_str(), ErrorNameFromErrorCode(hRes).c_str(), hRes, szFunction, szFile, iLine); if (fIsSet(output::dbgLevel::HRes)) { output::Output(output::dbgLevel::HRes, nullptr, true, strings::StripCarriage(szErrString)); output::Output(output::dbgLevel::HRes, nullptr, false, L"\n"); } if (bShowDialog && displayError) { displayError(szErrString); } } _Check_return_ HRESULT CheckWin32Error(bool bDisplayDialog, _In_z_ LPCSTR szFile, int iLine, _In_z_ LPCSTR szFunction) { const auto dwErr = GetLastError(); const auto hRes = HRESULT_FROM_WIN32(dwErr); LogFunctionCall(hRes, NULL, bDisplayDialog, false, true, dwErr, szFunction, szFile, iLine); return hRes; } void __cdecl ErrDialog(_In_z_ LPCSTR szFile, int iLine, UINT uidErrorFmt, ...) { auto szErrorFmt = strings::loadstring(uidErrorFmt); va_list argList = nullptr; va_start(argList, uidErrorFmt); const auto szErrorBegin = strings::formatV(szErrorFmt.c_str(), argList); va_end(argList); const auto szCombo = szErrorBegin + strings::formatmessage(IDS_INFILEONLINE, szFile, iLine); output::Output(output::dbgLevel::HRes, nullptr, true, szCombo); output::Output(output::dbgLevel::HRes, nullptr, false, L"\n"); if (displayError) { displayError(szCombo); } } std::wstring ErrorNameFromErrorCode(ULONG hrErr) { for (ULONG i = 0; i < g_ulErrorArray; i++) { if (g_ErrorArray[i].ulErrorName == hrErr) return g_ErrorArray[i].lpszName; } return strings::format(L"0x%08X", hrErr); } std::wstring ProblemArrayToString(_In_ const SPropProblemArray& problems) { std::wstring szOut; for (ULONG i = 0; i < problems.cProblem; i++) { szOut += strings::formatmessage( IDS_PROBLEMARRAY, problems.aProblem[i].ulIndex, proptags::TagToString(problems.aProblem[i].ulPropTag, nullptr, false, false).c_str(), problems.aProblem[i].scode, ErrorNameFromErrorCode(problems.aProblem[i].scode).c_str()); } return szOut; } std::wstring MAPIErrToString(ULONG ulFlags, _In_ const MAPIERROR& err) { auto szOut = strings::formatmessage( ulFlags & MAPI_UNICODE ? IDS_MAPIERRUNICODE : IDS_MAPIERRANSI, err.ulVersion, err.lpszError, err.lpszComponent, err.ulLowLevelError, ErrorNameFromErrorCode(err.ulLowLevelError).c_str(), err.ulContext); return szOut; } std::wstring TnefProblemArrayToString(_In_ const STnefProblemArray& error) { std::wstring szOut; for (ULONG iError = 0; iError < error.cProblem; iError++) { szOut += strings::formatmessage( IDS_TNEFPROBARRAY, error.aProblem[iError].ulComponent, error.aProblem[iError].ulAttribute, proptags::TagToString(error.aProblem[iError].ulPropTag, nullptr, false, false).c_str(), error.aProblem[iError].scode, ErrorNameFromErrorCode(error.aProblem[iError].scode).c_str()); } return szOut; } template <typename T> void CheckExtendedError(HRESULT hRes, T lpObject) { if (hRes == MAPI_E_EXTENDED_ERROR) { LPMAPIERROR lpErr = nullptr; hRes = WC_MAPI(lpObject->GetLastError(hRes, fMapiUnicode, &lpErr)); if (lpErr) { EC_MAPIERR(fMapiUnicode, lpErr); MAPIFreeBuffer(lpErr); } } else CHECKHRES(hRes); } template void CheckExtendedError<LPMAPIFORMCONTAINER>(HRESULT hRes, LPMAPIFORMCONTAINER lpObject); template void CheckExtendedError<LPMAPIFORMMGR>(HRESULT hRes, LPMAPIFORMMGR lpObject); }
#include <core/stdafx.h> #include <core/utility/error.h> #include <core/interpret/errorArray.h> #include <core/utility/strings.h> #include <core/utility/output.h> #include <core/utility/registry.h> #include <core/interpret/proptags.h> namespace error { std::function<void(const std::wstring& errString)> displayError; void LogFunctionCall( HRESULT hRes, HRESULT hrIgnore, bool bShowDialog, bool bMAPICall, bool bSystemCall, UINT uidErrorMsg, _In_opt_z_ LPCSTR szFunction, _In_z_ LPCSTR szFile, int iLine) { if (fIsSet(output::dbgLevel::MAPIFunctions) && bMAPICall) { const auto szFunctionString = strings::formatmessage(IDS_FUNCTION, szFile, iLine, szFunction); output::Output(output::dbgLevel::MAPIFunctions, nullptr, true, szFunctionString); output::Output(output::dbgLevel::MAPIFunctions, nullptr, false, L"\n"); } if (hRes == S_OK || hRes == hrIgnore) return; if (!(bShowDialog && displayError) && !fIsSet(output::dbgLevel::HRes)) return; const auto szErrorMsg = bSystemCall ? strings::formatmessagesys(uidErrorMsg) : uidErrorMsg ? strings::loadstring(uidErrorMsg) : L""; const auto szErrString = strings::formatmessage( FAILED(hRes) ? IDS_ERRFORMATSTRING : IDS_WARNFORMATSTRING, szErrorMsg.c_str(), ErrorNameFromErrorCode(hRes).c_str(), hRes, szFunction, szFile, iLine); if (fIsSet(output::dbgLevel::HRes)) { output::Output(output::dbgLevel::HRes, nullptr, true, strings::StripCarriage(szErrString)); output::Output(output::dbgLevel::HRes, nullptr, false, L"\n"); } if (bShowDialog && displayError) { displayError(szErrString); } } _Check_return_ HRESULT CheckWin32Error(bool bDisplayDialog, _In_z_ LPCSTR szFile, int iLine, _In_z_ LPCSTR szFunction) { const auto dwErr = GetLastError(); const auto hRes = HRESULT_FROM_WIN32(dwErr); LogFunctionCall(hRes, NULL, bDisplayDialog, false, true, dwErr, szFunction, szFile, iLine); return hRes; } void __cdecl ErrDialog(_In_z_ LPCSTR szFile, int iLine, UINT uidErrorFmt, ...) { auto szErrorFmt = strings::loadstring(uidErrorFmt); va_list argList = nullptr; va_start(argList, uidErrorFmt); const auto szErrorBegin = strings::formatV(szErrorFmt.c_str(), argList); va_end(argList); const auto szCombo = szErrorBegin + strings::formatmessage(IDS_INFILEONLINE, szFile, iLine); output::Output(output::dbgLevel::HRes, nullptr, true, szCombo); output::Output(output::dbgLevel::HRes, nullptr, false, L"\n"); if (displayError) { displayError(szCombo); } } std::wstring ErrorNameFromErrorCode(ULONG hrErr) { for (ULONG i = 0; i < g_ulErrorArray; i++) { if (g_ErrorArray[i].ulErrorName == hrErr) return g_ErrorArray[i].lpszName; } return strings::format(L"0x%08X", hrErr); } std::wstring ProblemArrayToString(_In_ const SPropProblemArray& problems) { std::wstring szOut; for (ULONG i = 0; i < problems.cProblem; i++) { szOut += strings::formatmessage( IDS_PROBLEMARRAY, problems.aProblem[i].ulIndex, proptags::TagToString(problems.aProblem[i].ulPropTag, nullptr, false, false).c_str(), problems.aProblem[i].scode, ErrorNameFromErrorCode(problems.aProblem[i].scode).c_str()); } return szOut; } std::wstring MAPIErrToString(ULONG ulFlags, _In_ co
Code(err.ulLowLevelError).c_str(), err.ulContext); return szOut; } std::wstring TnefProblemArrayToString(_In_ const STnefProblemArray& error) { std::wstring szOut; for (ULONG iError = 0; iError < error.cProblem; iError++) { szOut += strings::formatmessage( IDS_TNEFPROBARRAY, error.aProblem[iError].ulComponent, error.aProblem[iError].ulAttribute, proptags::TagToString(error.aProblem[iError].ulPropTag, nullptr, false, false).c_str(), error.aProblem[iError].scode, ErrorNameFromErrorCode(error.aProblem[iError].scode).c_str()); } return szOut; } template <typename T> void CheckExtendedError(HRESULT hRes, T lpObject) { if (hRes == MAPI_E_EXTENDED_ERROR) { LPMAPIERROR lpErr = nullptr; hRes = WC_MAPI(lpObject->GetLastError(hRes, fMapiUnicode, &lpErr)); if (lpErr) { EC_MAPIERR(fMapiUnicode, lpErr); MAPIFreeBuffer(lpErr); } } else CHECKHRES(hRes); } template void CheckExtendedError<LPMAPIFORMCONTAINER>(HRESULT hRes, LPMAPIFORMCONTAINER lpObject); template void CheckExtendedError<LPMAPIFORMMGR>(HRESULT hRes, LPMAPIFORMMGR lpObject); }
nst MAPIERROR& err) { auto szOut = strings::formatmessage( ulFlags & MAPI_UNICODE ? IDS_MAPIERRUNICODE : IDS_MAPIERRANSI, err.ulVersion, err.lpszError, err.lpszComponent, err.ulLowLevelError, ErrorNameFromError
function_block-random_span
[ { "content": " BEGIN_INTERFACE\n\n\n\n HRESULT ( STDMETHODCALLTYPE *QueryInterface )(\n\n IMimeEditTagCollection * This,\n\n /* [in] */ REFIID riid,\n", "file_path": "include/mimeole.h", "rank": 0, "score": 144058.305925519 }, { "content": "namespace error...
C++
ext/include/applications/osgearth_terraineffects/osgearth_terraineffects.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
#include <osgEarth/VirtualProgram> #include <osgEarth/Registry> #include <osgEarth/TerrainEngineNode> #include <osgEarth/MapNode> #include <osgEarthUtil/EarthManipulator> #include <osgEarthUtil/ExampleResources> #include <osgEarthUtil/Controls> #include <osgEarthUtil/ContourMap> #include <osgEarthUtil/LODBlending> #include <osgEarthUtil/NormalMap> #include <osgEarthUtil/VerticalScale> #include <osgEarthSymbology/Color> #include <osg/Notify> #include <osg/Fog> #include <osgViewer/Viewer> using namespace osgEarth; using namespace osgEarth::Util; using namespace osgEarth::Symbology; namespace ui = osgEarth::Util::Controls; int usage(const char* msg) { OE_NOTICE << msg << std::endl; return 0; } struct App { TerrainEngineNode* engine; osg::ref_ptr<ContourMap> contourMap; osg::ref_ptr<LODBlending> lodBlending; osg::ref_ptr<NormalMap> normalMap; osg::ref_ptr<VerticalScale> verticalScale; App() { contourMap = new ContourMap(); lodBlending = new LODBlending(); normalMap = new NormalMap(); verticalScale = new VerticalScale(); } }; #define SET_FLOAT( effect, func ) \ struct func : public ui::ControlEventHandler { \ App& _app; \ func (App& app) : _app(app) { } \ void onValueChanged(ui::Control*, float value) { \ _app. effect -> func (value); \ } \ }; #define TOGGLE( effect ) \ struct Toggle : public ui::ControlEventHandler { \ App& _app; \ Toggle (App& app) : _app(app) { } \ void onValueChanged(ui::Control*, bool value) { \ if ( value ) _app.engine->addEffect( _app. effect .get() ); \ else _app.engine->removeEffect( _app. effect .get() ); \ } \ }; struct ContourMapController { TOGGLE ( contourMap ); SET_FLOAT( contourMap, setOpacity ); ContourMapController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("ContourMap")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" opacity:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 1.0, 0.5, new setOpacity(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; struct LODBlendingController { TOGGLE ( lodBlending ); SET_FLOAT( lodBlending, setDelay ); SET_FLOAT( lodBlending, setDuration ); SET_FLOAT( lodBlending, setVerticalScale ); LODBlendingController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("LOD Blending")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" delay:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 2.0, 1.0, new setDelay(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); ++r; grid->setControl(0, r, new ui::LabelControl(" duration:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 5.0, 1.0, new setDuration(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); ++r; grid->setControl(0, r, new ui::LabelControl(" vertical scale:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 5.0, 1.0, new setVerticalScale(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; struct NormalMapController { TOGGLE ( normalMap ); NormalMapController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("NormalMap")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); } }; struct VerticalScaleController { TOGGLE ( verticalScale ); SET_FLOAT( verticalScale, setScale ); VerticalScaleController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("VerticalScale")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" scale:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 10.0, 1.0, new setScale(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; ui::Control* createUI( App& app ) { Grid* grid = new Grid(); grid->setAbsorbEvents( true ); grid->setControl(0, 0, new LabelControl("Terrain Effects", Color::Yellow) ); grid->setControl(1, 0, new LabelControl("")); grid->getControl(1, 0)->setHorizFill( true, 250 ); ContourMapController (app, grid); LODBlendingController (app, grid); NormalMapController (app, grid); VerticalScaleController (app, grid); return grid; } int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc, argv); if (arguments.read("--help")) return usage(argv[0]); osgViewer::Viewer viewer(arguments); viewer.setCameraManipulator( new EarthManipulator() ); App app; ui::Control* demo_ui = createUI(app); osg::Node* node = MapNodeHelper().load( arguments, &viewer, demo_ui ); if ( node ) { MapNode* mapNode = MapNode::get(node); if ( !mapNode ) return -1; app.engine = mapNode->getTerrainEngine(); viewer.setSceneData( node ); viewer.run(); } else { return usage("no earth file"); } return 0; }
#include <osgEarth/VirtualProgram> #include <osgEarth/Registry> #include <osgEarth/TerrainEngineNode> #include <osgEarth/MapNode> #include <osgEarthUtil/EarthManipulator> #include <osgEarthUtil/ExampleResources> #include <osgEarthUtil/Controls> #include <osgEarthUtil/ContourMap> #include <osgEarthUtil/LODBlending> #include <osgEarthUtil/NormalMap> #include <osgEarthUtil/VerticalScale> #include <osgEarthSymbology/Color> #include <osg/Notify> #include <osg/Fog> #include <osgViewer/Viewer> using namespace osgEarth; using namespace osgEarth::Util; using namespace osgEarth::Symbology; namespace ui = osgEarth::Util::Controls; int usage(const char* msg) { OE_NOTICE << msg << std::endl; return 0; } struct App { TerrainEngineNode* engine; osg::ref_ptr<ContourMap> contourMap; osg::ref_ptr<LODBlending> lodBlending; osg::ref_ptr<NormalMap> normalMap; osg::ref_ptr<VerticalScale> verticalScale; App() { contourMap = new ContourMap(); lodBlending = new LODBlending(); normalMap = new NormalMap(); verticalScale = new VerticalScale(); } }; #define SET_FLOAT( effect, func ) \ struct func : public ui::ControlEventHandler { \ App& _app; \ func (App& app) : _app(app) { } \ void onValueChanged(ui::Control*, float value) { \ _app. effect -> func (value); \ } \ }; #define TOGGLE( effect ) \ struct Toggle : public ui::ControlEventHandler { \ App& _app; \ Toggle (App& app) : _app(app) { } \ void onValueChanged(ui::Control*, bool value) { \ if ( value ) _app.engine->addEff
p, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("LOD Blending")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" delay:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 2.0, 1.0, new setDelay(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); ++r; grid->setControl(0, r, new ui::LabelControl(" duration:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 5.0, 1.0, new setDuration(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); ++r; grid->setControl(0, r, new ui::LabelControl(" vertical scale:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 5.0, 1.0, new setVerticalScale(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; struct NormalMapController { TOGGLE ( normalMap ); NormalMapController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("NormalMap")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); } }; struct VerticalScaleController { TOGGLE ( verticalScale ); SET_FLOAT( verticalScale, setScale ); VerticalScaleController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("VerticalScale")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" scale:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 10.0, 1.0, new setScale(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; ui::Control* createUI( App& app ) { Grid* grid = new Grid(); grid->setAbsorbEvents( true ); grid->setControl(0, 0, new LabelControl("Terrain Effects", Color::Yellow) ); grid->setControl(1, 0, new LabelControl("")); grid->getControl(1, 0)->setHorizFill( true, 250 ); ContourMapController (app, grid); LODBlendingController (app, grid); NormalMapController (app, grid); VerticalScaleController (app, grid); return grid; } int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc, argv); if (arguments.read("--help")) return usage(argv[0]); osgViewer::Viewer viewer(arguments); viewer.setCameraManipulator( new EarthManipulator() ); App app; ui::Control* demo_ui = createUI(app); osg::Node* node = MapNodeHelper().load( arguments, &viewer, demo_ui ); if ( node ) { MapNode* mapNode = MapNode::get(node); if ( !mapNode ) return -1; app.engine = mapNode->getTerrainEngine(); viewer.setSceneData( node ); viewer.run(); } else { return usage("no earth file"); } return 0; }
ect( _app. effect .get() ); \ else _app.engine->removeEffect( _app. effect .get() ); \ } \ }; struct ContourMapController { TOGGLE ( contourMap ); SET_FLOAT( contourMap, setOpacity ); ContourMapController(App& app, ui::Grid* grid) { int r = grid->getNumRows(); grid->setControl(0, r, new ui::LabelControl("ContourMap")); grid->setControl(1, r, new ui::CheckBoxControl(false, new Toggle(app))); ++r; grid->setControl(0, r, new ui::LabelControl(" opacity:")); grid->setControl(1, r, new ui::HSliderControl(0.0, 1.0, 0.5, new setOpacity(app))); grid->setControl(2, r, new ui::LabelControl(grid->getControl(1, r))); } }; struct LODBlendingController { TOGGLE ( lodBlending ); SET_FLOAT( lodBlending, setDelay ); SET_FLOAT( lodBlending, setDuration ); SET_FLOAT( lodBlending, setVerticalScale ); LODBlendingController(App& ap
random
[ { "content": "// Callback to toggle the visibility of the save/cancel buttons based on tool state\n\nstruct ToggleUIStateCallback : public FeatureQueryTool::Callback\n\n{\n\n // called when a valid feature is found under the mouse coords\n\n virtual void onHit( FeatureSourceIndexNode* index, FeatureID fid...
C++
include/nifty/graph/opt/common/visitor_base.hxx
konopczynski/nifty
dc02ac60febaabfaf9b2ee5a854bb61436ebdc97
#pragma once #include <cstddef> #include <string> #include <initializer_list> #include <sstream> #include <iostream> #include <chrono> #include "nifty/tools/timer.hxx" #include "nifty/tools/logging.hxx" namespace nifty { namespace graph { namespace opt{ namespace common{ template<class SOLVER> class VisitorBase{ public: typedef SOLVER SolverType; virtual void begin(SolverType * solver) = 0; virtual bool visit(SolverType * solver) = 0; virtual void end(SolverType * solver) = 0; virtual void clearLogNames(){ } virtual void addLogNames(std::initializer_list<std::string> logNames){ } virtual void setLogValue(const std::size_t logIndex, double logValue){ } virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ } }; template<class SOLVER> class VerboseVisitor : public VisitorBase<SOLVER>{ public: typedef SOLVER SolverType; typedef nifty::tools::Timer TimerType; VerboseVisitor( const int printNth = 1, const double timeLimitSolver = std::numeric_limits<double>::infinity(), const double timeLimitTotal = std::numeric_limits<double>::infinity(), const nifty::logging::LogLevel logLevel = nifty::logging::LogLevel::WARN ) : printNth_(printNth), runOpt_(true), iter_(1), timeLimitSolver_(timeLimitSolver), timeLimitTotal_(timeLimitTotal), runtimeSolver_(0.0), runtimeTotal_(0.0), logLevel_(logLevel) {} virtual void begin(SolverType * ) { timerSolver_.start(); timerTotal_.start(); } virtual bool visit(SolverType * solver) { timerSolver_.stop(); timerTotal_.stop(); runtimeTotal_ += timerTotal_.elapsedSeconds(); timerTotal_.reset().start(); runtimeSolver_ += timerSolver_.elapsedSeconds(); if(iter_%printNth_ == 0){ std::stringstream ss; ss << "E: " << solver->currentBestEnergy() << " "; ss << "t[s]: " << runtimeSolver_ << " "; ss << "/ " << runtimeTotal_ << " "; for(std::size_t i=0; i<logNames_.size(); ++i){ ss<<logNames_[i]<<" "<<logValues_[i]<<" "; } ss<<"\n"; std::cout<<ss.str(); } checkRuntime(); ++iter_; timerSolver_.reset().start(); return runOpt_; } virtual void end(SolverType * ) { timerSolver_.stop(); } virtual void clearLogNames(){ logNames_.clear(); logValues_.clear(); } virtual void addLogNames(std::initializer_list<std::string> logNames){ logNames_.assign(logNames.begin(), logNames.end()); logValues_.resize(logNames.size()); } virtual void setLogValue(const std::size_t logIndex, double logValue){ logValues_[logIndex] = logValue; } virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ if(int(logLevel) <= int(logLevel_)){ std::cout<<"LOG["<<nifty::logging::logLevelName(logLevel)<<"]: "<<logString<<"\n";\ } } void stopOptimize(){ runOpt_ = false; } double runtimeSolver() const{ return runtimeSolver_; } double runtimeTotal() const{ return runtimeTotal_; } double timeLimitTotal() const{ return timeLimitTotal_; } double timeLimitSolver() const{ return timeLimitSolver_; } private: bool runOpt_; int printNth_; int iter_; double timeLimitTotal_; double timeLimitSolver_; double runtimeSolver_; double runtimeTotal_; nifty::logging::LogLevel logLevel_; TimerType timerSolver_; TimerType timerTotal_; std::vector<std::string> logNames_; std::vector<double> logValues_; inline void checkRuntime() { if(runtimeSolver_ > timeLimitSolver_) { std::cout << runtimeSolver_ << " " << timeLimitSolver_ << std::endl; std::cout << "Inference has exceeded solver time limit and is stopped \n"; runOpt_ = false; } if(runtimeTotal_ > timeLimitTotal_) { std::cout << runtimeTotal_ << " " << timeLimitTotal_ << std::endl; std::cout << "Inference has exceeded total time limit and is stopped \n"; runOpt_ = false; } } }; template<class SOLVER> class EmptyVisitor : public VisitorBase<SOLVER>{ public: typedef SOLVER SolverType; virtual void begin(SolverType * solver) {} virtual bool visit(SolverType * solver) {return true;} virtual void end(SolverType * solver) {} private: }; template<class SOLVER> class VisitorProxy{ public: typedef SOLVER SolverType; typedef VisitorBase<SOLVER> VisitorBaseTpe; VisitorProxy(VisitorBaseTpe * visitor) : visitor_(visitor){ } void addLogNames(std::initializer_list<std::string> logNames){ if(visitor_ != nullptr){ visitor_->addLogNames(logNames); } } void begin(SolverType * solver) { if(visitor_ != nullptr){ visitor_->begin(solver); } } bool visit(SolverType * solver) { if(visitor_ != nullptr){ return visitor_->visit(solver); } return true; } void end(SolverType * solver) { if(visitor_ != nullptr){ visitor_->end(solver); } } void clearLogNames() { if(visitor_ != nullptr){ visitor_->clearLogNames(); } } void setLogValue(const std::size_t logIndex, const double logValue) { if(visitor_ != nullptr){ visitor_->setLogValue(logIndex, logValue); } } void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ if(visitor_ != nullptr){ visitor_->printLog(logLevel, logString); } } operator bool() const{ return visitor_ != nullptr; } private: VisitorBaseTpe * visitor_; }; } } } }
#pragma once #include <cstddef> #include <string> #include <initializer_list> #include <sstream> #include <iostream> #include <chrono> #include "nifty/tools/timer.hxx" #include "nifty/tools/logging.hxx" namespace nifty { namespace graph { namespace opt{ namespace common{ template<class SOLVER> class VisitorBase{ public: typedef SOLVER SolverType; virtual void begin(SolverType * solver) = 0; virtual bool visit(SolverType * solver) = 0; virtual void end(SolverType * solver) = 0; virtual void clearLogNames(){ } virtual void addLogNames(std::initializer_list<std::string> logNames){ } virtual void setLogValue(const std::size_t logIndex, double logValue){ } virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ } }; template<class SOLVER> class VerboseVisitor : public VisitorBase<SOLVER>{ public: typedef SOLVER SolverType; typedef nifty::tools::Timer TimerType; VerboseVisitor( const int printNth = 1, const double timeLimitSolver = std::numeric_limits<double>::infinity(), const double timeLimitTotal = std::numeric_limits<double>::infinity(), const nifty::logging::LogLevel logLevel = nifty::logging::LogLevel::WARN ) : printNth_(printNth), runOpt_(true), iter_(1), timeLimitSolver_(timeLimitSolver), timeLimitTotal_(timeLimitTotal), runtimeSolver_(0.0), runtimeTotal_(0.0), logLevel_(logLevel) {} virtual void begin(SolverType * ) { timerSolver_.start(); timerTotal_.start(); } virtual bool visit(SolverType * solver) { timerSolver_.stop(); timerTotal_.stop(); runtimeTotal_ += timerTotal_.elapsedSeconds(); timerTotal_.reset().start(); runtimeSolver_ += timerSolver_.elapsedSeconds(); if(iter_%printNth_ == 0){ std::stringstream ss; ss << "E: " << solver->currentBestEnergy() << " "; ss << "t[s]: " << runtimeSolver_ << " "; ss << "/ " << runtimeTotal_ << " "; for(std::size_t i=0; i<logNames_.size(); ++i){ ss<<logNames_[i]<<" "<<logValues_[i]<<" "; } ss<<"\n"; std::cout<<ss.str(); } checkRuntime(); ++iter_; timerSolver_.reset().start(); return runOpt_; } virtual void end(SolverType * ) { timerSolver_.stop(); } virtual void clearLogNames(){ logNames_.clear(); logValues_.clear(); } virtual void addLogNames(std::initializer_list<std::string> logNames){ logNames_.assign(logNames.begin(), logNames.end()); logValues_.resize(logNames.size()); } virtual void setLogValue(const std::size_t logIndex, double logValue){ logValues_[logIndex] = logValue; } virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ if(int(logLevel) <= int(logLevel_)){ std::cout<<"LOG["<<nifty::logging::logLevelName(logLevel)<<"]: "<<logString<<"\n";\ } } void stopOptimize(){ runOpt_ = false; } double runtimeSolver() const{ return runtimeSolver_; } double runtimeTotal() const{ return runtimeTotal_; } double timeLimitTotal() const{ return timeLimitTotal_; } double timeLimitSolver() const{ return timeLimitSolver_; } private: bool runOpt_; int printNth_; int iter_; double timeLimitTotal_; double timeLimitSolver_; double runtimeSolver_; double runtimeTotal_; nifty::logging::LogLevel logLevel_; TimerType timerSolver_; TimerType timerTotal_; std::vector<std::string> logNames_; std::vector<double> logValues_; inline void checkRuntime() { if(runtimeSolver_ > timeLimitSolver_) { std::cout << runtimeSolver_ << " " << timeLimitSolver_ << std::endl; std::cout << "Inference has exceeded solver time limit and is stopped \n"; runOpt_ = false; } if(runtimeTotal_ > timeLimitTotal_) { std::cout << runtimeTotal_ << " " << timeLimitTotal_ << std::endl; std::cout << "Inference has exceeded total time limit and is stopped \n"; runOpt_ = false; } } }; template<class SOLVER> class EmptyVisitor : public VisitorBase<SOLVER>{ public: typedef SOLVER SolverType; virtual void begin(SolverType * solver) {} virtual bool visit(SolverType * solver) {return true;} virtual void end(SolverType * solver) {} private: }; template<class SOLVER> class VisitorProxy{ public: typedef SOLVER SolverType; typedef VisitorBase<SOLVER> VisitorBaseTpe; VisitorProxy(VisitorBaseTpe * visitor) : visitor_(visitor){ } void addLogNames(std::initializer_list<std::string> logNames){ if(visitor_ != nullptr){ visitor_->addLogNames(logNames); } } void begin(SolverType * solver) { if(visitor_ != nullptr){ visitor_->begin(solver); } } boo
} void end(SolverType * solver) { if(visitor_ != nullptr){ visitor_->end(solver); } } void clearLogNames() { if(visitor_ != nullptr){ visitor_->clearLogNames(); } } void setLogValue(const std::size_t logIndex, const double logValue) { if(visitor_ != nullptr){ visitor_->setLogValue(logIndex, logValue); } } void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){ if(visitor_ != nullptr){ visitor_->printLog(logLevel, logString); } } operator bool() const{ return visitor_ != nullptr; } private: VisitorBaseTpe * visitor_; }; } } } }
l visit(SolverType * solver) { if(visitor_ != nullptr){ return visitor_->visit(solver); } return true;
function_block-random_span
[ { "content": " def verboseVisitor(visitNth=1, timeLimitSolver=float('inf'),\n\n timeLimitTotal=float('inf'), logLevel=LogLevel.WARN):\n\n V = getMcCls(\"VerboseVisitor\")\n", "file_path": "src/python/module/nifty/graph/opt/multicut/__init__.py", "rank": 0, "score": 16...
C++
src/prod/src/Naming/EntreeService.ForwardToFileStoreServiceAsyncOperation.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
#include "stdafx.h" namespace Naming { using namespace Common; using namespace Federation; using namespace Query; using namespace Reliability; using namespace std; using namespace SystemServices; using namespace Transport; using namespace Management::FileStoreService; using namespace ClientServerTransport; StringLiteral const TraceComponent("ProcessRequest.ForwardToFileStoreServiceAsyncOperation"); EntreeService::ForwardToFileStoreServiceAsyncOperation::ForwardToFileStoreServiceAsyncOperation( __in GatewayProperties & properties, MessageUPtr && receivedMessage, TimeSpan const timeout, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : RequestAsyncOperationBase (properties, std::move(receivedMessage), timeout, callback, parent) , serviceName_() , partitionId_() , activityHeader_() { } void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnRetry(AsyncOperationSPtr const & thisSPtr) { this->StartResolve(thisSPtr); } void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnStartRequest(AsyncOperationSPtr const & thisSPtr) { TimedAsyncOperation::OnStart(thisSPtr); Transport::ForwardMessageHeader forwardMessageHeader; if (!ReceivedMessage->Headers.TryReadFirst(forwardMessageHeader)) { WriteWarning(TraceComponent, "{0} ForwardMessageHeader missing: {1}", this->TraceId, *ReceivedMessage); TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage); return; } NamingPropertyHeader propertyHeader; if (ReceivedMessage->Headers.TryReadFirst(propertyHeader)) { WriteNoise( TraceComponent, "{0} read property header ({1})", this->TraceId, propertyHeader); serviceName_ = propertyHeader.Name; partitionId_ = propertyHeader.PropertyName; } else { this->TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage); return; } if (!ReceivedMessage->Headers.TryReadFirst(activityHeader_)) { activityHeader_ = FabricActivityHeader(Guid::NewGuid()); WriteWarning( TraceComponent, "{0} message {1} missing activity header: generated = {2}", this->TraceId, *ReceivedMessage, activityHeader_); } ServiceRoutingAgentHeader routingAgentHeader; bool hasRoutingAgentHeader = ReceivedMessage->Headers.TryReadFirst(routingAgentHeader); ReceivedMessage->Headers.RemoveAll(); ReceivedMessage->Headers.Replace(ActorHeader(forwardMessageHeader.Actor)); ReceivedMessage->Headers.Replace(ActionHeader(forwardMessageHeader.Action)); ReceivedMessage->Headers.Replace(activityHeader_); if (hasRoutingAgentHeader) { ReceivedMessage->Headers.Replace(routingAgentHeader); } this->StartResolve(thisSPtr); } void EntreeService::ForwardToFileStoreServiceAsyncOperation::StartResolve(Common::AsyncOperationSPtr const & thisSPtr) { auto batch = Common::make_unique<NamePropertyOperationBatch>(serviceName_); batch->AddGetPropertyOperation(partitionId_); MessageUPtr message = NamingTcpMessage::GetPropertyBatch(std::move(batch))->GetTcpMessage(); message->Headers.Replace(activityHeader_); auto inner = AsyncOperation::CreateAndStart<PropertyBatchAsyncOperation>( this->Properties, std::move(message), RemainingTime, [this] (AsyncOperationSPtr const & asyncOperation) { this->OnResolveRequestComplete(asyncOperation, false ); }, thisSPtr); this->OnResolveRequestComplete(inner, true ); } void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnResolveRequestComplete( AsyncOperationSPtr const & asyncOperation, bool expectedCompletedSynchronously) { if (asyncOperation->CompletedSynchronously != expectedCompletedSynchronously) { return; } MessageUPtr reply; ErrorCode error = RequestAsyncOperationBase::End(asyncOperation, reply); if (error.IsSuccess() && reply.get() == nullptr) { TRACE_WARNING_AND_TESTASSERT(TraceComponent, "{0}: null reply message on success", this->TraceId); error = ErrorCodeValue::OperationFailed; } if (error.IsSuccess()) { NamePropertyOperationBatchResult batchResult; if (!reply->GetBody(batchResult)) { this->TryComplete(asyncOperation->Parent, ErrorCodeValue::OperationFailed); return; } if(batchResult.Properties.empty()) { this->HandleRetryStart(asyncOperation->Parent); return; } vector<BYTE> serializedData = batchResult.Properties.front().Bytes; Management::FileStoreService::FileStorePartitionInfo info; error = FabricSerializer::Deserialize(info, serializedData); ASSERT_IFNOT(error.IsSuccess(), "Deserization of ReplicaInfo object should succeed. Error:{0}", error); WriteInfo( TraceComponent, "{0}: Received address from naming - SequenceNumber: {1}, Address: {2}", this->TraceId, batchResult.Properties.front().Metadata.SequenceNumber, info.PrimaryLocation); SystemServiceLocation parsedLocation; if (SystemServiceLocation::TryParse(info.PrimaryLocation, parsedLocation)) { auto instance = this->Properties.RequestInstance.GetNextInstance(); this->ReceivedMessage->Headers.Replace(TimeoutHeader(this->RemainingTime)); this->ReceivedMessage->Headers.Replace(parsedLocation.CreateFilterHeader()); this->ReceivedMessage->Headers.Replace(GatewayRetryHeader(this->RetryCount)); this->ReceivedMessage->Headers.Replace(RequestInstanceHeader(instance)); NodeInstance const & node = parsedLocation.NodeInstance; this->RouteToNode( this->ReceivedMessage->Clone(), node.Id, node.InstanceId, true, asyncOperation->Parent); return; } else { WriteWarning( TraceComponent, "{0}: could not parse system service location: {1}", this->TraceId, info.PrimaryLocation); this->HandleRetryStart(asyncOperation->Parent); return; } } else if (this->IsRetryable(error)) { WriteWarning( TraceComponent, "{0}: could not get FileStoreService address from naming - retrying. error = {1}", this->TraceId, error); this->HandleRetryStart(asyncOperation->Parent); return; } this->TryComplete(asyncOperation->Parent, error); } bool EntreeService::ForwardToFileStoreServiceAsyncOperation::IsRetryable(ErrorCode const & error) { switch (error.ReadValue()) { case ErrorCodeValue::ServiceOffline: case ErrorCodeValue::PartitionNotFound: return true; default: return NamingErrorCategories::IsRetryableAtGateway(error); } } }
#include "stdafx.h" namespace Naming { using namespace Common; using namespace Federation; using namespace Query; using namespace Reliability; using namespace std; using namespace SystemServices; using namespace Transport; using namespace Management::FileStoreService; using namespace ClientServerTransport; StringLiteral const TraceComponent("ProcessRequest.ForwardToFileStoreServiceAsyncOperation"); EntreeService::ForwardToFileStoreServiceAsyncOperation::ForwardToFileStoreServiceAsyncOperation( __in GatewayProperties & properties, MessageUPtr && receivedMessage, TimeSpan const timeout, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : RequestAsyncOperationBase (properties, std::move(receivedMessage), timeout, callback, parent) , serviceName_() , partitionId_() , activityHeader_() { } void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnRetry(AsyncOperationSPtr const & thisSPtr) { this->StartResolve(thisSPtr); }
void EntreeService::ForwardToFileStoreServiceAsyncOperation::StartResolve(Common::AsyncOperationSPtr const & thisSPtr) { auto batch = Common::make_unique<NamePropertyOperationBatch>(serviceName_); batch->AddGetPropertyOperation(partitionId_); MessageUPtr message = NamingTcpMessage::GetPropertyBatch(std::move(batch))->GetTcpMessage(); message->Headers.Replace(activityHeader_); auto inner = AsyncOperation::CreateAndStart<PropertyBatchAsyncOperation>( this->Properties, std::move(message), RemainingTime, [this] (AsyncOperationSPtr const & asyncOperation) { this->OnResolveRequestComplete(asyncOperation, false ); }, thisSPtr); this->OnResolveRequestComplete(inner, true ); } void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnResolveRequestComplete( AsyncOperationSPtr const & asyncOperation, bool expectedCompletedSynchronously) { if (asyncOperation->CompletedSynchronously != expectedCompletedSynchronously) { return; } MessageUPtr reply; ErrorCode error = RequestAsyncOperationBase::End(asyncOperation, reply); if (error.IsSuccess() && reply.get() == nullptr) { TRACE_WARNING_AND_TESTASSERT(TraceComponent, "{0}: null reply message on success", this->TraceId); error = ErrorCodeValue::OperationFailed; } if (error.IsSuccess()) { NamePropertyOperationBatchResult batchResult; if (!reply->GetBody(batchResult)) { this->TryComplete(asyncOperation->Parent, ErrorCodeValue::OperationFailed); return; } if(batchResult.Properties.empty()) { this->HandleRetryStart(asyncOperation->Parent); return; } vector<BYTE> serializedData = batchResult.Properties.front().Bytes; Management::FileStoreService::FileStorePartitionInfo info; error = FabricSerializer::Deserialize(info, serializedData); ASSERT_IFNOT(error.IsSuccess(), "Deserization of ReplicaInfo object should succeed. Error:{0}", error); WriteInfo( TraceComponent, "{0}: Received address from naming - SequenceNumber: {1}, Address: {2}", this->TraceId, batchResult.Properties.front().Metadata.SequenceNumber, info.PrimaryLocation); SystemServiceLocation parsedLocation; if (SystemServiceLocation::TryParse(info.PrimaryLocation, parsedLocation)) { auto instance = this->Properties.RequestInstance.GetNextInstance(); this->ReceivedMessage->Headers.Replace(TimeoutHeader(this->RemainingTime)); this->ReceivedMessage->Headers.Replace(parsedLocation.CreateFilterHeader()); this->ReceivedMessage->Headers.Replace(GatewayRetryHeader(this->RetryCount)); this->ReceivedMessage->Headers.Replace(RequestInstanceHeader(instance)); NodeInstance const & node = parsedLocation.NodeInstance; this->RouteToNode( this->ReceivedMessage->Clone(), node.Id, node.InstanceId, true, asyncOperation->Parent); return; } else { WriteWarning( TraceComponent, "{0}: could not parse system service location: {1}", this->TraceId, info.PrimaryLocation); this->HandleRetryStart(asyncOperation->Parent); return; } } else if (this->IsRetryable(error)) { WriteWarning( TraceComponent, "{0}: could not get FileStoreService address from naming - retrying. error = {1}", this->TraceId, error); this->HandleRetryStart(asyncOperation->Parent); return; } this->TryComplete(asyncOperation->Parent, error); } bool EntreeService::ForwardToFileStoreServiceAsyncOperation::IsRetryable(ErrorCode const & error) { switch (error.ReadValue()) { case ErrorCodeValue::ServiceOffline: case ErrorCodeValue::PartitionNotFound: return true; default: return NamingErrorCategories::IsRetryableAtGateway(error); } } }
void EntreeService::ForwardToFileStoreServiceAsyncOperation::OnStartRequest(AsyncOperationSPtr const & thisSPtr) { TimedAsyncOperation::OnStart(thisSPtr); Transport::ForwardMessageHeader forwardMessageHeader; if (!ReceivedMessage->Headers.TryReadFirst(forwardMessageHeader)) { WriteWarning(TraceComponent, "{0} ForwardMessageHeader missing: {1}", this->TraceId, *ReceivedMessage); TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage); return; } NamingPropertyHeader propertyHeader; if (ReceivedMessage->Headers.TryReadFirst(propertyHeader)) { WriteNoise( TraceComponent, "{0} read property header ({1})", this->TraceId, propertyHeader); serviceName_ = propertyHeader.Name; partitionId_ = propertyHeader.PropertyName; } else { this->TryComplete(thisSPtr, ErrorCodeValue::InvalidMessage); return; } if (!ReceivedMessage->Headers.TryReadFirst(activityHeader_)) { activityHeader_ = FabricActivityHeader(Guid::NewGuid()); WriteWarning( TraceComponent, "{0} message {1} missing activity header: generated = {2}", this->TraceId, *ReceivedMessage, activityHeader_); } ServiceRoutingAgentHeader routingAgentHeader; bool hasRoutingAgentHeader = ReceivedMessage->Headers.TryReadFirst(routingAgentHeader); ReceivedMessage->Headers.RemoveAll(); ReceivedMessage->Headers.Replace(ActorHeader(forwardMessageHeader.Actor)); ReceivedMessage->Headers.Replace(ActionHeader(forwardMessageHeader.Action)); ReceivedMessage->Headers.Replace(activityHeader_); if (hasRoutingAgentHeader) { ReceivedMessage->Headers.Replace(routingAgentHeader); } this->StartResolve(thisSPtr); }
function_block-full_function
[]
C++
test/test_bencoding.cpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
#include "libtorrent/bencode.hpp" #include "libtorrent/bdecode.hpp" #include <iostream> #include <cstring> #include <utility> #include "test.hpp" using namespace lt; namespace { std::string encode(entry const& e) { std::string ret; bencode(std::back_inserter(ret), e); return ret; } } TORRENT_TEST(strings) { entry e("spam"); TEST_CHECK(encode(e) == "4:spam"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers) { entry e(3); TEST_CHECK(encode(e) == "i3e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers2) { entry e(-3); TEST_CHECK(encode(e) == "i-3e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers3) { entry e(int(0)); TEST_CHECK(encode(e) == "i0e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(lists) { entry::list_type l; l.push_back(entry("spam")); l.push_back(entry("eggs")); entry e(l); TEST_CHECK(encode(e) == "l4:spam4:eggse"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(dictionaries) { entry e(entry::dictionary_t); e["spam"] = entry("eggs"); e["cow"] = entry("moo"); TEST_CHECK(encode(e) == "d3:cow3:moo4:spam4:eggse"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(preformatted) { entry e(entry::preformatted_t); char const str[] = "foobar"; e.preformatted().assign(str, str + sizeof(str)-1); TEST_EQUAL(encode(e), "foobar"); } TORRENT_TEST(preformatted_node) { entry e(entry::dictionary_t); char const str[] = "foobar"; e["info"] = entry::preformatted_type(str, str + sizeof(str)-1); TEST_EQUAL(encode(e), "d4:infofoobare"); } TORRENT_TEST(undefined_node) { entry e(entry::undefined_t); TEST_EQUAL(encode(e), "0:"); } TORRENT_TEST(undefined_node2) { entry e(entry::dictionary_t); e["info"] = entry(entry::undefined_t); TEST_EQUAL(encode(e), "d4:info0:e"); } TORRENT_TEST(implicit_construct) { entry e(entry::list_t); e.list().push_back(entry::list_t); TEST_EQUAL(e.list().back().type(), entry::list_t); } TORRENT_TEST(print_dict_single_line) { entry e; e["foo"] = "bar"; e["bar"] = "foo"; TEST_EQUAL(e.to_string(true), "{ 'bar': 'foo', 'foo': 'bar' }"); } TORRENT_TEST(print_dict) { entry e; e["foo"] = "bar"; e["bar"] = "foo"; TEST_EQUAL(e.to_string(), "{\n 'bar': 'foo',\n 'foo': 'bar' }"); } TORRENT_TEST(print_list_single_line) { entry e; e.list().push_back(entry("foo")); e.list().push_back(entry("bar")); TEST_EQUAL(e.to_string(true), "[ 'foo', 'bar' ]"); } TORRENT_TEST(print_list) { entry e; e.list().push_back(entry("foo")); e.list().push_back(entry("bar")); TEST_EQUAL(e.to_string(), "[\n 'foo',\n 'bar' ]"); } TORRENT_TEST(print_int_single_line) { entry e(1337); TEST_EQUAL(e.to_string(true), "1337"); } TORRENT_TEST(print_int) { entry e(1337); TEST_EQUAL(e.to_string(), "1337"); } TORRENT_TEST(print_string_single_line) { entry e("foobar"); TEST_EQUAL(e.to_string(true), "'foobar'"); } TORRENT_TEST(print_string) { entry e("foobar"); TEST_EQUAL(e.to_string(), "'foobar'"); } TORRENT_TEST(print_deep_dict_single_line) { entry e; e["strings"].list().push_back(entry("foo")); e["strings"].list().push_back(entry("bar")); e["ints"].list().push_back(entry(1)); e["ints"].list().push_back(entry(2)); e["ints"].list().push_back(entry(3)); e["a"] = "foobar"; TEST_EQUAL(e.to_string(true), "{ 'a': 'foobar', 'ints': [ 1, 2, 3 ], 'strings': [ 'foo', 'bar' ] }"); } TORRENT_TEST(print_deep_dict) { entry e; e["strings"].list().push_back(entry("foo")); e["strings"].list().push_back(entry("bar")); e["ints"].list().push_back(entry(1)); e["ints"].list().push_back(entry(2)); e["ints"].list().push_back(entry(3)); e["a"] = "foobar"; TEST_EQUAL(e.to_string(), R"({ 'a': 'foobar', 'ints': [ 1, 2, 3 ], 'strings': [ 'foo', 'bar' ] })"); } TORRENT_TEST(dict_constructor) { entry::dictionary_type e{{std::string("foo"), std::string("bar")}, {std::string("bar"), 1234}}; TEST_EQUAL(entry(e).to_string(), R"({ 'bar': 1234, 'foo': 'bar' })"); } TORRENT_TEST(integer_to_str) { using lt::aux::integer_to_str; std::array<char, 21> buf; TEST_CHECK(integer_to_str(buf, 0) == "0"_sv); TEST_CHECK(integer_to_str(buf, 1) == "1"_sv); TEST_CHECK(integer_to_str(buf, 2) == "2"_sv); TEST_CHECK(integer_to_str(buf, 3) == "3"_sv); TEST_CHECK(integer_to_str(buf, 4) == "4"_sv); TEST_CHECK(integer_to_str(buf, 5) == "5"_sv); TEST_CHECK(integer_to_str(buf, 6) == "6"_sv); TEST_CHECK(integer_to_str(buf, 7) == "7"_sv); TEST_CHECK(integer_to_str(buf, 8) == "8"_sv); TEST_CHECK(integer_to_str(buf, 9) == "9"_sv); TEST_CHECK(integer_to_str(buf, 10) == "10"_sv); TEST_CHECK(integer_to_str(buf, 11) == "11"_sv); TEST_CHECK(integer_to_str(buf, -1) == "-1"_sv); TEST_CHECK(integer_to_str(buf, -2) == "-2"_sv); TEST_CHECK(integer_to_str(buf, -3) == "-3"_sv); TEST_CHECK(integer_to_str(buf, -4) == "-4"_sv); TEST_CHECK(integer_to_str(buf, -5) == "-5"_sv); TEST_CHECK(integer_to_str(buf, -6) == "-6"_sv); TEST_CHECK(integer_to_str(buf, -7) == "-7"_sv); TEST_CHECK(integer_to_str(buf, -8) == "-8"_sv); TEST_CHECK(integer_to_str(buf, -9) == "-9"_sv); TEST_CHECK(integer_to_str(buf, -10) == "-10"_sv); TEST_CHECK(integer_to_str(buf, -11) == "-11"_sv); TEST_CHECK(integer_to_str(buf, 12) == "12"_sv); TEST_CHECK(integer_to_str(buf, -12) == "-12"_sv); TEST_CHECK(integer_to_str(buf, 123) == "123"_sv); TEST_CHECK(integer_to_str(buf, -123) == "-123"_sv); TEST_CHECK(integer_to_str(buf, 1234) == "1234"_sv); TEST_CHECK(integer_to_str(buf, -1234) == "-1234"_sv); TEST_CHECK(integer_to_str(buf, 12345) == "12345"_sv); TEST_CHECK(integer_to_str(buf, -12345) == "-12345"_sv); TEST_CHECK(integer_to_str(buf, 123456) == "123456"_sv); TEST_CHECK(integer_to_str(buf, -123456) == "-123456"_sv); TEST_CHECK(integer_to_str(buf, 123456789012345678LL) == "123456789012345678"_sv); TEST_CHECK(integer_to_str(buf, -123456789012345678LL) == "-123456789012345678"_sv); TEST_CHECK(integer_to_str(buf, std::numeric_limits<std::int64_t>::max()) == "9223372036854775807"_sv); TEST_CHECK(integer_to_str(buf, std::numeric_limits<std::int64_t>::min()) == "-9223372036854775808"_sv); }
#include "libtorrent/bencode.hpp" #include "libtorrent/bdecode.hpp" #include <iostream> #include <cstring> #include <utility> #include "test.hpp" using namespace lt; namespace { std::string encode(entry const& e) { std::string ret; bencode(std::back_inserter(ret), e); return ret; } } TORRENT_TEST(strings) { entry e("spam"); TEST_CHECK(encode(e) == "4:spam"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers) { entry e(3); TEST_CHECK(encode(e) == "i3e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers2) { entry e(-3); TEST_CHECK(encode(e) == "i-3e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(integers3) { entry e(int(0)); TEST_CHECK(encode(e) == "i0e"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(lists) { entry::list_type l; l.push_back(entry("spam")); l.push_back(entry("eggs")); entry e(l); TEST_CHECK(encode(e) == "l4:spam4:eggse"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(dictionaries) { entry e(entry::dictionary_t); e["spam"] = entry("eggs"); e["cow"] = entry("moo"); TEST_CHECK(encode(e) == "d3:cow3:moo4:spam4:eggse"); TEST_CHECK(bdecode(encode(e)) == e); } TORRENT_TEST(preformatted) { entry e(entry::preformatted_t); char const str[] = "foobar"; e.preformatted().assign(str, str + sizeof(str)-1); TEST_EQUAL(encode(e), "foobar"); } TORRENT_TEST(preformatted_node) { entry e(entry::dictionary_t); char const
CK(integer_to_str(buf, 3) == "3"_sv); TEST_CHECK(integer_to_str(buf, 4) == "4"_sv); TEST_CHECK(integer_to_str(buf, 5) == "5"_sv); TEST_CHECK(integer_to_str(buf, 6) == "6"_sv); TEST_CHECK(integer_to_str(buf, 7) == "7"_sv); TEST_CHECK(integer_to_str(buf, 8) == "8"_sv); TEST_CHECK(integer_to_str(buf, 9) == "9"_sv); TEST_CHECK(integer_to_str(buf, 10) == "10"_sv); TEST_CHECK(integer_to_str(buf, 11) == "11"_sv); TEST_CHECK(integer_to_str(buf, -1) == "-1"_sv); TEST_CHECK(integer_to_str(buf, -2) == "-2"_sv); TEST_CHECK(integer_to_str(buf, -3) == "-3"_sv); TEST_CHECK(integer_to_str(buf, -4) == "-4"_sv); TEST_CHECK(integer_to_str(buf, -5) == "-5"_sv); TEST_CHECK(integer_to_str(buf, -6) == "-6"_sv); TEST_CHECK(integer_to_str(buf, -7) == "-7"_sv); TEST_CHECK(integer_to_str(buf, -8) == "-8"_sv); TEST_CHECK(integer_to_str(buf, -9) == "-9"_sv); TEST_CHECK(integer_to_str(buf, -10) == "-10"_sv); TEST_CHECK(integer_to_str(buf, -11) == "-11"_sv); TEST_CHECK(integer_to_str(buf, 12) == "12"_sv); TEST_CHECK(integer_to_str(buf, -12) == "-12"_sv); TEST_CHECK(integer_to_str(buf, 123) == "123"_sv); TEST_CHECK(integer_to_str(buf, -123) == "-123"_sv); TEST_CHECK(integer_to_str(buf, 1234) == "1234"_sv); TEST_CHECK(integer_to_str(buf, -1234) == "-1234"_sv); TEST_CHECK(integer_to_str(buf, 12345) == "12345"_sv); TEST_CHECK(integer_to_str(buf, -12345) == "-12345"_sv); TEST_CHECK(integer_to_str(buf, 123456) == "123456"_sv); TEST_CHECK(integer_to_str(buf, -123456) == "-123456"_sv); TEST_CHECK(integer_to_str(buf, 123456789012345678LL) == "123456789012345678"_sv); TEST_CHECK(integer_to_str(buf, -123456789012345678LL) == "-123456789012345678"_sv); TEST_CHECK(integer_to_str(buf, std::numeric_limits<std::int64_t>::max()) == "9223372036854775807"_sv); TEST_CHECK(integer_to_str(buf, std::numeric_limits<std::int64_t>::min()) == "-9223372036854775808"_sv); }
str[] = "foobar"; e["info"] = entry::preformatted_type(str, str + sizeof(str)-1); TEST_EQUAL(encode(e), "d4:infofoobare"); } TORRENT_TEST(undefined_node) { entry e(entry::undefined_t); TEST_EQUAL(encode(e), "0:"); } TORRENT_TEST(undefined_node2) { entry e(entry::dictionary_t); e["info"] = entry(entry::undefined_t); TEST_EQUAL(encode(e), "d4:info0:e"); } TORRENT_TEST(implicit_construct) { entry e(entry::list_t); e.list().push_back(entry::list_t); TEST_EQUAL(e.list().back().type(), entry::list_t); } TORRENT_TEST(print_dict_single_line) { entry e; e["foo"] = "bar"; e["bar"] = "foo"; TEST_EQUAL(e.to_string(true), "{ 'bar': 'foo', 'foo': 'bar' }"); } TORRENT_TEST(print_dict) { entry e; e["foo"] = "bar"; e["bar"] = "foo"; TEST_EQUAL(e.to_string(), "{\n 'bar': 'foo',\n 'foo': 'bar' }"); } TORRENT_TEST(print_list_single_line) { entry e; e.list().push_back(entry("foo")); e.list().push_back(entry("bar")); TEST_EQUAL(e.to_string(true), "[ 'foo', 'bar' ]"); } TORRENT_TEST(print_list) { entry e; e.list().push_back(entry("foo")); e.list().push_back(entry("bar")); TEST_EQUAL(e.to_string(), "[\n 'foo',\n 'bar' ]"); } TORRENT_TEST(print_int_single_line) { entry e(1337); TEST_EQUAL(e.to_string(true), "1337"); } TORRENT_TEST(print_int) { entry e(1337); TEST_EQUAL(e.to_string(), "1337"); } TORRENT_TEST(print_string_single_line) { entry e("foobar"); TEST_EQUAL(e.to_string(true), "'foobar'"); } TORRENT_TEST(print_string) { entry e("foobar"); TEST_EQUAL(e.to_string(), "'foobar'"); } TORRENT_TEST(print_deep_dict_single_line) { entry e; e["strings"].list().push_back(entry("foo")); e["strings"].list().push_back(entry("bar")); e["ints"].list().push_back(entry(1)); e["ints"].list().push_back(entry(2)); e["ints"].list().push_back(entry(3)); e["a"] = "foobar"; TEST_EQUAL(e.to_string(true), "{ 'a': 'foobar', 'ints': [ 1, 2, 3 ], 'strings': [ 'foo', 'bar' ] }"); } TORRENT_TEST(print_deep_dict) { entry e; e["strings"].list().push_back(entry("foo")); e["strings"].list().push_back(entry("bar")); e["ints"].list().push_back(entry(1)); e["ints"].list().push_back(entry(2)); e["ints"].list().push_back(entry(3)); e["a"] = "foobar"; TEST_EQUAL(e.to_string(), R"({ 'a': 'foobar', 'ints': [ 1, 2, 3 ], 'strings': [ 'foo', 'bar' ] })"); } TORRENT_TEST(dict_constructor) { entry::dictionary_type e{{std::string("foo"), std::string("bar")}, {std::string("bar"), 1234}}; TEST_EQUAL(entry(e).to_string(), R"({ 'bar': 1234, 'foo': 'bar' })"); } TORRENT_TEST(integer_to_str) { using lt::aux::integer_to_str; std::array<char, 21> buf; TEST_CHECK(integer_to_str(buf, 0) == "0"_sv); TEST_CHECK(integer_to_str(buf, 1) == "1"_sv); TEST_CHECK(integer_to_str(buf, 2) == "2"_sv); TEST_CHE
random
[ { "content": "\n\n\t// hidden\n\n\t// explicit template declaration\n\n\textern template\n\n\tentry& entry::operator=(char const*) &;\n\n\n\nnamespace aux {\n\n\n\n\t// internal\n\n\tTORRENT_EXPORT string_view integer_to_str(std::array<char, 21>& buf\n\n\t\t, entry::integer_type val);\n\n}\n\n\n\n#if TORRENT_US...
C++
src/GenerateKernelDirectConvU8S8S32ACC32.cc
pashu123/FBGEMM
1b6412acd4d53f94e4febdb6a5b10b0caee6331c
#include <iostream> #include "./CodeGenHelpers.h" #include "./DirectConv.h" namespace fbgemm { namespace x86 = asmjit::x86; template <> template <inst_set_t instSet> void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::storeCRegs( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum) { using VecT = typename simd_info<instSet>::vec_reg_t; static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; for (int i = 0; i < rowRegs; ++i) { if (i != 0) { a->add(C_Offset, ldcReg); } else { a->xor_(C_Offset.r32(), C_Offset.r32()); } for (int j = 0; j < colRegs; ++j) { if (accum) { a->vpaddd( VecT(i * colRegs + j), VecT(i * colRegs + j), x86::dword_ptr( a->zcx(), C_Offset, 0, j * vectorLen * sizeof(int8_t))); } a->vmovups( x86::dword_ptr(a->zcx(), C_Offset, 0, j * vectorLen * sizeof(int8_t)), VecT(i * colRegs + j)); } } } template <> template <inst_set_t instSet> void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: genComputeBlockDirectConv( x86::Emitter* a, x86::Gp buffer_A, x86::Gp buffer_B, x86::Gp , int rowRegs, int colRegs, int strideXich) { static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; using VecRegT = typename simd_info<instSet>::vec_reg_t; constexpr int numRegs = simd_info<instSet>::NUM_VEC_REGS; VecRegT AReg(numRegs - 1); VecRegT BReg(numRegs - 2); VecRegT oneReg(numRegs - 3); VecRegT res1(numRegs - 4); for (int j = 0; j < colRegs; ++j) { emitLoadDWord<instSet, VecRegT>( a, BReg, x86::dword_ptr(buffer_B, j * vectorLen * sizeof(int8_t))); for (int i = 0; i < rowRegs; ++i) { a->vpbroadcastd( AReg, x86::dword_ptr(buffer_A, (i * strideXich) * sizeof(uint8_t))); a->vpmaddubsw(res1, AReg, BReg); a->vpmaddwd(res1, oneReg, res1); a->vpaddd(VecRegT(i * colRegs + j), res1, VecRegT(i * colRegs + j)); } } } template <> template <inst_set_t instSet> DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::jit_micro_kernel_fp DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::getOrCreateDirectConv( bool accum, int32_t O1, int32_t i1Xich, int32_t strideXich) { using VecRegT = typename simd_info<instSet>::vec_reg_t; constexpr int numRegs = simd_info<instSet>::NUM_VEC_REGS; static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; std::tuple<bool, int, int, int, int, int, int> kernelSig; int mRegBlockSize = 12; int nRegBlockSize = 8; int row_interleave = 4; kernelSig = std::make_tuple( accum, O1, i1Xich, strideXich, i1Xich, mRegBlockSize, nRegBlockSize); return codeCache_.getOrCreate(kernelSig, [&]() -> jit_micro_kernel_fp { asmjit::CodeHolder code; code.init(runtime().environment()); x86::Assembler assembler(&code); x86::Emitter* a = assembler.as<x86::Emitter>(); #if defined(FBGEMM_LOG_CODE) FILE* codeLogfile = fopen( getCodeLoggingFile<instSet>( accum, O1, i1Xich, strideXich, i1Xich, mRegBlockSize, nRegBlockSize) .c_str(), "w"); asmjit::FileLogger* codeLogger = new asmjit::FileLogger(codeLogfile); if (codeLogger) { code.setLogger(codeLogger); } #endif const int maxMRegs = mRegBlockSize; (void)maxMRegs; const int maxNRegs = nRegBlockSize * row_interleave / vectorLen; assert( maxMRegs * maxNRegs <= numRegs - 4 && "MRegs x NRegs is above available registers (MAX_REGS - 4)"); int O1RegBlocks = O1 / mRegBlockSize; int O1RegBlocksRem = O1 % mRegBlockSize; x86::Gp buffer_A = a->zdi(); x86::Gp buffer_B = a->zsi(); x86::Gp B_pf = a->zdx(); x86::Gp CBase = a->zcx(); x86::Gp ichXk1 = a->gpz(8); x86::Gp ldcReg = a->gpz(9); asmjit::FuncDetail func; func.init( asmjit::FuncSignatureT< void, uint8_t*, int8_t*, int8_t*, int32_t*, int, int>(asmjit::CallConv::kIdHost), a->environment()); asmjit::FuncFrame frame; frame.init(func); auto dirtyVecRegs = asmjit::Support::bitMask(0, 1, 2, 3, 4, 5, 6, 7) | asmjit::Support::bitMask(8, 9, 10, 11, 12, 13, 14, 15); if (numRegs >= 16) { dirtyVecRegs |= asmjit::Support::bitMask(16, 17, 18, 19, 20, 21, 22, 23) | asmjit::Support::bitMask(24, 25, 26, 27, 28, 29, 30, 31); } frame.setDirtyRegs(x86::Reg::kGroupVec, dirtyVecRegs); frame.setDirtyRegs( x86::Reg::kGroupGp, asmjit::Support::bitMask(8, 9, 10, 11, 12, 13, 14, 15)); asmjit::FuncArgsAssignment args(&func); args.assignAll(buffer_A, buffer_B, B_pf, CBase, ichXk1, ldcReg); args.updateFuncFrame(frame); frame.finalize(); a->emitProlog(frame); a->emitArgsAssignment(frame, args); asmjit::Label LoopMBlocks = a->newLabel(); x86::Gp buffer_B_saved = a->gpz(10); x86::Gp C_Offset = a->gpz(11); x86::Gp iIdx = a->gpz(13); x86::Gp kIdx = a->gpz(15); VecRegT oneReg(numRegs - 3); gen16BitVectorOne<instSet, VecRegT>(a, oneReg); a->imul(ldcReg, ldcReg, static_cast<asmjit::Imm>(sizeof(int32_t))); int colRegs = maxNRegs; auto issueLoopOverK = [&](int rowRegs) { asmjit::Label LoopKLabel = a->newLabel(); asmjit::Label LoopK0Label = a->newLabel(); initCRegs(a, rowRegs, colRegs); a->xor_(kIdx.r32(), kIdx.r32()); a->bind(LoopKLabel); a->add(kIdx, static_cast<asmjit::Imm>(row_interleave)); genComputeBlockDirectConv<instSet>( a, buffer_A, buffer_B, B_pf, rowRegs, colRegs, strideXich); a->add( buffer_A, static_cast<asmjit::Imm>(row_interleave * sizeof(uint8_t))); a->add(buffer_B, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->add(B_pf, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->cmp(kIdx, ichXk1); a->jl(LoopKLabel); a->sub(buffer_A, ichXk1); a->add(buffer_A, static_cast<asmjit::Imm>(i1Xich)); a->xor_(kIdx.r32(), kIdx.r32()); a->bind(LoopK0Label); a->add(kIdx, static_cast<asmjit::Imm>(row_interleave)); genComputeBlockDirectConv<instSet>( a, buffer_A, buffer_B, B_pf, rowRegs, colRegs, strideXich); a->add( buffer_A, static_cast<asmjit::Imm>(row_interleave * sizeof(uint8_t))); a->add(buffer_B, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->add(B_pf, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->cmp(kIdx, ichXk1); a->jl(LoopK0Label); a->sub(buffer_A, ichXk1); storeCRegs<instSet>(a, rowRegs, colRegs, C_Offset, ldcReg, accum); }; if (O1RegBlocks > 0) { a->xor_(iIdx.r32(), iIdx.r32()); a->bind(LoopMBlocks); a->inc(iIdx); a->mov(buffer_B_saved, buffer_B); issueLoopOverK(mRegBlockSize); int rowRegs = mRegBlockSize; a->sub(buffer_A, static_cast<asmjit::Imm>(i1Xich)); a->add( buffer_A, static_cast<asmjit::Imm>(rowRegs * strideXich * sizeof(uint8_t))); a->mov(buffer_B, buffer_B_saved); a->imul( C_Offset, ldcReg, static_cast<asmjit::Imm>(rowRegs * sizeof(int8_t))); a->add(CBase, C_Offset); a->cmp(iIdx, O1RegBlocks); a->jl(LoopMBlocks); } if (O1RegBlocksRem > 0) { issueLoopOverK(O1RegBlocksRem); } a->emitEpilog(frame); jit_micro_kernel_fp fn; asmjit::Error err; { std::unique_lock<std::mutex> lock(rtMutex_); err = runtime().add(&fn, &code); } if (err) { std::cout << "Error: in fn add" << std::endl; return nullptr; } #if defined(FBGEMM_LOG_CODE) fclose(codeLogfile); delete codeLogger; #endif return fn; }); } template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx512>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx512_ymm>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx2>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: jit_micro_kernel_fp DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: getOrCreateDirectConv<inst_set_t::avx2>( bool accum, int32_t O1, int32_t i1Xich, int32_t strideXich); }
#include <iostream> #include "./CodeGenHelpers.h" #include "./DirectConv.h" namespace fbgemm { namespace x86 = asmjit::x86; template <> template <inst_set_t instSet> void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::storeCRegs( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum) { using VecT = typename simd_info<instSet>::vec_reg_t; static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; for (int i = 0; i < rowRegs; ++i) { if (i != 0) { a->add(C_Offset, ldcReg); } else { a->xor_(C_Offset.r32(), C_Offset.r32()); } for (int j = 0; j < colRegs; ++j) { if (accum) { a->vpaddd( VecT(i * colRegs + j), VecT(i * colRegs + j), x86::dword_ptr( a->zcx(), C_Offset, 0, j * vectorLen * sizeof(int8_t))); } a->vmovups( x86::dword_ptr(a->zcx(), C_Offset, 0, j * vectorLen * sizeof(int8_t)), VecT(i * colRegs + j)); } } } template <> template <inst_set_t instSet> void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, i
template <> template <inst_set_t instSet> DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::jit_micro_kernel_fp DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>::getOrCreateDirectConv( bool accum, int32_t O1, int32_t i1Xich, int32_t strideXich) { using VecRegT = typename simd_info<instSet>::vec_reg_t; constexpr int numRegs = simd_info<instSet>::NUM_VEC_REGS; static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; std::tuple<bool, int, int, int, int, int, int> kernelSig; int mRegBlockSize = 12; int nRegBlockSize = 8; int row_interleave = 4; kernelSig = std::make_tuple( accum, O1, i1Xich, strideXich, i1Xich, mRegBlockSize, nRegBlockSize); return codeCache_.getOrCreate(kernelSig, [&]() -> jit_micro_kernel_fp { asmjit::CodeHolder code; code.init(runtime().environment()); x86::Assembler assembler(&code); x86::Emitter* a = assembler.as<x86::Emitter>(); #if defined(FBGEMM_LOG_CODE) FILE* codeLogfile = fopen( getCodeLoggingFile<instSet>( accum, O1, i1Xich, strideXich, i1Xich, mRegBlockSize, nRegBlockSize) .c_str(), "w"); asmjit::FileLogger* codeLogger = new asmjit::FileLogger(codeLogfile); if (codeLogger) { code.setLogger(codeLogger); } #endif const int maxMRegs = mRegBlockSize; (void)maxMRegs; const int maxNRegs = nRegBlockSize * row_interleave / vectorLen; assert( maxMRegs * maxNRegs <= numRegs - 4 && "MRegs x NRegs is above available registers (MAX_REGS - 4)"); int O1RegBlocks = O1 / mRegBlockSize; int O1RegBlocksRem = O1 % mRegBlockSize; x86::Gp buffer_A = a->zdi(); x86::Gp buffer_B = a->zsi(); x86::Gp B_pf = a->zdx(); x86::Gp CBase = a->zcx(); x86::Gp ichXk1 = a->gpz(8); x86::Gp ldcReg = a->gpz(9); asmjit::FuncDetail func; func.init( asmjit::FuncSignatureT< void, uint8_t*, int8_t*, int8_t*, int32_t*, int, int>(asmjit::CallConv::kIdHost), a->environment()); asmjit::FuncFrame frame; frame.init(func); auto dirtyVecRegs = asmjit::Support::bitMask(0, 1, 2, 3, 4, 5, 6, 7) | asmjit::Support::bitMask(8, 9, 10, 11, 12, 13, 14, 15); if (numRegs >= 16) { dirtyVecRegs |= asmjit::Support::bitMask(16, 17, 18, 19, 20, 21, 22, 23) | asmjit::Support::bitMask(24, 25, 26, 27, 28, 29, 30, 31); } frame.setDirtyRegs(x86::Reg::kGroupVec, dirtyVecRegs); frame.setDirtyRegs( x86::Reg::kGroupGp, asmjit::Support::bitMask(8, 9, 10, 11, 12, 13, 14, 15)); asmjit::FuncArgsAssignment args(&func); args.assignAll(buffer_A, buffer_B, B_pf, CBase, ichXk1, ldcReg); args.updateFuncFrame(frame); frame.finalize(); a->emitProlog(frame); a->emitArgsAssignment(frame, args); asmjit::Label LoopMBlocks = a->newLabel(); x86::Gp buffer_B_saved = a->gpz(10); x86::Gp C_Offset = a->gpz(11); x86::Gp iIdx = a->gpz(13); x86::Gp kIdx = a->gpz(15); VecRegT oneReg(numRegs - 3); gen16BitVectorOne<instSet, VecRegT>(a, oneReg); a->imul(ldcReg, ldcReg, static_cast<asmjit::Imm>(sizeof(int32_t))); int colRegs = maxNRegs; auto issueLoopOverK = [&](int rowRegs) { asmjit::Label LoopKLabel = a->newLabel(); asmjit::Label LoopK0Label = a->newLabel(); initCRegs(a, rowRegs, colRegs); a->xor_(kIdx.r32(), kIdx.r32()); a->bind(LoopKLabel); a->add(kIdx, static_cast<asmjit::Imm>(row_interleave)); genComputeBlockDirectConv<instSet>( a, buffer_A, buffer_B, B_pf, rowRegs, colRegs, strideXich); a->add( buffer_A, static_cast<asmjit::Imm>(row_interleave * sizeof(uint8_t))); a->add(buffer_B, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->add(B_pf, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->cmp(kIdx, ichXk1); a->jl(LoopKLabel); a->sub(buffer_A, ichXk1); a->add(buffer_A, static_cast<asmjit::Imm>(i1Xich)); a->xor_(kIdx.r32(), kIdx.r32()); a->bind(LoopK0Label); a->add(kIdx, static_cast<asmjit::Imm>(row_interleave)); genComputeBlockDirectConv<instSet>( a, buffer_A, buffer_B, B_pf, rowRegs, colRegs, strideXich); a->add( buffer_A, static_cast<asmjit::Imm>(row_interleave * sizeof(uint8_t))); a->add(buffer_B, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->add(B_pf, static_cast<asmjit::Imm>(8 * sizeof(int32_t))); a->cmp(kIdx, ichXk1); a->jl(LoopK0Label); a->sub(buffer_A, ichXk1); storeCRegs<instSet>(a, rowRegs, colRegs, C_Offset, ldcReg, accum); }; if (O1RegBlocks > 0) { a->xor_(iIdx.r32(), iIdx.r32()); a->bind(LoopMBlocks); a->inc(iIdx); a->mov(buffer_B_saved, buffer_B); issueLoopOverK(mRegBlockSize); int rowRegs = mRegBlockSize; a->sub(buffer_A, static_cast<asmjit::Imm>(i1Xich)); a->add( buffer_A, static_cast<asmjit::Imm>(rowRegs * strideXich * sizeof(uint8_t))); a->mov(buffer_B, buffer_B_saved); a->imul( C_Offset, ldcReg, static_cast<asmjit::Imm>(rowRegs * sizeof(int8_t))); a->add(CBase, C_Offset); a->cmp(iIdx, O1RegBlocks); a->jl(LoopMBlocks); } if (O1RegBlocksRem > 0) { issueLoopOverK(O1RegBlocksRem); } a->emitEpilog(frame); jit_micro_kernel_fp fn; asmjit::Error err; { std::unique_lock<std::mutex> lock(rtMutex_); err = runtime().add(&fn, &code); } if (err) { std::cout << "Error: in fn add" << std::endl; return nullptr; } #if defined(FBGEMM_LOG_CODE) fclose(codeLogfile); delete codeLogger; #endif return fn; }); } template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx512>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx512_ymm>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template void DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: storeCRegs<inst_set_t::avx2>( x86::Emitter* a, int rowRegs, int colRegs, x86::Gp C_Offset, x86::Gp ldcReg, bool accum); template DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: jit_micro_kernel_fp DirectConvCodeGenBase<uint8_t, int8_t, int32_t, int32_t>:: getOrCreateDirectConv<inst_set_t::avx2>( bool accum, int32_t O1, int32_t i1Xich, int32_t strideXich); }
nt32_t>:: genComputeBlockDirectConv( x86::Emitter* a, x86::Gp buffer_A, x86::Gp buffer_B, x86::Gp , int rowRegs, int colRegs, int strideXich) { static constexpr int vectorLen = simd_info<instSet>::WIDTH_BYTES; using VecRegT = typename simd_info<instSet>::vec_reg_t; constexpr int numRegs = simd_info<instSet>::NUM_VEC_REGS; VecRegT AReg(numRegs - 1); VecRegT BReg(numRegs - 2); VecRegT oneReg(numRegs - 3); VecRegT res1(numRegs - 4); for (int j = 0; j < colRegs; ++j) { emitLoadDWord<instSet, VecRegT>( a, BReg, x86::dword_ptr(buffer_B, j * vectorLen * sizeof(int8_t))); for (int i = 0; i < rowRegs; ++i) { a->vpbroadcastd( AReg, x86::dword_ptr(buffer_A, (i * strideXich) * sizeof(uint8_t))); a->vpmaddubsw(res1, AReg, BReg); a->vpmaddwd(res1, oneReg, res1); a->vpaddd(VecRegT(i * colRegs + j), res1, VecRegT(i * colRegs + j)); } } }
function_block-function_prefixed
[ { "content": "namespace fbgemm {\n\n\n\ntypedef uint16_t bfloat16;\n\n\n\n/**\n\n * @ Transform all entries in a matrix from fp32 to bfloat16: reference\n\n * implementation.\n\n *\n\n */\n\nFBGEMM_API void\n\nFloatToBfloat16_ref(const float* src, bfloat16* dst, size_t size);\n\n\n\n/**\n\n * @ Transform all en...
C++
EVE/EveHLT/AliEveHLTEventManagerHomer.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
#include "AliHLTEveHLT.h" #include "AliHLTEvePhos.h" #include "AliHLTEveEmcal.h" #include "AliESDEvent.h" #include "AliEveHLTEventManager.h" #include "AliEveEventBufferOffline.h" #include "AliEveHLTEventManagerHomer.h" #include "TList.h" #include "AliEveHOMERManager.h" #include "TEveManager.h" #include "TTimer.h" #include "TGLOverlayButton.h" #include "TGLViewer.h" ClassImp(AliEveHLTEventManagerHomer) AliEveHLTEventManagerHomer::AliEveHLTEventManagerHomer() : AliEveHLTEventManager(), fEventBuffer(NULL), fNextEventTimer(NULL), fInfoButton(NULL) { fEventBuffer = new AliEveEventBufferHomer(); fEventBuffer->StartBufferMonitor(); fNextEventTimer = new TTimer(); fNextEventTimer->Connect("Timeout()", "AliEveHLTEventManagerHomer", this, "TryNextEvent()" ); fInfoButton = new TGLOverlayButton(dynamic_cast<TGLViewerBase*>(gEve->GetDefaultGLViewer()), "", 0, 540, 210, 25); fInfoButton->SetAlphaValues(0.0, 0.8); } AliEveHLTEventManagerHomer::~AliEveHLTEventManagerHomer() { if(fEventBuffer) delete fEventBuffer; fEventBuffer = NULL; } void AliEveHLTEventManagerHomer::ProcessList(TList * blockList) { ProcessEvent(blockList); UpdateDisplay(); } void AliEveHLTEventManagerHomer::NextEvent() { fNextEventTimer->Start(1000); } void AliEveHLTEventManagerHomer::TryNextEvent() { if ( fEventBuffer->LockMutex() ) { fInfoButton->SetAlphaValues(0.8, 0.8); fInfoButton->SetText("Waiting for buffer..."); gEve->Redraw3D(kFALSE); cout << "try again in 1 sec"<<endl; return; } fInfoButton->SetAlphaValues(0.8, 0.8); fNextEventTimer->Stop(); cout << "Mutex is freeee!!"<<endl; TList * aSyncEvent = fEventBuffer->GetASyncEvent(); TList * event = static_cast<TList*>(fEventBuffer->NextEvent()); if(event) { cout << "Got the event, reset the display " <<endl; fInfoButton->SetText("Reset display.."); ResetDisplay(); cout << "Process event"<<endl; fInfoButton->SetText("Processing event.."); ProcessEvent(event); if(aSyncEvent) { cout << "Process asynchroneous event" << endl; ProcessEvent(aSyncEvent); } else { cout << "Could not get async event"<<endl; } cout << "Upate the display"<<endl; fInfoButton->SetText("Updating display..."); UpdateDisplay(); } else { cout << "couldn't get the sync event"<<endl; fInfoButton->SetAlphaValues(0.8, 0.8); fInfoButton->SetText("Waiting for buffer..."); fEventBuffer->UnLockMutex(); fEventBuffer->CreateBufferThread(); fNextEventTimer->Start(3000); return; } fInfoButton->SetAlphaValues(0.0, 0.0); fInfoButton->SetText("Done.."); fEventBuffer->UnLockMutex(); } void AliEveHLTEventManagerHomer::NavigateFwd() { TList * fEvent = dynamic_cast<TList*>(fEventBuffer->Fwd()); if(fEvent) { ResetDisplay(); ProcessEvent(fEvent); UpdateDisplay(); } else { cout << "couldn't get the fwd event"<<endl; } } void AliEveHLTEventManagerHomer::NavigateBack() { TList * fEvent = dynamic_cast<TList*>(fEventBuffer->Back()); if(fEvent) { ResetDisplay(); ProcessEvent(fEvent); UpdateDisplay(); } else { cout << "couldn't get the back event"<<endl; } }
#include "AliHLTEveHLT.h" #include "AliHLTEvePhos.h" #include "AliHLTEveEmcal.h" #include "AliESDEvent.h" #include "AliEveHLTEventManager.h" #include "AliEveEventBufferOffline.h" #include "AliEveHLTEventManagerHomer.h" #include "TList.h" #include "AliEveHOMERManager.h" #include "TEveManager.h" #include "TTimer.h" #include "TGLOverlayButton.h" #include "TGLViewer.h" ClassImp(AliEveHLTEventManagerHomer) AliEveHLTEventManagerHomer::AliEveHLTEventManagerHomer() : AliEveHLTEventManager(), fEventBuffer(NULL), fNextEventTimer(NULL), fInfoButton(NULL) { fEventBuffer = new AliEveEventBufferHomer(); fEventBuffer->StartBufferMonitor(); fNextEventTimer = new TTimer(); fNextEventTimer->Connect("Timeout()", "AliEveHLTEventManagerHomer", this, "TryNextEvent()" ); fInfoButton = new TGLOverlayButton(dynamic_cast<TGLViewerBase*>(gEve->GetDefaultGLViewer()), "", 0, 540, 210, 25); fInfoButton->SetAlphaValues(0.0, 0.8); } AliEveHLTEventManagerHomer::~AliEveHLTEventManagerHomer() { if(fEve
UpdateDisplay(); } else { cout << "couldn't get the sync event"<<endl; fInfoButton->SetAlphaValues(0.8, 0.8); fInfoButton->SetText("Waiting for buffer..."); fEventBuffer->UnLockMutex(); fEventBuffer->CreateBufferThread(); fNextEventTimer->Start(3000); return; } fInfoButton->SetAlphaValues(0.0, 0.0); fInfoButton->SetText("Done.."); fEventBuffer->UnLockMutex(); } void AliEveHLTEventManagerHomer::NavigateFwd() { TList * fEvent = dynamic_cast<TList*>(fEventBuffer->Fwd()); if(fEvent) { ResetDisplay(); ProcessEvent(fEvent); UpdateDisplay(); } else { cout << "couldn't get the fwd event"<<endl; } } void AliEveHLTEventManagerHomer::NavigateBack() { TList * fEvent = dynamic_cast<TList*>(fEventBuffer->Back()); if(fEvent) { ResetDisplay(); ProcessEvent(fEvent); UpdateDisplay(); } else { cout << "couldn't get the back event"<<endl; } }
ntBuffer) delete fEventBuffer; fEventBuffer = NULL; } void AliEveHLTEventManagerHomer::ProcessList(TList * blockList) { ProcessEvent(blockList); UpdateDisplay(); } void AliEveHLTEventManagerHomer::NextEvent() { fNextEventTimer->Start(1000); } void AliEveHLTEventManagerHomer::TryNextEvent() { if ( fEventBuffer->LockMutex() ) { fInfoButton->SetAlphaValues(0.8, 0.8); fInfoButton->SetText("Waiting for buffer..."); gEve->Redraw3D(kFALSE); cout << "try again in 1 sec"<<endl; return; } fInfoButton->SetAlphaValues(0.8, 0.8); fNextEventTimer->Stop(); cout << "Mutex is freeee!!"<<endl; TList * aSyncEvent = fEventBuffer->GetASyncEvent(); TList * event = static_cast<TList*>(fEventBuffer->NextEvent()); if(event) { cout << "Got the event, reset the display " <<endl; fInfoButton->SetText("Reset display.."); ResetDisplay(); cout << "Process event"<<endl; fInfoButton->SetText("Processing event.."); ProcessEvent(event); if(aSyncEvent) { cout << "Process asynchroneous event" << endl; ProcessEvent(aSyncEvent); } else { cout << "Could not get async event"<<endl; } cout << "Upate the display"<<endl; fInfoButton->SetText("Updating display...");
random
[]
C++
mvm-reversed/server/tf/bot/behavior/tf_bot_retreat_to_cover.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
ConVar tf_bot_retreat_to_cover_range("tf_bot_retreat_to_cover_range", "1000", FCVAR_CHEAT); ConVar tf_bot_debug_retreat_to_cover("tf_bot_debug_retreat_to_cover", "0", FCVAR_CHEAT); ConVar tf_bot_wait_in_cover_min_time("tf_bot_wait_in_cover_min_time", "1", FCVAR_CHEAT); ConVar tf_bot_wait_in_cover_max_time("tf_bot_wait_in_cover_max_time", "2", FCVAR_CHEAT); CTFBotRetreatToCover::CTFBotRetreatToCover(Action<CTFBot *> *done_action) { this->m_flDuration = -1.0f; this->m_DoneAction = done_action; } CTFBotRetreatToCover::CTFBotRetreatToCover(float duration) { this->m_flDuration = duration; this->m_DoneAction = nullptr; } CTFBotRetreatToCover::~CTFBotRetreatToCover() { } const char *CTFBotRetreatToCover::GetName() const { return "RetreatToCover"; } ActionResult<CTFBot> CTFBotRetreatToCover::OnStart(CTFBot *actor, Action<CTFBot> *action) { this->m_PathFollower.SetMinLookAheadDistance(actor->GetDesiredPathLookAheadRange()); this->m_CoverArea = this->FindCoverArea(actor); if (this->m_CoverArea == nullptr) { return ActionResult<CTFBot>::Done("No cover available!"); } if (this->m_flDuration < 0.0f) { this->m_flDuration = RandomFloat(tf_bot_wait_in_cover_min_time.GetFloat(), tf_bot_wait_in_cover_max_time.GetFloat()); } this->m_ctActionDuration.Start(this->m_flDuration); if (actor->IsPlayerClass(TF_CLASS_SPY) && !actor->m_Shared.IsStealthed()) { actor->PressAltFireButton(); } return ActionResult<CTFBot>::Continue(); } ActionResult<CTFBot> CTFBotRetreatToCover::Update(CTFBot *actor, float dt) { const CKnownEntity *threat = actor->GetVisionInterface()->GetPrimaryKnownThreat(true); if (actor->m_Shared.InCond(TF_COND_INVULNERABLE)) { return ActionResult<CTFBot>::Done("I'm invulnerable - no need to reatreat!"); } if (!this->ShouldRetreat(actor)) { return ActionResult<CTFBot>::Done("No longer need to retreat"); } actor->EquipBestWeaponForThreat(threat); auto primary = static_cast<CTFWeaponBase *>(actor->Weapon_GetSlot(0)); bool reloading = false; if (primary != nullptr && actor->GetAmmoCount(TF_AMMO_PRIMARY) > 0 && actor->IsBarrageAndReloadWeapon(primary) && primary->Clip1() < primary->GetMaxClip1()) { actor->PressReloadButton(); reloading = true; } if (actor->GetLastKnownArea() == this->m_CoverArea && threat != nullptr) { this->m_CoverArea = this->FindCoverArea(actor); if (this->m_CoverArea == nullptr) { return ActionResult<CTFBot>::Done("My cover is exposed, and there is no other cover available!"); } } if (threat != nullptr) { this->m_ctActionDuration.Reset(); if (this->m_ctRecomputePath.IsElapsed()) { this->m_ctRecomputePath.Start(RandomFloat(0.3f, 0.5f)); CTFBotPathCost cost_func(actor, RETREAT_ROUTE); this->m_PathFollower.Compute(actor, this->m_CoverArea->GetCenter(), cost_func, 0.0f, true); } this->m_PathFollower.Update(actor); return ActionResult<CTFBot>::Continue(); } if (actor->IsPlayerClass(TF_CLASS_SPY) && actor->m_Shared.InCond(TF_COND_DISGUISED)) { return ActionResult<CTFBot>::Continue(); } if (actor->m_Shared.IsStealthed()) { actor->PressAltFireButton(); } if (this->m_DoneAction != nullptr) { return ActionResult<CTFBot>::ChangeTo(this->m_DoneAction, "Doing given action now that I'm in cover"); } } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnMoveToSuccess(CTFBot *actor, const Path *path) { return EventDesiredResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnMoveToFailure(CTFBot *actor, const Path *path, MoveToFailureType fail) { return EventDesiredResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnStuck(CTFBot *actor) { return EventDesiredResult<CTFBot>::Continue(); } QueryResponse CTFBotRetreatToCover::ShouldHurry(const INextBot *nextbot) const { return QueryResponse::YES; } CTFNavArea *CTFBotRetreatToCover::FindCoverArea(CTFBot *actor) { VPROF_BUDGET("CTFBotRetreatToCover::FindCoverArea", "NextBot"); } CSearchForCover::CSearchForCover() { } CSearchForCover::~CSearchForCover() { } bool CSearchForCover::operator()(CNavArea *area, CNavArea *priorArea, float travelDistanceSoFar) { VPROF_BUDGET("CSearchForCover::operator()", "NextBot"); CTestAreaAgainstThreats functor(); this->m_Actor->GetVisionInterface()->ForEachKnownEntity(functor); } bool CSearchForCover::ShouldSearch(CNavArea *adjArea, CNavArea *currentArea, float travelDistanceSoFar) { if (travelDistanceSoFar > tf_bot_retreat_to_cover_range.GetFloat()) { return false; } return (this->m_Actor->GetLocomotionInterface()->GetStepHeight() > currentArea->ComputeAdjacentConnectionHeightChange(adjArea)) } void CSearchForCover::PostSearch() { if (tf_bot_debug_retreat_to_cover.GetBool()) { FOR_EACH_VEC(this->m_Areas, i) { TheNavMesh->AddToSelectedSet(this->m_Areas[i]); } } } CTestAreaAgainstThreats::CTestAreaAgainstThreats() { } CTestAreaAgainstThreats::~CTestAreaAgainstThreats() { } bool CTestAreaAgainstThreats::Inspect(const CKnownEntity& known) { VPROF_BUDGET("CTestAreaAgainstThreats::Inspect", "NextBot"); if (this->m_Actor->IsEnemy(known.GetEntity())) { CNavArea *lastknown = this->m_Actor->GetLastKnownArea(); if (lastknown != nullptr && this->m_Area->IsPotentiallyVisible(lastknown)) { ++this->m_nVisible; } } return true; }
ConVar tf_bot_retreat_to_cover_range("tf_bot_retreat_to_cover_range", "1000", FCVAR_CHEAT); ConVar tf_bot_debug_retreat_to_cover("tf_bot_debug_retreat_to_cover", "0", FCVAR_CHEAT); ConVar tf_bot_wait_in_cover_min_time("tf_bot_wait_in_cover_min_time", "1", FCVAR_CHEAT); ConVar tf_bot_wait_in_cover_max_time("tf_bot_wait_in_cover_max_time", "2", FCVAR_CHEAT); CTFBotRetreatToCover::CTFBotRetreatToCover(Action<CTFBot *> *done_action) { this->m_flDuration = -1.0f; this->m_DoneAction = done_action; } CTFBotRetreatToCover::CTFBotRetreatToCover(float duration) { this->m_flDuration = duration; this->m_DoneAction = nullptr; } CTFBotRetreatToCover::~CTFBotRetreatToCover() { } const char *CTFBotRetreatToCover::GetName() const { return "RetreatToCover"; } ActionResult<CTFBot> CTFBotRetreatToCover::OnStart(CTFBot *actor, Action<CTFBot> *action) { this->m_PathFollower.SetMinLookAheadDistance(actor->GetDesiredPathLookAheadRange()); this->m_CoverArea = this->FindCoverArea(actor); if (this->m_CoverArea == nullptr) { return ActionResult<CTFBot>::Done("No cover available!"); } if (this->m_flDuration < 0.0f) { this->m_flDuration = RandomFloat(tf_bot_wait_in_cover_min_time.GetFloat(), tf_bot_wait_in_cover_max_time.GetFloat()); } this->m_ctActionDuration.Start(this->m_flDuration); if (actor->IsPlayerClass(TF_CLASS_SPY) && !actor->m_Shared.IsStealthed()) { actor->PressAltFireButton(); } return ActionResult<CTFBot>::Continue(); } ActionResult<CTFBot> CTFBotRetreatToCover::Update(CTFBot *actor, float dt) { const CKnownEntity *threat = actor->GetVisionInterface()->GetPrimaryKnownThreat(true);
if (!this->ShouldRetreat(actor)) { return ActionResult<CTFBot>::Done("No longer need to retreat"); } actor->EquipBestWeaponForThreat(threat); auto primary = static_cast<CTFWeaponBase *>(actor->Weapon_GetSlot(0)); bool reloading = false; if (primary != nullptr && actor->GetAmmoCount(TF_AMMO_PRIMARY) > 0 && actor->IsBarrageAndReloadWeapon(primary) && primary->Clip1() < primary->GetMaxClip1()) { actor->PressReloadButton(); reloading = true; } if (actor->GetLastKnownArea() == this->m_CoverArea && threat != nullptr) { this->m_CoverArea = this->FindCoverArea(actor); if (this->m_CoverArea == nullptr) { return ActionResult<CTFBot>::Done("My cover is exposed, and there is no other cover available!"); } } if (threat != nullptr) { this->m_ctActionDuration.Reset(); if (this->m_ctRecomputePath.IsElapsed()) { this->m_ctRecomputePath.Start(RandomFloat(0.3f, 0.5f)); CTFBotPathCost cost_func(actor, RETREAT_ROUTE); this->m_PathFollower.Compute(actor, this->m_CoverArea->GetCenter(), cost_func, 0.0f, true); } this->m_PathFollower.Update(actor); return ActionResult<CTFBot>::Continue(); } if (actor->IsPlayerClass(TF_CLASS_SPY) && actor->m_Shared.InCond(TF_COND_DISGUISED)) { return ActionResult<CTFBot>::Continue(); } if (actor->m_Shared.IsStealthed()) { actor->PressAltFireButton(); } if (this->m_DoneAction != nullptr) { return ActionResult<CTFBot>::ChangeTo(this->m_DoneAction, "Doing given action now that I'm in cover"); } } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnMoveToSuccess(CTFBot *actor, const Path *path) { return EventDesiredResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnMoveToFailure(CTFBot *actor, const Path *path, MoveToFailureType fail) { return EventDesiredResult<CTFBot>::Continue(); } EventDesiredResult<CTFBot> CTFBotRetreatToCover::OnStuck(CTFBot *actor) { return EventDesiredResult<CTFBot>::Continue(); } QueryResponse CTFBotRetreatToCover::ShouldHurry(const INextBot *nextbot) const { return QueryResponse::YES; } CTFNavArea *CTFBotRetreatToCover::FindCoverArea(CTFBot *actor) { VPROF_BUDGET("CTFBotRetreatToCover::FindCoverArea", "NextBot"); } CSearchForCover::CSearchForCover() { } CSearchForCover::~CSearchForCover() { } bool CSearchForCover::operator()(CNavArea *area, CNavArea *priorArea, float travelDistanceSoFar) { VPROF_BUDGET("CSearchForCover::operator()", "NextBot"); CTestAreaAgainstThreats functor(); this->m_Actor->GetVisionInterface()->ForEachKnownEntity(functor); } bool CSearchForCover::ShouldSearch(CNavArea *adjArea, CNavArea *currentArea, float travelDistanceSoFar) { if (travelDistanceSoFar > tf_bot_retreat_to_cover_range.GetFloat()) { return false; } return (this->m_Actor->GetLocomotionInterface()->GetStepHeight() > currentArea->ComputeAdjacentConnectionHeightChange(adjArea)) } void CSearchForCover::PostSearch() { if (tf_bot_debug_retreat_to_cover.GetBool()) { FOR_EACH_VEC(this->m_Areas, i) { TheNavMesh->AddToSelectedSet(this->m_Areas[i]); } } } CTestAreaAgainstThreats::CTestAreaAgainstThreats() { } CTestAreaAgainstThreats::~CTestAreaAgainstThreats() { } bool CTestAreaAgainstThreats::Inspect(const CKnownEntity& known) { VPROF_BUDGET("CTestAreaAgainstThreats::Inspect", "NextBot"); if (this->m_Actor->IsEnemy(known.GetEntity())) { CNavArea *lastknown = this->m_Actor->GetLastKnownArea(); if (lastknown != nullptr && this->m_Area->IsPotentiallyVisible(lastknown)) { ++this->m_nVisible; } } return true; }
if (actor->m_Shared.InCond(TF_COND_INVULNERABLE)) { return ActionResult<CTFBot>::Done("I'm invulnerable - no need to reatreat!"); }
if_condition
[ { "content": "Returns 1, 2, or 1 + 2\n\n==================\n\n*/\n\nint __cdecl BoxOnPlaneSide (const float *emins, const float *emaxs, const cplane_t *p)\n\n{\n\n\tAssert( s_bMathlibInitialized );\n\n\tfloat\tdist1, dist2;\n\n\tint\t\tsides;\n\n\n\n\t// fast axial cases\n\n\tif (p->type < 3)\n\n\t{\n\n\t\tif (...
C++
copasi/UI/CQReportDM.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
#include <QtCore/QString> #include <QtCore/QList> #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "report/CReportDefinition.h" #include "report/CReportDefinitionVector.h" #include "CQMessageBox.h" #include "CQReportDM.h" #include "qtUtilities.h" CQReportDM::CQReportDM(QObject *parent) : CQBaseDataModel(parent) { } int CQReportDM::rowCount(const QModelIndex& C_UNUSED(parent)) const { return (int)(*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->size() + 1; } int CQReportDM::columnCount(const QModelIndex& C_UNUSED(parent)) const { return TOTAL_COLS_REPORTS; } Qt::ItemFlags CQReportDM::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled; if (index.column() == COL_NAME_REPORTS) return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; else return QAbstractItemModel::flags(index); } QVariant CQReportDM::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= rowCount()) return QVariant(); if (index.column() > 0 && role == Qt::ForegroundRole && !(flags(index) & Qt::ItemIsEditable)) return QColor(Qt::darkGray); if (role == Qt::DisplayRole || role == Qt::EditRole) { if (isDefaultRow(index)) { switch (index.column()) { case COL_ROW_NUMBER: return QVariant(QString("")); case COL_NAME_REPORTS: return QVariant(QString("New Report")); default: return QVariant(QString("")); } } else { CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->operator[](index.row()); switch (index.column()) { case COL_ROW_NUMBER: return QVariant(index.row() + 1); case COL_NAME_REPORTS: return QVariant(QString(FROM_UTF8(pRepDef->getObjectName()))); } } } return QVariant(); } QVariant CQReportDM::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case COL_ROW_NUMBER: return QVariant(QString("#")); case COL_NAME_REPORTS: return QVariant(QString("Name")); default: return QVariant(); } } else return QString("%1").arg(section + 1); } bool CQReportDM::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { bool defaultRow = isDefaultRow(index); if (defaultRow) { if (index.data() != value) insertRow(); else return false; } CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->operator[](index.row()); if (index.column() == COL_NAME_REPORTS) pRepDef->setObjectName(TO_UTF8(value.toString())); if (defaultRow && this->index(index.row(), COL_NAME_REPORTS).data().toString() == "report") pRepDef->setObjectName(TO_UTF8(createNewName("report", COL_NAME_REPORTS))); emit dataChanged(index, index); emit notifyGUI(ListViews::REPORT, ListViews::CHANGE, pRepDef->getKey()); } return true; } bool CQReportDM::insertRows(int position, int rows, const QModelIndex&) { beginInsertRows(QModelIndex(), position, position + rows - 1); for (int row = 0; row < rows; ++row) { CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->createReportDefinition(TO_UTF8(createNewName("report", COL_NAME_REPORTS)), ""); emit notifyGUI(ListViews::REPORT, ListViews::ADD, pRepDef->getKey()); } endInsertRows(); return true; } bool CQReportDM::removeRows(int position, int rows, const QModelIndex&) { if (rows <= 0) return true; CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0]; if (pDataModel == NULL) return false; CCopasiVector< CReportDefinition > * pReportList = pDataModel->getReportDefinitionList(); if (pReportList == NULL) return false; beginRemoveRows(QModelIndex(), position, position + rows - 1); for (int row = 0; row < rows; ++row) { CReportDefinition * pReport = (*pReportList)[position]; if (pReport == NULL) continue; std::set< const CCopasiObject * > Tasks; std::set< const CCopasiObject * > DeletedObjects; DeletedObjects.insert(pReport); if (pDataModel->appendDependentTasks(DeletedObjects, Tasks)) { std::set< const CCopasiObject * >::iterator it = Tasks.begin(); std::set< const CCopasiObject * >::iterator end = Tasks.end(); for (; it != end; ++it) { const CCopasiTask * pTask = static_cast< const CCopasiTask *>(*it); const_cast< CCopasiTask * >(pTask)->getReport().setReportDefinition(NULL); } } std::string deletedKey = pReport->getKey(); pReportList->remove(pReport); emit notifyGUI(ListViews::REPORT, ListViews::DELETE, deletedKey); } endRemoveRows(); return true; } bool CQReportDM::removeRows(QModelIndexList rows, const QModelIndex&) { if (rows.isEmpty()) return false; CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0]; assert(pDataModel != NULL); CCopasiVector< CReportDefinition > * pReportList = pDataModel->getReportDefinitionList(); if (pReportList == NULL) return false; QList< CReportDefinition * > Reports; QModelIndexList::const_iterator i; for (i = rows.begin(); i != rows.end(); ++i) { if (!isDefaultRow(*i) && (*pReportList)[(*i).row()]) Reports.append((*pReportList)[(*i).row()]); } QList< CReportDefinition * >::const_iterator j; for (j = Reports.begin(); j != Reports.end(); ++j) { CReportDefinition * pReport = *j; size_t delRow = pReportList->getIndex(pReport); if (delRow != C_INVALID_INDEX) { std::set< const CCopasiObject * > DeletedObjects; DeletedObjects.insert(pReport); QMessageBox::StandardButton choice = CQMessageBox::confirmDelete(NULL, "report", FROM_UTF8(pReport->getObjectName()), DeletedObjects); if (choice == QMessageBox::Ok) { removeRow((int) delRow); } } } return true; }
#include <QtCore/QString> #include <QtCore/QList> #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "report/CReportDefinition.h" #include "report/CReportDefinitionVector.h" #include "CQMessageBox.h" #include "CQReportDM.h" #include "qtUtilities.h" CQReportDM::CQReportDM(QObject *parent) : CQBaseDataModel(parent) { } int CQReportDM::rowCount(const QModelIndex& C_UNUSED(parent)) const { return (int)(*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->size() + 1; } int CQReportDM::columnCount(const QModelIndex& C_UNUSED(parent)) const { return TOTAL_COLS_REPORTS; } Qt::ItemFlags CQReportDM::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled;
} QVariant CQReportDM::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() >= rowCount()) return QVariant(); if (index.column() > 0 && role == Qt::ForegroundRole && !(flags(index) & Qt::ItemIsEditable)) return QColor(Qt::darkGray); if (role == Qt::DisplayRole || role == Qt::EditRole) { if (isDefaultRow(index)) { switch (index.column()) { case COL_ROW_NUMBER: return QVariant(QString("")); case COL_NAME_REPORTS: return QVariant(QString("New Report")); default: return QVariant(QString("")); } } else { CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->operator[](index.row()); switch (index.column()) { case COL_ROW_NUMBER: return QVariant(index.row() + 1); case COL_NAME_REPORTS: return QVariant(QString(FROM_UTF8(pRepDef->getObjectName()))); } } } return QVariant(); } QVariant CQReportDM::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case COL_ROW_NUMBER: return QVariant(QString("#")); case COL_NAME_REPORTS: return QVariant(QString("Name")); default: return QVariant(); } } else return QString("%1").arg(section + 1); } bool CQReportDM::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { bool defaultRow = isDefaultRow(index); if (defaultRow) { if (index.data() != value) insertRow(); else return false; } CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->operator[](index.row()); if (index.column() == COL_NAME_REPORTS) pRepDef->setObjectName(TO_UTF8(value.toString())); if (defaultRow && this->index(index.row(), COL_NAME_REPORTS).data().toString() == "report") pRepDef->setObjectName(TO_UTF8(createNewName("report", COL_NAME_REPORTS))); emit dataChanged(index, index); emit notifyGUI(ListViews::REPORT, ListViews::CHANGE, pRepDef->getKey()); } return true; } bool CQReportDM::insertRows(int position, int rows, const QModelIndex&) { beginInsertRows(QModelIndex(), position, position + rows - 1); for (int row = 0; row < rows; ++row) { CReportDefinition *pRepDef = (*CCopasiRootContainer::getDatamodelList())[0]->getReportDefinitionList()->createReportDefinition(TO_UTF8(createNewName("report", COL_NAME_REPORTS)), ""); emit notifyGUI(ListViews::REPORT, ListViews::ADD, pRepDef->getKey()); } endInsertRows(); return true; } bool CQReportDM::removeRows(int position, int rows, const QModelIndex&) { if (rows <= 0) return true; CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0]; if (pDataModel == NULL) return false; CCopasiVector< CReportDefinition > * pReportList = pDataModel->getReportDefinitionList(); if (pReportList == NULL) return false; beginRemoveRows(QModelIndex(), position, position + rows - 1); for (int row = 0; row < rows; ++row) { CReportDefinition * pReport = (*pReportList)[position]; if (pReport == NULL) continue; std::set< const CCopasiObject * > Tasks; std::set< const CCopasiObject * > DeletedObjects; DeletedObjects.insert(pReport); if (pDataModel->appendDependentTasks(DeletedObjects, Tasks)) { std::set< const CCopasiObject * >::iterator it = Tasks.begin(); std::set< const CCopasiObject * >::iterator end = Tasks.end(); for (; it != end; ++it) { const CCopasiTask * pTask = static_cast< const CCopasiTask *>(*it); const_cast< CCopasiTask * >(pTask)->getReport().setReportDefinition(NULL); } } std::string deletedKey = pReport->getKey(); pReportList->remove(pReport); emit notifyGUI(ListViews::REPORT, ListViews::DELETE, deletedKey); } endRemoveRows(); return true; } bool CQReportDM::removeRows(QModelIndexList rows, const QModelIndex&) { if (rows.isEmpty()) return false; CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0]; assert(pDataModel != NULL); CCopasiVector< CReportDefinition > * pReportList = pDataModel->getReportDefinitionList(); if (pReportList == NULL) return false; QList< CReportDefinition * > Reports; QModelIndexList::const_iterator i; for (i = rows.begin(); i != rows.end(); ++i) { if (!isDefaultRow(*i) && (*pReportList)[(*i).row()]) Reports.append((*pReportList)[(*i).row()]); } QList< CReportDefinition * >::const_iterator j; for (j = Reports.begin(); j != Reports.end(); ++j) { CReportDefinition * pReport = *j; size_t delRow = pReportList->getIndex(pReport); if (delRow != C_INVALID_INDEX) { std::set< const CCopasiObject * > DeletedObjects; DeletedObjects.insert(pReport); QMessageBox::StandardButton choice = CQMessageBox::confirmDelete(NULL, "report", FROM_UTF8(pReport->getObjectName()), DeletedObjects); if (choice == QMessageBox::Ok) { removeRow((int) delRow); } } } return true; }
if (index.column() == COL_NAME_REPORTS) return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; else return QAbstractItemModel::flags(index);
if_condition
[ { "content": "class FSwapClass : public FSwapBase<IndexType, ReturnType>\n\n{\n\nprotected:\n\n /**\n\n * Default constructor\n\n */\n\n FSwapClass():\n\n FSwapBase<IndexType, ReturnType>(),\n\n mpType(NULL),\n\n mpSwap(NULL)\n\n {}\n\n\n\npublic:\n\n /**\n\n * Specific constructor\n\n * @p...
C++
source/exhumed/src/bubbles.cpp
Talon1024/Raze
d92f56f36f246f12ea4012b3f9d5eb6c4abe0070
#include "ns.h" #include "bubbles.h" #include "runlist.h" #include "exhumed.h" #include "random.h" #include "engine.h" #include "sequence.h" #include "move.h" #include "init.h" #include "runlist.h" #include "init.h" #include "anims.h" #include <assert.h> BEGIN_PS_NS #define kMaxBubbles 200 #define kMaxMachines 125 struct Bubble { short nFrame; short nSeq; short nSprite; short nRun; }; struct machine { short _0; short nSprite; short _4; }; short BubbleCount = 0; short nFreeCount; short nMachineCount; uint8_t nBubblesFree[kMaxBubbles]; machine Machine[kMaxMachines]; Bubble BubbleList[kMaxBubbles]; static SavegameHelper sgh("bubbles", SV(BubbleCount), SV(nFreeCount), SV(nMachineCount), SA(nBubblesFree), SA(Machine), SA(BubbleList), nullptr); void InitBubbles() { BubbleCount = 0; nMachineCount = 0; for (int i = 0; i < kMaxBubbles; i++) { nBubblesFree[i] = i; } nFreeCount = kMaxBubbles; } void DestroyBubble(short nBubble) { short nSprite = BubbleList[nBubble].nSprite; runlist_DoSubRunRec(sprite[nSprite].lotag - 1); runlist_DoSubRunRec(sprite[nSprite].owner); runlist_SubRunRec(BubbleList[nBubble].nRun); mydeletesprite(nSprite); nBubblesFree[nFreeCount] = nBubble; nFreeCount++; } short GetBubbleSprite(short nBubble) { return BubbleList[nBubble].nSprite; } int BuildBubble(int x, int y, int z, short nSector) { int nSize = RandomSize(3); if (nSize > 4) { nSize -= 4; } if (nFreeCount <= 0) { return -1; } nFreeCount--; uint8_t nBubble = nBubblesFree[nFreeCount]; int nSprite = insertsprite(nSector, 402); assert(nSprite >= 0 && nSprite < kMaxSprites); sprite[nSprite].x = x; sprite[nSprite].y = y; sprite[nSprite].z = z; sprite[nSprite].cstat = 0; sprite[nSprite].shade = -32; sprite[nSprite].pal = 0; sprite[nSprite].clipdist = 5; sprite[nSprite].xrepeat = 40; sprite[nSprite].yrepeat = 40; sprite[nSprite].xoffset = 0; sprite[nSprite].yoffset = 0; sprite[nSprite].picnum = 1; sprite[nSprite].ang = inita; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = -1200; sprite[nSprite].hitag = -1; sprite[nSprite].extra = -1; sprite[nSprite].lotag = runlist_HeadRun() + 1; BubbleList[nBubble].nSprite = nSprite; BubbleList[nBubble].nFrame = 0; BubbleList[nBubble].nSeq = SeqOffsets[kSeqBubble] + nSize; sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nBubble | 0x140000); BubbleList[nBubble].nRun = runlist_AddRunRec(NewRun, nBubble | 0x140000); return nBubble | 0x140000; } void FuncBubble(int a, int UNUSED(b), int nRun) { short nBubble = RunData[nRun].nVal; assert(nBubble >= 0 && nBubble < kMaxBubbles); short nSprite = BubbleList[nBubble].nSprite; short nSeq = BubbleList[nBubble].nSeq; int nMessage = a & kMessageMask; switch (nMessage) { case 0x20000: { seq_MoveSequence(nSprite, nSeq, BubbleList[nBubble].nFrame); BubbleList[nBubble].nFrame++; if (BubbleList[nBubble].nFrame >= SeqSize[nSeq]) { BubbleList[nBubble].nFrame = 0; } sprite[nSprite].z += sprite[nSprite].zvel; short nSector = sprite[nSprite].sectnum; if (sprite[nSprite].z <= sector[nSector].ceilingz) { short nSectAbove = SectAbove[nSector]; if (sprite[nSprite].hitag > -1 && nSectAbove != -1) { BuildAnim(-1, 70, 0, sprite[nSprite].x, sprite[nSprite].y, sector[nSectAbove].floorz, nSectAbove, 64, 0); } DestroyBubble(nBubble); } return; } case 0x90000: { seq_PlotSequence(a & 0xFFFF, nSeq, BubbleList[nBubble].nFrame, 1); tsprite[a & 0xFFFF].owner = -1; return; } case 0x80000: case 0xA0000: return; default: Printf("unknown msg %d for Bubble\n", nMessage); return; } } void DoBubbleMachines() { for (int i = 0; i < nMachineCount; i++) { Machine[i]._0--; if (Machine[i]._0 <= 0) { Machine[i]._0 = (RandomWord() % Machine[i]._4) + 30; int nSprite = Machine[i].nSprite; BuildBubble(sprite[nSprite].x, sprite[nSprite].y, sprite[nSprite].z, sprite[nSprite].sectnum); } } } void BuildBubbleMachine(int nSprite) { if (nMachineCount >= kMaxMachines) { I_Error("too many bubble machines in level %d\n", levelnew); exit(-1); } Machine[nMachineCount]._4 = 75; Machine[nMachineCount].nSprite = nSprite; Machine[nMachineCount]._0 = Machine[nMachineCount]._4; nMachineCount++; sprite[nSprite].cstat = 0x8000; } void DoBubbles(int nPlayer) { int x, y, z; short nSector; WheresMyMouth(nPlayer, &x, &y, &z, &nSector); int nBubble = BuildBubble(x, y, z, nSector); int nSprite = GetBubbleSprite(nBubble); sprite[nSprite].hitag = nPlayer; } END_PS_NS
#include "ns.h" #include "bubbles.h" #include "runlist.h" #include "exhumed.h" #include "random.h" #include "engine.h" #include "sequence.h" #include "move.h" #include "init.h" #include "runlist.h" #include "init.h" #include "anims.h" #include <assert.h> BEGIN_PS_NS #define kMaxBubbles 200 #define kMaxMachines 125 struct Bubble { short nFrame; short nSeq; short nSprite; short nRun; }; struct machine { short _0; short nSprite; short _4; }; short BubbleCount = 0; short nFreeCount; short nMachineCount; uint8_t nBubblesFree[kMaxBubbles]; machine Machine[kMaxMachines]; Bubble BubbleList[kMaxBubbles]; static SavegameHelper sgh("bubbles", SV(BubbleCount), SV(nFreeCount), SV(nMachineCount), SA(nBubblesFree), SA(Machine), SA(BubbleList), nullptr); void InitBubbles() { BubbleCount = 0; nMachineCount = 0; for (int i = 0; i < kMaxBubbles; i++) { nBubblesFree[i] = i; } nFreeCount = kMaxBubbles; }
short GetBubbleSprite(short nBubble) { return BubbleList[nBubble].nSprite; } int BuildBubble(int x, int y, int z, short nSector) { int nSize = RandomSize(3); if (nSize > 4) { nSize -= 4; } if (nFreeCount <= 0) { return -1; } nFreeCount--; uint8_t nBubble = nBubblesFree[nFreeCount]; int nSprite = insertsprite(nSector, 402); assert(nSprite >= 0 && nSprite < kMaxSprites); sprite[nSprite].x = x; sprite[nSprite].y = y; sprite[nSprite].z = z; sprite[nSprite].cstat = 0; sprite[nSprite].shade = -32; sprite[nSprite].pal = 0; sprite[nSprite].clipdist = 5; sprite[nSprite].xrepeat = 40; sprite[nSprite].yrepeat = 40; sprite[nSprite].xoffset = 0; sprite[nSprite].yoffset = 0; sprite[nSprite].picnum = 1; sprite[nSprite].ang = inita; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = -1200; sprite[nSprite].hitag = -1; sprite[nSprite].extra = -1; sprite[nSprite].lotag = runlist_HeadRun() + 1; BubbleList[nBubble].nSprite = nSprite; BubbleList[nBubble].nFrame = 0; BubbleList[nBubble].nSeq = SeqOffsets[kSeqBubble] + nSize; sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nBubble | 0x140000); BubbleList[nBubble].nRun = runlist_AddRunRec(NewRun, nBubble | 0x140000); return nBubble | 0x140000; } void FuncBubble(int a, int UNUSED(b), int nRun) { short nBubble = RunData[nRun].nVal; assert(nBubble >= 0 && nBubble < kMaxBubbles); short nSprite = BubbleList[nBubble].nSprite; short nSeq = BubbleList[nBubble].nSeq; int nMessage = a & kMessageMask; switch (nMessage) { case 0x20000: { seq_MoveSequence(nSprite, nSeq, BubbleList[nBubble].nFrame); BubbleList[nBubble].nFrame++; if (BubbleList[nBubble].nFrame >= SeqSize[nSeq]) { BubbleList[nBubble].nFrame = 0; } sprite[nSprite].z += sprite[nSprite].zvel; short nSector = sprite[nSprite].sectnum; if (sprite[nSprite].z <= sector[nSector].ceilingz) { short nSectAbove = SectAbove[nSector]; if (sprite[nSprite].hitag > -1 && nSectAbove != -1) { BuildAnim(-1, 70, 0, sprite[nSprite].x, sprite[nSprite].y, sector[nSectAbove].floorz, nSectAbove, 64, 0); } DestroyBubble(nBubble); } return; } case 0x90000: { seq_PlotSequence(a & 0xFFFF, nSeq, BubbleList[nBubble].nFrame, 1); tsprite[a & 0xFFFF].owner = -1; return; } case 0x80000: case 0xA0000: return; default: Printf("unknown msg %d for Bubble\n", nMessage); return; } } void DoBubbleMachines() { for (int i = 0; i < nMachineCount; i++) { Machine[i]._0--; if (Machine[i]._0 <= 0) { Machine[i]._0 = (RandomWord() % Machine[i]._4) + 30; int nSprite = Machine[i].nSprite; BuildBubble(sprite[nSprite].x, sprite[nSprite].y, sprite[nSprite].z, sprite[nSprite].sectnum); } } } void BuildBubbleMachine(int nSprite) { if (nMachineCount >= kMaxMachines) { I_Error("too many bubble machines in level %d\n", levelnew); exit(-1); } Machine[nMachineCount]._4 = 75; Machine[nMachineCount].nSprite = nSprite; Machine[nMachineCount]._0 = Machine[nMachineCount]._4; nMachineCount++; sprite[nSprite].cstat = 0x8000; } void DoBubbles(int nPlayer) { int x, y, z; short nSector; WheresMyMouth(nPlayer, &x, &y, &z, &nSector); int nBubble = BuildBubble(x, y, z, nSector); int nSprite = GetBubbleSprite(nBubble); sprite[nSprite].hitag = nPlayer; } END_PS_NS
void DestroyBubble(short nBubble) { short nSprite = BubbleList[nBubble].nSprite; runlist_DoSubRunRec(sprite[nSprite].lotag - 1); runlist_DoSubRunRec(sprite[nSprite].owner); runlist_SubRunRec(BubbleList[nBubble].nRun); mydeletesprite(nSprite); nBubblesFree[nFreeCount] = nBubble; nFreeCount++; }
function_block-full_function
[ { "content": "struct TestSpanOpt0 { static const int Flags = 0; };\n", "file_path": "source/common/rendering/polyrenderer/drawers/screen_triangle.h", "rank": 1, "score": 232160.25810981102 }, { "content": "struct BlendColorOpt_Add { static const int Flags = 0; };\n", "file_path": "source...
C++
source/Core/ElementStyleProxy.cpp
weimingtom/rocketsquirrel
1d2a22672b7bacf2775d71c0164dee0ce419da2d
#include "ElementStyleProxy.h" #include "ElementInterface.h" #include "VariantInterface.h" #include <sqbind/SquirrelBind.h> #include "../Debug.h" #include "../BindingUtil.h" #include "../NamespaceHelper.h" #include "ElementWrapperDerived.h" namespace Rocket { namespace Core { namespace Squirrel { ElementStyleProxy::ElementStyleProxy(const ElementStyleProxy& other) : m_pElement(0x0) { operator=(other); } ElementStyleProxy::ElementStyleProxy(Rocket::Core::Element* pElement) : m_pElement(0x0) { SetElement(pElement); } ElementStyleProxy::ElementStyleProxy() : m_pElement(0x0) { } void ElementStyleProxy::SetElement(Rocket::Core::Element* pElement) { m_pElement = pElement; m_pElement->AddReference(); } ElementStyleProxy::~ElementStyleProxy() { if (m_pElement) { m_pElement->RemoveReference(); } } ElementStyleProxy& ElementStyleProxy::operator= (const ElementStyleProxy& other) { ROCKETSQUIRREL_ASSERT(other.m_pElement != 0x0); SetElement(other.m_pElement); return *this; } SQInteger ElementStyleProxy::SetAttr(HSQUIRRELVM vm) { sqb::StackHandler sh(vm); ROCKETSQUIRREL_ASSERT(sh.GetParamCount() >= 3); ROCKETSQUIRREL_ASSERT(sh.IsString(2)); Rocket::Core::String key = Rocket::Core::String(sh.GetString(2)).Replace("_", "-"); Rocket::Core::String value; if (sh.IsString(3)) { value = sh.GetString(3); } if (sh.IsNumber(3)) { Rocket::Core::Variant vari; vari.Set(sh.GetNumber<float>(3)); value = vari.Get<Rocket::Core::String>(); } if (!m_pElement->SetProperty(key.CString(), value.CString())) { return sh.ThrowNull(); } return sh.Return(); } SQInteger ElementStyleProxy::GetAttr(HSQUIRRELVM vm) { sqb::StackHandler sh(vm); ROCKETSQUIRREL_ASSERT(sh.GetParamCount() >= 2); ROCKETSQUIRREL_ASSERT(sh.IsString(2)); Rocket::Core::String key = Rocket::Core::String(sh.GetString(2)).Replace("_", "-"); const Rocket::Core::Property* property = m_pElement->GetProperty(key.CString()); if (!property) { return sh.ThrowNull(); } mCache = property->ToString(); return sh.Return(mCache.CString()); } void ElementStyleProxy::Bind(HSQUIRRELVM vm) { sqb::ClassDefinition<ElementStyleProxy> cE(vm, -1, _SC("Style")); cE.Constructor(&NoConstructable); cE.NativeClassFunction(&ElementStyleProxy::SetAttr, _SC("_set"), sqb::FunctionOptions().ParamCheckCount(-2).TypeMask(_SC("xss|i|f"))); cE.NativeClassFunction(&ElementStyleProxy::GetAttr, _SC("_get"), sqb::FunctionOptions().ParamCheckCount(-2).TypeMask(_SC("xs"))); } } } }
#include "ElementStyleProxy.h" #include "ElementInterface.h" #include "VariantInterface.h" #include <sqbind/SquirrelBind.h> #include "../Debug.h" #include "../BindingUtil.h" #include "../NamespaceHelper.h" #include "ElementWrapperDerived.h" namespace Rocket { namespace Core { namespace Squirrel { ElementStyleProxy::ElementStyleProxy(const ElementStyleProxy& other) : m_pElement(0x0) { operator=(other); } ElementStyleProxy::ElementStyleProxy(Rocket::Core::Element* pElement) : m_pElement(0x0) { SetElement(pElement); } ElementStyleProxy::ElementStyleProxy() : m_pElement(0x0) { } void ElementStyleProxy::SetElement(Rocket::Core::Element* pElement) { m_pElement = pElement; m_pElement->AddReference(); } ElementStyleProxy::~ElementStyleProxy() { if (m_pElement) { m_pElement->RemoveReference(); } } ElementStyleProxy& ElementStyleProxy::operator= (const ElementStyleProxy& other) { ROCKETSQUIRREL_ASSERT(other.m_pElement != 0x0); SetElement(other.m_pElement); return *this; } SQInteger ElementStyleProxy::SetAttr(HSQUIRRELVM vm) { sqb::StackHandler sh(vm); ROCKETSQUIRREL_ASSERT(sh.GetParamCount() >= 3); ROCKETSQUIRREL_ASSERT(sh.IsString(2)); Rocket::Core::String key = Rocket::Core::String(sh.GetString(2)).Replace("_", "-"); Rocket::Core::String value; if (sh.IsString(3)) { value = sh.GetString(3); } if (sh.IsNumber(3)) { Rocket::Core::Variant vari; vari.Set(sh.GetNumber<float>(3)); value = vari.Get<Rocket::Core::String>(); } if (!m_pElement->SetProperty(key.CString(), value.CString())) { return sh.ThrowNull(); } return sh.Return(); }
void ElementStyleProxy::Bind(HSQUIRRELVM vm) { sqb::ClassDefinition<ElementStyleProxy> cE(vm, -1, _SC("Style")); cE.Constructor(&NoConstructable); cE.NativeClassFunction(&ElementStyleProxy::SetAttr, _SC("_set"), sqb::FunctionOptions().ParamCheckCount(-2).TypeMask(_SC("xss|i|f"))); cE.NativeClassFunction(&ElementStyleProxy::GetAttr, _SC("_get"), sqb::FunctionOptions().ParamCheckCount(-2).TypeMask(_SC("xs"))); } } } }
SQInteger ElementStyleProxy::GetAttr(HSQUIRRELVM vm) { sqb::StackHandler sh(vm); ROCKETSQUIRREL_ASSERT(sh.GetParamCount() >= 2); ROCKETSQUIRREL_ASSERT(sh.IsString(2)); Rocket::Core::String key = Rocket::Core::String(sh.GetString(2)).Replace("_", "-"); const Rocket::Core::Property* property = m_pElement->GetProperty(key.CString()); if (!property) { return sh.ThrowNull(); } mCache = property->ToString(); return sh.Return(mCache.CString()); }
function_block-full_function
[ { "content": "class ROCKETSQUIRRELDLL_API Module : public Rocket::Core::Plugin\n\n{\n\nprivate:\n\n\n\n\tvoid OnInitialise();\n\n\tvoid OnShutdown();\n\n\n\n\tstatic Module* s_pInstance;\n\n\tbool mInitialized;\n\n\n\n\tScriptInterface* m_pScriptInterface;\n\n\n\npublic:\n\n\n\n\t/*! Module entry point\n\n\t * ...
C++
webkit/glue/event_conversion.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
#include "config.h" #include "base/compiler_specific.h" #if defined(OS_WIN) #include <windows.h> #else #include "KeyboardCodes.h" #endif #include "StringImpl.h" MSVC_PUSH_WARNING_LEVEL(0); #include "PlatformKeyboardEvent.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "Widget.h" MSVC_POP_WARNING(); #undef LOG #include "base/gfx/point.h" #include "base/logging.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/webinputevent.h" #include "webkit/glue/webkit_glue.h" using namespace WebCore; int MakePlatformMouseEvent::last_click_count_ = 0; uint32 MakePlatformMouseEvent::last_click_time_ = 0; MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget, const WebMouseEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_button = static_cast<MouseButton>(e.button); m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_modifierFlags = e.modifiers; m_timestamp = e.timestamp_sec; static IntPoint last_click_position; static MouseButton last_click_button = LeftButton; const uint32 current_time = static_cast<uint32>(m_timestamp * 1000); #if defined(OS_WIN) const bool cancel_previous_click = (abs(last_click_position.x() - m_position.x()) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2)) || (abs(last_click_position.y() - m_position.y()) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2)) || ((current_time - last_click_time_) > GetDoubleClickTime()); #elif defined(OS_MACOSX) || defined(OS_LINUX) const bool cancel_previous_click = false; #endif switch (e.type) { case WebInputEvent::MOUSE_MOVE: case WebInputEvent::MOUSE_LEAVE: if (cancel_previous_click) { last_click_count_ = 0; last_click_position = IntPoint(); last_click_time_ = 0; } m_clickCount = last_click_count_; m_eventType = MouseEventMoved; break; case WebInputEvent::MOUSE_DOWN: case WebInputEvent::MOUSE_DOUBLE_CLICK: if (!cancel_previous_click && (m_button == last_click_button)) { ++last_click_count_; } else { last_click_count_ = 1; last_click_position = m_position; } last_click_time_ = current_time; last_click_button = m_button; m_clickCount = last_click_count_; m_eventType = MouseEventPressed; break; case WebInputEvent::MOUSE_UP: m_clickCount = last_click_count_; m_eventType = MouseEventReleased; break; default: NOTREACHED() << "unexpected mouse event type"; } if (webkit_glue::IsLayoutTestMode()) { m_clickCount = e.layout_test_click_count; } } MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget, const WebMouseWheelEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_deltaX = static_cast<float>(e.delta_x); m_deltaY = static_cast<float>(e.delta_y); m_charsToScrollPerDelta = 1; m_linesToScrollPerDelta = 1; m_pageXScrollMode = false; m_pageYScrollMode = false; m_isAccepted = false; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_isContinuous = false; m_continuousDeltaX = 0; m_continuousDeltaY = 0; } static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType( WebInputEvent::Type type) { switch (type) { case WebInputEvent::KEY_UP: return PlatformKeyboardEvent::KeyUp; case WebInputEvent::KEY_DOWN: return PlatformKeyboardEvent::KeyDown; case WebInputEvent::CHAR: return PlatformKeyboardEvent::Char; default: ASSERT_NOT_REACHED(); } return PlatformKeyboardEvent::KeyDown; } static inline String ToSingleCharacterString(UChar c) { return String(&c, 1); } static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) { switch (keyCode) { case VK_MENU: return "Alt"; case VK_CONTROL: return "Control"; case VK_SHIFT: return "Shift"; case VK_CAPITAL: return "CapsLock"; case VK_LWIN: case VK_RWIN: return "Win"; case VK_CLEAR: return "Clear"; case VK_DOWN: return "Down"; case VK_END: return "End"; case VK_RETURN: return "Enter"; case VK_EXECUTE: return "Execute"; case VK_F1: return "F1"; case VK_F2: return "F2"; case VK_F3: return "F3"; case VK_F4: return "F4"; case VK_F5: return "F5"; case VK_F6: return "F6"; case VK_F7: return "F7"; case VK_F8: return "F8"; case VK_F9: return "F9"; case VK_F10: return "F11"; case VK_F12: return "F12"; case VK_F13: return "F13"; case VK_F14: return "F14"; case VK_F15: return "F15"; case VK_F16: return "F16"; case VK_F17: return "F17"; case VK_F18: return "F18"; case VK_F19: return "F19"; case VK_F20: return "F20"; case VK_F21: return "F21"; case VK_F22: return "F22"; case VK_F23: return "F23"; case VK_F24: return "F24"; case VK_HELP: return "Help"; case VK_HOME: return "Home"; case VK_INSERT: return "Insert"; case VK_LEFT: return "Left"; case VK_NEXT: return "PageDown"; case VK_PRIOR: return "PageUp"; case VK_PAUSE: return "Pause"; case VK_SNAPSHOT: return "PrintScreen"; case VK_RIGHT: return "Right"; case VK_SCROLL: return "Scroll"; case VK_SELECT: return "Select"; case VK_UP: return "Up"; case VK_DELETE: return "U+007F"; default: return String::format("U+%04X", toupper(keyCode)); } } MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e) { #if defined(OS_WIN) || defined(OS_LINUX) m_type = ToPlatformKeyboardEventType(e.type); if (m_type == Char || m_type == KeyDown) m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code); if (m_type != Char) m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code); if (m_type == Char || m_type == KeyDown || m_type == KeyUp || m_type == RawKeyDown) { m_windowsVirtualKeyCode = e.key_code; } else { m_windowsVirtualKeyCode = 0; } #endif m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0; m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; #if defined(OS_WIN) m_isSystemKey = e.system_key; #endif } void MakePlatformKeyboardEvent::SetKeyType(Type type) { ASSERT(m_type == KeyDown); ASSERT(type == RawKeyDown || type == Char); m_type = type; if (type == RawKeyDown) { m_text = String(); m_unmodifiedText = String(); } else { m_keyIdentifier = String(); m_windowsVirtualKeyCode = 0; } } bool MakePlatformKeyboardEvent::IsCharacterKey() const { switch (windowsVirtualKeyCode()) { #if defined(OS_WIN) case VK_BACK: case VK_ESCAPE: #endif return false; default: break; } return true; }
#include "config.h" #include "base/compiler_specific.h" #if defined(OS_WIN) #include <windows.h> #else #include "KeyboardCodes.h" #endif #include "StringImpl.h" MSVC_PUSH_WARNING_LEVEL(0); #include "PlatformKeyboardEvent.h" #include "PlatformMouseEvent.h" #include "PlatformWheelEvent.h" #include "Widget.h" MSVC_POP_WARNING(); #undef LOG #include "base/gfx/point.h" #include "base/logging.h" #include "webkit/glue/event_conversion.h" #include "webkit/glue/webinputevent.h" #include "webkit/glue/webkit_glue.h" using namespace WebCore; int MakePlatformMouseEvent::last_click_count_ = 0; uint32 MakePlatformMouseEvent::last_click_time_ = 0; MakePlatformMouseEvent::MakePlatformMouseEvent(Widget* widget, const WebMouseEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_button = static_cast<MouseButton>(e.button); m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_modifierFlags = e.modifiers; m_timestamp = e.timestamp_sec; static IntPoint last_click_position; static MouseButton last_click_button = LeftButton; const uint32 current_time = static_cast<uint32>(m_timestamp * 1000); #if defined(OS_WIN) const bool cancel_previous_click = (abs(last_click_position.x() - m_position.x()) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2)) || (abs(last_click_position.y() - m_position.y()) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2)) || ((current_time - last_click_time_) > GetDoubleClickTime()); #elif defined(OS_MACOSX) || defined(OS_LINUX) const bool cancel_previous_click = false; #endif switch (e.type) { case WebInputEvent::MOUSE_MOVE: case WebInputEvent::MOUSE_LEAVE: if (cancel_previous_click) { last_click_count_ = 0; last_click_position = IntPoint(); last_click_time_ = 0; } m_clickCount = last_click_count_; m_eventType = MouseEventMoved; break; case WebInputEvent::MOUSE_DOWN: case WebInputEvent::MOUSE_DOUBLE_CLICK: if (!cancel_previous_click && (m_button == last_click_button)) { ++last_click_count_; } else { last_click_count_ = 1; last_click_position = m_position; } last_click_time_ = current_time; last_click_button = m_button; m_clickCount = last_click_count_; m_eventType = MouseEventPressed; break; case WebInputEvent::MOUSE_UP: m_clickCount = last_click_count_; m_eventType = MouseEventReleased; break; default: NOTREACHED() << "unexpected mouse event type"; } if (webkit_glue::IsLayoutTestMode()) { m_clickCount = e.layout_test_click_count; } } MakePlatformWheelEvent::MakePlatformWheelEvent(Widget* widget, const WebMouseWheelEvent& e) { m_position = widget->convertFromContainingWindow(IntPoint(e.x, e.y)); m_globalPosition = IntPoint(e.global_x, e.global_y); m_deltaX = static_cast<float>(e.delta_x); m_deltaY = static_cast<float>(e.delta_y); m_charsToScrollPerDelta = 1; m_linesToScrollPerDelta = 1; m_pageXScrollMode = false; m_pageYScrollMode = false; m_isAccepted = false; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; m_isContinuous = false; m_continuousDeltaX = 0; m_continuousDeltaY = 0; } static inline const PlatformKeyboardEvent::Type ToPlatformKeyboardEventType( WebInputEvent::Type type) { switch (type) { case WebInputEvent::KEY_UP: return PlatformKeyboardEvent::KeyUp; case WebInputEvent::KEY_DOWN:
static inline String ToSingleCharacterString(UChar c) { return String(&c, 1); } static String GetKeyIdentifierForWindowsKeyCode(unsigned short keyCode) { switch (keyCode) { case VK_MENU: return "Alt"; case VK_CONTROL: return "Control"; case VK_SHIFT: return "Shift"; case VK_CAPITAL: return "CapsLock"; case VK_LWIN: case VK_RWIN: return "Win"; case VK_CLEAR: return "Clear"; case VK_DOWN: return "Down"; case VK_END: return "End"; case VK_RETURN: return "Enter"; case VK_EXECUTE: return "Execute"; case VK_F1: return "F1"; case VK_F2: return "F2"; case VK_F3: return "F3"; case VK_F4: return "F4"; case VK_F5: return "F5"; case VK_F6: return "F6"; case VK_F7: return "F7"; case VK_F8: return "F8"; case VK_F9: return "F9"; case VK_F10: return "F11"; case VK_F12: return "F12"; case VK_F13: return "F13"; case VK_F14: return "F14"; case VK_F15: return "F15"; case VK_F16: return "F16"; case VK_F17: return "F17"; case VK_F18: return "F18"; case VK_F19: return "F19"; case VK_F20: return "F20"; case VK_F21: return "F21"; case VK_F22: return "F22"; case VK_F23: return "F23"; case VK_F24: return "F24"; case VK_HELP: return "Help"; case VK_HOME: return "Home"; case VK_INSERT: return "Insert"; case VK_LEFT: return "Left"; case VK_NEXT: return "PageDown"; case VK_PRIOR: return "PageUp"; case VK_PAUSE: return "Pause"; case VK_SNAPSHOT: return "PrintScreen"; case VK_RIGHT: return "Right"; case VK_SCROLL: return "Scroll"; case VK_SELECT: return "Select"; case VK_UP: return "Up"; case VK_DELETE: return "U+007F"; default: return String::format("U+%04X", toupper(keyCode)); } } MakePlatformKeyboardEvent::MakePlatformKeyboardEvent(const WebKeyboardEvent& e) { #if defined(OS_WIN) || defined(OS_LINUX) m_type = ToPlatformKeyboardEventType(e.type); if (m_type == Char || m_type == KeyDown) m_text = m_unmodifiedText = ToSingleCharacterString(e.key_code); if (m_type != Char) m_keyIdentifier = GetKeyIdentifierForWindowsKeyCode(e.key_code); if (m_type == Char || m_type == KeyDown || m_type == KeyUp || m_type == RawKeyDown) { m_windowsVirtualKeyCode = e.key_code; } else { m_windowsVirtualKeyCode = 0; } #endif m_autoRepeat = (e.modifiers & WebInputEvent::IS_AUTO_REPEAT) != 0; m_isKeypad = (e.modifiers & WebInputEvent::IS_KEYPAD) != 0; m_shiftKey = (e.modifiers & WebInputEvent::SHIFT_KEY) != 0; m_ctrlKey = (e.modifiers & WebInputEvent::CTRL_KEY) != 0; m_altKey = (e.modifiers & WebInputEvent::ALT_KEY) != 0; m_metaKey = (e.modifiers & WebInputEvent::META_KEY) != 0; #if defined(OS_WIN) m_isSystemKey = e.system_key; #endif } void MakePlatformKeyboardEvent::SetKeyType(Type type) { ASSERT(m_type == KeyDown); ASSERT(type == RawKeyDown || type == Char); m_type = type; if (type == RawKeyDown) { m_text = String(); m_unmodifiedText = String(); } else { m_keyIdentifier = String(); m_windowsVirtualKeyCode = 0; } } bool MakePlatformKeyboardEvent::IsCharacterKey() const { switch (windowsVirtualKeyCode()) { #if defined(OS_WIN) case VK_BACK: case VK_ESCAPE: #endif return false; default: break; } return true; }
return PlatformKeyboardEvent::KeyDown; case WebInputEvent::CHAR: return PlatformKeyboardEvent::Char; default: ASSERT_NOT_REACHED(); } return PlatformKeyboardEvent::KeyDown; }
function_block-function_prefix_line
[ { "content": "class SkEvent;\n\n\n", "file_path": "skia/include/SkWidget.h", "rank": 0, "score": 202538.54512832483 }, { "content": "class WebMouseEvent;\n", "file_path": "chrome/browser/render_widget_host.h", "rank": 1, "score": 191707.1018699238 }, { "content": "class W...
C++
sync/internal_api/public/base/unique_position.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
#include "sync/internal_api/public/base/unique_position.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "sync/protocol/unique_position.pb.h" #include "third_party/zlib/zlib.h" namespace syncer { const size_t UniquePosition::kSuffixLength = 28; const size_t UniquePosition::kCompressBytesThreshold = 128; bool UniquePosition::IsValidSuffix(const std::string& suffix) { return suffix.length() == kSuffixLength; } bool UniquePosition::IsValidBytes(const std::string& bytes) { return bytes.length() >= kSuffixLength && bytes[bytes.length()-1] != 0; } UniquePosition UniquePosition::CreateInvalid() { UniquePosition pos; DCHECK(!pos.IsValid()); return pos; } UniquePosition UniquePosition::FromProto(const sync_pb::UniquePosition& proto) { if (proto.has_value()) { return UniquePosition(proto.value()); } else if (proto.has_compressed_value() && proto.has_uncompressed_length()) { uLongf uncompressed_len = proto.uncompressed_length(); std::string uncompressed; uncompressed.resize(uncompressed_len); int result = uncompress( reinterpret_cast<Bytef*>(string_as_array(&uncompressed)), &uncompressed_len, reinterpret_cast<const Bytef*>(proto.compressed_value().data()), proto.compressed_value().size()); if (result != Z_OK) { DLOG(ERROR) << "Unzip failed " << result; return UniquePosition::CreateInvalid(); } if (uncompressed_len != proto.uncompressed_length()) { DLOG(ERROR) << "Uncompressed length " << uncompressed_len << " did not match specified length " << proto.uncompressed_length(); return UniquePosition::CreateInvalid(); } return UniquePosition(uncompressed); } else { return UniquePosition::CreateInvalid(); } } UniquePosition UniquePosition::FromInt64( int64 x, const std::string& suffix) { uint64 y = static_cast<uint64>(x); y ^= 0x8000000000000000ULL; std::string bytes(8, 0); for (int i = 7; i >= 0; --i) { bytes[i] = static_cast<uint8>(y); y >>= 8; } return UniquePosition(bytes, suffix); } UniquePosition UniquePosition::InitialPosition( const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); return UniquePosition(std::string(), suffix); } UniquePosition UniquePosition::Before( const UniquePosition& x, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK(x.IsValid()); const std::string& before = FindSmallerWithSuffix(x.bytes_, suffix); return UniquePosition(before, suffix); } UniquePosition UniquePosition::After( const UniquePosition& x, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK(x.IsValid()); const std::string& after = FindGreaterWithSuffix(x.bytes_, suffix); return UniquePosition(after, suffix); } UniquePosition UniquePosition::Between( const UniquePosition& before, const UniquePosition& after, const std::string& suffix) { DCHECK(before.IsValid()); DCHECK(after.IsValid()); DCHECK(before.LessThan(after)); DCHECK(IsValidSuffix(suffix)); const std::string& mid = FindBetweenWithSuffix(before.bytes_, after.bytes_, suffix); return UniquePosition(mid, suffix); } UniquePosition::UniquePosition() : is_valid_(false) {} bool UniquePosition::LessThan(const UniquePosition& other) const { DCHECK(this->IsValid()); DCHECK(other.IsValid()); return bytes_ < other.bytes_; } bool UniquePosition::Equals(const UniquePosition& other) const { if (!this->IsValid() && !other.IsValid()) return true; return bytes_ == other.bytes_; } void UniquePosition::ToProto(sync_pb::UniquePosition* proto) const { proto->Clear(); if (bytes_.size() < kCompressBytesThreshold) { proto->set_value(bytes_); } else { proto->set_uncompressed_length(bytes_.size()); std::string* compressed = proto->mutable_compressed_value(); uLongf compressed_len = compressBound(bytes_.size()); compressed->resize(compressed_len); int result = compress(reinterpret_cast<Bytef*>(string_as_array(compressed)), &compressed_len, reinterpret_cast<const Bytef*>(bytes_.data()), bytes_.size()); if (result != Z_OK) { NOTREACHED() << "Failed to compress position: " << result; proto->Clear(); proto->set_value(bytes_); } else if (compressed_len >= bytes_.size()) { proto->Clear(); proto->set_value(bytes_); } else { compressed->resize(compressed_len); } } } void UniquePosition::SerializeToString(std::string* blob) const { DCHECK(blob); sync_pb::UniquePosition proto; ToProto(&proto); proto.SerializeToString(blob); } int64 UniquePosition::ToInt64() const { uint64 y = 0; const std::string& s = bytes_; size_t l = sizeof(int64); if (s.length() < l) { NOTREACHED(); l = s.length(); } for (size_t i = 0; i < l; ++i) { const uint8 byte = s[l - i - 1]; y |= static_cast<uint64>(byte) << (i * 8); } y ^= 0x8000000000000000ULL; return static_cast<int64>(y); } bool UniquePosition::IsValid() const { return is_valid_; } std::string UniquePosition::ToDebugString() const { if (bytes_.empty()) return std::string("INVALID[]"); std::string debug_string = base::HexEncode(bytes_.data(), bytes_.length()); if (!IsValid()) { debug_string = "INVALID[" + debug_string + "]"; } return debug_string;; } std::string UniquePosition::GetSuffixForTest() const { const size_t prefix_len = bytes_.length() - kSuffixLength; return bytes_.substr(prefix_len, std::string::npos); } std::string UniquePosition::FindSmallerWithSuffix( const std::string& reference, const std::string& suffix) { size_t ref_zeroes = reference.find_first_not_of('\0'); size_t suffix_zeroes = suffix.find_first_not_of('\0'); DCHECK_NE(ref_zeroes, std::string::npos); DCHECK_NE(suffix_zeroes, std::string::npos); if (suffix_zeroes > ref_zeroes) { return std::string(); } if (suffix.substr(suffix_zeroes) < reference.substr(ref_zeroes)) { return std::string(ref_zeroes - suffix_zeroes, '\0'); } else if (suffix_zeroes > 1) { return std::string(ref_zeroes - suffix_zeroes + 1, '\0'); } else { char lt_digit = static_cast<uint8>(reference[ref_zeroes])/2; return std::string(ref_zeroes, '\0') + lt_digit; } } std::string UniquePosition::FindGreaterWithSuffix( const std::string& reference, const std::string& suffix) { size_t ref_FFs = reference.find_first_not_of(kuint8max); size_t suffix_FFs = suffix.find_first_not_of(kuint8max); if (ref_FFs == std::string::npos) { ref_FFs = reference.length(); } if (suffix_FFs == std::string::npos) { suffix_FFs = suffix.length(); } if (suffix_FFs > ref_FFs) { return std::string(); } if (suffix.substr(suffix_FFs) > reference.substr(ref_FFs)) { return std::string(ref_FFs - suffix_FFs, kuint8max); } else if (suffix_FFs > 1) { return std::string(ref_FFs - suffix_FFs + 1, kuint8max); } else { char gt_digit = static_cast<uint8>(reference[ref_FFs]) + (kuint8max - static_cast<uint8>(reference[ref_FFs]) + 1) / 2; return std::string(ref_FFs, kuint8max) + gt_digit; } } std::string UniquePosition::FindBetweenWithSuffix( const std::string& before, const std::string& after, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK_NE(before, after); DCHECK_LT(before, after); std::string mid; if (before < suffix && suffix < after) { return std::string(); } size_t i = 0; for ( ; i < std::min(before.length(), after.length()); ++i) { uint8 a_digit = before[i]; uint8 b_digit = after[i]; if (b_digit - a_digit >= 2) { mid.push_back(a_digit + (b_digit - a_digit)/2); return mid; } else if (a_digit == b_digit) { mid.push_back(a_digit); if (before.substr(i+1) < suffix && suffix < after.substr(i+1)) { return mid; } } else { DCHECK_EQ(b_digit - a_digit, 1); std::string mid_a = mid; mid_a.push_back(a_digit); mid_a.append(FindGreaterWithSuffix(before.substr(i+1), suffix)); if (after.length() > i+1) { std::string mid_b = mid; mid_b.push_back(b_digit); mid_b.append(FindSmallerWithSuffix(after.substr(i+1), suffix)); if (mid_b.length() < mid_a.length()) { return mid_b; } } return mid_a; } } DCHECK_EQ(before.substr(0, i), after.substr(0, i)); DCHECK_EQ(before, mid); DCHECK_LT(before.length(), after.length()); mid.append(FindSmallerWithSuffix(after.substr(i), suffix)); return mid; } UniquePosition::UniquePosition(const std::string& internal_rep) : bytes_(internal_rep), is_valid_(IsValidBytes(bytes_)) { } UniquePosition::UniquePosition( const std::string& prefix, const std::string& suffix) : bytes_(prefix + suffix), is_valid_(IsValidBytes(bytes_)) { DCHECK(IsValidSuffix(suffix)); DCHECK(IsValid()); } }
#include "sync/internal_api/public/base/unique_position.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "sync/protocol/unique_position.pb.h" #include "third_party/zlib/zlib.h" namespace syncer { const size_t UniquePosition::kSuffixLength = 28; const size_t UniquePosition::kCompressBytesThreshold = 128; bool UniquePosition::IsValidSuffix(const std::string& suffix) { return suffix.length() == kSuffixLength; } bool UniquePosition::IsValidBytes(const std::string& bytes) { return bytes.length() >= kSuffixLength && bytes[bytes.length()-1] != 0; } UniquePosition UniquePosition::CreateInvalid() { UniquePosition pos; DCHECK(!pos.IsValid()); return pos; } UniquePosition UniquePosition::FromProto(const sync_pb::UniquePosition& proto) { if (proto.has_value()) { return UniquePosition(proto.value()); } else if (proto.has_compressed_value() && proto.has_uncompressed_length()) { uLongf uncompressed_len = proto.uncompressed_length(); std::string uncompressed; uncompressed.resize(uncompressed_len); int result = uncompress( reinterpret_cast<Bytef*>(string_as_array(&uncompressed)), &uncompressed_len, reinterpret_cast<const Bytef*>(proto.compressed_value().data()), proto.compressed_value().size()); if (result != Z_OK) { DLOG(ERROR) << "Unzip failed " << result; return UniquePosition::CreateInvalid(); } if (uncompressed_len != proto.uncompressed_length()) { DLOG(ERROR) << "Uncompressed length " << uncompressed_len << " did not match specified length " << proto.uncompressed_length(); return UniquePosition::CreateInvalid(); } return UniquePosition(uncompressed); } else { return UniquePosition::CreateInvalid(); } } UniquePosition UniquePosition::FromInt64( int64 x, const std::string& suffix) { uint64 y = static_cast<uint64>(x); y ^= 0x8000000000000000ULL; std::string bytes(8, 0); for (int i = 7; i >= 0; --i) { bytes[i] = static_cast<uint8>(y); y >>= 8; } return UniquePosition(bytes, suffix); } UniquePosition UniquePosition::InitialPosition( const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); return UniquePosition(std::string(), suffix); } UniquePosition UniquePosition::Before( const UniquePosition& x, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK(x.IsValid()); const std::string& before = FindSmallerWithSuffix(x.bytes_, suffix); return UniquePosition(before, suffix); }
UniquePosition UniquePosition::Between( const UniquePosition& before, const UniquePosition& after, const std::string& suffix) { DCHECK(before.IsValid()); DCHECK(after.IsValid()); DCHECK(before.LessThan(after)); DCHECK(IsValidSuffix(suffix)); const std::string& mid = FindBetweenWithSuffix(before.bytes_, after.bytes_, suffix); return UniquePosition(mid, suffix); } UniquePosition::UniquePosition() : is_valid_(false) {} bool UniquePosition::LessThan(const UniquePosition& other) const { DCHECK(this->IsValid()); DCHECK(other.IsValid()); return bytes_ < other.bytes_; } bool UniquePosition::Equals(const UniquePosition& other) const { if (!this->IsValid() && !other.IsValid()) return true; return bytes_ == other.bytes_; } void UniquePosition::ToProto(sync_pb::UniquePosition* proto) const { proto->Clear(); if (bytes_.size() < kCompressBytesThreshold) { proto->set_value(bytes_); } else { proto->set_uncompressed_length(bytes_.size()); std::string* compressed = proto->mutable_compressed_value(); uLongf compressed_len = compressBound(bytes_.size()); compressed->resize(compressed_len); int result = compress(reinterpret_cast<Bytef*>(string_as_array(compressed)), &compressed_len, reinterpret_cast<const Bytef*>(bytes_.data()), bytes_.size()); if (result != Z_OK) { NOTREACHED() << "Failed to compress position: " << result; proto->Clear(); proto->set_value(bytes_); } else if (compressed_len >= bytes_.size()) { proto->Clear(); proto->set_value(bytes_); } else { compressed->resize(compressed_len); } } } void UniquePosition::SerializeToString(std::string* blob) const { DCHECK(blob); sync_pb::UniquePosition proto; ToProto(&proto); proto.SerializeToString(blob); } int64 UniquePosition::ToInt64() const { uint64 y = 0; const std::string& s = bytes_; size_t l = sizeof(int64); if (s.length() < l) { NOTREACHED(); l = s.length(); } for (size_t i = 0; i < l; ++i) { const uint8 byte = s[l - i - 1]; y |= static_cast<uint64>(byte) << (i * 8); } y ^= 0x8000000000000000ULL; return static_cast<int64>(y); } bool UniquePosition::IsValid() const { return is_valid_; } std::string UniquePosition::ToDebugString() const { if (bytes_.empty()) return std::string("INVALID[]"); std::string debug_string = base::HexEncode(bytes_.data(), bytes_.length()); if (!IsValid()) { debug_string = "INVALID[" + debug_string + "]"; } return debug_string;; } std::string UniquePosition::GetSuffixForTest() const { const size_t prefix_len = bytes_.length() - kSuffixLength; return bytes_.substr(prefix_len, std::string::npos); } std::string UniquePosition::FindSmallerWithSuffix( const std::string& reference, const std::string& suffix) { size_t ref_zeroes = reference.find_first_not_of('\0'); size_t suffix_zeroes = suffix.find_first_not_of('\0'); DCHECK_NE(ref_zeroes, std::string::npos); DCHECK_NE(suffix_zeroes, std::string::npos); if (suffix_zeroes > ref_zeroes) { return std::string(); } if (suffix.substr(suffix_zeroes) < reference.substr(ref_zeroes)) { return std::string(ref_zeroes - suffix_zeroes, '\0'); } else if (suffix_zeroes > 1) { return std::string(ref_zeroes - suffix_zeroes + 1, '\0'); } else { char lt_digit = static_cast<uint8>(reference[ref_zeroes])/2; return std::string(ref_zeroes, '\0') + lt_digit; } } std::string UniquePosition::FindGreaterWithSuffix( const std::string& reference, const std::string& suffix) { size_t ref_FFs = reference.find_first_not_of(kuint8max); size_t suffix_FFs = suffix.find_first_not_of(kuint8max); if (ref_FFs == std::string::npos) { ref_FFs = reference.length(); } if (suffix_FFs == std::string::npos) { suffix_FFs = suffix.length(); } if (suffix_FFs > ref_FFs) { return std::string(); } if (suffix.substr(suffix_FFs) > reference.substr(ref_FFs)) { return std::string(ref_FFs - suffix_FFs, kuint8max); } else if (suffix_FFs > 1) { return std::string(ref_FFs - suffix_FFs + 1, kuint8max); } else { char gt_digit = static_cast<uint8>(reference[ref_FFs]) + (kuint8max - static_cast<uint8>(reference[ref_FFs]) + 1) / 2; return std::string(ref_FFs, kuint8max) + gt_digit; } } std::string UniquePosition::FindBetweenWithSuffix( const std::string& before, const std::string& after, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK_NE(before, after); DCHECK_LT(before, after); std::string mid; if (before < suffix && suffix < after) { return std::string(); } size_t i = 0; for ( ; i < std::min(before.length(), after.length()); ++i) { uint8 a_digit = before[i]; uint8 b_digit = after[i]; if (b_digit - a_digit >= 2) { mid.push_back(a_digit + (b_digit - a_digit)/2); return mid; } else if (a_digit == b_digit) { mid.push_back(a_digit); if (before.substr(i+1) < suffix && suffix < after.substr(i+1)) { return mid; } } else { DCHECK_EQ(b_digit - a_digit, 1); std::string mid_a = mid; mid_a.push_back(a_digit); mid_a.append(FindGreaterWithSuffix(before.substr(i+1), suffix)); if (after.length() > i+1) { std::string mid_b = mid; mid_b.push_back(b_digit); mid_b.append(FindSmallerWithSuffix(after.substr(i+1), suffix)); if (mid_b.length() < mid_a.length()) { return mid_b; } } return mid_a; } } DCHECK_EQ(before.substr(0, i), after.substr(0, i)); DCHECK_EQ(before, mid); DCHECK_LT(before.length(), after.length()); mid.append(FindSmallerWithSuffix(after.substr(i), suffix)); return mid; } UniquePosition::UniquePosition(const std::string& internal_rep) : bytes_(internal_rep), is_valid_(IsValidBytes(bytes_)) { } UniquePosition::UniquePosition( const std::string& prefix, const std::string& suffix) : bytes_(prefix + suffix), is_valid_(IsValidBytes(bytes_)) { DCHECK(IsValidSuffix(suffix)); DCHECK(IsValid()); } }
UniquePosition UniquePosition::After( const UniquePosition& x, const std::string& suffix) { DCHECK(IsValidSuffix(suffix)); DCHECK(x.IsValid()); const std::string& after = FindGreaterWithSuffix(x.bytes_, suffix); return UniquePosition(after, suffix); }
function_block-full_function
[]
C++
src/main.cpp
chhsgithub/PolygonExpand
36e42bcd9a5dee09e028cf7024e49dd7f67517b4
#include <iostream> #include <Windows.h> #include <vector> #include <opencv2/opencv.hpp> #define CVUI_IMPLEMENTATION #include "cvui.h" using namespace std; using namespace cv; #define WINDOW_NAME "Show" bool clockwise(vector<Point> contour); void expand_polygon(vector<Point> &contour, vector<Point> &contour_exp, float range); void on_Trackbar(int, void*) { } int main() { Mat show(800, 800, CV_8UC3, Scalar(255,255,255)); namedWindow(WINDOW_NAME); cvui::init(WINDOW_NAME); int range=0; vector<Point> contours; contours.push_back(Point(400, 650)); contours.push_back(Point(450, 600)); contours.push_back(Point(450, 450)); contours.push_back(Point(500, 450)); contours.push_back(Point(500, 400)); contours.push_back(Point(400, 400)); while (true) { show= Mat(800, 800, CV_8UC3, Scalar(255, 255, 255)); cvui::window(show, 200, 20, 400, 70, "Setting"); cvui::trackbar(show, 250, 40, 300, &range, -100, 100); cvui::update(); vector<Point> points_expand; expand_polygon(contours, points_expand, range); Point vertex; for (int i = 0; i < contours.size(); i++) { vertex.x = contours[i].x; vertex.y = contours[i].y; circle(show, vertex, 2, Scalar(0, 255, 0), 1); ostringstream indexText; indexText << i; putText(show, indexText.str(), vertex, cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(0, 0, 255), 1); int next = (i == (contours.size() - 1) ? 0 : (i + 1)); line(show, contours[i], contours[next], Scalar(0, 0, 255), 1); } for (int i = 0; i < points_expand.size(); i++) { vertex.x = points_expand[i].x; vertex.y = points_expand[i].y; circle(show, vertex, 2, Scalar(0, 255, 0), 1); ostringstream indexText; indexText << i; putText(show, indexText.str(), vertex, cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(0, 0, 255), 1); int next = (i == (points_expand.size() - 1) ? 0 : (i + 1)); line(show, points_expand[i], points_expand[next], Scalar(0, 255, 0), 1); } imshow(WINDOW_NAME, show); waitKey(1); } return 0; } bool clockwise(vector<Point> contour) { int x_max = contour[0].x; int index = 0; for (int i = 1; i < contour.size(); i++) { if (contour[i].x > x_max) { x_max = contour[i].x; index = i; } } Point a, b, c; if (index == 0) { a = contour.back(); b = contour[0]; c = contour[1]; } else if (index == contour.size() - 1) { a = contour[contour.size() - 2]; b = contour.back(); c = contour[0]; } else { a = contour[index - 1]; b = contour[index]; c = contour[index + 1]; } return ((b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)) > 0 ? TRUE : FALSE; } void expand_polygon(vector<Point> &contour, vector<Point> &contour_exp, float range) { if (clockwise(contour)) { range = -range; } vector<Point2f> dpList, ndpList; int count = contour.size(); for (int i = 0; i < count; i++) { int next = (i == (count - 1) ? 0 : (i + 1)); dpList.push_back(contour.at(next) - contour.at(i)); float unitLen = 1.0f / sqrt(dpList.at(i).dot(dpList.at(i))); ndpList.push_back(dpList.at(i) * unitLen); cout << "i=" << i << ",pList:" << contour.at(next) << "," << contour.at(i) << ",dpList:" << dpList.at(i) << ",ndpList:" << ndpList.at(i) << endl; } for (int i = 0; i < count; i++) { int startIndex = (i == 0 ? (count - 1) : (i - 1)); int endIndex = i; float sinTheta = ndpList.at(startIndex).cross(ndpList.at(endIndex)); Point2f orientVector = ndpList.at(endIndex) - ndpList.at(startIndex); Point2f temp_out; temp_out.x = contour.at(i).x + range / sinTheta * orientVector.x; temp_out.y = contour.at(i).y + range / sinTheta * orientVector.y; contour_exp.push_back(temp_out); } }
#include <iostream> #include <Windows.h> #include <vector> #include <opencv2/opencv.hpp> #define CVUI_IMPLEMENTATION #include "cvui.h" using namespace std; using namespace cv; #define WINDOW_NAME "Show" bool clockwise(vector<Point> contour); void expand_polygon(vector<Point> &contour, vector<Point> &contour_exp, float range); void on_Trackbar(int, void*) { } int main() { Mat show(800, 800, CV_8UC3, Scalar(255,255,255)); namedWindow(WINDOW_NAME); cvui::init(WINDOW_NAME); int range=0; vector<Point> contours; contours.push_back(Point(400, 650)); contours.push_back(Point(450, 600)); contours.push_back(Point(450, 450)); contours.push_back(Point(500, 450)); contours.push_back(Point(500, 400)); contours.push_back(Point(400, 400)); while (true) { show= Mat(800, 800, CV_8UC3, Scalar(255, 255, 255)); cvui::window(show, 200, 20, 400, 70, "Setting"); cvui::trackbar(show, 250, 40, 300, &range, -100, 100); cvui::update(); vector<Point> points_expand; expand_polygon(contours, points_expand, range); Point vertex; for (int i = 0; i < contours.size(); i++) { vertex.x = contours[i].x; vertex.y = contours[i].y; circle(show, vertex, 2, Scalar(0, 255, 0), 1); ostringstream indexText; indexText << i; putText(show, indexText.str(), vertex, cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(0, 0, 255), 1); int next = (i == (contours.size() - 1) ? 0 : (i + 1)); line(show, contours[i], contours[next], Scalar(0, 0, 255), 1); } for (int i = 0; i < points_expand.size(); i++) { vertex.x = points_expand[i].x; vertex.y = points_expand[i].y; circle(show, vertex, 2, Scalar(0, 255, 0), 1); ostringstream indexText; indexText << i; putText(show, indexText.str(), vertex, cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(0, 0, 255), 1); int next = (i == (points_expand.size() - 1) ? 0 : (i + 1)); line(show, points_expand[i], points_expand[next], Scalar(0, 255, 0), 1); } imshow(WINDOW_NAME, show); waitKey(1); } return 0; }
void expand_polygon(vector<Point> &contour, vector<Point> &contour_exp, float range) { if (clockwise(contour)) { range = -range; } vector<Point2f> dpList, ndpList; int count = contour.size(); for (int i = 0; i < count; i++) { int next = (i == (count - 1) ? 0 : (i + 1)); dpList.push_back(contour.at(next) - contour.at(i)); float unitLen = 1.0f / sqrt(dpList.at(i).dot(dpList.at(i))); ndpList.push_back(dpList.at(i) * unitLen); cout << "i=" << i << ",pList:" << contour.at(next) << "," << contour.at(i) << ",dpList:" << dpList.at(i) << ",ndpList:" << ndpList.at(i) << endl; } for (int i = 0; i < count; i++) { int startIndex = (i == 0 ? (count - 1) : (i - 1)); int endIndex = i; float sinTheta = ndpList.at(startIndex).cross(ndpList.at(endIndex)); Point2f orientVector = ndpList.at(endIndex) - ndpList.at(startIndex); Point2f temp_out; temp_out.x = contour.at(i).x + range / sinTheta * orientVector.x; temp_out.y = contour.at(i).y + range / sinTheta * orientVector.y; contour_exp.push_back(temp_out); } }
bool clockwise(vector<Point> contour) { int x_max = contour[0].x; int index = 0; for (int i = 1; i < contour.size(); i++) { if (contour[i].x > x_max) { x_max = contour[i].x; index = i; } } Point a, b, c; if (index == 0) { a = contour.back(); b = contour[0]; c = contour[1]; } else if (index == contour.size() - 1) { a = contour[contour.size() - 2]; b = contour.back(); c = contour[0]; } else { a = contour[index - 1]; b = contour[index]; c = contour[index + 1]; } return ((b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)) > 0 ? TRUE : FALSE; }
function_block-full_function
[ { "content": "# PolygonExpand\n\nEnlarging or reducing the polygon with trackbar\n\n\n\n![show](https://github.com/chhsgithub/PolygonExpand/blob/master/GIF.gif)\n\n****\n\n\t\n\n|Author|chh|\n\n|---|---\n\n|E-mail|chhsemail@gmail.com\n\n\n\n\n\n****\n\n# Requirements\n\n- Cmake\n\n- OpenCV\n\n- CVUI\n", "fi...
C++
sources/cpp/ecs/src/game/main.cpp
xunilrj/sandbox
f92c12f83433cac01a885585e41c02bb5826a01f
#include <deltaTime/deltaTime.h> #include <TaskSystem/TaskSystem.h> #include "../ecs/ecs.h" struct PositionComponent { COMPONENTID(1, DenseStore<PositionComponent>); float x, y, z; }; struct RigidBodyComponent { COMPONENTID(2, DenseStore<RigidBodyComponent>); float vx, vy, vz; float ax, ay, az; }; struct EulerIntegratorSystem : System<DeltaTimeComponent, PositionComponent, RigidBodyComponent> { virtual void update() override { foreach([](DeltaTimeComponent& time, PositionComponent& pos, RigidBodyComponent& rb) { pos.x += rb.vx * time.dt; pos.y += rb.vy; pos.z += rb.vz; rb.vx += rb.ax; rb.vy += rb.ay; rb.vz += rb.az; }); } }; #include <iostream> #include <iomanip> bool input_enabled = true; void enable_input(Scene& s) { input_enabled = true; } void disable_input(Scene& s) { input_enabled = false; } void animA(Scene& scene, EntityRef ref) { scene.call(0); auto anim1 = scene.build_anim() .then(AnimManager::lerp(1, 0, 1)) .then(AnimManager::lerp(2, 1, 0.5)); auto anim2 = scene.build_anim() .then(AnimManager::lerp(1, 0, 1)); auto& anim_i1 = scene.start(anim1, ref, &PositionComponent::x); auto& anim_i2 = scene.start_after(anim2, ref, &PositionComponent::y, &anim_i1); scene.call(1, &anim_i2); } int main() { auto scene = Scene{}; scene.add(0, disable_input); scene.add(1, enable_input); scene .add<EulerIntegratorSystem>(); auto e1 = scene.build_entity() .set(PositionComponent{ 0, 0, 0 }) .set(RigidBodyComponent{ 1, 0, 0, 0, 0, 0}) .build(); auto e2 = scene.build_entity() .set(PositionComponent{ 0, 0, 0 }) .build(); auto hStdout = GetStdHandle(STD_OUTPUT_HANDLE); deltaTime<double> dt{ 16, true }; while (true) { auto elapsed = dt.step(); if (elapsed > 0) { auto& int2 = scene.get<PositionComponent>(e2); if (input_enabled && (GetKeyState('A') & 0x8000)) { animA(scene, e2); } scene.set<DeltaTimeComponent>({ (float)(elapsed / 1000.0) }); scene.update(); std::cout.precision(4); std::cout << std::setw(4) << int2.x << " " << std::setw(4) << int2.y << std::endl; } } return 0; }
#include <deltaTime/deltaTime.h> #include <TaskSystem/TaskSystem.h> #include "../ecs/ecs.h" struct PositionComponent { COMPONENTID(1, DenseStore<PositionComponent>); float x, y, z; }; struct RigidBodyComponent { COMPONENTID(2, DenseStore<RigidBodyComponent>); float vx, vy, vz; float ax, ay, az; }; struct EulerIntegratorSystem : System<DeltaTimeComponent, PositionComponent, RigidBodyComponent> { virtua
}; #include <iostream> #include <iomanip> bool input_enabled = true; void enable_input(Scene& s) { input_enabled = true; } void disable_input(Scene& s) { input_enabled = false; } void animA(Scene& scene, EntityRef ref) { scene.call(0); auto anim1 = scene.build_anim() .then(AnimManager::lerp(1, 0, 1)) .then(AnimManager::lerp(2, 1, 0.5)); auto anim2 = scene.build_anim() .then(AnimManager::lerp(1, 0, 1)); auto& anim_i1 = scene.start(anim1, ref, &PositionComponent::x); auto& anim_i2 = scene.start_after(anim2, ref, &PositionComponent::y, &anim_i1); scene.call(1, &anim_i2); } int main() { auto scene = Scene{}; scene.add(0, disable_input); scene.add(1, enable_input); scene .add<EulerIntegratorSystem>(); auto e1 = scene.build_entity() .set(PositionComponent{ 0, 0, 0 }) .set(RigidBodyComponent{ 1, 0, 0, 0, 0, 0}) .build(); auto e2 = scene.build_entity() .set(PositionComponent{ 0, 0, 0 }) .build(); auto hStdout = GetStdHandle(STD_OUTPUT_HANDLE); deltaTime<double> dt{ 16, true }; while (true) { auto elapsed = dt.step(); if (elapsed > 0) { auto& int2 = scene.get<PositionComponent>(e2); if (input_enabled && (GetKeyState('A') & 0x8000)) { animA(scene, e2); } scene.set<DeltaTimeComponent>({ (float)(elapsed / 1000.0) }); scene.update(); std::cout.precision(4); std::cout << std::setw(4) << int2.x << " " << std::setw(4) << int2.y << std::endl; } } return 0; }
l void update() override { foreach([](DeltaTimeComponent& time, PositionComponent& pos, RigidBodyComponent& rb) { pos.x += rb.vx * time.dt; pos.y += rb.vy; pos.z += rb.vz; rb.vx += rb.ax; rb.vy += rb.ay; rb.vz += rb.az; }); }
function_block-function_prefixed
[ { "content": "struct some_non_vectorizable_type { float x; };\n\n\n\nvoid test_first_aligned()\n\n{\n\n EIGEN_ALIGN16 float array_float[100];\n\n test_first_aligned_helper(array_float, 50);\n\n test_first_aligned_helper(array_float+1, 50);\n\n test_first_aligned_helper(array_float+2, 50);\n\n test_first_al...
C++
uarm/src/swiftpro_rviz_node2.cpp
iamrajee/ROS
c8b0f09db9624f4d06e86a0b0e12df4f0471ca86
#include <string> #include <ros/ros.h> #include <std_msgs/String.h> #include <swiftpro/SwiftproState.h> #include <sensor_msgs/JointState.h> #include <tf/transform_broadcaster.h> #define MATH_PI 3.141592653589793238463 #define MATH_TRANS 57.2958 #define MATH_L1 106.6 #define MATH_L2 13.2 #define MATH_LOWER_ARM 142.07 #define MATH_UPPER_ARM 158.81 #define MATH_UPPER_LOWER (MATH_UPPER_ARM / MATH_LOWER_ARM) #define LOWER_ARM_MAX_ANGLE 135.6 #define LOWER_ARM_MIN_ANGLE 0 #define UPPER_ARM_MAX_ANGLE 100.7 #define UPPER_ARM_MIN_ANGLE 0 #define LOWER_UPPER_MAX_ANGLE 151 #define LOWER_UPPER_MIN_ANGLE 10 float joint_angle[9] = {0.0}; void all_joints_state(float angle[3]) { double alpha2; double alpha3; alpha2 = angle[1]; alpha3 = angle[2] - 3.8; joint_angle[0] = angle[0] - 90; joint_angle[1] = 90 - alpha2; joint_angle[5] = alpha3; joint_angle[2] = (alpha2 + alpha3) - 176.11 + 90; joint_angle[3] = -90 + alpha2; joint_angle[4] = joint_angle[1]; joint_angle[6] = 90 - (alpha2 + alpha3); joint_angle[7] = 176.11 - 180 - alpha3; joint_angle[8] = 48.39 + alpha3 - 44.55; } bool swiftpro_ik(float position[3], float angle[3]) { float x = position[0]; float y = position[1]; float z = position[2]; float xIn, zIn, phi, rightAll, sqrtZX = 0.0; float angleRot, angleLeft, angleRight = 0.0; z += 74.55; zIn = (z - MATH_L1) / MATH_LOWER_ARM; if (x < 0.1) x = 0.1; if (y == 0) angleRot = 90; else if (y < 0) angleRot = -atan(x / y) * MATH_TRANS; else if (y > 0) angleRot = 180 - atan(x / y) * MATH_TRANS; xIn = (x / sin(angleRot / MATH_TRANS) - MATH_L2 - 56.55) / MATH_LOWER_ARM; phi = atan(zIn / xIn) * MATH_TRANS; sqrtZX = sqrt(zIn * zIn + xIn * xIn); rightAll = (sqrtZX * sqrtZX + MATH_UPPER_LOWER * MATH_UPPER_LOWER - 1) / (2 * MATH_UPPER_LOWER * sqrtZX); angleRight = acos(rightAll) * MATH_TRANS; rightAll = (sqrtZX * sqrtZX + 1 - MATH_UPPER_LOWER * MATH_UPPER_LOWER ) / (2 * sqrtZX); angleLeft = acos(rightAll) * MATH_TRANS; angleLeft = angleLeft + phi; angleRight = angleRight - phi; if (isnan(angleRot) || isnan(angleLeft) || isnan(angleRight)) return false; angle[0] = angleRot; angle[1] = angleLeft; angle[2] = angleRight; return true; } void SwiftproState_Callback(const swiftpro::SwiftproState& msg) { float position[3]; float angle[3]; position[0] = msg.x; position[1] = msg.y; position[2] = msg.z; if ( swiftpro_ik(position, angle) ) all_joints_state(angle); else ROS_ERROR("Inverse kinematic is wrong"); } int main(int argc, char **argv) { ros::init(argc, argv, "swiftpro_rviz_node"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("SwiftproState_topic", 1, SwiftproState_Callback); ros::Publisher pub = n.advertise<sensor_msgs::JointState>("joint_states", 1); ros::Rate loop_rate(20); tf::TransformBroadcaster broadcaster; sensor_msgs::JointState joint_state; geometry_msgs::TransformStamped odom_trans; odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "Base"; while (ros::ok()) { joint_state.header.stamp = ros::Time::now(); joint_state.name.resize(9); joint_state.position.resize(9); joint_state.name[0] = "Joint1"; joint_state.position[0] = joint_angle[0] / 57.2958; joint_state.name[1] = "Joint2"; joint_state.position[1] = joint_angle[1] / 57.2958; joint_state.name[2] = "Joint3"; joint_state.position[2] = joint_angle[2] / 57.2958; joint_state.name[3] = "Joint4"; joint_state.position[3] = joint_angle[3] / 57.2958; joint_state.name[4] = "Joint5"; joint_state.position[4] = joint_angle[4] / 57.2958; joint_state.name[5] = "Joint6"; joint_state.position[5] = joint_angle[5] / 57.2958; joint_state.name[6] = "Joint7"; joint_state.position[6] = joint_angle[6] / 57.2958; joint_state.name[7] = "Joint8"; joint_state.position[7] = joint_angle[7] / 57.2958; joint_state.name[8] = "Joint9"; joint_state.position[8] = joint_angle[8] / 57.2958; odom_trans.header.stamp = ros::Time::now(); odom_trans.transform.translation.x = 0; odom_trans.transform.translation.y = 0; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(10); pub.publish(joint_state); broadcaster.sendTransform(odom_trans); ros::spinOnce(); loop_rate.sleep(); } return 0; }
#include <string> #include <ros/ros.h> #include <std_msgs/String.h> #include <swiftpro/SwiftproState.h> #include <sensor_msgs/JointState.h> #include <tf/transform_broadcaster.h> #define MATH_PI 3.141592653589793238463 #define MATH_TRANS 57.2958 #define MATH_L1 106.6 #define MATH_L2 13.2 #define MATH_LOWER_ARM 142.07 #define MATH_UPPER_ARM 158.81 #define MATH_UPPER_LOWER (MATH_UPPER_ARM / MATH_LOWER_ARM) #define LOWER_ARM_MAX_ANGLE 135.6 #define LOWER_ARM_MIN_ANGLE 0 #define UPPER_ARM_MAX_ANGLE 100.7 #define UPPER_ARM_MIN_ANGLE 0 #define LOWER_UPPER_MAX_ANGLE 151 #define LOWER_UPPER_MIN_ANGLE 10 float joint_angle[9] = {0.0}; void all_joints_state(float angle[3]) { double alpha2; double alpha3; alpha2 = angle[1]; alpha3 = angle[2] - 3.8; joint_angle[0] = angle[0] - 90; joint_angle[1] = 90 - alpha2; joint_angle[5] = alpha3; joint_angle[2] = (alpha2 + alpha3) - 176.11 + 90; joint_angle[3] = -90 + alpha2; joint_angle[4] = joint_angle[1]; joint_angle[6] = 90 - (alpha2 + alpha3); joint_angle[7] = 176.11 - 180 - alpha3; joint_angle[8] = 48.39 + alpha3 - 44.55; } bool swiftpro_ik(float position[3], float angle[3]) { float x = position[0]; float y = position[1]; float z = position[2]; float xIn, zIn, phi, rightAll, sqrtZX = 0.0; float angleRot, angleLeft, angleRight = 0.0; z += 74.55; zIn = (z - MATH_L1) / MATH_LOWER_ARM; if (x < 0.1) x = 0.1; if (y == 0) angleRot = 90; else if (y < 0) angleRot = -atan(x / y) * MATH_TRANS; else if (y > 0) angleRot = 180 - atan(x / y) * MATH_TRANS; xIn = (x / sin(angleRot / MATH_TRANS) -
sqrtZX + 1 - MATH_UPPER_LOWER * MATH_UPPER_LOWER ) / (2 * sqrtZX); angleLeft = acos(rightAll) * MATH_TRANS; angleLeft = angleLeft + phi; angleRight = angleRight - phi; if (isnan(angleRot) || isnan(angleLeft) || isnan(angleRight)) return false; angle[0] = angleRot; angle[1] = angleLeft; angle[2] = angleRight; return true; } void SwiftproState_Callback(const swiftpro::SwiftproState& msg) { float position[3]; float angle[3]; position[0] = msg.x; position[1] = msg.y; position[2] = msg.z; if ( swiftpro_ik(position, angle) ) all_joints_state(angle); else ROS_ERROR("Inverse kinematic is wrong"); } int main(int argc, char **argv) { ros::init(argc, argv, "swiftpro_rviz_node"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("SwiftproState_topic", 1, SwiftproState_Callback); ros::Publisher pub = n.advertise<sensor_msgs::JointState>("joint_states", 1); ros::Rate loop_rate(20); tf::TransformBroadcaster broadcaster; sensor_msgs::JointState joint_state; geometry_msgs::TransformStamped odom_trans; odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "Base"; while (ros::ok()) { joint_state.header.stamp = ros::Time::now(); joint_state.name.resize(9); joint_state.position.resize(9); joint_state.name[0] = "Joint1"; joint_state.position[0] = joint_angle[0] / 57.2958; joint_state.name[1] = "Joint2"; joint_state.position[1] = joint_angle[1] / 57.2958; joint_state.name[2] = "Joint3"; joint_state.position[2] = joint_angle[2] / 57.2958; joint_state.name[3] = "Joint4"; joint_state.position[3] = joint_angle[3] / 57.2958; joint_state.name[4] = "Joint5"; joint_state.position[4] = joint_angle[4] / 57.2958; joint_state.name[5] = "Joint6"; joint_state.position[5] = joint_angle[5] / 57.2958; joint_state.name[6] = "Joint7"; joint_state.position[6] = joint_angle[6] / 57.2958; joint_state.name[7] = "Joint8"; joint_state.position[7] = joint_angle[7] / 57.2958; joint_state.name[8] = "Joint9"; joint_state.position[8] = joint_angle[8] / 57.2958; odom_trans.header.stamp = ros::Time::now(); odom_trans.transform.translation.x = 0; odom_trans.transform.translation.y = 0; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(10); pub.publish(joint_state); broadcaster.sendTransform(odom_trans); ros::spinOnce(); loop_rate.sleep(); } return 0; }
MATH_L2 - 56.55) / MATH_LOWER_ARM; phi = atan(zIn / xIn) * MATH_TRANS; sqrtZX = sqrt(zIn * zIn + xIn * xIn); rightAll = (sqrtZX * sqrtZX + MATH_UPPER_LOWER * MATH_UPPER_LOWER - 1) / (2 * MATH_UPPER_LOWER * sqrtZX); angleRight = acos(rightAll) * MATH_TRANS; rightAll = (sqrtZX *
function_block-random_span
[ { "content": " class DDDouble : virtual public DDParam {\n\n public:\n\n string getName() const;\n\n\n\n void prepGroup(Group &group);\n\n\n\n void prepConfig(Config &conf);\n\n\n\n void prepConfigDescription(ConfigDescription &conf_desc);\n\n\n\n int getLevel() const;\n...
C++
BZOJ/BZOJ1336.cpp
xehoth/OnlineJudgeCodes
013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7
#include <algorithm> #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <iostream> namespace IO { inline char read() { static const int IN_LEN = 1000000; static char buf[IN_LEN], *s, *t; s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0; return s == t ? -1 : *s++; } template <typename T> inline void read(T &x) { static char c; static bool iosig; for (c = read(), iosig = false; !isdigit(c); c = read()) { if (c == -1) return; iosig ? x = -x : 0; } for (x = 0; isdigit(c); c = read()) x = (x + (x << 2) << 1) + (c ^ '0'); iosig ? x = -x : 0; } inline int read(char *buf) { register int s = 0; register char c; while (c = read(), isspace(c) && c != -1) ; if (c == -1) { *buf = '\0'; return -1; } do buf[s++] = c; while (c = read(), !isspace(c) && c != -1); buf[s] = '\0'; return s; } inline void read(double &x) { static char buf[30]; read(buf), x = atof(buf); } const int OUT_LEN = 1000000; char obuf[OUT_LEN], *oh = obuf; inline void print(char c) { oh == obuf + OUT_LEN ? (fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf) : 0; *oh++ = c; } template <typename T> inline void print(T x) { static int buf[30], cnt; if (x == 0) { print('0'); } else { x < 0 ? (print('-'), x = -x) : 0; for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48; while (cnt) print((char)buf[cnt--]); } } inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); } } namespace Task { const int MAXN = 100005; const double EPS = 1e-8; template <typename T> inline T square(const T &x) { return x * x; } struct Point { double x, y; Point(double x = 0, double y = 0) : x(x), y(y) {} inline double dis(const Point &p) const { return sqrt(square(x - p.x) + square(y - p.y)); } inline Point operator+(const Point &p) const { return Point(x + p.x, y + p.y); } inline Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); } inline Point operator*(const double i) const { return Point(x * i, y * i); } inline double operator*(const Point &p) const { return x * p.y - y * p.x; } inline double operator^(const Point &p) const { return x * p.x + y * p.y; } inline Point operator/(const double i) const { return Point(x / i, y / i); } inline void read() { IO::read(x), IO::read(y); } } p[MAXN]; struct Circle { Point o; double r; Circle(const Point &o, const double r) : o(o), r(r) {} Circle() {} }; struct Line { Point s, t; Line(const Point &s, const Point &t) : s(s), t(t) {} inline Point intersect(const Line &l) const { return s + (t - s) * (((s - l.s) * (l.t - l.s)) / ((l.t - l.s) * (t - s))); } inline Line getPerpendicularBisector() { return Line( Point((s.x + t.x) / 2, (s.y + t.y) / 2), Point((s.x + t.x) / 2 + s.y - t.y, (s.y + t.y) / 2 + t.x - s.x)); } }; inline Point getCenter(const Point &a, const Point &b, const Point &c) { return Line(a, b).getPerpendicularBisector().intersect( Line(a, c).getPerpendicularBisector()); } inline void solve() { using namespace IO; srand(495); register int n; read(n); for (register int i = 1; i <= n; i++) p[i].read(); std::random_shuffle(p + 1, p + n + 1); Circle c(p[1], 0); for (register int i = 1; i <= n; i++) { if (c.o.dis(p[i]) - c.r < EPS) continue; c = Circle((p[1] + p[i]) / 2, p[1].dis(p[i]) / 2); for (register int j = 2; j < i; j++) { if (c.o.dis(p[j]) - c.r < EPS) continue; c = Circle((p[i] + p[j]) / 2, p[i].dis(p[j]) / 2); for (register int k = 1; k < j; k++) { if (c.o.dis(p[k]) - c.r < EPS) continue; c = Circle(getCenter(p[i], p[j], p[k]), c.r); c.r = c.o.dis(p[k]); } } } printf("%.5lf\n%.5lf %.5lf\n", c.r, c.o.x, c.o.y); } } int main() { #ifdef DBG freopen("in.in", "r", stdin); #endif Task::solve(); return 0; }
#include <algorithm> #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <iostream> namespace IO { inline char read() { static const int IN_LEN = 1000000; static char buf[IN_LEN], *s, *t; s == t ? t = (s = buf) + fread(buf, 1, IN_LEN, stdin) : 0; return s == t ? -1 : *s++; } template <typename T> inline void read(T &x) { static char c; static bool iosig; for (c = read(), iosig = false; !isdigit(c); c = read()) { if (c == -1) return; iosig ? x = -x : 0; } for (x = 0; isdigit(c); c = read()) x = (x + (x << 2) << 1) + (c ^ '0'); iosig ? x = -x : 0; } inline int read(char *buf) { register int s = 0; register char c; while (c = read(), isspace(c) && c != -1) ; if (c == -1) { *buf = '\0'; return -1; } do buf[s++] = c; while (c = read(), !isspace(c) && c != -1); buf[s] = '\0'; return s; } inline void read(double &x) { static char buf[30]; read(buf), x = atof(buf); } const int OUT_LEN = 1000000; char obuf[OUT_LEN], *oh = obuf; inline void print(char c) { oh == obuf + OUT_LEN ? (fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf) : 0; *oh++ = c; } template <typename T> inline void print(T x) { static int buf[30], cnt;
} inline void flush() { fwrite(obuf, 1, oh - obuf, stdout); } } namespace Task { const int MAXN = 100005; const double EPS = 1e-8; template <typename T> inline T square(const T &x) { return x * x; } struct Point { double x, y; Point(double x = 0, double y = 0) : x(x), y(y) {} inline double dis(const Point &p) const { return sqrt(square(x - p.x) + square(y - p.y)); } inline Point operator+(const Point &p) const { return Point(x + p.x, y + p.y); } inline Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); } inline Point operator*(const double i) const { return Point(x * i, y * i); } inline double operator*(const Point &p) const { return x * p.y - y * p.x; } inline double operator^(const Point &p) const { return x * p.x + y * p.y; } inline Point operator/(const double i) const { return Point(x / i, y / i); } inline void read() { IO::read(x), IO::read(y); } } p[MAXN]; struct Circle { Point o; double r; Circle(const Point &o, const double r) : o(o), r(r) {} Circle() {} }; struct Line { Point s, t; Line(const Point &s, const Point &t) : s(s), t(t) {} inline Point intersect(const Line &l) const { return s + (t - s) * (((s - l.s) * (l.t - l.s)) / ((l.t - l.s) * (t - s))); } inline Line getPerpendicularBisector() { return Line( Point((s.x + t.x) / 2, (s.y + t.y) / 2), Point((s.x + t.x) / 2 + s.y - t.y, (s.y + t.y) / 2 + t.x - s.x)); } }; inline Point getCenter(const Point &a, const Point &b, const Point &c) { return Line(a, b).getPerpendicularBisector().intersect( Line(a, c).getPerpendicularBisector()); } inline void solve() { using namespace IO; srand(495); register int n; read(n); for (register int i = 1; i <= n; i++) p[i].read(); std::random_shuffle(p + 1, p + n + 1); Circle c(p[1], 0); for (register int i = 1; i <= n; i++) { if (c.o.dis(p[i]) - c.r < EPS) continue; c = Circle((p[1] + p[i]) / 2, p[1].dis(p[i]) / 2); for (register int j = 2; j < i; j++) { if (c.o.dis(p[j]) - c.r < EPS) continue; c = Circle((p[i] + p[j]) / 2, p[i].dis(p[j]) / 2); for (register int k = 1; k < j; k++) { if (c.o.dis(p[k]) - c.r < EPS) continue; c = Circle(getCenter(p[i], p[j], p[k]), c.r); c.r = c.o.dis(p[k]); } } } printf("%.5lf\n%.5lf %.5lf\n", c.r, c.o.x, c.o.y); } } int main() { #ifdef DBG freopen("in.in", "r", stdin); #endif Task::solve(); return 0; }
if (x == 0) { print('0'); } else { x < 0 ? (print('-'), x = -x) : 0; for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 | 48; while (cnt) print((char)buf[cnt--]); }
if_condition
[ { "content": "struct PriorityQueue : public std::map<int, int, std::greater<int> > {\n\n typedef std::map<int, int, std::greater<int> > super;\n\n\n\n inline void push(int x) { super::operator[](x)++; }\n\n\n\n inline void erase(int x) {\n\n super::iterator it = super::find(x);\n\n if (it...
C++
src/termination_check_base.cpp
kuri-kustar/victim_localization
b5b0b8f2915d9805372a1d8c4809991b6d63c1b5
#include "victim_localization/termination_check_base.h" TerminationCheckBase::TerminationCheckBase() { ros::param::param<int>("~termination_repeat_window_size", repeat_window_size_, 8); ros::param::param<std::string>("~SaveDataFolder",saveFolder, std::string("Data")); result_status="Success"; } bool TerminationCheckBase::isTerminated() { std::cout << "[TerminationCheckBase]: " << cc.yellow << "update() not defined. Used derived class with proper implimentation.\n" << cc.reset; return false; } void TerminationCheckBase::setHistory(nbv_history* h) { nbv_history_ = h; } void TerminationCheckBase::setViewEvaluator(view_evaluator_base* v) { view_evaluator = v; } void TerminationCheckBase::setNBVTimeTaken(ros::Duration t) { NBVDurationTaken=t; } void TerminationCheckBase::SaveResults() { std::string path = ros::package::getPath("victim_localization"); std::cout << "path to package is" << path <<std::endl; std::string file_path; file_path=path + "/" + saveFolder+ "/"; view_evaluator->view_gen_->manager_-> octree_->writeBinary(file_path+"environment"); ofstream myfile (file_path+"POSES.txt"); if (myfile.is_open()) { for(int i =0; i< (nbv_history_->selected_poses.size()) ;i+=1) { myfile << nbv_history_->selected_poses[i].position.x << " " << nbv_history_->selected_poses[i].position.y<< " " << nbv_history_->selected_poses[i].position.z<< " " << nbv_history_->selected_poses[i].orientation.x<< " " << nbv_history_->selected_poses[i].orientation.y<< " " << nbv_history_->selected_poses[i].orientation.z<< " " << nbv_history_->selected_poses[i].orientation.w<< "\n"; } myfile.close(); } else cout << "Unable to open PATH.txt file"; ofstream myfile2 (file_path+"PATH.txt"); if (myfile2.is_open()) { for(int i =0; i< (nbv_history_->selected_poses_along_path.size()) ;i+=1) { myfile2 << nbv_history_->selected_poses_along_path[i].position.x << " " << nbv_history_->selected_poses_along_path[i].position.y<< " " << nbv_history_->selected_poses_along_path[i].position.z<< " " << nbv_history_->selected_poses_along_path[i].orientation.x<< " " << nbv_history_->selected_poses_along_path[i].orientation.y<< " " << nbv_history_->selected_poses_along_path[i].orientation.z<< " " << nbv_history_->selected_poses_along_path[i].orientation.w<< "\n"; } myfile2.close(); } else cout << "Unable to open PATH.txt file"; cv::Mat occupancyImage; grid_map::GridMap gridMap; Victim_Map_Base *Map_=view_evaluator->mapping_module_; double upscale_factor=32; double upscale_resolution= Map_->map_resol/upscale_factor; std::string mapName= "SaveOccupancy"; gridMap.setGeometry(Map_->map.getLength(),upscale_resolution); gridMap.add(mapName,0); occupancyImage= upscaleOccupancyImage(Map_->map,Map_->layer_name,gridMap,mapName); cv::imwrite(file_path+Map_->getlayer_name()+"Occupancy.jpeg",occupancyImage); if (Map_->Maptype==MAP::COMBINED) { gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::DL)->map, Map_->getMapLayer(MAP::DL)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::DL)->getlayer_name()+"Occupancy.jpeg",occupancyImage); gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::THERMAL)->map, Map_->getMapLayer(MAP::THERMAL)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::THERMAL)->getlayer_name()+"Occupancy.jpeg",occupancyImage); gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::WIRELESS)->map, Map_->getMapLayer(MAP::WIRELESS)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::WIRELESS)->getlayer_name()+"Occupancy.jpeg",occupancyImage); } ofstream Results (file_path+Map_->layer_name+"Result.txt"); if (Results.is_open()) { Results << "time taken: " << NBVDurationTaken.toSec() << "\n" << "Total entropy: " << view_evaluator->info_entropy_total_ << "\n" << "distance: " << view_evaluator->info_distance_total_ << "\n" << "iteration: " << nbv_history_->iteration << "\n" << "Result Status: " << result_status << std::endl << "\n"; Results.close(); } else cout << "Unable to find Results file"; } cv::Mat TerminationCheckBase::upscaleOccupancyImage(grid_map::GridMap inputMap , std::string Input, grid_map::GridMap upscaledMap, std::string Output) { cv::Mat image; const float minValue = 0.0; const float maxValue = 1.0; Index index; Position position; for (grid_map::GridMapIterator iterator(upscaledMap); !iterator.isPastEnd(); ++iterator) { index=*iterator; upscaledMap.getPosition(index,position); upscaledMap.atPosition(Output,position)=1-inputMap.atPosition(Input,position); } GridMapCvConverter::toImage<unsigned char, 4>(upscaledMap, Output, CV_8UC4, minValue, maxValue, image); return image; }
#include "victim_localization/termination_check_base.h" TerminationCheckBase::TerminationCheckBase() { ros::param::param<int>("~termination_repeat_window_size", repeat_window_size_, 8); ros::param::param<std::string>("~SaveDataFolder",saveFolder, std::string("Data")); result_status="Success"; } bool TerminationCheckBase::isTerminated() { std::cout << "[TerminationCheckBase]: " << cc.yellow << "update() not defined. Used derived class with proper implimentation.\n" << cc.reset; return false; } void TerminationCheckBase::setHistory(nbv_history* h) { nbv_history_ = h; } void TerminationCheckBase::setViewEvaluator(view_evaluator_base* v) { view_evaluator = v; } void TerminationCheckBase::setNBVTimeTaken(ros::Duration t) { NBVDurationTaken=t; } void TerminationCheckBase::SaveResults() { std::string path = ros::package::getPath("victim_localization"); std::cout << "path to package is" << path <<std::endl; std::string file_path; file_path=path + "/" + saveFolder+ "/"; view_evaluator->view_gen_->manager_-> octree_->writeBinary(file_path+"environment"); ofstream myfile (file_path+"POSES.txt"); if (myfile.is_open()) { for(int i =0; i< (nbv_history_->selected_poses.size()) ;i+=1) { myfile << nbv_history_->selected_poses[i].position.x << " " << nbv_history_->selected_poses[i].position.y<< " " << nbv_history_->selected_poses[i].position.z<< " " << nbv_history_->selected_poses[i].orientation.x<< " " << nbv_history_->selected_poses[i].orientation.y<< " " << nbv_history_->selected_poses[i].orientation.z<< " " << nbv_history_->selected_poses[i].orientation.w<< "\n"; } myfile.close(); } else cout << "Unable to open PATH.txt file"; ofstream myfile2 (file_path+"PATH.txt"); if (myfile2.is_open()) { for(int i =0; i< (nbv_history_->selected_poses_along_path.size()) ;i+=1) { myfile2 << nbv_history_->selected_poses_along_path[i].position.x << " " << nbv_history_->selected_poses_along_path[i].position.y<< " " << nbv_history_->selected_poses_along_path[i].position.z<< " " << nbv_history_->selected_poses_along_path[i].orientation.x<< " " << nbv_history_->selected_poses_along_path[i].orientation.y<< " " << nbv_history_->selected_poses_along_path[i].orientation.z<< " " << nbv_history_->selected_poses_along_path[i].orientation.w<< "\n"; } myfile2.close(); } else cout
tion)=1-inputMap.atPosition(Input,position); } GridMapCvConverter::toImage<unsigned char, 4>(upscaledMap, Output, CV_8UC4, minValue, maxValue, image); return image; }
<< "Unable to open PATH.txt file"; cv::Mat occupancyImage; grid_map::GridMap gridMap; Victim_Map_Base *Map_=view_evaluator->mapping_module_; double upscale_factor=32; double upscale_resolution= Map_->map_resol/upscale_factor; std::string mapName= "SaveOccupancy"; gridMap.setGeometry(Map_->map.getLength(),upscale_resolution); gridMap.add(mapName,0); occupancyImage= upscaleOccupancyImage(Map_->map,Map_->layer_name,gridMap,mapName); cv::imwrite(file_path+Map_->getlayer_name()+"Occupancy.jpeg",occupancyImage); if (Map_->Maptype==MAP::COMBINED) { gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::DL)->map, Map_->getMapLayer(MAP::DL)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::DL)->getlayer_name()+"Occupancy.jpeg",occupancyImage); gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::THERMAL)->map, Map_->getMapLayer(MAP::THERMAL)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::THERMAL)->getlayer_name()+"Occupancy.jpeg",occupancyImage); gridMap[mapName].setZero(); occupancyImage= upscaleOccupancyImage(Map_->getMapLayer(MAP::WIRELESS)->map, Map_->getMapLayer(MAP::WIRELESS)->getlayer_name(), gridMap,mapName); cv::imwrite(file_path+Map_->getMapLayer(MAP::WIRELESS)->getlayer_name()+"Occupancy.jpeg",occupancyImage); } ofstream Results (file_path+Map_->layer_name+"Result.txt"); if (Results.is_open()) { Results << "time taken: " << NBVDurationTaken.toSec() << "\n" << "Total entropy: " << view_evaluator->info_entropy_total_ << "\n" << "distance: " << view_evaluator->info_distance_total_ << "\n" << "iteration: " << nbv_history_->iteration << "\n" << "Result Status: " << result_status << std::endl << "\n"; Results.close(); } else cout << "Unable to find Results file"; } cv::Mat TerminationCheckBase::upscaleOccupancyImage(grid_map::GridMap inputMap , std::string Input, grid_map::GridMap upscaledMap, std::string Output) { cv::Mat image; const float minValue = 0.0; const float maxValue = 1.0; Index index; Position position; for (grid_map::GridMapIterator iterator(upscaledMap); !iterator.isPastEnd(); ++iterator) { index=*iterator; upscaledMap.getPosition(index,position); upscaledMap.atPosition(Output,posi
random
[ { "content": "class ReactivePathPlanner : public navigationBase\n\n{\n\npublic:\n\n ReactivePathPlanner(const ros::NodeHandle &nh, const ros::NodeHandle &nh_private, volumetric_mapping::OctomapManager *manager);\n\n\n\n sspp::sspp_srv planningService;\n\n ReactivePlannerServer *reactivePlannerServer;\n\n\n\n...
C++
fin_control/src/fin_control.cpp
ChrisScianna/ROS-Underwater-RnD
f928bcc6b19a830b98e2cc2aedd65ff35b887901
#include "fin_control/fin_control.h" #include <string> #include <diagnostic_tools/message_stagnation_check.h> #include <diagnostic_tools/periodic_message_status.h> namespace qna { namespace robot { FinControl::FinControl(ros::NodeHandle &nodeHandle) : nodeHandle(nodeHandle), diagnosticsUpdater(nodeHandle) { diagnosticsUpdater.setHardwareID("fin_control"); fincontrolEnabled = false; std::string serial_dev = "/dev/ttyUSB0"; int serial_baud = 57600; ctrlFinOffset = 0; ctrlFinScaleFactor = 1.0; servosON = false; const char *log; currentLoggingEnabled = false; reportAngleRate = 25.0; minReportAngleRate = reportAngleRate / 2.0; maxReportAngleRate = reportAngleRate * 2.0; ros::NodeHandle nh; ROS_INFO("Starting fin_control node Version: [%s]", NODE_VERSION); nh.setParam("/version_numbers/fin_control", NODE_VERSION); if (nh.getParam("/fin_control/port", serial_dev) == 0) ROS_INFO("Parmeter Not found defaullting Serial Port: [%s]", serial_dev.c_str()); nh.getParam("/fin_control/baud", serial_baud); ROS_INFO("Serial Port: [%s]", serial_dev.c_str()); ROS_INFO("baud: [%d]", serial_baud); maxCtrlFinAngle = degreesToRadians(10); nh.getParam("/fin_control/max_ctrl_fin_angle", maxCtrlFinAngle); ROS_INFO("max cf angle: [%f] rad", maxCtrlFinAngle); nh.getParam("/fin_control/ctrl_fin_offset", ctrlFinOffset); ROS_INFO("cf offset: [%f] rad", ctrlFinOffset); nh.getParam("/fin_control/ctrl_fin_scale_factor", ctrlFinScaleFactor); ROS_INFO("cf scale: [%f]", ctrlFinScaleFactor); nh.getParam("/fin_control/current_logging_enabled", currentLoggingEnabled); if (currentLoggingEnabled) ROS_INFO("FIN CURRENT LOGGING ENABLED"); nh.getParam("/fin_control/report_angle_rate", reportAngleRate); nh.getParam("/fin_control/min_report_angle_rate", minReportAngleRate); nh.getParam("/fin_control/max_report_angle_rate", maxReportAngleRate); ROS_INFO("fin control constructor enter"); subscriber_setAngles = nodeHandle.subscribe("/fin_control/set_angles", 10, &FinControl::handleSetAngles, this); publisher_reportAngle = diagnostic_tools::create_publisher<fin_control::ReportAngle>( nodeHandle, "/fin_control/report_angle", 1); diagnostic_tools::PeriodicMessageStatusParams report_angle_rate_check_params; report_angle_rate_check_params.min_acceptable_period(minReportAngleRate); report_angle_rate_check_params.max_acceptable_period(maxReportAngleRate); report_angle_rate_check_params.abnormal_diagnostic(diagnostic_tools::Diagnostic::WARN); report_angle_rate_check_params.stale_diagnostic({ diagnostic_tools::Diagnostic::STALE, health_monitor::ReportFault::FIN_DATA_STALE }); diagnosticsUpdater.add( publisher_reportAngle.add_check<diagnostic_tools::PeriodicMessageStatus>( "rate check", report_angle_rate_check_params)); timer_reportAngle = nodeHandle.createTimer( ros::Duration(1. / reportAngleRate), &FinControl::reportAngleSendTimeout, this); finAngleCheck = diagnostic_tools::create_health_check<double>( "Fin angle within range", [this](double angle) -> diagnostic_tools::Diagnostic { using diagnostic_tools::Diagnostic; if (std::abs(angle) > maxCtrlFinAngle) { using health_monitor::ReportFault; return Diagnostic(Diagnostic::WARN, ReportFault::FIN_DATA_THRESHOLD_REACHED) .description("Fin angle beyond limits: |%f| rad > %f rad", angle, maxCtrlFinAngle); } return Diagnostic::OK; }); diagnosticsUpdater.add(finAngleCheck); if (myWorkBench.begin(serial_dev.c_str(), serial_baud, &log)) { ROS_INFO("Dynamixel Workbench intialized"); } else { ROS_ERROR("Dynamixel Workbench failed init %s", log); return; } numOfIDs = 0; if (myWorkBench.scan(ids, &numOfIDs, 1, 4, &log)) { ROS_INFO("num of ids found [%d]", numOfIDs); if (numOfIDs < NUM_FINS) ROS_WARN("Fin servos found: [%d] does not match expected number of fins [%d]", numOfIDs, NUM_FINS); } else { ROS_ERROR("Servo scan failed! %s", log); return; } for (int x = 0; x < numOfIDs; x++) { if (!myWorkBench.torqueOn(ids[x], &log)) { ROS_ERROR("Could not set torque on fin sevro [%d] %s", ids[x], log); return; } else { servosON = true; } } if (!myWorkBench.initBulkWrite(&log)) { ROS_ERROR("Could not init bulk write %s", log); return; } ros::spin(); } FinControl::~FinControl() { const char *log; if (servosON) { ROS_INFO("Turning off fin servos"); for (int x = 0; x < numOfIDs; x++) { if (!myWorkBench.torqueOff(ids[x], &log)) ROS_ERROR("Could not turn off torque on fin sevro [%d] %s", ids[x], log); } } } void FinControl::reportAngles() { const char *log; fin_control::ReportAngle message; bool servos_angles_info_complete = true; float radianAngleFromMyWorkBench = 0.; message.header.stamp = ros::Time::now(); for (int id = 1; id <= numOfIDs; ++id) { if (myWorkBench.getRadian(id, &radianAngleFromMyWorkBench, &log)) { message.angles_in_radians.push_back( static_cast<float>( round(((radianAngleFromMyWorkBench / ctrlFinScaleFactor) - ctrlFinOffset) * 100.0) / 100.0)); finAngleCheck.test(message.angles_in_radians.back()); } else { servos_angles_info_complete = false; ROS_ERROR("Could not get servo angle for ID %d %s", id, log); } } if (servos_angles_info_complete) { publisher_reportAngle.publish(message); } } float FinControl::degreesToRadians(float degrees) { return ((degrees / 180.0) * M_PI); } void FinControl::handleSetAngles(const fin_control::SetAngles::ConstPtr &msg) { const char *log; float angle_plus_offset; for (int i = 0; i < 4; i++) { if (fabs(msg->fin_angle_in_radians[i]) > maxCtrlFinAngle) { ROS_ERROR_STREAM("The Angle " << i << "to be set is out of range - value: " << msg->fin_angle_in_radians[i]); return; } } boost::mutex::scoped_lock lock(m_mutex); if (!myWorkBench.initBulkWrite(&log)) { ROS_ERROR("Could not init bulk write %s", log); return; } int32_t current_data = 0; for (int i = 0; i < 4; ++i) { angle_plus_offset = ctrlFinScaleFactor * (msg->fin_angle_in_radians[i] + ctrlFinOffset); const int id = i + 1; if (!(myWorkBench.addBulkWriteParam( id, "Goal_Position", myWorkBench.convertRadian2Value(id, angle_plus_offset), &log))) { ROS_ERROR_STREAM("Could not add bulk write param " << id << " " << log); return; } if (!myWorkBench.bulkWrite(&log)) { ROS_ERROR_STREAM("Could not bulk write " << log); } if (currentLoggingEnabled) { if (!myWorkBench.itemRead(id, "Present_Current", &current_data, &log)) { ROS_ERROR_STREAM("Could not read current from finID: " << id << " log: " << log); } else { ROS_DEBUG_STREAM("Current for Fin: " << id << " = " << myWorkBench.convertValue2Current(static_cast<int16_t>(current_data))); } } } } void FinControl::reportAngleSendTimeout(const ros::TimerEvent &ev) { reportAngles(); diagnosticsUpdater.update(); } } }
#include "fin_control/fin_control.h" #include <string> #include <diagnostic_tools/message_stagnation_check.h> #include <diagnostic_tools/periodic_message_status.h> namespace qna { namespace robot { FinControl::FinControl(ros::NodeHandle &nodeHandle) : nodeHandle(nodeHandle), diagnosticsUpdater(nodeHandle) { diagnosticsUpdater.setHardwareID("fin_control"); fincontrolEnabled = false; std::string serial_dev = "/dev/ttyUSB0"; int serial_baud = 57600; ctrlFinOffset = 0; ctrlFinScaleFactor = 1.0; servosON = false; const char *log; currentLoggingEnabled = false; reportAngleRate = 25.0; minReportAngleRate = reportAngleRate / 2.0; maxReportAngleRate = reportAngleRate * 2.0; ros::NodeHandle nh; ROS_INFO("Starting fin_control node Version: [%s]", NODE_VERSION); nh.setParam("/version_numbers/fin_control", NODE_VERSION); if (nh.getParam("/fin_control/port", serial_dev) == 0) ROS_INFO("Parmeter Not found defaullting Serial Port: [%s]", serial_dev.c_str()); nh.getParam("/fin_control/baud", serial_baud); ROS_INFO("Serial Port: [%s]", serial_dev.c_str()); ROS_INFO("baud: [%d]", serial_baud); maxCtrlFinAngle = degreesToRadians(10); nh.getParam("/fin_control/max_ctrl_fin_angle", maxCtrlFinAngle); ROS_INFO("max cf angle: [%f] rad", maxCtrlFinAngle); nh.getParam("/fin_control/ctrl_fin_offset", ctrlFinOffset); ROS_INFO("cf offset: [%f] rad", ctrlFinOffset); nh.getParam("/fin_control/ctrl_fin_scale_factor", ctrlFinScaleFactor); ROS_INFO("cf scale: [%f]", ctrlFinScaleFactor); nh.getParam("/fin_control/current_logging_enabled", currentLoggingEnabled); if (currentLoggingEnabled) ROS_INFO("FIN CURRENT LOGGING ENABLED"); nh.getParam("/fin_control/report_angle_rate", reportAngleRate); nh.getParam("/fin_control/min_report_angle_rate", minReportAngleRate); nh.getParam("/fin_control/max_report_angle_rate", maxReportAngleRate); ROS_INFO("fin control constructor enter"); subscriber_setAngles = nodeHandle.subscribe("/fin_control/set_angles", 10, &FinControl::handleSetAngles, this); publisher_reportAngle = diagnostic_tools::create_publisher<fin_control::ReportAngle>( nodeHandle, "/fin_control/report_angle", 1); diagnostic_tools::PeriodicMessageStatusParams report_angle_rate_check_params; report_angle_rate_check_params.min_acceptable_period(minReportAngleRate); report_angle_rate_check_params.max_acceptable_period(maxReportAngleRate); report_angle_rate_check_params.abnormal_diagnostic(diagnostic_tools::Diagnostic::WARN); report_angle_rate_check_params.stale_diagnostic({ diagnostic_tools::Diagnostic::STALE, health_monitor::ReportFault::FIN_DATA_STALE }); diagnosticsUpdater.add( publisher_reportAngle.add_check<diagnostic_tools::PeriodicMessageStatus>( "rate check", report_angle_rate_check_params)); timer_reportAngle = nodeHandle.createTimer( ros::Duration(1. / reportAngleRate), &FinControl::reportAngleSendTimeout, this); finAngleCheck = diagnostic_tools::create_health_check<double>( "Fin angle within range", [this](double angle) -> diagnostic_tools::Diagnostic { using diagnostic_tools::Diagnostic; if (std::abs(angle) > maxCtrlFinAngle) { using health_monitor::ReportFault; return Diagnostic(Diagnostic::WARN, ReportFault::FIN_DATA_THRESHOLD_REACHED) .description("Fin angle beyond limits: |%f| rad > %f rad", angle, maxCtrlFinAngle); } return Diagnostic::OK; }); diagnosticsUpdater.add(finAngleCheck); if (myWorkBench.begin(serial_dev.c_str(), serial_baud, &log)) { ROS_INFO("Dynamixel Workbench intialized"); } else { ROS_ERROR("Dynamixel Workbench failed init %s", log); return; } numOfIDs = 0; if (myWorkBench.scan(ids, &numOfIDs, 1, 4, &log)) { ROS_INFO("num of ids found [%d]", numOfIDs); if (numOfIDs < NUM_FINS) ROS_WARN("Fin servos found: [%d] does not match expected number of fins [%d]", numOfIDs, NUM_FINS); } else { ROS_ERROR("Servo scan failed! %s", log); return; } for (int x = 0; x < numOfIDs; x++) { if (!myWorkBench.torqueOn(ids[x], &log)) { ROS_ERROR("Could not set torque on fin sevro [%d] %s", ids[x], log); return; } else { servosON = true; } } if (!myWorkBench.initBulkWrite(&log)) { ROS_ERROR("Could not init bulk write %s", log); return; } ros::spin(); } FinControl::~FinControl() { const char *log; if (servosON) { ROS_INFO("Turning off fin servos"); for (int x = 0; x < numOfIDs; x++) { if (!myWorkBench.torqueOff(ids[x], &log)) ROS_ERROR("Could not turn off torque on fin sevro [%d] %s", ids[x], log); } } } void FinControl::reportAngles() { const char *log; fin_control::ReportAngle message; bool servos_angles_info_complete = true; float radianAngleFromMyWorkBench = 0.; message.header.stamp = ros::Time::now(); for (int id = 1; id <= numOfIDs; ++id) { if (myWorkBench.getRadian(id, &radianAngleFromMyWorkBench, &log)) { message.angles_in_radians.push_back( static_cast<floa
float FinControl::degreesToRadians(float degrees) { return ((degrees / 180.0) * M_PI); } void FinControl::handleSetAngles(const fin_control::SetAngles::ConstPtr &msg) { const char *log; float angle_plus_offset; for (int i = 0; i < 4; i++) { if (fabs(msg->fin_angle_in_radians[i]) > maxCtrlFinAngle) { ROS_ERROR_STREAM("The Angle " << i << "to be set is out of range - value: " << msg->fin_angle_in_radians[i]); return; } } boost::mutex::scoped_lock lock(m_mutex); if (!myWorkBench.initBulkWrite(&log)) { ROS_ERROR("Could not init bulk write %s", log); return; } int32_t current_data = 0; for (int i = 0; i < 4; ++i) { angle_plus_offset = ctrlFinScaleFactor * (msg->fin_angle_in_radians[i] + ctrlFinOffset); const int id = i + 1; if (!(myWorkBench.addBulkWriteParam( id, "Goal_Position", myWorkBench.convertRadian2Value(id, angle_plus_offset), &log))) { ROS_ERROR_STREAM("Could not add bulk write param " << id << " " << log); return; } if (!myWorkBench.bulkWrite(&log)) { ROS_ERROR_STREAM("Could not bulk write " << log); } if (currentLoggingEnabled) { if (!myWorkBench.itemRead(id, "Present_Current", &current_data, &log)) { ROS_ERROR_STREAM("Could not read current from finID: " << id << " log: " << log); } else { ROS_DEBUG_STREAM("Current for Fin: " << id << " = " << myWorkBench.convertValue2Current(static_cast<int16_t>(current_data))); } } } } void FinControl::reportAngleSendTimeout(const ros::TimerEvent &ev) { reportAngles(); diagnosticsUpdater.update(); } } }
t>( round(((radianAngleFromMyWorkBench / ctrlFinScaleFactor) - ctrlFinOffset) * 100.0) / 100.0)); finAngleCheck.test(message.angles_in_radians.back()); } else { servos_angles_info_complete = false; ROS_ERROR("Could not get servo angle for ID %d %s", id, log); } } if (servos_angles_info_complete) { publisher_reportAngle.publish(message); } }
function_block-function_prefixed
[ { "content": "class IntrospectableNode<BaseNodeT, true> : public BaseNodeT\n\n{\n\n public:\n\n IntrospectableNode(const std::string& name, const BT::NodeConfiguration& config)\n\n : BaseNodeT(name), blackboard_(config.blackboard)\n\n {\n\n }\n\n\n\n BT::NodeStatus executeTick() override\n\n {\n\n ...
C++
Source/UnitUtil.cpp
biug/XBot
20f51094ee18aeaa58d769a894c68b4f05f900d4
#include "UnitUtil.h" using namespace XBot; bool UnitUtil::IsMorphedBuildingType(BWAPI::UnitType type) { return type == BWAPI::UnitTypes::Zerg_Sunken_Colony || type == BWAPI::UnitTypes::Zerg_Spore_Colony || type == BWAPI::UnitTypes::Zerg_Lair || type == BWAPI::UnitTypes::Zerg_Hive || type == BWAPI::UnitTypes::Zerg_Greater_Spire; } bool UnitUtil::IsCombatSimUnit(BWAPI::UnitType type) { if (type.isWorker()) { return false; } return type.canAttack() || type == BWAPI::UnitTypes::Terran_Medic || type.isDetector(); } bool UnitUtil::IsCombatUnit(BWAPI::UnitType type) { if (type.isWorker() || type.isBuilding() || type == BWAPI::UnitTypes::Protoss_Interceptor) { return false; } if (type.canAttack() || type.isDetector() || type == BWAPI::UnitTypes::Terran_Medic || type == BWAPI::UnitTypes::Protoss_High_Templar || type.isFlyer() && type.spaceProvided() > 0) { return true; } return false; } bool UnitUtil::IsCombatUnit(BWAPI::Unit unit) { UAB_ASSERT(unit != nullptr, "Unit was null"); if (!unit) { return false; } return IsCombatUnit(unit->getType()); } bool UnitUtil::IsValidUnit(BWAPI::Unit unit) { return unit && unit->exists() && (unit->isCompleted() || IsMorphedBuildingType(unit->getType())) && unit->getHitPoints() > 0 && unit->getType() != BWAPI::UnitTypes::Unknown && unit->getPosition().isValid(); } bool UnitUtil::CanAttack(BWAPI::Unit attacker, BWAPI::Unit target) { return target->isFlying() ? TypeCanAttackAir(attacker->getType()) : TypeCanAttackGround(attacker->getType()); } bool UnitUtil::CanAttack(BWAPI::UnitType attacker, BWAPI::UnitType target) { return target.isFlyer() ? TypeCanAttackAir(attacker) : TypeCanAttackGround(attacker); } bool UnitUtil::CanAttackAir(BWAPI::Unit attacker) { return TypeCanAttackAir(attacker->getType()); } bool UnitUtil::TypeCanAttackAir(BWAPI::UnitType attacker) { return attacker.airWeapon() != BWAPI::WeaponTypes::None || attacker == BWAPI::UnitTypes::Terran_Bunker || attacker == BWAPI::UnitTypes::Protoss_Carrier; } bool UnitUtil::CanAttackGround(BWAPI::Unit attacker) { return TypeCanAttackGround(attacker->getType()); } bool UnitUtil::TypeCanAttackGround(BWAPI::UnitType attacker) { return attacker.groundWeapon() != BWAPI::WeaponTypes::None || attacker == BWAPI::UnitTypes::Terran_Bunker || attacker == BWAPI::UnitTypes::Protoss_Carrier || attacker == BWAPI::UnitTypes::Protoss_Reaver; } double UnitUtil::CalculateLTD(BWAPI::Unit attacker, BWAPI::Unit target) { BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None || weapon.damageCooldown() <= 0) { return 0; } return double(weapon.damageAmount()) / weapon.damageCooldown(); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::Unit attacker, BWAPI::Unit target) { return GetWeapon(attacker->getType(), target); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::UnitType attacker, BWAPI::Unit target) { if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return GetWeapon(BWAPI::UnitTypes::Protoss_Interceptor, target); } if (attacker == BWAPI::UnitTypes::Protoss_Reaver) { return GetWeapon(BWAPI::UnitTypes::Protoss_Scarab, target); } return target->isFlying() ? attacker.airWeapon() : attacker.groundWeapon(); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::UnitType attacker, BWAPI::UnitType target) { if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return GetWeapon(BWAPI::UnitTypes::Protoss_Interceptor, target); } if (attacker == BWAPI::UnitTypes::Protoss_Reaver) { return GetWeapon(BWAPI::UnitTypes::Protoss_Scarab, target); } return target.isFlyer() ? attacker.airWeapon() : attacker.groundWeapon(); } int UnitUtil::GetAttackRange(BWAPI::Unit attacker, BWAPI::Unit target) { if (attacker->getType() == BWAPI::UnitTypes::Protoss_Reaver && !target->isFlying()) { return 8; } if (attacker->getType() == BWAPI::UnitTypes::Protoss_Carrier) { return 8; } if (attacker->getType() == BWAPI::UnitTypes::Terran_Bunker) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::U_238_Shells)) { return 6 * 32; } return 5 * 32; } const BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None) { return 0; } int range = weapon.maxRange(); if (attacker->getType() == BWAPI::UnitTypes::Protoss_Dragoon) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Singularity_Charge)) { range = 6 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Terran_Marine) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::U_238_Shells)) { range = 5 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Terran_Goliath && target->isFlying()) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Charon_Boosters)) { range = 8 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Zerg_Hydralisk) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Grooved_Spines)) { range = 5 * 32; } } return range; } int UnitUtil::GetAttackRangeAssumingUpgrades(BWAPI::UnitType attacker, BWAPI::UnitType target) { if (attacker == BWAPI::UnitTypes::Protoss_Reaver && !target.isFlyer()) { return 8; } if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return 8; } if (attacker == BWAPI::UnitTypes::Terran_Bunker) { return 6 * 32; } BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None) { return 0; } int range = weapon.maxRange(); if (attacker == BWAPI::UnitTypes::Protoss_Dragoon) { range = 6 * 32; } else if (attacker == BWAPI::UnitTypes::Terran_Marine) { range = 5 * 32; } else if (attacker == BWAPI::UnitTypes::Terran_Goliath && target.isFlyer()) { range = 8 * 32; } else if (attacker == BWAPI::UnitTypes::Zerg_Hydralisk) { range = 5 * 32; } return range; } int UnitUtil::GetAllUnitCount(BWAPI::UnitType type) { int count = 0; for (const auto unit : BWAPI::Broodwar->self()->getUnits()) { if (unit->getType() == type) { count++; } if (unit->getType() == BWAPI::UnitTypes::Zerg_Egg && unit->getBuildType() == type) { count += type.isTwoUnitsInOneEgg() ? 2 : 1; } if (unit->getRemainingTrainTime() > 0) { BWAPI::UnitType trainType = unit->getLastCommand().getUnitType(); if (trainType == type && unit->getRemainingTrainTime() == trainType.buildTime()) { count++; } } } return count; } int UnitUtil::GetCompletedUnitCount(BWAPI::UnitType type) { int count = 0; for (const auto unit : BWAPI::Broodwar->self()->getUnits()) { if (unit->getType() == type && unit->isCompleted()) { count++; } } return count; }
#include "UnitUtil.h" using namespace XBot; bool UnitUtil::IsMorphedBuildingType(BWAPI::UnitType type) { return type == BWAPI::UnitTypes::Zerg_Sunken_Colony || type == BWAPI::UnitTypes::Zerg_Spore_Colony || type == BWAPI::UnitTypes::Zerg_Lair || type == BWAPI::UnitTypes::Zerg_Hive || type == BWAPI::UnitTypes::Zerg_Greater_Spire; } bool UnitUtil::IsCombatSimUnit(BWAPI::UnitType type) { if (type.isWorker()) { return false; } return type.canAttack() || type == BWAPI::UnitTypes::Terran_Medic || type.isDetector(); } bool UnitUtil::IsCombatUnit(BWAPI::UnitType type) { if (type.isWorker() || type.isBuilding() || type == BWAPI::UnitTypes::Protoss_Interceptor) { return false; } if (type.canAttack() || type.isDetector() || type == BWAPI::UnitTypes::Terran_Medic || type == BWAPI::UnitTypes::Protoss_High_Templar || type.isFlyer() && type.spaceProvided() > 0) { return true; } return false; } bool UnitUtil::IsCombatUnit(BWAPI::Unit unit) { UAB_ASSERT(unit != nullptr, "Unit was null"); if (!unit) { return false; } return IsCombatUnit(unit->getType()); } bool UnitUtil::IsValidUnit(BWAPI::Unit unit) { return unit && unit->exists() && (unit->isCompleted() || IsMorphedBuildingType(unit->getType())) && unit->getHitPoints() > 0 && unit->getType() != BWAPI::UnitTypes::Unknown && unit->getPosition().isValid(); } bool UnitUtil::CanAttack(BWAPI::Unit attacker, BWAPI::Unit target) { return target->isFlying() ? TypeCanAttackAir(attacker->getType()) : TypeCanAttackGround(attacker->getType()); } bool UnitUtil::CanAttack(BWAPI::UnitType attacker, BWAPI::UnitType target) { return target.isFlyer() ? TypeCanAttackAir(attacker) : TypeCanAttackGround(attacker); } bool UnitUtil::CanAttackAir(BWAPI::Unit attacker) { return TypeCanAttackAir(attacker->getType()); } bool UnitUtil::TypeCanAttackAir(BWAPI::UnitType attacker) { return attacker.airWeapon() != BWAPI::WeaponTypes::None || attacker == BWAPI::UnitTypes::Terran_Bunker || attacker == BWAPI::UnitTypes::Protoss_Carrier; } bool UnitUtil::CanAttackGround(BWAPI::Unit attacker) { return TypeCanAttackGround(attacker->getType()); } bool UnitUtil::TypeCanAttackGround(BWAPI::UnitType attacker) { return attacker.groundWeapon() != BWAPI::WeaponTypes::None || attacker == BWAPI::UnitTypes::Terran_Bunker || attacker == BWAPI::UnitTypes::Protoss_Carrier || attacker == BWAPI::UnitTypes::Protoss_Reaver; } double UnitUtil::CalculateLTD(BWAPI::Unit attacker, BWAPI::Unit target) { BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None || weapon.damageCooldown() <= 0) { return 0; } return double(weapon.damageAmount()) / weapon.damageCooldown(); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::Unit attacker, BWAPI::Unit target) { return GetWeapon(attacker->getType(), target); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::UnitType attacker, BWAPI::Unit target) { if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return GetWeapon(BWAPI::UnitTypes::Protoss_Interceptor, target); } if (attacker == BWAPI::UnitTypes::Protoss_Reaver) { return GetWeapon(BWAPI::UnitTypes::Protoss_Scarab, target); } return target->isFlying() ? attacker.airWeapon() : attacker.groundWeapon(); } BWAPI::WeaponType UnitUtil::GetWeapon(BWAPI::UnitType attacker, BWAPI::UnitType target) { if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return GetWeapon(BWAPI::UnitTypes::Protoss_Interceptor, target); } if (attacker == BWAPI::UnitTypes::Protoss_Reaver) { return GetWeapon(BWAPI::UnitTypes::Protoss_Scarab, target); } return target.isFlyer() ? attacker.airWeapon() : attacker.groundWeapon(); } int UnitUtil::GetAttackRange(BWAPI::Unit attacker, BWAPI::Unit target) { if (attacker->getType() == BWAPI::UnitTypes::Protoss_Reaver && !target->isFlying()) { return 8; } if (attacker->getType() == BWAPI::UnitTypes::Protoss_Carrier) { return 8; } if (attacker->getType() == BWAPI::UnitTypes::Terran_Bunker) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::U_238_Shells)) { return 6 * 32; } return 5 * 32; } const BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None) { return 0; } int range = weapon.maxRange(); if (attacker->getType() == BWAPI::UnitTypes::Protoss_Dragoon) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Singularity_Charge)) { range = 6 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Terran_Marine) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::U_238_Shells)) { range = 5 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Terran_Goliath && target->isFlying()) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Charon_Boosters)) { range = 8 * 32; } } else if (attacker->getType() == BWAPI::UnitTypes::Zerg_Hydralisk) { if (attacker->getPlayer() == BWAPI::Broodwar->enemy() || BWAPI::Broodwar->self()->getUpgradeLevel(BWAPI::UpgradeTypes::Grooved_Spines)) { range = 5 * 32; } } return range; } int UnitUtil::GetAttackRangeAssumingUpgrades(BWAPI::UnitType attacker, BWAPI::UnitType target) { if (attacker == BWAPI::UnitTypes::Protoss_Reaver && !target.isFlyer()) { return 8; } if (attacker == BWAPI::UnitTypes::Protoss_Carrier) { return 8; } if (attacker == BWAPI::UnitTypes::Terran_Bunker) { return 6 * 32; } BWAPI::WeaponType weapon = GetWeapon(attacker, target); if (weapon == BWAPI::WeaponTypes::None) { return 0; } int range = weapon.maxRange(); if (attacker == BWAPI::UnitTypes::Protoss_Dragoon) { range = 6 * 32; } else if (attacker == BWAPI::UnitTypes::Terran_Marine) { range = 5 * 32; } else if (attacker == BWAPI::UnitTypes::Terran_Goliath && target.isFlyer()) { range = 8 * 32; } else if (attacker == BWAPI::UnitTypes::Zerg_Hydralisk) { range = 5 * 32; } return range; } int UnitUtil::GetAllUnitCount(BWAPI::UnitType type) { int count = 0; for (const auto unit : BWAPI::Broodwar->self()->getUnits()) { if (unit->getType() == type) { count++; } if (unit->getType() == BWAPI::UnitTypes::Ze
int UnitUtil::GetCompletedUnitCount(BWAPI::UnitType type) { int count = 0; for (const auto unit : BWAPI::Broodwar->self()->getUnits()) { if (unit->getType() == type && unit->isCompleted()) { count++; } } return count; }
rg_Egg && unit->getBuildType() == type) { count += type.isTwoUnitsInOneEgg() ? 2 : 1; } if (unit->getRemainingTrainTime() > 0) { BWAPI::UnitType trainType = unit->getLastCommand().getUnitType(); if (trainType == type && unit->getRemainingTrainTime() == trainType.buildTime()) { count++; } } } return count; }
function_block-function_prefixed
[ { "content": "// Unit choices for main unit mix and tech target.\n\n// This deliberately omits support units like queens and defilers.\n\nenum class TechUnit : int\n\n\t{ None\n\n\t, Zerglings\n\n\t, Hydralisks\n\n\t, Lurkers\n\n\t, Mutalisks\n\n\t, Ultralisks\n\n\t, Guardians\n\n\t, Devourers\n\n\t, Size\n\n};...
C++
wrappers/8.1.1/vtkSPHQuinticKernelWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
#define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkSPHKernelWrap.h" #include "vtkSPHQuinticKernelWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkAbstractPointLocatorWrap.h" #include "vtkDataSetWrap.h" #include "vtkPointDataWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkSPHQuinticKernelWrap::ptpl; VtkSPHQuinticKernelWrap::VtkSPHQuinticKernelWrap() { } VtkSPHQuinticKernelWrap::VtkSPHQuinticKernelWrap(vtkSmartPointer<vtkSPHQuinticKernel> _native) { native = _native; } VtkSPHQuinticKernelWrap::~VtkSPHQuinticKernelWrap() { } void VtkSPHQuinticKernelWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkSPHQuinticKernel").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("SPHQuinticKernel").ToLocalChecked(), ConstructorGetter); } void VtkSPHQuinticKernelWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkSPHQuinticKernelWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkSPHKernelWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkSPHKernelWrap::ptpl)); tpl->SetClassName(Nan::New("VtkSPHQuinticKernelWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ComputeDerivWeight", ComputeDerivWeight); Nan::SetPrototypeMethod(tpl, "computeDerivWeight", ComputeDerivWeight); Nan::SetPrototypeMethod(tpl, "ComputeFunctionWeight", ComputeFunctionWeight); Nan::SetPrototypeMethod(tpl, "computeFunctionWeight", ComputeFunctionWeight); Nan::SetPrototypeMethod(tpl, "Initialize", Initialize); Nan::SetPrototypeMethod(tpl, "initialize", Initialize); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); #ifdef VTK_NODE_PLUS_VTKSPHQUINTICKERNELWRAP_INITPTPL VTK_NODE_PLUS_VTKSPHQUINTICKERNELWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkSPHQuinticKernelWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkSPHQuinticKernel> native = vtkSmartPointer<vtkSPHQuinticKernel>::New(); VtkSPHQuinticKernelWrap* obj = new VtkSPHQuinticKernelWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkSPHQuinticKernelWrap::ComputeDerivWeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->ComputeDerivWeight( info[0]->NumberValue() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::ComputeFunctionWeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->ComputeFunctionWeight( info[0]->NumberValue() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAbstractPointLocatorWrap::ptpl))->HasInstance(info[0])) { VtkAbstractPointLocatorWrap *a0 = ObjectWrap::Unwrap<VtkAbstractPointLocatorWrap>(info[0]->ToObject()); if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataSetWrap::ptpl))->HasInstance(info[1])) { VtkDataSetWrap *a1 = ObjectWrap::Unwrap<VtkDataSetWrap>(info[1]->ToObject()); if(info.Length() > 2 && info[2]->IsObject() && (Nan::New(VtkPointDataWrap::ptpl))->HasInstance(info[2])) { VtkPointDataWrap *a2 = ObjectWrap::Unwrap<VtkPointDataWrap>(info[2]->ToObject()); if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->Initialize( (vtkAbstractPointLocator *) a0->native.GetPointer(), (vtkDataSet *) a1->native.GetPointer(), (vtkPointData *) a2->native.GetPointer() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); vtkSPHQuinticKernel * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkSPHQuinticKernelWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkSPHQuinticKernelWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkSPHQuinticKernelWrap *w = new VtkSPHQuinticKernelWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkSPHQuinticKernelWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkSPHQuinticKernel * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkSPHQuinticKernelWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkSPHQuinticKernelWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkSPHQuinticKernelWrap *w = new VtkSPHQuinticKernelWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); }
#define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkSPHKernelWrap.h" #include "vtkSPHQuinticKernelWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkAbstractPointLocatorWrap.h" #include "vtkDataSetWrap.h" #include "vtkPointDataWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkSPHQuinticKernelWrap::ptpl; VtkSPHQuinticKernelWrap::VtkSPHQuinticKernelWrap() { } VtkSPHQuinticKernelWrap::VtkSPHQuinticKernelWrap(vtkSmartPointer<vtkSPHQuinticKernel> _native) { native = _native; } VtkSPHQuinticKernelWrap::~VtkSPHQuinticKernelWrap() { } void VtkSPHQuinticKernelWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkSPHQuinticKernel").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("SPHQuinticKernel").ToLocalChecked(), ConstructorGetter); } void VtkSPHQuinticKernelWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkSPHQuinticKernelWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkSPHKernelWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkSPHKernelWrap::ptpl)); tpl->SetClassName(Nan::New("VtkSPHQuinticKernelWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ComputeDerivWeight", ComputeDerivWeight); Nan::SetPrototypeMethod(tpl, "computeDerivWeight", ComputeDerivWeight); Nan::SetPrototypeMethod(tpl, "ComputeFunctionWeight", ComputeFunctionWeight); Nan::SetPrototypeMethod(tpl, "computeFunctionWeight", ComputeFunctionWeight); Nan::SetPrototypeMethod(tpl, "Initialize", Initialize); Nan::SetPrototypeMethod(tpl, "initialize", Initialize); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); #ifdef VTK_NODE_PLUS_VTKSPHQUINTICKERNELWRAP_INITPTPL VTK_NODE_PLUS_VTKSPHQUINTICKERNEL
et(wo); return; } Nan::ThrowError("Parameter mismatch"); }
WRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkSPHQuinticKernelWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkSPHQuinticKernel> native = vtkSmartPointer<vtkSPHQuinticKernel>::New(); VtkSPHQuinticKernelWrap* obj = new VtkSPHQuinticKernelWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkSPHQuinticKernelWrap::ComputeDerivWeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->ComputeDerivWeight( info[0]->NumberValue() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::ComputeFunctionWeight(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { double r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->ComputeFunctionWeight( info[0]->NumberValue() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAbstractPointLocatorWrap::ptpl))->HasInstance(info[0])) { VtkAbstractPointLocatorWrap *a0 = ObjectWrap::Unwrap<VtkAbstractPointLocatorWrap>(info[0]->ToObject()); if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataSetWrap::ptpl))->HasInstance(info[1])) { VtkDataSetWrap *a1 = ObjectWrap::Unwrap<VtkDataSetWrap>(info[1]->ToObject()); if(info.Length() > 2 && info[2]->IsObject() && (Nan::New(VtkPointDataWrap::ptpl))->HasInstance(info[2])) { VtkPointDataWrap *a2 = ObjectWrap::Unwrap<VtkPointDataWrap>(info[2]->ToObject()); if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->Initialize( (vtkAbstractPointLocator *) a0->native.GetPointer(), (vtkDataSet *) a1->native.GetPointer(), (vtkPointData *) a2->native.GetPointer() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkSPHQuinticKernelWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); vtkSPHQuinticKernel * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkSPHQuinticKernelWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkSPHQuinticKernelWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkSPHQuinticKernelWrap *w = new VtkSPHQuinticKernelWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkSPHQuinticKernelWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkSPHQuinticKernelWrap *wrapper = ObjectWrap::Unwrap<VtkSPHQuinticKernelWrap>(info.Holder()); vtkSPHQuinticKernel *native = (vtkSPHQuinticKernel *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkSPHQuinticKernel * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkSPHQuinticKernelWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkSPHQuinticKernelWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkSPHQuinticKernelWrap *w = new VtkSPHQuinticKernelWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().S
random
[]
C++
Engine/qxtcheckcombobox.cpp
vadkasevas/BAS
657f62794451c564c77d6f92b2afa9f5daf2f517
#include "qxtcheckcombobox.h" #include <QKeyEvent> #include <QDebug> #include <QStylePainter> bool QxtCheckComboBox::eventFilter(QObject* receiver, QEvent* event) { if(event->type() == QEvent::MouseButtonPress && receiver == Edit) { if(Edit->underMouse()) { showPopup(); } else { hidePopup(); } return true; } switch (event->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (receiver == this && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { showPopup(); return true; } else if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Escape) { QComboBox::hidePopup(); if (keyEvent->key() != Qt::Key_Escape) return true; } } case QEvent::MouseButtonPress: containerMousePress = (receiver == view()->window()); break; case QEvent::MouseButtonRelease: containerMousePress = false; break; default: break; } return false; } void QxtCheckComboBox::updateCheckedItems() { QStringList items = checkedItems(); QList<int> indexes = checkedIndexes(); if (items.isEmpty()) { setEditText(_defaultText); } else { setEditText(items.join(_separator)); } emit checkedItemsChanged(items); QList<int> New = indexes,Old = LastItemsSelected; LastItemsSelected = indexes; emit checkedIndexesChanged(Old,New); } void QxtCheckComboBox::toggleCheckState(int index) { QVariant value = itemData(index, Qt::CheckStateRole); if (value.isValid()) { Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); setItemData(index, (state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); } } QxtCheckComboModel::QxtCheckComboModel(QObject* parent) : QStandardItemModel(0, 1, parent) { } Qt::ItemFlags QxtCheckComboModel::flags(const QModelIndex& index) const { return QStandardItemModel::flags(index) | Qt::ItemIsUserCheckable; } QVariant QxtCheckComboModel::data(const QModelIndex& index, int role) const { QVariant value = QStandardItemModel::data(index, role); if (index.isValid() && role == Qt::CheckStateRole && !value.isValid()) value = Qt::Unchecked; return value; } bool QxtCheckComboModel::setData(const QModelIndex& index, const QVariant& value, int role) { bool ok = QStandardItemModel::setData(index, value, role); if (ok && role == Qt::CheckStateRole) { emit dataChanged(index, index); emit checkStateChanged(); } return ok; } QxtCheckComboBox::QxtCheckComboBox(QWidget* parent) : QComboBox(parent), mDisplayRectDelta(4, 1, -25, 0) { QListView * listView = new QListView(this); QPalette palette; palette.setColor(QPalette::Window, QColor( 200 , 200 , 200 )); palette.setColor(QPalette::Base, QColor( 55, 55 , 55 )); listView->setPalette(palette); setView(listView); _separator = QLatin1String(","); setModel(new QxtCheckComboModel(this)); connect(this, SIGNAL(activated(int)), this, SLOT(toggleCheckState(int))); connect(model(), SIGNAL(checkStateChanged()), this, SLOT(updateCheckedItems())); connect(model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(updateCheckedItems())); connect(model(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, SLOT(updateCheckedItems())); Edit = new QLineEdit(this); Edit->setReadOnly(true); setLineEdit(Edit); Edit->disconnect(this); Edit->installEventFilter(this); Edit->setEnabled(false); setInsertPolicy(QComboBox::NoInsert); view()->installEventFilter(this); view()->window()->installEventFilter(this); view()->viewport()->installEventFilter(this); this->installEventFilter(this); } QxtCheckComboBox::~QxtCheckComboBox() { } void QxtCheckComboBox::hidePopup() { if (containerMousePress) { QComboBox::hidePopup(); } } void QxtCheckComboBox::showPopup() { QComboBox::showPopup(); } Qt::CheckState QxtCheckComboBox::itemCheckState(int index) const { return static_cast<Qt::CheckState>(itemData(index, Qt::CheckStateRole).toInt()); } void QxtCheckComboBox::setItemCheckState(int index, Qt::CheckState state) { setItemData(index, state, Qt::CheckStateRole); } QStringList QxtCheckComboBox::checkedItems() const { QStringList items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.data().toString(); } return items; } QStringList QxtCheckComboBox::checkedData() const { QStringList items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.data(Qt::UserRole).toString(); } return items; } QList<int> QxtCheckComboBox::checkedIndexes() { QList<int> items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.row(); } return items; } void QxtCheckComboBox::setCheckedItems(const QStringList& items) { foreach(const QString& text, items) { const int index = findText(text); setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked); } } void QxtCheckComboBox::setCheckedData(const QStringList& items) { foreach(const QString& text, items) { const int index = findData(text); setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked); } } void QxtCheckComboBox::setCheckedIndexes(const QList<int>& indexes) { for(int index = 0;index<model()->rowCount();index ++) { setItemCheckState(index, indexes.contains(index) ? Qt::Checked : Qt::Unchecked); } LastItemsSelected = indexes; } QList<int> QxtCheckComboBox::currentIndexes() { return LastItemsSelected; } QString QxtCheckComboBox::defaultText() const { return _defaultText; } void QxtCheckComboBox::setDefaultText(const QString& text) { if (_defaultText != text) { _defaultText = text; this->updateCheckedItems(); } } QString QxtCheckComboBox::separator() const { return _separator; } void QxtCheckComboBox::setSeparator(const QString& separator) { if (_separator != separator) { _separator = separator; updateCheckedItems(); } }
#include "qxtcheckcombobox.h" #include <QKeyEvent> #include <QDebug> #include <QStylePainter> bool QxtCheckComboBox::eventFilter(QObject* receiver, QEvent* event) { if(event->type() == QEvent::MouseButtonPress && receiver == Edit) { if(Edit->underMouse()) { showPopup(); } else { hidePopup(); } return true; } switch (event->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (receiver == this && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { showPopup(); return true; } else if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Escape) { QComboBox::hidePopup(); if (keyEvent->key() != Qt::Key_Escape) return true; } } case QEvent::MouseButtonPress: containerMousePress = (receiver == view()->window()); break; case QEvent::MouseButtonRelease: containerMousePress = false; break; default: break; } return false; } void QxtCheckComboBox::updateCheckedItems() { QStringList items = checkedItems(); QList<int> indexes = checkedIndexes(); if (items.isEmpty()) { setEditText(_defaultText); } else { setEditText(items.join(_separator)); } emit checkedItemsChanged(items); QList<int> New = indexes,Old = LastItemsSelected; LastItemsSelected = indexes; emit checkedIndexesChanged(Old,New); } void QxtCheckComboBox::toggleCheckState(int index) { QVariant value = itemData(index, Qt::CheckStateRole); if (value.isValid()) { Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); setItemData(index, (state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); } } QxtCheckComboModel::QxtCheckComboModel(QObject* parent) : QStandardItemModel(0, 1, parent) { } Qt::ItemFlags QxtCheckComboModel::flags(const QModelIndex& index) const { return QStandardItemModel::flags(index) | Qt::ItemIsUserCheckable; } QVariant QxtCheckComboModel::data(const QModelIndex& index, int role) const { QVariant value = QStandardItemModel::data(index, role); if (index.isValid() && role == Qt::CheckStateRole && !value.isValid()) value = Qt::Unchecked; return value; } bool QxtCheckComboModel::setData(const QModelIndex& index, const QVariant& value, int role) { bool ok = QStandardItemModel::setData(index, value, role); if (ok && role == Qt::CheckStateRole) { emit dataChanged(index, index); emit checkStateChanged(); } return ok; } QxtCheckComboBox::QxtCheckComboBox(QWidget* parent) : QComboBox(parent), mDisplayRectDelta(4, 1, -25, 0) { QListView * listView = new QListView(this); QPalette palette; palette.setColor(QPalette::Window, QColor( 200 , 200 , 200 )); palette.setColor(QPalette::Base, QColor( 55, 55 , 55 )); listView->setPalette(palette); setView(listView); _separator = QLatin1String(","); setModel(new QxtCheckComboModel(this)); connect(this, SIGNAL(activated(int)), this, SLOT(toggleCheckState(int))); connect(model(), SIGNAL(checkStateChanged()), this, SLOT(updateCheckedItems())); connect(model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(updateCheckedItems())); connect(model(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, SLOT(updateCheckedItems())); Edit = new QLineEdit(this); Edit->setReadOnly(true); setLineEdit(Edit); Edit->disconnect(this); Edit->installEventFilter(this); Edit->setEnabled(false);
QxtCheckComboBox::~QxtCheckComboBox() { } void QxtCheckComboBox::hidePopup() { if (containerMousePress) { QComboBox::hidePopup(); } } void QxtCheckComboBox::showPopup() { QComboBox::showPopup(); } Qt::CheckState QxtCheckComboBox::itemCheckState(int index) const { return static_cast<Qt::CheckState>(itemData(index, Qt::CheckStateRole).toInt()); } void QxtCheckComboBox::setItemCheckState(int index, Qt::CheckState state) { setItemData(index, state, Qt::CheckStateRole); } QStringList QxtCheckComboBox::checkedItems() const { QStringList items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.data().toString(); } return items; } QStringList QxtCheckComboBox::checkedData() const { QStringList items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.data(Qt::UserRole).toString(); } return items; } QList<int> QxtCheckComboBox::checkedIndexes() { QList<int> items; if (model()) { QModelIndex index = model()->index(0, modelColumn(), rootModelIndex()); QModelIndexList indexes = model()->match(index, Qt::CheckStateRole, Qt::Checked, -1, Qt::MatchExactly); foreach(const QModelIndex& index, indexes) items += index.row(); } return items; } void QxtCheckComboBox::setCheckedItems(const QStringList& items) { foreach(const QString& text, items) { const int index = findText(text); setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked); } } void QxtCheckComboBox::setCheckedData(const QStringList& items) { foreach(const QString& text, items) { const int index = findData(text); setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked); } } void QxtCheckComboBox::setCheckedIndexes(const QList<int>& indexes) { for(int index = 0;index<model()->rowCount();index ++) { setItemCheckState(index, indexes.contains(index) ? Qt::Checked : Qt::Unchecked); } LastItemsSelected = indexes; } QList<int> QxtCheckComboBox::currentIndexes() { return LastItemsSelected; } QString QxtCheckComboBox::defaultText() const { return _defaultText; } void QxtCheckComboBox::setDefaultText(const QString& text) { if (_defaultText != text) { _defaultText = text; this->updateCheckedItems(); } } QString QxtCheckComboBox::separator() const { return _separator; } void QxtCheckComboBox::setSeparator(const QString& separator) { if (_separator != separator) { _separator = separator; updateCheckedItems(); } }
setInsertPolicy(QComboBox::NoInsert); view()->installEventFilter(this); view()->window()->installEventFilter(this); view()->viewport()->installEventFilter(this); this->installEventFilter(this); }
function_block-function_prefix_line
[ { "content": "var Index = GetInputConstructorValue(\"Index\", loader);\n", "file_path": "Modules/List/js/get_list_element_by_index_select.js", "rank": 0, "score": 107529.92272205185 }, { "content": "class DatabaseAdminItemEdit;\n\n}\n\nusing namespace BrowserAutomationStudioFramework;\n", ...
C++
wrappers/src/object-store/tests/results.cpp
drungrin/realm-dotnet
ebf18e8493fc730bfef694957a00b7890fc360c8
#include "catch.hpp" #include "util/test_file.hpp" #include "impl/realm_coordinator.hpp" #include "object_schema.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <realm/link_view.hpp> using namespace realm; TEST_CASE("Results") { InMemoryTestFile config; config.cache = false; config.automatic_change_notifications = false; config.schema = std::make_unique<Schema>(Schema{ {"object", "", { {"value", PropertyTypeInt}, {"link", PropertyTypeObject, "linked to object", false, false, true} }}, {"other object", "", { {"value", PropertyTypeInt} }}, {"linking object", "", { {"link", PropertyTypeObject, "object", false, false, true} }}, {"linked to object", "", { {"value", PropertyTypeInt} }} }); auto r = Realm::get_shared_realm(config); auto coordinator = _impl::RealmCoordinator::get_existing_coordinator(config.path); auto table = r->read_group()->get_table("class_object"); r->begin_transaction(); table->add_empty_row(10); for (int i = 0; i < 10; ++i) table->set_int(0, i, i); r->commit_transaction(); Results results(r, *config.schema->find("object"), table->where().greater(0, 0).less(0, 5)); SECTION("notifications") { int notification_calls = 0; auto token = results.async([&](std::exception_ptr err) { REQUIRE_FALSE(err); ++notification_calls; }); coordinator->on_change(); r->notify(); SECTION("initial results are delivered") { REQUIRE(notification_calls == 1); } SECTION("modifying the table sends a notification asynchronously") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a linked-to table send a notification") { r->begin_transaction(); r->read_group()->get_table("class_linked to object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a a linking table sends a notification") { r->begin_transaction(); r->read_group()->get_table("class_linking object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a an unrelated table does not send a notification") { r->begin_transaction(); r->read_group()->get_table("class_other object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 1); } SECTION("modifications from multiple transactions are collapsed") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); r->begin_transaction(); table->set_int(0, 1, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("notifications are not delivered when the token is destroyed before they are calculated") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); token = {}; coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 1); } SECTION("notifications are not delivered when the token is destroyed before they are delivered") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); token = {}; r->notify(); REQUIRE(notification_calls == 1); } } }
#include "catch.hpp" #include "util/test_file.hpp" #include "impl/realm_coordinator.hpp" #include "object_schema.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include <realm/commit_log.hpp> #include <realm/group_shared.hpp> #include <realm/link_view.hpp> using namespace realm; TEST_CASE("Results") { InMemoryTestFile config; config.cache = false; config.automatic_change_notifications = false; config.schema = std::make_unique<Schema>(Schema{ {"object", "", { {"value", PropertyTypeInt}, {"link", PropertyTypeObject, "linked to object", false, false, true} }}, {"other object", "", { {"value", PropertyTypeInt} }}, {"linking object", "", { {"link", PropertyTypeObject, "object", false, false, true} }}, {"linked to object", "", { {"value", PropertyTypeInt} }} }); auto r = Realm::get_shared_realm(config); auto coordinator = _impl::RealmCoordinator::get_existing_coordinator(config.path); auto table = r->read_group()->get_table("class_object"); r->begin_transaction(); table->add_empty_row(10); for (int i = 0; i < 10; ++i) table->set_int(0, i, i); r->commit_transaction(); Results results(r, *config.schema->find("object"), table->where().greater(0, 0).less(0, 5)); SECTION("notifications") { int notification_calls = 0; auto token = results.async([&](std::exception_ptr err) { REQUIRE_FALSE(err); ++notification_calls; }); coordinator->on_change(); r->notify(); SECTION("initial results are delivered") { REQUIRE(notification_calls == 1); } SECTION("modifying the table sends a notification asynchronously") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a linked-to table send a notification") { r->begin_transaction(); r->read_group()->get_table("class_linked to object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a a linking table sends a notification") { r->begin_transaction();
(); REQUIRE(notification_calls == 1); } SECTION("modifications from multiple transactions are collapsed") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); r->begin_transaction(); table->set_int(0, 1, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("notifications are not delivered when the token is destroyed before they are calculated") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); token = {}; coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 1); } SECTION("notifications are not delivered when the token is destroyed before they are delivered") { r->begin_transaction(); table->set_int(0, 0, 0); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); token = {}; r->notify(); REQUIRE(notification_calls == 1); } } }
r->read_group()->get_table("class_linking object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify(); REQUIRE(notification_calls == 2); } SECTION("modifying a an unrelated table does not send a notification") { r->begin_transaction(); r->read_group()->get_table("class_other object")->add_empty_row(); r->commit_transaction(); REQUIRE(notification_calls == 1); coordinator->on_change(); r->notify
random
[ { "content": "struct ValueGetter<Int, TableGetter> {\n\n static Int convert(TableGetter&&, const parser::Expression & value, Arguments &args)\n\n {\n\n if (value.type == parser::Expression::Type::Argument) {\n\n return args.long_for_argument(stot<int>(value.s));\n\n }\n\n r...
C++
dev/Code/Tools/RC/ResourceCompilerPC/CGA/ControllerPQ.cpp
crazyskateface/lumberyard
164512f8d415d6bdf37e195af319ffe5f96a8f0b
#include "stdafx.h" #include "AnimationLoader.h" #include "AnimationManager.h" #include "Wavelets/Compression.h" #include <float.h> namespace ControllerHelper { uint32 GetPositionsFormatSizeOf(uint32 format) { switch (format) { case eNoCompress: case eNoCompressVec3: { return sizeof (NoCompressVec3); } } return 0; } uint32 GetRotationFormatSizeOf(uint32 format) { switch (format) { case eNoCompress: case eNoCompressQuat: return sizeof(NoCompressQuat); case eSmallTree48BitQuat: return sizeof(SmallTree48BitQuat); case eSmallTree64BitQuat: return sizeof(SmallTree64BitQuat); case eSmallTree64BitExtQuat: return sizeof(SmallTree64BitExtQuat); } return 0; } uint32 GetKeyTimesFormatSizeOf(uint32 format) { switch (format) { case eF32: return sizeof(float); case eUINT16: return sizeof(uint16); case eByte: return sizeof(uint8); case eF32StartStop: return sizeof(float); case eUINT16StartStop: return sizeof(uint16); case eByteStartStop: return sizeof(uint8); case eBitset: return sizeof(uint16); } return 0; } ITrackPositionStorage* GetPositionControllerPtr(ECompressionFormat format) { switch (format) { case eNoCompress: case eNoCompressVec3: { return new NoCompressPosition; } } return 0; } ITrackRotationStorage* GetRotationControllerPtr(ECompressionFormat format) { switch (format) { case eNoCompress: case eNoCompressQuat: return new NoCompressRotation; case eSmallTree48BitQuat: return new SmallTree48BitQuatRotation; case eSmallTree64BitQuat: return new SmallTree64BitQuatRotation; case eSmallTree64BitExtQuat: return new SmallTree64BitExtQuatRotation; } return 0; } IKeyTimesInformation* GetKeyTimesControllerPtr(uint32 format) { switch (format) { case eF32: return new F32KeyTimesInformation; case eUINT16: return new UINT16KeyTimesInformation; case eByte: return new ByteKeyTimesInformation; case eBitset: return new CKeyTimesInformationBitSet; } return 0; } const uint8 m_byteLowBit[byteArraySize] _ALIGN(16) = { 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 }; const uint8 m_byteHighBit[byteArraySize] _ALIGN(16) = { 16, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; }; uint8 CKeyTimesInformationBitSet::m_bTable[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };
#include "stdafx.h" #include "AnimationLoader.h" #include "AnimationManager.h" #include "Wavelets/Compression.h" #include <float.h> namespace ControllerHelper { uint32 GetPositionsFormatSizeOf(uint32 format) { switch (format) { case eNoCompress: case eNoCompressVec3: { return sizeof (NoCompressVec3); } } return 0; } uint32 GetRotationFormatSizeOf(uint32 format) { switch (format) { case eNoCompress: case eNoCompressQuat: return sizeof(NoCompressQuat); case eSmallTree48BitQuat: return sizeof(SmallTree48BitQuat); case eSmallTree64BitQuat: return sizeof(SmallTree64BitQuat); case eSmallTree64BitExtQuat: return sizeof(SmallTree64BitExtQuat); } return 0; } uint32 GetKeyTimesFormatSizeOf(uint32 format) { switc
ation; case eByte: return new ByteKeyTimesInformation; case eBitset: return new CKeyTimesInformationBitSet; } return 0; } const uint8 m_byteLowBit[byteArraySize] _ALIGN(16) = { 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 }; const uint8 m_byteHighBit[byteArraySize] _ALIGN(16) = { 16, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; }; uint8 CKeyTimesInformationBitSet::m_bTable[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };
h (format) { case eF32: return sizeof(float); case eUINT16: return sizeof(uint16); case eByte: return sizeof(uint8); case eF32StartStop: return sizeof(float); case eUINT16StartStop: return sizeof(uint16); case eByteStartStop: return sizeof(uint8); case eBitset: return sizeof(uint16); } return 0; } ITrackPositionStorage* GetPositionControllerPtr(ECompressionFormat format) { switch (format) { case eNoCompress: case eNoCompressVec3: { return new NoCompressPosition; } } return 0; } ITrackRotationStorage* GetRotationControllerPtr(ECompressionFormat format) { switch (format) { case eNoCompress: case eNoCompressQuat: return new NoCompressRotation; case eSmallTree48BitQuat: return new SmallTree48BitQuatRotation; case eSmallTree64BitQuat: return new SmallTree64BitQuatRotation; case eSmallTree64BitExtQuat: return new SmallTree64BitExtQuatRotation; } return 0; } IKeyTimesInformation* GetKeyTimesControllerPtr(uint32 format) { switch (format) { case eF32: return new F32KeyTimesInformation; case eUINT16: return new UINT16KeyTimesInform
random
[]
C++
qtmultimedia/src/plugins/gstreamer/camerabin/camerabinrecorder.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
#include "camerabinrecorder.h" #include "camerabincontrol.h" #include "camerabinresourcepolicy.h" #include "camerabinaudioencoder.h" #include "camerabinvideoencoder.h" #include "camerabincontainer.h" #include <QtCore/QDebug> QT_BEGIN_NAMESPACE CameraBinRecorder::CameraBinRecorder(CameraBinSession *session) :QMediaRecorderControl(session), m_session(session), m_state(QMediaRecorder::StoppedState), m_status(QMediaRecorder::UnloadedStatus) { connect(m_session, SIGNAL(statusChanged(QCamera::Status)), SLOT(updateStatus())); connect(m_session, SIGNAL(pendingStateChanged(QCamera::State)), SLOT(updateStatus())); connect(m_session, SIGNAL(busyChanged(bool)), SLOT(updateStatus())); connect(m_session, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64))); connect(m_session, SIGNAL(mutedChanged(bool)), this, SIGNAL(mutedChanged(bool))); connect(m_session->cameraControl()->resourcePolicy(), SIGNAL(canCaptureChanged()), this, SLOT(updateStatus())); } CameraBinRecorder::~CameraBinRecorder() { } QUrl CameraBinRecorder::outputLocation() const { return m_session->outputLocation(); } bool CameraBinRecorder::setOutputLocation(const QUrl &sink) { m_session->setOutputLocation(sink); return true; } QMediaRecorder::State CameraBinRecorder::state() const { return m_state; } QMediaRecorder::Status CameraBinRecorder::status() const { return m_status; } void CameraBinRecorder::updateStatus() { QCamera::Status sessionStatus = m_session->status(); QMediaRecorder::State oldState = m_state; QMediaRecorder::Status oldStatus = m_status; if (sessionStatus == QCamera::ActiveStatus && m_session->captureMode().testFlag(QCamera::CaptureVideo)) { if (!m_session->cameraControl()->resourcePolicy()->canCapture()) { m_status = QMediaRecorder::UnavailableStatus; m_state = QMediaRecorder::StoppedState; m_session->stopVideoRecording(); } else if (m_state == QMediaRecorder::RecordingState) { m_status = QMediaRecorder::RecordingStatus; } else { m_status = m_session->isBusy() ? QMediaRecorder::FinalizingStatus : QMediaRecorder::LoadedStatus; } } else { if (m_state == QMediaRecorder::RecordingState) { m_state = QMediaRecorder::StoppedState; m_session->stopVideoRecording(); } m_status = m_session->pendingState() == QCamera::ActiveState && m_session->captureMode().testFlag(QCamera::CaptureVideo) ? QMediaRecorder::LoadingStatus : QMediaRecorder::UnloadedStatus; } if (m_state != oldState) emit stateChanged(m_state); if (m_status != oldStatus) emit statusChanged(m_status); } qint64 CameraBinRecorder::duration() const { return m_session->duration(); } void CameraBinRecorder::applySettings() { #ifdef HAVE_GST_ENCODING_PROFILES CameraBinContainer *containerControl = m_session->mediaContainerControl(); CameraBinAudioEncoder *audioEncoderControl = m_session->audioEncodeControl(); CameraBinVideoEncoder *videoEncoderControl = m_session->videoEncodeControl(); containerControl->resetActualContainerFormat(); audioEncoderControl->resetActualSettings(); videoEncoderControl->resetActualSettings(); if (containerControl->containerFormat().isEmpty() && audioEncoderControl->audioSettings().codec().isEmpty() && videoEncoderControl->videoSettings().codec().isEmpty()) { QList<QStringList> candidates; candidates.append(QStringList() << "video/x-matroska" << "video/x-h264" << "audio/mpeg, mpegversion=(int)4"); candidates.append(QStringList() << "video/webm" << "video/x-vp8" << "audio/x-vorbis"); candidates.append(QStringList() << "application/ogg" << "video/x-theora" << "audio/x-vorbis"); candidates.append(QStringList() << "video/quicktime" << "video/x-h264" << "audio/mpeg, mpegversion=(int)4"); candidates.append(QStringList() << "video/quicktime" << "video/x-h264" << "audio/mpeg"); candidates.append(QStringList() << "video/x-msvideo" << "video/x-divx" << "audio/mpeg"); foreach (const QStringList &candidate, candidates) { if (containerControl->supportedContainers().contains(candidate[0]) && videoEncoderControl->supportedVideoCodecs().contains(candidate[1]) && audioEncoderControl->supportedAudioCodecs().contains(candidate[2])) { containerControl->setActualContainerFormat(candidate[0]); QVideoEncoderSettings videoSettings = videoEncoderControl->videoSettings(); videoSettings.setCodec(candidate[1]); videoEncoderControl->setActualVideoSettings(videoSettings); QAudioEncoderSettings audioSettings = audioEncoderControl->audioSettings(); audioSettings.setCodec(candidate[2]); audioEncoderControl->setActualAudioSettings(audioSettings); break; } } } #endif } #ifdef HAVE_GST_ENCODING_PROFILES GstEncodingContainerProfile *CameraBinRecorder::videoProfile() { GstEncodingContainerProfile *containerProfile = m_session->mediaContainerControl()->createProfile(); if (containerProfile) { GstEncodingProfile *audioProfile = m_session->audioEncodeControl()->createProfile(); GstEncodingProfile *videoProfile = m_session->videoEncodeControl()->createProfile(); if (audioProfile) { if (!gst_encoding_container_profile_add_profile(containerProfile, audioProfile)) gst_encoding_profile_unref(audioProfile); } if (videoProfile) { if (!gst_encoding_container_profile_add_profile(containerProfile, videoProfile)) gst_encoding_profile_unref(videoProfile); } } return containerProfile; } #endif void CameraBinRecorder::setState(QMediaRecorder::State state) { if (m_state == state) return; QMediaRecorder::State oldState = m_state; QMediaRecorder::Status oldStatus = m_status; switch (state) { case QMediaRecorder::StoppedState: m_state = state; m_status = QMediaRecorder::FinalizingStatus; m_session->stopVideoRecording(); break; case QMediaRecorder::PausedState: emit error(QMediaRecorder::ResourceError, tr("QMediaRecorder::pause() is not supported by camerabin2.")); break; case QMediaRecorder::RecordingState: if (m_session->status() != QCamera::ActiveStatus) { emit error(QMediaRecorder::ResourceError, tr("Service has not been started")); } else if (!m_session->cameraControl()->resourcePolicy()->canCapture()) { emit error(QMediaRecorder::ResourceError, tr("Recording permissions are not available")); } else { m_session->recordVideo(); m_state = state; m_status = QMediaRecorder::RecordingStatus; emit actualLocationChanged(m_session->outputLocation()); } } if (m_state != oldState) emit stateChanged(m_state); if (m_status != oldStatus) emit statusChanged(m_status); } bool CameraBinRecorder::isMuted() const { return m_session->isMuted(); } qreal CameraBinRecorder::volume() const { return 1.0; } void CameraBinRecorder::setMuted(bool muted) { m_session->setMuted(muted); } void CameraBinRecorder::setVolume(qreal volume) { if (!qFuzzyCompare(volume, qreal(1.0))) qWarning() << "Media service doesn't support recorder audio gain."; } QT_END_NAMESPACE
#include "camerabinrecorder.h" #include "camerabincontrol.h" #include "camerabinresourcepolicy.h" #include "camerabinaudioencoder.h" #include "camerabinvideoencoder.h" #include "camerabincontainer.h" #include <QtCore/QDebug> QT_BEGIN_NAMESPACE CameraBinRecorder::CameraBinRecorder(CameraBinSession *session) :QMediaRecorderControl(session), m_session(session), m_state(QMediaRecorder::StoppedState), m_status(QMediaRecorder::UnloadedStatus) { connect(m_session, SIGNAL(statusChanged(QCamera::Status)), SLOT(updateStatus())); connect(m_session, SIGNAL(pendingStateChanged(QCamera::State)), SLOT(updateStatus())); connect(m_session, SIGNAL(busyChanged(bool)), SLOT(updateStatus())); connect(m_session, SIGNAL(durationChanged(qint64)), SIGNAL(durationChanged(qint64))); connect(m_session, SIGNAL(mutedChanged(bool)), this, SIGNAL(mutedChanged(bool))); connect(m_session->cameraControl()->resourcePolicy(), SIGNAL(canCaptureChanged()), this, SLOT(updateStatus())); } CameraBinRecorder::~CameraBinRecorder() { } QUrl CameraBinRecorder::outputLocation() const { return m_session->outputLocation(); } bool CameraBinRecorder::setOutputLocation(const QUrl &sink) { m_session->setOutputLocation(sink); return true; } QMediaRecorder::State CameraBinRecorder::state() const { return m_state; } QMediaRecorder::Status CameraBinRecorder::status() const { return m_status; } void CameraBinRecorder::updateStatus() { QCamera::Status sessionStatus = m_session->status(); QMediaRecorder::State oldState = m_state; QMediaRecorder::Status oldStatus = m_status; if (sessionStatus == QCamera::ActiveStatus && m_session->captureMode().testFlag(QCamera::CaptureVideo)) { if (!m_session->cameraControl()->resourcePolicy()->canCapture()) { m_status = QMediaRecorder::UnavailableStatus; m_state = QMediaRecorder::StoppedState; m_session->stopVideoRecording(); } else if (m_state == QMediaRecorder::RecordingState) { m_status = QMediaRecorder::RecordingStatus; } else { m_status = m_session->isBusy() ? QMediaRecorder::FinalizingStatus : QMediaRecorder::LoadedStatus; } } else { if (m_state == QMediaRecorder::RecordingState) { m_state = QMediaRecorder::StoppedState; m_session->stopVideoRecording(); } m_status = m_session->pendingState() == QCamera::ActiveState && m_session->captureMode().testFlag(QCamera::CaptureVideo) ? QMediaRecorder::LoadingStatus : QMediaRecorder::UnloadedStatus; } if (m_state != oldState) emit stateChanged(m_state); if (m_status != oldStatus) emit statusChanged(m_status); } qint64 CameraBinRecorder::duration() const { return m_session->duration(); } void CameraBinRecorder::applySettings() { #ifdef HAVE_GST_ENCODING_PROFILES CameraBinContainer *containerControl = m_session->mediaContainerControl(); CameraBinAudioEncoder *audioEncoderControl = m_session->audioEncodeControl(); CameraBinVideoEncoder *videoEncoderControl = m_session->videoEncodeControl(); containerControl->resetActualContainerFormat(); audioEncoderControl->resetActualSettings(); videoEncoderControl->resetActualSettings(); if (containerControl->containerFormat().isEmpty() && audioEncoderControl->audioSettings().codec().isEmpty() && videoEncoderControl->videoSettings().codec().isEmpty()) { QList<QStringList> candidates; candidates.append(QStringList() << "video/x-matroska" << "video/x-h264" << "audio/mpeg, mpegversion=(int)4"); candidates.append(QStringList() << "video/webm" << "video/x-vp8" << "audio/x-vorbis"); candidates.append(QStringList() << "application/ogg" << "video/x-theora" << "audio/x-vorbis"); candidates.append(QStringList() << "video/quicktime" << "video/x-h264" << "audio/mpeg, mpegversion=(int)4"); candidates.append(QStringList() << "video/quicktime" << "video/x-h264" << "audio/mpeg"); candidates.append(QStringList() << "video/x-msvideo" << "video/x-divx" << "audio/mpeg"); foreach (const QStringList &candidate, candidates) { if (containerControl->supportedContainers().contains(candidate[0]) && videoEncoderControl->supportedVideoCodecs().contains(candidate[1]) && audioEncoderControl->supportedAudioCodecs().contains(candidate[2])) { containerControl->setActualContainerFormat(candidate[0]); QVideoEncoderSettings videoSettings = videoEncoderControl->videoSettings(); videoSettings.setCodec(candidate[1]); videoEncoderControl->setActualVideoSettings(videoSettings); QAudioEncoderSettings audioSettings = audioEncoderControl->audioSettings(); audioSettings.setCodec(candidate[2]); audioEncoderControl->setActualAudioSettings(audioSettings); break; } } } #endif } #ifdef HAVE_GST_ENCODING_PROFILES GstEncodingContainerProfile *CameraBinRecorder::videoProfile() { GstEncodingContainerProfile *containerProfile = m_session->mediaContainerControl()->createProfile(); if (containerProfile) { GstEncodingProfile *audioProfile = m_session->audioEncodeControl()->createProfile(); GstEncodingProfile *videoProfile = m_session->videoEncodeControl()->createProfile(); if (audioProfile) { if (!gst_encoding_container_profile_add_profile(containerProfile, audioProfile)) gst_encoding_profile_unref(audioProfile); } if (videoProfile) { if (!gst_encoding_container_profile_add_profile(containerProfile, videoProfile)) gst_encoding_profile_unref(videoProfile); } } return containerProfile; } #endif void CameraBinRecorder::setState(QMediaRecorder::State state) { if (m_state == state) return; QMediaRecorder::State oldState = m_state; QMediaRecorder::Status oldStatus = m_status; switch (state) { case QMediaRecorder::StoppedState: m_state = state; m_status = QMediaRecorder::FinalizingStatus; m_session->stopVideoRecording(); break; case QMediaRecorder::PausedState: emit error(QMediaRecorder::ResourceError, tr("QMediaRecorder::pause() is not supported by camerabin2.")); break; case QMediaRecorder::RecordingState:
} if (m_state != oldState) emit stateChanged(m_state); if (m_status != oldStatus) emit statusChanged(m_status); } bool CameraBinRecorder::isMuted() const { return m_session->isMuted(); } qreal CameraBinRecorder::volume() const { return 1.0; } void CameraBinRecorder::setMuted(bool muted) { m_session->setMuted(muted); } void CameraBinRecorder::setVolume(qreal volume) { if (!qFuzzyCompare(volume, qreal(1.0))) qWarning() << "Media service doesn't support recorder audio gain."; } QT_END_NAMESPACE
if (m_session->status() != QCamera::ActiveStatus) { emit error(QMediaRecorder::ResourceError, tr("Service has not been started")); } else if (!m_session->cameraControl()->resourcePolicy()->canCapture()) { emit error(QMediaRecorder::ResourceError, tr("Recording permissions are not available")); } else { m_session->recordVideo(); m_state = state; m_status = QMediaRecorder::RecordingStatus; emit actualLocationChanged(m_session->outputLocation()); }
if_condition
[]
C++
camera/hal/test/v4l2/src/pipeline_test.cpp
openharmony-gitee-mirror/drivers_peripheral
4ee6d41befdf54a97afeb5838be5fcd0b4888d56
#include "pipeline_test.h" void UtestPipelineTest::SetUpTestCase(void) {} void UtestPipelineTest::TearDownTestCase(void) {} void UtestPipelineTest::SetUp(void) { if (display_ == nullptr) display_ = std::make_shared<TestDisplay>(); display_->FBInit(); display_->Init(); } void UtestPipelineTest::TearDown(void) { display_->Close(); } TEST_F(UtestPipelineTest, camera_ppl_0001) { std::cout << "==========[test log] Check ppl: preview success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->captureIds = {display_->captureId_preview}; display_->streamIds = {display_->streamId_preview}; display_->StopStream(display_->captureIds, display_->streamIds); } TEST_F(UtestPipelineTest, camera_ppl_0002) { std::cout << "==========[test log] Check ppl: preview + capture success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW, Camera::STILL_CAPTURE}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->StartCapture(display_->streamId_capture, display_->captureId_capture, false, true); display_->captureIds = {display_->captureId_preview, display_->captureId_capture}; display_->streamIds = {display_->streamId_preview, display_->streamId_capture}; display_->StopStream(display_->captureIds, display_->streamIds); } TEST_F(UtestPipelineTest, camera_ppl_0003) { std::cout << "==========[test log] Check ppl: preview + video success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW, Camera::VIDEO}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->StartCapture(display_->streamId_video, display_->captureId_video, false, true); display_->captureIds = {display_->captureId_preview, display_->captureId_video}; display_->streamIds = {display_->streamId_preview, display_->streamId_video}; display_->StopStream(display_->captureIds, display_->streamIds); } TEST_F(UtestPipelineTest, camera_ppl_0004) { std::cout << "==========[test log] Video mode without preview, system not support, "; std::cout << "expected return fail." << std::endl; EXPECT_EQ(true, display_->cameraDevice != nullptr); display_->AchieveStreamOperator(); std::vector<std::shared_ptr<StreamInfo>> streamInfos; std::shared_ptr<IBufferProducer> producer = IBufferProducer::CreateBufferQueue(); producer->SetQueueSize(8); if (producer->GetQueueSize() != 8) { std::cout << "~~~~~~~" << std::endl; } auto callback = [this](std::shared_ptr<SurfaceBuffer> b) { display_->BufferCallback(b, display_->video_mode); return; }; producer->SetCallback(callback); display_->streamInfo = std::make_shared<OHOS::Camera::StreamInfo>(); display_->streamInfo->streamId_ = display_->streamId_video; display_->streamInfo->width_ = 640; display_->streamInfo->height_ = 480; display_->streamInfo->format_ = CAMERA_FORMAT_YUYV_422_PKG; display_->streamInfo->datasapce_ = 10; display_->streamInfo->intent_ = Camera::VIDEO; display_->streamInfo->tunneledMode_ = 5; display_->streamInfo->bufferQueue_ = producer; std::vector<std::shared_ptr<OHOS::Camera::StreamInfo>>().swap(streamInfos); streamInfos.push_back(display_->streamInfo); display_->rc = display_->streamOperator->CreateStreams(streamInfos); EXPECT_EQ(false, display_->rc == Camera::METHOD_NOT_SUPPORTED); if (display_->rc == Camera::METHOD_NOT_SUPPORTED) { std::cout << "==========[test log] CreateStreams METHOD_NOT_SUPPORTED, streamId = "; std::cout << display_->streamId_video <<", intent = Camera::VIDEO" << std::endl; } else { std::cout << "==========[test log] CreateStreams fail, rc = " << display_->rc << std::endl; } display_->rc = display_->streamOperator->CommitStreams(Camera::NORMAL, nullptr); EXPECT_EQ(false, display_->rc == Camera::NO_ERROR); if (display_->rc == Camera::NO_ERROR) { std::cout << "==========[test log] CommitStreams success." << std::endl; } else { std::cout << "==========[test log] CommitStreams fail, rc = ." << display_->rc << std::endl; } }
#include "pipeline_test.h" void UtestPipelineTest::SetUpTestCase(void) {} void UtestPipelineTest::TearDownTestCase(void) {} void UtestPipelineTest::SetUp(void) { if (display_ == nullptr) display_ = std::make_shared<TestDisplay>(); display_->FBInit(); display_->Init(); } void UtestPipelineTest::TearDown(void) { display_->Close(); }
TEST_F(UtestPipelineTest, camera_ppl_0002) { std::cout << "==========[test log] Check ppl: preview + capture success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW, Camera::STILL_CAPTURE}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->StartCapture(display_->streamId_capture, display_->captureId_capture, false, true); display_->captureIds = {display_->captureId_preview, display_->captureId_capture}; display_->streamIds = {display_->streamId_preview, display_->streamId_capture}; display_->StopStream(display_->captureIds, display_->streamIds); } TEST_F(UtestPipelineTest, camera_ppl_0003) { std::cout << "==========[test log] Check ppl: preview + video success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW, Camera::VIDEO}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->StartCapture(display_->streamId_video, display_->captureId_video, false, true); display_->captureIds = {display_->captureId_preview, display_->captureId_video}; display_->streamIds = {display_->streamId_preview, display_->streamId_video}; display_->StopStream(display_->captureIds, display_->streamIds); } TEST_F(UtestPipelineTest, camera_ppl_0004) { std::cout << "==========[test log] Video mode without preview, system not support, "; std::cout << "expected return fail." << std::endl; EXPECT_EQ(true, display_->cameraDevice != nullptr); display_->AchieveStreamOperator(); std::vector<std::shared_ptr<StreamInfo>> streamInfos; std::shared_ptr<IBufferProducer> producer = IBufferProducer::CreateBufferQueue(); producer->SetQueueSize(8); if (producer->GetQueueSize() != 8) { std::cout << "~~~~~~~" << std::endl; } auto callback = [this](std::shared_ptr<SurfaceBuffer> b) { display_->BufferCallback(b, display_->video_mode); return; }; producer->SetCallback(callback); display_->streamInfo = std::make_shared<OHOS::Camera::StreamInfo>(); display_->streamInfo->streamId_ = display_->streamId_video; display_->streamInfo->width_ = 640; display_->streamInfo->height_ = 480; display_->streamInfo->format_ = CAMERA_FORMAT_YUYV_422_PKG; display_->streamInfo->datasapce_ = 10; display_->streamInfo->intent_ = Camera::VIDEO; display_->streamInfo->tunneledMode_ = 5; display_->streamInfo->bufferQueue_ = producer; std::vector<std::shared_ptr<OHOS::Camera::StreamInfo>>().swap(streamInfos); streamInfos.push_back(display_->streamInfo); display_->rc = display_->streamOperator->CreateStreams(streamInfos); EXPECT_EQ(false, display_->rc == Camera::METHOD_NOT_SUPPORTED); if (display_->rc == Camera::METHOD_NOT_SUPPORTED) { std::cout << "==========[test log] CreateStreams METHOD_NOT_SUPPORTED, streamId = "; std::cout << display_->streamId_video <<", intent = Camera::VIDEO" << std::endl; } else { std::cout << "==========[test log] CreateStreams fail, rc = " << display_->rc << std::endl; } display_->rc = display_->streamOperator->CommitStreams(Camera::NORMAL, nullptr); EXPECT_EQ(false, display_->rc == Camera::NO_ERROR); if (display_->rc == Camera::NO_ERROR) { std::cout << "==========[test log] CommitStreams success." << std::endl; } else { std::cout << "==========[test log] CommitStreams fail, rc = ." << display_->rc << std::endl; } }
TEST_F(UtestPipelineTest, camera_ppl_0001) { std::cout << "==========[test log] Check ppl: preview success." << std::endl; display_->AchieveStreamOperator(); display_->intents = {Camera::PREVIEW}; display_->StartStream(display_->intents); display_->StartCapture(display_->streamId_preview, display_->captureId_preview, false, true); display_->captureIds = {display_->captureId_preview}; display_->streamIds = {display_->streamId_preview}; display_->StopStream(display_->captureIds, display_->streamIds); }
function_block-full_function
[ { "content": "struct IWiFi *g_wifi = nullptr;\n\nconst int32_t WLAN_TX_POWER = 160;\n\nconst uint32_t WLAN_MIN_CHIPID = 0;\n\nconst uint32_t WLAN_MAX_CHIPID = 2;\n\nconst uint32_t IFNAME_MIN_NUM = 0;\n\nconst uint32_t IFNAME_MAX_NUM = 32;\n\nconst uint32_t MAX_IF_NAME_LENGTH = 16;\n\nconst uint32_t SIZE = 4;\n\...
C++
src/type3_AndroidCloud/anbox-master/external/process-cpp-minimal/src/core/posix/child_process.cpp
akraino-edge-stack/iec
b01bce6165ef8368a607e17e1f3d4697b79db31b
#include <core/posix/child_process.h> #ifndef ANDROID #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #endif #include <atomic> #include <fstream> #include <mutex> #include <unordered_map> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <sys/eventfd.h> #include <sys/signalfd.h> #include <assert.h> #include <sys/wait.h> #ifndef ANDROID namespace io = boost::iostreams; #endif namespace { struct DeathObserverImpl : public core::posix::ChildProcess::DeathObserver { DeathObserverImpl(const std::shared_ptr<core::posix::SignalTrap>& trap) : on_sig_child_connection { trap->signal_raised().connect([this](core::posix::Signal signal) { switch (signal) { case core::posix::Signal::sig_chld: on_sig_child(); break; default: break; } }) } { if (!trap->has(core::posix::Signal::sig_chld)) throw std::logic_error( "DeathObserver::DeathObserverImpl: Given SignalTrap" " instance does not trap Signal::sig_chld."); } bool add(const core::posix::ChildProcess& process) override { if (process.pid() == -1) return false; std::lock_guard<std::mutex> lg(guard); bool added = false; auto new_process = std::make_pair(process.pid(), process); std::tie(std::ignore, added) = children.insert(new_process); if (added) { int status{-1}; if (::waitpid(process.pid(), &status, WNOHANG) != 0) { signals.child_died(new_process.second); children.erase(new_process.first); return false; } } return added; } bool has(const core::posix::ChildProcess& process) const override { std::lock_guard<std::mutex> lg(guard); return children.count(process.pid()) > 0; } const core::Signal<core::posix::ChildProcess>& child_died() const override { return signals.child_died; } void on_sig_child() override { pid_t pid{-1}; int status{-1}; while (true) { pid = ::waitpid(0, &status, WNOHANG); if (pid == -1) { if (errno == ECHILD) { break; } continue; } else if (pid == 0) { break; } else { std::lock_guard<std::mutex> lg(guard); auto it = children.find(pid); if (it != children.end()) { if (WIFSIGNALED(status) || WIFEXITED(status)) { signals.child_died(it->second); children.erase(it); } } } } } mutable std::mutex guard; std::unordered_map<pid_t, core::posix::ChildProcess> children; core::ScopedConnection on_sig_child_connection; struct { core::Signal<core::posix::ChildProcess> child_died; } signals; }; } std::unique_ptr<core::posix::ChildProcess::DeathObserver> core::posix::ChildProcess::DeathObserver::create_once_with_signal_trap( std::shared_ptr<core::posix::SignalTrap> trap) { static std::atomic<bool> has_been_created_once{false}; if (has_been_created_once.exchange(true)) throw std::runtime_error { "DeathObserver::create_once_with_signal_trap: " "Cannot create more than one instance." }; try { std::unique_ptr<core::posix::ChildProcess::DeathObserver> result { new DeathObserverImpl{trap} }; return result; } catch(...) { has_been_created_once.store(false); std::rethrow_exception(std::current_exception()); } assert(false && "We should never reach here."); return std::unique_ptr<core::posix::ChildProcess::DeathObserver>{}; } namespace core { namespace posix { ChildProcess::Pipe ChildProcess::Pipe::invalid() { static Pipe p; static std::once_flag flag; std::call_once(flag, [&]() { p.close_read_fd(); p.close_write_fd(); }); return p; } ChildProcess::Pipe::Pipe() { int rc = ::pipe(fds); if (rc == -1) throw std::system_error(errno, std::system_category()); } ChildProcess::Pipe::Pipe(const ChildProcess::Pipe& rhs) : fds{-1, -1} { if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); } ChildProcess::Pipe::~Pipe() { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); } int ChildProcess::Pipe::read_fd() const { return fds[0]; } void ChildProcess::Pipe::close_read_fd() { if (fds[0] != -1) { ::close(fds[0]); fds[0] = -1; } } int ChildProcess::Pipe::write_fd() const { return fds[1]; } void ChildProcess::Pipe::close_write_fd() { if (fds[1] != -1) { ::close(fds[1]); fds[1] = -1; } } ChildProcess::Pipe& ChildProcess::Pipe::operator=(const ChildProcess::Pipe& rhs) { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); else fds[0] = -1; if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); else fds[1] = -1; return *this; } struct ChildProcess::Private { Private(pid_t pid, const ChildProcess::Pipe& stderr, const ChildProcess::Pipe& stdin, const ChildProcess::Pipe& stdout) : pipes{stderr, stdin, stdout}, #ifndef ANDROID serr(pipes.stderr.read_fd(), io::never_close_handle), sin(pipes.stdin.write_fd(), io::never_close_handle), sout(pipes.stdout.read_fd(), io::never_close_handle), cerr(&serr), cin(&sin), cout(&sout), #endif original_parent_pid(::getpid()), original_child_pid(pid) { } ~Private() { if (original_parent_pid == getpid() && !dont_kill_on_cleanup) { if (original_child_pid != -1) ::kill(original_child_pid, SIGKILL); } } struct { ChildProcess::Pipe stdin; ChildProcess::Pipe stdout; ChildProcess::Pipe stderr; } pipes; #ifndef ANDROID io::stream_buffer<io::file_descriptor_source> serr; io::stream_buffer<io::file_descriptor_sink> sin; io::stream_buffer<io::file_descriptor_source> sout; std::istream cerr; std::ostream cin; std::istream cout; #endif pid_t original_parent_pid; pid_t original_child_pid; bool dont_kill_on_cleanup = false; }; ChildProcess ChildProcess::invalid() { static const pid_t invalid_pid = 1; return ChildProcess(invalid_pid, Pipe::invalid(), Pipe::invalid(), Pipe::invalid()); } ChildProcess::ChildProcess(pid_t pid, const ChildProcess::Pipe& stdin_pipe, const ChildProcess::Pipe& stdout_pipe, const ChildProcess::Pipe& stderr_pipe) : Process(pid), d(new Private{pid, stdin_pipe, stdout_pipe, stderr_pipe}) { } ChildProcess::~ChildProcess() { } wait::Result ChildProcess::wait_for(const wait::Flags& flags) { int status = -1; pid_t result_pid = ::waitpid(pid(), std::addressof(status), static_cast<int>(flags)); if (result_pid == -1) throw std::system_error(errno, std::system_category()); wait::Result result; if (result_pid == 0) { result.status = wait::Result::Status::no_state_change; return result; } if (WIFEXITED(status)) { result.status = wait::Result::Status::exited; result.detail.if_exited.status = static_cast<exit::Status>(WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { result.status = wait::Result::Status::signaled; result.detail.if_signaled.signal = static_cast<Signal>(WTERMSIG(status)); result.detail.if_signaled.core_dumped = WCOREDUMP(status); } else if (WIFSTOPPED(status)) { result.status = wait::Result::Status::stopped; result.detail.if_stopped.signal = static_cast<Signal>(WSTOPSIG(status)); } #ifndef ANDROID else if (WIFCONTINUED(status)) { result.status = wait::Result::Status::continued; } #endif return result; } void ChildProcess::dont_kill_on_cleanup() { d->dont_kill_on_cleanup = true; } #ifndef ANDROID std::istream& ChildProcess::cerr() { return d->cerr; } std::ostream& ChildProcess::cin() { return d->cin; } std::istream& ChildProcess::cout() { return d->cout; } #endif } }
#include <core/posix/child_process.h> #ifndef ANDROID #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #endif #include <atomic> #include <fstream> #include <mutex> #include <unordered_map> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <sys/eventfd.h> #include <sys/signalfd.h> #include <assert.h> #include <sys/wait.h> #ifndef ANDROID namespace io = boost::iostreams; #endif namespace { struct DeathObserverImpl : public core::posix::ChildProcess::DeathObserver {
bool add(const core::posix::ChildProcess& process) override { if (process.pid() == -1) return false; std::lock_guard<std::mutex> lg(guard); bool added = false; auto new_process = std::make_pair(process.pid(), process); std::tie(std::ignore, added) = children.insert(new_process); if (added) { int status{-1}; if (::waitpid(process.pid(), &status, WNOHANG) != 0) { signals.child_died(new_process.second); children.erase(new_process.first); return false; } } return added; } bool has(const core::posix::ChildProcess& process) const override { std::lock_guard<std::mutex> lg(guard); return children.count(process.pid()) > 0; } const core::Signal<core::posix::ChildProcess>& child_died() const override { return signals.child_died; } void on_sig_child() override { pid_t pid{-1}; int status{-1}; while (true) { pid = ::waitpid(0, &status, WNOHANG); if (pid == -1) { if (errno == ECHILD) { break; } continue; } else if (pid == 0) { break; } else { std::lock_guard<std::mutex> lg(guard); auto it = children.find(pid); if (it != children.end()) { if (WIFSIGNALED(status) || WIFEXITED(status)) { signals.child_died(it->second); children.erase(it); } } } } } mutable std::mutex guard; std::unordered_map<pid_t, core::posix::ChildProcess> children; core::ScopedConnection on_sig_child_connection; struct { core::Signal<core::posix::ChildProcess> child_died; } signals; }; } std::unique_ptr<core::posix::ChildProcess::DeathObserver> core::posix::ChildProcess::DeathObserver::create_once_with_signal_trap( std::shared_ptr<core::posix::SignalTrap> trap) { static std::atomic<bool> has_been_created_once{false}; if (has_been_created_once.exchange(true)) throw std::runtime_error { "DeathObserver::create_once_with_signal_trap: " "Cannot create more than one instance." }; try { std::unique_ptr<core::posix::ChildProcess::DeathObserver> result { new DeathObserverImpl{trap} }; return result; } catch(...) { has_been_created_once.store(false); std::rethrow_exception(std::current_exception()); } assert(false && "We should never reach here."); return std::unique_ptr<core::posix::ChildProcess::DeathObserver>{}; } namespace core { namespace posix { ChildProcess::Pipe ChildProcess::Pipe::invalid() { static Pipe p; static std::once_flag flag; std::call_once(flag, [&]() { p.close_read_fd(); p.close_write_fd(); }); return p; } ChildProcess::Pipe::Pipe() { int rc = ::pipe(fds); if (rc == -1) throw std::system_error(errno, std::system_category()); } ChildProcess::Pipe::Pipe(const ChildProcess::Pipe& rhs) : fds{-1, -1} { if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); } ChildProcess::Pipe::~Pipe() { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); } int ChildProcess::Pipe::read_fd() const { return fds[0]; } void ChildProcess::Pipe::close_read_fd() { if (fds[0] != -1) { ::close(fds[0]); fds[0] = -1; } } int ChildProcess::Pipe::write_fd() const { return fds[1]; } void ChildProcess::Pipe::close_write_fd() { if (fds[1] != -1) { ::close(fds[1]); fds[1] = -1; } } ChildProcess::Pipe& ChildProcess::Pipe::operator=(const ChildProcess::Pipe& rhs) { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); else fds[0] = -1; if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); else fds[1] = -1; return *this; } struct ChildProcess::Private { Private(pid_t pid, const ChildProcess::Pipe& stderr, const ChildProcess::Pipe& stdin, const ChildProcess::Pipe& stdout) : pipes{stderr, stdin, stdout}, #ifndef ANDROID serr(pipes.stderr.read_fd(), io::never_close_handle), sin(pipes.stdin.write_fd(), io::never_close_handle), sout(pipes.stdout.read_fd(), io::never_close_handle), cerr(&serr), cin(&sin), cout(&sout), #endif original_parent_pid(::getpid()), original_child_pid(pid) { } ~Private() { if (original_parent_pid == getpid() && !dont_kill_on_cleanup) { if (original_child_pid != -1) ::kill(original_child_pid, SIGKILL); } } struct { ChildProcess::Pipe stdin; ChildProcess::Pipe stdout; ChildProcess::Pipe stderr; } pipes; #ifndef ANDROID io::stream_buffer<io::file_descriptor_source> serr; io::stream_buffer<io::file_descriptor_sink> sin; io::stream_buffer<io::file_descriptor_source> sout; std::istream cerr; std::ostream cin; std::istream cout; #endif pid_t original_parent_pid; pid_t original_child_pid; bool dont_kill_on_cleanup = false; }; ChildProcess ChildProcess::invalid() { static const pid_t invalid_pid = 1; return ChildProcess(invalid_pid, Pipe::invalid(), Pipe::invalid(), Pipe::invalid()); } ChildProcess::ChildProcess(pid_t pid, const ChildProcess::Pipe& stdin_pipe, const ChildProcess::Pipe& stdout_pipe, const ChildProcess::Pipe& stderr_pipe) : Process(pid), d(new Private{pid, stdin_pipe, stdout_pipe, stderr_pipe}) { } ChildProcess::~ChildProcess() { } wait::Result ChildProcess::wait_for(const wait::Flags& flags) { int status = -1; pid_t result_pid = ::waitpid(pid(), std::addressof(status), static_cast<int>(flags)); if (result_pid == -1) throw std::system_error(errno, std::system_category()); wait::Result result; if (result_pid == 0) { result.status = wait::Result::Status::no_state_change; return result; } if (WIFEXITED(status)) { result.status = wait::Result::Status::exited; result.detail.if_exited.status = static_cast<exit::Status>(WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { result.status = wait::Result::Status::signaled; result.detail.if_signaled.signal = static_cast<Signal>(WTERMSIG(status)); result.detail.if_signaled.core_dumped = WCOREDUMP(status); } else if (WIFSTOPPED(status)) { result.status = wait::Result::Status::stopped; result.detail.if_stopped.signal = static_cast<Signal>(WSTOPSIG(status)); } #ifndef ANDROID else if (WIFCONTINUED(status)) { result.status = wait::Result::Status::continued; } #endif return result; } void ChildProcess::dont_kill_on_cleanup() { d->dont_kill_on_cleanup = true; } #ifndef ANDROID std::istream& ChildProcess::cerr() { return d->cerr; } std::ostream& ChildProcess::cin() { return d->cin; } std::istream& ChildProcess::cout() { return d->cout; } #endif } }
DeathObserverImpl(const std::shared_ptr<core::posix::SignalTrap>& trap) : on_sig_child_connection { trap->signal_raised().connect([this](core::posix::Signal signal) { switch (signal) { case core::posix::Signal::sig_chld: on_sig_child(); break; default: break; } }) } { if (!trap->has(core::posix::Signal::sig_chld)) throw std::logic_error( "DeathObserver::DeathObserverImpl: Given SignalTrap" " instance does not trap Signal::sig_chld."); }
function_block-full_function
[ { "content": "struct CORE_POSIX_DLL_PUBLIC Stat\n\n{\n\n pid_t pid = 1; ///< The process ID\n\n std::string executable; ///< The filename of the executable, in parentheses.\n\n State state = State::undefined; ///< State of the process.\n\n pid_t parent = -1; ///< The PID of the parent.\n\n pid_t ...
C++
gmsh/Mesh/meshGRegionCarveHole.cpp
Poofee/fastFEM
14eb626df973e2123604041451912c867ab7188c
#include <set> #include "GmshConfig.h" #include "GmshMessage.h" #include "GModel.h" #include "MTriangle.h" #include "MQuadrangle.h" #include "MTetrahedron.h" #include "MHexahedron.h" #include "MPrism.h" #include "MPyramid.h" #if !defined(HAVE_ANN) void carveHole(GRegion *gr, int num, double distance, std::vector<int> &surfaces) { Msg::Error("Gmsh must be compiled with ANN support to carve holes in meshes"); } #else #include "ANN/ANN.h" template <class T> void carveHole(std::vector<T *> &elements, double distance, ANNkd_tree *kdtree) { ANNidxArray index = new ANNidx[1]; ANNdistArray dist = new ANNdist[1]; std::vector<T *> temp; for(std::size_t i = 0; i < elements.size(); i++) { for(std::size_t j = 0; j < elements[i]->getNumVertices(); j++) { MVertex *v = elements[i]->getVertex(j); double xyz[3] = {v->x(), v->y(), v->z()}; kdtree->annkSearch(xyz, 1, index, dist); double d = std::sqrt(dist[0]); if(d < distance) { delete elements[i]; break; } else if(j == elements[i]->getNumVertices() - 1) { temp.push_back(elements[i]); } } } elements = temp; delete[] index; delete[] dist; } template <class T> void addFaces(std::vector<T *> &elements, std::set<MFace, Less_Face> &faces) { for(std::size_t i = 0; i < elements.size(); i++) { for(int j = 0; j < elements[i]->getNumFaces(); j++) { MFace f = elements[i]->getFace(j); std::set<MFace, Less_Face>::iterator it = faces.find(f); if(it == faces.end()) faces.insert(f); else faces.erase(it); } } } void carveHole(GRegion *gr, int num, double distance, std::vector<int> &surfaces) { Msg::Info("Carving hole %d from surface %d at distance %g", num, surfaces[0], distance); GModel *m = gr->model(); int numnodes = 0; for(std::size_t i = 0; i < surfaces.size(); i++) { GFace *gf = m->getFaceByTag(surfaces[i]); if(!gf) { Msg::Error("Unknown carving surface %d", surfaces[i]); return; } numnodes += gf->mesh_vertices.size(); } ANNpointArray kdnodes = annAllocPts(numnodes, 3); int k = 0; for(std::size_t i = 0; i < surfaces.size(); i++) { GFace *gf = m->getFaceByTag(surfaces[i]); for(std::size_t j = 0; j < gf->mesh_vertices.size(); j++) { kdnodes[k][0] = gf->mesh_vertices[j]->x(); kdnodes[k][1] = gf->mesh_vertices[j]->y(); kdnodes[k][2] = gf->mesh_vertices[j]->z(); k++; } } ANNkd_tree *kdtree = new ANNkd_tree(kdnodes, numnodes, 3); carveHole(gr->tetrahedra, distance, kdtree); carveHole(gr->hexahedra, distance, kdtree); carveHole(gr->prisms, distance, kdtree); carveHole(gr->pyramids, distance, kdtree); delete kdtree; annDeallocPts(kdnodes); GFace *gf = m->getFaceByTag(num); if(!gf) return; std::set<MFace, Less_Face> faces; std::vector<GFace *> f = gr->faces(); for(std::vector<GFace *>::iterator it = f.begin(); it != f.end(); it++) { addFaces((*it)->triangles, faces); addFaces((*it)->quadrangles, faces); } addFaces(gr->tetrahedra, faces); addFaces(gr->hexahedra, faces); addFaces(gr->prisms, faces); addFaces(gr->pyramids, faces); std::set<MVertex *> verts; for(std::set<MFace, Less_Face>::iterator it = faces.begin(); it != faces.end(); it++) { for(std::size_t i = 0; i < it->getNumVertices(); i++) { it->getVertex(i)->setEntity(gf); verts.insert(it->getVertex(i)); } if(it->getNumVertices() == 3) gf->triangles.push_back( new MTriangle(it->getVertex(0), it->getVertex(1), it->getVertex(2))); else if(it->getNumVertices() == 4) gf->quadrangles.push_back( new MQuadrangle(it->getVertex(0), it->getVertex(1), it->getVertex(2), it->getVertex(3))); } } #endif
#include <set> #include "GmshConfig.h" #include "GmshMessage.h" #include "GModel.h" #include "MTriangle.h" #include "MQuadrangle.h" #include "MTetrahedron.h" #include "MHexahedron.h" #include "MPrism.h" #include "MPyramid.h" #if !defined(HAVE_ANN) void carveHole(GRegion *gr, int num, double distance, std::vector<int> &surfaces) { Msg::Error("Gmsh must be compiled with ANN support to carve holes in meshes"); } #else #include "ANN/ANN.h" template <class T> void carveHole(std::vector<T *> &elements, double distance, ANNkd_tree *kdtree) { ANNidxArray index = new ANNidx[1]; ANNdistArray dist = new ANNdist[1]; std::vector<T *> temp; for(std::size_t i = 0; i < elements.size(); i++) { for(std::size_t j = 0; j < elements[i]->getNumVertices(); j++) { MVertex *v = elements[i]->getVertex(j); double xyz[3] = {v->x(), v->y(), v->z()}; kdtree->annkSearch(xyz, 1, index, dist); double d = std::sqrt(dist[0]); if(d < distance) { delete elements[i]; break; } else if(j == elements[i]->getNumVertices() - 1) { temp.push_back(elements[i]); } } } elements = temp; delete[] index; delete[] dist; } template <class T> void addFaces(std::vector<T *> &elements, std::set<MFace, Less_Face> &faces) { for(std::size_t i = 0; i < elements.size(); i++) { for(int j = 0; j < elements[i]->getNumFaces(); j++) { MFace f = elements[i]->getFace(j); std::set<MFace, Less_Face>::iterator it = faces.find(f); if(it == faces.end()) faces.insert(f); else faces.erase(it); } } } void carveHole(GRegion *gr, int num, double distance, std::vector<int> &surfaces) { Msg::Info("Carving hole %d from surface %d at distance %g", num, surfaces[0], distance); GModel *m = gr->model(); int numnodes = 0; for(std::size_t i = 0; i < surfaces.size(); i++) { GFace *gf = m->getFaceByTag(surfaces[i]); if(!gf) { Msg::Error("Unknown carving surface %d", surfaces[i]); return; } numnodes += gf->mesh_vertices.size(); } ANNpointArray kdnodes = annAllocPts(numnodes, 3); int k = 0; for(std::size_t i = 0; i < surfaces.size(); i++) { GFace *gf = m->getFaceByTag(surfaces[i]); for(std::size_t j = 0; j < gf->mesh_vertices.size(); j++) { kdnodes[k][0] = gf->mesh_vertices[j]->x(); kdnodes[k][1] = gf->mesh_vertices[j]->y(); kdnodes[k][2] = gf->mesh_vertices[j]->z(); k++; } } ANNkd_tree *kdtree = new ANNkd_tree(kdnodes, numnodes, 3); carveHole(gr->tetrahedra, distance, kdtree); carveHole(gr->hexahedra, distance, kdtree); carveHole(gr->prisms, distance, kdtree); carveHole(gr->pyramids, distance, kdtree); delete kdtree; annDeallocPts(kdnodes); GFace *gf = m->getFaceByTag(num); if(!gf) return; std::set<MFace, Less_Face> faces; std::vector<GFace *> f = gr->faces(); for(std::vector<GFace *>::iterator it = f.begin(); it != f.end(); it++) { addFaces((*it)->triangles, faces); addFaces((*it)->quadrangles, faces); } addFaces(gr->tetrahedra, faces); addFaces(gr->hexahedra, faces); addFaces(gr->prisms, faces); addFaces(gr->pyramids, faces); std::set<MVertex *> verts; for(std::set<MFace, Less_Face>::iterator it = faces.begin(); it != faces.end(); it++) { for(std::size_t i = 0; i < it->getNumVertices(); i++) { it->getVertex(i)->setEntity(gf); verts.insert(it->getVertex(i)); } if(it->getNumVertices() == 3) gf->triangles.push_back( new MTriangle(it->getVertex(0), it->getVertex(1), it->getVertex(2))); else if(it->getNumVertices() == 4)
; } } #endif
gf->quadrangles.push_back( new MQuadrangle(it->getVertex(0), it->getVertex(1), it->getVertex(2), it->getVertex(3)))
call_expression
[ { "content": "class GFace;\n", "file_path": "gmsh/Mesh/meshGFace.h", "rank": 0, "score": 346488.86100550985 }, { "content": "class GFace;\n\n\n\nvoid meshGFaceBamg(GFace *gf);\n\n\n\n#endif\n", "file_path": "gmsh/Mesh/meshGFaceBamg.h", "rank": 1, "score": 339593.6655204776 }, ...
C++
Clients/OIViewer/ConfigurationLoader.cpp
OpenImageViewer/OIV
7b2b67ea156255bf77819ce77bf687c9d360e217
#include "ConfigurationLoader.h" #include <LLUtils/FileHelper.h> #include <LLUtils/PlatformUtility.h> #include <LLUtils/Exception.h> #include <LLUtils/Logging/Logger.h> #include <nlohmann/json.hpp> #include <stack> namespace OIV { ConfigurationLoader::CommandGroupList ConfigurationLoader::LoadCommandGroups() { using namespace nlohmann; using namespace LLUtils; std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/Commands.json")); auto jsonObject = json::parse(jsonText); auto commands = jsonObject["commands"]; if (commands == nullptr || commands.is_array() == false) LL_EXCEPTION(LLUtils::Exception::ErrorCode::BadParameters, "File contents mismatch"); CommandGroupList commandsList; for (auto commandGroup : commands) commandsList.push_back({ commandGroup["GroupID"], commandGroup["DisplayName"] ,commandGroup["Name"], commandGroup["arguments"] }); return commandsList; } ConfigurationLoader::KeyBindingList ConfigurationLoader::LoadKeyBindings() { using namespace nlohmann; using namespace LLUtils; std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/KeyBindings.json")); auto jsonObject = json::parse(jsonText); auto keyBindings = jsonObject["KeyBindings"]; if (keyBindings == nullptr || keyBindings.is_array() == false) LL_EXCEPTION(LLUtils::Exception::ErrorCode::BadParameters, "File contents mismatch"); KeyBindingList keyBindingsList; for (auto& keybindingPair : keyBindings.items()) { for (auto& [key, value] : keybindingPair.value().items()) keyBindingsList.push_back(KeyBinding{ key, value.get<std::string>() }); } return keyBindingsList; } ConfigurationLoader::MapSettings ConfigurationLoader::LoadSettings() { using namespace nlohmann; using namespace LLUtils; MapSettings mapSettings; try { std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/Settings.json")); auto jsonObject = json::parse(jsonText); SettingEntryForParsing root; using StackData = std::tuple<json*, SettingEntryForParsing*, std::string>; std::stack<StackData> stck; stck.emplace(&jsonObject, &root, ""); while (stck.empty() == false) { const auto [jsonTree, settingEntry, currentNamespace] = stck.top(); stck.pop(); struct TmpEntry { bool isObject = false; std::string name; json* child; SettingEntryForParsing entry; }; std::list< TmpEntry> tmpList; for (auto& child : jsonTree->items()) { tmpList.push_back(TmpEntry()); auto& currentTmp = tmpList.back(); auto& currentChild = tmpList.back().entry; currentChild.name = child.key(); if (child.value().is_object() == true) { currentTmp.isObject = true; currentTmp.child = &child.value(); currentTmp.name = child.key(); } else if (child.value().is_string()) currentChild.value = child.value().get<String>(); else currentChild.value = child.value().dump(0); if (child.value().is_object() == false) { std::string qualifiedName; if (currentNamespace.empty()) qualifiedName = currentChild.name; else qualifiedName = currentNamespace + seperator + currentChild.name; mapSettings.emplace(qualifiedName, currentChild.value); } } settingEntry->children.resize(tmpList.size()); decltype(tmpList)::const_iterator it = tmpList.begin(); for (size_t i = 0; i < tmpList.size(); i++, it++) { settingEntry->children.at(i) = it->entry; if (it->isObject) { std::string qualifiedName; if (currentNamespace.empty()) qualifiedName = it->name; else qualifiedName = currentNamespace + seperator + it->name; stck.emplace(it->child, &settingEntry->children.at(i), qualifiedName); } } } } catch (nlohmann::detail::exception& exception) { LLUtils::Logger::GetSingleton().Log(exception.what()); } catch (...) { } return mapSettings; } }
#include "ConfigurationLoader.h" #include <LLUtils/FileHelper.h> #include <LLUtils/PlatformUtility.h> #include <LLUtils/Exception.h> #include <LLUtils/Logging/Logger.h> #include <nlohmann/json.hpp> #include <stack> namespace OIV {
ConfigurationLoader::KeyBindingList ConfigurationLoader::LoadKeyBindings() { using namespace nlohmann; using namespace LLUtils; std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/KeyBindings.json")); auto jsonObject = json::parse(jsonText); auto keyBindings = jsonObject["KeyBindings"]; if (keyBindings == nullptr || keyBindings.is_array() == false) LL_EXCEPTION(LLUtils::Exception::ErrorCode::BadParameters, "File contents mismatch"); KeyBindingList keyBindingsList; for (auto& keybindingPair : keyBindings.items()) { for (auto& [key, value] : keybindingPair.value().items()) keyBindingsList.push_back(KeyBinding{ key, value.get<std::string>() }); } return keyBindingsList; } ConfigurationLoader::MapSettings ConfigurationLoader::LoadSettings() { using namespace nlohmann; using namespace LLUtils; MapSettings mapSettings; try { std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/Settings.json")); auto jsonObject = json::parse(jsonText); SettingEntryForParsing root; using StackData = std::tuple<json*, SettingEntryForParsing*, std::string>; std::stack<StackData> stck; stck.emplace(&jsonObject, &root, ""); while (stck.empty() == false) { const auto [jsonTree, settingEntry, currentNamespace] = stck.top(); stck.pop(); struct TmpEntry { bool isObject = false; std::string name; json* child; SettingEntryForParsing entry; }; std::list< TmpEntry> tmpList; for (auto& child : jsonTree->items()) { tmpList.push_back(TmpEntry()); auto& currentTmp = tmpList.back(); auto& currentChild = tmpList.back().entry; currentChild.name = child.key(); if (child.value().is_object() == true) { currentTmp.isObject = true; currentTmp.child = &child.value(); currentTmp.name = child.key(); } else if (child.value().is_string()) currentChild.value = child.value().get<String>(); else currentChild.value = child.value().dump(0); if (child.value().is_object() == false) { std::string qualifiedName; if (currentNamespace.empty()) qualifiedName = currentChild.name; else qualifiedName = currentNamespace + seperator + currentChild.name; mapSettings.emplace(qualifiedName, currentChild.value); } } settingEntry->children.resize(tmpList.size()); decltype(tmpList)::const_iterator it = tmpList.begin(); for (size_t i = 0; i < tmpList.size(); i++, it++) { settingEntry->children.at(i) = it->entry; if (it->isObject) { std::string qualifiedName; if (currentNamespace.empty()) qualifiedName = it->name; else qualifiedName = currentNamespace + seperator + it->name; stck.emplace(it->child, &settingEntry->children.at(i), qualifiedName); } } } } catch (nlohmann::detail::exception& exception) { LLUtils::Logger::GetSingleton().Log(exception.what()); } catch (...) { } return mapSettings; } }
ConfigurationLoader::CommandGroupList ConfigurationLoader::LoadCommandGroups() { using namespace nlohmann; using namespace LLUtils; std::string jsonText = File::ReadAllText<std::string>(LLUtils::PlatformUtility::GetExeFolder() + LLUTILS_TEXT("./Resources/Configuration/Commands.json")); auto jsonObject = json::parse(jsonText); auto commands = jsonObject["commands"]; if (commands == nullptr || commands.is_array() == false) LL_EXCEPTION(LLUtils::Exception::ErrorCode::BadParameters, "File contents mismatch"); CommandGroupList commandsList; for (auto commandGroup : commands) commandsList.push_back({ commandGroup["GroupID"], commandGroup["DisplayName"] ,commandGroup["Name"], commandGroup["arguments"] }); return commandsList; }
function_block-full_function
[ { "content": "namespace OIV\n\n{\n\n struct SelectionRect\n\n {\n\n LLUtils::PointI32 p0;\n\n LLUtils::PointI32 p1;\n\n };\n\n\n\n struct ViewParameters\n\n {\n\n LLUtils::PointI32 uViewportSize;\n\n LLUtils::Color uTransparencyColor1;\n\n LLUtils::Color uTransp...
C++
dependencies/PyMesh/tools/MeshUtils/DegeneratedTriangleRemoval.cpp
aprieels/3D-watermarking-spectral-decomposition
dcab78857d0bb201563014e58900917545ed4673
#include "DegeneratedTriangleRemoval.h" #include <cassert> #include <iostream> #include <limits> #include <set> #include <vector> #include <Math/MatrixUtils.h> #include <MeshUtils/FaceUtils.h> #include <MeshUtils/IsolatedVertexRemoval.h> #include <MeshUtils/ShortEdgeRemoval.h> #include <Predicates/predicates.h> using namespace PyMesh; namespace DegeneratedTriangleRemovalHelper { const size_t INVALID = std::numeric_limits<size_t>::max(); } using namespace DegeneratedTriangleRemovalHelper; DegeneratedTriangleRemoval::DegeneratedTriangleRemoval( const MatrixFr& vertices, const MatrixIr& faces) : m_vertices(vertices), m_faces(faces) { assert(m_vertices.cols() == 3); assert(m_faces.cols() == 3); exactinit(); init_ori_face_indices(); } void DegeneratedTriangleRemoval::run(size_t num_iterations) { size_t num_removed = 0; size_t count = 0; do { num_removed = 0; size_t e_removed = remove_zero_edges(); size_t e_flipped = remove_line_faces(); remove_isolated_vertices(); count++; num_removed += (e_removed + e_flipped); } while (num_removed != 0 && count < num_iterations); if (num_removed != 0) { std::cerr << "Warning: Max number of iterations reached. "; std::cerr << "Not all degenerated faces are removed." << std::endl; } } void DegeneratedTriangleRemoval::init_ori_face_indices() { const size_t num_faces = m_faces.rows(); m_ori_face_indices.resize(num_faces); for (size_t i=0; i<num_faces; i++) { m_ori_face_indices[i] = i; } } size_t DegeneratedTriangleRemoval::remove_zero_edges() { ShortEdgeRemoval remover(m_vertices, m_faces); size_t num_removed = remover.run(0.0); m_vertices = remover.get_vertices(); m_faces = remover.get_faces(); auto sources = remover.get_face_indices(); const size_t num_faces = m_faces.rows(); assert(num_faces == sources.rows()); assert(sources.size() == 0 || sources.minCoeff() >= 0); assert(sources.size() == 0 || sources.maxCoeff() < m_ori_face_indices.size()); VectorI updated_ori_face_indices(num_faces); for (size_t i=0; i<num_faces; i++) { updated_ori_face_indices[i] = m_ori_face_indices[sources[i]]; } m_ori_face_indices = updated_ori_face_indices; return num_removed; } size_t DegeneratedTriangleRemoval::remove_line_faces() { init_edge_map(); auto comp = [&](const Triplet& e1, const Triplet& e2) -> bool{ auto v1 = m_vertices.row(e1.get_ori_data()[0]); auto v2 = m_vertices.row(e1.get_ori_data()[1]); auto v3 = m_vertices.row(e2.get_ori_data()[0]); auto v4 = m_vertices.row(e2.get_ori_data()[1]); return (v1-v2).squaredNorm() > (v3-v4).squaredNorm(); }; const size_t num_faces = m_faces.rows(); std::set<Triplet, decltype(comp)> edges_to_remove(comp); std::vector<size_t> longest_edges(num_faces, INVALID); for (size_t fi=0; fi<num_faces; fi++) { if (!is_degenerated(fi)) continue; const auto& face = m_faces.row(fi); const size_t fi_opp_v = find_longest_edge(fi); const size_t vi_0 = face[(fi_opp_v+1)%3]; const size_t vi_1 = face[(fi_opp_v+2)%3]; Triplet edge(vi_0, vi_1); edges_to_remove.insert(edge); longest_edges[fi] = fi_opp_v; } std::vector<VectorI> new_faces; std::vector<VectorI::Scalar> new_ori_face_indices; std::vector<bool> is_valid(num_faces, true); size_t count = 0; for (auto& edge : edges_to_remove) { auto& neighboring_faces = m_edge_map[edge]; bool all_valid = true; for (auto fj : neighboring_faces) { all_valid &= is_valid[fj]; } if (!all_valid) continue; const size_t vi_0 = edge.get_ori_data()[0]; const size_t vi_1 = edge.get_ori_data()[1]; size_t vi_opp = INVALID; size_t fi = INVALID; for (auto fj : neighboring_faces) { if (longest_edges[fj] == INVALID) continue; const auto neighbor_face = m_faces.row(fj); const size_t vj_opp = neighbor_face[longest_edges[fj]]; if (vj_opp != vi_0 && vj_opp != vi_1) { fi = fj; vi_opp = vj_opp; break; } } assert(vi_opp != INVALID); assert(fi != INVALID); for (auto fj : neighboring_faces) { is_valid[fj] = false; if (fj == fi) continue; const auto neighbor_face = m_faces.row(fj); size_t fj_opp_v = INVALID; for (size_t i=0; i<3; i++) { if (neighbor_face[i] != vi_0 && neighbor_face[i] != vi_1) { fj_opp_v = i; break; } } assert(fj_opp_v != INVALID); const size_t vj_opp = neighbor_face[fj_opp_v]; const size_t vj_0 = neighbor_face[(fj_opp_v+1)%3]; const size_t vj_1 = neighbor_face[(fj_opp_v+2)%3]; new_faces.push_back(Vector3I(vi_opp, vj_opp, vj_0)); new_faces.push_back(Vector3I(vi_opp, vj_1, vj_opp)); new_ori_face_indices.push_back(m_ori_face_indices[fj]); new_ori_face_indices.push_back(m_ori_face_indices[fj]); } count++; } for (size_t fi=0; fi<num_faces; fi++) { if (is_valid[fi]) { new_faces.push_back(m_faces.row(fi)); new_ori_face_indices.push_back(m_ori_face_indices[fi]); } } if (!new_faces.empty()) { m_faces = MatrixUtils::rowstack(new_faces); m_ori_face_indices = MatrixUtils::std2eigen(new_ori_face_indices); } else { m_faces = MatrixIr(0, 3); m_ori_face_indices.resize(0); } assert(m_faces.rows() == new_faces.size()); return count; } void DegeneratedTriangleRemoval::remove_isolated_vertices() { IsolatedVertexRemoval remover(m_vertices, m_faces); remover.run(); m_vertices = remover.get_vertices(); m_faces = remover.get_faces(); } void DegeneratedTriangleRemoval::init_edge_map() { m_edge_map.clear(); const size_t num_faces = m_faces.rows(); assert(m_faces.cols() == 3); for (size_t i=0; i<num_faces; i++) { const auto& f = m_faces.row(i); m_edge_map.insert(Triplet(f[0], f[1]), i); m_edge_map.insert(Triplet(f[1], f[2]), i); m_edge_map.insert(Triplet(f[2], f[0]), i); } } bool DegeneratedTriangleRemoval::is_degenerated(size_t i) const { const auto& f = m_faces.row(i); const auto& v0 = m_vertices.row(f[0]); const auto& v1 = m_vertices.row(f[1]); const auto& v2 = m_vertices.row(f[2]); return FaceUtils::is_colinear_3D(v0, v1, v2); } size_t DegeneratedTriangleRemoval::find_longest_edge(size_t fi) const { const auto& f = m_faces.row(fi); const auto& v0 = m_vertices.row(f[0]); const auto& v1 = m_vertices.row(f[1]); const auto& v2 = m_vertices.row(f[2]); size_t i = 0; if (!(v0[0] == v1[0] || v0[0] == v2[0] || v1[0] == v2[0])) { i = 0; } else if (!(v0[1] == v1[1] || v0[1] == v2[1] || v1[1] == v2[1])) { i = 1; } else if (!(v0[2] == v1[2] || v0[2] == v2[2] || v1[2] == v2[2])) { i = 2; } else { std::cerr << f[0] << ": " << v0 << std::endl; std::cerr << f[1] << ": " << v1 << std::endl; std::cerr << f[2] << ": " << v2 << std::endl; throw RuntimeError("Triangle degenerates to a point, report this bug"); } if (v0[i] < v1[i] && v0[i] > v2[i]) return 0; if (v0[i] > v1[i] && v0[i] < v2[i]) return 0; if (v1[i] < v0[i] && v1[i] > v2[i]) return 1; if (v1[i] > v0[i] && v1[i] < v2[i]) return 1; if (v2[i] < v0[i] && v2[i] > v1[i]) return 2; if (v2[i] > v0[i] && v2[i] < v1[i]) return 2; std::cerr << f[0] << ": " << v0 << std::endl; std::cerr << f[1] << ": " << v1 << std::endl; std::cerr << f[2] << ": " << v2 << std::endl; throw RuntimeError("Triangle contains an zero edge, report this bug"); }
#include "DegeneratedTriangleRemoval.h" #include <cassert> #include <iostream> #include <limits> #include <set> #include <vector> #include <Math/MatrixUtils.h> #include <MeshUtils/FaceUtils.h> #include <MeshUtils/IsolatedVertexRemoval.h> #include <MeshUtils/ShortEdgeRemoval.h> #include <Predicates/predicates.h> using namespace PyMesh; namespace DegeneratedTriangleRemovalHelper { const size_t INVALID = std::numeric_limits<size_t>::max(); } using namespace DegeneratedTriangleRemovalHelper; DegeneratedTriangleRemoval::DegeneratedTriangleRemoval( const MatrixFr& vertices, const MatrixIr& faces) : m_vertices(vertices), m_faces(faces) { assert(m_vertices.cols() == 3); assert(m_faces.cols() == 3); exactinit(); init_ori_face_indices(); } void DegeneratedTriangleRemoval::run(size_t num_iterations) { size_t num_removed = 0; size_t count = 0; do { num_removed = 0; size_t e_removed = remove_zero_edges(); size_t e_flipped = remove_line_faces(); remove_isolated_vertices(); count++; num_removed += (e_removed + e_flipped); } while (num_removed != 0 && count < num_iterations); if (num_removed != 0) { std::cerr << "Warning: Max number of iterations reached. "; std::cerr << "Not all degenerated faces are removed." << std::endl; } } void DegeneratedTriangleRemoval::init_ori_face_indices() { const size_t num_faces = m_faces.rows(); m_ori_face_indices.resize(num_faces); for (size_t i=0; i<num_faces; i++) { m_ori_face_indices[i] = i; } } size_t DegeneratedTriangleRemoval::remove_zero_edges() { ShortEdgeRemoval remover(m_vertices, m_faces); size_t num_removed = remover.run(0.0); m_vertices = remover.get_vertices(); m_faces = remover.get_faces(); auto sources = remover.get_face_indices(); const size_t num_faces = m_faces.rows(); assert(num_faces == sources.rows()); assert(sources.size() == 0 || sources.minCoeff() >= 0); assert(sources.size() == 0 || sources.maxCoeff() < m_ori_face_indices.size()); VectorI updated_ori_face_indices(num_faces); for (size_t i=0; i<num_faces; i++) { updated_ori_face_indices[i] = m_ori_face_indices[sources[i]]; } m_ori_face_indices = updated_ori_face_indices; return num_removed; } size_t DegeneratedTriangleRemoval::remove_line_faces() { init_edge_map(); auto comp = [&](const Triplet& e1, const Triplet& e2) -> bool{ auto v1 = m_vertices.row(e1.get_ori_data()[0]); auto v2 = m_vertices.row(e1.get_ori_data()[1]); auto v3 = m_vertices.row(e2.get_ori_data()[0]); auto v4 = m_vertices.row(e2.get_ori_data()[1]); return (v1-v2).squaredNorm() > (v3-v4).squaredNorm(); }; const size_t num_faces = m_faces.rows(); std::set<Triplet, decltype(comp)> edges_to_remove(comp); std::vector<size_t> longest_edges(num_faces, INVALID); for (size_t fi=0; fi<num_faces; fi++) { if (!is_degenerated(fi)) continue; const auto& face = m_faces.row(fi); const size_t fi_opp_v = find_longest_edge(fi); const size_t vi_0 = face[(fi_opp_v+1)%3]; const size_t vi_1 = face[(fi_opp_v+2)%3]; Triplet edge(vi_0, vi_1); edges_to_remove.insert(edge); longest_edges[fi] = fi_opp_v; } std::vector<VectorI> new_faces; std::vector<VectorI::Scalar> new_ori_face_indices; std::vector<bool> is_valid(num_faces, true); size_t count = 0; for (auto& edge : edges_to_remove) { auto& neighboring_faces = m_edge_map[edge]; bool all_valid = true; for (auto fj : neighboring_faces) { all_valid &= is_valid[fj]; } if (!all_valid) continue; const size_t vi_0 = edge.get_ori_data()[0]; const size_t vi_1 = edge.get_ori_data()[1]; size_t vi_opp = INVALID; size_t fi = INVALID; for (auto fj : neighboring_faces) { if (longest_edges[fj] == INVALID) continue; const auto neighbor_face = m_faces.row(fj); const size_t vj_opp = neighbor_face[longest_edges[fj]]; if (vj_opp != vi_0 && vj_opp != vi_1) { fi = fj; vi_opp = vj_opp; break; } } assert(vi_opp != INVALID); assert(fi != INVALID); for (auto fj : neighboring_faces) { is_valid[fj] = false; if (fj == fi) continue; const auto neighbor_face = m_faces.row(fj); size_t fj_opp_v = INVALID; for (size_t i=0; i<3; i++) {
} assert(fj_opp_v != INVALID); const size_t vj_opp = neighbor_face[fj_opp_v]; const size_t vj_0 = neighbor_face[(fj_opp_v+1)%3]; const size_t vj_1 = neighbor_face[(fj_opp_v+2)%3]; new_faces.push_back(Vector3I(vi_opp, vj_opp, vj_0)); new_faces.push_back(Vector3I(vi_opp, vj_1, vj_opp)); new_ori_face_indices.push_back(m_ori_face_indices[fj]); new_ori_face_indices.push_back(m_ori_face_indices[fj]); } count++; } for (size_t fi=0; fi<num_faces; fi++) { if (is_valid[fi]) { new_faces.push_back(m_faces.row(fi)); new_ori_face_indices.push_back(m_ori_face_indices[fi]); } } if (!new_faces.empty()) { m_faces = MatrixUtils::rowstack(new_faces); m_ori_face_indices = MatrixUtils::std2eigen(new_ori_face_indices); } else { m_faces = MatrixIr(0, 3); m_ori_face_indices.resize(0); } assert(m_faces.rows() == new_faces.size()); return count; } void DegeneratedTriangleRemoval::remove_isolated_vertices() { IsolatedVertexRemoval remover(m_vertices, m_faces); remover.run(); m_vertices = remover.get_vertices(); m_faces = remover.get_faces(); } void DegeneratedTriangleRemoval::init_edge_map() { m_edge_map.clear(); const size_t num_faces = m_faces.rows(); assert(m_faces.cols() == 3); for (size_t i=0; i<num_faces; i++) { const auto& f = m_faces.row(i); m_edge_map.insert(Triplet(f[0], f[1]), i); m_edge_map.insert(Triplet(f[1], f[2]), i); m_edge_map.insert(Triplet(f[2], f[0]), i); } } bool DegeneratedTriangleRemoval::is_degenerated(size_t i) const { const auto& f = m_faces.row(i); const auto& v0 = m_vertices.row(f[0]); const auto& v1 = m_vertices.row(f[1]); const auto& v2 = m_vertices.row(f[2]); return FaceUtils::is_colinear_3D(v0, v1, v2); } size_t DegeneratedTriangleRemoval::find_longest_edge(size_t fi) const { const auto& f = m_faces.row(fi); const auto& v0 = m_vertices.row(f[0]); const auto& v1 = m_vertices.row(f[1]); const auto& v2 = m_vertices.row(f[2]); size_t i = 0; if (!(v0[0] == v1[0] || v0[0] == v2[0] || v1[0] == v2[0])) { i = 0; } else if (!(v0[1] == v1[1] || v0[1] == v2[1] || v1[1] == v2[1])) { i = 1; } else if (!(v0[2] == v1[2] || v0[2] == v2[2] || v1[2] == v2[2])) { i = 2; } else { std::cerr << f[0] << ": " << v0 << std::endl; std::cerr << f[1] << ": " << v1 << std::endl; std::cerr << f[2] << ": " << v2 << std::endl; throw RuntimeError("Triangle degenerates to a point, report this bug"); } if (v0[i] < v1[i] && v0[i] > v2[i]) return 0; if (v0[i] > v1[i] && v0[i] < v2[i]) return 0; if (v1[i] < v0[i] && v1[i] > v2[i]) return 1; if (v1[i] > v0[i] && v1[i] < v2[i]) return 1; if (v2[i] < v0[i] && v2[i] > v1[i]) return 2; if (v2[i] > v0[i] && v2[i] < v1[i]) return 2; std::cerr << f[0] << ": " << v0 << std::endl; std::cerr << f[1] << ": " << v1 << std::endl; std::cerr << f[2] << ": " << v2 << std::endl; throw RuntimeError("Triangle contains an zero edge, report this bug"); }
if (neighbor_face[i] != vi_0 && neighbor_face[i] != vi_1) { fj_opp_v = i; break; }
if_condition
[ { "content": "struct RemoveConst<const T[N]> {\n\n typedef typename RemoveConst<T>::type type[N];\n\n};\n\n\n\n#if defined(_MSC_VER) && _MSC_VER < 1400\n\n// This is the only specialization that allows VC++ 7.1 to remove const in\n\n// 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC\n...
C++
Sandbox/src/Sandbox2D.cpp
SunHailang/Hazel
1b4784c8d6bd2ad402ded34d677fd482a81a9d72
#include "Sandbox2D.h" #include <imgui/imgui.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> static const char* s_MapTiles = "lajksdasd"; Sandbox2D::Sandbox2D() :Hazel::Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f, true) { } void Sandbox2D::OnAttach() { HZ_PROFILE_FUNCTION(); m_texture = Hazel::Texture2D::Create("assets/textures/wall.jpg"); m_spriteSheet = Hazel::Texture2D::Create("assets/game/textures/RPGpack_sheet_2X.png"); m_textureStairs = Hazel::SubTexture2D::CreateFromCoords(m_spriteSheet, { 7, 6 }, { 128, 128 }); m_Particle.ColorBegin = { 254 / 255.0f, 109 / 255.0f, 41 / 255.0f, 1.0f }; m_Particle.ColorEnd = { 254 / 255.0f, 212 / 255.0f, 123 / 255.0f, 1.0f }; m_Particle.SizeBegin = 0.5f; m_Particle.SizeVariation = 0.3f; m_Particle.SizeEnd = 0.0f; m_Particle.LiftTime = 1.0f; m_Particle.Velocity = { 0.0f, 0.0f }; m_Particle.VelocityVariation = { 3.0f, 1.0f }; m_Particle.Position = { 0.0f, 0.0f }; m_CameraController.SetZoomLevel(5.0f); } void Sandbox2D::OnDetach() { } void Sandbox2D::OnUpdate(Hazel::Timestep ts) { HZ_PROFILE_FUNCTION(); m_CameraController.OnUpdate(ts); Hazel::Renderer2D::ResetStats(); { HZ_PROFILE_SCOPE("Renderer Prep"); Hazel::RendererCommand::SetClearColor(glm::vec4(0.2f, 0.2f, 0.2f, 1.0f)); Hazel::RendererCommand::Clear(); } { } if (Hazel::Input::IsMouseButtonPressed(HZ_MOUSE_BUTTON_LEFT)) { auto [x, y] = Hazel::Input::GetMousePosition(); auto width = Hazel::Application::Get().GetWindow().GetWidth(); auto height = Hazel::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_Particle.Position = { (x + pos.x), (y + pos.y) }; for (int i = 0; i < 5; i++) { m_ParticleSystem.Emit(m_Particle); } } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); Hazel::Renderer2D::BeginScene(m_CameraController.GetCamera()); Hazel::Renderer2D::DrawQuad({ 0.0f, 0.0f, 0.3f }, { 1.0f, 1.0f }, m_textureStairs); Hazel::Renderer2D::EndScene(); } void Sandbox2D::OnImGuiRender() { HZ_PROFILE_FUNCTION(); ImGui::Begin("Setting"); auto stats = Hazel::Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertics: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); ImGui::End(); } void Sandbox2D::OnEvent(Hazel::Event& event) { m_CameraController.OnEvent(event); }
#include "Sandbox2D.h" #include <imgui/imgui.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> static const char* s_MapTiles = "lajksdasd"; Sandbox2D::Sandbox2D() :Hazel::Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f, true) { } void Sandbox2D::OnAttach() { HZ_PROFILE_FUNCTION(); m_texture = Hazel::Texture2D::Create("assets/textures/wall.jpg"); m_spriteSheet = Hazel::Texture2D::Create("assets/game/textures/RPGpack_sheet_2X.png"); m_textureStairs = Hazel::SubTexture2D::CreateFromCoords(m_spriteSheet, { 7, 6 }, { 128, 128 }); m_Particle.ColorBegin = { 254 / 255.0f, 109 / 255.0f, 41 / 255.0f, 1.0f }; m_Particle.ColorEnd = { 254 / 255.0f, 212 / 255.0f, 123 / 255.0f, 1.0f }; m_Particle.SizeBegin = 0.5f; m_Particle.SizeVariation = 0.3f; m_Particle.SizeEnd = 0.0f; m_Particle.LiftTime = 1.0f; m_Particle.Velocity = { 0.0f, 0.0f }; m_Particle.VelocityVariation = { 3.0f, 1.0f }; m_Particle.Position = { 0.0f, 0.0f }; m_CameraController.SetZoomLevel(5.0f); } void Sandbox2D::OnDetach() { } void Sandbox2D::OnUpdate(Hazel::Timestep ts) { HZ_PROFILE_FUNCTION(); m_CameraController.
tWindow().GetWidth(); auto height = Hazel::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_Particle.Position = { (x + pos.x), (y + pos.y) }; for (int i = 0; i < 5; i++) { m_ParticleSystem.Emit(m_Particle); } } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); Hazel::Renderer2D::BeginScene(m_CameraController.GetCamera()); Hazel::Renderer2D::DrawQuad({ 0.0f, 0.0f, 0.3f }, { 1.0f, 1.0f }, m_textureStairs); Hazel::Renderer2D::EndScene(); } void Sandbox2D::OnImGuiRender() { HZ_PROFILE_FUNCTION(); ImGui::Begin("Setting"); auto stats = Hazel::Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertics: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); ImGui::End(); } void Sandbox2D::OnEvent(Hazel::Event& event) { m_CameraController.OnEvent(event); }
OnUpdate(ts); Hazel::Renderer2D::ResetStats(); { HZ_PROFILE_SCOPE("Renderer Prep"); Hazel::RendererCommand::SetClearColor(glm::vec4(0.2f, 0.2f, 0.2f, 1.0f)); Hazel::RendererCommand::Clear(); } { } if (Hazel::Input::IsMouseButtonPressed(HZ_MOUSE_BUTTON_LEFT)) { auto [x, y] = Hazel::Input::GetMousePosition(); auto width = Hazel::Application::Get().Ge
random
[ { "content": "#include \"hzpch.h\"\n\n#include \"OpenGLFramebuffer.h\"\n\n\n\n#include <glad/glad.h>\n\n\n\nnamespace Hazel\n\n{\n\n\n\n\tstatic const uint32_t s_MaxFramebufferSize = 8192;\n\n\n\n\tnamespace Utils {\n\n\n\n\t\tstatic GLenum TextureTarget(bool multisampled)\n\n\t\t{\n\n\t\t\treturn multisampled ...
C++
src/vm/vm_detect.cpp
bouldev/libbouldev
afe0d5dca71d4f9c94b11273c4884a92f2549df8
#include <libbouldev.h> #include <string> #ifdef _WIN32 #include "stdafx.h" #include <iostream> #include <Wbemidl.h> #pragma comment(lib, "wbemuuid.lib") #endif #ifdef _WIN32 static bool InitWMI(IWbemServices **pSvc, IWbemLocator **pLoc, const TCHAR* szNetworkResource) { HRESULT hres; hres = CoInitializeEx(0, COINIT_MULTITHREADED); hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); hres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(pLoc)); BSTR strNetworkResource = SysAllocString(szNetworkResource); if (strNetworkResource) { hres = (*pLoc)->ConnectServer(strNetworkResource, NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, 0, 0, pSvc); SysFreeString(strNetworkResource); } hres = CoSetProxyBlanket(*pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); return 1; } static bool ExecWMIQuery(IWbemServices **pSvc, IWbemLocator **pLoc, IEnumWbemClassObject **pEnumerator, const TCHAR* szQuery) { BSTR strQueryLanguage = SysAllocString(OLESTR("WQL")); BSTR strQuery = SysAllocString(szQuery); BOOL bQueryResult = TRUE; if (strQueryLanguage && strQuery) HRESULT hres = (*pSvc)->ExecQuery(strQueryLanguage, strQuery, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, pEnumerator); if (strQueryLanguage) SysFreeString(strQueryLanguage); if (strQuery) SysFreeString(strQuery); return bQueryResult; } static int wmi_query_count(const _TCHAR* query) { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; int count = 0; bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, query); if (bStatus) { IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; count++; pclsObj->Release(); } } pSvc->Release(); pLoc->Release(); CoUninitialize(); } else return -1; return count; } #endif #ifdef linux static bool under_qemu() { char *cmdline = NULL; char *out = NULL; int ret = 0; strcpy(cmdline, "cat /proc/cpuinfo | grep QEMU &> /dev/null"); boul_cmd buf = { cmdline, ret, out }; run_cmd(buf); if (ret == 0) return true; return false; } #endif static bool under_sandbox() { if (path_exists("/.dockerenv")) return true; #ifdef linux char *cmdline = NULL; char *out = NULL; int ret = 0; strcpy(cmdline, "grep -sq 'docker|lxc' /proc/1/cgroup &> /dev/null"); boul_cmd buf = { cmdline, ret, out }; run_cmd(buf); if (ret == 0) return true; #endif return false; } bool os_is_vm() { #ifdef _WIN32 return wmi_query_count(_T("SELECT * FROM Win32_PortConnector")) == 0 ? true : false; #elif defined(linux) return (under_qemu() || under_sandbox()); #elif defined(__APPLE__) return false; #endif }
#include <libbouldev.h> #include <string> #ifdef _WIN32 #include "stdafx.h" #include <iostream> #include <Wbemidl.h> #pragma comment(lib, "wbemuuid.lib") #endif #ifdef _WIN32 static bool InitWMI(IWbemServices **pSvc, IWbemLocator **pLoc, const TCHAR* szNetworkResource) { HRESULT hres; hres = CoInitializeEx(0, COINIT_MULTITHREADED); hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); hres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(pLoc)); BSTR strNetworkResource = SysAllocString(szNetworkResource); if (strNetworkResource) { hres = (*pLoc)->ConnectServer(strNetworkResource, NULL, NULL, NULL, WBEM_FLAG_CONNECT_USE_MAX_WAIT, 0, 0, pSvc); SysFreeString(strNetworkResource); } hres = CoSetProxyBlanket(*pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE); return 1; } static bool ExecWMIQuery(IWbemServices **pSvc, IWbemLocator **pLoc, IEnumWbemClassObject **pEnumerator, const TCHAR* szQuery) { BSTR strQueryLanguage = SysAllocString(OLESTR("WQL")); BSTR strQuery = SysAllo
static int wmi_query_count(const _TCHAR* query) { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; int count = 0; bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, query); if (bStatus) { IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; count++; pclsObj->Release(); } } pSvc->Release(); pLoc->Release(); CoUninitialize(); } else return -1; return count; } #endif #ifdef linux static bool under_qemu() { char *cmdline = NULL; char *out = NULL; int ret = 0; strcpy(cmdline, "cat /proc/cpuinfo | grep QEMU &> /dev/null"); boul_cmd buf = { cmdline, ret, out }; run_cmd(buf); if (ret == 0) return true; return false; } #endif static bool under_sandbox() { if (path_exists("/.dockerenv")) return true; #ifdef linux char *cmdline = NULL; char *out = NULL; int ret = 0; strcpy(cmdline, "grep -sq 'docker|lxc' /proc/1/cgroup &> /dev/null"); boul_cmd buf = { cmdline, ret, out }; run_cmd(buf); if (ret == 0) return true; #endif return false; } bool os_is_vm() { #ifdef _WIN32 return wmi_query_count(_T("SELECT * FROM Win32_PortConnector")) == 0 ? true : false; #elif defined(linux) return (under_qemu() || under_sandbox()); #elif defined(__APPLE__) return false; #endif }
cString(szQuery); BOOL bQueryResult = TRUE; if (strQueryLanguage && strQuery) HRESULT hres = (*pSvc)->ExecQuery(strQueryLanguage, strQuery, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, pEnumerator); if (strQueryLanguage) SysFreeString(strQueryLanguage); if (strQuery) SysFreeString(strQuery); return bQueryResult; }
function_block-function_prefixed
[ { "content": "\tchar *out; // stdout buffer\n", "file_path": "src/common/libbouldev_private.h", "rank": 6, "score": 1.5771744743371818 } ]
C++
argos3/src/plugins/robots/generic/simulator/radios_default_sensor.cpp
yiftachn/krembot_sim_fork
d3d1b050f9fff4c96bded298eadde5a9ca4dab6b
#include "radios_default_sensor.h" #include <argos3/plugins/simulator/entities/radio_equipped_entity.h> namespace argos { CRadiosDefaultSensor::CRadiosDefaultSensor() : m_pcRadioEquippedEntity(nullptr), m_pcControllableEntity(nullptr), m_bShowRays(false) {} void CRadiosDefaultSensor::SetRobot(CComposableEntity& c_entity) { try { m_pcRadioEquippedEntity = &(c_entity.GetComponent<CRadioEquippedEntity>("radios")); m_vecInterfaces.reserve(m_pcRadioEquippedEntity->GetInstances().size()); for(CRadioEquippedEntity::SInstance& s_instance : m_pcRadioEquippedEntity->GetInstances()) { m_vecInterfaces.emplace_back(s_instance.Radio.GetId()); } m_pcControllableEntity = &(c_entity.GetComponent<CControllableEntity>("controller")); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Can't set robot for the radios default sensor", ex); } Enable(); } void CRadiosDefaultSensor::Init(TConfigurationNode& t_tree) { try { CCI_RadiosSensor::Init(t_tree); GetNodeAttributeOrDefault(t_tree, "show_rays", m_bShowRays, m_bShowRays); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing the radios default sensor", ex); } } void CRadiosDefaultSensor::Update() { if (IsDisabled()) { return; } for(size_t i = 0; i < m_pcRadioEquippedEntity->GetInstances().size(); ++i) { CRadioEntity& cRadio = m_pcRadioEquippedEntity->GetRadio(i); m_vecInterfaces[i].Data.clear(); for(const std::pair<CVector3, CByteArray>& c_data : cRadio.GetData()) { m_vecInterfaces[i].Data.emplace_back(c_data.second); if(m_bShowRays) { CRay3 cRay(c_data.first, cRadio.GetPosition()); m_pcControllableEntity->GetCheckedRays().emplace_back(!c_data.second.Empty(), cRay); } } cRadio.GetData().clear(); } } void CRadiosDefaultSensor::Reset() { for(SInterface& s_interface : m_vecInterfaces) { s_interface.Data.clear(); } } REGISTER_SENSOR(CRadiosDefaultSensor, "radios", "default", "Michael Allwright [allsey87@gmail.com]", "1.0", "A generic radio sensor to receive messages from nearby radios.", "This radio sensor implementation allows an arbitary number of messages\n" "containing an arbitary number of bytes to be received from nearby robots. The\n" "implementation is very basic and any concepts such as throughput, addressing,\n" "or formatting of a message's contents is beyond the scope of this sensor's\n" "implementation\n\n" "This sensor is enabled by default.\n\n" "REQUIRED XML CONFIGURATION\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <radios implementation=\"default\" medium=\"radios\" />\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "The 'medium' attribute sets the id of the radio medium declared in the <media>\n" "XML section.\n\n" "OPTIONAL XML CONFIGURATION\n\n" "None.\n", "Usable" ); }
#include "radios_default_sensor.h" #include <argos3/plugins/simulator/entities/radio_equipped_entity.h> namespace argos { CRadiosDefaultSensor::CRadiosDefaultSensor() : m_pcRadioEquippedEntity(nullptr), m_pcControllableEntity(nullptr), m_bShowRays(false) {} void CRadiosDefaultSensor::SetRobot(CComposableEntity& c_entity) { try { m_pcRadioEquippedEntity = &(c_entity.GetComponent<CRadioEquippedEntity>("radios")); m_vecInterfaces.reserve(m_pcRadioEquippedEntity->GetInstances().size()); for(CRadioEquippedEntity::SInstance& s_instance : m_pcRadioEquippedEntity->GetInstances()) { m_vecInterfaces.emplace_back(s_instance.Radio.GetId()); } m_pcControllableEntity = &(c_entity.GetComponent<CControllableEntity>("controller")); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Can't set robot for the radios default sensor", ex); } Enable(); } void CRadiosDefaultSensor::Init(TConfigurationNode& t_tree) { try { CCI_RadiosSensor::Init(t_tree); GetNodeAttributeOrDefault(t_tree, "show_rays", m_bShowRays, m_bShowRays); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error initializing the radios default sensor", ex); } } void CRadiosDefaultSensor::Update() { if (IsDisabled()) { return; } for(size_t i = 0; i < m_pcRadioEquippedEntity->GetInstances().size(); ++i) { CRadioEntity& cRadio = m_pcRadioEquippedEntity->GetRadio(i); m_vecInterfaces[i].Data.clear(); for(const std::pair<CVector3, CByteArray>& c_data : cRadio.GetData()) { m_vecInterfaces[i].Data.emplace_back(c_data.second); if(m_bShowRays) { CRay3 cRay(c_data.first, cRadio.GetPosition()); m_pcControllableEntity->GetCheckedRays().emplace_back(!c_data.second.Empty(), cRay); } } cRadio.GetData().clear(); } } void
REGISTER_SENSOR(CRadiosDefaultSensor, "radios", "default", "Michael Allwright [allsey87@gmail.com]", "1.0", "A generic radio sensor to receive messages from nearby radios.", "This radio sensor implementation allows an arbitary number of messages\n" "containing an arbitary number of bytes to be received from nearby robots. The\n" "implementation is very basic and any concepts such as throughput, addressing,\n" "or formatting of a message's contents is beyond the scope of this sensor's\n" "implementation\n\n" "This sensor is enabled by default.\n\n" "REQUIRED XML CONFIGURATION\n\n" " <controllers>\n" " ...\n" " <my_controller ...>\n" " ...\n" " <sensors>\n" " ...\n" " <radios implementation=\"default\" medium=\"radios\" />\n" " ...\n" " </sensors>\n" " ...\n" " </my_controller>\n" " ...\n" " </controllers>\n\n" "The 'medium' attribute sets the id of the radio medium declared in the <media>\n" "XML section.\n\n" "OPTIONAL XML CONFIGURATION\n\n" "None.\n", "Usable" ); }
CRadiosDefaultSensor::Reset() { for(SInterface& s_interface : m_vecInterfaces) { s_interface.Data.clear(); } }
function_block-function_prefixed
[ { "content": " class CRadiosDefaultSensor;\n\n}\n\n\n\n#include <argos3/core/simulator/sensor.h>\n\n#include <argos3/plugins/robots/generic/control_interface/ci_radios_sensor.h>\n\n#include <argos3/plugins/simulator/entities/radio_equipped_entity.h>\n\n\n\nnamespace argos {\n\n\n", "file_path": "argos3/sr...
C++
Studio/src/Application/Groom/GroomTool.cc
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
#include <iostream> #include <QXmlStreamWriter> #include <QTemporaryFile> #include <QFileDialog> #include <QMessageBox> #include <QThread> #include <Groom/GroomTool.h> #include <Visualization/ShapeworksWorker.h> #include <Data/Project.h> #include <Data/Mesh.h> #include <Data/Shape.h> #include <ui_GroomTool.h> GroomTool::GroomTool(Preferences& prefs, std::vector<std::string>& files) : preferences_(prefs), files_(files) { this->ui_ = new Ui_GroomTool; this->ui_->setupUi(this); qRegisterMetaType<std::string>(); } GroomTool::~GroomTool() {} void GroomTool::on_antialias_checkbox_stateChanged(int state) { this->ui_->antialias_groupbox->setEnabled(state); } void GroomTool::on_blur_checkbox_stateChanged(int state) { this->ui_->blur_groupbox->setEnabled(state); } void GroomTool::on_autopad_checkbox_stateChanged(int state) { this->ui_->pad_groupbox->setEnabled(state); } void GroomTool::handle_error(std::string msg) { emit error_message(msg); this->ui_->run_groom_button->setEnabled(true); this->ui_->skipButton->setEnabled(true); } void GroomTool::handle_progress(int val) { emit progress(static_cast<size_t>(val)); } void GroomTool::on_restoreDefaults_clicked() { this->preferences_.delete_entry("groom_center"); this->preferences_.delete_entry("groom_antialias"); this->preferences_.delete_entry("groom_pad"); this->preferences_.delete_entry("groom_fastmarching"); this->preferences_.delete_entry("groom_blur"); this->preferences_.delete_entry("groom_isolate"); this->preferences_.delete_entry("groom_antialias_amount"); this->preferences_.delete_entry("groom_fill_holes"); this->preferences_.delete_entry("groom_blur_sigma"); this->preferences_.delete_entry("groom_pad_value"); this->preferences_.restore_defaults(); this->set_preferences(); qApp->processEvents(); this->preferences_.set_saved(false); } void GroomTool::set_preferences() { this->ui_->center_checkbox->setChecked( this->preferences_.get_preference("groom_center", this->ui_->center_checkbox->isChecked())); this->ui_->antialias_checkbox->setChecked( this->preferences_.get_preference("groom_antialias", this->ui_->antialias_checkbox->isChecked())); this->ui_->autopad_checkbox->setChecked( this->preferences_.get_preference("groom_pad", this->ui_->autopad_checkbox->isChecked())); this->ui_->fastmarching_checkbox->setChecked( this->preferences_.get_preference("groom_fastmarching", this->ui_->fastmarching_checkbox->isChecked())); this->ui_->blur_checkbox->setChecked( this->preferences_.get_preference("groom_blur", this->ui_->blur_checkbox->isChecked())); this->ui_->isolate_checkbox->setChecked( this->preferences_.get_preference("groom_isolate", this->ui_->isolate_checkbox->isChecked())); this->ui_->fill_holes_checkbox->setChecked( this->preferences_.get_preference("groom_fill_holes", this->ui_->fill_holes_checkbox->isChecked())); this->ui_->antialias_iterations->setValue( this->preferences_.get_preference("groom_antialias_amount", this->ui_->antialias_iterations->value())); this->ui_->blur_sigma->setValue( this->preferences_.get_preference("groom_blur_sigma", this->ui_->blur_sigma->value())); this->ui_->padding_amount->setValue( this->preferences_.get_preference("groom_pad_value", this->ui_->padding_amount->value())); } void GroomTool::disableActions() { this->ui_->skipButton->setEnabled(false); this->ui_->run_groom_button->setEnabled(false); } void GroomTool::enableActions() { this->ui_->skipButton->setEnabled(true); this->ui_->run_groom_button->setEnabled(true); } void GroomTool::update_preferences() { this->preferences_.set_preference("groom_center", this->ui_->center_checkbox->isChecked()); this->preferences_.set_preference("groom_antialias", this->ui_->antialias_checkbox->isChecked()); this->preferences_.set_preference("groom_pad", this->ui_->autopad_checkbox->isChecked()); this->preferences_.set_preference("groom_fastmarching", this->ui_->fastmarching_checkbox->isChecked()); this->preferences_.set_preference("groom_blur", this->ui_->blur_checkbox->isChecked()); this->preferences_.set_preference("groom_isolate", this->ui_->isolate_checkbox->isChecked()); this->preferences_.set_preference("groom_fill_holes", this->ui_->fill_holes_checkbox->isChecked()); this->preferences_.set_preference("groom_antialias_amount", this->ui_->antialias_iterations->value()); this->preferences_.set_preference("groom_blur_sigma", this->ui_->blur_sigma->value()); this->preferences_.set_preference("groom_pad_value", this->ui_->padding_amount->value()); } void GroomTool::on_run_groom_button_clicked() { this->update_preferences(); emit message("Please wait: running groom step..."); emit progress(5); auto shapes = this->project_->get_shapes(); std::vector<ImageType::Pointer> imgs; for (auto s : shapes) { imgs.push_back(s->get_original_image()); } this->groom_ = new QGroom(this, imgs, 0., 1., this->ui_->blur_sigma->value(), this->ui_->padding_amount->value(), this->ui_->antialias_iterations->value(), true); emit progress(15); if (this->ui_->center_checkbox->isChecked()) { this->groom_->queueTool("center"); } if (this->ui_->isolate_checkbox->isChecked()) { this->groom_->queueTool("isolate"); } if (this->ui_->fill_holes_checkbox->isChecked()) { this->groom_->queueTool("hole_fill"); } if (this->ui_->autopad_checkbox->isChecked()) { this->groom_->queueTool("auto_pad"); } if (this->ui_->antialias_checkbox->isChecked()) { this->groom_->queueTool("antialias"); } if (this->ui_->fastmarching_checkbox->isChecked()) { this->groom_->queueTool("fastmarching"); } if (this->ui_->blur_checkbox->isChecked()) { this->groom_->queueTool("blur"); } emit progress(10); this->ui_->run_groom_button->setEnabled(false); this->ui_->skipButton->setEnabled(false); QThread* thread = new QThread; ShapeworksWorker* worker = new ShapeworksWorker( ShapeworksWorker::GroomType, this->groom_, nullptr, this->project_); worker->moveToThread(thread); connect(thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(result_ready()), this, SLOT(handle_thread_complete())); connect(this->groom_, SIGNAL(progress(int)), this, SLOT(handle_progress(int))); connect(worker, SIGNAL(error_message(std::string)), this, SLOT(handle_error(std::string))); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); thread->start(); } void GroomTool::handle_thread_complete() { emit progress(95); this->project_->load_groomed_images(this->groom_->getImages(), this->ui_->fastmarching_checkbox->isChecked() ? 0. : 0.5); emit progress(100); emit message("Groom Complete"); emit groom_complete(); this->ui_->run_groom_button->setEnabled(true); this->ui_->skipButton->setEnabled(true); } void GroomTool::set_project(QSharedPointer<Project> project) { this->project_ = project; } void GroomTool::on_skipButton_clicked() { this->update_preferences(); auto shapes = this->project_->get_shapes(); std::vector<ImageType::Pointer> imgs; for (auto s : shapes) { imgs.push_back(s->get_original_image()); } this->project_->load_groomed_images(imgs, 0.); emit message("Skipped groom."); emit groom_complete(); }
#include <iostream> #include <QXmlStreamWriter> #include <QTemporaryFile> #include <QFileDialog> #include <QMessageBox> #include <QThread> #include <Groom/GroomTool.h> #include <Visualization/ShapeworksWorker.h> #include <Data/Project.h> #include <Data/Mesh.h> #include <Data/Shape.h> #include <ui_GroomTool.h>
GroomTool::~GroomTool() {} void GroomTool::on_antialias_checkbox_stateChanged(int state) { this->ui_->antialias_groupbox->setEnabled(state); } void GroomTool::on_blur_checkbox_stateChanged(int state) { this->ui_->blur_groupbox->setEnabled(state); } void GroomTool::on_autopad_checkbox_stateChanged(int state) { this->ui_->pad_groupbox->setEnabled(state); } void GroomTool::handle_error(std::string msg) { emit error_message(msg); this->ui_->run_groom_button->setEnabled(true); this->ui_->skipButton->setEnabled(true); } void GroomTool::handle_progress(int val) { emit progress(static_cast<size_t>(val)); } void GroomTool::on_restoreDefaults_clicked() { this->preferences_.delete_entry("groom_center"); this->preferences_.delete_entry("groom_antialias"); this->preferences_.delete_entry("groom_pad"); this->preferences_.delete_entry("groom_fastmarching"); this->preferences_.delete_entry("groom_blur"); this->preferences_.delete_entry("groom_isolate"); this->preferences_.delete_entry("groom_antialias_amount"); this->preferences_.delete_entry("groom_fill_holes"); this->preferences_.delete_entry("groom_blur_sigma"); this->preferences_.delete_entry("groom_pad_value"); this->preferences_.restore_defaults(); this->set_preferences(); qApp->processEvents(); this->preferences_.set_saved(false); } void GroomTool::set_preferences() { this->ui_->center_checkbox->setChecked( this->preferences_.get_preference("groom_center", this->ui_->center_checkbox->isChecked())); this->ui_->antialias_checkbox->setChecked( this->preferences_.get_preference("groom_antialias", this->ui_->antialias_checkbox->isChecked())); this->ui_->autopad_checkbox->setChecked( this->preferences_.get_preference("groom_pad", this->ui_->autopad_checkbox->isChecked())); this->ui_->fastmarching_checkbox->setChecked( this->preferences_.get_preference("groom_fastmarching", this->ui_->fastmarching_checkbox->isChecked())); this->ui_->blur_checkbox->setChecked( this->preferences_.get_preference("groom_blur", this->ui_->blur_checkbox->isChecked())); this->ui_->isolate_checkbox->setChecked( this->preferences_.get_preference("groom_isolate", this->ui_->isolate_checkbox->isChecked())); this->ui_->fill_holes_checkbox->setChecked( this->preferences_.get_preference("groom_fill_holes", this->ui_->fill_holes_checkbox->isChecked())); this->ui_->antialias_iterations->setValue( this->preferences_.get_preference("groom_antialias_amount", this->ui_->antialias_iterations->value())); this->ui_->blur_sigma->setValue( this->preferences_.get_preference("groom_blur_sigma", this->ui_->blur_sigma->value())); this->ui_->padding_amount->setValue( this->preferences_.get_preference("groom_pad_value", this->ui_->padding_amount->value())); } void GroomTool::disableActions() { this->ui_->skipButton->setEnabled(false); this->ui_->run_groom_button->setEnabled(false); } void GroomTool::enableActions() { this->ui_->skipButton->setEnabled(true); this->ui_->run_groom_button->setEnabled(true); } void GroomTool::update_preferences() { this->preferences_.set_preference("groom_center", this->ui_->center_checkbox->isChecked()); this->preferences_.set_preference("groom_antialias", this->ui_->antialias_checkbox->isChecked()); this->preferences_.set_preference("groom_pad", this->ui_->autopad_checkbox->isChecked()); this->preferences_.set_preference("groom_fastmarching", this->ui_->fastmarching_checkbox->isChecked()); this->preferences_.set_preference("groom_blur", this->ui_->blur_checkbox->isChecked()); this->preferences_.set_preference("groom_isolate", this->ui_->isolate_checkbox->isChecked()); this->preferences_.set_preference("groom_fill_holes", this->ui_->fill_holes_checkbox->isChecked()); this->preferences_.set_preference("groom_antialias_amount", this->ui_->antialias_iterations->value()); this->preferences_.set_preference("groom_blur_sigma", this->ui_->blur_sigma->value()); this->preferences_.set_preference("groom_pad_value", this->ui_->padding_amount->value()); } void GroomTool::on_run_groom_button_clicked() { this->update_preferences(); emit message("Please wait: running groom step..."); emit progress(5); auto shapes = this->project_->get_shapes(); std::vector<ImageType::Pointer> imgs; for (auto s : shapes) { imgs.push_back(s->get_original_image()); } this->groom_ = new QGroom(this, imgs, 0., 1., this->ui_->blur_sigma->value(), this->ui_->padding_amount->value(), this->ui_->antialias_iterations->value(), true); emit progress(15); if (this->ui_->center_checkbox->isChecked()) { this->groom_->queueTool("center"); } if (this->ui_->isolate_checkbox->isChecked()) { this->groom_->queueTool("isolate"); } if (this->ui_->fill_holes_checkbox->isChecked()) { this->groom_->queueTool("hole_fill"); } if (this->ui_->autopad_checkbox->isChecked()) { this->groom_->queueTool("auto_pad"); } if (this->ui_->antialias_checkbox->isChecked()) { this->groom_->queueTool("antialias"); } if (this->ui_->fastmarching_checkbox->isChecked()) { this->groom_->queueTool("fastmarching"); } if (this->ui_->blur_checkbox->isChecked()) { this->groom_->queueTool("blur"); } emit progress(10); this->ui_->run_groom_button->setEnabled(false); this->ui_->skipButton->setEnabled(false); QThread* thread = new QThread; ShapeworksWorker* worker = new ShapeworksWorker( ShapeworksWorker::GroomType, this->groom_, nullptr, this->project_); worker->moveToThread(thread); connect(thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(result_ready()), this, SLOT(handle_thread_complete())); connect(this->groom_, SIGNAL(progress(int)), this, SLOT(handle_progress(int))); connect(worker, SIGNAL(error_message(std::string)), this, SLOT(handle_error(std::string))); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); thread->start(); } void GroomTool::handle_thread_complete() { emit progress(95); this->project_->load_groomed_images(this->groom_->getImages(), this->ui_->fastmarching_checkbox->isChecked() ? 0. : 0.5); emit progress(100); emit message("Groom Complete"); emit groom_complete(); this->ui_->run_groom_button->setEnabled(true); this->ui_->skipButton->setEnabled(true); } void GroomTool::set_project(QSharedPointer<Project> project) { this->project_ = project; } void GroomTool::on_skipButton_clicked() { this->update_preferences(); auto shapes = this->project_->get_shapes(); std::vector<ImageType::Pointer> imgs; for (auto s : shapes) { imgs.push_back(s->get_original_image()); } this->project_->load_groomed_images(imgs, 0.); emit message("Skipped groom."); emit groom_complete(); }
GroomTool::GroomTool(Preferences& prefs, std::vector<std::string>& files) : preferences_(prefs), files_(files) { this->ui_ = new Ui_GroomTool; this->ui_->setupUi(this); qRegisterMetaType<std::string>(); }
function_block-full_function
[ { "content": "// Constrained Delaunay Triangulation types\n\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n\n#include <CGAL/Constrained_triangulation_plus_2.h>\n\n\n\n// Axis-align boxes for all-pairs self-intersection detection\n\n#include <CGAL/point_generators_3.h>\n\n#include <CGAL/Bbox_3.h>\n\n#i...
C++
owGame/M2/M2_AnimatorComponent.cpp
Chaos192/OpenWow
1d91a51fafeedadc67122a3e9372ec4637a48434
#include "stdafx.h" #include "M2.h" #include "M2_Base_Instance.h" #include "M2_AnimatorComponent.h" CM2AnimatorComponent::CM2AnimatorComponent(const CM2_Base_Instance& OwnerNode) : CSceneNodeComponentBase(OwnerNode) , m_CurrentAnimationID(EAnimationID::Stand) , m_CurrentAnimation(nullptr) , m_IsLoop(false) , m_IsStopped(false) , m_AnimTime(0.0) , m_CurrentTime(0) { } CM2AnimatorComponent::~CM2AnimatorComponent() { } void CM2AnimatorComponent::LoadAnimations() { const auto& sequences = GetM2OwnerNode().GetM2().getSkeleton().GetSequences(); for (uint16 j = 0; j < sequences.size(); j++) { const auto& sequence = sequences[j]; if (sequence.variationIndex == 0) { const DBC_AnimationDataRecord* dbcAnimationRecord = GetBaseManager().GetManager<CDBCStorage>()->DBC_AnimationData()[sequence.__animID]; if (dbcAnimationRecord == nullptr) throw CException("CM2AnimatorComponent::CM2AnimatorComponent: Sequence '%d' not found in 'DBC_AnimationData'.", sequence.__animID); m_Animations.insert(std::make_pair(sequence.__animID, MakeShared(CM2_Animation, GetM2OwnerNode().GetM2(), sequence, dbcAnimationRecord->Get_Name(), j))); } } _ASSERT(m_Animations.size() > 0); PlayAnimation(m_CurrentAnimationID, true); } void CM2AnimatorComponent::PlayAnimation(EAnimationID AnimationId, bool Loop) { if (Loop && m_CurrentAnimationID == AnimationId && m_CurrentAnimation && m_CurrentAnimation->getAnimID() == AnimationId) return; const auto& animIt = m_Animations.find((uint16)AnimationId); if (animIt != m_Animations.end()) { m_CurrentAnimationID = AnimationId; m_CurrentAnimation = animIt->second.get(); } else { m_CurrentAnimationID = EAnimationID::Stand; m_CurrentAnimation = m_Animations.begin()->second.get(); } m_IsLoop = Loop; m_IsStopped = false; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getStart(); } void CM2AnimatorComponent::SetAnimationEventListener(std::shared_ptr<IM2AnimationEventsListener> M2AnimationEventListener) { m_M2AnimationEventListener = M2AnimationEventListener; } void CM2AnimatorComponent::PrintList() { for (auto& it : m_Animations) { Log::Warn("[%d] is [%s]", it.first, it.second->getAnimationName().c_str()); } } void CM2AnimatorComponent::Update(const UpdateEventArgs & e) { if (m_CurrentAnimation == nullptr) return; if (m_IsStopped) return; m_AnimTime += e.DeltaTime; m_CurrentTime = m_CurrentAnimation->getStart() + static_cast<uint32>(m_AnimTime); if (m_CurrentTime < m_CurrentAnimation->getEnd()) { return; } if (auto animationEventListener = m_M2AnimationEventListener.lock()) animationEventListener->OnAnimationEnded(m_CurrentAnimationID); if (m_IsLoop) { m_IsStopped = false; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getStart(); } else { m_IsStopped = true; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getEnd() - 1; } } const CM2_Base_Instance & CM2AnimatorComponent::GetM2OwnerNode() const { return dynamic_cast<const CM2_Base_Instance&>(GetOwnerNode()); }
#include "stdafx.h" #include "M2.h" #include "M2_Base_Instance.h" #include "M2_AnimatorComponent.h" CM2AnimatorComponent::CM2AnimatorComponent(const CM2_Base_Instance& OwnerNode) : CSceneNodeComponentBase(OwnerNode) , m_CurrentAnimationID(EAnimationID::Stand) , m_CurrentAnimation(nullptr) , m_IsLoop(false) , m_IsStopped(false) , m_AnimTime(0.0) , m_CurrentTime(0) { } CM2AnimatorComponent::~CM2AnimatorComponent() { } void CM2AnimatorComponent::LoadAnimations() { const auto& sequences = GetM2OwnerNode().GetM2().getSkeleton().GetSequences(); for (uint16 j = 0; j < sequences.size(); j++) { const auto& sequence = sequences[j]; if (sequence.variationIndex == 0) { const DBC_AnimationDataRecord* dbcAnimationRecord = GetBaseManager().GetManager<CDBCStorage>()->DBC_AnimationData()[sequence.__animID]; if (dbcAnimationRecord == nullptr) throw CException("CM2AnimatorComponent::CM2AnimatorComponent: Sequence '%d' not found in 'DBC_AnimationData'.", sequence.__animID); m_Animations.insert(std::make_pair(sequence.__animID, MakeShared(CM2_Animation, GetM2OwnerNode().GetM2(), sequence, dbcAnimationRecord->Get_Name(), j))); } } _ASSERT(m_Animations.size() > 0); PlayAnimation(m_CurrentAnimationID, true); } void CM2AnimatorComponent::PlayAnimation(EAnimationID AnimationId, bool Loop) { if (Loop && m_CurrentAnimationID == AnimationId && m_CurrentAnimation && m_CurrentAnimation->getAnimID() == AnimationId) return; const auto& animIt = m_Animations.find((uint16)AnimationId); if (animIt != m_Animations.end()) { m_CurrentAnimationID = AnimationId; m_CurrentAnimation = animIt->second.get(); } else { m_CurrentAnimationID = EAnimationID::Stand; m_CurrentAnimation = m_Animations.begin()->second.get(); } m_IsLoop = Loop; m_IsStopped = false; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getStart(); } void CM2AnimatorComponent::SetAnimationEventListener(std::shared_ptr<IM2AnimationEventsListener> M2AnimationEventListener) { m_M2AnimationEventListener = M2AnimationEventListener; } void CM2AnimatorComponent::PrintList() { for (auto& it : m_Animations) { Log::Warn("[%d] is [%s]", it.first, it.second->getAnimationName().c_str()); } }
const CM2_Base_Instance & CM2AnimatorComponent::GetM2OwnerNode() const { return dynamic_cast<const CM2_Base_Instance&>(GetOwnerNode()); }
void CM2AnimatorComponent::Update(const UpdateEventArgs & e) { if (m_CurrentAnimation == nullptr) return; if (m_IsStopped) return; m_AnimTime += e.DeltaTime; m_CurrentTime = m_CurrentAnimation->getStart() + static_cast<uint32>(m_AnimTime); if (m_CurrentTime < m_CurrentAnimation->getEnd()) { return; } if (auto animationEventListener = m_M2AnimationEventListener.lock()) animationEventListener->OnAnimationEnded(m_CurrentAnimationID); if (m_IsLoop) { m_IsStopped = false; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getStart(); } else { m_IsStopped = true; m_AnimTime = 0.0; m_CurrentTime = m_CurrentAnimation->getEnd() - 1; } }
function_block-full_function
[ { "content": "enum Opcodes : uint16\n\n{\n\n\tNULL_ACTION = 0x000,\n\n\tCMSG_BOOTME = 0x001,\n\n\tCMSG_DBLOOKUP = 0x002,\n\n\tSMSG_DBLOOKUP = 0x003,\n\n\tCMSG_QUERY_OBJECT_POSITION = 0x004,\n\n\tSMSG_QUERY_OBJECT_POSITION = 0x005,\n\n\tCMSG_QUERY_OBJECT_ROTATION = 0x006,\n\n\tSMSG_QUERY_OBJECT_ROTATION = 0x007,...
C++
src/mame/audio/dsbz80.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
#include "emu.h" #include "audio/dsbz80.h" #include "machine/clock.h" #define Z80_TAG "mpegcpu" void dsbz80_device::dsbz80_map(address_map &map) { map(0x0000, 0x7fff).rom().region(":mpegcpu", 0); map(0x8000, 0xffff).ram(); } void dsbz80_device::dsbz80io_map(address_map &map) { map.global_mask(0xff); map(0xe0, 0xe0).w(FUNC(dsbz80_device::mpeg_trigger_w)); map(0xe2, 0xe4).rw(FUNC(dsbz80_device::mpeg_pos_r), FUNC(dsbz80_device::mpeg_start_w)); map(0xe5, 0xe7).w(FUNC(dsbz80_device::mpeg_end_w)); map(0xe8, 0xe8).w(FUNC(dsbz80_device::mpeg_volume_w)); map(0xe9, 0xe9).w(FUNC(dsbz80_device::mpeg_stereo_w)); map(0xf0, 0xf1).rw("uart", FUNC(i8251_device::read), FUNC(i8251_device::write)); } DEFINE_DEVICE_TYPE(DSBZ80, dsbz80_device, "dsbz80_device", "Sega Z80-based Digital Sound Board") void dsbz80_device::device_add_mconfig(machine_config &config) { Z80(config, m_ourcpu, 4000000); m_ourcpu->set_addrmap(AS_PROGRAM, &dsbz80_device::dsbz80_map); m_ourcpu->set_addrmap(AS_IO, &dsbz80_device::dsbz80io_map); I8251(config, m_uart, 4000000); m_uart->rxrdy_handler().set_inputline(m_ourcpu, INPUT_LINE_IRQ0); m_uart->txd_handler().set(FUNC(dsbz80_device::output_txd)); clock_device &uart_clock(CLOCK(config, "uart_clock", 500000)); uart_clock.signal_handler().set("uart", FUNC(i8251_device::write_rxc)); uart_clock.signal_handler().append("uart", FUNC(i8251_device::write_txc)); } dsbz80_device::dsbz80_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, DSBZ80, tag, owner, clock), device_sound_interface(mconfig, *this), m_ourcpu(*this, Z80_TAG), m_uart(*this, "uart"), m_rxd_handler(*this) { } void dsbz80_device::device_start() { m_rxd_handler.resolve_safe(); uint8_t *rom_base = machine().root_device().memregion("mpeg")->base(); decoder = new mpeg_audio(rom_base, mpeg_audio::L2, false, 0); stream_alloc(0, 2, 32000); } void dsbz80_device::device_reset() { start = end = 0; audio_pos = audio_avail = 0; memset(audio_buf, 0, sizeof(audio_buf)); mp_state = 0; m_uart->write_cts(0); } WRITE_LINE_MEMBER(dsbz80_device::write_txd) { m_uart->write_rxd(state); } WRITE_LINE_MEMBER(dsbz80_device::output_txd) { m_rxd_handler(state); } void dsbz80_device::mpeg_trigger_w(uint8_t data) { mp_state = data; if (data == 0) { mp_state = 0; audio_pos = audio_avail = 0; } else if (data == 1) { mp_pos = mp_start*8; } else if (data == 2) { mp_pos = mp_start*8; } } uint8_t dsbz80_device::mpeg_pos_r(offs_t offset) { int mp_prg = mp_pos >> 3; switch (offset) { case 0: return (mp_prg>>16)&0xff; case 1: return (mp_prg>>8)&0xff; case 2: return mp_prg&0xff; } return 0; } void dsbz80_device::mpeg_start_w(offs_t offset, uint8_t data) { switch (offset) { case 0: start &= 0x00ffff; start |= (int)data<<16; break; case 1: start &= 0xff00ff; start |= (int)data<<8; break; case 2: start &= 0xffff00; start |= data; if (mp_state == 0) { mp_start = start; } else { lp_start = start; if (lp_end == 0) { } else { } } break; } } void dsbz80_device::mpeg_end_w(offs_t offset, uint8_t data) { switch (offset) { case 0: end &= 0x00ffff; end |= (int)data<<16; break; case 1: end &= 0xff00ff; end |= (int)data<<8; break; case 2: end &= 0xffff00; end |= data; if (mp_state == 0) { mp_end = end; } else { lp_end = end; } break; } } void dsbz80_device::mpeg_volume_w(uint8_t data) { mp_vol = 0x7f - data; } void dsbz80_device::mpeg_stereo_w(uint8_t data) { mp_pan = data & 3; } void dsbz80_device::sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs) { auto &out_l = outputs[0]; auto &out_r = outputs[1]; int samples = out_l.samples(); int sampindex = 0; for(;;) { while(samples && audio_pos < audio_avail) { switch (mp_pan) { case 0: out_l.put_int(sampindex, audio_buf[audio_pos*2], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); sampindex++; break; case 1: out_l.put_int(sampindex, audio_buf[audio_pos*2], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2], 32768); sampindex++; break; case 2: out_l.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); sampindex++; break; } audio_pos++; samples--; } if(!samples) { break; } if(mp_state == 0) { out_l.fill(0, sampindex); out_r.fill(0, sampindex); break; } else { int sample_rate, channel_count; bool ok = decoder->decode_buffer(mp_pos, mp_end*8, audio_buf, audio_avail, sample_rate, channel_count); if (ok) { audio_pos = 0; } else { if(mp_state == 2) { if (mp_pos == lp_start*8) { mp_state = 0; } mp_pos = lp_start*8; if (lp_end) { mp_end = lp_end; } } else { mp_state = 0; } } } } }
#include "emu.h" #include "audio/dsbz80.h" #include "machine/clock.h" #define Z80_TAG "mpegcpu" void dsbz80_device::dsbz80_map(address_map &map) { map(0x0000, 0x7fff).rom().region(":mpegcpu", 0); map(0x8000, 0xffff).ram(); } void dsbz80_device::dsbz80io_map(address_map &map) { map.global_mask(0xff); map(0xe0, 0xe0).w(FUNC(dsbz80_device::mpeg_trigger_w)); map(0xe2, 0xe4).rw(FUNC(dsbz80_device::mpeg_pos_r), FUNC(dsbz80_device::mpeg_start_w)); map(0xe5, 0xe7).w(FUNC(dsbz80_device::mpeg_end_w)); map(0xe8, 0xe8).w(FUNC(dsbz80_device::mpeg_volume_w)); map(0xe9, 0xe9).w(FUNC(dsbz80_device::mpeg_stereo_w)); map(0xf0, 0xf1).rw("uart", FUNC(i8251_device::read), FUNC(i8251_device::write)); } DEFINE_DEVICE_TYPE(DSBZ80, dsbz80_device, "dsbz80_device", "Sega Z80-based Digital Sound Board") void dsbz80_device::device_add_mconfig(machine_config &config) { Z80(config, m_ourcpu, 4000000); m_ourcpu->set_addrmap(AS_PROGRAM, &dsbz80_device::dsbz80_map); m_ourcpu->set_addrmap(AS_IO, &dsbz80_device::dsbz80io_map); I8251(config, m_uart, 4000000); m_uart->rxrdy_handler().set_inputline(m_ourcpu, INPUT_LINE_IRQ0); m_uart->txd_handler().set(FUNC(dsbz80_device::output_txd)); clock_device &uart_clock(CLOCK(config, "uart_clock", 500000)); uart_clock.signal_handler().set("uart", FUNC(i8251_device::write_rxc)); uart_clock.signal_handler().append("uart", FUNC(i8251_device::write_txc)); } dsbz80_device::dsbz80_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, DSBZ80, tag, owner, clock), device_sound_interface(mconfig, *this), m_ourcpu(*this, Z80_TAG), m_uart(*this, "uart"), m_rxd_handler(*this) { } void dsbz80_device::device_start() { m_rxd_handler.resolve_safe(); uint8_t *rom_base = machine().root_device().memregion("mpeg")->base(); decoder = new mpeg_audio(rom_base, mpeg_audio::L2, false, 0); stream_alloc(0, 2, 32000); } void dsbz80_device::device_reset() { start = end = 0; audio_pos = audio_avail = 0; memset(audio_buf, 0, sizeof(audio_buf)); mp_state = 0; m_uart->write_cts(0); } WRITE_LINE_MEMBER(dsbz80_device::write_txd) { m_uart->write_rxd(state); } WRITE_LINE_MEMBER(dsbz80_device::output_txd) { m_rxd_handler(state); } void dsbz80_device::mpeg_trigger_w(uint8_t data) { mp_state = data; if (data == 0) { mp_state = 0; audio_pos = audio_avail = 0; } else if (data == 1) { mp_pos = mp_start*8; } else if (data == 2) { mp_pos = mp_start*8; } } uint8_t dsbz80_device::mpeg_pos_r(offs_t offset) { int mp_prg = mp_pos >> 3; switch (offset) { case 0: return (mp_prg>>16)&0xff; case 1: return (mp_prg>>8)&0xff; case 2: return mp_prg&0xff; } return 0; } void dsbz80_device::mpeg_start_w(offs_t offset, uint8_t data) { switch (offset) { case 0: start &= 0x00ffff; start |= (int)data<<16; break; case 1: start &= 0xff00ff; start |= (int)data<<8; break; case 2: start &= 0xffff00; start |= data; if (mp_state == 0) { mp_start = start; } else { lp_start = start; if (lp_end == 0) { } else { } } break; } } void dsbz80_device::mpeg_end_w(offs_t offset, uint8_t data) { switch (offset) { case 0: end &= 0x00ffff; end |= (int)data<<16; break; case 1: end &= 0xff00ff; end |= (int)data<<8; break; case 2: end &= 0xffff00; end |= data; if (mp_state == 0) { mp_end = end; } else { lp_end = end; } break; } } void dsbz80_device::mpeg_volume_w(uint8_t data) { mp_vol = 0x7f - data; } void dsbz80_device::mpeg_stereo_w(uint8_t data) { mp_pan = data & 3; } void dsbz80_device::sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs) { auto &out_l = outputs[0]; auto &out_r = outputs[1]; int samples = out_l.samples(); int sampindex = 0; for(;;) { while(samples && audio_pos < audio_avail) { switch (mp_pan) { case 0: out_l.put_int(sampindex, audio_buf[audio_pos*2], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); sampindex++; break; case 1: out_l.put_int(sampindex, audio_buf[audio_pos*2], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2], 32768); sampindex++;
ampindex++; break; } audio_pos++; samples--; } if(!samples) { break; } if(mp_state == 0) { out_l.fill(0, sampindex); out_r.fill(0, sampindex); break; } else { int sample_rate, channel_count; bool ok = decoder->decode_buffer(mp_pos, mp_end*8, audio_buf, audio_avail, sample_rate, channel_count); if (ok) { audio_pos = 0; } else { if(mp_state == 2) { if (mp_pos == lp_start*8) { mp_state = 0; } mp_pos = lp_start*8; if (lp_end) { mp_end = lp_end; } } else { mp_state = 0; } } } } }
break; case 2: out_l.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); out_r.put_int(sampindex, audio_buf[audio_pos*2+1], 32768); s
random
[]
C++
Charts/Core/Testing/Cxx/TestPlotBarRangeHandlesItem.cxx
cclauss/VTK
f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d
#include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkContextInteractorStyle.h> #include <vtkContextScene.h> #include <vtkIntArray.h> #include <vtkInteractorEventRecorder.h> #include <vtkNew.h> #include <vtkPlotBar.h> #include <vtkPlotBarRangeHandlesItem.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkTable.h> #include <iostream> #include <map> class vtkRangeHandlesCallBack : public vtkCommand { public: static vtkRangeHandlesCallBack* New() { return new vtkRangeHandlesCallBack; } void Execute(vtkObject* caller, unsigned long event, void* vtkNotUsed(callData)) override { vtkPlotRangeHandlesItem* self = vtkPlotRangeHandlesItem::SafeDownCast(caller); if (!self) { return; } if (event == vtkCommand::EndInteractionEvent) { self->GetHandlesRange(this->Range); } if (this->EventSpy.count(event) == 0) { this->EventSpy[event] = 0; } ++this->EventSpy[event]; std::cout << "InvokedEvent: " << event << this->EventSpy[event] << std::endl; } std::map<unsigned long, int> EventSpy; double Range[2]; }; int TestPlotBarRangeHandlesItem(int, char*[]) { vtkNew<vtkTable> table; vtkNew<vtkIntArray> arrMonth; arrMonth->SetName("Months"); arrMonth->SetNumberOfComponents(1); arrMonth->SetNumberOfTuples(12); for (int i = 0; i < arrMonth->GetNumberOfTuples(); ++i) { arrMonth->SetValue(i, i); } table->AddColumn(arrMonth); constexpr int books[12] = { 5675, 5902, 6388, 5990, 5575, 7393, 9878, 8082, 6417, 5946, 5526, 5166 }; vtkNew<vtkIntArray> arrBooks; arrBooks->SetName("Books"); arrBooks->SetNumberOfComponents(1); arrBooks->SetNumberOfTuples(12); for (int i = 0; i < arrBooks->GetNumberOfTuples(); ++i) { arrBooks->SetValue(i, books[i]); } table->AddColumn(arrBooks); vtkNew<vtkChartXY> chart; chart->GetAxis(vtkAxis::BOTTOM)->SetRange(-5, 15); chart->GetAxis(vtkAxis::LEFT)->SetRange(-5, 15); vtkNew<vtkContextScene> scene; scene->AddItem(chart); vtkNew<vtkContextInteractorStyle> interactorStyle; interactorStyle->SetScene(scene); vtkNew<vtkRenderWindowInteractor> iren; iren->SetInteractorStyle(interactorStyle); vtkNew<vtkInteractorEventRecorder> recorder; recorder->SetInteractor(iren); recorder->ReadFromInputStringOn(); vtkPlotBar* barPlot = vtkPlotBar::SafeDownCast(chart->AddPlot(vtkChart::BAR)); barPlot->SetInputData(table, "Months", "Books"); chart->SetBarWidthFraction(1.0); vtkNew<vtkPlotBarRangeHandlesItem> rangeItem; rangeItem->SetPlotBar(barPlot); rangeItem->SetExtent(0, 12, 0, 1); chart->AddPlot(rangeItem); rangeItem->ComputeHandlesDrawRange(); chart->RaisePlot(rangeItem); chart->Update(); vtkNew<vtkRangeHandlesCallBack> cbk; rangeItem->AddObserver(vtkCommand::StartInteractionEvent, cbk); rangeItem->AddObserver(vtkCommand::InteractionEvent, cbk); rangeItem->AddObserver(vtkCommand::EndInteractionEvent, cbk); double range[2]; rangeItem->GetHandlesRange(range); if (range[0] != 0 || range[1] != 12) { std::cerr << "Initialization: Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [0, 12]." << std::endl; return EXIT_FAILURE; } const char leftEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 0 10 0 0 0 0 0\n" "MouseMoveEvent 3 10 0 0 0 0 0\n" "LeftButtonReleaseEvent 3 10 0 0 0 0 0\n"; recorder->SetInputString(leftEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move left handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (fabs(range[0] - 2.5) > 1e-3 || range[1] != 12) { std::cerr << "Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [2.5, 12]." << std::endl; return EXIT_FAILURE; } cbk->EventSpy.clear(); const char rightEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 12 10 0 0 0 0 0\n" "MouseMoveEvent 10 10 0 0 0 0 0\n" "LeftButtonReleaseEvent 10 10 0 0 0 0 0\n"; recorder->SetInputString(rightEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move right handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (fabs(range[0] - 2.5) > 1e-3 || fabs(range[1] - 10.5) > 1e-3) { std::cerr << "Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [2.5, 10.5]." << std::endl; return EXIT_FAILURE; } barPlot->SetOrientation(vtkPlotBar::HORIZONTAL); rangeItem->SetHandleOrientationToHorizontal(); rangeItem->SetExtent(0, 12, 0, 1); rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (range[0] != 0 || range[1] != 12) { std::cerr << "Unexpected range in horizontal range handle: [" << range[0] << ", " << range[1] << "]. Expecting: [0, 12]." << std::endl; return EXIT_FAILURE; } cbk->EventSpy.clear(); const char hRightEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 1 12 0 0 0 0 0\n" "MouseMoveEvent 1 5 0 0 0 0 0\n" "LeftButtonReleaseEvent 1 5 0 0 0 0 0\n"; recorder->SetInputString(hRightEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move horizontal handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (range[0] != 0 || fabs(range[1] - 5.5) > 1e-3) { std::cerr << "Unexpected range for horizontal handle : [" << range[0] << ", " << range[1] << "]. Expecting : [0, 5.5]." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
#include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkContextInteractorStyle.h> #include <vtkContextScene.h> #include <vtkIntArray.h> #include <vtkInteractorEventRecorder.h> #include <vtkNew.h> #include <vtkPlotBar.h> #include <vtkPlotBarRangeHandlesItem.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkTable.h> #include <iostream> #include <map> class vtkRangeHandlesCallBack : public vtkCommand { public: static vtkRangeHandlesCallBack* New() { return new vtkRangeHandlesCallBack; } void Execute(vtkObject* caller, unsigned long event, void* vtkNotUsed(callData)) override { vtkPlotRangeHandlesItem* self = vtkPlotRangeH
ventSpy[event] = 0; } ++this->EventSpy[event]; std::cout << "InvokedEvent: " << event << this->EventSpy[event] << std::endl; } std::map<unsigned long, int> EventSpy; double Range[2]; }; int TestPlotBarRangeHandlesItem(int, char*[]) { vtkNew<vtkTable> table; vtkNew<vtkIntArray> arrMonth; arrMonth->SetName("Months"); arrMonth->SetNumberOfComponents(1); arrMonth->SetNumberOfTuples(12); for (int i = 0; i < arrMonth->GetNumberOfTuples(); ++i) { arrMonth->SetValue(i, i); } table->AddColumn(arrMonth); constexpr int books[12] = { 5675, 5902, 6388, 5990, 5575, 7393, 9878, 8082, 6417, 5946, 5526, 5166 }; vtkNew<vtkIntArray> arrBooks; arrBooks->SetName("Books"); arrBooks->SetNumberOfComponents(1); arrBooks->SetNumberOfTuples(12); for (int i = 0; i < arrBooks->GetNumberOfTuples(); ++i) { arrBooks->SetValue(i, books[i]); } table->AddColumn(arrBooks); vtkNew<vtkChartXY> chart; chart->GetAxis(vtkAxis::BOTTOM)->SetRange(-5, 15); chart->GetAxis(vtkAxis::LEFT)->SetRange(-5, 15); vtkNew<vtkContextScene> scene; scene->AddItem(chart); vtkNew<vtkContextInteractorStyle> interactorStyle; interactorStyle->SetScene(scene); vtkNew<vtkRenderWindowInteractor> iren; iren->SetInteractorStyle(interactorStyle); vtkNew<vtkInteractorEventRecorder> recorder; recorder->SetInteractor(iren); recorder->ReadFromInputStringOn(); vtkPlotBar* barPlot = vtkPlotBar::SafeDownCast(chart->AddPlot(vtkChart::BAR)); barPlot->SetInputData(table, "Months", "Books"); chart->SetBarWidthFraction(1.0); vtkNew<vtkPlotBarRangeHandlesItem> rangeItem; rangeItem->SetPlotBar(barPlot); rangeItem->SetExtent(0, 12, 0, 1); chart->AddPlot(rangeItem); rangeItem->ComputeHandlesDrawRange(); chart->RaisePlot(rangeItem); chart->Update(); vtkNew<vtkRangeHandlesCallBack> cbk; rangeItem->AddObserver(vtkCommand::StartInteractionEvent, cbk); rangeItem->AddObserver(vtkCommand::InteractionEvent, cbk); rangeItem->AddObserver(vtkCommand::EndInteractionEvent, cbk); double range[2]; rangeItem->GetHandlesRange(range); if (range[0] != 0 || range[1] != 12) { std::cerr << "Initialization: Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [0, 12]." << std::endl; return EXIT_FAILURE; } const char leftEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 0 10 0 0 0 0 0\n" "MouseMoveEvent 3 10 0 0 0 0 0\n" "LeftButtonReleaseEvent 3 10 0 0 0 0 0\n"; recorder->SetInputString(leftEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move left handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (fabs(range[0] - 2.5) > 1e-3 || range[1] != 12) { std::cerr << "Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [2.5, 12]." << std::endl; return EXIT_FAILURE; } cbk->EventSpy.clear(); const char rightEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 12 10 0 0 0 0 0\n" "MouseMoveEvent 10 10 0 0 0 0 0\n" "LeftButtonReleaseEvent 10 10 0 0 0 0 0\n"; recorder->SetInputString(rightEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move right handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (fabs(range[0] - 2.5) > 1e-3 || fabs(range[1] - 10.5) > 1e-3) { std::cerr << "Unexpected range for vertical handle: [" << range[0] << ", " << range[1] << "]. Expecting: [2.5, 10.5]." << std::endl; return EXIT_FAILURE; } barPlot->SetOrientation(vtkPlotBar::HORIZONTAL); rangeItem->SetHandleOrientationToHorizontal(); rangeItem->SetExtent(0, 12, 0, 1); rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (range[0] != 0 || range[1] != 12) { std::cerr << "Unexpected range in horizontal range handle: [" << range[0] << ", " << range[1] << "]. Expecting: [0, 12]." << std::endl; return EXIT_FAILURE; } cbk->EventSpy.clear(); const char hRightEvents[] = "# StreamVersion 1\n" "LeftButtonPressEvent 1 12 0 0 0 0 0\n" "MouseMoveEvent 1 5 0 0 0 0 0\n" "LeftButtonReleaseEvent 1 5 0 0 0 0 0\n"; recorder->SetInputString(hRightEvents); recorder->Play(); if (cbk->EventSpy[vtkCommand::StartInteractionEvent] != 1 || cbk->EventSpy[vtkCommand::InteractionEvent] != 1 || cbk->EventSpy[vtkCommand::EndInteractionEvent] != 1) { std::cerr << "Move horizontal handle: Wrong number of fired events : " << cbk->EventSpy[vtkCommand::StartInteractionEvent] << " " << cbk->EventSpy[vtkCommand::InteractionEvent] << " " << cbk->EventSpy[vtkCommand::EndInteractionEvent] << std::endl; return EXIT_FAILURE; } rangeItem->ComputeHandlesDrawRange(); rangeItem->GetHandlesRange(range); if (range[0] != 0 || fabs(range[1] - 5.5) > 1e-3) { std::cerr << "Unexpected range for horizontal handle : [" << range[0] << ", " << range[1] << "]. Expecting : [0, 5.5]." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
andlesItem::SafeDownCast(caller); if (!self) { return; } if (event == vtkCommand::EndInteractionEvent) { self->GetHandlesRange(this->Range); } if (this->EventSpy.count(event) == 0) { this->E
random
[]
C++
uuv_gazebo_plugins/uuv_gazebo_ros_plugins/src/ThrusterROSPlugin.cpp
MoMagDii/VAUV-simulator
56f55f9349e38e0a327a40feb5a437fcad511b00
#include <uuv_gazebo_ros_plugins/ThrusterROSPlugin.h> #include <string> #include <gazebo/physics/Base.hh> #include <gazebo/physics/Link.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <uuv_gazebo_ros_plugins_msgs/msg/float_stamped.hpp> namespace uuv_simulator_ros { ThrusterROSPlugin::ThrusterROSPlugin() { this->rosPublishPeriod = gazebo::common::Time(0.05); this->lastRosPublishTime = gazebo::common::Time(0.0); } ThrusterROSPlugin::~ThrusterROSPlugin() { #if GAZEBO_MAJOR_VERSION >= 8 this->rosPublishConnection.reset(); #else gazebo::event::Events::DisconnectWorldUpdateBegin( this->rosPublishConnection); #endif } void ThrusterROSPlugin::SetThrustReference( const uuv_gazebo_ros_plugins_msgs::msg::FloatStamped::SharedPtr _msg) { if (std::isnan(_msg->data)) { RCLCPP_WARN(myRosNode->get_logger(), "ThrusterROSPlugin: Ignoring nan command"); return; } this->inputCommand = _msg->data; } gazebo::common::Time ThrusterROSPlugin::GetRosPublishPeriod() { return this->rosPublishPeriod; } void ThrusterROSPlugin::SetRosPublishRate(double _hz) { if (_hz > 0.0) this->rosPublishPeriod = 1.0 / _hz; else this->rosPublishPeriod = 0.; } void ThrusterROSPlugin::Init() { ThrusterPlugin::Init(); } void ThrusterROSPlugin::Reset() { this->lastRosPublishTime.Set(0, 0); } void ThrusterROSPlugin::Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf) { using std::placeholders::_1; using std::placeholders::_2; try { ThrusterPlugin::Load(_parent, _sdf); } catch(gazebo::common::Exception &_e) { gzerr << "Error loading plugin." << "Please ensure that your model is correct." << '\n'; return; } if (!rclcpp::is_initialized()) { gzerr << "Not loading plugin since ROS has not been " << "properly initialized. Try starting gazebo with ros plugin:\n" << " gazebo -s libgazebo_ros_api_plugin.so\n"; return; } try { myRosNode = gazebo_ros::Node::CreateWithArgs(_sdf->Get<std::string>("name")); gzmsg << "[ThrusterROSPlugin] Node created with name: " << myRosNode->get_name() << ", with ns: " << myRosNode->get_namespace() << "\n"; mySet_thrust_force_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency>( myTopicPrefix + "set_thrust_force_efficiency", std::bind(&ThrusterROSPlugin::SetThrustForceEfficiency, this, _1, _2)); myGet_thrust_force_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency>( myTopicPrefix + "get_thrust_force_efficiency", std::bind(&ThrusterROSPlugin::GetThrustForceEfficiency, this, _1, _2)); mySet_dynamic_state_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency>( myTopicPrefix + "set_dynamic_state_efficiency", std::bind(&ThrusterROSPlugin::SetDynamicStateEfficiency, this, _1, _2)); myGet_dynamic_state_efficiency = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency>( myTopicPrefix + "get_dynamic_state_efficiency", std::bind(&ThrusterROSPlugin::GetDynamicStateEfficiency, this, _1, _2)); mySet_thruster_state = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState>( myTopicPrefix + "set_thruster_state", std::bind(&ThrusterROSPlugin::SetThrusterState, this, _1, _2)); myGet_thruster_state = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState>( myTopicPrefix + "get_thruster_state", std::bind(&ThrusterROSPlugin::GetThrusterState, this, _1, _2)); myGet_thruster_conversion_fcn = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn>( myTopicPrefix + "get_thruster_conversion_fcn", std::bind(&ThrusterROSPlugin::GetThrusterConversionFcn, this, _1, _2)); mySubThrustReference = myRosNode->create_subscription< uuv_gazebo_ros_plugins_msgs::msg::FloatStamped >(this->commandSubscriber->GetTopic(), 10, std::bind(&ThrusterROSPlugin::SetThrustReference, this, _1)); myPubThrust = myRosNode->create_publisher< uuv_gazebo_ros_plugins_msgs::msg::FloatStamped >(this->thrustTopicPublisher->GetTopic(), 10); myPubThrustWrench = myRosNode->create_publisher<geometry_msgs::msg::WrenchStamped>( this->thrustTopicPublisher->GetTopic() + "_wrench", 10); myPubThrusterState = myRosNode->create_publisher<std_msgs::msg::Bool>( myTopicPrefix + "is_on", 1); myPubThrustForceEff = myRosNode->create_publisher<std_msgs::msg::Float64>( myTopicPrefix + "thrust_efficiency", 1); myPubDynamicStateEff = myRosNode->create_publisher<std_msgs::msg::Float64>( myTopicPrefix + "dynamic_state_efficiency", 1); gzmsg << "Thruster #" << this->thrusterID << " initialized" << std::endl << "\t- Link: " << this->thrusterLink->GetName() << std::endl << "\t- Robot model: " << _parent->GetName() << std::endl << "\t- Input command topic: " << this->commandSubscriber->GetTopic() << std::endl << "\t- Thrust output topic: " << this->thrustTopicPublisher->GetTopic() << std::endl; this->rosPublishConnection = gazebo::event::Events::ConnectWorldUpdateBegin( std::bind(&ThrusterROSPlugin::RosPublishStates, this)); } catch(std::exception& e) { gzerr << "Exception when loading plugin: " << e.what() << "\n"; } } void ThrusterROSPlugin::RosPublishStates() { if (this->thrustForceStamp - this->lastRosPublishTime >= this->rosPublishPeriod) { this->lastRosPublishTime = this->thrustForceStamp; uuv_gazebo_ros_plugins_msgs::msg::FloatStamped thrustMsg; thrustMsg.header.stamp = myRosNode->now(); thrustMsg.header.frame_id = this->thrusterLink->GetName(); thrustMsg.data = this->thrustForce; myPubThrust->publish(thrustMsg); geometry_msgs::msg::WrenchStamped thrustWrenchMsg; thrustWrenchMsg.header.stamp = myRosNode->now(); thrustWrenchMsg.header.frame_id = this->thrusterLink->GetName(); ignition::math::Vector3d thrustVector = this->thrustForce * this->thrusterAxis; thrustWrenchMsg.wrench.force.x = thrustVector.X(); thrustWrenchMsg.wrench.force.y = thrustVector.Y(); thrustWrenchMsg.wrench.force.z = thrustVector.Z(); myPubThrustWrench->publish(thrustWrenchMsg); std_msgs::msg::Bool isOnMsg; isOnMsg.data = this->isOn; myPubThrusterState->publish(isOnMsg); std_msgs::msg::Float64 thrustEffMsg; thrustEffMsg.data = this->thrustEfficiency; myPubThrustForceEff->publish(thrustEffMsg); std_msgs::msg::Float64 dynStateEffMsg; dynStateEffMsg.data = this->propellerEfficiency; myPubDynamicStateEff->publish(dynStateEffMsg); } } void ThrusterROSPlugin::SetThrustForceEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Response::SharedPtr _res) { if (_req->efficiency < 0.0 || _req->efficiency > 1.0) { _res->success = false; } else { this->thrustEfficiency = _req->efficiency; _res->success = true; gzmsg << "Setting thrust efficiency at thruster " << this->thrusterLink->GetName() << "=" << _req->efficiency * 100 << "%" << std::endl; } } void ThrusterROSPlugin::GetThrustForceEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Response::SharedPtr _res) { _res->efficiency = this->thrustEfficiency; } void ThrusterROSPlugin::SetDynamicStateEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Response::SharedPtr _res) { if (_req->efficiency < 0.0 || _req->efficiency > 1.0) { _res->success = false; } else { this->propellerEfficiency = _req->efficiency; _res->success = true; gzmsg << "Setting propeller efficiency at thruster " << this->thrusterLink->GetName() << "=" << _req->efficiency * 100 << "%" << std::endl; } } void ThrusterROSPlugin::GetDynamicStateEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Response::SharedPtr _res) { _res->efficiency = this->propellerEfficiency; } void ThrusterROSPlugin::SetThrusterState( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState::Response::SharedPtr _res) { this->isOn = _req->on; gzmsg << "Turning thruster " << this->thrusterLink->GetName() << " " << (this->isOn ? "ON" : "OFF") << std::endl; _res->success = true; } void ThrusterROSPlugin::GetThrusterState( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState::Response::SharedPtr _res) { _res->is_on = this->isOn; } void ThrusterROSPlugin::GetThrusterConversionFcn( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn::Response::SharedPtr _res) { _res->fcn.function_name = this->conversionFunction->GetType(); double param; if (!_res->fcn.function_name.compare("Basic")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::Basic" << std::endl; _res->fcn.tags.push_back("rotor_constant"); this->conversionFunction->GetParam("rotor_constant", param); _res->fcn.data.push_back(param); } else if (!_res->fcn.function_name.compare("Bessa")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::Bessa" << std::endl; _res->fcn.tags.push_back("rotor_constant_l"); this->conversionFunction->GetParam("rotor_constant_l", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("rotor_constant_r"); this->conversionFunction->GetParam("rotor_constant_r", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("delta_l"); this->conversionFunction->GetParam("delta_l", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("delta_r"); this->conversionFunction->GetParam("delta_r", param); _res->fcn.data.push_back(param); } else if (!_res->fcn.function_name.compare("LinearInterp")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::LinearInterp" << std::endl; std::map<double, double> table = this->conversionFunction->GetTable(); for (auto& item : table) { gzmsg << item.first << " " << item.second << std::endl; _res->fcn.lookup_table_input.push_back(item.first); _res->fcn.lookup_table_output.push_back(item.second); } } } GZ_REGISTER_MODEL_PLUGIN(ThrusterROSPlugin) }
#include <uuv_gazebo_ros_plugins/ThrusterROSPlugin.h> #include <string> #include <gazebo/physics/Base.hh> #include <gazebo/physics/Link.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <uuv_gazebo_ros_plugins_msgs/msg/float_stamped.hpp> namespace uuv_simulator_ros { ThrusterROSPlugin::ThrusterROSPlugin() { this->rosPublishPeriod = gazebo::common::Time(0.05); this->lastRosPublishTime = gazebo::common::Time(0.0); } ThrusterROSPlugin::~ThrusterROSPlugin() { #if GAZEBO_MAJOR_VERSION >= 8 this->rosPublishConnection.reset(); #else gazebo::event::Events::DisconnectWorldUpdateBegin( this->rosPublishConnection); #endif } void ThrusterROSPlugin::SetThrustReference( const uuv_gazebo_ros_plugins_msgs::msg::FloatStamped::SharedPtr _msg) { if (std::isnan(_msg->data)) { RCLCPP_WARN(myRosNode->get_logger(), "ThrusterROSPlugin: Ignoring nan command"); return; } this->inputCommand = _msg->data; } gazebo::common::Time ThrusterROSPlugin::GetRosPublishPeriod() { return this->rosPublishPeriod; } void ThrusterROSPlugin::SetRosPublishRate(double _hz) { if (_hz > 0.0) this->rosPublishPeriod = 1.0 / _hz; else this->rosPublishPeriod = 0.; } void ThrusterROSPlugin::Init() { ThrusterPlugin::Init(); } void ThrusterROSPlugin::Reset() { this->lastRosPublishTime.Set(0, 0); } void ThrusterROSPlugin::Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf) { using std::placeholders::_1; using std::placeholders::_2; try { ThrusterPlugin::Load(_parent, _sdf); } catch(gazebo::common::Exception &_e) { gzerr << "Error loading plugin." << "Please ensure that your model is correct." << '\n'; return; } if (!rclcpp::is_initialized()) { gzerr << "Not loading plugin since ROS has not been " << "properly initialized. Try starting gazebo with ros plugin:\n" << " gazebo -s libgazebo_ros_api_plugin.so\n"; return; } try { myRosNode = gazebo_ros::Node::CreateWithArgs(_sdf->Get<std::string>("name")); gzmsg << "[ThrusterROSPlugin] Node created with name: " << myRosNode->get_name() << ", with ns: " << myRosNode->get_namespace() << "\n"; mySet_thrust_force_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency>( myTopicPrefix + "set_thrust_force_efficiency", std::bind(&ThrusterROSPlugin::SetThrustForceEfficiency, this, _1, _2)); myGet_thrust_force_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency>( myTopicPrefix + "get_thrust_force_efficiency", std::bind(&ThrusterROSPlugin::GetThrustForceEfficiency, this, _1, _2)); mySet_dynamic_state_efficiencySrv = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency>( myTopicPrefix + "set_dynamic_state_efficiency", std::bind(&ThrusterROSPlugin::SetDynamicStateEfficiency, this, _1, _2)); myGet_dynamic_state_efficiency = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency>( myTopicPrefix + "get_dynamic_state_efficiency", std::bind(&ThrusterROSPlugin::GetDynamicStateEfficiency, this, _1, _2)); mySet_thruster_state = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState>( myTopicPrefix + "set_thruster_state", std::bind(&ThrusterROSPlugin::SetThrusterState, this, _1, _2)); myGet_thruster_state = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState>( myTopicPrefix + "get_thruster_state", std::bind(&ThrusterROSPlugin::GetThrusterState, this, _1, _2)); myGet_thruster_conversion_fcn = myRosNode->create_service<uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn>( myTopicPrefix + "get_thruster_conversion_fcn", std::bind(&ThrusterROSPlugin::GetThrusterConversionFcn, this, _1, _2)); mySubThrustReference =
; myPubThrust = myRosNode->create_publisher< uuv_gazebo_ros_plugins_msgs::msg::FloatStamped >(this->thrustTopicPublisher->GetTopic(), 10); myPubThrustWrench = myRosNode->create_publisher<geometry_msgs::msg::WrenchStamped>( this->thrustTopicPublisher->GetTopic() + "_wrench", 10); myPubThrusterState = myRosNode->create_publisher<std_msgs::msg::Bool>( myTopicPrefix + "is_on", 1); myPubThrustForceEff = myRosNode->create_publisher<std_msgs::msg::Float64>( myTopicPrefix + "thrust_efficiency", 1); myPubDynamicStateEff = myRosNode->create_publisher<std_msgs::msg::Float64>( myTopicPrefix + "dynamic_state_efficiency", 1); gzmsg << "Thruster #" << this->thrusterID << " initialized" << std::endl << "\t- Link: " << this->thrusterLink->GetName() << std::endl << "\t- Robot model: " << _parent->GetName() << std::endl << "\t- Input command topic: " << this->commandSubscriber->GetTopic() << std::endl << "\t- Thrust output topic: " << this->thrustTopicPublisher->GetTopic() << std::endl; this->rosPublishConnection = gazebo::event::Events::ConnectWorldUpdateBegin( std::bind(&ThrusterROSPlugin::RosPublishStates, this)); } catch(std::exception& e) { gzerr << "Exception when loading plugin: " << e.what() << "\n"; } } void ThrusterROSPlugin::RosPublishStates() { if (this->thrustForceStamp - this->lastRosPublishTime >= this->rosPublishPeriod) { this->lastRosPublishTime = this->thrustForceStamp; uuv_gazebo_ros_plugins_msgs::msg::FloatStamped thrustMsg; thrustMsg.header.stamp = myRosNode->now(); thrustMsg.header.frame_id = this->thrusterLink->GetName(); thrustMsg.data = this->thrustForce; myPubThrust->publish(thrustMsg); geometry_msgs::msg::WrenchStamped thrustWrenchMsg; thrustWrenchMsg.header.stamp = myRosNode->now(); thrustWrenchMsg.header.frame_id = this->thrusterLink->GetName(); ignition::math::Vector3d thrustVector = this->thrustForce * this->thrusterAxis; thrustWrenchMsg.wrench.force.x = thrustVector.X(); thrustWrenchMsg.wrench.force.y = thrustVector.Y(); thrustWrenchMsg.wrench.force.z = thrustVector.Z(); myPubThrustWrench->publish(thrustWrenchMsg); std_msgs::msg::Bool isOnMsg; isOnMsg.data = this->isOn; myPubThrusterState->publish(isOnMsg); std_msgs::msg::Float64 thrustEffMsg; thrustEffMsg.data = this->thrustEfficiency; myPubThrustForceEff->publish(thrustEffMsg); std_msgs::msg::Float64 dynStateEffMsg; dynStateEffMsg.data = this->propellerEfficiency; myPubDynamicStateEff->publish(dynStateEffMsg); } } void ThrusterROSPlugin::SetThrustForceEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Response::SharedPtr _res) { if (_req->efficiency < 0.0 || _req->efficiency > 1.0) { _res->success = false; } else { this->thrustEfficiency = _req->efficiency; _res->success = true; gzmsg << "Setting thrust efficiency at thruster " << this->thrusterLink->GetName() << "=" << _req->efficiency * 100 << "%" << std::endl; } } void ThrusterROSPlugin::GetThrustForceEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Response::SharedPtr _res) { _res->efficiency = this->thrustEfficiency; } void ThrusterROSPlugin::SetDynamicStateEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterEfficiency::Response::SharedPtr _res) { if (_req->efficiency < 0.0 || _req->efficiency > 1.0) { _res->success = false; } else { this->propellerEfficiency = _req->efficiency; _res->success = true; gzmsg << "Setting propeller efficiency at thruster " << this->thrusterLink->GetName() << "=" << _req->efficiency * 100 << "%" << std::endl; } } void ThrusterROSPlugin::GetDynamicStateEfficiency( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterEfficiency::Response::SharedPtr _res) { _res->efficiency = this->propellerEfficiency; } void ThrusterROSPlugin::SetThrusterState( const uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState::Request::SharedPtr _req, uuv_gazebo_ros_plugins_msgs::srv::SetThrusterState::Response::SharedPtr _res) { this->isOn = _req->on; gzmsg << "Turning thruster " << this->thrusterLink->GetName() << " " << (this->isOn ? "ON" : "OFF") << std::endl; _res->success = true; } void ThrusterROSPlugin::GetThrusterState( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterState::Response::SharedPtr _res) { _res->is_on = this->isOn; } void ThrusterROSPlugin::GetThrusterConversionFcn( const uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn::Request::SharedPtr , uuv_gazebo_ros_plugins_msgs::srv::GetThrusterConversionFcn::Response::SharedPtr _res) { _res->fcn.function_name = this->conversionFunction->GetType(); double param; if (!_res->fcn.function_name.compare("Basic")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::Basic" << std::endl; _res->fcn.tags.push_back("rotor_constant"); this->conversionFunction->GetParam("rotor_constant", param); _res->fcn.data.push_back(param); } else if (!_res->fcn.function_name.compare("Bessa")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::Bessa" << std::endl; _res->fcn.tags.push_back("rotor_constant_l"); this->conversionFunction->GetParam("rotor_constant_l", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("rotor_constant_r"); this->conversionFunction->GetParam("rotor_constant_r", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("delta_l"); this->conversionFunction->GetParam("delta_l", param); _res->fcn.data.push_back(param); _res->fcn.tags.push_back("delta_r"); this->conversionFunction->GetParam("delta_r", param); _res->fcn.data.push_back(param); } else if (!_res->fcn.function_name.compare("LinearInterp")) { gzmsg << "ThrusterROSPlugin::GetThrusterConversionFcn::LinearInterp" << std::endl; std::map<double, double> table = this->conversionFunction->GetTable(); for (auto& item : table) { gzmsg << item.first << " " << item.second << std::endl; _res->fcn.lookup_table_input.push_back(item.first); _res->fcn.lookup_table_output.push_back(item.second); } } } GZ_REGISTER_MODEL_PLUGIN(ThrusterROSPlugin) }
myRosNode->create_subscription< uuv_gazebo_ros_plugins_msgs::msg::FloatStamped >(this->commandSubscriber->GetTopic(), 10, std::bind(&ThrusterROSPlugin::SetThrustReference, this, _1))
call_expression
[ { "content": "/// \\brief Gazebo model plugin class for underwater objects\n\nclass UnderwaterObjectPlugin : public gazebo::ModelPlugin\n\n{\n\n /// \\brief Constructor\n\n public: UnderwaterObjectPlugin();\n\n\n\n /// \\brief Destructor\n\n public: virtual ~UnderwaterObjectPlugin();\n\n\n\n // Documentati...
C++
src/publishers/EnviroDIYPublisher.cpp
ssuttles-usgs/ModularSensors
8bc62eb7705729e47e4a47a6b2f02dab955b63f8
#include "EnviroDIYPublisher.h" const char *EnviroDIYPublisher::postEndpoint = "/api/data-stream/"; const char *EnviroDIYPublisher::enviroDIYHost = "data.envirodiy.org"; const int EnviroDIYPublisher::enviroDIYPort = 80; const char *EnviroDIYPublisher::tokenHeader = "\r\nTOKEN: "; const char *EnviroDIYPublisher::contentLengthHeader = "\r\nContent-Length: "; const char *EnviroDIYPublisher::contentTypeHeader = "\r\nContent-Type: application/json\r\n\r\n"; const char *EnviroDIYPublisher::samplingFeatureTag = "{\"sampling_feature\":\""; const char *EnviroDIYPublisher::timestampTag = "\",\"timestamp\":\""; EnviroDIYPublisher::EnviroDIYPublisher() : dataPublisher() { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, sendEveryX, sendOffset) { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, Client *inClient, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, inClient, sendEveryX, sendOffset) { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, const char *registrationToken, const char *samplingFeatureUUID, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, sendEveryX, sendOffset) { setToken(registrationToken); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, Client *inClient, const char *registrationToken, const char *samplingFeatureUUID, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, inClient, sendEveryX, sendOffset) { setToken(registrationToken); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } EnviroDIYPublisher::~EnviroDIYPublisher(){} void EnviroDIYPublisher::setToken(const char *registrationToken) { _registrationToken = registrationToken; } uint16_t EnviroDIYPublisher::calculateJsonSize() { uint16_t jsonLength = 21; jsonLength += 36; jsonLength += 15; jsonLength += 25; jsonLength += 2; for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { jsonLength += 1; jsonLength += 36; jsonLength += 2; jsonLength += _baseLogger->getValueStringAtI(i).length(); if (i + 1 != _baseLogger->getArrayVarCount()) { jsonLength += 1; } } jsonLength += 1; return jsonLength; } void EnviroDIYPublisher::printSensorDataJSON(Stream *stream) { stream->print(samplingFeatureTag); stream->print(_baseLogger->getSamplingFeatureUUID()); stream->print(timestampTag); stream->print(_baseLogger->formatDateTime_ISO8601(Logger::markedEpochTime)); stream->print(F("\",")); for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { stream->print('"'); stream->print(_baseLogger->getVarUUIDAtI(i)); stream->print(F("\":")); stream->print(_baseLogger->getValueStringAtI(i)); if (i + 1 != _baseLogger->getArrayVarCount()) { stream->print(','); } } stream->print('}'); } void EnviroDIYPublisher::printEnviroDIYRequest(Stream *stream) { stream->print(postHeader); stream->print(postEndpoint); stream->print(HTTPtag); stream->print(hostHeader); stream->print(enviroDIYHost); stream->print(tokenHeader); stream->print(_registrationToken); stream->print(contentLengthHeader); stream->print(calculateJsonSize()); stream->print(contentTypeHeader); printSensorDataJSON(stream); } void EnviroDIYPublisher::begin(Logger& baseLogger, Client *inClient, const char *registrationToken, const char *samplingFeatureUUID) { setToken(registrationToken); dataPublisher::begin(baseLogger, inClient); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } void EnviroDIYPublisher::begin(Logger& baseLogger, const char *registrationToken, const char *samplingFeatureUUID) { setToken(registrationToken); dataPublisher::begin(baseLogger); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } int16_t EnviroDIYPublisher::publishData(Client *_outClient) { char tempBuffer[37] = ""; uint16_t did_respond = 0; MS_DBG(F("Outgoing JSON size:"), calculateJsonSize()); MS_DBG(F("Connecting client")); MS_START_DEBUG_TIMER; if (_outClient->connect(enviroDIYHost, enviroDIYPort)) { MS_DBG(F("Client connected after"), MS_PRINT_DEBUG_TIMER, F("ms\n")); strcpy(txBuffer, postHeader); strcat(txBuffer, postEndpoint); strcat(txBuffer, HTTPtag); if (bufferFree() < 28) printTxBuffer(_outClient); strcat(txBuffer, hostHeader); strcat(txBuffer, enviroDIYHost); if (bufferFree() < 47) printTxBuffer(_outClient); strcat(txBuffer, tokenHeader); strcat(txBuffer, _registrationToken); if (bufferFree() < 26) printTxBuffer(_outClient); strcat(txBuffer, contentLengthHeader); itoa(calculateJsonSize(), tempBuffer, 10); strcat(txBuffer, tempBuffer); if (bufferFree() < 42) printTxBuffer(_outClient); strcat(txBuffer, contentTypeHeader); if (bufferFree() < 21) printTxBuffer(_outClient); strcat(txBuffer, samplingFeatureTag); if (bufferFree() < 36) printTxBuffer(_outClient); strcat(txBuffer, _baseLogger->getSamplingFeatureUUID()); if (bufferFree() < 42) printTxBuffer(_outClient); strcat(txBuffer, timestampTag); _baseLogger->formatDateTime_ISO8601(Logger::markedEpochTime).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer); txBuffer[strlen(txBuffer)] = '"'; txBuffer[strlen(txBuffer)] = ','; for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { if (bufferFree() < 47) printTxBuffer(_outClient); txBuffer[strlen(txBuffer)] = '"'; _baseLogger->getVarUUIDAtI(i).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer); txBuffer[strlen(txBuffer)] = '"'; txBuffer[strlen(txBuffer)] = ':'; _baseLogger->getValueStringAtI(i).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer); if (i + 1 != _baseLogger->getArrayVarCount()) { txBuffer[strlen(txBuffer)] = ','; } else { txBuffer[strlen(txBuffer)] = '}'; } } printTxBuffer(_outClient, true); uint32_t start = millis(); while ((millis() - start) < 10000L && _outClient->available() < 12) {delay(10);} did_respond = _outClient->readBytes(tempBuffer, 12); MS_DBG(F("Stopping client")); MS_RESET_DEBUG_TIMER; _outClient->stop(); MS_DBG(F("Client stopped after"), MS_PRINT_DEBUG_TIMER, F("ms")); } else { PRINTOUT(F("\n -- Unable to Establish Connection to EnviroDIY Data Portal --")); } int16_t responseCode = 0; if (did_respond > 0) { char responseCode_char[4]; for (uint8_t i = 0; i < 3; i++) { responseCode_char[i] = tempBuffer[i+9]; } responseCode = atoi(responseCode_char); } else { responseCode=504; } PRINTOUT(F("-- Response Code --")); PRINTOUT(responseCode); return responseCode; }
#include "EnviroDIYPublisher.h" const char *EnviroDIYPublisher::postEndpoint = "/api/data-stream/"; const char *EnviroDIYPublisher::enviroDIYHost = "data.envirodiy.org"; const int EnviroDIYPublisher::enviroDIYPort = 80; const char *EnviroDIYPublisher::tokenHeader = "\r\nTOKEN: "; const char *EnviroDIYPublisher::contentLengthHeader = "\r\nContent-Length: "; const char *EnviroDIYPublisher::contentTypeHeader = "\r\nContent-Type: application/json\r\n\r\n"; const char *EnviroDIYPublisher::samplingFeatureTag = "{\"sampling_feature\":\""; const char *EnviroDIYPublisher::timestampTag = "\",\"timestamp\":\""; EnviroDIYPublisher::EnviroDIYPublisher() : dataPublisher() { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, sendEveryX, sendOffset) { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, Client *inClient, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, inClient, sendEveryX, sendOffset) { } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, const char *registrationToken, const char *samplingFeatureUUID, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, sendEveryX, sendOffset) { setToken(registrationToken); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } EnviroDIYPublisher::EnviroDIYPublisher(Logger& baseLogger, Client *inClient, const char *registrationToken, const char *samplingFeatureUUID, uint8_t sendEveryX, uint8_t sendOffset) : dataPublisher(baseLogger, inClient, sendEveryX, sendOffset) { setToken(registrationToken); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } EnviroDIYPublisher::~EnviroDIYPublisher(){} void EnviroDIYPublisher::setToken(const char *registrationToken) { _registrationToken = registrationToken; } uint16_t EnviroDIYPublisher::calculateJsonSize() { uint16_t jsonLength = 21; jsonLength += 36; jsonLength += 15; jsonLength += 25; jsonLength += 2; for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { jsonLength += 1; jsonLength += 36; jsonLength += 2; jsonLength += _baseLogger->getValueStringAtI(i).length(); if (i + 1 != _baseLogger->getArrayVarCount()) { jsonLength += 1; } } jsonLength += 1; return jsonLength; } void EnviroDIYPublisher::printSensorDataJSON(Stream *stream) { stream->print(samplingFeatureTag); stream->print(_baseLogger->getSamplingFeatureUUID()); stream->print(timestampTag); stream->print(_baseLogger->formatDateTime_ISO8601(Logger::markedEpochTime)); stream->print(F("\",")); for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { stream->print('"'); stream->print(_baseLogger->getVarUUIDAtI(i)); stream->print(F("\":")); stream->print(_baseLogger->getValueStringAtI(i)); if (i + 1 != _baseLogger->getArrayVarCount()) { stream->print(','); } } stream->print('}'); } void EnviroDIYPublisher::printEnviroDIYRequest(Stream *stream) { stream->print(postHeader); stream->print(postEndpoint); stream->print(HTTPtag); stream->print(hostHeader); stream->print(enviroDIYHost); stream->print(tokenHeader); stream->print(_registrationToken); stream->print(contentLengthHeader); stream->print(calculateJsonSize()); stream->print(contentTypeHeader); printSensorDataJSON(stream); } void EnviroDIYPublisher::begin(Logger& baseLogger, Client *inClient, const char *registrationToken, const char *samplingFeatureUUID) { setToken(registrationToken); dataPublisher::begin(baseLogger, inClient); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } void EnviroDIYPublisher::begin(Logger& baseLogger, const char *registrationToken, const char *samplingFeatureUUID) { setToken(registrationToken); dataPublisher::begin(baseLogger); _baseLogger->setSamplingFeatureUUID(samplingFeatureUUID); } int16_t EnviroDIYPublisher::publishData(Client *_outClient) { char tempBuffer[37] = ""; uint16_t did_respond = 0; MS_DBG(F("Outgoing JSON size:"), calculateJsonSize()); MS_DBG(F("Connecting client")); MS_START_DEBUG_TIMER; if (_outClient->connect(enviroDIYHost, enviroDIYPort)) { MS_DBG(F("Client connected after"), MS_PRINT_DEBUG_TIMER, F("ms\n")); strcpy(txBuffer, postHeader); strcat(txBuffer, postEndpoint); strcat(txBuffer, HTTPtag); if (bufferFree() < 28) printTxBuffer(_outClient); strcat(txBuffer, hostHeader); strcat(txBuffer, enviroDIYHost); if (bufferFree() < 47) printTxBuffer(_outClient); strcat(txBuffer, tokenHeader); strcat(txBuffer, _registrationToken); if (bufferFree() < 26) printTxBuffer(_outClient); strcat(txBuffer, contentLengthHeader); itoa(calculateJsonSize(), tempBuffer, 10); strcat(txBuffer, tempBuffer); if (bufferFree() < 42) printTxBuffer(_outClient); strcat(txBuffer, contentTypeHeader); if (bufferFree() < 21) printTxBuffer(_outClient); strcat(txBuffer, samplingFeatureTag); if (bufferFree() < 36) printTxBuffer(_outClient); strcat(txBuffer, _baseLogger->getSamplingFeatureUUID()); if (bufferFree() < 42) printTxBuffer(_outClient); strcat(txBuffer, timestampTag); _baseLogger->formatDateTime_ISO8601(Logger::markedEpochTime).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer); txBuffer[strlen(txBuffer)] = '"'; txBuffer[strlen(txBuffer)] = ','; for (uint8_t i = 0; i < _baseLogger->getArrayVarCount(); i++) { if (bufferFree() < 47) printTxBuffer(_outClient); txBuffer[strlen(txBuffer)] = '"'; _baseLogger->getVarUUIDAtI(i).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer);
- Response Code --")); PRINTOUT(responseCode); return responseCode; }
txBuffer[strlen(txBuffer)] = '"'; txBuffer[strlen(txBuffer)] = ':'; _baseLogger->getValueStringAtI(i).toCharArray(tempBuffer, 37); strcat(txBuffer, tempBuffer); if (i + 1 != _baseLogger->getArrayVarCount()) { txBuffer[strlen(txBuffer)] = ','; } else { txBuffer[strlen(txBuffer)] = '}'; } } printTxBuffer(_outClient, true); uint32_t start = millis(); while ((millis() - start) < 10000L && _outClient->available() < 12) {delay(10);} did_respond = _outClient->readBytes(tempBuffer, 12); MS_DBG(F("Stopping client")); MS_RESET_DEBUG_TIMER; _outClient->stop(); MS_DBG(F("Client stopped after"), MS_PRINT_DEBUG_TIMER, F("ms")); } else { PRINTOUT(F("\n -- Unable to Establish Connection to EnviroDIY Data Portal --")); } int16_t responseCode = 0; if (did_respond > 0) { char responseCode_char[4]; for (uint8_t i = 0; i < 3; i++) { responseCode_char[i] = tempBuffer[i+9]; } responseCode = atoi(responseCode_char); } else { responseCode=504; } PRINTOUT(F("-
random
[ { "content": " // Returns the data destination\n\n virtual String getEndpoint(void){return String(enviroDIYHost);}\n\n\n\n // Adds the site registration token\n\n void setToken(const char *registrationToken);\n\n\n\n // Calculates how long the JSON will be\n\n uint16_t calculateJsonSize();\n\n...
C++
third_party/blink/renderer/core/layout/ng/ng_relative_utils_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/layout/geometry/physical_offset.h" #include "third_party/blink/renderer/core/layout/geometry/physical_size.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace { const LayoutUnit kLeft{3}; const LayoutUnit kRight{5}; const LayoutUnit kTop{7}; const LayoutUnit kBottom{9}; const LayoutUnit kAuto{-1}; const LayoutUnit kZero{0}; class NGRelativeUtilsTest : public testing::Test { protected: void SetUp() override { style_ = ComputedStyle::CreateInitialStyleSingleton(); style_->SetPosition(EPosition::kRelative); } void SetTRBL(LayoutUnit top, LayoutUnit right, LayoutUnit bottom, LayoutUnit left) { style_->SetTop(top == kAuto ? Length::Auto() : Length::Fixed(top.ToInt())); style_->SetRight(right == kAuto ? Length::Auto() : Length::Fixed(right.ToInt())); style_->SetBottom(bottom == kAuto ? Length::Auto() : Length::Fixed(bottom.ToInt())); style_->SetLeft(left == kAuto ? Length::Auto() : Length::Fixed(left.ToInt())); } scoped_refptr<ComputedStyle> style_; LogicalSize container_size_; }; TEST_F(NGRelativeUtilsTest, HorizontalTB) { LogicalOffset offset; SetTRBL(kAuto, kAuto, kAuto, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kZero); EXPECT_EQ(offset.block_offset, kZero); SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kLeft); EXPECT_EQ(offset.block_offset, kTop); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kRight); EXPECT_EQ(offset.block_offset, kTop); SetTRBL(kAuto, kRight, kBottom, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kRight); EXPECT_EQ(offset.block_offset, -kBottom); } TEST_F(NGRelativeUtilsTest, VerticalRightLeft) { LogicalOffset offset; SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kTop); EXPECT_EQ(offset.block_offset, kRight); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kBottom); EXPECT_EQ(offset.block_offset, kRight); SetTRBL(kAuto, kAuto, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kBottom); EXPECT_EQ(offset.block_offset, -kLeft); } TEST_F(NGRelativeUtilsTest, VerticalLeftRight) { LogicalOffset offset; SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kTop); EXPECT_EQ(offset.block_offset, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kBottom); EXPECT_EQ(offset.block_offset, kLeft); SetTRBL(kAuto, kRight, kBottom, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kBottom); EXPECT_EQ(offset.block_offset, -kRight); } } }
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/layout/geometry/physical_offset.h" #include "third_party/blink/renderer/core/layout/geometry/physical_size.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace { const LayoutUnit kLeft{3}; const LayoutUnit kRight{5}; const LayoutUnit kTop{7}; const LayoutUnit kBottom{9}; const LayoutUnit kAuto{-1}; const LayoutUnit kZero{0}; class NGRelativeUtilsTest : public testing::Test { protected: void SetUp() override { style_ = ComputedStyle::CreateInitialStyleSingleton(); style_->SetPosition(EPosition::kRelative); }
scoped_refptr<ComputedStyle> style_; LogicalSize container_size_; }; TEST_F(NGRelativeUtilsTest, HorizontalTB) { LogicalOffset offset; SetTRBL(kAuto, kAuto, kAuto, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kZero); EXPECT_EQ(offset.block_offset, kZero); SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kLeft); EXPECT_EQ(offset.block_offset, kTop); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kRight); EXPECT_EQ(offset.block_offset, kTop); SetTRBL(kAuto, kRight, kBottom, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kHorizontalTb, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kRight); EXPECT_EQ(offset.block_offset, -kBottom); } TEST_F(NGRelativeUtilsTest, VerticalRightLeft) { LogicalOffset offset; SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kTop); EXPECT_EQ(offset.block_offset, kRight); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kBottom); EXPECT_EQ(offset.block_offset, kRight); SetTRBL(kAuto, kAuto, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalRl, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kBottom); EXPECT_EQ(offset.block_offset, -kLeft); } TEST_F(NGRelativeUtilsTest, VerticalLeftRight) { LogicalOffset offset; SetTRBL(kTop, kRight, kBottom, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, kTop); EXPECT_EQ(offset.block_offset, kLeft); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kRtl}, container_size_); EXPECT_EQ(offset.inline_offset, kBottom); EXPECT_EQ(offset.block_offset, kLeft); SetTRBL(kAuto, kRight, kBottom, kAuto); offset = ComputeRelativeOffset( *style_, {WritingMode::kVerticalLr, TextDirection::kLtr}, container_size_); EXPECT_EQ(offset.inline_offset, -kBottom); EXPECT_EQ(offset.block_offset, -kRight); } } }
void SetTRBL(LayoutUnit top, LayoutUnit right, LayoutUnit bottom, LayoutUnit left) { style_->SetTop(top == kAuto ? Length::Auto() : Length::Fixed(top.ToInt())); style_->SetRight(right == kAuto ? Length::Auto() : Length::Fixed(right.ToInt())); style_->SetBottom(bottom == kAuto ? Length::Auto() : Length::Fixed(bottom.ToInt())); style_->SetLeft(left == kAuto ? Length::Auto() : Length::Fixed(left.ToInt())); }
function_block-full_function
[]
C++
v8bridge/userland/userland_class.hpp
QuartzTechnologies/v8bridge
5e2f2d6b93adae25295b88c0c4e0eb4f93e22057
#ifndef BOOST_PP_IS_ITERATING # ifndef v8bridge_userland_class_hpp # define v8bridge_userland_class_hpp # include <stdexcept> # include <v8bridge/detail/prefix.hpp> # include <v8bridge/conversion.hpp> # include <v8bridge/userland/userland_instance.hpp> # include <boost/preprocessor/repetition.hpp> # include <boost/preprocessor/iteration/iterate.hpp> # include <boost/shared_ptr.hpp> namespace v8 { namespace bridge { using namespace v8; class V8_DECL UserlandClass { public: UserlandClass(Isolate *isolationScope, Handle<Value> functionHandle) : m_isolationScope(isolationScope), m_function(isolationScope, Handle<Function>::Cast(functionHandle)) , m_instances(new TInstancesList()) { }; UserlandClass(Isolate *isolationScope, Handle<Function> functionHandle) : m_isolationScope(isolationScope), m_function(isolationScope, functionHandle) , m_instances(new TInstancesList()) { }; ~UserlandClass() { this->m_function.Reset(); for (TInstancesList::iterator it = this->m_instances->begin(); it != this->m_instances->end(); ++it) { (*it).reset(); } this->m_instances->clear(); } inline Local<Function> getCtorFunction() { return Local<Function>::New(this->m_isolationScope, this->m_function); } inline Local<Value> getHandle(std::string key) { EscapableHandleScope handle_scope(this->m_isolationScope); return handle_scope.Escape( this->getCtorFunction()->Get(String::NewFromUtf8(this->m_isolationScope, key.c_str())) ); } template <class TType> inline TType getValue(std::string key) { Local<Value> value = this->getCtorFunction()->Get(String::NewFromUtf8(this->m_isolationScope, key.c_str())); TType result; if (!JsToNative(this->m_isolationScope, result, value)) { std::stringstream io; io << "The requested variable (" << key << ")" << " does not match the specified TType (" << TypeId<TType>().name() << ")."; throw std::runtime_error(io.str()); } return result; } inline UserlandInstance *newInstance() { Handle<Value> argv[] = { }; Handle<Value> v8Instance = this->getCtorFunction()->NewInstance(0, argv); UserlandInstance *instance = new UserlandInstance(this->m_isolationScope, v8Instance); boost::shared_ptr<UserlandInstance> adapter(instance); this->m_instances->push_back(adapter); return instance; } template <class TResult> inline typename boost::disable_if< boost::is_same<TResult, void>, TResult >::type invoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; TResult result; if (!JsToNative(this->m_isolationScope, result, callback->Call(callback, 0, argv))) { std::stringstream io; io << "The function returned value does not match the specified TResult (" << TypeId<TResult>().name() << ")."; throw std::runtime_error(io.str()); } return result; } template <class TResult> inline typename boost::enable_if< boost::is_same<TResult, void>, TResult >::type invoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; callback->Call(callback, 0, argv); } inline Handle<Value> rawInvoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; return callback->Call(callback, 0, argv); } # define BOOST_PP_ITERATION_PARAMS_1 (3, (1, V8_MAX_ARITY, <v8bridge/userland/userland_class.hpp>)) # include BOOST_PP_ITERATE() private: typedef std::list<boost::shared_ptr<UserlandInstance> > TInstancesList; Isolate *m_isolationScope; Persistent<Function> m_function; TInstancesList *m_instances; }; } } # endif #else # if BOOST_PP_ITERATION_DEPTH() == 1 # define N BOOST_PP_ITERATION() # define V8_BRIDGE_CALL_CONCAT_ARG(z, n, data) BOOST_PP_CAT(TClass, n) BOOST_PP_CAT(arg, n) # define V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE(z, n, data) NativeToJs<BOOST_PP_CAT(TClass, n)>(this->m_isolationScope, BOOST_PP_CAT(arg, n)) template <BOOST_PP_ENUM_PARAMS(N, class TClass) > UserlandInstance *newInstance(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; Handle<Value> v8Instance = this->getCtorFunction()->NewInstance(N, argv); UserlandInstance *instance = new UserlandInstance(this->m_isolationScope, v8Instance); boost::shared_ptr<UserlandInstance> adapter(instance); this->m_instances->push_back(adapter); return instance; } template <class TResult, BOOST_PP_ENUM_PARAMS(N, class TClass) > inline typename boost::disable_if< boost::is_same<TResult, void>, TResult >::type invoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; TResult result; if (!JsToNative(this->m_isolationScope, result, callback->Call(callback, N, argv))) { std::stringstream io; io << "The function returned value does not match the specified TResult (" << TypeId<TResult>().name() << ")."; throw std::runtime_error(io.str()); } return result; } template <class TResult, BOOST_PP_ENUM_PARAMS(N, class TClass) > inline typename boost::enable_if< boost::is_same<TResult, void>, TResult >::type invoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; callback->Call(callback, N, argv); } template <BOOST_PP_ENUM_PARAMS(N, class TClass) > inline Handle<Value> rawInvoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; return callback->Call(callback, N, argv); } # endif #endif
#ifndef BOOST_PP_IS_ITERATING # ifndef v8bridge_userland_class_hpp # define v8bridge_userland_class_hpp # include <stdexcept> # include <v8bridge/detail/prefix.hpp> # include <v8bridge/conversion.hpp> # include <v8bridge/userland/userland_instance.hpp> # include <boost/preprocessor/repetition.hpp> # include <boost/preprocessor/iteration/iterate.hpp> # include <boost/shared_ptr.hpp> namespace v8 { namespace bridge { using namespace v8; class V8_DECL UserlandClass { public: UserlandClass(Isolate *isolationScope, Handle<Value> functionHandle) : m_isolationScope(isolationScope), m_function(isolationScope, Handle<Function>::Cast(functionHandle)) , m_instances(new TInstancesList()) { }; UserlandClass(Isolate *isolationScope, Handle<Function> functionHandle) : m_isolationScope(isolationScope), m_function(isolationScope, functionHandle) , m_instances(new TInstancesList()) { }; ~UserlandClass() { this->m_function.Reset();
function returned value does not match the specified TResult (" << TypeId<TResult>().name() << ")."; throw std::runtime_error(io.str()); } return result; } template <class TResult, BOOST_PP_ENUM_PARAMS(N, class TClass) > inline typename boost::enable_if< boost::is_same<TResult, void>, TResult >::type invoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; callback->Call(callback, N, argv); } template <BOOST_PP_ENUM_PARAMS(N, class TClass) > inline Handle<Value> rawInvoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; return callback->Call(callback, N, argv); } # endif #endif
for (TInstancesList::iterator it = this->m_instances->begin(); it != this->m_instances->end(); ++it) { (*it).reset(); } this->m_instances->clear(); } inline Local<Function> getCtorFunction() { return Local<Function>::New(this->m_isolationScope, this->m_function); } inline Local<Value> getHandle(std::string key) { EscapableHandleScope handle_scope(this->m_isolationScope); return handle_scope.Escape( this->getCtorFunction()->Get(String::NewFromUtf8(this->m_isolationScope, key.c_str())) ); } template <class TType> inline TType getValue(std::string key) { Local<Value> value = this->getCtorFunction()->Get(String::NewFromUtf8(this->m_isolationScope, key.c_str())); TType result; if (!JsToNative(this->m_isolationScope, result, value)) { std::stringstream io; io << "The requested variable (" << key << ")" << " does not match the specified TType (" << TypeId<TType>().name() << ")."; throw std::runtime_error(io.str()); } return result; } inline UserlandInstance *newInstance() { Handle<Value> argv[] = { }; Handle<Value> v8Instance = this->getCtorFunction()->NewInstance(0, argv); UserlandInstance *instance = new UserlandInstance(this->m_isolationScope, v8Instance); boost::shared_ptr<UserlandInstance> adapter(instance); this->m_instances->push_back(adapter); return instance; } template <class TResult> inline typename boost::disable_if< boost::is_same<TResult, void>, TResult >::type invoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; TResult result; if (!JsToNative(this->m_isolationScope, result, callback->Call(callback, 0, argv))) { std::stringstream io; io << "The function returned value does not match the specified TResult (" << TypeId<TResult>().name() << ")."; throw std::runtime_error(io.str()); } return result; } template <class TResult> inline typename boost::enable_if< boost::is_same<TResult, void>, TResult >::type invoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; callback->Call(callback, 0, argv); } inline Handle<Value> rawInvoke() { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = {}; return callback->Call(callback, 0, argv); } # define BOOST_PP_ITERATION_PARAMS_1 (3, (1, V8_MAX_ARITY, <v8bridge/userland/userland_class.hpp>)) # include BOOST_PP_ITERATE() private: typedef std::list<boost::shared_ptr<UserlandInstance> > TInstancesList; Isolate *m_isolationScope; Persistent<Function> m_function; TInstancesList *m_instances; }; } } # endif #else # if BOOST_PP_ITERATION_DEPTH() == 1 # define N BOOST_PP_ITERATION() # define V8_BRIDGE_CALL_CONCAT_ARG(z, n, data) BOOST_PP_CAT(TClass, n) BOOST_PP_CAT(arg, n) # define V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE(z, n, data) NativeToJs<BOOST_PP_CAT(TClass, n)>(this->m_isolationScope, BOOST_PP_CAT(arg, n)) template <BOOST_PP_ENUM_PARAMS(N, class TClass) > UserlandInstance *newInstance(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; Handle<Value> v8Instance = this->getCtorFunction()->NewInstance(N, argv); UserlandInstance *instance = new UserlandInstance(this->m_isolationScope, v8Instance); boost::shared_ptr<UserlandInstance> adapter(instance); this->m_instances->push_back(adapter); return instance; } template <class TResult, BOOST_PP_ENUM_PARAMS(N, class TClass) > inline typename boost::disable_if< boost::is_same<TResult, void>, TResult >::type invoke(BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONCAT_ARG, ~)) { HandleScope handle_scope(this->m_isolationScope); Local<Function> callback = this->getCtorFunction(); Handle<Value> argv[] = { BOOST_PP_ENUM(N, V8_BRIDGE_CALL_CONVERT_TO_V8_ARG_TYPE, ~) }; TResult result; if (!JsToNative(this->m_isolationScope, result, callback->Call(callback, N, argv))) { std::stringstream io; io << "The
random
[ { "content": " class V8_DECL NativeClass : public NativeEndpoint\n\n {\n\n public:\n\n NativeClass(Isolate *isolationScope) : NativeEndpoint(isolationScope),\n\n m_ctor(new NativeCtor(isolationScope)),\n\n m_methods(new TMethodsMap()),\n\n m_stati...
C++
ModelTakuzu.cpp
Ezryuk/Takuzu
6dd94470c15c0071ca210a9655eb85d8458163c3
#include "ModelTakuzu.h" #include <cassert> #include <iostream> #include <QtAlgorithms> #include <QFile> #include <QTextStream> ModelTakuzu::ModelTakuzu() { _nbMaps = -1; _sizeMap = -1; _grids = nullptr; } ModelTakuzu::~ModelTakuzu() { delete[] _grids; } Pawn ModelTakuzu::permuteR(Pawn p) { if (p == Black) { return White; } else if (p == White) { return Empty; } else { return Black; } } Pawn ModelTakuzu::permuteL(Pawn p) { if (p == Black) { return Empty; } else if (p == Empty) { return White; } else { return Black; } } void ModelTakuzu::loadFile(const QString &name) { QFile file(":/resources/"+name); if (!(file.open(QIODevice::ReadOnly | QIODevice::Text))) { std::cerr << "Error while opening new file: " << name.toStdString() << " .\n"; } else { QString line; QTextStream in(&file); bool ok = true; _nbMaps = in.readLine().toInt(&ok); if (!ok) { std::cerr << "Issue when reading new line. \n"\ << "Make sure the file has the same path as the executable.\n"; } _grids = new Grid_[_nbMaps]; for (int i = 0; i < _nbMaps; ++i) { _grids[i] = Grid_(_sizeMap * _sizeMap); } int i = 0; while (!in.atEnd()) { line = in.readLine(); int letterIndex = 0; QChar letter; foreach(letter, line) { if (letterIndex < _sizeMap * _sizeMap) { _grids[i][letterIndex++] = ModelTakuzu::toPawn(letter); } } i++; } } } void ModelTakuzu::chooseMapPool(ModelTakuzu::Difficulty difficulty, int size) { QString name = QString::number(size); if (difficulty == Easy) { name.append("_easy.txt"); } else { name.append("_hard.txt"); } _difficulty = difficulty; _sizeMap = size; loadFile(QString(name)); setRandomMap(); emit notifyNumberMap(_difficulty, _sizeMap, _chosenMap, _nbMaps); } int ModelTakuzu::setMap(int chosenMap) { assert((_nbMaps != -1 || _sizeMap != -1) && \ "Choose a map pool before using setRandomMap()."); _chosenMap = chosenMap; _currentGrid = _grids[chosenMap]; _countPawn = { std::vector<int>(_sizeMap), std::vector<int>(_sizeMap), std::vector<int>(_sizeMap), std::vector<int>(_sizeMap) }; for(int i = 0; i < _sizeMap; ++i) { for (int j = 0; j < _sizeMap; ++j) { emit notifyInitialPawn(i, j, _grids[chosenMap][i * _sizeMap + j]); } } initCount(); return _chosenMap; } int ModelTakuzu::setRandomMap() { int randomGridIndex = (rand() % _nbMaps); _chosenMap = setMap(randomGridIndex); return randomGridIndex; } void ModelTakuzu::playAt(int i, int j, Pawn pawn) { assert((!_currentGrid.empty()) && \ "Set a map using setRandomMap() before calling playAt()."); Pawn oldPawn = pawnAt(i, j); Pawn newPawn = pawn; updateCount(i, j, oldPawn, newPawn); pawnAt(i, j) = newPawn; positionIsValid(i, j); emit notifyNewPawn(i, j, pawn); } bool ModelTakuzu::positionIsValid(int i, int j) { const bool isVertical = true; const bool isOK = true; bool repetitionInRow = isBBBorWWWpresentIn(getRow(i)); bool repetitionInCol = isBBBorWWWpresentIn(getCol(j)); if (repetitionInRow) { emit notifyOverThreeAdjacentPawns(i, !isVertical, !isOK); } else { emit notifyOverThreeAdjacentPawns(i, !isVertical, isOK); } if (repetitionInCol) { emit notifyOverThreeAdjacentPawns(j, isVertical, !isOK); } else { emit notifyOverThreeAdjacentPawns(j, isVertical, isOK); } int oneOtherIdenticalRow = findFirstIdenticalRowTo(i); int oneOtherIdenticalCol = findFirstIdenticalColTo(j); static auto oneOtherIdenticalRowColIsFound = [this](int index) -> bool { return (index != _sizeMap); }; if (oneOtherIdenticalRowColIsFound(oneOtherIdenticalRow)) { emit notifyCommonPatterns(i, oneOtherIdenticalRow, !isVertical, isOK); } else { emit notifyCommonPatterns(i, oneOtherIdenticalRow, !isVertical, !isOK); } if (oneOtherIdenticalRowColIsFound(oneOtherIdenticalCol)) { emit notifyCommonPatterns(j, oneOtherIdenticalCol, isVertical, isOK); } else { emit notifyCommonPatterns(j, oneOtherIdenticalCol, isVertical, !isOK); } return (!repetitionInRow && !repetitionInCol && (oneOtherIdenticalRow == _sizeMap) && (oneOtherIdenticalCol == _sizeMap)); } bool ModelTakuzu::rowIsValid(int i) { static auto forAll = [](bool tab[], int length) -> bool { for (int i = 0; i < length; ++i) { if (!tab[i]) return false; } return true; }; bool tab[_sizeMap]; for (int j = 0; j < _sizeMap; ++j) { tab[j] = positionIsValid(i, j); } return forAll(tab, _sizeMap) && (_countPawn._Brow[i] == _countPawn._Wrow[i]); } bool ModelTakuzu::colIsValid(int j) { static auto forAll = [](bool tab[], int length) -> bool { for (int i = 0; i < length; ++i) { if (!tab[i]) return false; } return true; }; bool tab[_sizeMap]; for (int i = 0; i < _sizeMap; ++i) { tab[i] = positionIsValid(i, j); } return forAll(tab, _sizeMap) && (_countPawn._Bcol[j] == _countPawn._Wcol[j]); } void ModelTakuzu::initCount() { for (int i = 0; i < _sizeMap; ++i) { for (int j = 0; j < _sizeMap; ++j) { updateCount(i, j, Empty, _grids[_chosenMap][i * _sizeMap + j]); } } } void ModelTakuzu::updateCount(int i, int j, Pawn oldPawn, Pawn newPawn) { if (oldPawn != newPawn) { switch (oldPawn) { case Black: _countPawn._Brow[i]--; _countPawn._Bcol[j]--; break; case White: _countPawn._Wrow[i]--; _countPawn._Wcol[j]--; break; case Empty: break; } switch (newPawn) { case Black: _countPawn._Brow[i]++; _countPawn._Bcol[j]++; break; case White: _countPawn._Wrow[i]++; _countPawn._Wcol[j]++; break; case Empty: break; } } emit notifyCount(i, j, _countPawn._Brow[i], _countPawn._Bcol[j], _countPawn._Wrow[i], _countPawn._Wcol[j]); } Pawn ModelTakuzu::getPawn(int i, int j) const { return _currentGrid[i * _sizeMap + j]; } bool ModelTakuzu::doFinalCheck() { std::vector<bool> isValid; for(int i = 0; i < _sizeMap; ++i) { for(int j = 0; j < _sizeMap; ++j) { isValid.push_back(positionIsValid(i, j)); } } std::vector<std::vector<Pawn>> rowsAndCols; for (int i = 0; i < _sizeMap; ++i) { rowsAndCols.push_back(getRow(i)); rowsAndCols.push_back(getCol(i)); } std::vector<int> counterOcc; std::for_each(rowsAndCols.begin(), rowsAndCols.end(), [&counterOcc](std::vector<Pawn> &vec) -> void { counterOcc.push_back(std::count(vec.begin(), vec.end(), Black)); counterOcc.push_back(std::count(vec.begin(), vec.end(), White)); }); return (std::all_of(_currentGrid.begin(), _currentGrid.end(), [](Pawn p)->bool { return (p != Empty);}) && std::all_of(isValid.begin(), isValid.end(), [](bool b)-> bool {return b;}) && std::all_of(counterOcc.begin(), counterOcc.end(), [this](int v) -> bool {return (_sizeMap == 2 * v);})); } void ModelTakuzu::registerPlayAt(int i, int j) { Pawn nextPawn = permuteR(pawnAt(i, j)); playAt(i, j, nextPawn); } void ModelTakuzu::registerChooseMapPool(ModelTakuzu::Difficulty difficulty, int size) { chooseMapPool(difficulty, size); } void ModelTakuzu::registerSizeMapPicked(ModelTakuzu::Difficulty difficulty, int size) { QString name = QString::number(size); if (difficulty == Easy) { name.append("_easy.txt"); } else { name.append("_hard.txt"); } _difficulty = difficulty; _sizeMap = size; loadFile(QString(name)); emit notifyNbMaps(_nbMaps); } void ModelTakuzu::registerChooseMapPicked(int mapPicked) { _chosenMap = mapPicked; setMap(_chosenMap); emit notifyNumberMap(_difficulty, _sizeMap, _chosenMap, _nbMaps); } void ModelTakuzu::registerAttemptToEndGame() { bool win = doFinalCheck(); emit notifyEndGame(win); } QChar ModelTakuzu::toQChar(Pawn pawn) { switch (pawn) { case Black: return QChar('B'); case White: return QChar('W'); case Empty: return QChar('.'); default: return QChar('.'); } } Pawn ModelTakuzu::toPawn(QChar letter) { switch (letter.unicode()) { case 'B': return Black; case 'W': return White; case '.': return Empty; default: return Empty; } } Pawn &ModelTakuzu::pawnAt(int i, int j) { assert(_chosenMap != -1 && "A map should be chosen before trying to access to _currentGrid."); return _currentGrid[i * _sizeMap + j]; } Pawn ModelTakuzu::pawnAt(int i, int j) const { assert(_chosenMap != -1 && "A map should be chosen before trying to access to _currentGrid."); return _currentGrid[i * _sizeMap + j]; } std::vector<Pawn> ModelTakuzu::getRow(int i) const { return std::vector<Pawn>(_currentGrid.begin() + i * _sizeMap, _currentGrid.begin() + (i + 1) * _sizeMap); } std::vector<Pawn> ModelTakuzu::getCol(int j) const { std::vector<Pawn> column; for (int row = 0; row < _sizeMap; ++row) { column.push_back(pawnAt(row, j)); } return column; } bool ModelTakuzu::isBBBorWWWpresentIn(std::vector<Pawn> vec) { static std::vector<Pawn> vecBBB = {Black, Black, Black}; static std::vector<Pawn> vecWWW = {White, White, White}; auto itB = std::search(vec.cbegin(), vec.cend(), vecBBB.cbegin(), vecBBB.cend()); auto itW = std::search(vec.cbegin(), vec.cend(), vecWWW.cbegin(), vecWWW.cend()); return (itB != vec.cend() || itW != vec.cend()); } int ModelTakuzu::findFirstIdenticalRowTo(int i) const { std::vector<Pawn> rowToScan = getRow(i); for (int rowIndex = 0; rowIndex < _sizeMap;++rowIndex) { if (rowIndex != i) { if (std::equal(_currentGrid.cbegin() + rowIndex * _sizeMap, _currentGrid.cbegin() + (rowIndex + 1) * _sizeMap, rowToScan.cbegin())) { return rowIndex; } } } return _sizeMap; } int ModelTakuzu::findFirstIdenticalColTo(int j) const { std::vector<Pawn> colToScan = getCol(j); for (int colIndex = 0; colIndex < _sizeMap; ++colIndex) { if (colIndex != j) { std::vector<Pawn> otherCol = getCol(colIndex); if (std::equal(colToScan.begin(), colToScan.end(), otherCol.begin(), otherCol.end())) { return colIndex; } } } return _sizeMap; }
#include "ModelTakuzu.h" #include <cassert> #include <iostream> #include <QtAlgorithms> #include <QFile> #include <QTextStream> ModelTakuzu::ModelTakuzu() { _nbMaps = -1; _sizeMap = -1; _grids = nullptr; } ModelTakuzu::~ModelTakuzu() { delete[] _grids; } Pawn ModelTakuzu::permuteR(Pawn p) { if (p == Black) { return White; } else if (p == White) { return Empty; } else { return Black; } } Pawn ModelTakuzu::permuteL(Pawn p) { if (p == Black) { return Empty; } else if (p == Empty) { return White; } else { return Black; } } void ModelTakuzu::loadFile(const QString &name) { QFile file(":/resources/"+name); if (!(file.open(QIODevice::ReadOnly | QIODevice::Text))) { std::cerr << "Error while opening new file: " << name.toStdString() << " .\n"; } else { QString line; QTextStream in(&file); bool ok = true; _nbMaps = in.readLine().toInt(&ok); if (!ok) { std::cerr << "Issue when reading new line. \n"\ << "Make sure the file has the same path as the executable.\n"; } _grids = new Grid_[_nbMaps]; for (int i = 0; i < _nbMaps; ++i) { _grids[i] = Grid_(_sizeMap * _sizeMap); } int i = 0; while (!in.atEnd()) { line = in.readLine(); int letterIndex = 0; QChar letter; foreach(letter, line) { if (letterIndex < _sizeMap * _sizeMap) { _grids[i][letterIndex++] = ModelTakuzu::toPawn(letter); } } i++; } } } void ModelTakuzu::chooseMapPool(ModelTakuzu::Difficulty difficulty, int size) { QString name = QString::number(size); if (difficulty == Easy) { name.append("_easy.txt"); } else { name.append("_hard.txt"); } _difficulty = difficulty; _sizeMap = size; loadFile(QString(name)); setRandomMap(); emit notifyNumberMap(_difficulty, _sizeMap, _chosenMap, _nbMaps); } int ModelTakuzu::setMap(int chosenMap) { assert((_nbMaps != -1 || _sizeMap != -1) && \ "Choose a map pool before using setRandomMap()."); _chosenMap = chosenMap; _currentGrid = _grids[chosenMap]; _countPawn = { std::vector<int>(_sizeMap), std::vector<int>(_sizeMap), std::vector<int>(_sizeMap), std::vector<int>(_sizeMap) }; for(int i = 0; i < _sizeMap; ++i) { for (int j = 0; j < _sizeMap; ++j) { emit notifyInitialPawn(i, j, _grids[chosenMap][i * _sizeMap + j]); } } initCount(); return _chosenMap; } int ModelTakuzu::setRandomMap() { int randomGridIndex = (rand() % _nbMaps); _chosenMap = setMap(randomGridIndex); return randomGridIndex; } void ModelTakuzu::playAt(int i, int j, Pawn pawn) { assert((!_currentGrid.empty()) && \ "Set a map using setRandomMap() before calling playAt()."); Pawn oldPawn = pawnAt(i, j); Pawn newPawn = pawn; updateCount(i, j, oldPawn, newPawn); pawnAt(i, j) = newPawn; positionIsValid(i, j); emit notifyNewPawn(i, j, pawn); } bool ModelTakuzu::positionIsValid(int i, int j) { const bool isVertical = true; const bool isOK = true; bool repetitionInRow = isBBBorWWWpresentIn(getRow(i)); bool repetitionInCol = isBBBorWWWpresentIn(getCol(j)); if (repetitionInRow) { emit notifyOverThreeAdjacentPawns(i, !isVertical, !isOK); } else { emit notifyOverThreeAdjacentPawns(i, !isVertical, isOK); } if (repetitionInCol) { emit notifyOverThreeAdjacentPawns(j, isVertical, !isOK); } else { emit notifyOverThreeAdjacentPawns(j, isVertical, isOK); } int oneOtherIdenticalRow = findFirstIdenticalRowTo(i); int oneOtherIdenticalCol = findFirstIdenticalColTo(j); static auto oneOtherIdenticalRowColIsFound = [this](int index) -> bool { return (index != _sizeMap); }; if (oneOtherIdenticalRowColIsFound(oneOtherIdenticalRow)) { emit notifyCommonPatterns(i, oneOtherIdenticalRow, !isVertical, isOK); } else { emit notifyCommonPatterns(i, oneOtherIdenticalRow, !isVertical, !isOK); } if (oneOtherIdenticalRowColIsFound(oneOtherIdenticalCol)) { emit notifyCommonPatterns(j, oneOtherIdenticalCol, isVertical, isOK); } else { emit notifyCommonPatterns(j, oneOtherIdenticalCol, isVertical, !isOK); } return (!repetitionInRow && !repetitionInCol && (oneOtherIdenticalRow == _sizeMap) && (oneOtherIdenticalCol == _sizeMap)); } bool ModelTakuzu::rowIsValid(int i) { static auto forAll = [](bool tab[], int length) -> bool { for (int i = 0; i < length; ++i) { if (!tab[i]) return false; } return true; }; bool tab[_sizeMap]; for (int j = 0; j < _sizeMap; ++j) { tab[j] = positionIsValid(i, j); } return forAll(tab, _sizeMap) && (_countPawn._Brow[i] == _countPawn._Wrow[i]); } bool ModelTakuzu::colIsValid(int j) { static auto forAll = [](bool tab[], int length) -> bool { for (int i = 0; i < length; ++i) { if (!tab[i]) return false; } return true; }; bool tab[_sizeMap]; for (int i = 0; i < _sizeMap; ++i) { tab[i] = positionIsValid(i, j); } return forAll(tab, _sizeMap) && (_countPawn._Bcol[j] == _countPawn._Wcol[j]); } void ModelTakuzu::initCount() { for (int i = 0; i < _sizeMap; ++i) { for (int j = 0; j < _sizeMap; ++j) { updateCount(i, j, Empty, _grids[_chosenMap][i * _sizeMap + j]); } } } void ModelTakuzu::updateCount(int i, int j, Pawn oldPawn, Pawn newPawn) { if (oldPawn != newPawn) { switch (oldPawn) { case Black: _countPawn._Brow[i]--; _countPawn._Bcol[j]--; break; case White: _countPawn._Wrow[i]--; _countPawn._Wcol[j]--; break; case Empty: break; } switch (newPawn) { case Black: _countPawn._Brow[i]++; _countPawn._Bcol[j]++; break; case White: _countPawn._Wrow[i]++; _countPawn._Wcol[j]++; break; case Empty: break; } } emit notifyCount(i, j, _countPawn._Brow[i], _countPawn._Bcol[j], _countPawn._Wrow[i], _countPawn._Wcol[j]); } Pawn ModelTakuzu::getPawn(int i, int j) const { return _currentGrid[i * _sizeMap + j]; } bool ModelTakuzu::doFinalCheck() { std::vector<bool> isValid; for(int i = 0; i < _sizeMap; ++i) { for(int j = 0; j < _sizeMap; ++j) { isValid.push_back(positionIsValid(i, j)); } } std::vector<std::vector<Pawn>> rowsAndCols; for (int i = 0; i < _sizeMap; ++i) { rowsAndCols.push_back(getRow(i)); rowsAndCols.push_back(getCol(i)); } std::vector<int> counterOcc;
; return (std::all_of(_currentGrid.begin(), _currentGrid.end(), [](Pawn p)->bool { return (p != Empty);}) && std::all_of(isValid.begin(), isValid.end(), [](bool b)-> bool {return b;}) && std::all_of(counterOcc.begin(), counterOcc.end(), [this](int v) -> bool {return (_sizeMap == 2 * v);})); } void ModelTakuzu::registerPlayAt(int i, int j) { Pawn nextPawn = permuteR(pawnAt(i, j)); playAt(i, j, nextPawn); } void ModelTakuzu::registerChooseMapPool(ModelTakuzu::Difficulty difficulty, int size) { chooseMapPool(difficulty, size); } void ModelTakuzu::registerSizeMapPicked(ModelTakuzu::Difficulty difficulty, int size) { QString name = QString::number(size); if (difficulty == Easy) { name.append("_easy.txt"); } else { name.append("_hard.txt"); } _difficulty = difficulty; _sizeMap = size; loadFile(QString(name)); emit notifyNbMaps(_nbMaps); } void ModelTakuzu::registerChooseMapPicked(int mapPicked) { _chosenMap = mapPicked; setMap(_chosenMap); emit notifyNumberMap(_difficulty, _sizeMap, _chosenMap, _nbMaps); } void ModelTakuzu::registerAttemptToEndGame() { bool win = doFinalCheck(); emit notifyEndGame(win); } QChar ModelTakuzu::toQChar(Pawn pawn) { switch (pawn) { case Black: return QChar('B'); case White: return QChar('W'); case Empty: return QChar('.'); default: return QChar('.'); } } Pawn ModelTakuzu::toPawn(QChar letter) { switch (letter.unicode()) { case 'B': return Black; case 'W': return White; case '.': return Empty; default: return Empty; } } Pawn &ModelTakuzu::pawnAt(int i, int j) { assert(_chosenMap != -1 && "A map should be chosen before trying to access to _currentGrid."); return _currentGrid[i * _sizeMap + j]; } Pawn ModelTakuzu::pawnAt(int i, int j) const { assert(_chosenMap != -1 && "A map should be chosen before trying to access to _currentGrid."); return _currentGrid[i * _sizeMap + j]; } std::vector<Pawn> ModelTakuzu::getRow(int i) const { return std::vector<Pawn>(_currentGrid.begin() + i * _sizeMap, _currentGrid.begin() + (i + 1) * _sizeMap); } std::vector<Pawn> ModelTakuzu::getCol(int j) const { std::vector<Pawn> column; for (int row = 0; row < _sizeMap; ++row) { column.push_back(pawnAt(row, j)); } return column; } bool ModelTakuzu::isBBBorWWWpresentIn(std::vector<Pawn> vec) { static std::vector<Pawn> vecBBB = {Black, Black, Black}; static std::vector<Pawn> vecWWW = {White, White, White}; auto itB = std::search(vec.cbegin(), vec.cend(), vecBBB.cbegin(), vecBBB.cend()); auto itW = std::search(vec.cbegin(), vec.cend(), vecWWW.cbegin(), vecWWW.cend()); return (itB != vec.cend() || itW != vec.cend()); } int ModelTakuzu::findFirstIdenticalRowTo(int i) const { std::vector<Pawn> rowToScan = getRow(i); for (int rowIndex = 0; rowIndex < _sizeMap;++rowIndex) { if (rowIndex != i) { if (std::equal(_currentGrid.cbegin() + rowIndex * _sizeMap, _currentGrid.cbegin() + (rowIndex + 1) * _sizeMap, rowToScan.cbegin())) { return rowIndex; } } } return _sizeMap; } int ModelTakuzu::findFirstIdenticalColTo(int j) const { std::vector<Pawn> colToScan = getCol(j); for (int colIndex = 0; colIndex < _sizeMap; ++colIndex) { if (colIndex != j) { std::vector<Pawn> otherCol = getCol(colIndex); if (std::equal(colToScan.begin(), colToScan.end(), otherCol.begin(), otherCol.end())) { return colIndex; } } } return _sizeMap; }
std::for_each(rowsAndCols.begin(), rowsAndCols.end(), [&counterOcc](std::vector<Pawn> &vec) -> void { counterOcc.push_back(std::count(vec.begin(), vec.end(), Black)); counterOcc.push_back(std::count(vec.begin(), vec.end(), White)); })
call_expression
[ { "content": "enum Pawn : unsigned char { Empty, Black, White};\n\nusing Grid_ = std::vector<Pawn>;\n\n\n", "file_path": "ModelTakuzu.h", "rank": 0, "score": 86767.76155417053 }, { "content": " void updateCount(int i, int j, Pawn oldPawn, Pawn newPawn);\n\n Pawn getPawn(int i, int j) c...
C++
hardware/interface/power/Power.cpp
aospwhatawurst/aosp_android_device_samsung_exynos9820-common
77fe612901d6133d2734619cd3d1e86f6e7f0200
#define LOG_TAG "power@1.0-exynos9820" #include <android-base/logging.h> #include <android-base/file.h> #include <android-base/properties.h> #include <android-base/strings.h> #include "Power.h" #include <tsp.h> #include <iostream> namespace android { namespace hardware { namespace power { namespace V1_0 { namespace implementation { using ::android::hardware::power::V1_0::Feature; using ::android::hardware::power::V1_0::PowerHint; using ::android::hardware::power::V1_0::PowerStatePlatformSleepState; using ::android::hardware::power::V1_0::Status; using ::android::hardware::hidl_vec; using ::android::hardware::Return; using ::android::hardware::Void; #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) static std::string interactive_node_paths[] = { "/sys/class/sec/tsp/input/enabled", "/sys/class/sec/tsp1/input/enabled", "/sys/class/sec/tsp2/input/enabled", "/sys/class/sec/sec_epen/input/enabled", "/sys/class/sec/sec_touchkey/input/enabled", "/sys/class/sec/sec_sidekey/input/enabled", "/sys/class/power_supply/battery/lcd" }; template <typename T> static void writeNode(const std::string& path, const T& value) { std::ofstream node(path); if (!node) { PLOG(ERROR) << "Failed to open: " << path; return; } LOG(DEBUG) << "writeNode node: " << path << " value: " << value; node << value << std::endl; if (!node) { PLOG(ERROR) << "Failed to write: " << value; } } static bool doesNodeExist(const std::string& path) { std::ifstream f(path.c_str()); if (f.good()) { LOG(DEBUG) << "Found node: " << path; } return f.good(); } Power::Power() { size_t inode_size = ARRAY_SIZE(interactive_node_paths); mInteractionHandler.Init(); mEpic.Init(); tsp_init(); LOG(DEBUG) << "Looking for touchsceen/lcd nodes"; for (size_t i = 0; i < inode_size; i++) { std::string node_path = interactive_node_paths[i]; if (doesNodeExist(node_path)) { mInteractiveNodes.push_back(node_path); } } } Return<void> Power::setInteractive(bool interactive) { writeNode("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq", interactive ? "1950000" : "1053000"); if (mDoubleTapEnabled && !interactive) { tsp_enable_doubletap(); } for (size_t i = 0; i < mInteractiveNodes.size(); i++) { writeNode(mInteractiveNodes[i], interactive ? "1" : "0"); } if (mDoubleTapEnabled && interactive) { tsp_disable_doubletap(); } return Void(); } Return<void> Power::powerHint(PowerHint hint, int32_t data __unused) { switch (hint) { #if 0 case PowerHint::INTERACTION: mInteractionHandler.Acquire(data); break; #endif case PowerHint::VIDEO_ENCODE: { mEpic.videoEncode(hint); break; } default: return Void(); } return Void(); } Return<void> Power::setFeature(Feature feature, bool activate) { switch (feature) { case Feature::POWER_FEATURE_DOUBLE_TAP_TO_WAKE: if (activate) { LOG(INFO) << "Enable double tap to wake"; mDoubleTapEnabled = true; } else { LOG(INFO) << "Disable double tap to wake"; mDoubleTapEnabled = false; } break; default: break; } return Void(); } Return<void> Power::getPlatformLowPowerStats(getPlatformLowPowerStats_cb _hidl_cb) { hidl_vec<PowerStatePlatformSleepState> states; _hidl_cb(states, Status::SUCCESS); return Void(); } } } } } }
#define LOG_TAG "power@1.0-exynos9820" #include <android-base/logging.h> #include <android-base/file.h> #include <android-base/properties.h> #include <android-base/strings.h> #include "Power.h" #include <tsp.h> #include <iostream> namespace android { namespace hardware { namespace power { namespace V1_0 { namespace implementation { using ::android::hardware::power::V1_0::Feature; using ::android::hardware::power::V1_0::PowerHint; using ::android::hardware::power::V1_0::PowerStatePlatformSleepState; using ::android::hardware::power::V1_0::Status; using ::android::hardware::hidl_vec; using ::android::hardware::Return; using ::android::hardware::Void; #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) static std::string interactive_node_paths[] = { "/sys/class/sec/tsp/input/enabled", "/sys/class/sec/tsp1/input/enabled", "/sys/class/sec/tsp2/input/enabled", "/sys/class/sec/sec_epen/input/enabled", "/sys/class/sec/sec_touchkey/input/enabled", "/sys/class/sec/sec_sidekey/input/enabled", "/sys/class/power_supply/battery/lcd" }; template <typename T> static void writeNode(const std::string& path, const T& value) { std::ofstream node(path); if (!node) { PLOG(ERROR) << "Failed to open: " << path; return; } LOG(DEBUG) << "writeNode node: " << path << " value: " << value; node << value << std::endl; if (!node) { PLOG(ERROR) << "Failed to write: " << value; } } static bool doesNodeExist(const std::string& path) { std::ifstream f(path.c_str()); if (f.good()) { LOG(DEBUG) << "Found node: " << path; } return f.good(); }
Return<void> Power::setInteractive(bool interactive) { writeNode("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq", interactive ? "1950000" : "1053000"); if (mDoubleTapEnabled && !interactive) { tsp_enable_doubletap(); } for (size_t i = 0; i < mInteractiveNodes.size(); i++) { writeNode(mInteractiveNodes[i], interactive ? "1" : "0"); } if (mDoubleTapEnabled && interactive) { tsp_disable_doubletap(); } return Void(); } Return<void> Power::powerHint(PowerHint hint, int32_t data __unused) { switch (hint) { #if 0 case PowerHint::INTERACTION: mInteractionHandler.Acquire(data); break; #endif case PowerHint::VIDEO_ENCODE: { mEpic.videoEncode(hint); break; } default: return Void(); } return Void(); } Return<void> Power::setFeature(Feature feature, bool activate) { switch (feature) { case Feature::POWER_FEATURE_DOUBLE_TAP_TO_WAKE: if (activate) { LOG(INFO) << "Enable double tap to wake"; mDoubleTapEnabled = true; } else { LOG(INFO) << "Disable double tap to wake"; mDoubleTapEnabled = false; } break; default: break; } return Void(); } Return<void> Power::getPlatformLowPowerStats(getPlatformLowPowerStats_cb _hidl_cb) { hidl_vec<PowerStatePlatformSleepState> states; _hidl_cb(states, Status::SUCCESS); return Void(); } } } } } }
Power::Power() { size_t inode_size = ARRAY_SIZE(interactive_node_paths); mInteractionHandler.Init(); mEpic.Init(); tsp_init(); LOG(DEBUG) << "Looking for touchsceen/lcd nodes"; for (size_t i = 0; i < inode_size; i++) { std::string node_path = interactive_node_paths[i]; if (doesNodeExist(node_path)) { mInteractiveNodes.push_back(node_path); } } }
function_block-full_function
[ { "content": "namespace android {\n\nnamespace hardware {\n\nnamespace power {\n\nnamespace V1_0 {\n\nnamespace implementation {\n\n\n\nusing ::android::hardware::power::V1_0::Feature;\n\nusing ::android::hardware::power::V1_0::PowerHint;\n\nusing ::android::hardware::power::V1_0::IPower;\n\nusing ::android::ha...
C++
Src/Qt/qwt/src/qwt_spline.cpp
iclosure/smartsoft
62eaed49efd8306642b928ef4f2d96e36aca6527
#include "precomp.h" #include "qwt_spline.h" #include "qwt_math.h" class QwtSpline::PrivateData { public: PrivateData(): splineType( QwtSpline::Natural ) { } QwtSpline::SplineType splineType; QVector<double> a; QVector<double> b; QVector<double> c; QPolygonF points; }; static int lookup( double x, const QPolygonF &values ) { #if 0 #endif int i1; const int size = values.size(); if ( x <= values[0].x() ) i1 = 0; else if ( x >= values[size - 2].x() ) i1 = size - 2; else { i1 = 0; int i2 = size - 2; int i3 = 0; while ( i2 - i1 > 1 ) { i3 = i1 + ( ( i2 - i1 ) >> 1 ); if ( values[i3].x() > x ) i2 = i3; else i1 = i3; } } return i1; } QwtSpline::QwtSpline() { d_data = new PrivateData; } QwtSpline::QwtSpline( const QwtSpline& other ) { d_data = new PrivateData( *other.d_data ); } QwtSpline &QwtSpline::operator=( const QwtSpline & other ) { *d_data = *other.d_data; return *this; } QwtSpline::~QwtSpline() { delete d_data; } void QwtSpline::setSplineType( SplineType splineType ) { d_data->splineType = splineType; } QwtSpline::SplineType QwtSpline::splineType() const { return d_data->splineType; } bool QwtSpline::setPoints( const QPolygonF& points ) { const int size = points.size(); if ( size <= 2 ) { reset(); return false; } d_data->points = points; d_data->a.resize( size - 1 ); d_data->b.resize( size - 1 ); d_data->c.resize( size - 1 ); bool ok; if ( d_data->splineType == Periodic ) ok = buildPeriodicSpline( points ); else ok = buildNaturalSpline( points ); if ( !ok ) reset(); return ok; } QPolygonF QwtSpline::points() const { return d_data->points; } const QVector<double> &QwtSpline::coefficientsA() const { return d_data->a; } const QVector<double> &QwtSpline::coefficientsB() const { return d_data->b; } const QVector<double> &QwtSpline::coefficientsC() const { return d_data->c; } void QwtSpline::reset() { d_data->a.resize( 0 ); d_data->b.resize( 0 ); d_data->c.resize( 0 ); d_data->points.resize( 0 ); } bool QwtSpline::isValid() const { return d_data->a.size() > 0; } double QwtSpline::value( double x ) const { if ( d_data->a.size() == 0 ) return 0.0; const int i = lookup( x, d_data->points ); const double delta = x - d_data->points[i].x(); return( ( ( ( d_data->a[i] * delta ) + d_data->b[i] ) * delta + d_data->c[i] ) * delta + d_data->points[i].y() ); } bool QwtSpline::buildNaturalSpline( const QPolygonF &points ) { int i; const QPointF *p = points.data(); const int size = points.size(); double *a = d_data->a.data(); double *b = d_data->b.data(); double *c = d_data->c.data(); QVector<double> h( size - 1 ); for ( i = 0; i < size - 1; i++ ) { h[i] = p[i+1].x() - p[i].x(); if ( h[i] <= 0 ) return false; } QVector<double> d( size - 1 ); double dy1 = ( p[1].y() - p[0].y() ) / h[0]; for ( i = 1; i < size - 1; i++ ) { b[i] = c[i] = h[i]; a[i] = 2.0 * ( h[i-1] + h[i] ); const double dy2 = ( p[i+1].y() - p[i].y() ) / h[i]; d[i] = 6.0 * ( dy1 - dy2 ); dy1 = dy2; } for ( i = 1; i < size - 2; i++ ) { c[i] /= a[i]; a[i+1] -= b[i] * c[i]; } QVector<double> s( size ); s[1] = d[1]; for ( i = 2; i < size - 1; i++ ) s[i] = d[i] - c[i-1] * s[i-1]; s[size - 2] = - s[size - 2] / a[size - 2]; for ( i = size - 3; i > 0; i-- ) s[i] = - ( s[i] + b[i] * s[i+1] ) / a[i]; s[size - 1] = s[0] = 0.0; for ( i = 0; i < size - 1; i++ ) { a[i] = ( s[i+1] - s[i] ) / ( 6.0 * h[i] ); b[i] = 0.5 * s[i]; c[i] = ( p[i+1].y() - p[i].y() ) / h[i] - ( s[i+1] + 2.0 * s[i] ) * h[i] / 6.0; } return true; } bool QwtSpline::buildPeriodicSpline( const QPolygonF &points ) { int i; const QPointF *p = points.data(); const int size = points.size(); double *a = d_data->a.data(); double *b = d_data->b.data(); double *c = d_data->c.data(); QVector<double> d( size - 1 ); QVector<double> h( size - 1 ); QVector<double> s( size ); for ( i = 0; i < size - 1; i++ ) { h[i] = p[i+1].x() - p[i].x(); if ( h[i] <= 0.0 ) return false; } const int imax = size - 2; double htmp = h[imax]; double dy1 = ( p[0].y() - p[imax].y() ) / htmp; for ( i = 0; i <= imax; i++ ) { b[i] = c[i] = h[i]; a[i] = 2.0 * ( htmp + h[i] ); const double dy2 = ( p[i+1].y() - p[i].y() ) / h[i]; d[i] = 6.0 * ( dy1 - dy2 ); dy1 = dy2; htmp = h[i]; } a[0] = qSqrt( a[0] ); c[0] = h[imax] / a[0]; double sum = 0; for ( i = 0; i < imax - 1; i++ ) { b[i] /= a[i]; if ( i > 0 ) c[i] = - c[i-1] * b[i-1] / a[i]; a[i+1] = qSqrt( a[i+1] - qwtSqr( b[i] ) ); sum += qwtSqr( c[i] ); } b[imax-1] = ( b[imax-1] - c[imax-2] * b[imax-2] ) / a[imax-1]; a[imax] = qSqrt( a[imax] - qwtSqr( b[imax-1] ) - sum ); s[0] = d[0] / a[0]; sum = 0; for ( i = 1; i < imax; i++ ) { s[i] = ( d[i] - b[i-1] * s[i-1] ) / a[i]; sum += c[i-1] * s[i-1]; } s[imax] = ( d[imax] - b[imax-1] * s[imax-1] - sum ) / a[imax]; s[imax] = - s[imax] / a[imax]; s[imax-1] = -( s[imax-1] + b[imax-1] * s[imax] ) / a[imax-1]; for ( i = imax - 2; i >= 0; i-- ) s[i] = - ( s[i] + b[i] * s[i+1] + c[i] * s[imax] ) / a[i]; s[size-1] = s[0]; for ( i = 0; i < size - 1; i++ ) { a[i] = ( s[i+1] - s[i] ) / ( 6.0 * h[i] ); b[i] = 0.5 * s[i]; c[i] = ( p[i+1].y() - p[i].y() ) / h[i] - ( s[i+1] + 2.0 * s[i] ) * h[i] / 6.0; } return true; }
#include "precomp.h" #include "qwt_spline.h" #include "qwt_math.h" class QwtSpline::PrivateData { public: PrivateData(): splineType( QwtSpline::Natural ) { } QwtSpline::SplineType splineType; QVector<double> a; QVector<double> b; QVector<double> c; QPolygonF points; }; static int lookup( double x, const QPolygonF &values ) { #if 0 #endif int i1; const int size = values.size(); if ( x <= values[0].x() ) i1 = 0; else if ( x >= values[size - 2].x() ) i1 = size - 2; else {
QwtSpline::QwtSpline() { d_data = new PrivateData; } QwtSpline::QwtSpline( const QwtSpline& other ) { d_data = new PrivateData( *other.d_data ); } QwtSpline &QwtSpline::operator=( const QwtSpline & other ) { *d_data = *other.d_data; return *this; } QwtSpline::~QwtSpline() { delete d_data; } void QwtSpline::setSplineType( SplineType splineType ) { d_data->splineType = splineType; } QwtSpline::SplineType QwtSpline::splineType() const { return d_data->splineType; } bool QwtSpline::setPoints( const QPolygonF& points ) { const int size = points.size(); if ( size <= 2 ) { reset(); return false; } d_data->points = points; d_data->a.resize( size - 1 ); d_data->b.resize( size - 1 ); d_data->c.resize( size - 1 ); bool ok; if ( d_data->splineType == Periodic ) ok = buildPeriodicSpline( points ); else ok = buildNaturalSpline( points ); if ( !ok ) reset(); return ok; } QPolygonF QwtSpline::points() const { return d_data->points; } const QVector<double> &QwtSpline::coefficientsA() const { return d_data->a; } const QVector<double> &QwtSpline::coefficientsB() const { return d_data->b; } const QVector<double> &QwtSpline::coefficientsC() const { return d_data->c; } void QwtSpline::reset() { d_data->a.resize( 0 ); d_data->b.resize( 0 ); d_data->c.resize( 0 ); d_data->points.resize( 0 ); } bool QwtSpline::isValid() const { return d_data->a.size() > 0; } double QwtSpline::value( double x ) const { if ( d_data->a.size() == 0 ) return 0.0; const int i = lookup( x, d_data->points ); const double delta = x - d_data->points[i].x(); return( ( ( ( d_data->a[i] * delta ) + d_data->b[i] ) * delta + d_data->c[i] ) * delta + d_data->points[i].y() ); } bool QwtSpline::buildNaturalSpline( const QPolygonF &points ) { int i; const QPointF *p = points.data(); const int size = points.size(); double *a = d_data->a.data(); double *b = d_data->b.data(); double *c = d_data->c.data(); QVector<double> h( size - 1 ); for ( i = 0; i < size - 1; i++ ) { h[i] = p[i+1].x() - p[i].x(); if ( h[i] <= 0 ) return false; } QVector<double> d( size - 1 ); double dy1 = ( p[1].y() - p[0].y() ) / h[0]; for ( i = 1; i < size - 1; i++ ) { b[i] = c[i] = h[i]; a[i] = 2.0 * ( h[i-1] + h[i] ); const double dy2 = ( p[i+1].y() - p[i].y() ) / h[i]; d[i] = 6.0 * ( dy1 - dy2 ); dy1 = dy2; } for ( i = 1; i < size - 2; i++ ) { c[i] /= a[i]; a[i+1] -= b[i] * c[i]; } QVector<double> s( size ); s[1] = d[1]; for ( i = 2; i < size - 1; i++ ) s[i] = d[i] - c[i-1] * s[i-1]; s[size - 2] = - s[size - 2] / a[size - 2]; for ( i = size - 3; i > 0; i-- ) s[i] = - ( s[i] + b[i] * s[i+1] ) / a[i]; s[size - 1] = s[0] = 0.0; for ( i = 0; i < size - 1; i++ ) { a[i] = ( s[i+1] - s[i] ) / ( 6.0 * h[i] ); b[i] = 0.5 * s[i]; c[i] = ( p[i+1].y() - p[i].y() ) / h[i] - ( s[i+1] + 2.0 * s[i] ) * h[i] / 6.0; } return true; } bool QwtSpline::buildPeriodicSpline( const QPolygonF &points ) { int i; const QPointF *p = points.data(); const int size = points.size(); double *a = d_data->a.data(); double *b = d_data->b.data(); double *c = d_data->c.data(); QVector<double> d( size - 1 ); QVector<double> h( size - 1 ); QVector<double> s( size ); for ( i = 0; i < size - 1; i++ ) { h[i] = p[i+1].x() - p[i].x(); if ( h[i] <= 0.0 ) return false; } const int imax = size - 2; double htmp = h[imax]; double dy1 = ( p[0].y() - p[imax].y() ) / htmp; for ( i = 0; i <= imax; i++ ) { b[i] = c[i] = h[i]; a[i] = 2.0 * ( htmp + h[i] ); const double dy2 = ( p[i+1].y() - p[i].y() ) / h[i]; d[i] = 6.0 * ( dy1 - dy2 ); dy1 = dy2; htmp = h[i]; } a[0] = qSqrt( a[0] ); c[0] = h[imax] / a[0]; double sum = 0; for ( i = 0; i < imax - 1; i++ ) { b[i] /= a[i]; if ( i > 0 ) c[i] = - c[i-1] * b[i-1] / a[i]; a[i+1] = qSqrt( a[i+1] - qwtSqr( b[i] ) ); sum += qwtSqr( c[i] ); } b[imax-1] = ( b[imax-1] - c[imax-2] * b[imax-2] ) / a[imax-1]; a[imax] = qSqrt( a[imax] - qwtSqr( b[imax-1] ) - sum ); s[0] = d[0] / a[0]; sum = 0; for ( i = 1; i < imax; i++ ) { s[i] = ( d[i] - b[i-1] * s[i-1] ) / a[i]; sum += c[i-1] * s[i-1]; } s[imax] = ( d[imax] - b[imax-1] * s[imax-1] - sum ) / a[imax]; s[imax] = - s[imax] / a[imax]; s[imax-1] = -( s[imax-1] + b[imax-1] * s[imax] ) / a[imax-1]; for ( i = imax - 2; i >= 0; i-- ) s[i] = - ( s[i] + b[i] * s[i+1] + c[i] * s[imax] ) / a[i]; s[size-1] = s[0]; for ( i = 0; i < size - 1; i++ ) { a[i] = ( s[i+1] - s[i] ) / ( 6.0 * h[i] ); b[i] = 0.5 * s[i]; c[i] = ( p[i+1].y() - p[i].y() ) / h[i] - ( s[i+1] + 2.0 * s[i] ) * h[i] / 6.0; } return true; }
i1 = 0; int i2 = size - 2; int i3 = 0; while ( i2 - i1 > 1 ) { i3 = i1 + ( ( i2 - i1 ) >> 1 ); if ( values[i3].x() > x ) i2 = i3; else i1 = i3; } } return i1; }
function_block-function_prefix_line
[ { "content": "class BCGCBPRODLLEXPORT CBCGPPointsArray : public CArray<CBCGPPoint, const CBCGPPoint&>\n\n{\n\npublic:\n\n\tCBCGPPointsArray() {}\n\n\tCBCGPPointsArray(int nNewSize, int nGrowBy = -1)\n\n\t{\n\n\t\tSetSize(nNewSize, nGrowBy);\n\n\t}\n\n\n\n\t~CBCGPPointsArray() {}\n\n\n\n\tCBCGPRect GetBoundsRect...
C++
src/client/commands/CmdBase.cpp
lclc/opentxs
0bc847c6601d20e3346bb2faf81feda3a14ab303
#include "CmdBase.hpp" #include "../ot_made_easy_ot.hpp" #include <opentxs/client/ot_otapi_ot.hpp> #include "../ot_utility_ot.hpp" #include <opentxs/client/OpenTransactions.hpp> #include <opentxs/client/OTAPI.hpp> #include <opentxs/client/OTWallet.hpp> #include <opentxs/core/Account.hpp> #include <opentxs/core/AssetContract.hpp> #include <opentxs/core/OTLog.hpp> #include <opentxs/core/OTPseudonym.hpp> #include <opentxs/core/OTServerContract.hpp> #include <map> #include <sstream> using namespace opentxs; using namespace std; CmdBase::CmdBase() : category(catError) , command(nullptr) , help(nullptr) , usage(nullptr) { for (int i = 0; i < MAX_ARGS; i++) { args[i] = nullptr; } } CmdBase::~CmdBase() { } bool CmdBase::checkAccount(const char* name, string& account) const { if (!checkMandatory(name, account)) { return false; } OTWallet* wallet = getWallet(); Account* theAccount = wallet->GetAccount(account); if (theAccount == nullptr) { theAccount = wallet->GetAccountPartialMatch(account); if (theAccount == nullptr) { otOut << "Error: " << name << ": unknown account: " << account << "\n"; return false; } } String tmp; theAccount->GetPurportedAccountID().GetString(tmp); account = tmp.Get(); otOut << "Using " << name << ": " << account << "\n"; return true; } int64_t CmdBase::checkAmount(const char* name, const string& amount, const string& myacct) const { if (!checkMandatory(name, amount)) { return OT_ERROR_AMOUNT; } string assetType = getAccountAssetType(myacct); if ("" == assetType) { return OT_ERROR_AMOUNT; } int64_t value = OTAPI_Wrap::StringToAmount(assetType, amount); if (OT_ERROR_AMOUNT == value) { otOut << "Error: " << name << ": invalid amount: " << amount << "\n"; return OT_ERROR_AMOUNT; } return value; } bool CmdBase::checkFlag(const char* name, const string& value) const { if (!checkMandatory(name, value)) { return false; } if (value != "false" && value != "true") { otOut << "Error: " << name << ": expected 'false' or 'true'.\n"; return false; } return true; } int32_t CmdBase::checkIndex(const char* name, const string& index, int32_t items) const { if (!checkValue(name, index)) { return -1; } if (!checkIndicesRange(name, index, items)) { return -1; } return stoi(index); } bool CmdBase::checkIndices(const char* name, const string& indices) const { if (!checkMandatory(name, indices)) { return false; } if ("all" == indices) { return true; } for (string::size_type i = 0; i < indices.length(); i++) { if (!isdigit(indices[i])) { otOut << "Error: " << name << ": not a value: " << indices << "\n"; return false; } for (i++; i < indices.length() && isdigit(indices[i]); i++) { } if (i < indices.length() && ',' != indices[i]) { otOut << "Error: " << name << ": not a value: " << indices << "\n"; return false; } } return true; } bool CmdBase::checkIndicesRange(const char* name, const string& indices, int32_t items) const { if ("all" == indices) { return true; } for (string::size_type i = 0; i < indices.length(); i++) { int32_t value = 0; for (; isdigit(indices[i]); i++) { value = value * 10 + indices[i] - '0'; } if (0 > value || value >= items) { otOut << "Error: " << name << ": value (" << value << ") out of range (must be < " << items << ")\n"; return false; } } return true; } bool CmdBase::checkMandatory(const char* name, const string& value) const { if ("" == value) { otOut << "Error: " << name << ": mandatory parameter not specified.\n"; return false; } return true; } bool CmdBase::checkNym(const char* name, string& nym) const { if (!checkMandatory(name, nym)) { return false; } OTWallet* wallet = getWallet(); OTPseudonym* theNym = wallet->GetNymByID(nym); if (theNym == nullptr) { theNym = wallet->GetNymByIDPartialMatch(nym); if (theNym == nullptr) { otOut << "Error: " << name << ": unknown nymm: " << nym << "\n"; return false; } } String tmp; theNym->GetIdentifier(tmp); nym = tmp.Get(); otOut << "Using " << name << ": " << nym << "\n"; return true; } bool CmdBase::checkPurse(const char* name, string& purse) const { if (!checkMandatory(name, purse)) { return false; } OTWallet* wallet = getWallet(); AssetContract* thePurse = wallet->GetAssetContract(purse); if (thePurse == nullptr) { thePurse = wallet->GetAssetContractPartialMatch(purse); if (thePurse == nullptr) { otOut << "Error: " << name << ": unknown purse: " << purse << "\n"; return false; } } String tmp; thePurse->GetIdentifier(tmp); purse = tmp.Get(); otOut << "Using " << name << ": " << purse << "\n"; return true; } bool CmdBase::checkServer(const char* name, string& server) const { if (!checkMandatory(name, server)) { return false; } OTWallet* wallet = getWallet(); OTServerContract* theServer = wallet->GetServerContract(server); if (theServer == nullptr) { theServer = wallet->GetServerContractPartialMatch(server); if (theServer == nullptr) { otOut << "Error: " << name << ": unknown server: " << server << "\n"; return false; } } String tmp; theServer->GetIdentifier(tmp); server = tmp.Get(); otOut << "Using " << name << ": " << server << "\n"; return true; } int64_t CmdBase::checkTransNum(const char* name, const string& id) const { if (!checkMandatory(name, id)) { return -1; } for (string::size_type i = 0; i < id.length(); i++) { if (!isdigit(id[i])) { otOut << "Error: " << name << ": not a value: " << id << "\n"; return -1; } } int64_t value = stoll(id); if (0 >= value) { otOut << "Error: " << name << ": invalid value: " << id << "\n"; return -1; } return value; } bool CmdBase::checkValue(const char* name, const string& value) const { if (!checkMandatory(name, value)) { return false; } for (string::size_type i = 0; i < value.length(); i++) { if (!isdigit(value[i])) { otOut << "Error: " << name << ": not a value: " << value << "\n"; return false; } } return true; } void CmdBase::dashLine() const { cout << "--------------------------------------" "--------------------------------------\n"; } const vector<string>& CmdBase::extractArgumentNames() { if (0 != argNames.size()) { return argNames; } for (int i = 0; i < MAX_ARGS && args[i] != nullptr; i++) { const char* arg = args[i]; while ('[' == *arg || '-' == *arg) { arg++; } string argName = ""; for (; isalpha(*arg); arg++) { argName += *arg; } argNames.push_back(argName); } return argNames; } string CmdBase::formatAmount(const string& assetType, int64_t amount) const { if (OT_ERROR_AMOUNT == amount) { return "UNKNOWN_AMOUNT"; } if ("" == assetType) { return to_string(amount); } return OTAPI_Wrap::FormatAmount(assetType, amount); } Category CmdBase::getCategory() const { return category; } const char* CmdBase::getCommand() const { return command; } const char* CmdBase::getHelp() const { return help; } string CmdBase::getAccountAssetType(const string& myacct) const { string assetType = OTAPI_Wrap::GetAccountWallet_AssetTypeID(myacct); if ("" == assetType) { otOut << "Error: cannot load asset type from myacct.\n"; } return assetType; } string CmdBase::getAccountNym(const string& myacct) const { string mynym = OTAPI_Wrap::GetAccountWallet_NymID(myacct); if ("" == mynym) { otOut << "Error: cannot determine mynym from myacct.\n"; } return mynym; } string CmdBase::getAccountServer(const string& myacct) const { string server = OTAPI_Wrap::GetAccountWallet_ServerID(myacct); if ("" == server) { otOut << "Error: cannot determine server from myacct.\n"; } return server; } string CmdBase::getOption(string optionName) const { auto result = options.find(optionName); if (result == options.end()) { otWarn << "Option " << optionName << " not found.\n"; return ""; } otInfo << "Option " << result->first << ": " << result->second << "\n"; return result->second; } string CmdBase::getUsage() const { stringstream ss; ss << "Usage: " << command; for (int i = 0; i < MAX_ARGS && args[i] != nullptr; i++) { ss << " " << args[i]; } ss << "\n\n" << help << "\n\n"; if (usage != nullptr) { ss << usage << "\n\n"; } return ss.str(); } OTWallet* CmdBase::getWallet() const { OTWallet* wallet = OTAPI_Wrap::OTAPI()->GetWallet(); OT_ASSERT_MSG(wallet != nullptr, "Cannot load wallet->\n"); return wallet; } int32_t CmdBase::harvestTxNumbers(const string& contract, const string& mynym) { OTAPI_Wrap::Msg_HarvestTransactionNumbers(contract, mynym, false, false, false, false, false); return -1; } string CmdBase::inputLine() { return OT_CLI_ReadLine(); } string CmdBase::inputText(const char* what) { cout << "Please paste " << what << ",\n" << "followed by an EOF or a ~ on a line by itself:\n"; string input = OT_CLI_ReadUntilEOF(); if ("" == input) { otOut << "Error: you did not paste " << what << ".\n"; } return input; } int32_t CmdBase::processResponse(const string& response, const char* what) const { switch (responseStatus(response)) { case 1: break; case 0: otOut << "Error: failed to " << what << ".\n"; return -1; default: otOut << "Error: cannot " << what << ".\n"; return -1; } cout << response << "\n"; return 1; } int32_t CmdBase::processTxResponse(const string& server, const string& mynym, const string& myacct, const string& response, const char* what) const { if (1 != responseStatus(response)) { otOut << "Error: cannot " << what << ".\n"; return -1; } if (1 != VerifyMsgBalanceAgrmntSuccess(server, mynym, myacct, response)) { otOut << "Error: " << what << " balance agreement failed.\n"; return -1; } if (1 != VerifyMsgTrnxSuccess(server, mynym, myacct, response)) { otOut << "Error: " << what << " transaction failed.\n"; return -1; } cout << response << "\n"; return 1; } int32_t CmdBase::responseReply(const string& response, const string& server, const string& mynym, const string& myacct, const char* function) const { return InterpretTransactionMsgReply(server, mynym, myacct, function, response); } int32_t CmdBase::responseStatus(const string& response) const { return VerifyMessageSuccess(response); } bool CmdBase::run(const map<string, string>& _options) { options = _options; int32_t returnValue = runWithOptions(); options.empty(); switch (returnValue) { case 0: return true; case 1: return true; case -1: return false; default: otOut << "Error: undefined error code: " << returnValue << ".\n"; break; } return false; } vector<string> CmdBase::tokenize(const string& str, char delim, bool noEmpty) const { vector<string> tokens; const char* p = str.c_str(); int begin = 0; while (true) { int next = begin; while (p[next] != delim && '\0' != p[next]) { next++; } if (next != begin || !noEmpty) { tokens.push_back(str.substr(begin, next - begin)); } if ('\0' == p[next]) { break; } begin = next + 1; } return tokens; }
#include "CmdBase.hpp" #include "../ot_made_easy_ot.hpp" #include <opentxs/client/ot_otapi_ot.hpp> #include "../ot_utility_ot.hpp" #include <opentxs/client/OpenTransactions.hpp> #include <opentxs/client/OTAPI.hpp> #include <opentxs/client/OTWallet.hpp> #include <opentxs/core/Account.hpp> #include <opentxs/core/AssetContract.hpp> #include <opentxs/core/OTLog.hpp> #include <opentxs/core/OTPseudonym.hpp> #include <opentxs/core/OTServerContract.hpp> #include <map> #include <sstream> using namespace opentxs; using namespace std; CmdBase::CmdBase() : category(catError) , command(nullptr) , help(nullptr) , usage(nullptr) { for (int i = 0; i < MAX_ARGS; i++) { args[i] = nullptr; } } CmdBase::~CmdBase() { } bool CmdBase::checkAccount(const char* name, string& account) const { if (!checkMandatory(name, account)) { return false; } OTWallet* wallet = getWallet(); Account* theAccount = wallet->GetAccount(account); if (theAccount == nullptr) { theAccount = wallet->GetAccountPartialMatch(account); if (theAccount == nullptr) { otOut << "Error: " << name << ": unknown account: " << account << "\n"; return false; } } String tmp; theAccount->GetPurportedAccountID().GetString(tmp); account = tmp.Get(); otOut << "Using " << name << ": " << account << "\n"; return true; } int64_t CmdBase::checkAmount(const char* name, const string& amount, const string& myacct) const { if (!checkMandatory(name, amount)) { return OT_ERROR_AMOUNT; } string assetType = getAccountAssetType(myacct); if ("" == assetType) { return OT_ERROR_AMOUNT; } int64_t value = OTAPI_Wrap::StringToAmount(assetType, amount); if (OT_ERROR_AMOUNT == value) { otOut << "Error: " << name << ": invalid amount: " << amount << "\n"; return OT_ERROR_AMOUNT; } return value; } bool CmdBase::checkFlag(const char* name, const string& value) const { if (!checkMandatory(name, value)) { return false; } if (value != "false" && value != "true") { otOut << "Error: " << name << ": expected 'false' or 'true'.\n"; return false; } return true; } int32_t CmdBase::checkIndex(const char* name, const string& index, int32_t items) const { if (!checkValue(name, index)) { return -1; } if (!checkIndicesRange(name, index, items)) { return -1; } return stoi(index); } bool CmdBase::checkIndices(const char* name, const string& indices) const { if (!checkMandatory(name, indices)) { return false; } if ("all" == indices) { return true; } for (string::size_type i = 0; i < indices.length(); i++) { if (!isdigit(indices[i])) { otOut << "Error: " << name << ": not a value: " << indices << "\n"; return false; } for (i++; i < indices.length() && isdigit(indices[i]); i++) { } if (i < indices.length() && ',' != indices[i]) { otOut << "Error: " << name << ": not a value: " << indices << "\n"; return false; } } return true; } bool CmdBase::checkIndicesRange(const char* name, const string& indices, int32_t items) const { if ("all" == indices) { return true; } for (string::size_type i = 0; i < indices.length(); i++) { int32_t value = 0; for (; isdigit(indices[i]); i++) { value = value * 10 + indices[i] - '0'; } if (0 > value || value >= items) { otOut << "Error: " << name << ": value (" << value << ") out of range (must be < " << items << ")\n"; return false; } } return true; } bool CmdBase::checkMandatory(const char* name, const string& value) const { if ("" == value) { otOut << "Error: " << name << ": mandatory parameter not specified.\n"; return false; } return true; } bool CmdBase::checkNym(const char* name, string& nym) const { if (!checkMandatory(name, nym)) { return false; } OTWallet* wallet = getWallet(); OTPseudonym* theNym = wallet->GetNymByID(nym); if (theNym == nullptr) { theNym = wallet->GetNymByIDPartialMatch(nym); if (theNym == nullptr) { otOut << "Error: " << name << ": unknown nymm: " << nym << "\n"; return false; } } String tmp; theNym->GetIdentifier(tmp); nym = tmp.Get(); otOut << "Using " << name << ": " << nym << "\n"; return true; } bool CmdBase::checkPurse(const char* name, string& purse) const { if (!checkMandatory(name, purse)) { return false; } OTWallet* wallet = getWallet(); AssetContract* thePurse = wallet->GetAssetContract(purse); if (thePurse == nullptr) { thePurse = wallet->GetAssetContractPartialMatch(purse); if (thePurse == nullptr) { otOut << "Error: " << name << ": unknown purse: " << purse << "\n"; return false; } } String tmp; thePurse->GetIdentifier(tmp); purse = tmp.Get(); otOut << "Using " << name << ": " << purse << "\n"; return true; } bool CmdBase::checkServer(const char* name, string& server) const { if (!checkMandatory(name, server)) { return false; } OTWallet* wallet = getWallet(); OTServerContract* theServer = wallet->GetServerContract(server); if (theServer == nullptr) { theServer = wallet->GetServerContractPartialMatch(server); if (theServer == nullptr) { otOut << "Error: " << name << ": unknown server: " << server << "\n"; return false; } } String tmp; theServer->GetIdentifier(tmp); server = tmp.Get(); otOut << "Using " << name << ": " << server << "\n"; return true; } int64_t CmdBase::checkTransNum(const char* name, const string& id) const { if (!checkMandatory(name, id)) { return -1; } for (string::size_type i = 0; i < id.length(); i++) { if (!isdigit(id[i])) { otOut << "Error: " << name << ": not a value: " << id << "\n"; return -1; } } int64_t value = stoll(id); if (0 >= value) { otOut << "Error: " << name << ": invalid value: " << id << "\n"; return -1; } return value; } bool CmdBase::checkValue(const char* name, const string& value) const { if (!checkMandatory(name, value)) { return false; } for (string::size_type i = 0; i < value.length(); i++) { if (!isdigit(value[i])) { otOut << "Error: " << name << ": not a value: " << value << "\n"; return false; } } return true; } void CmdBase::dashLine() const { cout << "--------------------------------------" "--------------------------------------\n"; } const vector<string>& CmdBase::extractArgumentNames() { if (0 != argNames.size()) { return argNames; } for (int i = 0; i < MAX_ARGS && args[i] != nullptr; i++) { const char* arg = args[i]; while ('[' == *arg || '-' == *arg) { arg++; } string argName = ""; for (; isalpha(*arg); arg++) { argName += *arg; } argNames.push_back(argName); } return argNames; }
Category CmdBase::getCategory() const { return category; } const char* CmdBase::getCommand() const { return command; } const char* CmdBase::getHelp() const { return help; } string CmdBase::getAccountAssetType(const string& myacct) const { string assetType = OTAPI_Wrap::GetAccountWallet_AssetTypeID(myacct); if ("" == assetType) { otOut << "Error: cannot load asset type from myacct.\n"; } return assetType; } string CmdBase::getAccountNym(const string& myacct) const { string mynym = OTAPI_Wrap::GetAccountWallet_NymID(myacct); if ("" == mynym) { otOut << "Error: cannot determine mynym from myacct.\n"; } return mynym; } string CmdBase::getAccountServer(const string& myacct) const { string server = OTAPI_Wrap::GetAccountWallet_ServerID(myacct); if ("" == server) { otOut << "Error: cannot determine server from myacct.\n"; } return server; } string CmdBase::getOption(string optionName) const { auto result = options.find(optionName); if (result == options.end()) { otWarn << "Option " << optionName << " not found.\n"; return ""; } otInfo << "Option " << result->first << ": " << result->second << "\n"; return result->second; } string CmdBase::getUsage() const { stringstream ss; ss << "Usage: " << command; for (int i = 0; i < MAX_ARGS && args[i] != nullptr; i++) { ss << " " << args[i]; } ss << "\n\n" << help << "\n\n"; if (usage != nullptr) { ss << usage << "\n\n"; } return ss.str(); } OTWallet* CmdBase::getWallet() const { OTWallet* wallet = OTAPI_Wrap::OTAPI()->GetWallet(); OT_ASSERT_MSG(wallet != nullptr, "Cannot load wallet->\n"); return wallet; } int32_t CmdBase::harvestTxNumbers(const string& contract, const string& mynym) { OTAPI_Wrap::Msg_HarvestTransactionNumbers(contract, mynym, false, false, false, false, false); return -1; } string CmdBase::inputLine() { return OT_CLI_ReadLine(); } string CmdBase::inputText(const char* what) { cout << "Please paste " << what << ",\n" << "followed by an EOF or a ~ on a line by itself:\n"; string input = OT_CLI_ReadUntilEOF(); if ("" == input) { otOut << "Error: you did not paste " << what << ".\n"; } return input; } int32_t CmdBase::processResponse(const string& response, const char* what) const { switch (responseStatus(response)) { case 1: break; case 0: otOut << "Error: failed to " << what << ".\n"; return -1; default: otOut << "Error: cannot " << what << ".\n"; return -1; } cout << response << "\n"; return 1; } int32_t CmdBase::processTxResponse(const string& server, const string& mynym, const string& myacct, const string& response, const char* what) const { if (1 != responseStatus(response)) { otOut << "Error: cannot " << what << ".\n"; return -1; } if (1 != VerifyMsgBalanceAgrmntSuccess(server, mynym, myacct, response)) { otOut << "Error: " << what << " balance agreement failed.\n"; return -1; } if (1 != VerifyMsgTrnxSuccess(server, mynym, myacct, response)) { otOut << "Error: " << what << " transaction failed.\n"; return -1; } cout << response << "\n"; return 1; } int32_t CmdBase::responseReply(const string& response, const string& server, const string& mynym, const string& myacct, const char* function) const { return InterpretTransactionMsgReply(server, mynym, myacct, function, response); } int32_t CmdBase::responseStatus(const string& response) const { return VerifyMessageSuccess(response); } bool CmdBase::run(const map<string, string>& _options) { options = _options; int32_t returnValue = runWithOptions(); options.empty(); switch (returnValue) { case 0: return true; case 1: return true; case -1: return false; default: otOut << "Error: undefined error code: " << returnValue << ".\n"; break; } return false; } vector<string> CmdBase::tokenize(const string& str, char delim, bool noEmpty) const { vector<string> tokens; const char* p = str.c_str(); int begin = 0; while (true) { int next = begin; while (p[next] != delim && '\0' != p[next]) { next++; } if (next != begin || !noEmpty) { tokens.push_back(str.substr(begin, next - begin)); } if ('\0' == p[next]) { break; } begin = next + 1; } return tokens; }
string CmdBase::formatAmount(const string& assetType, int64_t amount) const { if (OT_ERROR_AMOUNT == amount) { return "UNKNOWN_AMOUNT"; } if ("" == assetType) { return to_string(amount); } return OTAPI_Wrap::FormatAmount(assetType, amount); }
function_block-function_prefix_line
[ { "content": "class String;\n", "file_path": "include/opentxs/core/Account.hpp", "rank": 0, "score": 273173.24958394736 }, { "content": "class Account;\n", "file_path": "include/opentxs/server/Transactor.hpp", "rank": 1, "score": 272706.39791854477 }, { "content": "class ...