hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6c5f8b0d9e21d735e32da5b6cd7df24a3d8a8c0e
328
hpp
C++
pythran/pythonic/include/math/isinf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,647
2015-01-13T01:45:38.000Z
2022-03-28T01:23:41.000Z
pythran/pythonic/include/math/isinf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
1,116
2015-01-01T09:52:05.000Z
2022-03-18T21:06:40.000Z
pythran/pythonic/include/math/isinf.hpp
davidbrochart/pythran
24b6c8650fe99791a4091cbdc2c24686e86aa67c
[ "BSD-3-Clause" ]
180
2015-02-12T02:47:28.000Z
2022-03-14T10:28:18.000Z
#ifndef PYTHONIC_INCLUDE_MATH_ISINF_HPP #define PYTHONIC_INCLUDE_MATH_ISINF_HPP #include "pythonic/include/utils/functor.hpp" #include <cmath> PYTHONIC_NS_BEGIN namespace math { template <class T> bool isinf(T const &v) { return std::isinf(v); } DEFINE_FUNCTOR(pythonic::math, isinf); } PYTHONIC_NS_END #endif
15.619048
45
0.759146
davidbrochart
6c6209dc6c677a30dee8c46d4f40c671423853df
7,573
cpp
C++
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
null
null
null
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
1
2020-05-17T04:37:32.000Z
2020-05-17T04:37:32.000Z
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.0-rc.1+0545ce110 #include <hxcpp.h> #ifndef INCLUDED_tink_core_LinkObject #include <tink/core/LinkObject.h> #endif #ifndef INCLUDED_tink_core__Callback_CallbackList_Impl_ #include <tink/core/_Callback/CallbackList_Impl_.h> #endif #ifndef INCLUDED_tink_core__Callback_Callback_Impl_ #include <tink/core/_Callback/Callback_Impl_.h> #endif #ifndef INCLUDED_tink_core__Callback_ListCell #include <tink/core/_Callback/ListCell.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_153__new,"tink.core._Callback.CallbackList_Impl_","_new",0x5530bdef,"tink.core._Callback.CallbackList_Impl_._new","tink/core/Callback.hx",153,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_157_get_length,"tink.core._Callback.CallbackList_Impl_","get_length",0x2f368bbd,"tink.core._Callback.CallbackList_Impl_.get_length","tink/core/Callback.hx",157,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_159_add,"tink.core._Callback.CallbackList_Impl_","add",0x29b71553,"tink.core._Callback.CallbackList_Impl_.add","tink/core/Callback.hx",159,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_166_invoke,"tink.core._Callback.CallbackList_Impl_","invoke",0x9c17df86,"tink.core._Callback.CallbackList_Impl_.invoke","tink/core/Callback.hx",166,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_170_clear,"tink.core._Callback.CallbackList_Impl_","clear",0x81bd453f,"tink.core._Callback.CallbackList_Impl_.clear","tink/core/Callback.hx",170,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_174_invokeAndClear,"tink.core._Callback.CallbackList_Impl_","invokeAndClear",0xfb2cccdc,"tink.core._Callback.CallbackList_Impl_.invokeAndClear","tink/core/Callback.hx",174,0x0104eb06) namespace tink{ namespace core{ namespace _Callback{ void CallbackList_Impl__obj::__construct() { } Dynamic CallbackList_Impl__obj::__CreateEmpty() { return new CallbackList_Impl__obj; } void *CallbackList_Impl__obj::_hx_vtable = 0; Dynamic CallbackList_Impl__obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< CallbackList_Impl__obj > _hx_result = new CallbackList_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool CallbackList_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x17f0bab2; } ::Array< ::Dynamic> CallbackList_Impl__obj::_new(){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_153__new) HXDLIN( 153) ::Array< ::Dynamic> this1 = ::Array_obj< ::Dynamic>::__new(0); HXDLIN( 153) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC0(CallbackList_Impl__obj,_new,return ) int CallbackList_Impl__obj::get_length(::Array< ::Dynamic> this1){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_157_get_length) HXDLIN( 157) return this1->length; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(CallbackList_Impl__obj,get_length,return ) ::Dynamic CallbackList_Impl__obj::add(::Array< ::Dynamic> this1, ::Dynamic cb){ HX_GC_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_159_add) HXLINE( 160) ::tink::core::_Callback::ListCell node = ::tink::core::_Callback::ListCell_obj::__alloc( HX_CTX ,cb,this1); HXLINE( 161) this1->push(node); HXLINE( 162) return node; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,add,return ) void CallbackList_Impl__obj::invoke(::Array< ::Dynamic> this1, ::Dynamic data){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_166_invoke) HXDLIN( 166) int _g = 0; HXDLIN( 166) ::Array< ::Dynamic> _g1 = this1->copy(); HXDLIN( 166) while((_g < _g1->length)){ HXDLIN( 166) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 166) _g = (_g + 1); HXLINE( 167) if (hx::IsNotNull( cell->cb )) { HXLINE( 167) ::tink::core::_Callback::Callback_Impl__obj::invoke(cell->cb,data); } } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,invoke,(void)) void CallbackList_Impl__obj::clear(::Array< ::Dynamic> this1){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_170_clear) HXDLIN( 170) int _g = 0; HXDLIN( 170) ::Array< ::Dynamic> _g1 = this1->splice(0,this1->length); HXDLIN( 170) while((_g < _g1->length)){ HXDLIN( 170) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 170) _g = (_g + 1); HXLINE( 171) cell->clear(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC1(CallbackList_Impl__obj,clear,(void)) void CallbackList_Impl__obj::invokeAndClear(::Array< ::Dynamic> this1, ::Dynamic data){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_174_invokeAndClear) HXDLIN( 174) int _g = 0; HXDLIN( 174) ::Array< ::Dynamic> _g1 = this1->splice(0,this1->length); HXDLIN( 174) while((_g < _g1->length)){ HXDLIN( 174) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 174) _g = (_g + 1); HXLINE( 175) if (hx::IsNotNull( cell->cb )) { HXLINE( 175) ::tink::core::_Callback::Callback_Impl__obj::invoke(cell->cb,data); } } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,invokeAndClear,(void)) CallbackList_Impl__obj::CallbackList_Impl__obj() { } bool CallbackList_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"add") ) { outValue = add_dyn(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"clear") ) { outValue = clear_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"invoke") ) { outValue = invoke_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"get_length") ) { outValue = get_length_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"invokeAndClear") ) { outValue = invokeAndClear_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *CallbackList_Impl__obj_sMemberStorageInfo = 0; static hx::StaticInfo *CallbackList_Impl__obj_sStaticStorageInfo = 0; #endif hx::Class CallbackList_Impl__obj::__mClass; static ::String CallbackList_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), HX_("get_length",af,04,8f,8f), HX_("add",21,f2,49,00), HX_("invoke",78,77,e0,9f), HX_("clear",8d,71,5b,48), HX_("invokeAndClear",ce,a6,19,d4), ::String(null()) }; void CallbackList_Impl__obj::__register() { CallbackList_Impl__obj _hx_dummy; CallbackList_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("tink.core._Callback.CallbackList_Impl_",a0,82,ff,67); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &CallbackList_Impl__obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(CallbackList_Impl__obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< CallbackList_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = CallbackList_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = CallbackList_Impl__obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace tink } // end namespace core } // end namespace _Callback
40.068783
229
0.74594
sonygod
48417b49da918eff1b1f74ab854371df97d8386b
12,316
cpp
C++
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
19
2017-04-03T09:06:21.000Z
2022-03-05T19:06:07.000Z
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2019-05-24T14:40:07.000Z
2020-04-15T01:10:23.000Z
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2020-03-08T07:14:49.000Z
2020-03-09T10:39:52.000Z
/* * VS_TextureInternal.cpp * VectorStorm * * Created by Trevor Powell on 3/08/08. * Copyright 2009 Trevor Powell. All rights reserved. * */ #include "VS_TextureInternal.h" #include "VS_Color.h" #include "VS_FloatImage.h" #include "VS_Image.h" #include "VS_HalfIntImage.h" #include "VS_HalfFloatImage.h" #include "VS_RenderTarget.h" #include "VS_RenderBuffer.h" #include "VS/Files/VS_File.h" #include "VS/Memory/VS_Store.h" #include "VS_OpenGL.h" #if TARGET_OS_IPHONE #include "VS_TextureInternalIPhone.h" vsTextureInternal::vsTextureInternal( const vsString &filename_in ): vsResource(filename_in), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { vsString filename = vsFile::GetFullFilename(filename_in); m_texture = ::loadTexture( filename.c_str() ); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsImage *maker ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsFloatImage *image ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfFloatImage *image ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsSurface *surface, bool depth ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { if ( surface ) m_texture = (depth) ? surface->m_depth : surface->m_texture; m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderBuffer *buffer ): vsResource(name), m_texture(0), m_premultipliedAlpha(false), m_tbo(buffer), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; m_nearestSampling = false; } vsTextureInternal::~vsTextureInternal() { GLuint t = m_texture; glDeleteTextures(1, &t); m_texture = 0; vsDelete( m_tbo ); m_renderTarget = NULL; } #else // TARGET_OS_IPHONE void vsTextureInternal::PrepareToBind() { if ( m_renderTarget ) { if ( IsDepth() ) m_renderTarget->ResolveDepth(); else m_renderTarget->Resolve(m_surfaceBuffer); } } /* Quick utility function for texture creation */ void vsTextureInternal::SetRenderTarget( vsRenderTarget* renderTarget, int surfaceBuffer, bool depth ) { // to be used for deferred texture creation (We went through the vsSurface // constructor with a NULL argument; now we're providing the surface) m_renderTarget = renderTarget; m_surfaceBuffer = surfaceBuffer; vsSurface *surface = renderTarget->GetTextureSurface(); if ( surface ) { m_texture = (depth) ? surface->m_depth : surface->m_texture[surfaceBuffer]; m_glTextureWidth = surface->m_width; m_glTextureHeight = surface->m_height; m_width = surface->m_width; m_height = surface->m_height; if ( m_nearestSampling ) SetNearestSampling(); } } vsTextureInternal::vsTextureInternal( const vsString &filename_in ): vsResource(filename_in), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { vsImage image(filename_in); if ( image.IsOK() ) { int w = image.GetWidth(); int h = image.GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image.RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } } vsTextureInternal::vsTextureInternal( const vsString&name, const vsArray<vsString> &mipmaps ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); for ( int i = 0; i < mipmaps.ItemCount(); i++ ) { vsImage image(mipmaps[i]); int w = image.GetWidth(); int h = image.GetHeight(); m_width = w; m_height = w; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image.RawData()); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Anisotropic filtering didn't become part of OpenGL core contextx until // OpenGL 4.6 (!!), so.. we sort of still have to explicitly check for // support. Blah!! if ( GL_EXT_texture_filter_anisotropic ) { float aniso = 0.0f; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso); aniso = vsMin(aniso,9); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); } } vsTextureInternal::vsTextureInternal( const vsString &name, vsImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsFloatImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfIntImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16UI, w, h, 0, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, image->RawData()); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfFloatImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_HALF_FLOAT, image->RawData()); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderBuffer *buffer ): vsResource(name), m_texture(0), m_premultipliedAlpha(false), m_tbo(buffer), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, uint32_t glTextureId ): vsResource(name), m_texture(glTextureId), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } void vsTextureInternal::Blit( vsImage *image, const vsVector2D &where) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexSubImage2D(GL_TEXTURE_2D, 0, (int)where.x, (int)where.y, image->GetWidth(), image->GetHeight(), GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); } void vsTextureInternal::Blit( vsFloatImage *image, const vsVector2D &where) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexSubImage2D(GL_TEXTURE_2D, 0, (int)where.x, (int)where.y, image->GetWidth(), image->GetHeight(), GL_RGBA, GL_FLOAT, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderTarget *renderTarget, int surfaceBuffer, bool depth ): vsResource(name), m_texture(0), m_glTextureWidth(0), m_glTextureHeight(0), m_width(0), m_height(0), m_depth(depth), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { if ( renderTarget && renderTarget->GetTextureSurface() ) { SetRenderTarget(renderTarget, surfaceBuffer, depth); } m_nearestSampling = false; } vsTextureInternal::~vsTextureInternal() { GLuint t = m_texture; glDeleteTextures(1, &t); m_texture = 0; vsDelete( m_tbo ); m_renderTarget = NULL; // this doesn't belong to us; don't destroy it! } void vsTextureInternal::SetNearestSampling() { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_nearestSampling = true; } void vsTextureInternal::SetLinearSampling(bool linearMipmaps) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if ( linearMipmaps ) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); m_nearestSampling = false; } #endif // TARGET_OS_IPHONE uint32_t vsTextureInternal::ScaleColour(uint32_t ini, float amt) { char r = (ini & 0x000000FF); char g = (ini & 0x0000FF00) >> 8; char b = (ini & 0x00FF0000) >> 16; char a = (ini & 0xFF000000) >> 24; r = (char)(r * amt); g = (char)(g * amt); b = (char)(b * amt); a = (char)(a * amt); uint32_t result = (r & 0x000000FF) | ((g << 8) & 0x0000FF00) | ((b << 16) & 0x00FF0000) | ((a << 24) & 0xFF000000); return result; } uint32_t vsTextureInternal::SafeAddColour(uint32_t acolour, uint32_t bcolour) { int ra = (acolour & 0x000000FF); int ga = (acolour & 0x0000FF00) >> 8; int ba = (acolour & 0x00FF0000) >> 16; int aa = (acolour & 0xFF000000) >> 24; int rb = (bcolour & 0x000000FF); int gb = (bcolour & 0x0000FF00) >> 8; int bb = (bcolour & 0x00FF0000) >> 16; int ab = (bcolour & 0xFF000000) >> 24; int r = vsMin( ra + rb, 0xFF ); int g = vsMin( ga + gb, 0xFF ); int b = vsMin( ba + bb, 0xFF ); int a = vsMin( aa + ab, 0xFF ); uint32_t result = (r & 0x000000FF) | ((g << 8) & 0x0000FF00) | ((b << 16) & 0x00FF0000) | ((a << 24) & 0xFF000000); return result; } void vsTextureInternal::ClampUV( bool u, bool v ) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, u ? GL_CLAMP_TO_EDGE : GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, v ? GL_CLAMP_TO_EDGE : GL_REPEAT ); }
22.723247
122
0.732543
vectorstorm
48448f9efd2e96c394fd1a77cd8ecdc53972eebb
319
hpp
C++
examples/publisher_transformer_subscriber/string_publisher.hpp
ManuelMeraz/flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
3
2021-01-05T16:12:08.000Z
2021-01-12T21:44:10.000Z
examples/publisher_transformer_subscriber/string_publisher.hpp
RoboSDK/Flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
9
2020-10-06T23:53:39.000Z
2021-01-23T00:41:39.000Z
examples/publisher_transformer_subscriber/string_publisher.hpp
RoboSDK/Flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <flow/publisher.hpp> #include <spdlog/spdlog.h> namespace example { class string_publisher { public: std::string operator()() { spdlog::info("Producing Hello World string!"); return "Hello World!"; } std::string publish_to() { return "hello_world"; }; }; }// namespace example
16.789474
53
0.677116
ManuelMeraz
4849c90419558b179352f38539f0d65aefd0f686
2,670
cpp
C++
fmivisbase/TextImageLayer.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
fmivisbase/TextImageLayer.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
fmivisbase/TextImageLayer.cpp
fmidev/smartmet-workstation-vtk
ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99
[ "MIT" ]
null
null
null
#include "TextImageLayer.h" #include <vtkImageData.h> #include <vtkTextRendererStringToImage.h> #include <vtkImageBlend.h> #include <vtkTextProperty.h> #include <vtkStdString.h> #include <vtkImageAppendComponents.h> #include <vtkImageReslice.h> #include "vtkTransform.h" TextImageLayer::TextImageLayer(int x, int y) : image( vtkSmartPointer<vtkImageData>::New()), textRen ( vtkSmartPointer<vtkTextRendererStringToImage>::New()), blend (vtkSmartPointer<vtkImageBlend>::New()), textProp (vtkSmartPointer<vtkTextProperty>::New()), outData(vtkSmartPointer< vtkImageData>::New()), pad(vtkSmartPointer<vtkImageReslice>::New()), buffer(vtkSmartPointer<vtkImageData>::New()) { textProp->SetLineSpacing(2.17); textProp->SetFontFamilyToCourier(); blend->SetBlendModeToCompound(); Clear(x,y); } TextImageLayer::TextImageLayer(int x, int y, std::string &font): TextImageLayer(x,y) { textProp->SetFontFamily(VTK_FONT_FILE); textProp->SetFontFile(font.c_str()); } TextImageLayer::~TextImageLayer() { } void TextImageLayer::AddText(std::string &s, int x, int y) { vtkStdString text = vtkStdString{ s }; // auto buffer = vtkSmartPointer<vtkImageData>::New(); buffer->PrepareForNewData(); textRen->RenderString(textProp, text,70,buffer); int dim[3]; buffer->GetDimensions(dim); int extents[6]; buffer->GetExtent(extents); // buffer->SetOrigin(x, y, 0); if (x > 0) { extents[1] += x; extents[0] += x; } else extents[0] += x; if (y > 0) { extents[3] += y; extents[2] += y; } else extents[2] += y; //auto pad = vtkSmartPointer<vtkImageReslice>::New(); pad->SetOutputExtent(extents); pad->RemoveAllInputs(); pad->AddInputData(buffer); pad->Update(); buffer->ShallowCopy(pad->GetOutput()); blend->AddInputData( buffer ); //blend->AddInputData(mask); } void TextImageLayer::SetSize(float sz) { textProp->SetFontSize(sz); } void TextImageLayer::SetColor(double r, double g, double b, double a) { textProp->SetColor(r, g, b); textProp->SetOpacity(a); } void TextImageLayer::Clear(int sx, int sy) { image->SetDimensions(sx, sy, 1); Clear(); } void TextImageLayer::Clear() { image->AllocateScalars(VTK_UNSIGNED_CHAR, 4); blend->RemoveAllInputs(); blend->SetInputData(image); } vtkSmartPointer<vtkImageData> TextImageLayer::GetImage() { blend->Update(); outData->ShallowCopy(blend->GetOutput()); auto dim = outData->GetDimensions(); for (long iy = 0; iy < dim[1]; ++iy) { for (long ix = 0; ix < dim[0]; ++ix) { auto bp = static_cast<unsigned char*>(outData->GetScalarPointer(ix, iy,0)); if (bp[0] > 0 || bp[1] > 0 || bp[2] > 0) bp[3] = 255; } } outData->Modified(); return outData; }
19.925373
78
0.692884
fmidev
484dde96e9de72bdd23d2f17e6eb641ee184be83
1,223
hpp
C++
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
#ifndef H_AW_KEYBINDING #define H_AW_KEYBINDING #include <vector> #include <functional> #include <SFML/Window.hpp> namespace aw { class Keybinding { public: typedef std::function <void()> KeybindingCallback; Keybinding (const KeybindingCallback&, bool, sf::Keyboard::Key, bool, bool, bool); ~Keybinding () = default; Keybinding (Keybinding&&) = default; Keybinding& operator = (Keybinding&&) = default; Keybinding (const Keybinding&) = default; Keybinding& operator = (const Keybinding&) = default; bool check (bool, sf::Keyboard::Key, bool, bool, bool) const; void process (bool, sf::Keyboard::Key, bool, bool, bool); const KeybindingCallback& getCallback () const; bool getAction () const; sf::Keyboard::Key getKey () const; bool getAlt () const; bool getControl () const; bool getShift () const; void setCallback (const KeybindingCallback&); void setAction (bool); void setKey (sf::Keyboard::Key); void setAlt (bool); void setControl (bool); void setShift (bool); private: KeybindingCallback m_callback; bool m_action; sf::Keyboard::Key m_key; bool m_alt; bool m_control; bool m_shift; }; } #endif
22.648148
86
0.6713
DangerInteractive
48520d2a6ff5106755db288823bef13e0dec8ccf
2,236
cpp
C++
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
#include "EntityManager.h" EntityManager::EntityManager(RenderEngine* pRenderEngine, EditorSystem* pEditorSystem, ScriptSystem* pScriptSystem, flecs::world* ecs) : m_pRenderEngine(pRenderEngine), m_pEditorSystem(pEditorSystem), m_pEcs(ecs), m_pScriptSystem(pScriptSystem) { } EntityManager::~EntityManager() { m_entityQueue.clear(); } void EntityManager::CreateEntity(std::string strScriptName) { flecs::entity newEntity = m_pEcs->entity(); uint32_t nIndex = GetNewIndex(); ScriptNode* pScriptNode = m_pScriptSystem->CreateScriptNode(strScriptName, newEntity); Ogre::String strMeshName = pScriptNode->GetMeshName(); RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName); newEntity.set(EntityIndex{ nIndex }) .set(RenderNodeComponent{ pRenderNode }) .set(ScriptNodeComponent{ pScriptNode }); m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode); Entity entity; entity.pRenderNode = pRenderNode; entity.pScriptNode = pScriptNode; entity.idx = nIndex; m_entityQueue[nIndex] = entity; } void EntityManager::CreateEntity(const EntityInfo &fromSave) { flecs::entity newEntity = m_pEcs->entity(); uint32_t nIndex = GetNewIndex(); EditorNode* pEditorNode = m_pEditorSystem->CreateNode(fromSave, nIndex, newEntity); ScriptNode* pScriptNode = m_pScriptSystem->CreateScriptNode(fromSave.scriptName, newEntity); pScriptNode->SetPosition(fromSave.position); pScriptNode->SetOrientation(fromSave.rotation); Ogre::String strEnityName = fromSave.entityName; Ogre::String strMeshName = fromSave.meshName; RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName); newEntity.set(EntityIndex{ nIndex }) .set(RenderNodeComponent{ pRenderNode }) .set(EditorNodeComponent{ pEditorNode }) .set(ScriptNodeComponent{ pScriptNode }); m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode); Entity entity; entity.idx = nIndex; entity.entityName = strEnityName; entity.pEditorNode = pEditorNode; entity.pRenderNode = pRenderNode; entity.pScriptNode = pScriptNode; m_entityQueue[nIndex] = entity; } uint32_t EntityManager::GetNewIndex() const { return m_entityQueue.size(); } std::unordered_map<uint32_t, Entity> EntityManager::GetEntityQueue() const { return m_entityQueue; }
27.268293
136
0.780859
Negawisp
4853b92d7c78c3c093165f6c0a1b2126d16d1a6a
366
cpp
C++
checkalpha.cpp
yami0307/cpp-practice
1945a6eaad22de487ac9926b2fbe67d50df9c05a
[ "MIT" ]
null
null
null
checkalpha.cpp
yami0307/cpp-practice
1945a6eaad22de487ac9926b2fbe67d50df9c05a
[ "MIT" ]
null
null
null
checkalpha.cpp
yami0307/cpp-practice
1945a6eaad22de487ac9926b2fbe67d50df9c05a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; bool checkAlpha(char c){ if((c>=65 && c<=90)||(c>=97 && c<=122)){ return true; } else{ return false; } } int main(){ char c; cin>>c; if(checkAlpha(c)){ cout<<"It is an alphabet."<<endl; } else{ cout<<"It is not an alphabet."<<endl; } return 0; }
17.428571
45
0.489071
yami0307
48552f2a2ff3689b70b88b5ae5b11add416e6fd5
1,288
cpp
C++
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2009-2010 Satoshi Nakamoto //版权所有(c)2009-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <threadinterrupt.h> #include <sync.h> CThreadInterrupt::CThreadInterrupt() : flag(false) {} CThreadInterrupt::operator bool() const { return flag.load(std::memory_order_acquire); } void CThreadInterrupt::reset() { flag.store(false, std::memory_order_release); } void CThreadInterrupt::operator()() { { LOCK(mut); flag.store(true, std::memory_order_release); } cond.notify_all(); } bool CThreadInterrupt::sleep_for(std::chrono::milliseconds rel_time) { WAIT_LOCK(mut, lock); return !cond.wait_for(lock, rel_time, [this]() { return flag.load(std::memory_order_acquire); }); } bool CThreadInterrupt::sleep_for(std::chrono::seconds rel_time) { return sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(rel_time)); } bool CThreadInterrupt::sleep_for(std::chrono::minutes rel_time) { return sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(rel_time)); }
23.851852
101
0.737578
yinchengtsinghua
4858df62263f0cb9b3b2f3e516f30fc13f39ab3d
9,595
cpp
C++
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
#include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/aruco.hpp" #include "opencv2/aruco/dictionary.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/video/tracking.hpp" #include "opencv2/features2d/features2d.hpp" #include <vector> #include <sstream> #include <iostream> #include <fstream> #include <ctype.h> #include <algorithm> #include <iterator> #include <ctime> #include <string> #include <stdio.h> using namespace std; using namespace cv; // 2.6 cm - 26 mm - 0.026 m const float calibrationSquareDimension = 0.026f; //meters // 13.2 cm - 132 mm - 0.132 m // 33.9 cm - 339 mm - 0.339 m const float arucoSquareDimensionMaior = 0.339f; //meters // 7.9 cm - 79 mm - 0.079 m const float arucoSquareDimensionMenor = 0.079f; //meters // dimension of cheesboard const Size chessboardDimensions = Size(6,9); //default capture width and height const int FRAME_WIDTH = 640; const int FRAME_HEIGHT = 480; //initial min and max THRESHOLD filter values //our sensitivity value to be used in the threshold() function //these will be changed using trackbars int THRESHOLD_MIN = 220; int THRESHOLD_MAX = 256; int BLUR_SIZE = 5; int DILATATION = 2; int ERODE = 2; //diameter of circle is 54 cm const float DIAMETER = 54; // focal distance const float FOCO = 675; void on_trackbar(int, void *) { //This function gets called whenever a // trackbar position is changed } //int to string helper function string intToString(int number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } //float to string helper function string floatToString(float number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } string doubleToString(double number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } float distanceLandmarck(int &radius) { // f = foco(taxa de transformação); x = diâmetro(pixels); // Z = distáncia entre câmera(altura) = landmark(centimetros); X = diâmetro do landmark(centimetros) // Z = (X * f) / x; // diâmetro circulo em pixels float pixelDiametro = radius * 2; // f(24) = 672 f(20) = 680 f(54) = 675 float altura = (DIAMETER * FOCO) / pixelDiametro; return altura; } // calcular distancias(x,y) do mundo real entre landmark e o frame do drone float *positionCenter(float &xLandmark, float &yLandmark, float &altura) { float px = xLandmark - FRAME_WIDTH / 2; float py = yLandmark - FRAME_HEIGHT / 2; float *out = (float *)calloc(2, sizeof(float)); // contastane k que relaciona diametro com a quantidade de pixels Z/f ou X/x float k = altura / FOCO; out[0] = px * k; out[1] = py * k; return out; } void searchForCircule(Mat &thresholdImage, Mat &cameraFeed) { vector<Vec3f> circles; HoughCircles(thresholdImage, circles, HOUGH_GRADIENT, 1.4, thresholdImage.rows / 2, // change this value to detect circles with different distances to each other 100, 100, 0, 0 // change the last two parameters // (min_radius & max_radius) to detect larger circles ); //cout << "size circulo " << circles.size() << endl; if (circles.size() == 1) { for (size_t i = 0; i < circles.size(); i++) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); float Xc = cvRound(circles[i][0]); float Yc = cvRound(circles[i][1]); float Altura = distanceLandmarck(radius); // converction cm to mm Altura = Altura * 10; float *direction = positionCenter(Xc, Yc, Altura); // converction to meters Altura = Altura / 1000; // circle center circle(cameraFeed, center, 3, Scalar(0, 255, 0), -1, 8, 0); // circle outline circle(cameraFeed, center, radius, Scalar(0, 0, 255), 3, 8, 0); putText(cameraFeed, "Tracking first aim at (" + intToString(cvRound(circles[i][0])) + "pixel , " + intToString(cvRound(circles[i][1])) + "pixel )", Point(10, 20), 1.2, 1.2, Scalar(255, 0, 0), 2); putText(cameraFeed, "Altitude: " + doubleToString(Altura) + " m", Point(10, 50), 1.2, 1.2, Scalar(0, 0, 255), 2); putText(cameraFeed, "Correction coordinates (" + floatToString(cvRound(direction[0])) + "mm , " + floatToString(cvRound(direction[1])) + "mm )", Point(10, 80), 1.2, 1.2, Scalar(0, 255, 0), 2); putText(cameraFeed, "X", Point(FRAME_WIDTH / 2, FRAME_HEIGHT / 2), 1.2, 1.2, Scalar(0, 0, 255), 2); // Vec3i c = circles[i]; // circle(cameraFeed, Point(c[0], c[1]), c[2], Scalar(0, 0, 255), 3, LINE_AA); // circle(cameraFeed, Point(c[0], c[1]), 2, Scalar(0, 255, 0), 3, LINE_AA); } // realizar o processo para identificar sempre o maior circulo para calculo da altura // associar os circulos (diametro pixels) com suas respectivas distancias // altura próxima de 1 m baixar o threshold // achar triangulo para encontrar orientação (por angulos em relação ao quadrado) } } bool loadCameraCalibration(Mat& cameraMatrix, Mat& distanceCoefficients) { ifstream myfile; myfile.open("calibrationFile(smartphone).txt"); if (myfile.is_open()) { uint16_t rows; uint16_t columns; myfile >> rows; myfile >> columns; cameraMatrix = Mat(Size(columns, rows), CV_64F); for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { double read = 0.0f; myfile >> read; cameraMatrix.at<double>(r, c) = read; //cout << cameraMatrix.at<double>(r, c) << endl; } } //Distance Coefficients myfile >> rows; myfile >> columns; distanceCoefficients = Mat(Size(columns, rows), CV_64F); for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { double read = 0.0f; myfile >> read; distanceCoefficients.at<double>(r, c) = read; //cout << distanceCoefficients.at<double>(r, c) << endl; } } myfile.close(); return true; } return false; } int startWebcamMonitoring(Mat& cameraMatrix, Mat& distanceCoefficients, float arucoSquareDimension) { Mat frame, frameCopy; vector<int> markerIds; vector<vector<Point2f > > markerCorners, rejectedCandidates; aruco::DetectorParameters parameters; Ptr<aruco::Dictionary> markerDictionary = aruco::getPredefinedDictionary(aruco::DICT_4X4_1000); VideoCapture video(1); vector<Vec3d> rotationVectors, translationVectors; // visualizar parametros intrinsecos da camera for (int r = 0; r < cameraMatrix.rows; r++) { for (int c = 0; c < cameraMatrix.cols; c++) { cout << cameraMatrix.at<double>(r, c) << endl; } } // visualizar distorções da camera for (int r = 0; r < distanceCoefficients.rows; r++) { for (int c = 0; c < distanceCoefficients.cols; c++) { cout << distanceCoefficients.at<double>(r, c) << endl; } } namedWindow("WebCam Aruco", CV_WINDOW_NORMAL); while (1) { video.open("/home/alantavares/Datasets/indoor_HD_1920.mp4"); if (!video.isOpened()) { cout << "ERROR ACQUIRING VIDEO FEED" << endl; getchar(); return -1; } else{ cout << "CORRECT ACQUIRING VIDEO FEED" << endl; } //check if the video has reach its last frame. //we add '-1' because we are reading two frames from the video at a time. //if this is not included, we get a memory error! while (video.get(CV_CAP_PROP_POS_FRAMES) < video.get(CV_CAP_PROP_FRAME_COUNT) - 1) { //read first frame video.read(frame); frame.copyTo(frameCopy); aruco::detectMarkers(frame, markerDictionary, markerCorners, markerIds); aruco::estimatePoseSingleMarkers(markerCorners, arucoSquareDimension, cameraMatrix, distanceCoefficients, rotationVectors, translationVectors); //cout << "markerIds: " << markerIds.size() << endl; for (int i = 0; i < markerIds.size(); i++) { //cout << "markerCorners: " << markerCorners.at<Point2f> << endl; aruco::drawDetectedMarkers(frame, markerCorners, markerIds); aruco::drawAxis(frame, cameraMatrix, distanceCoefficients, rotationVectors[i], translationVectors[i], 0.1f); } //***************************************************************** // //thresholded difference image (for use in findContours() function) // Mat thresholdImage, grayImage; // //convert frame1 to gray scale for frame differencing // cvtColor(frameCopy, grayImage, COLOR_BGR2GRAY); // //threshold intensity image at a given sensitivity value // threshold(grayImage, thresholdImage, THRESHOLD_MIN, THRESHOLD_MAX, THRESH_BINARY); // //use blur() to smooth the image, remove possible noise and // blur(thresholdImage, thresholdImage, Size(BLUR_SIZE, BLUR_SIZE)); // searchForCircule(thresholdImage,frame); imshow("WebCam Aruco", frame); if (waitKey(1) >= 0) { break; } } return 1; } } int main(int argc, char const *argv[]) { Mat cameraMatrix = Mat::eye(3, 3, CV_64F); Mat distanceCoefficients; loadCameraCalibration(cameraMatrix, distanceCoefficients); startWebcamMonitoring(cameraMatrix, distanceCoefficients, arucoSquareDimensionMaior); return 0; }
28.47181
153
0.642001
alanprodam
485a83cf0a500058b73ecf8893830d9c71894a58
417
cpp
C++
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #undef STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #undef STB_IMAGE_WRITE_IMPLEMENTATION #pragma GCC diagnostic pop
37.909091
61
0.841727
lenamueller
485c070bec6f0e63076eb5641143cb729701a07d
3,351
hpp
C++
src/libraries/core/db/CallbackRegistry/CallbackRegistry.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/CallbackRegistry/CallbackRegistry.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/CallbackRegistry/CallbackRegistry.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::CallbackRegistry Description Base class with which callbacks are registered. Derive from this class and extend by adding the appropriate callback functions that loop and call the callback functions for each entry. \*---------------------------------------------------------------------------*/ #ifndef CallbackRegistry_H #define CallbackRegistry_H #include "UIDLList.hpp" #include "className.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of classes template<class CallbackType> class Callback; /*---------------------------------------------------------------------------*\ Class CallbackRegistry Declaration \*---------------------------------------------------------------------------*/ TemplateName(CallbackRegistry); /*---------------------------------------------------------------------------*\ Class CallbackRegistry Declaration \*---------------------------------------------------------------------------*/ template<class CallbackType> class CallbackRegistry : public CallbackRegistryName, public UIDLList<CallbackType> { // Private Member Functions //- Disallow default bitwise copy construct CallbackRegistry(const CallbackRegistry&); //- Disallow default bitwise assignment void operator=(const CallbackRegistry&); public: // Constructors //- Construct null CallbackRegistry(); //- Destructor virtual ~CallbackRegistry(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class CallbackType> CML::CallbackRegistry<CallbackType>::CallbackRegistry() : CallbackRegistryName(), UIDLList<CallbackType>() {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // template<class CallbackType> CML::CallbackRegistry<CallbackType>::~CallbackRegistry() { forAllIter(typename CallbackRegistry<CallbackType>, *this, iter) { iter().Callback<CallbackType>::checkOut(); } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
27.925
79
0.484631
MrAwesomeRocks
485c58814be7293221cd4d7d77617cd22764ae9a
707
cpp
C++
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 160_intersection_of_two_linked_lists.cpp // leetcode_linked_list // // Created by Hadley on 25.09.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <vector> #include <unordered_set> #include <unordered_map> #include "83_Remove_duplicats_from_sorted_list.cpp" using namespace std; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { unordered_map<ListNode*,int>map; while(headA){ map[headA]++; headA=headA->next; } while(headB){ map[headB]++; if(map[headB]==2)break; headB=headB->next; } return headB; } };
22.09375
69
0.618105
Hadleyhzy
485e7897324f471024044742b871a41222a2b572
4,234
cpp
C++
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
8
2019-12-08T23:37:13.000Z
2021-10-04T06:14:00.000Z
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
null
null
null
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
1
2019-12-31T02:44:01.000Z
2019-12-31T02:44:01.000Z
#include "engine/gen/FlowField.h" FlowField::FlowField() { dijkstraGrid = std::vector<std::vector<node>>(gridWidth); } FlowField::~FlowField() { } void FlowField::GenerateFlowField() { GenerateDijkstraGrid(std::vector<glm::vec2>{ {2, 4}, { 5,6 }}); int x, y; std::vector<std::vector<glm::vec2>> flowField(gridWidth); for (x = 0; x < gridWidth; x++) { std::vector<glm::vec2> arr(gridHeight); for (y = 0; y < gridHeight; y++) { arr[y] = glm::vec2(0,0); } flowField[x] = arr; } for (x = 0; x < gridWidth; x++) { for (y = 0; y < gridHeight; y++) { if (dijkstraGrid[x][y].weight == INT_MAX) { continue; } std::vector neighbours = AllNeighboursOf(dijkstraGrid[x][y]); node min = node(); float minDist = 0; for (int i = 0; i < neighbours.size(); i++) { node n = neighbours[i]; float dist = dijkstraGrid[n.pos.x][n.pos.y].weight - dijkstraGrid[x][y].weight; //if (i == 0) minDist = dist; //if (dist < minDist) // minDist = dist; if (dist < minDist) { n.distance = dist; min = n; minDist = dist; } } //if valid neightbour point in its direction if (min.distance != 0) { flowField[x][y] = glm::normalize(min.pos - dijkstraGrid[x][y].pos); } } } } void FlowField::GenerateDijkstraGrid(std::vector<glm::vec2> obstacles) { int gridWidth = 10; int gridHeight = 10; for (int x = 0; x < gridWidth; x++) { std::vector<node> arr(gridHeight); for (int y = 0; y < gridHeight; y++) { arr[y].weight = 0; arr[y].pos = glm::vec2(x, y); arr[y].distance = 0; } dijkstraGrid[x] = arr; } //set all places with obstacles with weight of MAXINT for (int i = 0; i<obstacles.size(); i++) { glm::vec2 t = obstacles[i]; dijkstraGrid[t.x][t.y].weight = INT_MAX; } node pathEnd; pathEnd.distance = 0; pathEnd.pos = { 2,4 }; pathEnd.weight = 0; dijkstraGrid[pathEnd.pos.x][pathEnd.pos.y].weight = 0; std::vector<node> toVisit{ pathEnd }; for (int i = 0; i < toVisit.size(); i++) { std::vector<node> neighbours = NeighboursOf(toVisit[i]); //for each neighbour of this node (only straight line neighbours) for (int j = 0; j < neighbours.size(); j++) { node n = neighbours[j]; if (dijkstraGrid[n.pos.x][n.pos.y].weight == 0) { n.distance = toVisit[i].distance + 1; dijkstraGrid[n.pos.x][n.pos.y].weight = n.distance; toVisit.push_back(n); } } } } //no diagonal neighbours std::vector<node> FlowField::NeighboursOf(node& neighbour) { std::vector<node> neighbours; if (neighbour.pos.x != gridWidth-1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][neighbour.pos.y]); if (neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][neighbour.pos.y]); if (neighbour.pos.y != gridHeight-1) neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y + 1]); if (neighbour.pos.y != 0)neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y - 1]); return neighbours; } //all neighbours including diagonal std::vector<node> FlowField::AllNeighboursOf(node& neighbour) { std::vector<node> neighbours; if (neighbour.pos.x != gridWidth -1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][neighbour.pos.y]); if(neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][neighbour.pos.y]); if (neighbour.pos.y != gridHeight -1) neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y + 1]); if(neighbour.pos.y != 0 )neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y - 1]); if (neighbour.pos.x != gridWidth - 1 && neighbour.pos.y != gridHeight -1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][(int)neighbour.pos.y + 1]); if (neighbour.pos.x != 0 && neighbour.pos.y != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][(int)neighbour.pos.y - 1]); if (neighbour.pos.y != gridHeight - 1 && neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][(int)neighbour.pos.y + 1]); if (neighbour.pos.y != 0 && neighbour.pos.x != gridWidth - 1)neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][(int)neighbour.pos.y - 1]); return neighbours; }
27.493506
162
0.645253
Eothaun
4861bc5e8598ec7ae2279bff66213b13e006ec1b
836
cpp
C++
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Add and Divide #include <iostream> #include <limits> using namespace std; int main() { int t; cin >> t; while(t--) { int a, b; cin >> a >> b; int ans = numeric_limits<int>::max(); bool b_is_one = false; if (b == 1) { b += 1; b_is_one = true; } // Explanation - https://www.youtube.com/watch?v=BzIc0ZwLvps int tmp, current_ans; for (int i = 0; i < 31; ++i) { tmp = a; current_ans = 0; if (b_is_one) { ++current_ans; } while (tmp != 0) { tmp /= (b + i); ++current_ans; } ans = min(ans, current_ans + i); } cout << ans << endl; } return 0; }
16.72
68
0.389952
sgrade
486768fc3c4659bb98f60b08d39a319baece52b2
8,095
cpp
C++
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
44
2015-05-29T14:37:31.000Z
2021-11-17T11:22:04.000Z
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
4
2016-06-28T12:34:31.000Z
2019-12-03T10:54:10.000Z
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
4
2016-08-09T08:51:46.000Z
2018-01-13T15:36:36.000Z
#include "SpeedTest.h" #include "Random.h" #include <stdio.h> // for printf #include <memory.h> // for memset #include <math.h> // for sqrt #include <algorithm> // for sort //----------------------------------------------------------------------------- // We view our timing values as a series of random variables V that has been // contaminated with occasional outliers due to cache misses, thread // preemption, etcetera. To filter out the outliers, we search for the largest // subset of V such that all its values are within three standard deviations // of the mean. double CalcMean ( std::vector<double> & v ) { double mean = 0; for(int i = 0; i < (int)v.size(); i++) { mean += v[i]; } mean /= double(v.size()); return mean; } double CalcMean ( std::vector<double> & v, int a, int b ) { double mean = 0; for(int i = a; i <= b; i++) { mean += v[i]; } mean /= (b-a+1); return mean; } double CalcStdv ( std::vector<double> & v, int a, int b ) { double mean = CalcMean(v,a,b); double stdv = 0; for(int i = a; i <= b; i++) { double x = v[i] - mean; stdv += x*x; } stdv = sqrt(stdv / (b-a+1)); return stdv; } // Return true if the largest value in v[0,len) is more than three // standard deviations from the mean bool ContainsOutlier ( std::vector<double> & v, size_t len ) { double mean = 0; for(size_t i = 0; i < len; i++) { mean += v[i]; } mean /= double(len); double stdv = 0; for(size_t i = 0; i < len; i++) { double x = v[i] - mean; stdv += x*x; } stdv = sqrt(stdv / double(len)); double cutoff = mean + stdv*3; return v[len-1] > cutoff; } // Do a binary search to find the largest subset of v that does not contain // outliers. void FilterOutliers ( std::vector<double> & v ) { std::sort(v.begin(),v.end()); size_t len = 0; for(size_t x = 0x40000000; x; x = x >> 1 ) { if((len | x) >= v.size()) continue; if(!ContainsOutlier(v,len | x)) { len |= x; } } v.resize(len); } // Iteratively tighten the set to find a subset that does not contain // outliers. I'm not positive this works correctly in all cases. void FilterOutliers2 ( std::vector<double> & v ) { std::sort(v.begin(),v.end()); int a = 0; int b = (int)(v.size() - 1); for(int i = 0; i < 10; i++) { //printf("%d %d\n",a,b); double mean = CalcMean(v,a,b); double stdv = CalcStdv(v,a,b); double cutA = mean - stdv*3; double cutB = mean + stdv*3; while((a < b) && (v[a] < cutA)) a++; while((b > a) && (v[b] > cutB)) b--; } std::vector<double> v2; v2.insert(v2.begin(),v.begin()+a,v.begin()+b+1); v.swap(v2); } //----------------------------------------------------------------------------- // We really want the rdtsc() calls to bracket the function call as tightly // as possible, but that's hard to do portably. We'll try and get as close as // possible by marking the function as NEVER_INLINE (to keep the optimizer from // moving it) and marking the timing variables as "volatile register". NEVER_INLINE int64_t timehash ( pfHash hash, int hashsize, const void * key, int len, int seed, const int repeats, bool measure_throughput ) { volatile register int64_t begin,end; uint32_t temp[16]; begin = rdtsc(); if (measure_throughput) { for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); } } else { // measure back-to-back latency switch (hashsize) { case 32: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; // ensure that new seed depends on ALL bits of hash result } break; case 64: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = (sizeof(size_t) == 4? temp[0] + temp[1] : (*(uint64_t*)temp >> 1)); } break; case 128: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0] + temp[1] + temp[2] + temp[3]; } break; case 256: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; for (int j=1; j < 256/32; j++) seed += temp[j]; } break; case 512: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; for (int j=1; j < 512/32; j++) seed += temp[j]; } break; } } end = rdtsc(); return end-begin; } //----------------------------------------------------------------------------- double SpeedTest ( pfHash hash, int hashsize, uint32_t seed, const int trials, const int repeats, const int blocksize, const int align, bool measure_throughput ) { Rand r(seed); uint8_t * buf = new uint8_t[blocksize + 512]; uint64_t t1 = reinterpret_cast<uint64_t>(buf); t1 = (t1 + 255) & BIG_CONSTANT(0xFFFFFFFFFFFFFF00); t1 += align; uint8_t * block = reinterpret_cast<uint8_t*>(t1); r.rand_p(block,blocksize); //---------- std::vector<double> times; times.reserve(trials); for(int itrial = 0; itrial < trials; itrial++) { r.rand_p(block,blocksize); double t = (double)timehash(hash,hashsize,block,blocksize,itrial,repeats,measure_throughput); if(t > 0) times.push_back(t); } //---------- std::sort(times.begin(),times.end()); FilterOutliers(times); delete [] buf; return CalcMean(times)/repeats; } //----------------------------------------------------------------------------- // 256k blocks seem to give the best results. void BulkSpeedTest ( pfHash hash, int hashsize, uint32_t seed ) { const int trials = 2999; const int repeats = 1; const int blocksize = 256 * 1024; const bool measure_throughput = true; printf("Bulk speed test - %d-byte keys\n",blocksize); for(int align = 0; align < 8; align++) { double cycles = SpeedTest(hash,hashsize,seed,trials,repeats,blocksize,align,measure_throughput); double bestbpc = double(blocksize)/cycles; double bestbps = (bestbpc * 3000000000.0 / 1048576.0); printf("Alignment %2d - %6.3f bytes/cycle - %7.2f MiB/sec @ 3 ghz\n",align,bestbpc,bestbps); } } //----------------------------------------------------------------------------- void TinySpeedTest ( pfHash hash, int hashsize, int max_keysize, uint32_t seed, bool verbose ) { const int trials = 1000; const int repeats = 1000; std::vector<double> cycles_latency(max_keysize+1); std::vector<double> cycles_throughput(max_keysize+1); printf("Small key speed test"); for (int i=0; i<10; i++) { if(verbose) printf("."); for(int keysize = 0; keysize <= max_keysize; keysize++) { double cycles; cycles = SpeedTest(hash,hashsize,seed,trials,repeats,keysize,0,false); if (i==0 || cycles < cycles_latency[keysize]) cycles_latency[keysize] = cycles; cycles = SpeedTest(hash,hashsize,seed,trials,repeats,keysize,0,true); if (i==0 || cycles < cycles_throughput[keysize]) cycles_throughput[keysize] = cycles; } } printf("\n"); for(int keysize = 0; keysize <= max_keysize; keysize++) { printf("%4d-byte keys - latency %8.2f cycles/hash, throughput %8.2f cycles/hash\n", keysize, cycles_latency[keysize], cycles_throughput[keysize]); } } //-----------------------------------------------------------------------------
25.455975
162
0.512786
Bulat-Ziganshin
48695be33dc62aab206b61ad431856e152a0fb5c
634
cpp
C++
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 1005; char s[maxn]; inline int idx(char c) { if (c == 'I') return 1; else if (c == 'V') return 5; else if (c == 'X') return 10; else if (c == 'L') return 50; else if (c == 'C') return 100; else if (c == 'D') return 500; else if (c == 'M') return 1000; return 0; } int main () { int cas; scanf("%d", &cas); while (cas--) { scanf("%s", s); int ans = 0, len = strlen(s); for (int i = 0; i < len; i++) { int k = (idx(s[i]) >= idx(s[i+1]) ? 1 : -1); ans += k * idx(s[i]); } printf("%d\n", ans); } return 0; }
18.114286
47
0.520505
JeraKrs
486bb4035507edb026439935bdea0925e4483525
1,864
cpp
C++
runtime/libs/tflite/src/OutputResetter.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
runtime/libs/tflite/src/OutputResetter.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
runtime/libs/tflite/src/OutputResetter.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tflite/OutputResetter.h" #include "tflite/TensorView.h" #include <misc/tensor/IndexIterator.h> namespace nnfw { namespace tflite { void OutputResetter::run(::tflite::Interpreter &interp) { for (const auto &tensor_idx : interp.outputs()) { TfLiteTensor *tensor = interp.tensor(tensor_idx); switch (tensor->type) { case kTfLiteInt32: resetValue<int32_t>(interp, tensor_idx); break; case kTfLiteUInt8: resetValue<uint8_t>(interp, tensor_idx); break; case kTfLiteInt8: resetValue<int8_t>(interp, tensor_idx); break; case kTfLiteBool: resetValue<bool>(interp, tensor_idx); break; case kTfLiteFloat32: resetValue<float>(interp, tensor_idx); break; default: throw std::runtime_error{"Not supported output type"}; } } } template <typename T> void OutputResetter::resetValue(::tflite::Interpreter &interp, int tensor_idx) { auto tensor_view = nnfw::tflite::TensorView<T>::make(interp, tensor_idx); nnfw::misc::tensor::iterate(tensor_view.shape()) << [&](const nnfw::misc::tensor::Index &ind) { tensor_view.at(ind) = 0; }; } } // namespace tflite } // namespace nnfw
28.676923
100
0.684549
chogba6
486e3ce93dbdc4edc36fc00bb0f7316686a0cca3
558
hpp
C++
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
12
2020-03-04T18:43:43.000Z
2022-01-30T22:59:27.000Z
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
17
2019-05-20T20:22:09.000Z
2022-01-11T16:55:26.000Z
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
6
2020-06-05T18:17:13.000Z
2022-03-19T20:13:58.000Z
#pragma once #include "Rule.hpp" #include "RelayModuleNode.hpp" class RuleBoost : public Rule { public: RuleBoost(RelayModuleNode* solarRelay, RelayModuleNode* poolRelay); const char* getMode() { return "boost"; }; void setSolarRelayNode(RelayModuleNode* relay) { _solarRelay = relay; }; void setPoolRelayNode(RelayModuleNode* relay) { _poolRelay = relay; }; virtual void loop(); protected: RelayModuleNode* _solarRelay; RelayModuleNode* _poolRelay; private: const char* cCaption = "• RuleBoost:"; const char* cIndent = " ◦ "; };
21.461538
74
0.716846
d3wy
486e7d60adaa20f05290b9247e629ef8cc8c8731
260
cpp
C++
kattis/quadrant.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2019-11-06T15:17:48.000Z
2019-11-06T15:17:48.000Z
kattis/quadrant.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
null
null
null
kattis/quadrant.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2018-11-13T08:43:26.000Z
2018-11-13T08:43:26.000Z
/*input 10 -6 */ #include <iostream> int x, y, q; int main(){ std::cin>>x>>y; if(x > 0 && y > 0){ q = 1; }else if(x < 0 && y < 0){ q = 3; }else if(y < 0 && x > 0){ q = 4; }else if(y > 0 && x < 0){ q = 2; } std::cout<<q<<std::endl; return 0; }
11.818182
26
0.423077
andraantariksa
4872cb9656f275d58c9a8bf2c3a83edd2382339f
4,646
cpp
C++
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
#include "qheduino_CAR.h" //输入参数为TB6612六个引脚对应的Arduino管脚 CAR::CAR(int left_go, int left_back, int left_pwm, int right_go, int right_back, int right_pwm ) { Left_motor_go = left_go; //左电机前进 AIN1 Left_motor_back = left_back; //左电机后退 AIN2 Right_motor_go = right_go; //右电机前进 BIN1 Right_motor_back = right_back; //右电机后退 BIN2 Left_motor_pwm = left_pwm; //左电机控速 PWMA Right_motor_pwm = right_pwm; //右电机控速 PWMB //初始化电机驱动IO口为输出方式 pinMode(Left_motor_go, OUTPUT); pinMode(Left_motor_back, OUTPUT); pinMode(Right_motor_go, OUTPUT); pinMode(Right_motor_back, OUTPUT); } //dir ----- 0:刹车 1:前进 2:后退 3:左转 4:右转 5:原地左转 6:原地右转 //speed 0~255 void CAR::direction_speed_ctrl(int dir, int speed){ speed = (int)( ((float)speed)*2.55 ); speed = speed>255?255:speed; speed = speed<0?0:speed; switch(dir){ case 1: run( speed ); break; case 2: back( speed ); break; case 3: left( speed ); break; case 4: right( speed ); break; case 5: spin_left( speed ); break; case 6: spin_right( speed ); break; case 0: brake(); break; default: brake(); break; } } /** * Function run * @author George * @brief 小车前进 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::run(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //PWM比例0-255调速,左右轮差异略增减 //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); //PWM比例0-255调速,左右轮差异略增减 } /** * Function back * @author George * @brief 小车后退 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::back(int speed) { //左电机后退 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, HIGH); //左电机后退使能 analogWrite(Left_motor_pwm, speed); //右电机后退 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, HIGH); //右电机后退使能 analogWrite(Right_motor_pwm, speed); } /** * Function brake * @author George * @brief 小车刹车 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::brake() { digitalWrite(Left_motor_go, LOW); digitalWrite(Left_motor_back, LOW); digitalWrite(Right_motor_go, LOW); digitalWrite(Right_motor_back, LOW); } /** * Function left * @author George * @brief 小车左转 左转(左轮不动,右轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::left(int speed) { //左电机停止 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, 0); //左边电机速度设为0(0-255) //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); //右边电机速度设200(0-255) } /** * Function right * @author George * @brief 小车右转 右转(左轮前进,右轮不动) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::right(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //左边电机速度设200(0-255) //右电机停止 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, 0); //右边电机速度设0(0-255) } /** * Function spin_left * @author George * @brief 小车原地左转 原地左转(左轮后退,右轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::spin_left(int speed) { //左电机后退 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, HIGH); //左电机后退使能 analogWrite(Left_motor_pwm, speed); //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); } /** * Function spin_right * @author George * @brief 小车原地右转 原地右转(右轮后退,左轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::spin_right(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //右电机后退 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, HIGH); //右电机后退使能 analogWrite(Right_motor_pwm, speed); }
23.114428
98
0.64378
zzboss
4873d633f2dfe552a6768aa2782d82ae5d9b5008
4,633
cxx
C++
graphics/nxwm/src/cfullscreenwindow.cxx
DS-LK/incubator-nuttx-apps
5719753399c41529478ced0a3af9a8fae93a50a9
[ "Apache-2.0" ]
1
2022-01-04T04:04:58.000Z
2022-01-04T04:04:58.000Z
graphics/nxwm/src/cfullscreenwindow.cxx
VanFeo/incubator-nuttx-apps
009e66874538658c10a26bc076d27e9de48fabc6
[ "Apache-2.0" ]
null
null
null
graphics/nxwm/src/cfullscreenwindow.cxx
VanFeo/incubator-nuttx-apps
009e66874538658c10a26bc076d27e9de48fabc6
[ "Apache-2.0" ]
null
null
null
/******************************************************************************************** * apps/graphics/nxwm/src/cfullscreenwindow.cxx * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ********************************************************************************************/ /******************************************************************************************** * Included Files ********************************************************************************************/ #include <nuttx/config.h> #include <nuttx/nx/nxglib.h> #include "graphics/nxwidgets/nxconfig.hxx" #include "graphics/nxwidgets/cwidgetcontrol.hxx" #include "graphics/nxwidgets/cgraphicsport.hxx" #include "graphics/nxwm/nxwmconfig.hxx" #include "graphics/nxglyphs.hxx" #include "graphics/nxwm/cfullscreenwindow.hxx" /******************************************************************************************** * Pre-Processor Definitions ********************************************************************************************/ /******************************************************************************************** * CFullScreenWindow Method Implementations ********************************************************************************************/ using namespace NxWM; /** * CFullScreenWindow Constructor * * @param window. The raw window to be used by this application. */ CFullScreenWindow::CFullScreenWindow(NXWidgets::CNxWindow *window) { // Save the window for later use m_window = window; } /** * CFullScreenWindow Destructor */ CFullScreenWindow::~CFullScreenWindow(void) { // We didn't create the window. That was done by the task bar, // But we will handle destruction of with window as a courtesy. if (m_window) { delete m_window; } } /** * Initialize window. Window initialization is separate from * object instantiation so that failures can be reported. * * @return True if the window was successfully initialized. */ bool CFullScreenWindow::open(void) { return true; } /** * Re-draw the application window */ void CFullScreenWindow::redraw(void) { } /** * The application window is hidden (either it is minimized or it is * maximized, but not at the top of the hierarchy) */ void CFullScreenWindow::hide(void) { } /** * Recover the contained raw window instance * * @return. The window used by this application */ NXWidgets::INxWindow *CFullScreenWindow::getWindow(void) const { return static_cast<NXWidgets::INxWindow*>(m_window); } /** * Recover the contained widget control * * @return. The widget control used by this application */ NXWidgets::CWidgetControl *CFullScreenWindow::getWidgetControl(void) const { return m_window->getWidgetControl(); } /** * Block further activity on this window in preparation for window * shutdown. * * @param app. The application to be blocked */ void CFullScreenWindow::block(IApplication *app) { // Get the widget control from the NXWidgets::CNxWindow instance NXWidgets::CWidgetControl *control = m_window->getWidgetControl(); // And then block further reporting activity on the underlying // NX raw window nx_block(control->getWindowHandle(), (FAR void *)app); } /** * Set the window label * * @param appname. The name of the application to place on the window */ void CFullScreenWindow::setWindowLabel(NXWidgets::CNxString &appname) { } /** * Report of this is a "normal" window or a full screen window. The * primary purpose of this method is so that window manager will know * whether or not it show draw the task bar. * * @return True if this is a full screen window. */ bool CFullScreenWindow::isFullScreen(void) const { return true; } /** * Register to receive callbacks when toolbar icons are selected */ void CFullScreenWindow::registerCallbacks(IApplicationCallback *callback) { }
26.474286
94
0.616879
DS-LK
4876effedc7f70ccacd951b3eadcfce9fc0e8480
11,299
cpp
C++
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
2
2017-11-08T16:27:25.000Z
2018-08-10T09:08:35.000Z
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
null
null
null
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
4
2017-11-08T16:25:30.000Z
2021-05-23T06:14:59.000Z
/* * Created by phuctm97 on Sep 30th 2017 */ #include "Scene.h" #include "StdHelper.h" #include "GameResource.h" #include "GameManager.h" #include "../2d/2dMacros.h" #include "../2d/Camera.h" NAMESPACE_ALA { ALA_CLASS_SOURCE_2(ala::Scene, ala::Initializable, ala::Releasable) // ================================================ // Basic // ================================================ Scene::Scene(): _toReleaseInNextFrame( false ), _gameObjectInLock( false ), _quadTree( NULL ), _camera( NULL ), _cameraTransform( NULL ), _visibleWidth( 0 ), _visibleHeight( 0 ), _halfVisibleWidth( 0 ), _halfVisibleHeight( 0 ), _physicsEnabled( false ), _gravityAcceleration( 0, -100.0f ) { // check initial state ALA_ASSERT((!isInitialized()) && (!isInitializing()) && (!isReleased()) && (!isReleasing())); TOTAL_SCENES_CREATED++; } Scene::~Scene() { if ( isInitialized() ) { // make sure object released after destruction // ALA_ASSERT(isReleased()); } TOTAL_SCENES_DELETED++; } // ================================================= // Events // ================================================= void Scene::initialize() { // make sure scene is not initialized; ALA_ASSERT((!isInitializing()) && (!isInitialized())); // required framework objects const auto gameManager = GameManager::get(); _camera = gameManager->getPrefab( ALA_MAIN_CAMERA )->instantiate( ALA_MAIN_CAMERA ); _cameraTransform = _camera->getTransform(); _visibleWidth = gameManager->getVisibleWidth(); _visibleHeight = gameManager->getVisibleHeight(); _halfVisibleWidth = _visibleWidth / 2; _halfVisibleHeight = _visibleHeight / 2; onPreInitialize(); setToInitializing(); // TODO: lock mutual exclusive when run in multithreading mode // load resources scope with this for ( auto resource : GameManager::get()->getResourcesWith( this ) ) { if ( !resource->isLoaded() ) { resource->load(); } } // init game objects for ( const auto it : _gameObjects ) { auto object = it.second; if ( !object->isInitialized() ) { object->initialize(); } } setToInitialized(); onPostInitialize(); } void Scene::onPreInitialize() { } void Scene::onPostInitialize() {} void Scene::updatePhysics( const float delta ) { if ( isReleasing() || isReleased() || !isInitialized() || !isPhysicsEnabled() ) return; lockGameObjects(); onPrePhysicsUpdate( delta ); // update game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->updatePhysics( delta ); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->updatePhysics( delta ); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->updatePhysics( delta ); } } onPostPhysicsUpdate( delta ); unlockGameObjects(); } void Scene::onPrePhysicsUpdate( const float delta ) {} void Scene::onPostPhysicsUpdate( const float delta ) {} void Scene::update( const float delta ) { if ( isReleasing() || isReleased() || !isInitialized() ) return; lockGameObjects(); onPreUpdate( delta ); // update game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->update( delta ); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->update( delta ); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->update( delta ); } } onPostUpdate( delta ); unlockGameObjects(); } void Scene::onPreUpdate( const float delta ) {} void Scene::onPostUpdate( const float delta ) {} void Scene::render() { // make sure scene is initialized and not being released if ( (!isInitialized()) || isReleasing() || isReleased() ) return; lockGameObjects(); onPreRender(); // render game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->render(); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->render(); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->render(); } } onPostRender(); unlockGameObjects(); } void Scene::onPreRender() {} void Scene::onPostRender() {} void Scene::release() { // check lock if ( _gameObjectInLock ) { releaseInNextFrame(); return; } // make sure scene is initialized and not released // ALA_ASSERT(isInitialized() && (!isReleasing()) && (!isReleased())); onPreRelease(); setToReleasing(); // release quad tree if ( _quadTree != NULL ) delete _quadTree; // release game objects std::vector<GameObject*> gameObjectsToRelease; for ( const auto it : _gameObjects ) { auto object = it.second; object->release(); } // release resources scope with this for ( auto resouce : GameManager::get()->getResourcesWith( this ) ) { resouce->release(); } setToReleased(); onPostRelease(); // destroy delete this; } void Scene::releaseInNextFrame() { // make sure scene is initialized and not released // ALA_ASSERT(isInitialized() && (!isReleasing()) && (!isReleased())); _toReleaseInNextFrame = true; } void Scene::onPreRelease() {} void Scene::onPostRelease() {} void Scene::resolveLockedTasks() { if ( isReleasing() || isReleased() ) return; // lazy initialization if ( !isInitialized() ) { initialize(); } // update to release in next frame if ( _toReleaseInNextFrame ) { release(); _toReleaseInNextFrame = false; return; } // update locked actions updateAddAndRemoveGameObjects(); // update quad tree if ( isQuadTreeEnabled() ) { updateQuadTreeVisibility(); } // client onResolveLockedTasks(); // update game object locked tasks lockGameObjects(); if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->resolveLockedTasks(); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->resolveLockedTasks(); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->resolveLockedTasks(); } } unlockGameObjects(); } void Scene::onResolveLockedTasks() { } // ================================================== // Objects Management // ================================================== GameObject* Scene::getGameObject( const long id ) const { const auto it = _gameObjects.find( id ); if ( it == _gameObjects.end() ) return NULL; return it->second; } GameObject* Scene::getMainCamera() const { return _camera; } bool Scene::isInLock() const { return _gameObjectInLock; } void Scene::addGameObject( GameObject* gameObject, const std::string& quadIndex ) { // check lock if ( _gameObjectInLock ) { addGameObjectInNextFrame( gameObject ); return; } if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; doAddGameObject( gameObject, quadIndex ); } void Scene::addGameObjectInNextFrame( GameObject* gameObject, const std::string& quadIndex ) { if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; _gameObjectsToAddInNextFrame.push_back( std::make_pair( gameObject, quadIndex ) ); } void Scene::removeGameObject( GameObject* gameObject ) { // check lock if ( _gameObjectInLock ) { removeGameObjectInNextFrame( gameObject ); return; } if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; doRemoveGameObject( gameObject->getId() ); } void Scene::removeGameObjectInNextFrame( GameObject* gameObject ) { if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; _gameObjectsToRemoveInNextFrame.push_back( gameObject->getId() ); } QuadTree* Scene::getQuadTree() const { return _quadTree; } void Scene::enableQuadTree( const float spaceMinX, const float spaceMinY, const float spaceWidth, const float spaceHeight, const int level ) { _quadTree = new QuadTree( spaceMinX, spaceMinY, spaceWidth, spaceHeight, level ); } bool Scene::isQuadTreeEnabled() const { return _quadTree != NULL; } void Scene::updateQuadTreeVisibility() const { const auto cameraPosition = _cameraTransform->getPosition(); // TODO: calculate with camera scale const auto cameraMinX = cameraPosition.getX() - _halfVisibleWidth; const auto cameraMinY = cameraPosition.getY() - _halfVisibleHeight; const auto cameraMaxX = cameraPosition.getX() + _halfVisibleWidth; const auto cameraMaxY = cameraPosition.getY() + _halfVisibleHeight; _quadTree->updateVisibility( cameraMinX, cameraMinY, cameraMaxX, cameraMaxY ); } void Scene::lockGameObjects() { _gameObjectInLock = true; } void Scene::unlockGameObjects() { _gameObjectInLock = false; } void Scene::updateAddAndRemoveGameObjects() { for ( const auto it : _gameObjectsToAddInNextFrame ) { doAddGameObject( it.first, it.second ); } _gameObjectsToAddInNextFrame.clear(); for ( auto objectId : _gameObjectsToRemoveInNextFrame ) { doRemoveGameObject( objectId ); } _gameObjectsToRemoveInNextFrame.clear(); } void Scene::doAddGameObject( GameObject* gameObject, const std::string& quadIndex ) { _gameObjects.emplace( gameObject->getId(), gameObject ); if ( !isQuadTreeEnabled() || quadIndex.empty() ) { _dynamicGameObjects.emplace( gameObject->getId(), gameObject ); } else { _quadTree->getNode( quadIndex )->addGameObject( gameObject ); _gameObjectToQuadNode.emplace( gameObject->getId(), quadIndex ); } } void Scene::doRemoveGameObject( const long id ) { const auto gameObjectIt = _gameObjects.find( id ); if ( gameObjectIt == _gameObjects.cend() ) return; if ( isQuadTreeEnabled() ) { const auto gameObjectToQuadNodeIt = _gameObjectToQuadNode.find( id ); if ( gameObjectToQuadNodeIt != _gameObjectToQuadNode.cend() ) { _quadTree->getNode( gameObjectToQuadNodeIt->second )->removeGameObject( gameObjectIt->second ); _gameObjectToQuadNode.erase( gameObjectToQuadNodeIt ); } } _gameObjects.erase( id ); _dynamicGameObjects.erase( id ); } const Vec2& Scene::getGravityAcceleration() const { return _gravityAcceleration; } void Scene::enablePhysics( const Vec2& gravity ) { _physicsEnabled = true; _gravityAcceleration = gravity; } bool Scene::isPhysicsEnabled() const { return _physicsEnabled; } // ============================================= // Debug memory allocation // ============================================= long Scene::TOTAL_SCENES_CREATED( 0 ); long Scene::TOTAL_SCENES_DELETED( 0 ); }
24.887665
101
0.638995
Khuongnb1997
487a31b93598cf12ca603abf7f9cf66c04d95618
5,826
hpp
C++
QuantExt/qle/pricingengines/commodityapoengine.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/pricingengines/commodityapoengine.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/pricingengines/commodityapoengine.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2019 Quaternion Risk Management Ltd All rights reserved. */ /*! \file qle/pricingengines/commodityapoengine.hpp \brief commodity average price option engine \ingroup engines */ #ifndef quantext_commodity_apo_engine_hpp #define quantext_commodity_apo_engine_hpp #include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp> #include <ql/termstructures/yieldtermstructure.hpp> #include <qle/instruments/commodityapo.hpp> #include <qle/methods/multipathgeneratorbase.hpp> namespace QuantExt { /*! Commodity APO Engine base class Correlation is parametrized as \f$\rho(s, t) = \exp(-\beta * \abs(s - t))\f$ where \f$s\f$ and \f$t\f$ are times to futures expiry. */ class CommodityAveragePriceOptionBaseEngine : public CommodityAveragePriceOption::engine { public: CommodityAveragePriceOptionBaseEngine(const QuantLib::Handle<QuantLib::YieldTermStructure>& discountCurve, const QuantLib::Handle<QuantLib::BlackVolTermStructure>& vol, Real beta = 0.0); protected: /*! Calculate accrued portion of the average commodity price if any. There will be an accrued portion of the average price if any of the <em>Pricing Dates</em> are on or before the valuation date. The return value contains the accrued average price and the number of <em>Pricing Dates</em> that were on or before the valution date. If there has been no accrual, the return value is (0.0, 0). */ std::pair<QuantLib::Real, QuantLib::Size> calculateAccrued() const; //! Return the correlation between two future expiry dates \p ed_1 and \p ed_2 QuantLib::Real rho(const QuantLib::Date& ed_1, const QuantLib::Date& ed_2) const; /*! In certain cases, the APO value is not model dependent. This method returns \c true if the APO value is model dependent. If the APO value is not model dependent, this method returns \c false and populates the results with the model independent value. */ bool isModelDependent(const std::pair<QuantLib::Real, QuantLib::Size>& accrued) const; QuantLib::Handle<QuantLib::YieldTermStructure> discountCurve_; QuantLib::Handle<QuantLib::BlackVolTermStructure> volStructure_; QuantLib::Real beta_; }; /*! Commodity APO Analytical Engine Analytical pricing based on the two-moment Turnbull-Wakeman approximation. Reference: Iain Clark, Commodity Option Pricing, Wiley, section 2.7.4 See also the documentation in the ORE+ product catalogue. */ class CommodityAveragePriceOptionAnalyticalEngine : public CommodityAveragePriceOptionBaseEngine { public: CommodityAveragePriceOptionAnalyticalEngine(const QuantLib::Handle<QuantLib::YieldTermStructure>& discountCurve, const QuantLib::Handle<QuantLib::BlackVolTermStructure>& vol, QuantLib::Real beta = 0.0) : CommodityAveragePriceOptionBaseEngine(discountCurve, vol, beta) {} void calculate() const; }; /*! Commodity APO Monte Carlo Engine Monte Carlo implementation of the APO payoff Reference: Iain Clark, Commodity Option Pricing, Wiley, section 2.7.4, equations (2.118) and (2.126) */ class CommodityAveragePriceOptionMonteCarloEngine : public CommodityAveragePriceOptionBaseEngine { public: CommodityAveragePriceOptionMonteCarloEngine(const QuantLib::Handle<QuantLib::YieldTermStructure>& discountCurve, const QuantLib::Handle<QuantLib::BlackVolTermStructure>& vol, QuantLib::Size samples, QuantLib::Real beta = 0.0, const QuantLib::Size seed = 42) : CommodityAveragePriceOptionBaseEngine(discountCurve, vol, beta), samples_(samples), seed_(seed) {} void calculate() const; private: //! Calculations when underlying swap references a commodity spot price void calculateSpot(const std::pair<QuantLib::Real, QuantLib::Size>& accrued) const; //! Calculations when underlying swap references a commodity spot price void calculateFuture(const std::pair<QuantLib::Real, QuantLib::Size>& accrued) const; /*! Prepare data for APO calculation. The \p outVolatilities parameter will be populated with separate future contract volatilities taking into account the \p strike level. The number of elements of \p outVolatilities gives the number, N, of future contracts involved in the non-accrued portion of the APO. The matrix \p outSqrtCorr is populated with the square root of the correlation matrix between the future contracts. The \p outPrices vector will be populated with the current future price values. The \p futureIndex is populated with the index of the future to be used on each timestep in the simulation. */ void setupFuture(std::vector<QuantLib::Real>& outVolatilities, QuantLib::Matrix& outSqrtCorr, std::vector<QuantLib::Real>& outPrices, std::vector<QuantLib::Size>& futureIndex, QuantLib::Real strike) const; /*! Return the \f$n\f$ timesteps from today, \f$t_0\f$, up to \f$t_n\f$ where \f$n > 0\f$. Note that each \f$t_i\f$ corresponds to a pricing date \f$d_i\f$ that is after today. The method returns the vector of time deltas \f$t_i - t_{i-1}\f$ for \f$i=1,\ldots,n\f$ and populates the vector \p outDates with the dates \f$d_0, d_1,...,d_n\f$. Note that the size of \p outDates is one larger than the size of the return vector. */ std::vector<QuantLib::Real> timegrid(std::vector<QuantLib::Date>& outDates) const; QuantLib::Size samples_; QuantLib::Size seed_; }; } // namespace QuantExt #endif
50.66087
117
0.700309
mrslezak
487a5ced28622cdd7c84c8d638daa1086c5b3e9b
2,802
cpp
C++
cpp/coroutine_noop_coroutine.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/coroutine_noop_coroutine.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/coroutine_noop_coroutine.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/coroutine_noop_coroutine.exe ./cpp/coroutine_noop_coroutine.cpp && (cd ../_build/cpp/;./coroutine_noop_coroutine.exe) https://en.cppreference.com/w/cpp/coroutine/noop_coroutine */ #include <coroutine> #include <utility> #include <iostream> template<class T> struct task { struct promise_type { auto get_return_object() { return task(std::coroutine_handle<promise_type>::from_promise(*this)); } std::suspend_always initial_suspend() { return {}; } struct final_awaiter { bool await_ready() noexcept { return false; } void await_resume() noexcept {} std::coroutine_handle<> await_suspend(std::coroutine_handle<promise_type> h) noexcept { // final_awaiter::await_suspend is called when the execution of the // current coroutine (referred to by 'h') is about to finish. // If the current coroutine was resumed by another coroutine via // co_await get_task(), a handle to that coroutine has been stored // as h.promise().previous. In that case, return the handle to resume // the previous coroutine. // Otherwise, return noop_coroutine(), whose resumption does nothing. auto previous = h.promise().previous; if (previous) { return previous; } else { return std::noop_coroutine(); } } }; final_awaiter final_suspend() noexcept { return {}; } void unhandled_exception() { throw; } void return_value(T value) { result = std::move(value); } T result; std::coroutine_handle<> previous; }; task(std::coroutine_handle<promise_type> h) : coro(h) {} task(task&& t) = delete; ~task() { coro.destroy(); } struct awaiter { bool await_ready() { return false; } T await_resume() { return std::move(coro.promise().result); } auto await_suspend(std::coroutine_handle<> h) { coro.promise().previous = h; return coro; } std::coroutine_handle<promise_type> coro; }; awaiter operator co_await() { return awaiter{coro}; } T operator()() { coro.resume(); return std::move(coro.promise().result); } private: std::coroutine_handle<promise_type> coro; }; task<int> get_random() { std::cout << "in get_random()\n"; co_return 4; } task<int> test() { task<int> v = get_random(); task<int> u = get_random(); std::cout << "in test()\n"; int x = (co_await v + co_await u); co_return x; } int main() { task<int> t = test(); int result = t(); std::cout << result << '\n'; }
36.38961
159
0.584582
rpuntaie
487aa1d1c63091c25dde2241d1062b1d7dd5af96
1,195
cpp
C++
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
auto PSG::write(uint8 data) -> void { bool l = data.bit(7); if(l) select = data.bits(4,6); switch(select) { case 0: { if(l) tone0.pitch.bits(0,3) = data.bits(0,3); else tone0.pitch.bits(4,9) = data.bits(0,5); break; } case 1: { tone0.volume = data.bits(0,3); break; } case 2: { if(l) tone1.pitch.bits(0,3) = data.bits(0,3); else tone1.pitch.bits(4,9) = data.bits(0,5); break; } case 3: { tone1.volume = data.bits(0,3); break; } case 4: { if(l) tone2.pitch.bits(0,3) = data.bits(0,3); else tone2.pitch.bits(4,9) = data.bits(0,5); noise.pitch = tone2.pitch; break; } case 5: { tone2.volume = data.bits(0,3); break; } case 6: { noise.rate = data.bits(0,1); noise.enable = data.bit(2); noise.lfsr = 0x8000; break; } case 7: { noise.volume = data.bits(0,3); break; } } } //Game Gear only auto PSG::balance(uint8 data) -> void { tone0.right = data.bit(0); tone1.right = data.bit(1); tone2.right = data.bit(2); noise.right = data.bit(3); tone0.left = data.bit(4); tone1.left = data.bit(5); tone2.left = data.bit(6); noise.left = data.bit(7); }
17.835821
49
0.553975
13824125580
487aefa8e6a9b2449309a561ee11d697dc3562ec
1,403
cpp
C++
test/constant/scalar/sqrt_2o_3.cpp
TobiasLudwig/boost.simd
c04d0cc56747188ddb9a128ccb5715dd3608dbc1
[ "BSL-1.0" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
test/constant/scalar/sqrt_2o_3.cpp
remymuller/boost.simd
3caefb7ee707e5f68dae94f8f31f72f34b7bb5de
[ "BSL-1.0" ]
null
null
null
test/constant/scalar/sqrt_2o_3.cpp
remymuller/boost.simd
3caefb7ee707e5f68dae94f8f31f72f34b7bb5de
[ "BSL-1.0" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #include <boost/simd/constant/sqrt_2o_3.hpp> #include <boost/simd/constant/ratio.hpp> #include <boost/simd/as.hpp> #include <scalar_test.hpp> STF_CASE_TPL( "Check sqrt_2o_3 behavior for integral types" , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t) (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t) ) { using boost::simd::as; using boost::simd::detail::sqrt_2o_3; using boost::simd::Sqrt_2o_3; STF_TYPE_IS(decltype(Sqrt_2o_3<T>()), T); STF_EQUAL(Sqrt_2o_3<T>(), T(0)); STF_EQUAL(sqrt_2o_3( as(T{}) ),T(0)); } STF_CASE_TPL( "Check sqrt_2o_3 behavior for floating types" , (double)(float) ) { using boost::simd::as; using boost::simd::detail::sqrt_2o_3; using boost::simd::Sqrt_2o_3; using boost::simd::Ratio; STF_TYPE_IS(decltype(Sqrt_2o_3<T>()), T); auto z1 = Sqrt_2o_3<T>(); STF_ULP_EQUAL(z1*z1, (Ratio<T,2,3>()), 0.5); auto z2 = sqrt_2o_3( as(T{}) ); STF_ULP_EQUAL(z2*z2, (Ratio<T,2,3>()), 0.5); }
29.851064
100
0.558803
TobiasLudwig
488178167970c29b3461a8ddb955a4034ebb91bf
8,974
cpp
C++
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
1
2020-11-05T06:51:16.000Z
2020-11-05T06:51:16.000Z
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
null
null
null
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
4
2019-06-06T11:35:42.000Z
2021-11-20T02:40:15.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <exception> #include <limits> #if _MSC_VER #include "msinttypes/stdint.h" #else #include <stdint.h> #endif #include <cstdlib> #include <math.h> #include <random> #include "resultfilename.h" #include "timer.h" #include "test.h" #include "double-conversion/double-conversion.h" const unsigned kIterationForRandom = 100; const unsigned kIterationPerDigit = 10; const unsigned kTrial = 10; class RandomData { public: static double* GetData() { static RandomData singleton; return singleton.mData; } static const size_t kCount = 100000; private: RandomData() : mData(new double[kCount]) { std::mt19937 rg{ std::random_device{}() }; union { double d; uint64_t u; }u; for (size_t i = 0; i < kCount; i++) { do { // Need to call r() in two statements for cross-platform coherent sequence. u.u = uint64_t(rg()) << 32; u.u |= uint64_t(rg()); } while (isnan(u.d) || isinf(u.d)); mData[i] = u.d; } } ~RandomData() { delete[] mData; } double* mData; }; static size_t VerifyValue(double value, void(*f)(double, char*), const char* expect = 0) { char buffer[1024]; f(value, buffer); //printf("%.17g -> %s\n", value, buffer); if (expect && strcmp(buffer, expect) != 0) { printf("Error: expect %s but actual %s\n", expect, buffer); //throw std::exception(); } #if 0 char* end; double roundtrip = strtod(buffer, &end); int processed = int(end - buffer); #else // double-conversion returns correct result. using namespace double_conversion; StringToDoubleConverter converter(StringToDoubleConverter::ALLOW_TRAILING_JUNK, 0.0, 0.0, NULL, NULL); int processed = 0; double roundtrip = converter.StringToDouble(buffer, 1024, &processed); #endif size_t len = strlen(buffer); if (len != (size_t)processed) { printf("Error: some extra character %g -> '%s'\n", value, buffer); throw std::exception(); } if (value != roundtrip) { printf("Error: roundtrip fail %.17g -> '%s' -> %.17g\n", value, buffer, roundtrip); //throw std::exception(); } return len; } static void Verify(void(*f)(double, char*), const char* fname) { printf("Verifying %-20s ... ", fname); // Boundary and simple cases VerifyValue(0, f); /*VerifyValue(0.1, f, "0.1"); VerifyValue(0.12, f, "0.12"); VerifyValue(0.123, f, "0.123"); VerifyValue(0.1234, f, "0.1234"); VerifyValue(1.2345, f, "1.2345");*/ ////////////////////// VerifyValue(0.1, f); VerifyValue(0.12, f); VerifyValue(0.123, f); VerifyValue(0.1234, f); VerifyValue(1.2345, f); ////////////////////// VerifyValue(1.0 / 3.0, f); VerifyValue(2.0 / 3.0, f); VerifyValue(10.0 / 3.0, f); VerifyValue(20.0 / 3.0, f); VerifyValue(std::numeric_limits<double>::min(), f); VerifyValue(std::numeric_limits<double>::max(), f); VerifyValue(std::numeric_limits<double>::denorm_min(), f); char buffer[256]; double* data = RandomData::GetData(); size_t n = RandomData::kCount; uint64_t lenSum = 0; size_t lenMax = 0; for (unsigned i = 0; i < n; i++) { size_t len = VerifyValue(data[i], f); lenSum += len; lenMax = std::max(lenMax, len); } double lenAvg = double(lenSum) / n; printf("OK. Length Avg = %2.3f, Max = %d\n", lenAvg, (int)lenMax); } void VerifyAll() { const TestList& tests = TestManager::Instance().GetTests(); for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) { if (strcmp((*itr)->fname, "null") != 0) { // skip null try { Verify((*itr)->dtoa, (*itr)->fname); } catch (...) { } } } } void BenchSequential(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking sequential %-20s ... ", fname); char buffer[256] = { '\0' }; double minDuration = std::numeric_limits<double>::max(); double maxDuration = 0.0; int64_t start = 1; for (int digit = 1; digit <= 17; digit++) { int64_t end = start * 10; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { int64_t v = start; std::mt19937 rg{ std::random_device{}() }; v += ((int64_t(rg()) << 32) | int64_t(rg())) % start; double sign = 1; Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) { double d = v * sign; f(d, buffer); //printf("%.17g -> %s\n", d, buffer); sign = -sign; v += 1; if (v >= end) v = start; } timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / kIterationPerDigit; // convert to nano second per operation minDuration = std::min(minDuration, duration); maxDuration = std::max(maxDuration, duration); fprintf(fp, "%s_sequential,%d,%f\n", fname, digit, duration); start = end; } printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration); } void BenchRandom(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking random %-20s ... ", fname); char buffer[256]; double* data = RandomData::GetData(); size_t n = RandomData::kCount; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationForRandom; iteration++) for (size_t i = 0; i < n; i++) f(data[i], buffer); timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / (kIterationForRandom * n); // convert to nano second per operation fprintf(fp, "random,%s,0,%f\n", fname, duration); printf("%8.3fns\n", duration); } class RandomDigitData { public: static double* GetData(int digit) { assert(digit >= 1 && digit <= 17); static RandomDigitData singleton; return singleton.mData + (digit - 1) * kCount; } static const int kMaxDigit = 17; static const size_t kCount = 10000; private: RandomDigitData() : mData(new double[kMaxDigit * kCount]) { std::mt19937 rg{ std::random_device{}() }; union { double d; uint64_t u; }u; double* p = mData; for (int digit = 1; digit <= kMaxDigit; digit++) { for (size_t i = 0; i < kCount; i++) { do { // Need to call r() in two statements for cross-platform coherent sequence. u.u = uint64_t(rg()) << 32; u.u |= uint64_t(rg()); } while (isnan(u.d) || isinf(u.d)); // Convert to string with limited digits, and convert it back. char buffer[256]; sprintf(buffer, "%.*g", digit, u.d); using namespace double_conversion; StringToDoubleConverter converter(StringToDoubleConverter::ALLOW_TRAILING_JUNK, 0.0, 0.0, NULL, NULL); int processed = 0; double roundtrip = converter.StringToDouble(buffer, 256, &processed); *p++ = roundtrip; } } } ~RandomDigitData() { delete[] mData; } double* mData; }; void BenchRandomDigit(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking randomdigit %-20s ... ", fname); char buffer[256]; double minDuration = std::numeric_limits<double>::max(); double maxDuration = 0.0; for (int digit = 1; digit <= RandomDigitData::kMaxDigit; digit++) { double* data = RandomDigitData::GetData(digit); size_t n = RandomDigitData::kCount; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) { for (size_t i = 0; i < n; i++) { f(data[i], buffer); //if (trial == 0 && iteration == 0 && i == 0) // printf("%.17g -> %s\n", data[i], buffer); } } timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / (kIterationPerDigit * n); // convert to nano second per operation minDuration = std::min(minDuration, duration); maxDuration = std::max(maxDuration, duration); fprintf(fp, "randomdigit,%s,%d,%f\n", fname, digit, duration); } printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration); } void Bench(void(*f)(double, char*), const char* fname, FILE* fp) { //BenchSequential(f, fname, fp); //BenchRandom(f, fname, fp); BenchRandomDigit(f, fname, fp); } void BenchAll() { // doublery to write to /result path, where template.php exists FILE *fp; if ((fp = fopen("../../result/template.php", "r")) != NULL) { fclose(fp); fp = fopen("../../result/" RESULT_FILENAME, "w"); } else if ((fp = fopen("../result/template.php", "r")) != NULL) { fclose(fp); fp = fopen("../result/" RESULT_FILENAME, "w"); } else fp = fopen(RESULT_FILENAME, "w"); fprintf(fp, "Type,Function,Digit,Time(ns)\n"); const TestList& tests = TestManager::Instance().GetTests(); for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) Bench((*itr)->dtoa, (*itr)->fname, fp); fclose(fp); } int main() { // sort tests TestList& tests = TestManager::Instance().GetTests(); std::sort(tests.begin(), tests.end()); VerifyAll(); BenchAll(); }
26.087209
106
0.634723
jk-jeon
4882d3004fbce99beccaf4a94e9ac7b8b46da600
1,596
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
//<Snippet2> // Example of the Decimal( unsigned int ) constructor. using namespace System; // Create a Decimal object and display its value. void CreateDecimal( unsigned int value, String^ valToStr ) { Decimal decimalNum = Decimal(value); // Format the constructor for display. String^ ctor = String::Format( "Decimal( {0} )", valToStr ); // Display the constructor and its value. Console::WriteLine( "{0,-30}{1,16}", ctor, decimalNum ); } int main() { Console::WriteLine( "This example of the Decimal( unsigned " "int ) constructor \ngenerates the following output.\n" ); Console::WriteLine( "{0,-30}{1,16}", "Constructor", "Value" ); Console::WriteLine( "{0,-30}{1,16}", "-----------", "-----" ); // Construct Decimal objects from unsigned int values. CreateDecimal( UInt32::MinValue, "UInt32::MinValue" ); CreateDecimal( UInt32::MaxValue, "UInt32::MaxValue" ); CreateDecimal( Int32::MaxValue, "Int32::MaxValue" ); CreateDecimal( 999999999, "999999999" ); CreateDecimal( 0x40000000, "0x40000000" ); CreateDecimal( 0xC0000000, "0xC0000000" ); } /* This example of the Decimal( unsigned int ) constructor generates the following output. Constructor Value ----------- ----- Decimal( UInt32::MinValue ) 0 Decimal( UInt32::MaxValue ) 4294967295 Decimal( Int32::MaxValue ) 2147483647 Decimal( 999999999 ) 999999999 Decimal( 0x40000000 ) 1073741824 Decimal( 0xC0000000 ) 3221225472 */ //</Snippet2>
33.25
65
0.62406
BohdanMosiyuk
4885dcc922f24c54522095ca6d4d3c45d062dd0c
8,247
cpp
C++
TAO/tao/AnyTypeCode/AnyTypeCode_Adapter_Impl.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/AnyTypeCode/AnyTypeCode_Adapter_Impl.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/AnyTypeCode/AnyTypeCode_Adapter_Impl.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // $Id: AnyTypeCode_Adapter_Impl.cpp 97073 2013-04-24 08:21:15Z sma $ #include "tao/AnyTypeCode/AnyTypeCode_Adapter_Impl.h" #include "tao/AnyTypeCode/SystemExceptionA.h" #include "tao/AnyTypeCode/WrongTransactionA.h" #include "tao/AnyTypeCode/PolicyA.h" #include "tao/AnyTypeCode/Any.h" #include "tao/AnyTypeCode/Any_Unknown_IDL_Type.h" #include "tao/AnyTypeCode/BooleanSeqA.h" #include "tao/AnyTypeCode/OctetSeqA.h" #include "tao/AnyTypeCode/CharSeqA.h" #include "tao/AnyTypeCode/WCharSeqA.h" #include "tao/AnyTypeCode/ShortSeqA.h" #include "tao/AnyTypeCode/UShortSeqA.h" #include "tao/AnyTypeCode/LongSeqA.h" #include "tao/AnyTypeCode/ULongSeqA.h" #include "tao/AnyTypeCode/LongLongSeqA.h" #include "tao/AnyTypeCode/ULongLongSeqA.h" #include "tao/AnyTypeCode/FloatSeqA.h" #include "tao/AnyTypeCode/DoubleSeqA.h" #include "tao/AnyTypeCode/LongDoubleSeqA.h" #include "tao/AnyTypeCode/StringSeqA.h" #include "tao/AnyTypeCode/WStringSeqA.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL #define STANDARD_EXCEPTION_LIST \ TAO_SYSTEM_EXCEPTION (UNKNOWN) \ TAO_SYSTEM_EXCEPTION (BAD_PARAM) \ TAO_SYSTEM_EXCEPTION (NO_MEMORY) \ TAO_SYSTEM_EXCEPTION (IMP_LIMIT) \ TAO_SYSTEM_EXCEPTION (COMM_FAILURE) \ TAO_SYSTEM_EXCEPTION (INV_OBJREF) \ TAO_SYSTEM_EXCEPTION (OBJECT_NOT_EXIST) \ TAO_SYSTEM_EXCEPTION (NO_PERMISSION) \ TAO_SYSTEM_EXCEPTION (INTERNAL) \ TAO_SYSTEM_EXCEPTION (MARSHAL) \ TAO_SYSTEM_EXCEPTION (INITIALIZE) \ TAO_SYSTEM_EXCEPTION (NO_IMPLEMENT) \ TAO_SYSTEM_EXCEPTION (BAD_TYPECODE) \ TAO_SYSTEM_EXCEPTION (BAD_OPERATION) \ TAO_SYSTEM_EXCEPTION (NO_RESOURCES) \ TAO_SYSTEM_EXCEPTION (NO_RESPONSE) \ TAO_SYSTEM_EXCEPTION (PERSIST_STORE) \ TAO_SYSTEM_EXCEPTION (BAD_INV_ORDER) \ TAO_SYSTEM_EXCEPTION (TRANSIENT) \ TAO_SYSTEM_EXCEPTION (FREE_MEM) \ TAO_SYSTEM_EXCEPTION (INV_IDENT) \ TAO_SYSTEM_EXCEPTION (INV_FLAG) \ TAO_SYSTEM_EXCEPTION (INTF_REPOS) \ TAO_SYSTEM_EXCEPTION (BAD_CONTEXT) \ TAO_SYSTEM_EXCEPTION (OBJ_ADAPTER) \ TAO_SYSTEM_EXCEPTION (DATA_CONVERSION) \ TAO_SYSTEM_EXCEPTION (INV_POLICY) \ TAO_SYSTEM_EXCEPTION (REBIND) \ TAO_SYSTEM_EXCEPTION (TIMEOUT) \ TAO_SYSTEM_EXCEPTION (TRANSACTION_UNAVAILABLE) \ TAO_SYSTEM_EXCEPTION (TRANSACTION_MODE) \ TAO_SYSTEM_EXCEPTION (TRANSACTION_REQUIRED) \ TAO_SYSTEM_EXCEPTION (TRANSACTION_ROLLEDBACK) \ TAO_SYSTEM_EXCEPTION (INVALID_TRANSACTION) \ TAO_SYSTEM_EXCEPTION (CODESET_INCOMPATIBLE) \ TAO_SYSTEM_EXCEPTION (BAD_QOS) \ TAO_SYSTEM_EXCEPTION (INVALID_ACTIVITY) \ TAO_SYSTEM_EXCEPTION (ACTIVITY_COMPLETED) \ TAO_SYSTEM_EXCEPTION (ACTIVITY_REQUIRED) \ TAO_SYSTEM_EXCEPTION (THREAD_CANCELLED) \ TAO_SYSTEM_EXCEPTION (WrongTransaction) \ TAO_SYSTEM_EXCEPTION (PolicyError) \ TAO_SYSTEM_EXCEPTION (InvalidPolicies) #define TAO_SYSTEM_EXCEPTION(name) \ CORBA::TypeCode_ptr \ TAO_AnyTypeCode_Adapter_Impl::_tao_type_ ## name (void) const \ { \ return CORBA::_tc_ ## name; \ } STANDARD_EXCEPTION_LIST #undef TAO_SYSTEM_EXCEPTION void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Char const * mychar) { (*any) <<= mychar; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::WChar const * mywchar) { (*any) <<= mywchar; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const std::string & value) { (*any) <<= value.c_str (); } #if !defined(ACE_LACKS_STD_WSTRING) void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const std::wstring & value) { (*any) <<= value.c_str (); } #endif /* ACE_LACKS_STD_WSTRING */ void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Long value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Short value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::UShort value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Float value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Double value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::LongLong value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::ULongLong value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::LongDouble value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Policy_ptr policy) { (*any) <<= policy; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::Policy_ptr * policy) { (*any) <<= policy; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, CORBA::ULong value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, ACE_OutputCDR::from_wchar value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, ACE_OutputCDR::from_char value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, ACE_OutputCDR::from_octet value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, ACE_OutputCDR::from_boolean value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::BooleanSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::OctetSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::CharSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::WCharSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::ShortSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::UShortSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::LongSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::ULongSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::LongLongSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::ULongLongSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::FloatSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::DoubleSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::LongDoubleSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::StringSeq & value) { (*any) <<= value; } void TAO_AnyTypeCode_Adapter_Impl::insert_into_any (CORBA::Any * any, const CORBA::WStringSeq & value) { (*any) <<= value; } int TAO_AnyTypeCode_Adapter_Impl::Initializer (void) { // The TAO::Unknown_IDL_Type::lock_i () is a PRIVATE thread unsafe singleton // which we need to initialise before Unknown_IDL_Types are used in a // threaded environment. This singleton is called for every constructed // Unknown_IDL_Type, so just create a throw-a-way from a null typecode. TAO::Unknown_IDL_Type singleton_initaliser (0); ACE_UNUSED_ARG (singleton_initaliser); return ACE_Service_Config::process_directive ( ace_svc_desc_TAO_AnyTypeCode_Adapter_Impl); } ACE_STATIC_SVC_DEFINE ( TAO_AnyTypeCode_Adapter_Impl, ACE_TEXT ("AnyTypeCode_Adapter"), ACE_SVC_OBJ_T, &ACE_SVC_NAME (TAO_AnyTypeCode_Adapter_Impl), ACE_Service_Type::DELETE_THIS | ACE_Service_Type::DELETE_OBJ, 0) ACE_FACTORY_DEFINE (TAO_AnyTypeCode, TAO_AnyTypeCode_Adapter_Impl) TAO_END_VERSIONED_NAMESPACE_DECL
26.015773
100
0.745241
cflowe
4885ef7749b1cab8ce2e88c3699c6d00239d6432
6,289
cpp
C++
src/material.cpp
ECToo/knowledge
ed6a51b9c7a119f453acb8b1151cbf6aa43f3099
[ "MIT" ]
null
null
null
src/material.cpp
ECToo/knowledge
ed6a51b9c7a119f453acb8b1151cbf6aa43f3099
[ "MIT" ]
null
null
null
src/material.cpp
ECToo/knowledge
ed6a51b9c7a119f453acb8b1151cbf6aa43f3099
[ "MIT" ]
null
null
null
/* Copyright (c) 2008-2009 Rômulo Fernandes Machado <romulo@castorgroup.net> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "material.h" #include "root.h" #include "logger.h" namespace k { material::material() { mCull = CULLMODE_FRONT; mDepthTest = true; mDepthWrite = true; mNoDraw = false; mIsOpaque = true; mReceiveLight = 1; } material::material(texture* tex) { kAssert(tex); try { materialStage* newStage = new materialStage(0); newStage->setTexturesCount(1); newStage->setTexture(tex, 0); pushStage(newStage); } catch (...) { S_LOG_INFO("Failed to allocate material stage."); } mCull = CULLMODE_FRONT; mDepthTest = true; mDepthWrite = true; mNoDraw = false; mIsOpaque = true; mReceiveLight = 1; } material::material(const std::string& filename) { texture* newTexture = textureManager::getSingleton().getTexture(filename); if (!newTexture) { S_LOG_INFO("Failed to make a new material, texture not found."); return; } try { materialStage* newStage = new materialStage(0); newStage->setTexturesCount(1); newStage->setTexture(newTexture, 0); pushStage(newStage); } catch (...) { S_LOG_INFO("Failed to allocate material stage."); } mCull = CULLMODE_FRONT; mDepthTest = true; mDepthWrite = true; mNoDraw = false; mIsOpaque = true; mReceiveLight = 1; } material::~material() { std::vector<materialStage*>::iterator it; for (it = mStages.begin(); it != mStages.end(); it++) { materialStage* tmpStage = (*it); delete tmpStage; } mStages.clear(); } void material::start() { // Material Properties renderSystem* rs = root::getSingleton().getRenderSystem(); if (mNoDraw) return; rs->bindMaterial(this); rs->matAmbient(mAmbient); rs->matDiffuse(mDiffuse); rs->matSpecular(mSpecular); rs->setCulling(mCull); rs->setDepthTest(mDepthTest); rs->setDepthMask(mDepthWrite); // Color/Light Only if (!mStages.size()) { rs->setColorChannels(0); rs->setTextureGenerations(0); rs->setTextureUnits(1); } else { rs->setColorChannels(1); rs->setTextureGenerations(mStages.size()); rs->setTextureUnits(mStages.size()); } if (!mReceiveLight && rs->isLightOn()) { // Magic trick mReceiveLight = -rs->getEnabledLightCount(); rs->setLighting(false); } // Cycle through textures std::vector<materialStage*>::const_iterator it; for (it = mStages.begin(); it != mStages.end(); it++) { (*it)->feedAnims(); (*it)->draw(); } } void material::finish() { if (mNoDraw) return; renderSystem* rs = root::getSingleton().getRenderSystem(); if (mReceiveLight < 0) { rs->setLighting(true); for (int i = 0; i < -mReceiveLight; i++) rs->setLight(i, true); // Disabled again mReceiveLight = 0; } // Cycle through textures std::vector<materialStage*>::const_iterator it; for (it = mStages.begin(); it != mStages.end(); it++) (*it)->finish(); } materialStage::materialStage(unsigned short index) { mIndex = index; mAngle = 0; mBlendSrc = 0; mBlendDst = 0; mRotate = 0; mScroll.x = 0; mScroll.y = 0; mLastFeedTime = root::getSingleton().getGlobalTime(); mNumberOfFrames = 0; mCurrentFrame = 0; mFrameRate = 0; mTexEnv = TEXENV_REPLACE; mCoordType = TEXCOORD_UV; mTextures = NULL; mTexturesCount = 0; } materialStage::~materialStage() { delete [] mTextures; } void materialStage::setEnv(unsigned int tev) { mTexEnv = tev; } void materialStage::setBlendMode(unsigned short src, unsigned short dst) { mBlendSrc = src; mBlendDst = dst; } void materialStage::setTexturesCount(unsigned int count) { mTexturesCount = count; try { mTextures = new texture*[mTexturesCount]; for (unsigned int i = 0; i < mTexturesCount; i++) mTextures[i] = NULL; } catch (...) { S_LOG_INFO("Failed to allocate texture array for material stage."); } } void materialStage::feedAnims() { if (mNumberOfFrames == 0) return; long timeNow = root::getSingleton().getGlobalTime(); mCurrentFrame += (mFrameRate * (timeNow - mLastFeedTime)) / 1000.0f; mLastFeedTime = timeNow; while ((uint32_t)mCurrentFrame >= mNumberOfFrames) mCurrentFrame -= mNumberOfFrames; } void materialStage::setTexture(texture* tex, unsigned int index) { kAssert(tex); mTextures[index] = tex; } const texture* materialStage::getTexture(unsigned int i) const { return mTextures[i]; } unsigned int materialStage::getWidth() const { if (mTextures[0]) return mTextures[0]->getWidth(); else return 0; } unsigned int materialStage::getHeight() const { if (mTextures[0]) return mTextures[0]->getHeight(); else return 0; } bool materialStage::isOpaque() const { if (!mBlendDst && !mBlendSrc) return true; else return false; } void materialStage::setCoordType(TextureCoordType type) { mCoordType = type; } void materialStage::setScroll(vector2 scroll) { mScroll = scroll; } unsigned int materialStage::getImagesCount() const { return mTexturesCount; } void materialStage::setScale(vector2 scale) { mScale = scale; } void materialStage::setRotate(vec_t angle) { mRotate = angle; } bool materialStage::containsTexture(const std::string& name) const { for (unsigned int i = 0; i < mTexturesCount; i++) { if (!mTextures[i]) break; if (mTextures[i]->containsFilename(name)) return true; } return false; } }
19.5919
77
0.703927
ECToo
4886283cfef1b077fc731acc675521925944c343
3,323
cpp
C++
code/test_billboard.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
1
2021-06-22T07:05:51.000Z
2021-06-22T07:05:51.000Z
code/test_billboard.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
14
2018-08-29T09:32:17.000Z
2018-09-15T10:52:22.000Z
code/test_billboard.cpp
aod6060/fps_game
b1d55d02ec124dc22ce877b814b6ff8452915213
[ "MIT" ]
null
null
null
#include "sys.h" glm::vec3 randColor() { return glm::vec3( (rand() % 255) / 255.0f, (rand() % 255) / 255.0f, (rand() % 255) / 255.0f ); } void TestBillboard::init(const glm::vec3& location) { this->loadParticles(); this->tex.init(this->getParticles()); this->location = location + glm::vec3(0.0f, 1.0f, 0.0f); // Shaders vertex.create(GL_VERTEX_SHADER, "data/shaders/test_billboard.vert"); fragment.create(GL_FRAGMENT_SHADER, "data/shaders/test_billboard.frag"); // Program program.addShader(&vertex); program.addShader(&fragment); program.create(); // Attributes program.bind(); program.getAttr()->set("vertices", 0); program.getAttr()->set("texCoords", 1); program.getAttr()->bind(); program.getAttr()->enable("vertices"); program.getAttr()->enable("texCoords"); program.getAttr()->unbind(); program.getAttr()->disable("vertices"); program.getAttr()->disable("texCoords"); // Uniforms program.getUniforms()->create("proj"); program.getUniforms()->create("view"); program.getUniforms()->create("model"); program.getUniforms()->create("tex0"); program.getUniforms()->set1i("tex0", 0); program.getUniforms()->create("colorize"); program.getUniforms()->set3f("colorize", randColor()); program.unbind(); // Vertex Buffer vbuf.add(-0.5f, 0.5f, 0.0f); vbuf.add(0.5f, 0.5f, 0.0f); vbuf.add(-0.5f, -0.5f, 0.0f); vbuf.add(0.5f, -0.5f, 0.0f); vbuf.create(); vbuf.upload(); tbuf.add(0.0f, 0.0f); tbuf.add(1.0f, 0.0f); tbuf.add(0.0f, 1.0f); tbuf.add(1.0f, 1.0f); tbuf.create(); tbuf.upload(); // Index Buffer ibuf.add(0, 1, 2); ibuf.add(2, 1, 3); ibuf.create(); ibuf.upload(); std::cout << vbuf.size() << ", " << ibuf.size() << std::endl; } static void _combine(glm::mat4& model, glm::mat4& rot) { for (uint32_t i = 0; i < 3; i++) { model[i].x = rot[i].x; model[i].y = rot[i].y; model[i].z = rot[i].z; } } void TestBillboard::render(Camera& camera) { glm::mat4 model = glm::translate(glm::mat4(1.0f), location); glm::mat4 rot = glm::transpose(camera.toViewMatrix()); _combine(model, rot); model *= glm::scale(glm::mat4(1.0f), glm::vec3(4.0f, 4.0f, 0.0f)); glEnable(GL_BLEND); //glBlendFunc(GL_SRC_COLOR, GL_ONE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); program.bind(); program.getUniforms()->setMat4("proj", camera.toProjMatrix()); program.getUniforms()->setMat4("view", camera.toViewMatrix()); program.getUniforms()->setMat4("model", model); tex.bind(GL_TEXTURE0); program.getAttr()->bind(); vbuf.bind(); program.getAttr()->pointer("vertices", 3, GL_FLOAT); vbuf.unbind(); tbuf.bind(); program.getAttr()->pointer("texCoords", 2, GL_FLOAT); tbuf.unbind(); ibuf.bind(); glDrawElements( GL_TRIANGLES, ibuf.size(), GL_UNSIGNED_INT, 0); ibuf.unbind(); program.getAttr()->unbind(); tex.unbind(GL_TEXTURE0); program.unbind(); glDisable(GL_BLEND); } void TestBillboard::release() { ibuf.release(); tbuf.release(); vbuf.release(); program.release(); fragment.release(); vertex.release(); tex.release(); } void TestBillboard::loadParticles() { std::ifstream in("data/textures/particles/particles.txt"); std::string temp; while (std::getline(in, temp)) { ppath.push_back(temp); } in.close(); } std::string TestBillboard::getParticles() { return ppath[rand() % ppath.size()]; }
20.512346
73
0.656636
aod6060
4886e4e3705016ccad778d9ed1e290088926b00e
9,867
cpp
C++
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
23
2017-11-01T14:47:26.000Z
2021-12-30T08:04:31.000Z
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
1
2018-12-06T14:19:55.000Z
2018-12-07T04:06:35.000Z
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
4
2017-11-30T10:25:58.000Z
2019-04-21T14:11:40.000Z
#include "SimpleCharacter2D.h" #include "Services/Render/Render.h" #include "SceneObjects/2D/SpriteAsset.h" CLASSREG(SceneObject, SimpleCharacter2D, "SimpleCharacter2D") META_DATA_DESC(SimpleCharacter2D) BASE_SCENE_OBJ_PROP(SimpleCharacter2D) FLOAT_PROP(SimpleCharacter2D, trans.pos.x, 100.0f, "Geometry", "x", "X coordinate of position of a character") FLOAT_PROP(SimpleCharacter2D, trans.pos.y, 100.0f, "Geometry", "y", "X coordinate of position of a character") SCENEOBJECT_PROP(SimpleCharacter2D, vjoy_ref, "Prop", "VJoy") STRING_PROP(SimpleCharacter2D, asset_name, "", "Prop", "Asset") FLOAT_PROP(SimpleCharacter2D, speed, 120.0f, "Prop", "Speed", "Speed of a charater") BOOL_PROP(SimpleCharacter2D, is_enemy, true, "Prop", "IsEnemy", "Definig if charcter is a enemy") INT_PROP(SimpleCharacter2D, max_hp, 100, "Prop", "HP", "Max Health of a character") FLOAT_PROP(SimpleCharacter2D, floor_width, 500.0f, "Prop", "FloorWidth", "Width of a level floor") FLOAT_PROP(SimpleCharacter2D, floor_height, 200.0f, "Prop", "FloorHeight", "Higth of a level floor") META_DATA_DESC_END() void SimpleCharacter2D::BindClassToScript() { BIND_TYPE_TO_SCRIPT(SimpleCharacter2D, "SimpleCharacter2D") core.scripts.RegisterObjectProperty(script_class_name, "int cur_hp", memberOFFSET(SimpleCharacter2D, cur_hp), "Health of acharacter"); core.scripts.RegisterObjectMethod(script_class_name, "void Reset()", WRAP_MFN(SimpleCharacter2D, Reset), "Setting postion to initial position on start scene"); core.scripts.RegisterObjectMethod(script_class_name, "void SetAnimGraph(string&in)", WRAP_MFN(SimpleCharacter2D, SetAnimGraph), "Setting anim graph asset by name"); } void SimpleCharacter2D::Init() { trans.offset.y = 1.0f; Tasks(false)->AddTask(10, this, (Object::Delegate)&SimpleCharacter2D::Update); RenderTasks(false)->AddTask(ExecuteLevels::Sprites, this, (Object::Delegate)&SimpleCharacter2D::Draw); GetScene()->AddToGroup(this, "SimpleCharacter2D"); } void SimpleCharacter2D::ApplyProperties() { SetAnimGraph(asset_name); vjoy = (VirtualJoystick*)vjoy_ref.object; } void SimpleCharacter2D::Update(float dt) { if (state != Active) { return; } if (!asset || !graph_instance.cur_node) { return; } if (GetScene()->Playing()) { if (arraive > 0.0f) { arraive -= dt; if (arraive < 0.0f) { arraive = -1.0f; graph_instance.ActivateLink("Idle"); } else { return; } } if (!target) { target = FindTarget(); } if (!is_enemy) { ControlPlayer(dt); } else { ControlEnemy(dt); } if (cur_time_to_kick > 0.0f) { cur_time_to_kick -= dt; if (cur_time_to_kick < 0.0f) { cur_time_to_kick = -1.0f; Vector2 kick_pos = trans.pos; kick_pos.x += flipped ? -120.0f : 120.0f; MakeHit(kick_pos, 25); if (target && target->cur_hp == 0) { target = nullptr; } } } if (target && allow_move) { flipped = trans.pos.x > target->trans.pos.x; } if (dir_horz == 0 && dir_vert == 0) { if (allow_move) { graph_instance.ActivateLink("Idle"); allow_move = false; } } else { trans.pos.x += dt * speed * dir_horz; trans.pos.x = fmax(-floor_width, trans.pos.x); trans.pos.x = fmin( floor_width, trans.pos.x); trans.pos.y += dt * speed * 0.75f * dir_vert; trans.pos.y = fmax(floor_margin.x, trans.pos.y); trans.pos.y = fmin(floor_margin.y, trans.pos.y); } if (resp_time > 0.0f) { resp_time -= dt; if (resp_time < 0.0f) { resp_time = -1.0f; Respawn(); } } if (vanish_time > 0.0f) { vanish_time -= dt; if (vanish_time < 0.0f) { vanish_time = -1.0f; resp_time = 3.0f; } } if (death_fly > 0.0f) { death_fly -= dt; trans.pos.x += dt * (flipped ? 380.0f : -380.0f); if (death_fly < 0.0f) { death_fly = -1.0f; vanish_time = 2.0f; } } } } void SimpleCharacter2D::Draw(float dt) { if (GetState() == Invisible) { return; } if (!asset || !graph_instance.cur_node) { return; } if (resp_time > 0.0f || (vanish_time > 0.0f && ((int)(vanish_time / 0.1f) % 2 == 0))) { return; } trans.size = graph_instance.cur_node->asset->trans.size; trans.depth = 0.74f - ((trans.pos.y - floor_margin.x) / floor_height) * 0.5f; graph_instance.state.horz_flipped = flipped; trans.BuildMatrices(); if (arraive > 0.0f) { trans.mat_global.Pos().y -= 1024.0f * arraive; } if (GetState() == Active) { graph_instance.Update(GetName(), 0, Script(), nullptr, dt); } Sprite::Draw(&trans, COLOR_WHITE, &graph_instance.cur_node->asset->sprite, &graph_instance.state, true, false); } SimpleCharacter2D* SimpleCharacter2D::FindTarget() { vector<Scene::Group*> out_group; GetScene()->GetGroup(out_group, "SimpleCharacter2D"); for (auto group : out_group) { for (auto& object : group->objects) { SimpleCharacter2D* chraracter = (SimpleCharacter2D*)object; if (chraracter->cur_hp <= 0) { continue; } if (chraracter->is_enemy == !is_enemy) { return chraracter; } } } return nullptr; } void SimpleCharacter2D::ControlPlayer(float dt) { dir_horz = 0; if (core.controls.DebugKeyPressed("KEY_A", Controls::Active) || (vjoy && vjoy->stick_delta.x < 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink(target ? "WalkBack" : "Walk"); } if (allow_move) { if (!target) { flipped = true; } dir_horz = -1; } } else if (core.controls.DebugKeyPressed("KEY_D", Controls::Active) || (vjoy && vjoy->stick_delta.x > 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { if (!target) { flipped = false; } dir_horz = 1; } } dir_vert = 0; if (core.controls.DebugKeyPressed("KEY_W", Controls::Active) || (vjoy && vjoy->stick_delta.y < 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("WalkBack"); } if (allow_move) { dir_vert = -1; } } else if (core.controls.DebugKeyPressed("KEY_S", Controls::Active) || (vjoy && vjoy->stick_delta.y > 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_vert = 1; } } if (core.controls.DebugKeyPressed("KEY_E") || (vjoy && vjoy->button_a_pressed == 2)) { if (graph_instance.ActivateLink("LegKick1")) { cur_time_to_kick = 0.45f; allow_move = false; } } if (core.controls.DebugKeyPressed("KEY_R") || (vjoy && vjoy->button_b_pressed == 2)) { if (graph_instance.ActivateLink("LegKick2")) { cur_time_to_kick = 0.55f; allow_move = false; } } } void SimpleCharacter2D::ControlEnemy(float dt) { if (target) { //if (next_kick == -1) { //next_kick } if (fabs(trans.pos.x - target->trans.pos.x) > 200.0f) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_horz = (trans.pos.x - target->trans.pos.x) > 0.0f ? -1 : 1; } } else { dir_horz = 0; } if (fabs(trans.pos.x - target->trans.pos.x) < 500.0f && fabs(trans.pos.y - target->trans.pos.y) > 5.0f) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_vert = (trans.pos.y - target->trans.pos.y) > 0.0f ? -1 : 1; } } else { dir_vert = 0; } if (fabs(trans.pos.x - target->trans.pos.x) < 200.0f && fabs(trans.pos.y - target->trans.pos.y) < 5.0f) { cur_time_2_kuck += dt; if (cur_time_2_kuck > time_2_kick) { cur_time_2_kuck = 0.0f; bool sec_kick = Math::Rand() > 0.5; if (graph_instance.ActivateLink(sec_kick ? "LegKick1" : "LegKick2")) { cur_time_to_kick = sec_kick ? 0.55f : 0.85f; flipped = trans.pos.x > target->trans.pos.x; allow_move = false; } } } else { cur_time_2_kuck = 0.0f; } } } void SimpleCharacter2D::MakeHit(Vector2 pos, int damage) { vector<Scene::Group*> out_group; GetScene()->GetGroup(out_group, "SimpleCharacter2D"); for (auto group : out_group) { for (auto& object : group->objects) { SimpleCharacter2D* chraracter = (SimpleCharacter2D*)object; if (chraracter->is_enemy == !is_enemy && chraracter->cur_hp > 0) { if ((chraracter->trans.pos.x - 85.0f) < pos.x && pos.x < (chraracter->trans.pos.x + 85.0f) && fabs(chraracter->trans.pos.y - pos.y) < 15.0f) { if (chraracter->graph_instance.ActivateLink("Hit")) { chraracter->cur_hp -= damage; chraracter->cur_time_to_kick = -1.0f; chraracter->allow_move = false; if (chraracter->cur_hp <= 0) { chraracter->cur_hp = 0; chraracter->target = nullptr; chraracter->graph_instance.GotoNode("Death"); chraracter->death_fly = 0.75f; } } } } } } } void SimpleCharacter2D::Respawn() { cur_hp = max_hp; arraive = 1.0f; graph_instance.GotoNode("Resp"); } void SimpleCharacter2D::Reset() { trans.pos = init_pos; cur_hp = max_hp; allow_move = false; flipped = false; dir_horz = 0; dir_vert = 0; time_2_kick = 0.5f; cur_time_2_kuck = 0; cur_time_to_kick = -1.0f; death_fly = -1.0f; vanish_time = -1.0f; arraive = -1.0f; resp_time = -1.0f; next_kick = -1; graph_instance.Reset(); if (is_enemy) { Respawn(); } } void SimpleCharacter2D::SetAnimGraph(string& graph) { asset = (SpriteGraphAsset*)GetScene()->FindInGroup("SpriteGraphAsset", graph.c_str()); if (asset) { asset->PrepareInstance(&graph_instance); if (graph_instance.cur_node) { floor_margin.y = 1024.0f; floor_margin.x = floor_margin.y - floor_height; } } } bool SimpleCharacter2D::Play() { init_pos = trans.pos; Reset(); return true; } #ifdef EDITOR void SimpleCharacter2D::SetEditMode(bool ed) { SceneObject::SetEditMode(ed); Gizmo::inst->SetTrans2D(Gizmo::Transform2D(trans), Gizmo::trans_2d_move); } #endif
20.095723
165
0.643458
ENgineE777
488734c888c59e686a0da790371c263afdcbcd0d
2,710
cpp
C++
src/configuration/expr/compute_ternary.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/configuration/expr/compute_ternary.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/configuration/expr/compute_ternary.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin library #include "lapin_private.h" bool expr_compute_ternary(Expression &exp, bool dry, SmallConf *root, SmallConf *local, SmallConf *artif, SmallConf *param) { if (exp.is_const) return (true); if (exp.operand.size() != 3) scream_error_if (return (false), BE_BAD_ADDRESS, "Incomplete ternary on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (exp.operand[1]->optor != Expression::BEO_TERNARY) scream_error_if (return (false), BE_BAD_ADDRESS, "First ternary token must be '?' on line %s:%d", "configuration,syntax", exp.file.c_str(),exp.line); if (exp.operand[2]->optor != Expression::BEO_TERNARY_ELSE) scream_error_if (return (false), BE_BAD_ADDRESS, "Second ternary token must be ':' on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (dry) return (true); Expression &x = *exp.operand[0]; Expression *y; SmallConf *ope; bool cnst; int tmp; cnst = true; if (x.optor_family == -1) {} else if (x.optor_family == Expression::LAST_OPERATOR_FAMILY) { if (expr_compute_function_call(x, dry, root, local, artif, param) == false) return (false); } else if (gl_expr_computation[x.optor_family] (x, dry, root, local, artif, param) == false) return (false); ope = &x.val; if (ope->last_type == SmallConf::RAWSTRING) { cnst = false; if ((ope = expr_get_variable (*ope, dry, root, local, artif, param)) == NULL) scream_error_if (return (false), BE_BAD_ADDRESS, "Undefined variable or unresolvable address %s " "from context %s on line %s:%d", "configuration,syntax", x.val.original_value.c_str(), artif->address.c_str(), exp.file.c_str(), exp.line); } else if (x.is_const == false) cnst = false; if (ope->GetInt(&tmp) == false) scream_error_if (return (false), BE_TYPE_ERROR, "Cannot evaluate the truthness of the main ternary operand on line %s:%d", "configuration,syntax", exp.file.c_str(), exp.line); if (tmp) y = exp.operand[1]; else y = exp.operand[2]; if (y->optor_family == -1) {} else if (y->optor_family == Expression::LAST_OPERATOR_FAMILY) { if (expr_compute_function_call(*y, dry, root, local, artif, param) == false) return (false); } else if (gl_expr_computation[y->optor_family] (*y, dry, root, local, artif, param) == false) return (false); exp.val = y->val; if (cnst) exp.is_const = true; return (true); }
26.31068
82
0.61107
Damdoshi
48895b1ac57feb1f34ce894c2616f0f748393102
3,701
hpp
C++
src/ndnSIM/NFD/daemon/table/cs-entry.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2021-09-07T04:12:15.000Z
2021-09-07T04:12:15.000Z
src/ndnSIM/NFD/daemon/table/cs-entry.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
null
null
null
src/ndnSIM/NFD/daemon/table/cs-entry.hpp
NDNLink/NDN-Chord
cfabf8f56eea2c4ba47052ce145a939ebdc21e57
[ "MIT" ]
1
2020-07-15T06:21:03.000Z
2020-07-15T06:21:03.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2014-2017, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis. * * This file is part of NFD (Named Data Networking Forwarding Daemon). * See AUTHORS.md for complete list of NFD authors and contributors. * * NFD is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NFD_DAEMON_TABLE_CS_ENTRY_HPP #define NFD_DAEMON_TABLE_CS_ENTRY_HPP #include "core/common.hpp" namespace nfd { namespace cs { /** \brief represents a base class for CS entry */ class Entry { public: // exposed through ContentStore enumeration /** \return the stored Data * \pre hasData() */ const Data& getData() const { BOOST_ASSERT(this->hasData()); return *m_data; } /** \return Name of the stored Data * \pre hasData() */ const Name& getName() const { BOOST_ASSERT(this->hasData()); return m_data->getName(); } /** \return full name (including implicit digest) of the stored Data * \pre hasData() */ const Name& getFullName() const { BOOST_ASSERT(this->hasData()); return m_data->getFullName(); } /** \return whether the stored Data is unsolicited * \pre hasData() */ bool isUnsolicited() const { BOOST_ASSERT(this->hasData()); return m_isUnsolicited; } /** \return the absolute time when the stored Data becomes stale * \note if the returned TimePoint is in the past, the Data is stale * \pre hasData() */ const time::steady_clock::TimePoint& getStaleTime() const { BOOST_ASSERT(this->hasData()); return m_staleTime; } /** \brief checks if the stored Data is stale now * \pre hasData() */ bool isStale() const; /** \brief determines whether Interest can be satisified by the stored Data * \note ChildSelector is not considered * \pre hasData() */ bool canSatisfy(const Interest& interest) const; public: // used by generic ContentStore implementation /** \return true if a Data packet is stored */ bool hasData() const { return m_data != nullptr; } /** \brief replaces the stored Data */ void setData(shared_ptr<const Data> data, bool isUnsolicited); /** \brief replaces the stored Data */ void setData(const Data& data, bool isUnsolicited) { this->setData(data.shared_from_this(), isUnsolicited); } /** \brief refreshes stale time relative to current time */ void updateStaleTime(); /** \brief clears the entry * \post !hasData() */ void reset(); private: shared_ptr<const Data> m_data; bool m_isUnsolicited; time::steady_clock::TimePoint m_staleTime; }; } // namespace cs } // namespace nfd #endif // NFD_DAEMON_TABLE_CS_ENTRY_HPP
25.349315
83
0.653877
NDNLink
488a5f636b595d52badc25017d05d9afeee5bdc5
137
hpp
C++
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/headers/testPattern.hpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
/**/ #include "pattern.hpp" class TestPattern : public Pattern { public: TestPattern(); Color patternAt(Tuple); };
13.7
36
0.59854
HxHexa
488eb4ea9eb47e3e7ad94b15d5a0b24006881669
438
cpp
C++
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
1
2018-11-21T07:36:16.000Z
2018-11-21T07:36:16.000Z
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
UVa/10370 - Above Average.cpp
geniustanley/problem-solving
2b83c5c8197fa8fe2277367027b392a2911d4a28
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int main(void) { int T, n, sum, ans; int num[1005]; double average; scanf("%d", &T); while(T--) { scanf("%d", &n); sum = 0; ans = 0; for(int i = 0; i < n; i++) { scanf("%d", &num[i]); sum += num[i]; } average = (double)sum/n; for(int i = 0; i < n; i++) if(average < num[i]) ans++; printf("%.3lf%%\n", (double)ans/n*100); } return 0; }
14.129032
42
0.429224
geniustanley
4890b57d04bd8cde59c176d6584e2822b2f0ae7c
1,497
hpp
C++
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
186
2015-06-20T00:38:04.000Z
2022-02-19T16:08:33.000Z
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
17
2015-07-09T10:23:02.000Z
2022-01-19T17:34:44.000Z
lib/luwra/types/pushable.hpp
jonmortiboy/luwra
71264e49103f8633ee5225dab1f4567a7f3672a2
[ "BSD-3-Clause" ]
21
2015-07-05T12:59:48.000Z
2020-07-20T18:50:43.000Z
/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_TYPES_PUSHABLE_H_ #define LUWRA_TYPES_PUSHABLE_H_ #include "../common.hpp" #include "../values.hpp" #include "../stack.hpp" #include <utility> #include <memory> LUWRA_NS_BEGIN namespace internal { struct PushableI { virtual void push(State* state) const = 0; virtual ~PushableI() {} }; template <typename Type> struct PushableT: virtual PushableI { Type value; template <typename Source> inline PushableT(Source&& value): value(std::forward<Source>(value)) {} virtual void push(State* state) const { luwra::push(state, value); } virtual ~PushableT() {} }; using SharedPushableImpl = std::shared_ptr<PushableI>; } /// Arbitrary pushable value /// /// This class is implicitly constructible using any type. One can use this class with STL /// containers in order to achieve pushable mixed-type containers. struct Pushable { const internal::SharedPushableImpl interface; template <typename Type> inline Pushable(Type&& value): interface(new internal::PushableT<Type>(std::forward<Type>(value))) {} // Used in ordered STL containers inline bool operator <(const Pushable& other) const { return interface < other.interface; } }; /// Enables pushing for `Pushables` template <> struct Value<Pushable> { static inline void push(State* state, const Pushable& value) { value.interface->push(state); } }; LUWRA_NS_END #endif
19.697368
90
0.713427
jonmortiboy
48930bdb106b028921a0afe23bcd10f003b6993c
541
cpp
C++
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
src/glCompact/threadContextGroup_.cpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
#include "glCompact/threadContextGroup_.hpp" namespace glCompact { #ifdef GLCOMPACT_MULTIPLE_CONTEXT_GROUP thread_local ContextGroup_* __restrict threadContextGroup_; #else static char contextGroupMem[sizeof(ContextGroup_)] alignas(ContextGroup_); ContextGroup_*const __restrict threadContextGroup_ = reinterpret_cast<ContextGroup_*>(&contextGroupMem); bool threadContextGroupConstructed_ = false; #endif }
45.083333
125
0.64695
PixelOfDeath
48959e689b285106da57c3e8120b39781108404b
51,345
cpp
C++
third_party/WebKit/Source/core/paint/BoxPainter.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
third_party/WebKit/Source/core/paint/BoxPainter.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
third_party/WebKit/Source/core/paint/BoxPainter.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/paint/BoxPainter.h" #include "core/HTMLNames.h" #include "core/frame/Settings.h" #include "core/html/HTMLFrameOwnerElement.h" #include "core/layout/ImageQualityController.h" #include "core/layout/LayoutBox.h" #include "core/layout/LayoutBoxModelObject.h" #include "core/layout/LayoutObject.h" #include "core/layout/LayoutTable.h" #include "core/layout/LayoutTheme.h" #include "core/layout/LayoutView.h" #include "core/layout/compositing/CompositedDeprecatedPaintLayerMapping.h" #include "core/style/BorderEdge.h" #include "core/style/ShadowList.h" #include "core/paint/BackgroundImageGeometry.h" #include "core/paint/BoxBorderPainter.h" #include "core/paint/BoxDecorationData.h" #include "core/paint/DeprecatedPaintLayer.h" #include "core/paint/LayoutObjectDrawingRecorder.h" #include "core/paint/NinePieceImagePainter.h" #include "core/paint/PaintInfo.h" #include "core/paint/RoundedInnerRectClipper.h" #include "core/paint/ThemePainter.h" #include "platform/LengthFunctions.h" #include "platform/geometry/LayoutPoint.h" #include "platform/geometry/LayoutRectOutsets.h" #include "platform/graphics/GraphicsContextStateSaver.h" #include "platform/graphics/paint/CompositingDisplayItem.h" #include "wtf/Optional.h" namespace blink { void BoxPainter::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) { LayoutPoint adjustedPaintOffset = paintOffset + m_layoutBox.location(); // default implementation. Just pass paint through to the children PaintInfo childInfo(paintInfo); childInfo.updatePaintingRootForChildren(&m_layoutBox); for (LayoutObject* child = m_layoutBox.slowFirstChild(); child; child = child->nextSibling()) child->paint(childInfo, adjustedPaintOffset); } void BoxPainter::paintBoxDecorationBackground(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) { if (!paintInfo.shouldPaintWithinRoot(&m_layoutBox)) return; LayoutRect paintRect = m_layoutBox.borderBoxRect(); paintRect.moveBy(paintOffset); paintBoxDecorationBackgroundWithRect(paintInfo, paintOffset, paintRect); } LayoutRect BoxPainter::boundsForDrawingRecorder(const LayoutPoint& paintOffset) { if (!RuntimeEnabledFeatures::slimmingPaintEnabled()) return LayoutRect(); // Use the visual overflow rect here, because it will include overflow introduced by the theme. LayoutRect bounds = m_layoutBox.visualOverflowRect(); bounds.moveBy(paintOffset); return LayoutRect(pixelSnappedIntRect(bounds)); } namespace { bool bleedAvoidanceIsClipping(BackgroundBleedAvoidance bleedAvoidance) { return bleedAvoidance == BackgroundBleedClipOnly || bleedAvoidance == BackgroundBleedClipLayer; } } // anonymous namespace void BoxPainter::paintBoxDecorationBackgroundWithRect(const PaintInfo& paintInfo, const LayoutPoint& paintOffset, const LayoutRect& paintRect) { const ComputedStyle& style = m_layoutBox.styleRef(); // FIXME: For now we don't have notification on media buffered range change from media player // and miss paint invalidation on buffered range change. crbug.com/484288. Optional<DisplayItemCacheSkipper> cacheSkipper; if (style.appearance() == MediaSliderPart) cacheSkipper.emplace(*paintInfo.context); if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(*paintInfo.context, m_layoutBox, DisplayItem::BoxDecorationBackground)) return; LayoutObjectDrawingRecorder recorder(*paintInfo.context, m_layoutBox, DisplayItem::BoxDecorationBackground, boundsForDrawingRecorder(paintOffset)); BoxDecorationData boxDecorationData(m_layoutBox); // FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have // custom shadows of their own. if (!m_layoutBox.boxShadowShouldBeAppliedToBackground(boxDecorationData.bleedAvoidance)) paintBoxShadow(paintInfo, paintRect, style, Normal); GraphicsContextStateSaver stateSaver(*paintInfo.context, false); if (bleedAvoidanceIsClipping(boxDecorationData.bleedAvoidance)) { stateSaver.save(); FloatRoundedRect border = style.getRoundedBorderFor(paintRect); paintInfo.context->clipRoundedRect(border); if (boxDecorationData.bleedAvoidance == BackgroundBleedClipLayer) paintInfo.context->beginLayer(); } // If we have a native theme appearance, paint that before painting our background. // The theme will tell us whether or not we should also paint the CSS background. IntRect snappedPaintRect(pixelSnappedIntRect(paintRect)); ThemePainter& themePainter = LayoutTheme::theme().painter(); bool themePainted = boxDecorationData.hasAppearance && !themePainter.paint(&m_layoutBox, paintInfo, snappedPaintRect); if (!themePainted) { paintBackground(paintInfo, paintRect, boxDecorationData.backgroundColor, boxDecorationData.bleedAvoidance); if (boxDecorationData.hasAppearance) themePainter.paintDecorations(&m_layoutBox, paintInfo, snappedPaintRect); } paintBoxShadow(paintInfo, paintRect, style, Inset); // The theme will tell us whether or not we should also paint the CSS border. if (boxDecorationData.hasBorderDecoration && (!boxDecorationData.hasAppearance || (!themePainted && LayoutTheme::theme().painter().paintBorderOnly(&m_layoutBox, paintInfo, snappedPaintRect))) && !(m_layoutBox.isTable() && toLayoutTable(&m_layoutBox)->collapseBorders())) paintBorder(m_layoutBox, paintInfo, paintRect, style, boxDecorationData.bleedAvoidance); if (boxDecorationData.bleedAvoidance == BackgroundBleedClipLayer) paintInfo.context->endLayer(); } void BoxPainter::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, const Color& backgroundColor, BackgroundBleedAvoidance bleedAvoidance) { if (m_layoutBox.isDocumentElement()) return; if (m_layoutBox.backgroundStolenForBeingBody()) return; if (m_layoutBox.boxDecorationBackgroundIsKnownToBeObscured()) return; paintFillLayers(paintInfo, backgroundColor, m_layoutBox.style()->backgroundLayers(), paintRect, bleedAvoidance); } static bool isFillLayerOpaque(const FillLayer& layer, const LayoutObject& imageClient) { return layer.hasOpaqueImage(&imageClient) && layer.image()->canRender(imageClient, imageClient.style()->effectiveZoom()) && !layer.image()->imageSize(&imageClient, imageClient.style()->effectiveZoom()).isEmpty() && layer.hasRepeatXY(); } bool BoxPainter::calculateFillLayerOcclusionCulling(FillLayerOcclusionOutputList &reversedPaintList, const FillLayer& fillLayer) { bool isNonAssociative = false; for (auto currentLayer = &fillLayer; currentLayer; currentLayer = currentLayer->next()) { reversedPaintList.append(currentLayer); // Stop traversal when an opaque layer is encountered. // FIXME : It would be possible for the following occlusion culling test to be more aggressive // on layers with no repeat by testing whether the image covers the layout rect. // Testing that here would imply duplicating a lot of calculations that are currently done in // LayoutBoxModelObject::paintFillLayerExtended. A more efficient solution might be to move // the layer recursion into paintFillLayerExtended, or to compute the layer geometry here // and pass it down. // TODO(trchen): Need to check compositing mode as well. if (currentLayer->blendMode() != WebBlendModeNormal) isNonAssociative = true; // TODO(trchen): A fill layer cannot paint if the calculated tile size is empty. // This occlusion check can be wrong. if (currentLayer->clipOccludesNextLayers() && isFillLayerOpaque(*currentLayer, m_layoutBox)) { if (currentLayer->clip() == BorderFillBox) isNonAssociative = false; break; } } return isNonAssociative; } void BoxPainter::paintFillLayers(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance, SkXfermode::Mode op, LayoutObject* backgroundObject) { // TODO(trchen): Box shadow optimization and background color are concepts that only // apply to background layers. Ideally we should refactor those out of paintFillLayer. FillLayerOcclusionOutputList reversedPaintList; bool shouldDrawBackgroundInSeparateBuffer = false; if (!m_layoutBox.boxShadowShouldBeAppliedToBackground(bleedAvoidance)) { shouldDrawBackgroundInSeparateBuffer = calculateFillLayerOcclusionCulling(reversedPaintList, fillLayer); } else { // If we are responsible for painting box shadow, don't perform fill layer culling. // TODO(trchen): In theory we only need to make sure the last layer has border box clipping // and make it paint the box shadow. Investigate optimization opportunity later. for (auto currentLayer = &fillLayer; currentLayer; currentLayer = currentLayer->next()) { reversedPaintList.append(currentLayer); if (currentLayer->composite() != CompositeSourceOver || currentLayer->blendMode() != WebBlendModeNormal) shouldDrawBackgroundInSeparateBuffer = true; } } // TODO(trchen): We can optimize out isolation group if we have a non-transparent // background color and the bottom layer encloses all other layers. GraphicsContext* context = paintInfo.context; if (!context) shouldDrawBackgroundInSeparateBuffer = false; if (shouldDrawBackgroundInSeparateBuffer) context->beginLayer(); for (auto it = reversedPaintList.rbegin(); it != reversedPaintList.rend(); ++it) paintFillLayer(paintInfo, c, **it, rect, bleedAvoidance, op, backgroundObject); if (shouldDrawBackgroundInSeparateBuffer) context->endLayer(); } void BoxPainter::paintFillLayer(const PaintInfo& paintInfo, const Color& c, const FillLayer& fillLayer, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance, SkXfermode::Mode op, LayoutObject* backgroundObject) { BoxPainter::paintFillLayerExtended(m_layoutBox, paintInfo, c, fillLayer, rect, bleedAvoidance, 0, LayoutSize(), op, backgroundObject); } void BoxPainter::applyBoxShadowForBackground(GraphicsContext* context, LayoutObject& obj) { const ShadowList* shadowList = obj.style()->boxShadow(); ASSERT(shadowList); for (size_t i = shadowList->shadows().size(); i--; ) { const ShadowData& boxShadow = shadowList->shadows()[i]; if (boxShadow.style() != Normal) continue; FloatSize shadowOffset(boxShadow.x(), boxShadow.y()); context->setShadow(shadowOffset, boxShadow.blur(), boxShadow.color().resolve(obj.resolveColor(CSSPropertyColor)), DrawLooperBuilder::ShadowRespectsTransforms, DrawLooperBuilder::ShadowIgnoresAlpha); return; } } FloatRoundedRect BoxPainter::getBackgroundRoundedRect(LayoutObject& obj, const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) { FloatRoundedRect border = obj.style()->getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge); if (box && (box->nextLineBox() || box->prevLineBox())) { FloatRoundedRect segmentBorder = obj.style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge); border.setRadii(segmentBorder.radii()); } return border; } FloatRoundedRect BoxPainter::backgroundRoundedRectAdjustedForBleedAvoidance(LayoutObject& obj, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) { if (bleedAvoidance == BackgroundBleedShrinkBackground) { // Inset the background rect by a "safe" amount: 1/2 border-width for opaque border styles, // 1/6 border-width for double borders. // TODO(fmalita): we should be able to fold these parameters into BoxBorderInfo or // BoxDecorationData and avoid calling getBorderEdgeInfo redundantly here. BorderEdge edges[4]; obj.style()->getBorderEdgeInfo(edges, includeLogicalLeftEdge, includeLogicalRightEdge); // Use the most conservative inset to avoid mixed-style corner issues. float fractionalInset = 1.0f / 2; for (auto& edge : edges) { if (edge.borderStyle() == DOUBLE) { fractionalInset = 1.0f / 6; break; } } FloatRectOutsets insets( -fractionalInset * edges[BSTop].width, -fractionalInset * edges[BSRight].width, -fractionalInset * edges[BSBottom].width, -fractionalInset * edges[BSLeft].width); FloatRoundedRect backgroundRoundedRect = getBackgroundRoundedRect(obj, borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge); FloatRect insetRect(backgroundRoundedRect.rect()); insetRect.expand(insets); FloatRoundedRect::Radii insetRadii(backgroundRoundedRect.radii()); insetRadii.shrink(-insets.top(), -insets.bottom(), -insets.left(), -insets.right()); return FloatRoundedRect(insetRect, insetRadii); } return getBackgroundRoundedRect(obj, borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge); } void BoxPainter::paintFillLayerExtended(LayoutBoxModelObject& obj, const PaintInfo& paintInfo, const Color& color, const FillLayer& bgLayer, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, SkXfermode::Mode op, LayoutObject* backgroundObject) { GraphicsContext* context = paintInfo.context; if (rect.isEmpty()) return; bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true; bool includeRightEdge = box ? box->includeLogicalRightEdge() : true; bool hasRoundedBorder = obj.style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge); bool clippedWithLocalScrolling = obj.hasOverflowClip() && bgLayer.attachment() == LocalBackgroundAttachment; bool isBorderFill = bgLayer.clip() == BorderFillBox; bool isBottomLayer = !bgLayer.next(); Color bgColor = color; StyleImage* bgImage = bgLayer.image(); bool forceBackgroundToWhite = shouldForceWhiteBackgroundForPrintEconomy(obj.styleRef(), obj.document()); // When printing backgrounds is disabled or using economy mode, // change existing background colors and images to a solid white background. // If there's no bg color or image, leave it untouched to avoid affecting transparency. // We don't try to avoid loading the background images, because this style flag is only set // when printing, and at that point we've already loaded the background images anyway. (To avoid // loading the background images we'd have to do this check when applying styles rather than // while layout.) if (forceBackgroundToWhite) { // Note that we can't reuse this variable below because the bgColor might be changed bool shouldPaintBackgroundColor = isBottomLayer && bgColor.alpha(); if (bgImage || shouldPaintBackgroundColor) { bgColor = Color::white; bgImage = nullptr; } } // Fast path for drawing simple color backgrounds. if (!clippedWithLocalScrolling && !bgImage && isBorderFill && isBottomLayer) { if (!bgColor.alpha()) return; bool boxShadowShouldBeAppliedToBackground = obj.boxShadowShouldBeAppliedToBackground(bleedAvoidance, box); GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground); if (boxShadowShouldBeAppliedToBackground) BoxPainter::applyBoxShadowForBackground(context, obj); if (hasRoundedBorder && !bleedAvoidanceIsClipping(bleedAvoidance)) { FloatRoundedRect border = backgroundRoundedRectAdjustedForBleedAvoidance(obj, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge); if (border.isRenderable()) { context->fillRoundedRect(border, bgColor); } else { RoundedInnerRectClipper clipper(obj, paintInfo, rect, border, ApplyToContext); context->fillRect(border.rect(), bgColor); } } else { context->fillRect(pixelSnappedIntRect(rect), bgColor); } return; } // BorderFillBox radius clipping is taken care of by BackgroundBleedClip{Only,Layer} bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidanceIsClipping(bleedAvoidance)); Optional<RoundedInnerRectClipper> clipToBorder; if (clipToBorderRadius) { FloatRoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(obj, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(obj, rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge); // Clip to the padding or content boxes as necessary. if (bgLayer.clip() == ContentFillBox) { border = obj.style()->getRoundedInnerBorderFor(LayoutRect(border.rect()), LayoutRectOutsets( -(obj.paddingTop() + obj.borderTop()), -(obj.paddingRight() + obj.borderRight()), -(obj.paddingBottom() + obj.borderBottom()), -(obj.paddingLeft() + obj.borderLeft())), includeLeftEdge, includeRightEdge); } else if (bgLayer.clip() == PaddingFillBox) { border = obj.style()->getRoundedInnerBorderFor(LayoutRect(border.rect()), includeLeftEdge, includeRightEdge); } clipToBorder.emplace(obj, paintInfo, rect, border, ApplyToContext); } int bLeft = includeLeftEdge ? obj.borderLeft() : 0; int bRight = includeRightEdge ? obj.borderRight() : 0; LayoutUnit pLeft = includeLeftEdge ? obj.paddingLeft() : LayoutUnit(); LayoutUnit pRight = includeRightEdge ? obj.paddingRight() : LayoutUnit(); GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling); LayoutRect scrolledPaintRect = rect; if (clippedWithLocalScrolling) { // Clip to the overflow area. LayoutBox* thisBox = toLayoutBox(&obj); context->clip(thisBox->overflowClipRect(rect.location())); // Adjust the paint rect to reflect a scrolled content box with borders at the ends. IntSize offset = thisBox->scrolledContentOffset(); scrolledPaintRect.move(-offset); scrolledPaintRect.setWidth(bLeft + thisBox->scrollWidth() + bRight); scrolledPaintRect.setHeight(thisBox->borderTop() + thisBox->scrollHeight() + thisBox->borderBottom()); } GraphicsContextStateSaver backgroundClipStateSaver(*context, false); IntRect maskRect; switch (bgLayer.clip()) { case PaddingFillBox: case ContentFillBox: { if (clipToBorderRadius) break; // Clip to the padding or content boxes as necessary. bool includePadding = bgLayer.clip() == ContentFillBox; LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()), scrolledPaintRect.y() + obj.borderTop() + (includePadding ? obj.paddingTop() : LayoutUnit()), scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()), scrolledPaintRect.height() - obj.borderTop() - obj.borderBottom() - (includePadding ? obj.paddingTop() + obj.paddingBottom() : LayoutUnit())); backgroundClipStateSaver.save(); context->clip(clipRect); break; } case TextFillBox: { // First figure out how big the mask has to be. It should be no bigger than what we need // to actually render, so we should intersect the dirty rect with the border box of the background. maskRect = pixelSnappedIntRect(rect); if (!RuntimeEnabledFeatures::slimmingPaintEnabled()) maskRect.intersect(paintInfo.rect); // We draw the background into a separate layer, to be later masked with yet another layer // holding the text content. backgroundClipStateSaver.save(); context->clip(maskRect); context->beginLayer(); break; } case BorderFillBox: break; default: ASSERT_NOT_REACHED(); break; } BackgroundImageGeometry geometry; if (bgImage) calculateBackgroundImageGeometry(obj, paintInfo.paintContainer(), bgLayer, scrolledPaintRect, geometry, backgroundObject); bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(obj, obj.style()->effectiveZoom()); // Paint the color first underneath all images, culled if background image occludes it. // TODO(trchen): In the !bgLayer.hasRepeatXY() case, we could improve the culling test // by verifying whether the background image covers the entire painting area. if (isBottomLayer) { IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect)); bool boxShadowShouldBeAppliedToBackground = obj.boxShadowShouldBeAppliedToBackground(bleedAvoidance, box); bool backgroundImageOccludesBackgroundColor = shouldPaintBackgroundImage && isFillLayerOpaque(bgLayer, obj); if (boxShadowShouldBeAppliedToBackground || !backgroundImageOccludesBackgroundColor) { if (!RuntimeEnabledFeatures::slimmingPaintEnabled() && !boxShadowShouldBeAppliedToBackground) backgroundRect.intersect(paintInfo.rect); GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground); if (boxShadowShouldBeAppliedToBackground) BoxPainter::applyBoxShadowForBackground(context, obj); if (bgColor.alpha()) context->fillRect(backgroundRect, bgColor); } } // no progressive loading of the background image if (shouldPaintBackgroundImage) { if (!geometry.destRect().isEmpty()) { SkXfermode::Mode bgOp = WebCoreCompositeToSkiaComposite(bgLayer.composite(), bgLayer.blendMode()); // if op != SkXfermode::kSrcOver_Mode, a mask is being painted. SkXfermode::Mode compositeOp = op == SkXfermode::kSrcOver_Mode ? bgOp : op; LayoutObject* clientForBackgroundImage = backgroundObject ? backgroundObject : &obj; RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize()); InterpolationQuality interpolationQuality = chooseInterpolationQuality(*clientForBackgroundImage, context, image.get(), &bgLayer, LayoutSize(geometry.tileSize())); if (bgLayer.maskSourceType() == MaskLuminance) context->setColorFilter(ColorFilterLuminanceToAlpha); InterpolationQuality previousInterpolationQuality = context->imageInterpolationQuality(); context->setImageInterpolationQuality(interpolationQuality); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "PaintImage", "data", InspectorPaintImageEvent::data(obj, *bgImage)); context->drawTiledImage(image.get(), geometry.destRect(), geometry.phase(), geometry.tileSize(), compositeOp, geometry.spaceSize()); context->setImageInterpolationQuality(previousInterpolationQuality); } } if (bgLayer.clip() == TextFillBox) { // Create the text mask layer. context->beginLayer(1, SkXfermode::kDstIn_Mode); // Now draw the text into the mask. We do this by painting using a special paint phase that signals to // InlineTextBoxes that they should just add their contents to the clip. PaintInfo info(context, maskRect, PaintPhaseTextClip, PaintBehaviorNormal, 0); if (box) { RootInlineBox& root = box->root(); box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root.lineTop(), root.lineBottom()); } else { // FIXME: this should only have an effect for the line box list within |obj|. Change this to create a LineBoxListPainter directly. LayoutSize localOffset = obj.isBox() ? toLayoutBox(&obj)->locationOffset() : LayoutSize(); obj.paint(info, scrolledPaintRect.location() - localOffset); } context->endLayer(); context->endLayer(); } } void BoxPainter::paintMask(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) { if (!paintInfo.shouldPaintWithinRoot(&m_layoutBox) || m_layoutBox.style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask) return; if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(*paintInfo.context, m_layoutBox, paintInfo.phase)) return; LayoutRect visualOverflowRect(m_layoutBox.visualOverflowRect()); visualOverflowRect.moveBy(paintOffset); LayoutObjectDrawingRecorder recorder(*paintInfo.context, m_layoutBox, paintInfo.phase, visualOverflowRect); LayoutRect paintRect = LayoutRect(paintOffset, m_layoutBox.size()); paintMaskImages(paintInfo, paintRect); } void BoxPainter::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect) { // Figure out if we need to push a transparency layer to render our mask. bool pushTransparencyLayer = false; bool compositedMask = m_layoutBox.hasLayer() && m_layoutBox.layer()->hasCompositedMask(); bool flattenCompositingLayers = m_layoutBox.view()->frameView() && m_layoutBox.view()->frameView()->paintBehavior() & PaintBehaviorFlattenCompositingLayers; bool allMaskImagesLoaded = true; if (!compositedMask || flattenCompositingLayers) { pushTransparencyLayer = true; StyleImage* maskBoxImage = m_layoutBox.style()->maskBoxImage().image(); const FillLayer& maskLayers = m_layoutBox.style()->maskLayers(); // Don't render a masked element until all the mask images have loaded, to prevent a flash of unmasked content. if (maskBoxImage) allMaskImagesLoaded &= maskBoxImage->isLoaded(); allMaskImagesLoaded &= maskLayers.imagesAreLoaded(); paintInfo.context->beginLayer(1, SkXfermode::kDstIn_Mode); } if (allMaskImagesLoaded) { paintFillLayers(paintInfo, Color::transparent, m_layoutBox.style()->maskLayers(), paintRect); paintNinePieceImage(m_layoutBox, paintInfo.context, paintRect, m_layoutBox.styleRef(), m_layoutBox.style()->maskBoxImage()); } if (pushTransparencyLayer) paintInfo.context->endLayer(); } void BoxPainter::paintClippingMask(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) { ASSERT(paintInfo.phase == PaintPhaseClippingMask); if (!paintInfo.shouldPaintWithinRoot(&m_layoutBox) || m_layoutBox.style()->visibility() != VISIBLE) return; if (!m_layoutBox.layer() || m_layoutBox.layer()->compositingState() != PaintsIntoOwnBacking) return; if (LayoutObjectDrawingRecorder::useCachedDrawingIfPossible(*paintInfo.context, m_layoutBox, paintInfo.phase)) return; IntRect paintRect = pixelSnappedIntRect(LayoutRect(paintOffset, m_layoutBox.size())); LayoutObjectDrawingRecorder drawingRecorder(*paintInfo.context, m_layoutBox, paintInfo.phase, paintRect); paintInfo.context->fillRect(paintRect, Color::black); } // Return the amount of space to leave between image tiles for the background-repeat: space property. static inline int getSpaceBetweenImageTiles(int areaSize, int tileSize) { int numberOfTiles = areaSize / tileSize; int space = -1; if (numberOfTiles > 1) { // Spec doesn't specify rounding, so use the same method as for background-repeat: round. space = lroundf((areaSize - numberOfTiles * tileSize) / (float)(numberOfTiles - 1)); } return space; } void BoxPainter::calculateBackgroundImageGeometry(LayoutBoxModelObject& obj, const LayoutBoxModelObject* paintContainer, const FillLayer& fillLayer, const LayoutRect& paintRect, BackgroundImageGeometry& geometry, LayoutObject* backgroundObject) { LayoutUnit left = 0; LayoutUnit top = 0; IntSize positioningAreaSize; IntRect snappedPaintRect = pixelSnappedIntRect(paintRect); bool isLayoutView = obj.isLayoutView(); const LayoutBox* rootBox = nullptr; if (isLayoutView) { // It is only possible reach here when root element has a box. Element* documentElement = obj.document().documentElement(); ASSERT(documentElement); ASSERT(documentElement->layoutObject()); ASSERT(documentElement->layoutObject()->isBox()); rootBox = toLayoutBox(documentElement->layoutObject()); } const LayoutBoxModelObject& positioningBox = isLayoutView ? static_cast<const LayoutBoxModelObject&>(*rootBox) : obj; // Determine the background positioning area and set destRect to the background painting area. // destRect will be adjusted later if the background is non-repeating. // FIXME: transforms spec says that fixed backgrounds behave like scroll inside transforms. bool fixedAttachment = fillLayer.attachment() == FixedBackgroundAttachment; if (RuntimeEnabledFeatures::fastMobileScrollingEnabled()) { // As a side effect of an optimization to blit on scroll, we do not honor the CSS // property "background-attachment: fixed" because it may result in rendering // artifacts. Note, these artifacts only appear if we are blitting on scroll of // a page that has fixed background images. fixedAttachment = false; } if (!fixedAttachment) { geometry.setDestRect(snappedPaintRect); LayoutUnit right = 0; LayoutUnit bottom = 0; // Scroll and Local. if (fillLayer.origin() != BorderFillBox) { left = positioningBox.borderLeft(); right = positioningBox.borderRight(); top = positioningBox.borderTop(); bottom = positioningBox.borderBottom(); if (fillLayer.origin() == ContentFillBox) { left += positioningBox.paddingLeft(); right += positioningBox.paddingRight(); top += positioningBox.paddingTop(); bottom += positioningBox.paddingBottom(); } } if (isLayoutView) { // The background of the box generated by the root element covers the entire canvas and will // be painted by the view object, but the we should still use the root element box for // positioning. positioningAreaSize = pixelSnappedIntSize(rootBox->size() - LayoutSize(left + right, top + bottom), rootBox->location()); // The input paint rect is specified in root element local coordinate (i.e. a transform // is applied on the context for painting), and is expanded to cover the whole canvas. // Since left/top is relative to the paint rect, we need to offset them back. left -= paintRect.x(); top -= paintRect.y(); } else { positioningAreaSize = pixelSnappedIntSize(paintRect.size() - LayoutSize(left + right, top + bottom), paintRect.location()); } } else { geometry.setHasNonLocalGeometry(); IntRect viewportRect = pixelSnappedIntRect(obj.viewRect()); if (fixedBackgroundPaintsInLocalCoordinates(obj)) viewportRect.setLocation(IntPoint()); else if (FrameView* frameView = obj.view()->frameView()) viewportRect.setLocation(frameView->scrollPosition()); if (paintContainer) { IntPoint absoluteContainerOffset = roundedIntPoint(paintContainer->localToAbsolute(FloatPoint())); viewportRect.moveBy(-absoluteContainerOffset); } geometry.setDestRect(viewportRect); positioningAreaSize = geometry.destRect().size(); } const LayoutObject* clientForBackgroundImage = backgroundObject ? backgroundObject : &obj; IntSize fillTileSize = calculateFillTileSize(positioningBox, fillLayer, positioningAreaSize); fillLayer.image()->setContainerSizeForLayoutObject(clientForBackgroundImage, fillTileSize, obj.style()->effectiveZoom()); geometry.setTileSize(fillTileSize); EFillRepeat backgroundRepeatX = fillLayer.repeatX(); EFillRepeat backgroundRepeatY = fillLayer.repeatY(); int availableWidth = positioningAreaSize.width() - geometry.tileSize().width(); int availableHeight = positioningAreaSize.height() - geometry.tileSize().height(); LayoutUnit computedXPosition = roundedMinimumValueForLength(fillLayer.xPosition(), availableWidth); if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) { long nrTiles = std::max(1l, lroundf((float)positioningAreaSize.width() / fillTileSize.width())); // Round tile size per css3-background spec. fillTileSize.setWidth(lroundf(positioningAreaSize.width() / (float)nrTiles)); // Maintain aspect ratio if background-size: auto is set if (fillLayer.size().size.height().isAuto() && backgroundRepeatY != RoundFill) { fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (nrTiles * fillTileSize.width())); } geometry.setTileSize(fillTileSize); geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0); geometry.setSpaceSize(IntSize()); } LayoutUnit computedYPosition = roundedMinimumValueForLength(fillLayer.yPosition(), availableHeight); if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) { long nrTiles = std::max(1l, lroundf((float)positioningAreaSize.height() / fillTileSize.height())); // Round tile size per css3-background spec. fillTileSize.setHeight(lroundf(positioningAreaSize.height() / (float)nrTiles)); // Maintain aspect ratio if background-size: auto is set if (fillLayer.size().size.width().isAuto() && backgroundRepeatX != RoundFill) { fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (nrTiles * fillTileSize.height())); } geometry.setTileSize(fillTileSize); geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0); geometry.setSpaceSize(IntSize()); } if (backgroundRepeatX == RepeatFill) { geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0); geometry.setSpaceSize(IntSize()); } else if (backgroundRepeatX == SpaceFill && fillTileSize.width() > 0) { int space = getSpaceBetweenImageTiles(positioningAreaSize.width(), geometry.tileSize().width()); int actualWidth = geometry.tileSize().width() + space; if (space >= 0) { computedXPosition = roundedMinimumValueForLength(Length(), availableWidth); geometry.setSpaceSize(IntSize(space, 0)); geometry.setPhaseX(actualWidth ? actualWidth - roundToInt(computedXPosition + left) % actualWidth : 0); } else { backgroundRepeatX = NoRepeatFill; } } if (backgroundRepeatX == NoRepeatFill) { int xOffset = fillLayer.backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition; geometry.setNoRepeatX(left + xOffset); geometry.setSpaceSize(IntSize(0, geometry.spaceSize().height())); } if (backgroundRepeatY == RepeatFill) { geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0); geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), 0)); } else if (backgroundRepeatY == SpaceFill && fillTileSize.height() > 0) { int space = getSpaceBetweenImageTiles(positioningAreaSize.height(), geometry.tileSize().height()); int actualHeight = geometry.tileSize().height() + space; if (space >= 0) { computedYPosition = roundedMinimumValueForLength(Length(), availableHeight); geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), space)); geometry.setPhaseY(actualHeight ? actualHeight - roundToInt(computedYPosition + top) % actualHeight : 0); } else { backgroundRepeatY = NoRepeatFill; } } if (backgroundRepeatY == NoRepeatFill) { int yOffset = fillLayer.backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition; geometry.setNoRepeatY(top + yOffset); geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), 0)); } if (fixedAttachment) geometry.useFixedAttachment(snappedPaintRect.location()); geometry.clip(snappedPaintRect); } InterpolationQuality BoxPainter::chooseInterpolationQuality(LayoutObject& obj, GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size) { return ImageQualityController::imageQualityController()->chooseInterpolationQuality(context, &obj, image, layer, size); } bool BoxPainter::fixedBackgroundPaintsInLocalCoordinates(const LayoutObject& obj) { if (!obj.isLayoutView()) return false; const LayoutView& view = toLayoutView(obj); if (view.frameView() && view.frameView()->paintBehavior() & PaintBehaviorFlattenCompositingLayers) return false; DeprecatedPaintLayer* rootLayer = view.layer(); if (!rootLayer || rootLayer->compositingState() == NotComposited) return false; return rootLayer->compositedDeprecatedPaintLayerMapping()->backgroundLayerPaintsFixedRootBackground(); } static inline void applySubPixelHeuristicForTileSize(LayoutSize& tileSize, const IntSize& positioningAreaSize) { tileSize.setWidth(positioningAreaSize.width() - tileSize.width() <= 1 ? tileSize.width().ceil() : tileSize.width().floor()); tileSize.setHeight(positioningAreaSize.height() - tileSize.height() <= 1 ? tileSize.height().ceil() : tileSize.height().floor()); } IntSize BoxPainter::calculateFillTileSize(const LayoutBoxModelObject& obj, const FillLayer& fillLayer, const IntSize& positioningAreaSize) { StyleImage* image = fillLayer.image(); EFillSizeType type = fillLayer.size().type; IntSize imageIntrinsicSize = obj.calculateImageIntrinsicDimensions(image, positioningAreaSize, LayoutBoxModelObject::ScaleByEffectiveZoom); imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor()); switch (type) { case SizeLength: { LayoutSize tileSize(positioningAreaSize); Length layerWidth = fillLayer.size().size.width(); Length layerHeight = fillLayer.size().size.height(); if (layerWidth.isFixed()) tileSize.setWidth(layerWidth.value()); else if (layerWidth.hasPercent()) tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width())); if (layerHeight.isFixed()) tileSize.setHeight(layerHeight.value()); else if (layerHeight.hasPercent()) tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height())); applySubPixelHeuristicForTileSize(tileSize, positioningAreaSize); // If one of the values is auto we have to use the appropriate // scale to maintain our aspect ratio. if (layerWidth.isAuto() && !layerHeight.isAuto()) { if (imageIntrinsicSize.height()) { LayoutUnit adjustedWidth = imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height(); if (imageIntrinsicSize.width() >= 1 && adjustedWidth < 1) adjustedWidth = 1; tileSize.setWidth(adjustedWidth); } } else if (!layerWidth.isAuto() && layerHeight.isAuto()) { if (imageIntrinsicSize.width()) { LayoutUnit adjustedHeight = imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width(); if (imageIntrinsicSize.height() >= 1 && adjustedHeight < 1) adjustedHeight = 1; tileSize.setHeight(adjustedHeight); } } else if (layerWidth.isAuto() && layerHeight.isAuto()) { // If both width and height are auto, use the image's intrinsic size. tileSize = LayoutSize(imageIntrinsicSize); } tileSize.clampNegativeToZero(); return flooredIntSize(tileSize); } case SizeNone: { // If both values are 'auto' then the intrinsic width and/or height of the image should be used, if any. if (!imageIntrinsicSize.isEmpty()) return imageIntrinsicSize; // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'. type = Contain; } case Contain: case Cover: { float horizontalScaleFactor = imageIntrinsicSize.width() ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1; float verticalScaleFactor = imageIntrinsicSize.height() ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1; float scaleFactor = type == Contain ? std::min(horizontalScaleFactor, verticalScaleFactor) : std::max(horizontalScaleFactor, verticalScaleFactor); return IntSize(std::max(1l, lround(imageIntrinsicSize.width() * scaleFactor)), std::max(1l, lround(imageIntrinsicSize.height() * scaleFactor))); } } ASSERT_NOT_REACHED(); return IntSize(); } bool BoxPainter::paintNinePieceImage(LayoutBoxModelObject& obj, GraphicsContext* graphicsContext, const LayoutRect& rect, const ComputedStyle& style, const NinePieceImage& ninePieceImage, SkXfermode::Mode op) { NinePieceImagePainter ninePieceImagePainter(obj); return ninePieceImagePainter.paint(graphicsContext, rect, style, ninePieceImage, op); } bool BoxPainter::shouldAntialiasLines(GraphicsContext* context) { if (RuntimeEnabledFeatures::slimmingPaintEnabled()) return true; // FIXME: We may want to not antialias when scaled by an integral value, // and we may want to antialias when translated by a non-integral value. // FIXME: See crbug.com/382491. getCTM does not include scale factors applied at raster time, such // as device zoom. return !context->getCTM().isIdentityOrTranslationOrFlipped(); } bool BoxPainter::allCornersClippedOut(const FloatRoundedRect& border, const IntRect& intClipRect) { LayoutRect boundingRect(border.rect()); LayoutRect clipRect(intClipRect); if (clipRect.contains(boundingRect)) return false; FloatRoundedRect::Radii radii = border.radii(); LayoutRect topLeftRect(boundingRect.location(), LayoutSize(radii.topLeft())); if (clipRect.intersects(topLeftRect)) return false; LayoutRect topRightRect(boundingRect.location(), LayoutSize(radii.topRight())); topRightRect.setX(boundingRect.maxX() - topRightRect.width()); if (clipRect.intersects(topRightRect)) return false; LayoutRect bottomLeftRect(boundingRect.location(), LayoutSize(radii.bottomLeft())); bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height()); if (clipRect.intersects(bottomLeftRect)) return false; LayoutRect bottomRightRect(boundingRect.location(), LayoutSize(radii.bottomRight())); bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width()); bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height()); if (clipRect.intersects(bottomRightRect)) return false; return true; } void BoxPainter::paintBorder(LayoutBoxModelObject& obj, const PaintInfo& info, const LayoutRect& rect, const ComputedStyle& style, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) { // border-image is not affected by border-radius. if (paintNinePieceImage(obj, info.context, rect, style, style.borderImage())) return; const BoxBorderPainter borderPainter(rect, style, info.rect, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); borderPainter.paintBorder(info, rect); } void BoxPainter::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const ComputedStyle& style, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) { // FIXME: Deal with border-image. Would be great to use border-image as a mask. GraphicsContext* context = info.context; if (!style.boxShadow()) return; FloatRoundedRect border = (shadowStyle == Inset) ? style.getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge) : style.getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge); bool hasBorderRadius = style.hasBorderRadius(); bool isHorizontal = style.isHorizontalWritingMode(); bool hasOpaqueBackground = style.visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255; GraphicsContextStateSaver stateSaver(*context, false); const ShadowList* shadowList = style.boxShadow(); for (size_t i = shadowList->shadows().size(); i--; ) { const ShadowData& shadow = shadowList->shadows()[i]; if (shadow.style() != shadowStyle) continue; FloatSize shadowOffset(shadow.x(), shadow.y()); float shadowBlur = shadow.blur(); float shadowSpread = shadow.spread(); if (shadowOffset.isZero() && !shadowBlur && !shadowSpread) continue; const Color& shadowColor = shadow.color().resolve(style.visitedDependentColor(CSSPropertyColor)); if (shadow.style() == Normal) { FloatRect fillRect = border.rect(); fillRect.inflate(shadowSpread); if (fillRect.isEmpty()) continue; FloatRect shadowRect(border.rect()); shadowRect.inflate(shadowBlur + shadowSpread); shadowRect.move(shadowOffset); // Save the state and clip, if not already done. // The clip does not depend on any shadow-specific properties. if (!stateSaver.saved()) { stateSaver.save(); if (hasBorderRadius) { FloatRoundedRect rectToClipOut = border; // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time // when painting the shadow. On the other hand, it introduces subpixel gaps along the // corners. Those are avoided by insetting the clipping path by one CSS pixel. if (hasOpaqueBackground) rectToClipOut.inflateWithRadii(-1); if (!rectToClipOut.isEmpty()) context->clipOutRoundedRect(rectToClipOut); } else { // This IntRect is correct even with fractional shadows, because it is used for the rectangle // of the box itself, which is always pixel-aligned. FloatRect rectToClipOut = border.rect(); // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time // when painting the shadow. On the other hand, it introduces subpixel gaps along the // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path // by one CSS pixel. if (hasOpaqueBackground) rectToClipOut.inflate(-1); if (!rectToClipOut.isEmpty()) context->clipOut(rectToClipOut); } } // Draw only the shadow. context->setShadow(shadowOffset, shadowBlur, shadowColor, DrawLooperBuilder::ShadowRespectsTransforms, DrawLooperBuilder::ShadowIgnoresAlpha, DrawShadowOnly); if (hasBorderRadius) { FloatRoundedRect influenceRect(pixelSnappedIntRect(LayoutRect(shadowRect)), border.radii()); float changeAmount = 2 * shadowBlur + shadowSpread; if (changeAmount >= 0) influenceRect.expandRadii(changeAmount); else influenceRect.shrinkRadii(-changeAmount); if (allCornersClippedOut(influenceRect, info.rect)) { context->fillRect(fillRect, Color::black); } else { // TODO: support non-integer shadows - crbug.com/334829 FloatRoundedRect roundedFillRect = border; roundedFillRect.inflate(shadowSpread); if (shadowSpread >= 0) roundedFillRect.expandRadii(shadowSpread); else roundedFillRect.shrinkRadii(-shadowSpread); if (!roundedFillRect.isRenderable()) roundedFillRect.adjustRadii(); roundedFillRect.constrainRadii(); context->fillRoundedRect(roundedFillRect, Color::black); } } else { context->fillRect(fillRect, Color::black); } } else { // The inset shadow case. GraphicsContext::Edges clippedEdges = GraphicsContext::NoEdge; if (!includeLogicalLeftEdge) { if (isHorizontal) clippedEdges |= GraphicsContext::LeftEdge; else clippedEdges |= GraphicsContext::TopEdge; } if (!includeLogicalRightEdge) { if (isHorizontal) clippedEdges |= GraphicsContext::RightEdge; else clippedEdges |= GraphicsContext::BottomEdge; } // TODO: support non-integer shadows - crbug.com/334828 context->drawInnerShadow(border, shadowColor, flooredIntSize(shadowOffset), shadowBlur, shadowSpread, clippedEdges); } } } bool BoxPainter::shouldForceWhiteBackgroundForPrintEconomy(const ComputedStyle& style, const Document& document) { return document.printing() && style.printColorAdjust() == PrintColorAdjustEconomy && (!document.settings() || !document.settings()->shouldPrintBackgrounds()); } } // namespace blink
48.714421
305
0.694965
wenfeifei
4895b449b8a1ea8118e69b15504c731ddae33732
16,163
cpp
C++
src/types/quamodbusrtuserialclient.cpp
juangburgos/QUaModbusClient
e1ac862e723cfdf9e6127d395fb7c614829e2154
[ "MIT" ]
26
2019-08-19T18:18:51.000Z
2022-03-24T12:56:30.000Z
src/types/quamodbusrtuserialclient.cpp
ManfredHerrmann/QUaModbusClient
38a3ec715db0336d4c26398084bef22ab5ca5072
[ "MIT" ]
2
2019-08-25T03:45:59.000Z
2021-01-21T12:06:55.000Z
src/types/quamodbusrtuserialclient.cpp
ManfredHerrmann/QUaModbusClient
38a3ec715db0336d4c26398084bef22ab5ca5072
[ "MIT" ]
9
2019-09-10T14:31:40.000Z
2021-09-28T05:37:54.000Z
#include "quamodbusrtuserialclient.h" #include <QSerialPortInfo> #ifdef QUA_ACCESS_CONTROL #include <QUaPermissions> #endif // QUA_ACCESS_CONTROL QUaModbusRtuSerialClient::QUaModbusRtuSerialClient(QUaServer *server) : QUaModbusClient(server) { // set defaults type ()->setDataTypeEnum(QMetaEnum::fromType<QModbusClientType>()); type ()->setValue(QModbusClientType::Serial); comPort ()->setDataTypeEnum(QUaModbusRtuSerialClient::ComPorts); comPort ()->setValue(0); parity ()->setDataTypeEnum(QMetaEnum::fromType<QParity>()); parity ()->setValue(QSerialPort::EvenParity); baudRate()->setDataTypeEnum(QMetaEnum::fromType<QBaudRate>()); baudRate()->setValue(QSerialPort::Baud19200); dataBits()->setDataTypeEnum(QMetaEnum::fromType<QDataBits>()); dataBits()->setValue(QSerialPort::Data8); stopBits()->setDataTypeEnum(QMetaEnum::fromType<QStopBits>()); stopBits()->setValue(QSerialPort::OneStop); // set initial conditions comPort ()->setWriteAccess(true); parity ()->setWriteAccess(true); baudRate()->setWriteAccess(true); dataBits()->setWriteAccess(true); stopBits()->setWriteAccess(true); // instantiate client this->resetModbusClient(); // handle state changes QObject::connect(comPort (), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_comPortChanged , Qt::QueuedConnection); QObject::connect(parity (), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_parityChanged , Qt::QueuedConnection); QObject::connect(baudRate(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_baudRateChanged, Qt::QueuedConnection); QObject::connect(dataBits(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_dataBitsChanged, Qt::QueuedConnection); QObject::connect(stopBits(), &QUaBaseVariable::valueChanged, this, &QUaModbusRtuSerialClient::on_stopBitsChanged, Qt::QueuedConnection); // set descriptions /* comPort ()->setDescription("Local serial COM port used to connect to the Modbus server."); parity ()->setDescription("Parity value (for error detection) used to communicate with the Modbus server."); baudRate()->setDescription("Baud Rate value (data rate in bits per second) used to communicate with the Modbus server."); dataBits()->setDescription("Number of Data Bits (in each character) used to communicate with the Modbus server."); stopBits()->setDescription("Number of Stop Bits (sent at the end of every character) used to communicate with the Modbus server."); */ } QUaProperty * QUaModbusRtuSerialClient::comPort() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("ComPort"); } QUaProperty * QUaModbusRtuSerialClient::parity() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("Parity"); } QUaProperty * QUaModbusRtuSerialClient::baudRate() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("BaudRate"); } QUaProperty * QUaModbusRtuSerialClient::dataBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("DataBits"); } QUaProperty * QUaModbusRtuSerialClient::stopBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return const_cast<QUaModbusRtuSerialClient*>(this)->browseChild<QUaProperty>("StopBits"); } QString QUaModbusRtuSerialClient::ComPorts = "QUaModbusRtuSerialClient::ComPorts"; QUaEnumMap QUaModbusRtuSerialClient::EnumComPorts() { QUaEnumMap mapPorts; QList<QSerialPortInfo> list = QSerialPortInfo::availablePorts(); for (int i = 0; i < list.count(); i++) { QSerialPortInfo portInfo = list.at(i); mapPorts.insert(i, { { "", portInfo.portName().toUtf8() }, { "", "" } } ); } return mapPorts; } void QUaModbusRtuSerialClient::resetModbusClient() { m_workerThread.execInThread([this]() { // instantiate in thread so it runs on the thread m_modbusClient.reset(new QModbusRtuSerialMaster(nullptr), [](QObject* client) { client->deleteLater(); }); // defaults m_modbusClient->setConnectionParameter(QModbusDevice::SerialPortNameParameter, this->getComPort ()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialParityParameter , this->getParity ()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, this->getBaudRate()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, this->getDataBits()); m_modbusClient->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, this->getStopBits()); // setup client (call base class method) this->QUaModbusClient::resetModbusClient(); QObject::connect(m_modbusClient.data(), &QModbusClient::stateChanged, this, &QUaModbusRtuSerialClient::on_stateChanged, Qt::QueuedConnection); }); } QDomElement QUaModbusRtuSerialClient::toDomElement(QDomDocument & domDoc) const { // add client list element QDomElement elemSerialClient = domDoc.createElement(QUaModbusRtuSerialClient::staticMetaObject.className()); #ifdef QUA_ACCESS_CONTROL // set parmissions if any if (this->hasPermissionsObject()) { elemSerialClient.setAttribute("Permissions", this->permissionsObject()->nodeId()); } #endif // QUA_ACCESS_CONTROL // set client attributes elemSerialClient.setAttribute("BrowseName" , this->browseName() ); elemSerialClient.setAttribute("ServerAddress" , getServerAddress() ); elemSerialClient.setAttribute("KeepConnecting", getKeepConnecting() ); elemSerialClient.setAttribute("ComPort" , QString(QUaModbusRtuSerialClient::EnumComPorts().value(getComPortKey()).displayName.text())); elemSerialClient.setAttribute("Parity" , QMetaEnum::fromType<QParity> ().valueToKey(getParity() )); elemSerialClient.setAttribute("BaudRate" , QMetaEnum::fromType<QBaudRate>().valueToKey(getBaudRate() )); elemSerialClient.setAttribute("DataBits" , QMetaEnum::fromType<QDataBits>().valueToKey(getDataBits() )); elemSerialClient.setAttribute("StopBits" , QMetaEnum::fromType<QStopBits>().valueToKey(getStopBits() )); // add block list element auto elemBlockList = const_cast<QUaModbusRtuSerialClient*>(this)->dataBlocks()->toDomElement(domDoc); elemSerialClient.appendChild(elemBlockList); // return list element return elemSerialClient; } void QUaModbusRtuSerialClient::fromDomElement(QDomElement & domElem, QQueue<QUaLog>& errorLogs) { // get client attributes (BrowseName must be already set) QString strBrowseName = domElem.attribute("BrowseName", ""); Q_ASSERT(this->browseName() == QUaQualifiedName(strBrowseName)); bool bOK; // ServerAddress auto serverAddress = domElem.attribute("ServerAddress").toUInt(&bOK); #ifdef QUA_ACCESS_CONTROL // load permissions if any if (domElem.hasAttribute("Permissions") && !domElem.attribute("Permissions").isEmpty()) { QString strError = this->setPermissions(domElem.attribute("Permissions")); if (strError.contains("Error")) { errorLogs << QUaLog( strError, QUaLogLevel::Error, QUaLogCategory::Serialization ); } } #endif // QUA_ACCESS_CONTROL if (bOK) { this->setServerAddress(serverAddress); } else { errorLogs << QUaLog( tr("Invalid ServerAddress attribute '%1' in Modbus client %2. Default value set.").arg(serverAddress).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // KeepConnecting auto keepConnecting = (bool)domElem.attribute("KeepConnecting").toUInt(&bOK); if (bOK) { this->setKeepConnecting(keepConnecting); } else { errorLogs << QUaLog( tr("Invalid KeepConnecting attribute '%1' in Modbus client %2. Default value set.").arg(keepConnecting).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // ComPort auto comPort = domElem.attribute("ComPort"); if (!comPort.isEmpty()) { this->setComPortKey(QUaModbusRtuSerialClient::EnumComPorts().key( { { "", comPort.toUtf8() }, { "", "" } }, 0)); } else { errorLogs << QUaLog( tr("Invalid ComPort attribute '%1' in Modbus client %2. Default value set.").arg(comPort).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // Parity auto strParity = domElem.attribute("Parity"); auto parity = (QParity)QMetaEnum::fromType<QParity>().keysToValue(strParity.toUtf8(), &bOK); if (bOK) { this->setParity(parity); } else { errorLogs << QUaLog( tr("Invalid Parity attribute '%1' in Modbus client %2. Default value set.").arg(strParity).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // BaudRate auto strBaudRate = domElem.attribute("BaudRate"); auto baudRate = (QBaudRate)QMetaEnum::fromType<QBaudRate>().keysToValue(strBaudRate.toUtf8(), &bOK); if (bOK) { this->setBaudRate(baudRate); } else { errorLogs << QUaLog( tr("Invalid BaudRate attribute '%1' in Modbus client %2. Default value set.").arg(strBaudRate).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // DataBits auto strDataBits = domElem.attribute("DataBits"); auto dataBits = (QDataBits)QMetaEnum::fromType<QDataBits>().keysToValue(strDataBits.toUtf8(), &bOK); if (bOK) { this->setDataBits(dataBits); } else { errorLogs << QUaLog( tr("Invalid DataBits attribute '%1' in Modbus client %2. Default value set.").arg(strDataBits).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // StopBits auto strStopBits = domElem.attribute("StopBits"); auto stopBits = (QStopBits)QMetaEnum::fromType<QStopBits>().keysToValue(strStopBits.toUtf8(), &bOK); if (bOK) { this->setStopBits(stopBits); } else { errorLogs << QUaLog( tr("Invalid StopBits attribute '%1' in Modbus client %2. Default value set.").arg(strStopBits).arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } // get block list QDomElement elemBlockList = domElem.firstChildElement(QUaModbusDataBlockList::staticMetaObject.className()); if (!elemBlockList.isNull()) { dataBlocks()->fromDomElement(elemBlockList, errorLogs); } else { errorLogs << QUaLog( tr("Modbus client %2 does not have a QUaModbusDataBlockList child. No blocks will be loaded.").arg(strBrowseName), QUaLogLevel::Warning, QUaLogCategory::Serialization ); } } void QUaModbusRtuSerialClient::on_stateChanged(const QModbusDevice::State &state) { // only allow to write connection params if not connected if (state == QModbusDevice::State::UnconnectedState) { comPort ()->setWriteAccess(true); parity ()->setWriteAccess(true); baudRate()->setWriteAccess(true); dataBits()->setWriteAccess(true); stopBits()->setWriteAccess(true); } else { comPort ()->setWriteAccess(false); parity ()->setWriteAccess(false); baudRate()->setWriteAccess(false); dataBits()->setWriteAccess(false); stopBits()->setWriteAccess(false); } } void QUaModbusRtuSerialClient::on_comPortChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QString strComPort = QUaModbusRtuSerialClient::EnumComPorts().value(value.toInt()).displayName.text(); // set in thread, for thread-safety m_workerThread.execInThread([this, strComPort]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialPortNameParameter, strComPort); }); // emit emit this->comPortChanged(strComPort); } void QUaModbusRtuSerialClient::on_parityChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QParity parity = value.value<QParity>(); // set in thread, for thread-safety m_workerThread.execInThread([this, parity]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialParityParameter, parity); }); // emit emit this->parityChanged(parity); } void QUaModbusRtuSerialClient::on_baudRateChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QBaudRate baudRate = value.value<QBaudRate>(); // set in thread, for thread-safety m_workerThread.execInThread([this, baudRate]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialBaudRateParameter, baudRate); }); // emit emit this->baudRateChanged(baudRate); } void QUaModbusRtuSerialClient::on_dataBitsChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QDataBits dataBits = value.value<QDataBits>(); // set in thread, for thread-safety m_workerThread.execInThread([this, dataBits]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialDataBitsParameter, dataBits); }); // emit emit this->dataBitsChanged(dataBits); } void QUaModbusRtuSerialClient::on_stopBitsChanged(const QVariant & value) { // NOTE : if connected, will not change until reconnect QStopBits stopBits = value.value<QStopBits>(); // set in thread, for thread-safety m_workerThread.execInThread([this, stopBits]() { m_modbusClient->setConnectionParameter(QModbusDevice::SerialStopBitsParameter, stopBits); }); // emit emit this->stopBitsChanged(stopBits); } QString QUaModbusRtuSerialClient::getComPort() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); auto key = this->comPort()->value().toInt(); return QUaModbusRtuSerialClient::EnumComPorts().value(key).displayName.text(); } void QUaModbusRtuSerialClient::setComPort(const QString & strComPort) { QMutexLocker locker(&m_mutex); auto comPort = QUaModbusRtuSerialClient::EnumComPorts().key( { { "", strComPort.toUtf8() }, { "", "" } }, 0); this->comPort()->setValue(comPort); this->on_comPortChanged(comPort); } int QUaModbusRtuSerialClient::getComPortKey() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->comPort()->value().toInt(); } void QUaModbusRtuSerialClient::setComPortKey(const int & comPort) { QMutexLocker locker(&m_mutex); this->comPort()->setValue(comPort); this->on_comPortChanged(comPort); } QParity QUaModbusRtuSerialClient::getParity() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->parity()->value().value<QParity>(); } void QUaModbusRtuSerialClient::setParity(const QParity & parity) { QMutexLocker locker(&m_mutex); this->parity()->setValue(parity); this->on_parityChanged(parity); } QBaudRate QUaModbusRtuSerialClient::getBaudRate() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->baudRate()->value().value<QBaudRate>(); } void QUaModbusRtuSerialClient::setBaudRate(const QBaudRate & baudRate) { QMutexLocker locker(&m_mutex); this->baudRate()->setValue(baudRate); this->on_baudRateChanged(baudRate); } QDataBits QUaModbusRtuSerialClient::getDataBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->dataBits()->value().value<QDataBits>(); } void QUaModbusRtuSerialClient::setDataBits(const QDataBits & dataBits) { QMutexLocker locker(&m_mutex); this->dataBits()->setValue(dataBits); this->on_dataBitsChanged(dataBits); } QStopBits QUaModbusRtuSerialClient::getStopBits() const { QMutexLocker locker(&(const_cast<QUaModbusRtuSerialClient*>(this)->m_mutex)); return this->stopBits()->value().value<QStopBits>(); } void QUaModbusRtuSerialClient::setStopBits(const QStopBits & stopBits) { QMutexLocker locker(&m_mutex); this->stopBits()->setValue(stopBits); this->on_stopBitsChanged(stopBits); }
35.838137
145
0.7313
juangburgos
489b14a3a7c5c911339d34e93467ea20e62d3cd6
3,119
cc
C++
content/common/input/synthetic_pointer_action_params.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
content/common/input/synthetic_pointer_action_params.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
content/common/input/synthetic_pointer_action_params.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/input/synthetic_pointer_action_params.h" namespace content { SyntheticPointerActionParams::SyntheticPointerActionParams() = default; SyntheticPointerActionParams::SyntheticPointerActionParams( PointerActionType action_type) : pointer_action_type_(action_type), button_(action_type == PointerActionType::MOVE ? Button::NO_BUTTON : Button::LEFT) {} SyntheticPointerActionParams::SyntheticPointerActionParams( const SyntheticPointerActionParams& other) = default; SyntheticPointerActionParams::~SyntheticPointerActionParams() = default; // static unsigned SyntheticPointerActionParams::GetWebMouseEventModifier( SyntheticPointerActionParams::Button button) { switch (button) { case SyntheticPointerActionParams::Button::LEFT: return blink::WebMouseEvent::kLeftButtonDown; case SyntheticPointerActionParams::Button::MIDDLE: return blink::WebMouseEvent::kMiddleButtonDown; case SyntheticPointerActionParams::Button::RIGHT: return blink::WebMouseEvent::kRightButtonDown; case SyntheticPointerActionParams::Button::BACK: return blink::WebMouseEvent::kBackButtonDown; case SyntheticPointerActionParams::Button::FORWARD: return blink::WebMouseEvent::kForwardButtonDown; case SyntheticPointerActionParams::Button::NO_BUTTON: return blink::WebMouseEvent::kNoModifiers; } NOTREACHED(); return blink::WebMouseEvent::kNoModifiers; } // static blink::WebMouseEvent::Button SyntheticPointerActionParams::GetWebMouseEventButton( SyntheticPointerActionParams::Button button) { switch (button) { case SyntheticPointerActionParams::Button::LEFT: return blink::WebMouseEvent::Button::kLeft; case SyntheticPointerActionParams::Button::MIDDLE: return blink::WebMouseEvent::Button::kMiddle; case SyntheticPointerActionParams::Button::RIGHT: return blink::WebMouseEvent::Button::kRight; case SyntheticPointerActionParams::Button::BACK: return blink::WebMouseEvent::Button::kBack; case SyntheticPointerActionParams::Button::FORWARD: return blink::WebMouseEvent::Button::kForward; case SyntheticPointerActionParams::Button::NO_BUTTON: return blink::WebMouseEvent::Button::kNoButton; } NOTREACHED(); return blink::WebMouseEvent::Button::kNoButton; } // static blink::WebMouseEvent::Button SyntheticPointerActionParams::GetWebMouseEventButtonFromModifier( unsigned modifiers) { blink::WebMouseEvent::Button button = blink::WebMouseEvent::Button::kNoButton; if (modifiers & blink::WebMouseEvent::kLeftButtonDown) button = blink::WebMouseEvent::Button::kLeft; if (modifiers & blink::WebMouseEvent::kMiddleButtonDown) button = blink::WebMouseEvent::Button::kMiddle; if (modifiers & blink::WebMouseEvent::kRightButtonDown) button = blink::WebMouseEvent::Button::kRight; return button; } } // namespace content
38.9875
80
0.761462
zealoussnow
489eea62bd2b9e266f41e6b0e4b9477aa9a1ad0a
6,023
cpp
C++
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
1
2020-03-18T02:34:32.000Z
2020-03-18T02:34:32.000Z
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
null
null
null
qt_project/MainWindow.cpp
hejiangda/DaDaXiuXiu
ed2aeba3517065ed552d17acd43c66863143a867
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include "ui_MainWindow.h" #include <QFileInfo> #include <QDir> MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), addFlg(0), t1ok(false), t2ok(false), t3ok(false) { ui->setupUi(this); connect(&MT1, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT1, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT2, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT2, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT3, SIGNAL(WhiteDisplay(QPixmap)), ui->WhiteImg, SLOT(setPixmap(QPixmap))); connect(&MT3, SIGNAL(TransDisplay(QPixmap)), ui->TransImg, SLOT(setPixmap(QPixmap))); connect(&MT1, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); connect(&MT2, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); connect(&MT3, SIGNAL(jobFinish(int)), this, SLOT(setflgAndReOpen(int))); MT1.setNo(1); MT2.setNo(2); MT3.setNo(3); } MainWindow::~MainWindow() { MT1.quit(); MT2.quit(); MT3.quit(); delete ui; } void MainWindow::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasUrls()) //判断数据类型 { e->acceptProposedAction();//接收该数据类型拖拽事件 } else { e->ignore();//忽略 } } void MainWindow::dropEvent(QDropEvent* event) { //窗口部件放下一个对象时,调用该函数 QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) { event->ignore(); return; } QStringList acceptedFileTypes; acceptedFileTypes.append("jpg"); acceptedFileTypes.append("png"); acceptedFileTypes.append("bmp"); QList<QUrl>::iterator it; for (it = urls.begin(); it != urls.end(); it++) { QUrl url = *it; QFileInfo fileInfo(it->toLocalFile()); if (fileInfo.isFile()) { if (acceptedFileTypes.contains(fileInfo.suffix().toLower())) { //是文件就直接加进来 ui->imgListWidget->addItem(fileInfo.filePath()); if (addFlg == 0) l1.push_back(fileInfo.filePath().toStdString()); else if (addFlg == 1) l2.push_back(fileInfo.filePath().toStdString()); else if (addFlg == 2) l3.push_back(fileInfo.filePath().toStdString()); addFlg = (addFlg + 1) % 3; } } else if (fileInfo.isDir()) { //文件路径就循环读取 QFileInfoList fileInfoList = GetAllFileList(fileInfo.filePath()); for (QFileInfo fileInfo1 : fileInfoList) { if (acceptedFileTypes.contains(fileInfo1.suffix().toLower())) { ui->imgListWidget->addItem(fileInfo1.filePath()); if (addFlg == 0) l1.push_back(fileInfo1.filePath().toStdString()); else if (addFlg == 1) l2.push_back(fileInfo1.filePath().toStdString()); else if (addFlg == 2) l3.push_back(fileInfo1.filePath().toStdString()); addFlg = (addFlg + 1) % 3; } } } } MT1.setFileLists(l1); MT2.setFileLists(l2); MT3.setFileLists(l3); if (ui->comboBox->currentIndex() == 0) { MT1.setSz(Size(800, 800)); MT2.setSz(Size(800, 800)); MT3.setSz(Size(800, 800)); } else { MT1.setSz(Size(800, 1200)); MT2.setSz(Size(800, 1200)); MT3.setSz(Size(800, 1200)); } } //只取得该目录下的子文件不考虑子文件夹 QFileInfoList MainWindow::GetAllFileList(QString path) { QDir dir(path); QFileInfoList file_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks); return file_list; } void MainWindow::resizeEvent(QResizeEvent* event) { Q_UNUSED(event); if (!WhiteShow.isNull()) { ui->WhiteImg->setPixmap(WhiteShow.scaled(ui->WhiteImg->width() - 5, ui->WhiteImg->height() - 5, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } if (!TransShow.isNull()) { ui->TransImg->setPixmap(TransShow.scaled(ui->TransImg->width() - 5, ui->TransImg->height() - 5, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } void MainWindow::on_imgListWidget_itemClicked(QListWidgetItem* item) { } void MainWindow::on_pushButton_clicked() { MT1.start(); t1ok = false; MT2.start(); t2ok = false; MT3.start(); t3ok = false; ui->pushButton->setDisabled(true); } #include <QMessageBox> void MainWindow::setflgAndReOpen(int flg) { // cout << "flg Ok:" << t1ok << " " << t2ok << " " << t3ok << endl; switch (flg) { case 1: t1ok = true; break; case 2: t2ok = true; break; case 3: t3ok = true; break; } if (t1ok and t2ok and t3ok) { t1ok = t2ok = t3ok = false; ui->pushButton->setDisabled(false); l1.clear(); l2.clear(); l3.clear(); ui->imgListWidget->clear(); cout << endl << "finished" << endl; QApplication::beep(); QMessageBox box; box.setWindowTitle("电商图片自动处理"); box.setText("所有图片已经处理完成,请添加新图片!"); box.exec(); } }
27.377273
95
0.506724
hejiangda
48a271564b47fbb9c429f0585ab527e5c81a5a93
15,795
hpp
C++
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
include/kip/elements.hpp
kei10in/kip
23d83ffa4f40431ef8bd6983e928ae889bfc3872
[ "MIT" ]
null
null
null
#ifndef KIP_ELEMENTS_HPP_ #define KIP_ELEMENTS_HPP_ #include <string> #include <unordered_map> #include <vector> #include "kip/xml-ns.hpp" namespace kip { struct static_object { std::string const empty_string; xml::qname const empty_qname; static_object() {} }; static static_object const& statics() { static static_object const s; return s; } template <class T, class U> class named_element_map { using container_t = std::unordered_map<xml::qname, std::shared_ptr<U>>; container_t container_; public: named_element_map() = default; bool operator==(named_element_map<T, U> const& rhs) const { return container_ == rhs.container_; } T find(xml::qname const& name) const { auto it = container_.find(name); if (it == container_.end()) { return T(); } else { return T(*it); } } std::pair<typename container_t::iterator, bool> insert(std::pair<xml::qname, std::shared_ptr<U>> const& v) { return container_.insert(v); } size_t size() const { return container_.size(); } template <class F> void traverse(F& f) const { for (auto const& it : container_) { T(it).traverse(f); } } }; struct property_impl; struct scored_property_impl; struct option_impl; struct feature_impl; struct parameter_def_impl; class property; class scored_property; class option; class feature_def; class parameter_def; using property_collection = named_element_map<property, property_impl>; using scored_property_collection = named_element_map<scored_property, scored_property_impl>; // todo: rename to feature_def_collection using feature_collection = named_element_map<feature_def, feature_impl>; using parameter_def_collection = named_element_map<parameter_def, parameter_def_impl>; enum class value_type { empty, string, qname, integer, decimal, }; class value_holder { public: virtual ~value_holder() {} virtual value_type type() const = 0; virtual std::string const& string_value() const = 0; virtual xml::qname const& qname_value() const = 0; virtual int integer_value() const = 0; virtual float decimal_value() const = 0; virtual bool equals(value_holder const& rhs) const = 0; virtual bool equals(std::string const& rhs) const = 0; virtual bool equals(xml::qname const& rhs) const = 0; virtual bool equals(int rhs) const = 0; virtual bool equals(float rhs) const = 0; }; template <value_type tag> class base_value_holder : public value_holder { protected: value_type type() const override { return tag; } std::string const& string_value() const override { return statics().empty_string; } xml::qname const& qname_value() const override { return statics().empty_qname; } int integer_value() const override { return 0; } float decimal_value() const override { return 0.0; } // can't define basics // bool equals(value_holder) const = 0; bool equals(std::string const& rhs) const override { return false; } bool equals(xml::qname const& rhs) const override { return false; } bool equals(int rhs) const override { return false; } bool equals(float rhs) const override { return false; } }; class empty_value_holder final : public base_value_holder<value_type::empty> { protected: bool equals(value_holder const& rhs) const override { return type() == rhs.type(); } }; template <value_type tag, class T> class assigned_value_holder : public base_value_holder<tag> { protected: T const value_; explicit assigned_value_holder(T const& v) : value_(v) {} bool equals(value_holder const& rhs) const override { if (type() != rhs.type()) return false; else return rhs.equals(value_); } }; class string_value_holder final : public assigned_value_holder<value_type::string, std::string> { public: explicit string_value_holder(std::string const& v) : assigned_value_holder(v) {} std::string const& string_value() const override { return value_; } bool equals(std::string const& rhs) const override { return value_ == rhs; } }; class qname_value_holder final : public assigned_value_holder<value_type::qname, xml::qname> { public: explicit qname_value_holder(xml::qname const& v) : assigned_value_holder(v) {} xml::qname const& qname_value() const override { return value_; } bool equals(xml::qname const& rhs) const override { return value_ == rhs; } }; class integer_value_holder final : public assigned_value_holder<value_type::integer, int> { public: explicit integer_value_holder(int v) : assigned_value_holder(v) {} int integer_value() const override { return value_; } bool equals(int rhs) const override { return value_ == rhs; } }; class decimal_value_holder final : public assigned_value_holder<value_type::decimal, float> { public: explicit decimal_value_holder(float v) : assigned_value_holder(v) {} float decimal_value() const override { return value_; } bool equals(float rhs) const override { return value_ == rhs; } }; class value { std::shared_ptr<value_holder> holder; public: value() : holder(std::make_shared<empty_value_holder>()) {} value(std::string const& v) : holder(std::make_shared<string_value_holder>(v)) {} value(xml::qname const& v) : holder(std::make_shared<qname_value_holder>(v)) {} value(int v) : holder(std::make_shared<integer_value_holder>(v)) {} value(float v) : holder(std::make_shared<decimal_value_holder>(v)) {} bool empty() const { return type() == value_type::empty; } value_type type() const { return holder->type(); } std::string const& string_value() const { return holder->string_value(); } xml::qname const& qname_value() const { return holder->qname_value(); } int integer_value() const { return holder->integer_value() ;} float decimal_value() const { return holder->decimal_value(); } bool operator==(value const& rhs) const { return holder->equals(*rhs.holder); } template <class T> bool operator==(T const& rhs) const { return holder->equals(rhs); } template <class F> void traverse(F& f) const { if (empty()) return; f.start(*this); f.end(*this); } }; struct parameter_ref { xml::qname name; }; inline bool operator==(parameter_ref const& lhs, parameter_ref const& rhs) { return lhs.name == rhs.name; } inline bool operator!=(parameter_ref const& lhs, parameter_ref const& rhs) { return !(lhs == rhs); } struct property_impl { kip::value value; property_collection properties; }; inline bool operator==(property_impl const& lhs, property_impl const& rhs) { return lhs.value == rhs.value && lhs.properties == rhs.properties; } inline bool operator!=(property_impl const& lhs, property_impl const& rhs) { return !(lhs == rhs); } class property { xml::qname name_; std::shared_ptr<property_impl> pimpl; public: property() {} property(std::pair<xml::qname, std::shared_ptr<property_impl>> const& v) : name_(v.first) , pimpl(v.second) {} property(xml::qname const& n, std::shared_ptr<property_impl> p) : name_(n) , pimpl(p) {} xml::qname const& name() const { return name_; } bool empty() { return pimpl == nullptr; } kip::value const& value() const { return pimpl->value; } property const& operator=(xml::qname const& v) { pimpl->value = v; return *this; } property const& operator=(std::string const& v) { pimpl->value = v; return *this; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->value.traverse(f); pimpl->properties.traverse(f); f.end(*this); } }; struct scored_property_impl { parameter_ref reference; kip::value value; scored_property_collection scored_properties; property_collection properties; }; inline bool operator==(scored_property_impl const& lhs, scored_property_impl const& rhs) { return lhs.value == rhs.value && lhs.scored_properties == rhs.scored_properties && lhs.properties == rhs.properties; } inline bool operator!=(scored_property_impl const& lhs, scored_property_impl const& rhs) { return !(lhs == rhs); } class scored_property { xml::qname name_; std::shared_ptr<scored_property_impl> pimpl; public: scored_property() {} scored_property(std::pair<xml::qname, std::shared_ptr<scored_property_impl>> const& v) : name_(v.first) , pimpl(v.second) {} scored_property(xml::qname n, std::shared_ptr<scored_property_impl> p) : name_(n) , pimpl(p) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } kip::value const& value() const { return pimpl->value; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->value.traverse(f); pimpl->properties.traverse(f); pimpl->scored_properties.traverse(f); f.end(*this); } }; struct option_impl { xml::qname const name; xml::qname const constrained; scored_property_collection scored_properties; property_collection properties; option_impl(xml::qname const& name) : name(name) {} option_impl( xml::qname const& name, xml::qname const& constrained) : name(name) , constrained(constrained) {} }; inline bool operator==(option_impl const& lhs, option_impl const& rhs) { return lhs.name == rhs.name && lhs.constrained == rhs.constrained && lhs.scored_properties == rhs.scored_properties && lhs.properties == rhs.properties; } inline bool operator!=(option_impl const& lhs, option_impl const& rhs) { return !(lhs == rhs); } class option { std::shared_ptr<option_impl> pimpl; public: option() {} option(std::shared_ptr<option_impl> op) : pimpl(op) {} bool operator==(option const& rhs) const { return *pimpl == *rhs.pimpl; } bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return pimpl->name; } xml::qname const& constrained() const { return pimpl->constrained; } property property(xml::qname const& n) { return pimpl->properties.find(n); } scored_property scored_property(xml::qname const& n) { return pimpl->scored_properties.find(n); } // TODO: delete property_collection const& properties() const { return pimpl->properties; } // TODO: delete scored_property_collection const& scored_properties() const { return pimpl->scored_properties; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->properties.traverse(f); pimpl->scored_properties.traverse(f); f.end(*this); } }; struct feature_impl { std::vector<option> options; property_collection properties; feature_collection sub_features; }; inline bool operator==(feature_impl const& lhs, feature_impl const& rhs) { return lhs.options == rhs.options && lhs.properties == rhs.properties && lhs.sub_features == rhs.sub_features; } inline bool operator!=(feature_impl const& lhs, feature_impl const& rhs) { return !(lhs == rhs); } class feature_def { xml::qname name_; std::shared_ptr<feature_impl> pimpl; public: feature_def() {} feature_def(std::pair<xml::qname, std::shared_ptr<feature_impl>> const& ft) : name_(ft.first) , pimpl(ft.second) {} feature_def(xml::qname const& n, std::shared_ptr<feature_impl> pimpl) : name_(n) , pimpl(pimpl) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } std::vector<option> const& options() const { return pimpl->options; } property property(xml::qname const& n) { return pimpl->properties.find(n); } feature_def sub_feature(xml::qname const& n) { return pimpl->sub_features.find(n); } // TODO: delete property_collection const& properties() const { return pimpl->properties; } // TODO: delete feature_collection const& sub_features() const { return pimpl->sub_features; } template <class F> void traverse(F& f) const { f.start(*this); for (auto const& o : pimpl->options) { o.traverse(f); } pimpl->properties.traverse(f); f.end(*this); } }; struct parameter_init { kip::value value; }; inline bool operator==(parameter_init const& lhs, parameter_init const& rhs) { return lhs.value == rhs.value; } inline bool operator!=(parameter_init const& lhs, parameter_init const& rhs) { return !(lhs == rhs); } struct parameter_def_impl { property_collection properties; }; inline bool operator==(parameter_def_impl const& lhs, parameter_def_impl const& rhs) { return lhs.properties == rhs.properties; } inline bool operator!=(parameter_def_impl const& lhs, parameter_def_impl const& rhs) { return !(lhs == rhs); } class parameter_def { xml::qname name_; std::shared_ptr<parameter_def_impl> pimpl; public: parameter_def() {} parameter_def(std::pair<xml::qname, std::shared_ptr<parameter_def_impl>> pd) : name_(pd.first) , pimpl(pd.second) {} parameter_def(xml::qname const& n, std::shared_ptr<parameter_def_impl> p) : name_(n) , pimpl(p) {} bool empty() const { return pimpl == nullptr; } xml::qname const& name() const { return name_; } property property(xml::qname const& n) { return pimpl->properties.find(n); } template <class F> void traverse(F& f) const { f.start(*this); pimpl->properties.traverse(f); f.end(*this); } }; struct print_capabilities_impl { int version; std::string device_namespace; std::string device_namespace_prefix; feature_collection features; property_collection properties; parameter_def_collection parameters; print_capabilities_impl( int v, std::string const& dn, std::string const& pref ) : version(v) , device_namespace(dn) , device_namespace_prefix(pref) {} }; inline bool operator==(print_capabilities_impl const& lhs, print_capabilities_impl const& rhs) { return lhs.version == rhs.version && lhs.device_namespace == rhs.device_namespace && lhs.features == rhs.features && lhs.properties == rhs.properties && lhs.parameters == rhs.parameters; } inline bool operator!=(print_capabilities_impl const& lhs, print_capabilities_impl const& rhs) { return !(lhs == rhs); } class print_capabilities { bool empty_; std::shared_ptr<print_capabilities_impl> pimpl; public: print_capabilities() : empty_(true) , pimpl(std::shared_ptr<print_capabilities_impl>()) {} print_capabilities(std::shared_ptr<print_capabilities_impl> pimpl) : empty_(false) , pimpl(pimpl) {} bool empty() const { return empty_; } int version() const { return pimpl->version; } std::string const& device_namespace() const { return pimpl->device_namespace; } std::string const& device_namespace_prefix() const { return pimpl->device_namespace_prefix; } feature_def feature(xml::qname const& n) { return pimpl->features.find(n); } parameter_def parameter(xml::qname const& n) { return pimpl->parameters.find(n); } feature_collection const& features() const { return pimpl->features; } property_collection const& properties() const { return pimpl->properties; } parameter_def_collection const& parameters() const { return pimpl->parameters; } template <class F> void traverse(F& f) const { f.start(*this); pimpl->features.traverse(f); pimpl->parameters.traverse(f); pimpl->properties.traverse(f); f.end(*this); } }; struct print_ticket_document { int version; feature_collection features; std::unordered_map<xml::qname, property_impl> properties; std::unordered_map<xml::qname, parameter_init> parameters; }; } // namespace kip #endif // KIP_ELEMENTS_HPP_
22.090909
92
0.686103
kei10in
48a5561aa1275dd9a3126832a3e1371e13c8d865
247
hpp
C++
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
1
2016-03-01T14:22:31.000Z
2016-03-01T14:22:31.000Z
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
null
null
null
src/util.hpp
torque-project/rev
245561f9028d65c88029e4a4bc705f6a0a18da4c
[ "MIT" ]
null
null
null
#pragma once namespace rev { inline std::string replace(const std::string& s, char a, char b) { std::string out(s); int pos = 0; while ((pos = out.find(a)) != std::string::npos) { out[pos] = b; } return out; } }
14.529412
68
0.54251
torque-project
48a6b33d998c26470ff236c60ab2f19627b5f541
1,563
cpp
C++
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
3
2019-07-16T13:19:50.000Z
2020-01-06T10:42:23.000Z
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
15
2018-12-11T14:00:48.000Z
2021-12-21T17:42:42.000Z
src/c/rfc822/CMessageParser.cpp
readdle/mailcore2
cf95a1587cebd5b2257e6b6fa0e34149a4d70394
[ "BSD-3-Clause" ]
2
2015-05-26T18:07:22.000Z
2017-04-04T10:01:17.000Z
#include "CMessageParser.h" #include "CBase+Private.h" #include <MailCore/MCCore.h> #include <MailCore/MCDefines.h> #include <MailCore/MCAttachment.h> #include <MailCore/MCMessageHeader.h> #include <MailCore/MCHTMLRenderer.h> #include <MailCore/MCHTMLBodyRendererTemplateCallback.h> #include "CData.h" #include "CAbstractMessageRendererCallback.h" #include "CAbstractMessageRendererCallbackWrapper.h" #define nativeType mailcore::MessageParser #define structName CMessageParser C_SYNTHESIZE_CONSTRUCTOR() C_SYNTHESIZE_COBJECT_CAST() CMessageParser CMessageParser_init(CData data) { return CMessageParser_new(new mailcore::MessageParser(data.instance)); } C_SYNTHESIZE_FUNC_WITH_OBJ(CAbstractPart, mainPart) C_SYNTHESIZE_FUNC_WITH_OBJ(CData, data) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, htmlBodyRendering) C_SYNTHESIZE_FUNC_WITH_OBJ(MailCoreString, plainTextRendering) C_SYNTHESIZE_FUNC_WITH_OBJ(CDictionary, serializable) MailCoreString CMessageParser_plainTextBodyRenderingAndStripWhitespace(struct CMessageParser self, bool stripWhitespace) { return MailCoreString_new(self.instance->plainTextBodyRendering(stripWhitespace)); } MailCoreString CMessageParser_htmlRendering(struct CMessageParser self, struct CAbstractMessageRendererCallback htmlCallback) { return MailCoreString_new(self.instance->htmlRendering(static_cast<mailcore::HTMLRendererTemplateCallback*>(htmlCallback.callbackBridge))); } void CMessageParser_saveToFile(struct CMessageParser self, MailCoreString fileName) { self.instance->saveToFile(fileName.instance); }
36.348837
143
0.849648
readdle
48a8070872b2db78c4ef2c254d17a73283de9be7
514
cpp
C++
Codeforces/A_448.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
Codeforces/A_448.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
Codeforces/A_448.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { int n, sum = 0, temp, shelves = 0; for (int i = 0; i < 3; i++) { scanf("%d", &temp); sum += temp; } shelves += sum / 5; if (sum % 5 != 0) shelves++; sum = 0; for (int i = 0; i < 3; i++) { scanf("%d", &temp); sum += temp; } shelves += sum / 10; if (sum % 10 != 0) shelves++; scanf("%d", &n); if (shelves > n) printf("NO"); else printf("YES"); return 0; }
17.724138
38
0.383268
ahakouz17
48a8472b0de1d1e4264a77a96151090f3bc491c7
193
cpp
C++
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
kattis/zoo/zoo.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
1
2020-10-25T05:46:57.000Z
2020-10-25T05:46:57.000Z
#include <iostream> #include <string> using namespace std; int main() { int n; string cin >> n; while (n > 0) { for (int i = 0; i < n; i++) cin >> n; } }
12.866667
35
0.455959
pi-guy-in-the-sky
48a97b4775396932a785c0deb33655b5fac7b3b7
4,856
cpp
C++
gsa/wit/COIN/Bcp/TM/BCP_tm_node.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/Bcp/TM/BCP_tm_node.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/Bcp/TM/BCP_tm_node.cpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2000, International Business Machines // Corporation and others. All Rights Reserved. #include "BCP_tm.hpp" #include "BCP_tm_user.hpp" #include "BCP_tm_node.hpp" #include "BCP_node_change.hpp" //############################################################################# BCP_tm_node::~BCP_tm_node() { delete _desc; delete lp; delete cg; delete vg; delete cp; delete vp; } //############################################################################# int BCP_tm_node::mark_descendants_for_deletion() { int del_num = child_num(); if (del_num > 0) { BCP_vec<BCP_tm_node*>::iterator child = _children.begin(); BCP_vec<BCP_tm_node*>::const_iterator lastchild = _children.end(); while (child != lastchild) { del_num += (*child)->mark_descendants_for_deletion(); (*child)->_index = -1; ++child; } _children.clear(); } return del_num; } //############################################################################# // This member function counts for every serch tree node the number of // descendants and that how many of them are pruned already / currently being // processed. (This includes the node itself.) void BCP_tree::enumerate_leaves(BCP_tm_node* node, const double obj_limit) { if (node->child_num() == 0) { const BCP_tm_node_status st = node->status; node->_leaf_num = 1; node->_processed_leaf_num = st == BCP_ActiveNode ? 1 : 0; const bool is_pruned = ( st == BCP_PrunedNode_OverUB || st == BCP_PrunedNode_Infeas || st == BCP_PrunedNode_Discarded ); node->_pruned_leaf_num = is_pruned ? 1 : 0; const bool is_next_phase = ( st == BCP_NextPhaseNode_OverUB || st == BCP_NextPhaseNode_Infeas ); node->_tobepriced_leaf_num = ( ((st & (BCP_ProcessedNode | BCP_ActiveNode | BCP_CandidateNode)) && node->true_lower_bound() > obj_limit) || is_next_phase ) ? 1 : 0; } else { node->_leaf_num = 0; node->_processed_leaf_num = 0; node->_pruned_leaf_num = 0; node->_tobepriced_leaf_num = 0; BCP_vec<BCP_tm_node*>::iterator child; BCP_vec<BCP_tm_node*>::const_iterator lastchild = node->_children.end(); for (child = node->_children.begin(); child != lastchild; ++child) { this->enumerate_leaves(*child, obj_limit); node->_processed_leaf_num += (*child)->_processed_leaf_num; node->_pruned_leaf_num += (*child)->_pruned_leaf_num; node->_tobepriced_leaf_num += (*child)->_tobepriced_leaf_num; node->_leaf_num += (*child)->_leaf_num; } } } //############################################################################# // Find the best lower bound double BCP_tree::true_lower_bound(const BCP_tm_node* node) const { double worstlb = DBL_MAX; if (node->child_num() == 0) { const BCP_tm_node_status st = node->status; if (st == BCP_ActiveNode || st == BCP_CandidateNode) worstlb = node->true_lower_bound(); } else { BCP_vec<BCP_tm_node*>::const_iterator child; BCP_vec<BCP_tm_node*>::const_iterator lastchild = node->_children.end(); for (child = node->_children.begin(); child != lastchild; ++child) { const double childlb = true_lower_bound(*child); if (childlb < worstlb) worstlb = childlb; } } return worstlb; } //############################################################################# void BCP_node_queue::pop() { BCP_tm_node* node = _pq.back(); _pq.pop_back(); const int size = _pq.size(); if (size > 0) { int pos = 1; int ch; for (ch = 2; ch < size - 1; pos = ch, ch *= 2) { if (_p.user->compare_tree_nodes(_pq[ch+1], _pq[ch])) ++ch; if (_p.user->compare_tree_nodes(node, _pq[ch])) break; _pq[pos] = _pq[ch]; } if (ch == size - 1) { if (_p.user->compare_tree_nodes(_pq[ch], node)) { _pq[pos] = _pq[ch]; pos = ch; } } _pq[pos] = node; } } //============================================================================= void BCP_node_queue::insert(BCP_tm_node* node) { int pos = _pq.size(); int ch; _pq.push_back(node); for (ch = pos/2; ch != 0; pos = ch, ch /= 2) { if (_p.user->compare_tree_nodes(_pq[ch], node)) break; _pq[pos] = _pq[ch]; } _pq[pos] = node; } //============================================================================= void BCP_node_queue::compare_to_UB(int& quality_above_UB, int& quality_below_UB) { quality_above_UB = quality_below_UB = 0; const int size = _pq.size(); if (! _p.has_ub()) { quality_below_UB = size; return; } const double threshold = _p.ub() - _p.granularity(); for (int i = 1; i < size; ++i) { if (_pq[i]->quality() <= threshold) { ++quality_below_UB; } else { ++quality_above_UB; } } } //#############################################################################
30.161491
79
0.55416
kant
48aa101eddb97f962211341a51bb8ad0a307b828
2,787
cpp
C++
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
24
2019-10-14T14:35:32.000Z
2021-11-28T02:06:26.000Z
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
3
2019-10-14T14:29:07.000Z
2020-01-21T14:48:49.000Z
test/net/test_address_manager.cpp
EPI-ONE/epic
c314cab526641c00d49e51e08ec0793f1a6c171b
[ "MIT" ]
4
2020-04-09T09:12:50.000Z
2021-06-15T13:41:42.000Z
// Copyright (c) 2019 EPI-ONE Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <gtest/gtest.h> #include "address_manager.h" class TestAddressManager : public testing::Test { public: AddressManager addressManager; std::string addressFilePath = "test_address.toml"; NetAddress ip1 = *NetAddress::GetByIP("127.0.0.1:7877"); NetAddress ip2 = *NetAddress::GetByIP("192.168.0.1:7877"); NetAddress ip3 = *NetAddress::GetByIP("100.0.0.4:7877"); NetAddress ip4 = *NetAddress::GetByIP("172.4.2.111:7877"); void SetUp() { addressManager.AddNewAddress(ip1); addressManager.AddNewAddress(ip2); addressManager.AddNewAddress(ip3); addressManager.AddNewAddress(ip4); } void TearDown() { addressManager.Clear(); } }; TEST_F(TestAddressManager, BasicOp) { EXPECT_TRUE(addressManager.IsNew(ip1)); EXPECT_TRUE(addressManager.IsNew(ip2)); EXPECT_TRUE(addressManager.IsNew(ip3)); EXPECT_TRUE(addressManager.IsNew(ip4)); addressManager.MarkOld(ip1); addressManager.MarkOld(ip2); EXPECT_TRUE(addressManager.IsOld(ip1)); EXPECT_TRUE(addressManager.IsOld(ip2)); EXPECT_FALSE(addressManager.IsNew(ip1)); EXPECT_FALSE(addressManager.IsNew(ip2)); EXPECT_TRUE(addressManager.ContainAddress(ip1)); EXPECT_TRUE(addressManager.ContainAddress(ip2)); EXPECT_TRUE(addressManager.ContainAddress(ip3)); EXPECT_TRUE(addressManager.ContainAddress(ip4)); } TEST_F(TestAddressManager, GetAddr) { auto addresses = addressManager.GetAddresses(); EXPECT_EQ(addresses.size(), 4); addressManager.MarkOld(ip1); addressManager.MarkOld(ip2); auto res = addressManager.GetOneAddress(true); EXPECT_TRUE(addressManager.IsNew(*res)); } TEST_F(TestAddressManager, SaveAndLoad) { addressManager.SaveAddress("./", addressFilePath); addressManager.Clear(); addressManager.LoadAddress("./", addressFilePath); std::remove(addressFilePath.c_str()); EXPECT_EQ(addressManager.SizeOfAllAddr(), 4); } TEST_F(TestAddressManager, LocalAddr) { addressManager.LoadLocalAddresses(); EXPECT_TRUE(addressManager.IsLocal(ip1)); } TEST_F(TestAddressManager, DeleteInactiveAddr) { CONFIG = std::make_unique<Config>(); addressManager.SaveAddress("./", addressFilePath); for (int i = 0; i < CONFIG->GetMaxFailedAttempts() + 1; i++) { addressManager.SetLastTry(ip4, time(nullptr)); } addressManager.SaveAddress("./", addressFilePath); addressManager.Clear(); addressManager.LoadAddress("./", addressFilePath); std::remove(addressFilePath.c_str()); EXPECT_FALSE(addressManager.ContainAddress(ip4)); }
31.314607
70
0.717976
EPI-ONE
48abc277e66474d520ca9e1938c3ea96b918c2eb
1,484
cpp
C++
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
8
2016-06-05T19:19:27.000Z
2019-05-14T10:33:37.000Z
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
2
2017-02-21T12:38:27.000Z
2018-01-28T20:05:00.000Z
cpp/segment_trees/segtree2d_min.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
6
2015-12-26T21:12:17.000Z
2022-03-26T21:40:17.000Z
class segtree{ public: int n; // array size vector<int> t; void build(vector<int> &v) { // build the tree for (int i = n; i < 2 * n; i++) t[i] = v[i - n]; for (int i = n - 1; i > 0; --i) t[i] = min(t[i<<1], t[i<<1|1]); } void build(segtree &t1, segtree &t2) { // build the tree for (int i = 1; i < 2 * n; i++) t[i] = min(t1.t[i], t2.t[i]); } int query(int l, int r) { // sum on interval [l, r) int res = 2e9; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res = min(res, t[l++]); if (r&1) res = min(res, t[--r]); } return res; } segtree(int n):n(n),t(){ t.resize(n << 1); } }; class segtree2{ public: int n, m; // array size vector<segtree> t; void build(vector<vector<int> > &v) { // build the tree for (int i = 0; i < n; i++) { t[n + i].build(v[i]); } for (int i = n - 1; i > 0; i--) { t[i].build(t[i * 2], t[i * 2 + 1]); } } int query(int d, int l, int u, int r) { // sum on interval [l, r) int res = 2e9; for (d += n, u += n; d < u; d >>= 1, u >>= 1) { if (d&1) res = min(res, t[d++].query(l, r)); if (u&1) res = min(res, t[--u].query(l, r)); } return res; } segtree2(int n, int m, vector<vector<int> > &v):n(n),m(m),t(){ t.assign(n << 1, segtree(m)); build(v); } };
26.035088
71
0.402291
petuhovskiy
48ac16a9362fecb2a66229ae8ae4449c8816d748
1,002
cpp
C++
Benchmarks/UnorderedMap/UMapAllocBench.cpp
adamhutchings/HackySTL
624a0cdc92b297f52588190d3a693d6923b7a4e7
[ "MIT" ]
33
2020-11-20T14:58:25.000Z
2022-03-04T10:04:08.000Z
Benchmarks/UnorderedMap/UMapAllocBench.cpp
adamhutchings/HackySTL
624a0cdc92b297f52588190d3a693d6923b7a4e7
[ "MIT" ]
8
2021-01-05T23:18:32.000Z
2022-02-22T18:25:37.000Z
Benchmarks/UnorderedMap/UMapAllocBench.cpp
HackyTeam/HackySTL
2496c7e110a218d09c73005b5a39d15b380ce354
[ "MIT" ]
6
2021-01-05T22:02:57.000Z
2022-02-22T18:34:22.000Z
#include <benchmark/benchmark.h> #include "../../cpp/UnorderedMap.hpp" static void MapBufAlloc(benchmark::State& state) { hsd::uchar buf[4096]{}; for(auto _ : state) { hsd::buffered_allocator<hsd::uchar> alloc{buf, 4096}; hsd::unordered_map<size_t, size_t, hsd::hash<size_t, size_t>, hsd::buffered_allocator> map{alloc}; [&]<size_t... Ints>(hsd::index_sequence<Ints...>) { (map.emplace(Ints, Ints), ...); }(hsd::make_index_sequence<14>{}); benchmark::DoNotOptimize(map.begin()); } } static void MapHeapAlloc(benchmark::State& state) { for(auto _ : state) { hsd::unordered_map<size_t, size_t, hsd::hash<size_t, size_t>> map; [&]<size_t... Ints>(hsd::index_sequence<Ints...>) { (map.emplace(Ints, Ints), ...); }(hsd::make_index_sequence<14>{}); benchmark::DoNotOptimize(map.begin()); } } BENCHMARK(MapBufAlloc); BENCHMARK(MapHeapAlloc); BENCHMARK_MAIN();
24.439024
106
0.5998
adamhutchings
48b1be830bec6aabb243a2c8faf705c2ee737be9
3,784
cpp
C++
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
src/reconstruct/weno5.cpp
luminoctum/athena-crm
525ad5d1c442f9f6d66f2307eed88cd6fb723810
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file plm.cpp // \brief piecewise linear reconstruction // Athena++ headers #include "reconstruction.hpp" #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../hydro/hydro.hpp" #include "../mesh/mesh.hpp" #include "../coordinates/coordinates.hpp" // WENO 5 interpolation inline Real interp_weno5(Real phim2, Real phim1, Real phi, Real phip1, Real phip2) { Real p0 = (1.0/3.0)*phim2 - (7.0/6.0)*phim1 + (11.0/6.0)*phi; Real p1 = (-1.0/6.0) * phim1 + (5.0/6.0)*phi + (1.0/3.0)*phip1; Real p2 = (1.0/3.0) * phi + (5.0/6.0)*phip1 - (1.0/6.0)*phip2; Real beta2 = (13.0/12.0 * (phi - 2.0 * phip1 + phip2)*(phi - 2.0 * phip1 + phip2) + 0.25 * (3.0 * phi - 4.0 * phip1 + phip2)*(3.0 * phi - 4.0 * phip1 + phip2)); Real beta1 = (13.0/12.0 * (phim1 - 2.0 * phi + phip1)*(phim1 - 2.0 * phi + phip1) + 0.25 * (phim1 - phip1)*(phim1 - phip1)); Real beta0 = (13.0/12.0 * (phim2 - 2.0 * phim1 + phi)*(phim2 - 2.0 * phim1 + phi) + 0.25 * (phim2 - 4.0 * phim1 + 3.0 * phi)*(phim2 - 4.0 * phim1 + 3.0 * phi)); Real alpha0 = 0.1/((beta0 + 1e-10) * (beta0 + 1e-10)); Real alpha1 = 0.6/((beta1 + 1e-10) * (beta1 + 1e-10)); Real alpha2 = 0.3/((beta2 + 1e-10) * (beta2 + 1e-10)); Real alpha_sum_inv = 1.0/(alpha0 + alpha1 + alpha2); Real w0 = alpha0 * alpha_sum_inv; Real w1 = alpha1 * alpha_sum_inv; Real w2 = alpha2 * alpha_sum_inv; return w0 * p0 + w1 * p1 + w2 * p2; }; //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX1() // \brief void Reconstruction::HighResFuncX1(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k,j,i-3),q(n,k,j,i-2),q(n,k,j,i-1),q(n,k,j,i),q(n,k,j,i+1)); qr(n,i) = interp_weno5(q(n,k,j,i+2),q(n,k,j,i+1),q(n,k,j,i),q(n,k,j,i-1),q(n,k,j,i-2)); } } return; } //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX2() // \brief void Reconstruction::HighResFuncX2(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k,j-3,i),q(n,k,j-2,i),q(n,k,j-1,i),q(n,k,j,i),q(n,k,j+1,i)); qr(n,i) = interp_weno5(q(n,k,j+2,i),q(n,k,j+1,i),q(n,k,j,i),q(n,k,j-1,i),q(n,k,j-2,i)); } } return; } //---------------------------------------------------------------------------------------- //! \fn Reconstruction::ReconstructionFuncX3() // \brief void Reconstruction::HighResFuncX3(const int k, const int j, const int il, const int iu, const AthenaArray<Real> &q, const AthenaArray<Real> &bcc, AthenaArray<Real> &ql, AthenaArray<Real> &qr) { for (int n=0; n<NHYDRO; ++n) { #pragma simd for (int i=il; i<=iu; ++i){ ql(n,i) = interp_weno5(q(n,k-3,j,i),q(n,k-2,j,i),q(n,k-1,j,i),q(n,k,j,i),q(n,k,j,i+1)); qr(n,i) = interp_weno5(q(n,k+2,j,i),q(n,k+1,j,i),q(n,k,j,i),q(n,k-1,j,i),q(n,k-2,j,i)); } } return; }
37.098039
102
0.512421
luminoctum
48b479477ca9590c872460097b8fe6e1d43c6f40
34,695
cc
C++
src/GaIA/pkgs/nmap/nmap-6.40/portlist.cc
uninth/UNItools
c8b1fbfd5d3753b5b14fa19033e39737dedefc00
[ "BSD-3-Clause" ]
null
null
null
src/GaIA/pkgs/nmap/nmap-6.40/portlist.cc
uninth/UNItools
c8b1fbfd5d3753b5b14fa19033e39737dedefc00
[ "BSD-3-Clause" ]
null
null
null
src/GaIA/pkgs/nmap/nmap-6.40/portlist.cc
uninth/UNItools
c8b1fbfd5d3753b5b14fa19033e39737dedefc00
[ "BSD-3-Clause" ]
1
2021-06-08T15:59:26.000Z
2021-06-08T15:59:26.000Z
/*************************************************************************** * portlist.cc -- Functions for manipulating various lists of ports * * maintained internally by Nmap. * * * ***********************IMPORTANT NMAP LICENSE TERMS************************ * * * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * * also a registered trademark of Insecure.Com LLC. This program is free * * software; you may redistribute and/or modify it under the terms of the * * GNU General Public License as published by the Free Software * * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS * * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, * * modify, and redistribute this software under certain conditions. If * * you wish to embed Nmap technology into proprietary software, we sell * * alternative licenses (contact sales@insecure.com). Dozens of software * * vendors already license Nmap technology such as host discovery, port * * scanning, OS detection, version detection, and the Nmap Scripting * * Engine. * * * * Note that the GPL places important restrictions on "derivative works", * * yet it does not provide a detailed definition of that term. To avoid * * misunderstandings, we interpret that term as broadly as copyright law * * allows. For example, we consider an application to constitute a * * derivative work for the purpose of this license if it does any of the * * following with any software or content covered by this license * * ("Covered Software"): * * * * o Integrates source code from Covered Software. * * * * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db * * or nmap-service-probes. * * * * o Is designed specifically to execute Covered Software and parse the * * results (as opposed to typical shell or execution-menu apps, which will * * execute anything you tell them to). * * * * o Includes Covered Software in a proprietary executable installer. The * * installers produced by InstallShield are an example of this. Including * * Nmap with other software in compressed or archival form does not * * trigger this provision, provided appropriate open source decompression * * or de-archiving software is widely available for no charge. For the * * purposes of this license, an installer is considered to include Covered * * Software even if it actually retrieves a copy of Covered Software from * * another source during runtime (such as by downloading it from the * * Internet). * * * * o Links (statically or dynamically) to a library which does any of the * * above. * * * * o Executes a helper program, module, or script to do any of the above. * * * * This list is not exclusive, but is meant to clarify our interpretation * * of derived works with some common examples. Other people may interpret * * the plain GPL differently, so we consider this a special exception to * * the GPL that we apply to Covered Software. Works which meet any of * * these conditions must conform to all of the terms of this license, * * particularly including the GPL Section 3 requirements of providing * * source code and allowing free redistribution of the work as a whole. * * * * As another special exception to the GPL terms, Insecure.Com LLC grants * * permission to link the code of this program with any version of the * * OpenSSL library which is distributed under a license identical to that * * listed in the included docs/licenses/OpenSSL.txt file, and distribute * * linked combinations including the two. * * * * Any redistribution of Covered Software, including any derived works, * * must obey and carry forward all of the terms of this license, including * * obeying all GPL rules and restrictions. For example, source code of * * the whole work must be provided and free redistribution must be * * allowed. All GPL references to "this License", are to be treated as * * including the special and conditions of the license text as well. * * * * Because this license imposes special exceptions to the GPL, Covered * * Work may not be combined (even as part of a larger work) with plain GPL * * software. The terms, conditions, and exceptions of this license must * * be included as well. This license is incompatible with some other open * * source licenses as well. In some cases we can relicense portions of * * Nmap or grant special permissions to use it in other open source * * software. Please contact fyodor@nmap.org with any such requests. * * Similarly, we don't incorporate incompatible open source software into * * Covered Software without special permission from the copyright holders. * * * * If you have any questions about the licensing restrictions on using * * Nmap in other works, are happy to help. As mentioned above, we also * * offer alternative license to integrate Nmap into proprietary * * applications and appliances. These contracts have been sold to dozens * * of software vendors, and generally include a perpetual license as well * * as providing for priority support and updates. They also fund the * * continued development of Nmap. Please email sales@insecure.com for * * further information. * * * * If you received these files with a written license agreement or * * contract stating terms other than the terms above, then that * * alternative license agreement takes precedence over these comments. * * * * Source is provided to this software because we believe users have a * * right to know exactly what a program is going to do before they run it. * * This also allows you to audit the software for security holes (none * * have been found so far). * * * * Source code also allows you to port Nmap to new platforms, fix bugs, * * and add new features. You are highly encouraged to send your changes * * to the dev@nmap.org mailing list for possible incorporation into the * * main distribution. By sending these changes to Fyodor or one of the * * Insecure.Org development mailing lists, or checking them into the Nmap * * source code repository, it is understood (unless you specify otherwise) * * that you are offering the Nmap Project (Insecure.Com LLC) the * * unlimited, non-exclusive right to reuse, modify, and relicense the * * code. Nmap will always be available Open Source, but this is important * * because the inability to relicense code has caused devastating problems * * for other Free Software projects (such as KDE and NASM). We also * * occasionally relicense the code to third parties as discussed above. * * If you wish to specify special license conditions of your * * contributions, just say so when you send them. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap * * license file for more details (it's in a COPYING file included with * * Nmap, and also available from https://svn.nmap.org/nmap/COPYING * * * ***************************************************************************/ /* $Id: portlist.cc 31563 2013-07-28 22:08:48Z fyodor $ */ #include "nmap.h" #include "portlist.h" #include "nmap_error.h" #include "NmapOps.h" #include "services.h" #include "protocols.h" #include "tcpip.h" #include "libnetutil/netutil.h" #if HAVE_STRINGS_H #include <strings.h> #endif /* HAVE_STRINGS_H */ extern NmapOps o; /* option structure */ Port::Port() { portno = proto = 0; state = 0; service = NULL; state_reason_init(&reason); } void Port::freeService(bool del_service) { if (service != NULL) { std::vector<char *>::iterator it; if (service->name) free(service->name); if (service->product) free(service->product); if (service->version) free(service->version); if (service->extrainfo) free(service->extrainfo); if (service->hostname) free(service->hostname); if (service->ostype) free(service->ostype); if (service->devicetype) free(service->devicetype); if (service->service_fp) free(service->service_fp); for (it = service->cpe.begin(); it != service->cpe.end(); it++) free(*it); service->cpe.clear(); if (del_service) delete service; } } void Port::freeScriptResults(void) { #ifndef NOLUA while (!scriptResults.empty()) { scriptResults.front().clear(); scriptResults.pop_front(); } #endif } /* Fills in namebuf (as long as there is space in buflen) with the Name nmap normal output will use to describe the port. This takes into account to confidence level, any SSL tunneling, etc. Truncates namebuf to 0 length if there is no room.*/ void Port::getNmapServiceName(char *namebuf, int buflen) const { const char *tunnel_prefix; const char *service_name; int len; if (service != NULL && service->service_tunnel == SERVICE_TUNNEL_SSL) tunnel_prefix = "ssl/"; else tunnel_prefix = ""; if (service != NULL && service->name != NULL) { service_name = service->name; } else { struct servent *service; service = nmap_getservbyport(portno, IPPROTO2STR(proto)); if (service != NULL) service_name = service->s_name; else service_name = NULL; } if (service_name != NULL && strcmp(service_name, "unknown") != 0) { /* The port has a name and the name is not "unknown". How confident are we? */ if (o.servicescan && state == PORT_OPEN && (service == NULL || service->name_confidence <= 5)) len = Snprintf(namebuf, buflen, "%s%s?", tunnel_prefix, service_name); else len = Snprintf(namebuf, buflen, "%s%s", tunnel_prefix, service_name); } else { len = Snprintf(namebuf, buflen, "%sunknown", tunnel_prefix); } if (len >= buflen || len < 0) { namebuf[0] = '\0'; return; } } serviceDeductions::serviceDeductions() { name = NULL; name_confidence = 0; product = NULL; version = NULL; extrainfo = NULL; hostname = NULL; ostype = NULL; devicetype = NULL; service_tunnel = SERVICE_TUNNEL_NONE; service_fp = NULL; dtype = SERVICE_DETECTION_TABLE; } // Uses the sd->{product,version,extrainfo} if available to fill // out sd->fullversion. If unavailable, it will be set to zero length. void serviceDeductions::populateFullVersionString(char *buf, size_t n) const { char *dst = buf; unsigned int spaceleft = n - 1; // Leave room for \0 int needpad = 0; // Do we need to pad a space between the next template? dst[0] = '\0'; /* Sometimes there is really great product/version/extra information * available that won't quite fit. Rather than just drop that information * this routine will truncate the string that is too long with "...". * If there are fewer than 8 characters left don't bother and just skip * that bit of information. */ if (product && spaceleft >= 8) { if (spaceleft < strlen(product)) { strncat(dst, product, spaceleft - 3); // Leave room for "..." strncat(dst, "...", spaceleft); spaceleft = 0; } else { strncat(dst, product, spaceleft); spaceleft -= strlen(product); } needpad = 1; } if (version && spaceleft >= 8) { if (needpad) { strncat(dst, " ", spaceleft); spaceleft--; } if (spaceleft < strlen(version)) { strncat(dst, version, spaceleft - 3); strncat(dst, "...", spaceleft); spaceleft = 0; } else { strncat(dst, version, spaceleft); spaceleft -= strlen(version); } needpad = 1; } if (extrainfo && spaceleft >= 8) { if (needpad) { strncat(dst, " ", spaceleft); spaceleft--; } // This time we need to trucate inside of the () so we have spaceleft - 2 strncat(dst, "(", spaceleft); if (spaceleft - 2 < strlen(extrainfo)) { strncat(dst, extrainfo, spaceleft - 5); strncat(dst, "...", spaceleft - 2); spaceleft = 1; // Fit the paren } else { strncat(dst, extrainfo, spaceleft); spaceleft -= (strlen(extrainfo) + 2); } strncat(dst, ")", spaceleft); spaceleft--; } } // pass in an allocated struct serviceDeductions (don't worry about // initializing, and you don't have to free any internal ptrs. See the // serviceDeductions definition for the fields that are populated. // Returns 0 if at least a name is available. void PortList::getServiceDeductions(u16 portno, int protocol, struct serviceDeductions *sd) const { const Port *port; port = lookupPort(portno, protocol); if (port == NULL || port->service == NULL) { struct servent *service; /* Look up the service name. */ *sd = serviceDeductions(); service = nmap_getservbyport(portno, IPPROTO2STR(protocol)); if (service != NULL) sd->name = service->s_name; else sd->name = NULL; sd->name_confidence = 3; } else { *sd = *port->service; } } // sname should be NULL if sres is not // PROBESTATE_FINISHED_MATCHED. product,version, and/or extrainfo // will be NULL if unavailable. Note that this function makes its // own copy of sname and product/version/extrainfo. This function // also takes care of truncating the version strings to a // 'reasonable' length if necessary, and cleaning up any unprintable // chars. (these tests are to avoid annoying DOS (or other) attacks // by malicious services). The fingerprint should be NULL unless // one is available and the user should submit it. tunnel must be // SERVICE_TUNNEL_NULL (normal) or SERVICE_TUNNEL_SSL (means ssl was // detected and we tried to tunnel through it ). static char *cstringSanityCheck(const char* string, int len) { char *result; int slen; if(!string) return NULL; slen = strlen(string); if (slen > len) slen = len; result = (char *) safe_malloc(slen + 1); memcpy(result, string, slen); result[slen] = '\0'; replacenonprintable(result, slen, '.'); return result; } void PortList::setServiceProbeResults(u16 portno, int protocol, enum serviceprobestate sres, const char *sname, enum service_tunnel_type tunnel, const char *product, const char *version, const char *extrainfo, const char *hostname, const char *ostype, const char *devicetype, const std::vector<const char *> *cpe, const char *fingerprint) { std::vector<char *>::iterator it; Port *port; char *p; port = createPort(portno, protocol); if (port->service == NULL) port->service = new serviceDeductions; if (sres == PROBESTATE_FINISHED_HARDMATCHED || sres == PROBESTATE_FINISHED_SOFTMATCHED) { port->service->dtype = SERVICE_DETECTION_PROBED; port->service->name_confidence = 10; } else if (sres == PROBESTATE_FINISHED_TCPWRAPPED) { port->service->dtype = SERVICE_DETECTION_PROBED; if (sname == NULL) sname = "tcpwrapped"; port->service->name_confidence = 8; } else { /* PROBESTATE_FINISHED_NOMATCH, PROBESTATE_EXCLUDED, PROBESTATE_INCOMPLETE. Just look up the service name if none is provided. */ if (sname == NULL) { struct servent *service; service = nmap_getservbyport(portno, IPPROTO2STR(protocol)); if (service != NULL) sname = service->s_name; } port->service->dtype = SERVICE_DETECTION_TABLE; port->service->name_confidence = 3; // Since we didn't even check it, we aren't very confident } // port->serviceprobe_results = sres; port->service->service_tunnel = tunnel; port->freeService(false); if (sname) port->service->name = strdup(sname); else port->service->name = NULL; if (fingerprint) port->service->service_fp = strdup(fingerprint); else port->service->service_fp = NULL; port->service->product = cstringSanityCheck(product, 80); port->service->version = cstringSanityCheck(version, 80); port->service->extrainfo = cstringSanityCheck(extrainfo, 256); port->service->hostname = cstringSanityCheck(hostname, 80); port->service->ostype = cstringSanityCheck(ostype, 32); port->service->devicetype = cstringSanityCheck(devicetype, 32); if (cpe) { std::vector<const char *>::const_iterator cit; for (cit = cpe->begin(); cit != cpe->end(); cit++) { p = cstringSanityCheck(*cit, 80); if (p != NULL) port->service->cpe.push_back(p); } } } #ifndef NOLUA void PortList::addScriptResult(u16 portno, int protocol, ScriptResult& sr) { Port *port; port = createPort(portno, protocol); port->scriptResults.push_back(sr); } #endif /*****************************************************************************/ /* Convert protocol name from in.h to enum portlist_proto. * So IPPROTO_TCP will be changed to PORTLIST_PROTO_TCP and so on. */ #define INPROTO2PORTLISTPROTO(p) \ ((p)==IPPROTO_TCP ? PORTLIST_PROTO_TCP : \ (p)==IPPROTO_UDP ? PORTLIST_PROTO_UDP : \ (p)==IPPROTO_SCTP ? PORTLIST_PROTO_SCTP : \ PORTLIST_PROTO_IP) #define PORTLISTPROTO2INPROTO(p) \ ((p)==PORTLIST_PROTO_TCP ? IPPROTO_TCP : \ (p)==PORTLIST_PROTO_UDP ? IPPROTO_UDP : \ (p)==PORTLIST_PROTO_SCTP ? IPPROTO_SCTP : \ IPPROTO_IP) PortList::PortList() { int proto; memset(state_counts_proto, 0, sizeof(state_counts_proto)); memset(port_list, 0, sizeof(port_list)); for(proto=0; proto < PORTLIST_PROTO_MAX; proto++) { if(port_list_count[proto] > 0) port_list[proto] = (Port**) safe_zalloc(sizeof(Port*)*port_list_count[proto]); default_port_state[proto].proto = PORTLISTPROTO2INPROTO(proto); default_port_state[proto].reason.reason_id = ER_NORESPONSE; state_counts_proto[proto][default_port_state[proto].state] = port_list_count[proto]; } numscriptresults = 0; idstr = NULL; } PortList::~PortList() { int proto, i; if (idstr) { free(idstr); idstr = NULL; } for(proto=0; proto < PORTLIST_PROTO_MAX; proto++) { // for every protocol if(port_list[proto]) { for(i=0; i < port_list_count[proto]; i++) { // free every Port if(port_list[proto][i]) { port_list[proto][i]->freeService(true); port_list[proto][i]->freeScriptResults(); delete port_list[proto][i]; } } free(port_list[proto]); } } } void PortList::setDefaultPortState(u8 protocol, int state) { int proto = INPROTO2PORTLISTPROTO(protocol); int i; for (i = 0; i < port_list_count[proto]; i++) { if (port_list[proto][i] == NULL) { state_counts_proto[proto][default_port_state[proto].state]--; state_counts_proto[proto][state]++; } } default_port_state[proto].state = state; } void PortList::setPortState(u16 portno, u8 protocol, int state) { const Port *oldport; Port *current; int proto = INPROTO2PORTLISTPROTO(protocol); assert(state < PORT_HIGHEST_STATE); if ((state == PORT_OPEN && o.verbose) || (o.debugging > 1)) { log_write(LOG_STDOUT, "Discovered %s port %hu/%s%s\n", statenum2str(state), portno, proto2ascii_lowercase(protocol), idstr? idstr : ""); log_flush(LOG_STDOUT); } /* Make sure state is OK */ if (state != PORT_OPEN && state != PORT_CLOSED && state != PORT_FILTERED && state != PORT_UNFILTERED && state != PORT_OPENFILTERED && state != PORT_CLOSEDFILTERED) fatal("%s: attempt to add port number %d with illegal state %d\n", __func__, portno, state); assert(protocol!=IPPROTO_IP || portno<256); oldport = lookupPort(portno, protocol); if (oldport != NULL) { /* We must discount our statistics from the old values. Also warn if a complete duplicate */ if (o.debugging && oldport->state == state) { error("Duplicate port (%hu/%s)", portno, proto2ascii_lowercase(protocol)); } state_counts_proto[proto][oldport->state]--; } else { state_counts_proto[proto][default_port_state[proto].state]--; } current = createPort(portno, protocol); current->state = state; state_counts_proto[proto][state]++; if(state == PORT_FILTERED || state == PORT_OPENFILTERED) setStateReason(portno, protocol, ER_NORESPONSE, 0, NULL); return; } int PortList::getPortState(u16 portno, u8 protocol) { const Port *port; port = lookupPort(portno, protocol); if (port == NULL) return default_port_state[INPROTO2PORTLISTPROTO(protocol)].state; return port->state; } /* Return true if nothing special is known about this port; i.e., it's in the default state as defiend by setDefaultPortState and every other data field is unset. */ bool PortList::portIsDefault(u16 portno, u8 protocol) { return lookupPort(portno, protocol) == NULL; } /* Saves an identification string for the target containing these ports (an IP address might be a good example, but set what you want). Only used when printing new port updates. Optional. A copy is made. */ void PortList::setIdStr(const char *id) { int len = 0; if (idstr) free(idstr); if (!id) { idstr = NULL; return; } len = strlen(id); len += 5; // " on " + \0 idstr = (char *) safe_malloc(len); Snprintf(idstr, len, " on %s", id); } int PortList::getStateCounts(int protocol, int state) const { return state_counts_proto[INPROTO2PORTLISTPROTO(protocol)][state]; } int PortList::getStateCounts(int state) const { int sum=0, proto; for(proto=0; proto < PORTLIST_PROTO_MAX; proto++) sum += getStateCounts(PORTLISTPROTO2INPROTO(proto), state); return(sum); } /* A function for iterating through the ports. Give NULL for the first "afterthisport". Then supply the most recent returned port for each subsequent call. When no more matching ports remain, NULL will be returned. To restrict returned ports to just one protocol, specify IPPROTO_TCP, IPPROTO_UDP or IPPROTO_SCTP for allowed_protocol. A TCPANDUDPANDSCTP for allowed_protocol matches either. A 0 for allowed_state matches all possible states. This function returns ports in numeric order from lowest to highest, except that if you ask for both TCP, UDP & SCTP, every TCP port will be returned before we start returning UDP and SCTP ports */ Port *PortList::nextPort(const Port *cur, Port *next, int allowed_protocol, int allowed_state) { int proto; int mapped_pno; Port *port; if (cur) { proto = INPROTO2PORTLISTPROTO(cur->proto); assert(port_map[proto]!=NULL); // Hmm, it's not posible to handle port that doesn't have anything in map assert(cur->proto!=IPPROTO_IP || cur->portno<256); mapped_pno = port_map[proto][cur->portno]; mapped_pno++; // we're interested in next port after current } else { // running for the first time if (allowed_protocol == TCPANDUDPANDSCTP) proto = INPROTO2PORTLISTPROTO(IPPROTO_TCP); else if (allowed_protocol == UDPANDSCTP) proto = INPROTO2PORTLISTPROTO(IPPROTO_UDP); else proto = INPROTO2PORTLISTPROTO(allowed_protocol); mapped_pno = 0; } if(port_list[proto] != NULL) { for(;mapped_pno < port_list_count[proto]; mapped_pno++) { port = port_list[proto][mapped_pno]; if (port && (allowed_state==0 || port->state==allowed_state)) { *next = *port; return next; } if (!port && (allowed_state==0 || default_port_state[proto].state==allowed_state)) { *next = default_port_state[proto]; next->portno = port_map_rev[proto][mapped_pno]; return next; } } } /* if all protocols, than after TCP search UDP & SCTP */ if((!cur && allowed_protocol == TCPANDUDPANDSCTP) || (cur && proto == INPROTO2PORTLISTPROTO(IPPROTO_TCP))) return(nextPort(NULL, next, UDPANDSCTP, allowed_state)); /* if all protocols, than after UDP search SCTP */ if((!cur && allowed_protocol == UDPANDSCTP) || (cur && proto == INPROTO2PORTLISTPROTO(IPPROTO_UDP))) return(nextPort(NULL, next, IPPROTO_SCTP, allowed_state)); return(NULL); } /* Convert portno and protocol into the internal indices used to index port_list. */ void PortList::mapPort(u16 *portno, u8 *protocol) const { int mapped_portno, mapped_protocol; mapped_protocol = INPROTO2PORTLISTPROTO(*protocol); if (*protocol == IPPROTO_IP) assert(*portno < 256); if(port_map[mapped_protocol]==NULL || port_list[mapped_protocol]==NULL) { fatal("%s(%i,%i): you're trying to access uninitialized protocol", __func__, *portno, *protocol); } mapped_portno = port_map[mapped_protocol][*portno]; assert(mapped_portno < port_list_count[mapped_protocol]); assert(mapped_portno >= 0); *portno = mapped_portno; *protocol = mapped_protocol; } const Port *PortList::lookupPort(u16 portno, u8 protocol) const { mapPort(&portno, &protocol); return port_list[protocol][portno]; } /* Create the port if it doesn't exist; otherwise this is like lookupPort. */ Port *PortList::createPort(u16 portno, u8 protocol) { Port *p; u16 mapped_portno; u8 mapped_protocol; mapped_portno = portno; mapped_protocol = protocol; mapPort(&mapped_portno, &mapped_protocol); p = port_list[mapped_protocol][mapped_portno]; if (p == NULL) { p = new Port(); p->portno = portno; p->proto = protocol; p->state = default_port_state[mapped_protocol].state; p->reason.reason_id = ER_NORESPONSE; port_list[mapped_protocol][mapped_portno] = p; } return port_list[mapped_protocol][mapped_portno]; } int PortList::forgetPort(u16 portno, u8 protocol) { Port *answer = NULL; log_write(LOG_PLAIN, "Removed %d\n", portno); mapPort(&portno, &protocol); answer = port_list[protocol][portno]; if (answer == NULL) return -1; state_counts_proto[protocol][answer->state]--; state_counts_proto[protocol][default_port_state[protocol].state]++; delete answer; port_list[protocol][portno] = NULL; if (o.verbose) { log_write(LOG_STDOUT, "Deleting port %hu/%s, which we thought was %s\n", portno, proto2ascii_lowercase(answer->proto), statenum2str(answer->state)); log_flush(LOG_STDOUT); } return 0; } /* Just free memory used by PortList::port_map[]. Should be done somewhere * before closing nmap. */ void PortList::freePortMap() { int proto; for (proto=0; proto < PORTLIST_PROTO_MAX; proto++) { if (port_map[proto]) { free(port_map[proto]); port_map[proto] = NULL; } if (port_map_rev[proto]) { free(port_map_rev[proto]); port_map_rev[proto] = NULL; } port_list_count[proto] = 0; } } u16 *PortList::port_map[PORTLIST_PROTO_MAX]; u16 *PortList::port_map_rev[PORTLIST_PROTO_MAX]; int PortList::port_list_count[PORTLIST_PROTO_MAX]; /* This function must be runned before any PortList object is created. * It must be runned for every used protocol. The data in "ports" * should be sorted. */ void PortList::initializePortMap(int protocol, u16 *ports, int portcount) { int i; int ports_max = (protocol == IPPROTO_IP) ? 256 : 65536; int proto = INPROTO2PORTLISTPROTO(protocol); if (port_map[proto] != NULL || port_map_rev[proto] != NULL) fatal("%s: portmap for protocol %i already initialized", __func__, protocol); assert(port_list_count[proto]==0); /* this memory will never be freed, but this is the way it has to be. */ port_map[proto] = (u16 *) safe_zalloc(sizeof(u16) * ports_max); port_map_rev[proto] = (u16 *) safe_zalloc(sizeof(u16) * portcount); port_list_count[proto] = portcount; for(i=0; i < portcount; i++) { port_map[proto][ports[i]] = i; port_map_rev[proto][i] = ports[i]; } /* So now port_map should have such structure (lets scan 2nd,4th and 6th port): * port_map[0,0,1,0,2,0,3,...] <- indexes to port_list structure * port_list[port_2,port_4,port_6] */ } /* Cycles through the 0 or more "ignored" ports which should be consolidated for Nmap output. They are returned sorted by the number of prots in the state, starting with the most common. It should first be called with PORT_UNKNOWN to obtain the most popular ignored state (if any). Then call with that state to get the next most popular one. Returns the state if there is one, but returns PORT_UNKNOWN if there are no (more) states which qualify for consolidation */ int PortList::nextIgnoredState(int prevstate) { int beststate = PORT_UNKNOWN; for(int state=0; state < PORT_HIGHEST_STATE; state++) { /* The state must be ignored */ if (!isIgnoredState(state)) continue; /* We can't give the same state again ... */ if (state == prevstate) continue; /* If a previous state was given, we must have fewer ports than that one, or be tied but be a larger state number */ if (prevstate != PORT_UNKNOWN && (getStateCounts(state) > getStateCounts(prevstate) || (getStateCounts(state) == getStateCounts(prevstate) && state <= prevstate))) continue; /* We only qualify if we have more ports than the current best */ if (beststate != PORT_UNKNOWN && getStateCounts(beststate) >= getStateCounts(state)) continue; /* Yay! We found the best state so far ... */ beststate = state; } return beststate; } /* Returns true if a state should be ignored (consolidated), false otherwise */ bool PortList::isIgnoredState(int state) { if (o.debugging > 2) return false; if (state == PORT_OPEN || state == PORT_UNKNOWN || state == PORT_TESTING || state == PORT_FRESH) return false; /* Cannot be ignored */ if (state == PORT_OPENFILTERED && (o.verbose > 2 || o.debugging > 2)) return false; /* If openonly, we always ignore states that don't at least have open as a possibility. */ if (o.openOnly() && state != PORT_OPENFILTERED && state != PORT_UNFILTERED && getStateCounts(state) > 0) return true; int max_per_state = 25; // Ignore states with more ports than this /* We will show more ports when verbosity is requested */ if (o.verbose || o.debugging) { if (o.ipprotscan) max_per_state *= (o.verbose + 3 * o.debugging); else max_per_state *= (o.verbose + 20 * o.debugging); } if (getStateCounts(state) > max_per_state) return true; return false; } int PortList::numIgnoredStates() { int numstates = 0; for(int state=0; state < PORT_HIGHEST_STATE; state++) { if (isIgnoredState(state)) numstates++; } return numstates; } int PortList::numIgnoredPorts() { int numports = 0; for(int state=0; state < PORT_HIGHEST_STATE; state++) { if (isIgnoredState(state)) numports += getStateCounts(state); } return numports; } int PortList::numPorts() const { int proto, num = 0; for (proto = 0; proto < PORTLIST_PROTO_MAX; proto++) num += port_list_count[proto]; return num; } /* Return true if any of the ports are potentially open. */ bool PortList::hasOpenPorts() const { return getStateCounts(PORT_OPEN) != 0 || getStateCounts(PORT_OPENFILTERED) != 0 || getStateCounts(PORT_UNFILTERED) != 0; } int PortList::setStateReason(u16 portno, u8 proto, reason_t reason, u8 ttl, const struct sockaddr_storage *ip_addr) { Port *answer = NULL; answer = createPort(portno, proto); /* set new reason and increment its count */ answer->reason.reason_id = reason; if (ip_addr == NULL) answer->reason.ip_addr.sockaddr.sa_family = AF_UNSPEC; else answer->reason.set_ip_addr(ip_addr); answer->reason.ttl = ttl; return 0; } // Move some popular TCP ports to the beginning of the portlist, because // that can speed up certain scans. You should have already done any port // randomization, this should prevent the ports from always coming out in the // same order. void random_port_cheat(u16 *ports, int portcount) { int allportidx = 0; int popportidx = 0; int earlyreplidx = 0; /* Updated 2008-12-19 from nmap-services-all. Top 25 open TCP ports plus 113, 554, and 256 */ u16 pop_ports[] = { 80, 23, 443, 21, 22, 25, 3389, 110, 445, 139, 143, 53, 135, 3306, 8080, 1723, 111, 995, 993, 5900, 1025, 587, 8888, 199, 1720, 113, 554, 256 }; int num_pop_ports = sizeof(pop_ports) / sizeof(u16); for(allportidx = 0; allportidx < portcount; allportidx++) { // see if the currentport is a popular port for(popportidx = 0; popportidx < num_pop_ports; popportidx++) { if (ports[allportidx] == pop_ports[popportidx]) { // This one is popular! Swap it near to the beginning. if (allportidx != earlyreplidx) { ports[allportidx] = ports[earlyreplidx]; ports[earlyreplidx] = pop_ports[popportidx]; } earlyreplidx++; break; } } } }
36.636748
108
0.638334
uninth
48b5f125075603cff51445c86f4837bcf448372f
7,321
cxx
C++
main/fpicker/source/win32/filepicker/controlcommand.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/fpicker/source/win32/filepicker/controlcommand.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/fpicker/source/win32/filepicker/controlcommand.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include "controlcommand.hxx" #include "controlcommandrequest.hxx" #include "controlcommandresult.hxx" #include "filepickerstate.hxx" //--------------------------------------------- // //--------------------------------------------- CControlCommand::CControlCommand( sal_Int16 aControlId ) : m_NextCommand( NULL ), m_aControlId( aControlId ) { } //--------------------------------------------- // //--------------------------------------------- CControlCommand::~CControlCommand( ) { } //--------------------------------------------- // //--------------------------------------------- CControlCommandResult* SAL_CALL CControlCommand::handleRequest( CControlCommandRequest* pRequest ) { // if the command does not support handleRequest, it should at least // redirect the request to the next element // so the base class implementation has to do it OSL_ENSURE( pRequest, "inavlid parameter" ); CControlCommandResult* result; CControlCommand* nextCommand; nextCommand = getNextCommand( ); if ( nextCommand ) { result = nextCommand->handleRequest( pRequest ); } else { result = new CControlCommandResult(); } return result; } //--------------------------------------------- // //--------------------------------------------- CControlCommand* SAL_CALL CControlCommand::getNextCommand( ) const { return m_NextCommand; } //--------------------------------------------- // //--------------------------------------------- void SAL_CALL CControlCommand::setNextCommand( CControlCommand* nextCommand ) { m_NextCommand = nextCommand; } //--------------------------------------------- // //--------------------------------------------- sal_Int16 SAL_CALL CControlCommand::getControlId( ) const { return m_aControlId; } //--------------------------------------------- // //--------------------------------------------- CValueControlCommand::CValueControlCommand( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue ) : CControlCommand( aControlId ), m_aControlAction( aControlAction ), m_aValue( aValue ) { } //--------------------------------------------- // //--------------------------------------------- void SAL_CALL CValueControlCommand::exec( CFilePickerState* aFilePickerState ) { OSL_ENSURE( aFilePickerState, "empty reference" ); aFilePickerState->setValue( getControlId( ), m_aControlAction, m_aValue ); } //--------------------------------------------- // //--------------------------------------------- CControlCommandResult* SAL_CALL CValueControlCommand::handleRequest( CControlCommandRequest* aRequest ) { CValueControlCommandRequest* value_request = dynamic_cast< CValueControlCommandRequest* >( aRequest ); CControlCommandResult* result; CControlCommand* nextCommand; if ( value_request && (value_request->getControlId( ) == getControlId( )) && (value_request->getControlAction( ) == m_aControlAction) ) { result = new CValueCommandResult( sal_True, m_aValue ); } else { nextCommand = getNextCommand( ); if ( nextCommand ) { result = nextCommand->handleRequest( aRequest ); } else { result = new CControlCommandResult( ); } } return result; } //--------------------------------------------- // //--------------------------------------------- sal_Int16 SAL_CALL CValueControlCommand::getControlAction( ) const { return m_aControlAction; } //--------------------------------------------- // //--------------------------------------------- ::com::sun::star::uno::Any SAL_CALL CValueControlCommand::getValue( ) const { return m_aValue; } //--------------------------------------------- // //--------------------------------------------- CLabelControlCommand::CLabelControlCommand( sal_Int16 aControlId, const rtl::OUString& aLabel ) : CControlCommand( aControlId ), m_aLabel( aLabel ) { } //--------------------------------------------- // //--------------------------------------------- void SAL_CALL CLabelControlCommand::exec( CFilePickerState* aFilePickerState ) { OSL_ENSURE( aFilePickerState, "empty reference" ); aFilePickerState->setLabel( getControlId( ), m_aLabel ); } //--------------------------------------------- // //--------------------------------------------- CControlCommandResult* SAL_CALL CLabelControlCommand::handleRequest( CControlCommandRequest* aRequest ) { OSL_ENSURE( aRequest, "inavlid parameter" ); CControlCommandResult* result; CControlCommand* nextCommand; CValueControlCommandRequest* value_request = dynamic_cast< CValueControlCommandRequest* >( aRequest ); if ( !value_request && (aRequest->getControlId( ) == getControlId( )) ) { result = new CLabelCommandResult( sal_True, m_aLabel ); } else { nextCommand = getNextCommand( ); if ( nextCommand ) { result = nextCommand->handleRequest( aRequest ); } else { result = new CControlCommandResult( ); } } return result; } //--------------------------------------------- // //--------------------------------------------- rtl::OUString SAL_CALL CLabelControlCommand::getLabel( ) const { return m_aLabel; } //--------------------------------------------- // //--------------------------------------------- CEnableControlCommand::CEnableControlCommand( sal_Int16 aControlId, sal_Bool bEnable ) : CControlCommand( aControlId ), m_bEnable( bEnable ) { } //--------------------------------------------- // //--------------------------------------------- void SAL_CALL CEnableControlCommand::exec( CFilePickerState* aFilePickerState ) { OSL_ENSURE( aFilePickerState, "empty reference" ); aFilePickerState->enableControl( getControlId( ), m_bEnable ); }
26.240143
103
0.502117
Grosskopf
48b5fbbb2924f7f6f143de57bc188593f3db3097
432
cpp
C++
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
1
2015-07-15T07:31:42.000Z
2015-07-15T07:31:42.000Z
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
linear-list/array/climbing_stairs.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
/** *You are climbing a stair case. It takes n steps to reach to the top. *Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * */ class Solution { public: int climbStairs(int n) { int prev = 0; int cur = 1; for(int i = 1; i <= n; i++) { int tmp = prev; cur += prev; prev = tmp; } return cur; } };
22.736842
98
0.513889
zhangxin23
48b7d4bd1fafc82dd2fd9a8c0364ea416fb66cda
164
cpp
C++
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
atcoder/abc86_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int a, b; cin >> a >> b; printf("%s\n", (a % 2 != 0 && b % 2 != 0) ? "Odd" : "Even"); return 0; }
18.222222
62
0.47561
cosmicray001
48bfd7aa35f34e02e3032c71d380f1497af2dfc3
744
cpp
C++
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
null
null
null
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
null
null
null
src/lib/word_loader.cpp
michielgoethals/word-blaster-solution
58720caeeda16356b32ade501add2e018a3b755d
[ "MIT" ]
3
2020-06-03T10:01:22.000Z
2020-10-02T11:26:18.000Z
#include "word_loader.h" #include <fstream> #include <iostream> namespace WordBlasterTheGame { void WordLoader::load(WordList * words, std::string filename) { // Load from file - see https://oop-cpp.netlify.app/09-file-streams/#reading-from-a-file // File stream object std::ifstream file; file.open(filename); // Make sure operation did not fail if (!file) { std::cerr << "Could not open the file " << filename << " in reading mode" << std::endl; return; // Let's do nothing anymore } // Read the words from the file and store them in the wordlist std::string line; while (getline(file, line)) { words->add(line); } // Close the file file.close(); } };
24
92
0.620968
michielgoethals
48c02e5e008707e7f7c4f024fab781fa457f54cb
5,801
cpp
C++
src/slib/social/facebook.cpp
emarc99/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
146
2017-03-21T07:50:43.000Z
2022-03-19T03:32:22.000Z
src/slib/social/facebook.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
50
2017-03-22T04:08:15.000Z
2019-10-21T16:55:48.000Z
src/slib/social/facebook.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
55
2017-03-21T07:52:58.000Z
2021-12-27T13:02:08.000Z
/* * Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "slib/social/facebook.h" #include "slib/core/safe_static.h" namespace slib { namespace priv { namespace facebook { SLIB_STATIC_ZERO_INITIALIZED(AtomicRef<Facebook>, g_instance) } } using namespace priv::facebook; SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(FacebookUser) SLIB_DEFINE_JSON(FacebookUser) { if (isFromJson) { this->json = json; } SLIB_JSON_ADD_MEMBERS(id, email, name, name_format, first_name, middle_name, last_name, short_name, gender, birthday, quotes, profile_pic) } FacebookUser::FacebookUser() { } SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(FacebookShareResult) FacebookShareResult::FacebookShareResult() { flagSuccess = sl_false; flagCancel = sl_false; } SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(FacebookShareParam) FacebookShareParam::FacebookShareParam() { } SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(FacebookParam) FacebookParam::FacebookParam() : FacebookParam(sl_null) { } FacebookParam::FacebookParam(const String& _version) { if (_version.isNotEmpty()) { version = _version; authorizeUrl = String::format("https://www.facebook.com/%s/dialog/oauth", _version); accessTokenUrl = String::format("https://graph.facebook.com/%s/oauth/access_token", _version); } else { authorizeUrl = "https://www.facebook.com/dialog/oauth"; accessTokenUrl = "https://graph.facebook.com/oauth/access_token"; } accessTokenMethod = HttpMethod::GET; defaultScopes.add_NoLock("public_profile"); defaultScopes.add_NoLock("email"); } SLIB_DEFINE_OBJECT(Facebook, OAuth2) Facebook::Facebook(const FacebookParam& param) : OAuth2(param) { m_version = param.version; } Facebook::~Facebook() { } Ref<Facebook> Facebook::create(const FacebookParam& param) { return new Facebook(param); } void Facebook::initialize(const FacebookParam& param) { if (SLIB_SAFE_STATIC_CHECK_FREED(g_instance)) { return; } g_instance = create(param); } void Facebook::initialize() { FacebookParam param; param.preferenceName = "facebook"; initialize(param); } Ref<Facebook> Facebook::create(const String& appId, const String& appSecret, const String& redirectUri) { FacebookParam param; param.clientId = appId; param.clientSecret = appSecret; param.redirectUri = redirectUri; return create(param); } void Facebook::initialize(const String& appId, const String& appSecret, const String& redirectUri) { FacebookParam param; param.preferenceName = "facebook"; param.clientId = appId; param.clientSecret = appSecret; param.redirectUri = redirectUri; initialize(param); } Ref<Facebook> Facebook::create(const String& appId, const String& redirectUri) { return create(appId, String::null(), redirectUri); } void Facebook::initialize(const String& appId, const String& redirectUri) { initialize(appId, String::null(), redirectUri); } Ref<Facebook> Facebook::createWithAccessToken(const String& accessToken) { FacebookParam param; param.accessToken.token = accessToken; return create(param); } Ref<Facebook> Facebook::getInstance() { if (SLIB_SAFE_STATIC_CHECK_FREED(g_instance)) { return sl_null; } return g_instance; } String Facebook::getRequestUrl(const String& path) { if (m_version.isNotEmpty()) { return String::format("https://graph.facebook.com/%s/%s", m_version, path); } else { return "https://graph.facebook.com/" + path; } } void Facebook::getUser(const String& personId, const String& fields, const Function<void(FacebookResult&, FacebookUser&)>& onComplete) { UrlRequestParam rp; if (personId.isNotEmpty()) { rp.url = getRequestUrl(String::format("%s", personId)); } else { SLIB_STATIC_STRING(me, "me") rp.url = getRequestUrl(me); } if (fields.isNotEmpty()) { rp.parameters.put_NoLock("fields", fields); } rp.onComplete = [onComplete](UrlRequest* request) { FacebookResult result(request); FacebookUser user; if (!(request->isError())) { FromJson(result.response, user); result.flagSuccess = user.id.isNotEmpty(); } onComplete(result, user); }; authorizeRequest(rp); UrlRequest::send(rp); } void Facebook::getUser(const String& personId, const List<String>& fields, const Function<void(FacebookResult&, FacebookUser&)>& onComplete) { getUser(personId, String::join(fields, ","), onComplete); } void Facebook::getUser(const String& personId, const Function<void(FacebookResult&, FacebookUser&)>& onComplete) { SLIB_STATIC_STRING(defaultFields, "id,name,name_format,first_name,last_name,middle_name,email") getUser(personId, defaultFields, onComplete); } }
27.363208
141
0.726599
emarc99
48c1139d6b2aef6f5c0145f943bc1d3c135b6c10
2,751
cpp
C++
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
1
2019-11-10T18:45:48.000Z
2019-11-10T18:45:48.000Z
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
null
null
null
lib/primesieve/src/PreSieve.cpp
KrishnaPrasath/primecount
16e6f70643c45aaac8a96aa127f21b1ed1a51063
[ "BSD-2-Clause" ]
null
null
null
/// /// @file PreSieve.cpp /// @brief Pre-sieve multiples of small primes to speed up /// the sieve of Eratosthenes. /// /// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/PreSieve.hpp> #include <primesieve/EratSmall.hpp> #include <primesieve/pmath.hpp> #include <primesieve/types.hpp> #include <stdint.h> #include <algorithm> #include <array> #include <iterator> #include <memory> using namespace std; namespace { // small primes >= 7 const array<uint64_t, 5> primes = { 7, 11, 13, 17, 19 }; // prime products of primes >= 7 const array<uint64_t, 5> primeProducts = { 210, 2310, 30030, 510510, 9699690 }; } // namespace namespace primesieve { void PreSieve::init(uint64_t start, uint64_t stop) { // the pre-sieve buffer should be at least 10 // times smaller than the sieving distance // in order to reduce initialization overhead uint64_t dist = stop - start; uint64_t threshold = max(dist, isqrt(stop)) / 100; auto last = primeProducts.end() - 1; auto iter = lower_bound(primeProducts.begin(), last, threshold); auto i = distance(primeProducts.begin(), iter); if (primes.at(i) > maxPrime_) initBuffer(primes[i], primeProducts[i]); } /// Initialize the buffer by removing the /// multiples of primes <= maxPrime. /// void PreSieve::initBuffer(uint64_t maxPrime, uint64_t primeProduct) { maxPrime_ = maxPrime; primeProduct_ = primeProduct; size_ = primeProduct_ / 30; buffer_ = new byte_t[size_]; deleter_.reset(buffer_); fill_n(buffer_, size_, (byte_t) 0xff); EratSmall eratSmall; uint64_t stop = primeProduct_ * 2; eratSmall.init(stop, size_, maxPrime_); for (uint64_t prime : primes) if (prime <= maxPrime_) eratSmall.addSievingPrime(prime, primeProduct_); eratSmall.crossOff(buffer_, size_); } /// Copy pre-sieved buffer to sieve array void PreSieve::copy(byte_t* sieve, uint64_t sieveSize, uint64_t segmentLow) const { // find segmentLow index uint64_t remainder = segmentLow % primeProduct_; uint64_t i = remainder / 30; uint64_t sizeLeft = size_ - i; if (sieveSize <= sizeLeft) copy_n(&buffer_[i], sieveSize, sieve); else { // copy the last remaining bytes of buffer // to the beginning of the sieve array copy_n(&buffer_[i], sizeLeft, sieve); // restart copying at the beginning of buffer for (i = sizeLeft; i + size_ < sieveSize; i += size_) copy_n(buffer_, size_, &sieve[i]); // copy the last remaining bytes copy_n(buffer_, sieveSize - i, &sieve[i]); } } } // namespace
25.95283
79
0.671029
KrishnaPrasath
48c3ff7071457459aaa9ff43e137fcb2f82e27f3
517
hpp
C++
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
3
2017-03-30T03:08:48.000Z
2018-07-27T17:48:41.000Z
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
34
2016-12-28T18:04:22.000Z
2017-06-01T07:32:48.000Z
include/sigma/graphics/cubemap.hpp
siegelaaron94/engine
e09985b37de8d3d671878b9e0385e8d73cd0f441
[ "MIT" ]
1
2017-05-13T05:45:01.000Z
2017-05-13T05:45:01.000Z
#ifndef SIGMA_GRAPHICS_CUBEMAP_HPP #define SIGMA_GRAPHICS_CUBEMAP_HPP #include <sigma/config.hpp> #include <sigma/graphics/texture.hpp> #include <array> namespace sigma { namespace graphics { struct cubemap { enum class face : unsigned int { POSITIVE_X, NEGATIVE_X, POSITIVE_Y, NEGATIVE_Y, POSITIVE_Z, NEGATIVE_Z }; std::array<std::shared_ptr<texture>, 6> faces; }; } } #endif // SIGMA_GRAPHICS_CUBEMAP_HPP
18.464286
54
0.618956
siegelaaron94
48c61af5fac5e146420d2797ea39da58fff100e7
5,748
cpp
C++
Sources/Core/Surface/ImplicitSurfaceSet3.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
3
2020-04-15T13:41:16.000Z
2020-12-29T11:23:59.000Z
Sources/Core/Surface/ImplicitSurfaceSet3.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
Sources/Core/Surface/ImplicitSurfaceSet3.cpp
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: ImplicitSurfaceSet3.cpp > Project Name: CubbyFlow > Author: Dongmin Kim > Purpose: 3-D implicit surface set. > Created Time: 2017/04/18 > Copyright (c) 2018, Dongmin Kim *************************************************************************/ #include <Core/Surface/ImplicitSurfaceSet3.h> #include <Core/Surface/SurfaceToImplicit3.h> namespace CubbyFlow { ImplicitSurfaceSet3::ImplicitSurfaceSet3() { // Do nothing } ImplicitSurfaceSet3::ImplicitSurfaceSet3( const std::vector<ImplicitSurface3Ptr>& surfaces, const Transform3& transform, bool isNormalFlipped) : ImplicitSurface3(transform, isNormalFlipped), m_surfaces(surfaces) { // Do nothing } ImplicitSurfaceSet3::ImplicitSurfaceSet3( const std::vector<Surface3Ptr>& surfaces, const Transform3& transform, bool isNormalFlipped) : ImplicitSurface3(transform, isNormalFlipped) { for (const auto& surface : surfaces) { AddExplicitSurface(surface); } } ImplicitSurfaceSet3::ImplicitSurfaceSet3(const ImplicitSurfaceSet3& other) : ImplicitSurface3(other), m_surfaces(other.m_surfaces) { // Do nothing } void ImplicitSurfaceSet3::UpdateQueryEngine() { BuildBVH(); } size_t ImplicitSurfaceSet3::NumberOfSurfaces() const { return m_surfaces.size(); } const ImplicitSurface3Ptr& ImplicitSurfaceSet3::SurfaceAt(size_t i) const { return m_surfaces[i]; } void ImplicitSurfaceSet3::AddExplicitSurface(const Surface3Ptr& surface) { AddSurface(std::make_shared<SurfaceToImplicit3>(surface)); } void ImplicitSurfaceSet3::AddSurface(const ImplicitSurface3Ptr& surface) { m_surfaces.push_back(surface); InvalidateBVH(); } Vector3D ImplicitSurfaceSet3::ClosestPointLocal(const Vector3D& otherPoint) const { BuildBVH(); const auto distanceFunc = [](const Surface3Ptr& surface, const Vector3D& pt) { return surface->ClosestDistance(pt); }; const auto queryResult = m_bvh.GetNearestNeighbor(otherPoint, distanceFunc); if (queryResult.item != nullptr) { return (*queryResult.item)->ClosestPoint(otherPoint); } return Vector3D{ std::numeric_limits<double>::max(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max() }; } double ImplicitSurfaceSet3::ClosestDistanceLocal(const Vector3D& otherPoint) const { BuildBVH(); const auto distanceFunc = [](const Surface3Ptr& surface, const Vector3D& pt) { return surface->ClosestDistance(pt); }; const auto queryResult = m_bvh.GetNearestNeighbor(otherPoint, distanceFunc); return queryResult.distance; } Vector3D ImplicitSurfaceSet3::ClosestNormalLocal(const Vector3D& otherPoint) const { BuildBVH(); const auto distanceFunc = [](const Surface3Ptr& surface, const Vector3D& pt) { return surface->ClosestDistance(pt); }; const auto queryResult = m_bvh.GetNearestNeighbor(otherPoint, distanceFunc); if (queryResult.item != nullptr) { return (*queryResult.item)->ClosestNormal(otherPoint); } return Vector3D{ 1.0, 0.0, 0.0 }; } bool ImplicitSurfaceSet3::IntersectsLocal(const Ray3D& ray) const { BuildBVH(); const auto testFunc = [](const Surface3Ptr& surface, const Ray3D& ray) { return surface->Intersects(ray); }; return m_bvh.IsIntersects(ray, testFunc); } SurfaceRayIntersection3 ImplicitSurfaceSet3::ClosestIntersectionLocal(const Ray3D& ray) const { BuildBVH(); const auto testFunc = [](const Surface3Ptr& surface, const Ray3D& ray) { SurfaceRayIntersection3 result = surface->ClosestIntersection(ray); return result.distance; }; const auto queryResult = m_bvh.GetClosestIntersection(ray, testFunc); SurfaceRayIntersection3 result; result.distance = queryResult.distance; result.isIntersecting = queryResult.item != nullptr; if (queryResult.item != nullptr) { result.point = ray.PointAt(queryResult.distance); result.normal = (*queryResult.item)->ClosestNormal(result.point); } return result; } BoundingBox3D ImplicitSurfaceSet3::BoundingBoxLocal() const { BuildBVH(); return m_bvh.GetBoundingBox(); } double ImplicitSurfaceSet3::SignedDistanceLocal(const Vector3D& otherPoint) const { double sdf = std::numeric_limits<double>::max(); for (const auto& surface : m_surfaces) { sdf = std::min(sdf, surface->SignedDistance(otherPoint)); } return sdf; } void ImplicitSurfaceSet3::InvalidateBVH() const { m_bvhInvalidated = true; } void ImplicitSurfaceSet3::BuildBVH() const { if (m_bvhInvalidated) { std::vector<BoundingBox3D> bounds(m_surfaces.size()); for (size_t i = 0; i < m_surfaces.size(); ++i) { bounds[i] = m_surfaces[i]->BoundingBox(); } m_bvh.Build(m_surfaces, bounds); m_bvhInvalidated = false; } } ImplicitSurfaceSet3::Builder ImplicitSurfaceSet3::GetBuilder() { return Builder(); } ImplicitSurfaceSet3::Builder& ImplicitSurfaceSet3::Builder::WithSurfaces( const std::vector<ImplicitSurface3Ptr>& surfaces) { m_surfaces = surfaces; return *this; } ImplicitSurfaceSet3::Builder& ImplicitSurfaceSet3::Builder::WithExplicitSurfaces( const std::vector<Surface3Ptr>& surfaces) { m_surfaces.clear(); for (const auto& surface : surfaces) { m_surfaces.push_back(std::make_shared<SurfaceToImplicit3>(surface)); } return *this; } ImplicitSurfaceSet3 ImplicitSurfaceSet3::Builder::Build() const { return ImplicitSurfaceSet3(m_surfaces, m_transform, m_isNormalFlipped); } ImplicitSurfaceSet3Ptr ImplicitSurfaceSet3::Builder::MakeShared() const { return std::shared_ptr<ImplicitSurfaceSet3>(new ImplicitSurfaceSet3(m_surfaces, m_transform, m_isNormalFlipped), [](ImplicitSurfaceSet3* obj) { delete obj; }); } }
24.253165
128
0.718337
utilForever
48c67e2ad26fdc3c2748e7b63e2b0b6d4dc41aa2
3,287
cpp
C++
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
19
2016-06-18T02:03:56.000Z
2022-02-23T17:26:32.000Z
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
43
2017-03-09T07:32:12.000Z
2022-03-23T20:18:35.000Z
src/HumdrumFileContent-timesig.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
5
2019-11-14T22:24:02.000Z
2021-09-07T18:27:21.000Z
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Wed Nov 30 22:27:57 PST 2016 // Last Modified: Wed Nov 30 22:28:03 PST 2016 // Filename: HumdrumFileContent-timesig.cpp // URL: https://github.com/craigsapp/humlib/blob/master/src/HumdrumFileContent-timesig.cpp // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: // Extracts time signature top and bottoms for a specific part. // #include "HumdrumFileContent.h" #include "Convert.h" #include <algorithm> #include <string.h> using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // HumdrumFileStructure::getTimeSigs -- Return the prevailing time signature // top and bottom for a particular spine for each line in the HumdrumFile. // This version does not handle mulimeters such as 2+3/4 or 3/4+6/8. // Only checks the primary strand of a spine/track for time signatures. // // default value: track = 0: 0 means use the time signature // of the first **kern spine in the file; otherwise, use the // time signatures found in the given track (indexed from 1 // for the first spine on a line). A value of <0, 0> is used for // unassigned time signature lines. // void HumdrumFileContent::getTimeSigs(vector<pair<int, HumNum> >& output, int track) { HumdrumFileStructure& infile = *this; int lineCount = infile.getLineCount(); output.resize(lineCount); pair<int, HumNum> current(0, 0); fill(output.begin(), output.end(), current); if (track == 0) { vector<HTp> kernspines = infile.getKernSpineStartList(); if (kernspines.size() > 0) { track = kernspines[0]->getTrack(); } } if (track == 0) { track = 1; } int top = 0; // top number of time signature (0 for no meter) int bot = 0; // bottom number of time signature int bot2 = 0; // such as the 2 in 3%2. int firstsig = -1; int firstdata = -1; HTp token = getTrackStart(track); while (token) { if (token->isData()) { if (firstdata < 0) { firstdata = token->getLineIndex(); } token = token->getNextToken(); continue; } if (!token->isInterpretation()) { token = token->getNextToken(); continue; } // check for time signature: if (sscanf(token->c_str(), "*M%d/%d%%%d", &top, &bot, &bot2) == 3) { current.first = top; current.second.setValue(bot, bot2); if (firstsig < 0) { firstsig = token->getLineIndex(); } } else if (sscanf(token->c_str(), "*M%d/%d", &top, &bot) == 2) { current.first = top; current.second = bot; if (firstsig < 0) { firstsig = token->getLineIndex(); } } output[token->getLineIndex()] = current; token = token->getNextToken(); } // Back-fill the list if the first time signature occurs before // the start of the data: if ((firstsig > 0) && (firstdata >= firstsig)) { current = output[firstsig]; for (int i=0; i<firstsig; i++) { output[i] = current; } } // In-fill the list: int starti = firstsig; if (starti < 0) { starti = 0; } current = output[starti]; for (int i=starti+1; i<(int)output.size(); i++) { if (output[i].first == 0) { output[i] = current; } else { current = output[i]; } } } // END_MERGE } // end namespace hum
26.087302
100
0.628841
johnnymac647
48c8cc9758779b2a17818786c04154910b6436d0
204
cpp
C++
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
CodeForces/StonesontheTable.cpp
mysterio0801/CP
68983c423a42f98d6e9bf5375bc3f936e980d631
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; string str; cin>>str; int count = 0; for(int i = 1; i < n; i++){ if(str[i] == str[i-1]){ count++; } } cout<<count; }
12.75
28
0.529412
mysterio0801
48c9d6686ef4c99b92b07ded20964e49ad020417
2,372
cpp
C++
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
src/maze.cpp
carolinafsilva/Pacman
e7c5c1c448d4888bdf1c6e72e9a542bdebe65720
[ "MIT" ]
null
null
null
#include "maze.hpp" glm::vec2 Maze::getCenter(glm::vec3 position) { return glm::vec2(position.x + position.z / 2, position.y + position.z / 2); } int Maze::getDotsRemaining() { return this->dotsRemaining; } void Maze::decrementDotsRemaining() { this->dotsRemaining -= 1; } glm::ivec2 Maze::pixelToBlock(glm::vec2 center) { int c = floor(center.x / 8); int l = floor(center.y / 8); return glm::ivec2(l, c); } glm::vec2 Maze::blockToPixel(glm::ivec2 block) { int x = block.y * 8 + 4; int y = block.x * 8 + 4; return glm::vec2(x, y); } glm::ivec2 Maze::blockNext(glm::ivec2 block, orientation direction) { int c, l; switch (direction) { case up: l = block.x - 1; c = block.y; break; case left: l = block.x; c = block.y - 1; break; case down: l = block.x + 1; c = block.y; break; case right: l = block.x; c = block.y + 1; break; } return glm::ivec2(l, c); } bool Maze::valid(glm::ivec2 block, bool door) { if (block.x >= 0 && block.x < BLOCK_L && block.y >= 0 && block.y < BLOCK_C) { return (door && this->isDoor(block)) || this->matrix[block.x][block.y] >= 0; } return false; } bool Maze::isDoor(glm::ivec2 block) { return this->matrix[block.x][block.y] == -2; } int Maze::eat(glm::ivec2 block) { int points = 0; if (valid(block, false)) { points = matrix[block.x][block.y]; matrix[block.x][block.y] = 0; } return points; } int Maze::value(glm::ivec2 block) { int points = 0; if (valid(block, false)) { points = matrix[block.x][block.y]; } return points; } float Maze::euclidianDist(glm::vec2 position1, glm::vec2 position2) { return sqrtf(powf(position1.x - position2.x, 2) + powf(position1.y - position2.y, 2)); } glm::vec2 Maze::getTunnelLeft() { return this->tunnelLeft; } glm::vec2 Maze::getTunnelRight() { return this->tunnelRight; }; void Maze::reset() { this->dotsRemaining = 244; for (int i = 0; i < BLOCK_L; i++) { for (int j = 0; j < BLOCK_C; j++) { this->matrix[i][j] = this->backup[i][j]; } } } Maze::Maze() { this->dotsRemaining = 244; this->tunnelLeft = glm::vec2(-16, 108); this->tunnelRight = glm::vec2(224, 108); for (int i = 0; i < BLOCK_L; i++) { for (int j = 0; j < BLOCK_C; j++) { this->backup[i][j] = this->matrix[i][j]; } } }
23.485149
80
0.580523
carolinafsilva
48c9fe84f315acb92daf5d2c61d6356adc384b98
183
cpp
C++
decibel-cpp/src/decibel/messaging/IRabbitMQMessageHandler.cpp
kcollinssibley/sysadmin
81b6c424f7d9d5c25724cd1f544902ff3ff62cc2
[ "Apache-2.0" ]
14
2017-05-31T19:38:25.000Z
2022-01-19T20:56:32.000Z
decibel-cpp/src/decibel/messaging/IRabbitMQMessageHandler.cpp
kcollinssibley/sysadmin
81b6c424f7d9d5c25724cd1f544902ff3ff62cc2
[ "Apache-2.0" ]
26
2017-06-07T14:05:07.000Z
2020-01-29T20:06:34.000Z
decibel-cpp/src/decibel/messaging/IRabbitMQMessageHandler.cpp
kcollinssibley/sysadmin
81b6c424f7d9d5c25724cd1f544902ff3ff62cc2
[ "Apache-2.0" ]
9
2017-05-31T21:09:59.000Z
2021-05-14T15:11:18.000Z
#include "decibel/messaging/IRabbitMQMessageHandler.h" namespace decibel { namespace messaging { IRabbitMQMessageHandler::~IRabbitMQMessageHandler() { } } // messaging } // decibel
14.076923
54
0.781421
kcollinssibley
48cc911ba80c0bcc04638e7a876264525d073b20
10,553
cc
C++
media/cast/logging/encoding_event_subscriber.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
media/cast/logging/encoding_event_subscriber.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
media/cast/logging/encoding_event_subscriber.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/cast/logging/encoding_event_subscriber.h" #include <cstring> #include <utility> #include "base/logging.h" #include "media/cast/logging/proto/proto_utils.h" using google::protobuf::RepeatedPtrField; using media::cast::proto::AggregatedFrameEvent; using media::cast::proto::AggregatedPacketEvent; using media::cast::proto::BasePacketEvent; using media::cast::proto::LogMetadata; namespace { // A size limit on maps to keep lookups fast. const size_t kMaxMapSize = 200; // The smallest (oredered by RTP timestamp) |kNumMapEntriesToTransfer| entries // will be moved when the map size reaches |kMaxMapSize|. // Must be smaller than |kMaxMapSize|. const size_t kNumMapEntriesToTransfer = 100; template <typename ProtoPtr> bool IsRtpTimestampLessThan(const ProtoPtr& lhs, const ProtoPtr& rhs) { return lhs->relative_rtp_timestamp() < rhs->relative_rtp_timestamp(); } BasePacketEvent* GetNewBasePacketEvent(AggregatedPacketEvent* event_proto, int packet_id, int size) { BasePacketEvent* base = event_proto->add_base_packet_event(); base->set_packet_id(packet_id); base->set_size(size); return base; } } namespace media { namespace cast { EncodingEventSubscriber::EncodingEventSubscriber( EventMediaType event_media_type, size_t max_frames) : event_media_type_(event_media_type), max_frames_(max_frames), frame_event_storage_index_(0), packet_event_storage_index_(0), seen_first_rtp_timestamp_(false), first_rtp_timestamp_(0u) {} EncodingEventSubscriber::~EncodingEventSubscriber() { DCHECK(thread_checker_.CalledOnValidThread()); } void EncodingEventSubscriber::OnReceiveFrameEvent( const FrameEvent& frame_event) { DCHECK(thread_checker_.CalledOnValidThread()); if (event_media_type_ != frame_event.media_type) return; RtpTimestamp relative_rtp_timestamp = GetRelativeRtpTimestamp(frame_event.rtp_timestamp); FrameEventMap::iterator it = frame_event_map_.find(relative_rtp_timestamp); linked_ptr<AggregatedFrameEvent> event_proto; // Look up existing entry. If not found, create a new entry and add to map. if (it == frame_event_map_.end()) { event_proto.reset(new AggregatedFrameEvent); event_proto->set_relative_rtp_timestamp(relative_rtp_timestamp); frame_event_map_.insert( std::make_pair(relative_rtp_timestamp, event_proto)); } else { event_proto = it->second; if (event_proto->event_type_size() >= kMaxEventsPerProto) { DVLOG(2) << "Too many events in frame " << frame_event.rtp_timestamp << ". Using new frame event proto."; AddFrameEventToStorage(event_proto); event_proto.reset(new AggregatedFrameEvent); event_proto->set_relative_rtp_timestamp(relative_rtp_timestamp); it->second = event_proto; } } event_proto->add_event_type(ToProtoEventType(frame_event.type)); event_proto->add_event_timestamp_ms( (frame_event.timestamp - base::TimeTicks()).InMilliseconds()); if (frame_event.type == FRAME_ENCODED) { event_proto->set_encoded_frame_size(frame_event.size); if (frame_event.media_type == VIDEO_EVENT) { event_proto->set_encoded_frame_size(frame_event.size); event_proto->set_key_frame(frame_event.key_frame); event_proto->set_target_bitrate(frame_event.target_bitrate); } } else if (frame_event.type == FRAME_PLAYOUT) { event_proto->set_delay_millis(frame_event.delay_delta.InMilliseconds()); } if (frame_event_map_.size() > kMaxMapSize) TransferFrameEvents(kNumMapEntriesToTransfer); DCHECK(frame_event_map_.size() <= kMaxMapSize); DCHECK(frame_event_storage_.size() <= max_frames_); } void EncodingEventSubscriber::OnReceivePacketEvent( const PacketEvent& packet_event) { DCHECK(thread_checker_.CalledOnValidThread()); if (event_media_type_ != packet_event.media_type) return; RtpTimestamp relative_rtp_timestamp = GetRelativeRtpTimestamp(packet_event.rtp_timestamp); PacketEventMap::iterator it = packet_event_map_.find(relative_rtp_timestamp); linked_ptr<AggregatedPacketEvent> event_proto; BasePacketEvent* base_packet_event_proto = NULL; // Look up existing entry. If not found, create a new entry and add to map. if (it == packet_event_map_.end()) { event_proto.reset(new AggregatedPacketEvent); event_proto->set_relative_rtp_timestamp(relative_rtp_timestamp); packet_event_map_.insert( std::make_pair(relative_rtp_timestamp, event_proto)); base_packet_event_proto = GetNewBasePacketEvent( event_proto.get(), packet_event.packet_id, packet_event.size); } else { // Found existing entry, now look up existing BasePacketEvent using packet // ID. If not found, create a new entry and add to proto. event_proto = it->second; RepeatedPtrField<BasePacketEvent>* field = event_proto->mutable_base_packet_event(); for (RepeatedPtrField<BasePacketEvent>::pointer_iterator base_it = field->pointer_begin(); base_it != field->pointer_end(); ++base_it) { if ((*base_it)->packet_id() == packet_event.packet_id) { base_packet_event_proto = *base_it; break; } } if (!base_packet_event_proto) { if (event_proto->base_packet_event_size() >= kMaxPacketsPerFrame) { DVLOG(3) << "Too many packets in AggregatedPacketEvent " << packet_event.rtp_timestamp << ". " << "Using new packet event proto."; AddPacketEventToStorage(event_proto); event_proto.reset(new AggregatedPacketEvent); event_proto->set_relative_rtp_timestamp(relative_rtp_timestamp); it->second = event_proto; } base_packet_event_proto = GetNewBasePacketEvent( event_proto.get(), packet_event.packet_id, packet_event.size); } else if (base_packet_event_proto->event_type_size() >= kMaxEventsPerProto) { DVLOG(3) << "Too many events in packet " << packet_event.rtp_timestamp << ", " << packet_event.packet_id << ". Using new packet event proto."; AddPacketEventToStorage(event_proto); event_proto.reset(new AggregatedPacketEvent); event_proto->set_relative_rtp_timestamp(relative_rtp_timestamp); it->second = event_proto; base_packet_event_proto = GetNewBasePacketEvent( event_proto.get(), packet_event.packet_id, packet_event.size); } } base_packet_event_proto->add_event_type( ToProtoEventType(packet_event.type)); base_packet_event_proto->add_event_timestamp_ms( (packet_event.timestamp - base::TimeTicks()).InMilliseconds()); // |base_packet_event_proto| could have been created with a receiver event // which does not have the packet size and we would need to overwrite it when // we see a sender event, which does have the packet size. if (packet_event.size > 0) { base_packet_event_proto->set_size(packet_event.size); } if (packet_event_map_.size() > kMaxMapSize) TransferPacketEvents(kNumMapEntriesToTransfer); DCHECK(packet_event_map_.size() <= kMaxMapSize); DCHECK(packet_event_storage_.size() <= max_frames_); } void EncodingEventSubscriber::GetEventsAndReset(LogMetadata* metadata, FrameEventList* frame_events, PacketEventList* packet_events) { DCHECK(thread_checker_.CalledOnValidThread()); // Flush all events. TransferFrameEvents(frame_event_map_.size()); TransferPacketEvents(packet_event_map_.size()); std::sort(frame_event_storage_.begin(), frame_event_storage_.end(), &IsRtpTimestampLessThan<linked_ptr<AggregatedFrameEvent> >); std::sort(packet_event_storage_.begin(), packet_event_storage_.end(), &IsRtpTimestampLessThan<linked_ptr<AggregatedPacketEvent> >); metadata->set_is_audio(event_media_type_ == AUDIO_EVENT); metadata->set_first_rtp_timestamp(first_rtp_timestamp_); metadata->set_num_frame_events(frame_event_storage_.size()); metadata->set_num_packet_events(packet_event_storage_.size()); metadata->set_reference_timestamp_ms_at_unix_epoch( (base::TimeTicks::UnixEpoch() - base::TimeTicks()).InMilliseconds()); frame_events->swap(frame_event_storage_); packet_events->swap(packet_event_storage_); Reset(); } void EncodingEventSubscriber::TransferFrameEvents(size_t max_num_entries) { DCHECK(frame_event_map_.size() >= max_num_entries); FrameEventMap::iterator it = frame_event_map_.begin(); for (size_t i = 0; i < max_num_entries && it != frame_event_map_.end(); i++, ++it) { AddFrameEventToStorage(it->second); } frame_event_map_.erase(frame_event_map_.begin(), it); } void EncodingEventSubscriber::TransferPacketEvents(size_t max_num_entries) { PacketEventMap::iterator it = packet_event_map_.begin(); for (size_t i = 0; i < max_num_entries && it != packet_event_map_.end(); i++, ++it) { AddPacketEventToStorage(it->second); } packet_event_map_.erase(packet_event_map_.begin(), it); } void EncodingEventSubscriber::AddFrameEventToStorage( const linked_ptr<AggregatedFrameEvent>& frame_event_proto) { if (frame_event_storage_.size() >= max_frames_) { frame_event_storage_[frame_event_storage_index_] = frame_event_proto; } else { frame_event_storage_.push_back(frame_event_proto); } frame_event_storage_index_ = (frame_event_storage_index_ + 1) % max_frames_; } void EncodingEventSubscriber::AddPacketEventToStorage( const linked_ptr<AggregatedPacketEvent>& packet_event_proto) { if (packet_event_storage_.size() >= max_frames_) packet_event_storage_[packet_event_storage_index_] = packet_event_proto; else packet_event_storage_.push_back(packet_event_proto); packet_event_storage_index_ = (packet_event_storage_index_ + 1) % max_frames_; } RtpTimestamp EncodingEventSubscriber::GetRelativeRtpTimestamp( RtpTimestamp rtp_timestamp) { if (!seen_first_rtp_timestamp_) { seen_first_rtp_timestamp_ = true; first_rtp_timestamp_ = rtp_timestamp; } return rtp_timestamp - first_rtp_timestamp_; } void EncodingEventSubscriber::Reset() { frame_event_map_.clear(); frame_event_storage_.clear(); frame_event_storage_index_ = 0; packet_event_map_.clear(); packet_event_storage_.clear(); packet_event_storage_index_ = 0; seen_first_rtp_timestamp_ = false; first_rtp_timestamp_ = 0u; } } // namespace cast } // namespace media
36.770035
80
0.745191
justremotephone
48d249155316e82448c83a262b1e421122d18026
3,131
cpp
C++
development/core/src/SOSrv/SOSrvXML.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
19
2021-05-19T11:03:57.000Z
2022-03-18T06:53:48.000Z
development/core/src/SOSrv/SOSrvXML.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
8
2021-04-26T10:47:20.000Z
2022-03-15T11:25:07.000Z
development/core/src/SOSrv/SOSrvXML.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
11
2021-05-28T06:35:20.000Z
2022-03-31T14:07:25.000Z
//----------------------------------------------------------------------------- // | // Softing Industrial Automation GmbH | // Richard-Reitzner-Allee 6 | // 85540 Haar, Germany | // | // This is a part of the Softing OPC Toolkit | // Copyright (c) 2005-2020 Softing Industrial Automation GmbH | // All Rights Reserved | // | //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // OPC Toolkit - SOSrv | // | // Filename : SOSrvXML.cpp | // Version : 4.47.1 | // Date : 27-July-2020 | // | // Description : XML server related classes | // - SOSrvXML: XML server object | // | //----------------------------------------------------------------------------- #include "stdafx.h" #ifdef SOSRV #include "SOSrvXML.h" #ifdef SOFEATURE_XML_METHOD //----------------------------------------------------------------------------- // SOSrvXmlMethod | //----------------------------------------------------------------------------- SOSrvXmlMethod::SOSrvXmlMethod(void) : SOCmnXmlMethod() { } #ifdef SOFEATURE_SOAP SOSrvXmlMethod::SOSrvXmlMethod( IN BYTE xmlMethodType, IN SOSrvHTTPHandler* pHandler, IN SOSrvHTTPHandlerData* pHTTPData, IN DWORD lenBody, IN BYTE* pBody) { m_xmlMethod = xmlMethodType; m_httpHandler.setWithAddRef(pHandler); m_httpHandlerData.setWithAddRef(pHTTPData); m_rcvTime = pHTTPData->m_rcvTime; m_flags = 0; m_lenData = lenBody; m_flags = pHTTPData->m_flags; SOCMN_ALLOCATE_MEMORY_C(m_pData, m_lenData + 1, (BYTE*)) if (m_pData) { memcpy(m_pData, pBody, m_lenData + 1); } setObjectState(SOCMNXMLMETHOD_STATE_INIT); create(NULL, _T('|')); setHandler(SCMNXML_HANDLER_ELEMENT | SCMNXML_HANDLER_CHARACTERDATA | SCMNXML_HANDLER_NAMESPACEDECL); m_elementStack.create(); m_namespaceList.create(SOCMNLIST_TYPE_ORG_MAP | SOCMNLIST_TYPE_KEY_STRING | SOCMNLIST_TYPE_OBJ_STRING | SOCMNLIST_TYPE_BLOCKED); } #endif SOSrvXmlMethod::~SOSrvXmlMethod(void) { SOCMN_FREE_MEMORY(m_pData) } #endif //SOFEATURE_XML_METHOD #endif // SOSRV
38.182927
129
0.377196
Movares
48d4c5be790ad7d2bf66586478375f35467d8c9d
8,525
cpp
C++
TESTS/TARGET_RDA/dcs2_sdk/duerapp_alarm.cpp
ghsecuritylab/RDA5981_Develop
bb97e2ae458a5bbb4757c8fe4c7fbc4401356db2
[ "Apache-2.0" ]
3
2018-03-13T13:42:12.000Z
2019-05-17T11:48:04.000Z
TESTS/TARGET_RDA/dcs2_sdk/duerapp_alarm.cpp
ghsecuritylab/RDA5981_Develop
bb97e2ae458a5bbb4757c8fe4c7fbc4401356db2
[ "Apache-2.0" ]
null
null
null
TESTS/TARGET_RDA/dcs2_sdk/duerapp_alarm.cpp
ghsecuritylab/RDA5981_Develop
bb97e2ae458a5bbb4757c8fe4c7fbc4401356db2
[ "Apache-2.0" ]
8
2018-01-28T02:23:18.000Z
2021-02-26T01:15:55.000Z
// Copyright (2017) Baidu Inc. All rights reserved. /** * File: duerapp_alarm.cpp * Auth: Gang Chen(chengang12@baidu.com) * Desc: Duer alarm functions. */ #include "duerapp_alarm.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <list.h> #include "mbed.h" #include "heap_monitor.h" #include "baidu_alarm.h" #include "baidu_ca_ntp.h" #include "baidu_ca_types.h" #include "duer_log.h" #include "baidu_media_manager.h" #include "baidu_iot_mutex.h" #include "baidu_measure_stack.h" namespace duer { typedef struct duerapp_alarm_node_{ int id; int time; char *token; char *url; baidu_timer_t handle; }duerapp_alarm_node; typedef struct _duer_alarm_list { struct _duer_alarm_list *next; duerapp_alarm_node *data; } duer_alarm_list_t; static duer_alarm_list_t s_alarm_list; static const int ALARM_QUEUE_SIZE = 5; static const int ALARM_TREAD_STACK_SIZE = 1024 * 4; static rtos::Queue<duerapp_alarm_node, ALARM_QUEUE_SIZE> s_message_q; static rtos::Thread s_alarm_thread(osPriorityNormal, ALARM_TREAD_STACK_SIZE); static iot_mutex_t s_alarm_mutex; static bca_errcode_e duer_alarm_list_push(duerapp_alarm_node *data) { bca_errcode_e rt = BCA_NO_ERR; duer_alarm_list_t *new_node = NULL; duer_alarm_list_t *tail = &s_alarm_list; new_node = (duer_alarm_list_t *)MALLOC(sizeof(duer_alarm_list_t), ALARM); if (!new_node) { DUER_LOGE("Memory too low"); rt = BCA_ERR_INTERNAL; goto error_out; } new_node->next = NULL; new_node->data = data; while (tail->next) { tail = tail->next; } tail->next = new_node; error_out: return rt; } static bca_errcode_e duer_alarm_list_remove(duerapp_alarm_node *data) { duer_alarm_list_t *pre = &s_alarm_list; duer_alarm_list_t *cur = NULL; bca_errcode_e rt = BCA_ERR_INTERNAL; while (pre->next) { cur = pre->next; if (cur->data == data) { pre->next = cur->next; FREE(cur); rt = BCA_NO_ERR; break; } pre = pre->next; } return rt; } static duerapp_alarm_node *duer_create_alarm_node(const int id, const int time, const char *token, const char *url, baidu_timer_t handle) { size_t len = 0; duerapp_alarm_node *alarm = NULL; alarm = (duerapp_alarm_node *)MALLOC(sizeof(duerapp_alarm_node), ALARM); if (!alarm) { goto error_out; } memset(alarm, 0, sizeof(duerapp_alarm_node)); len = strlen(token) + 1; alarm->token = (char *)MALLOC(len, ALARM); if (!alarm->token) { goto error_out; } snprintf(alarm->token, len, "%s", token); len = strlen(url) + 1; alarm->url = (char *)MALLOC(len, ALARM); if (!alarm->url) { return NULL; } snprintf(alarm->url, len, "%s", url); alarm->id = id; alarm->time = time; alarm->handle = handle; return alarm; error_out: DUER_LOGE("Memory too low"); if (alarm) { if (alarm->token) { FREE(alarm->token); } if (alarm->url) { FREE(alarm->url); } FREE(alarm); } return NULL; } static void duer_free_alarm_node(duerapp_alarm_node *alarm) { if (alarm) { if (alarm->token) { FREE(alarm->token); alarm->token = NULL; } if (alarm->url) { FREE(alarm->url); alarm->url = NULL; } if (alarm->handle) { baidu_timer_destroy(alarm->handle); alarm->handle = NULL; } FREE(alarm); } } static void duer_alarm_callback(void *param) { duerapp_alarm_node *node = (duerapp_alarm_node *)param; DUER_LOGI("alarm started: token: %s, url: %s\n", node->token, node->url); duer_report_alarm_event(0, node->token, ALERT_START); // play url MediaManager::instance().play_url(node->url, false, true); iot_mutex_lock(s_alarm_mutex, 0); duer_alarm_list_remove(node); iot_mutex_unlock(s_alarm_mutex); duer_free_alarm_node(node); } static int duer_alarm_set(const int id, const char *token, const char *url, const int time) { int rs = BCA_NO_ERR; duerapp_alarm_node* alarm = NULL; DUER_LOGI("set alarm: scheduled_time: %d, token: %s\n", time, token); alarm = duer_create_alarm_node(id, time, token, url, NULL); if (!alarm) { duer_report_alarm_event(id, token, SET_ALERT_FAIL); rs = BCA_ERR_INTERNAL; } else { // create alarm in duer_alarm_thread and return immediately s_message_q.put(alarm, 1); } return rs; } static duerapp_alarm_node *duer_find_target_alarm(const char *token) { duer_alarm_list_t *node = s_alarm_list.next; while (node) { if (node->data) { if (strcmp(token, node->data->token) == 0) { return node->data; } } node = node->next; } return NULL; } /** * We use ntp to get current time, it might spend too long time and block the thread, * hence we use a new thread to create alarm. */ static void duer_alarm_thread() { DuerTime cur_time; size_t delay = 0; int rs = BCA_NO_ERR; duerapp_alarm_node* alarm = NULL; while (1) { osEvent evt = s_message_q.get(); if (evt.status != osEventMessage) { continue; } alarm = (duerapp_alarm_node*)evt.value.p; rs = bca_ntp_client(NULL, 0, &cur_time); if (rs < 0) { DUER_LOGE("Failed to get NTP time\n"); duer_report_alarm_event(alarm->id, alarm->token, SET_ALERT_FAIL); continue; } if (alarm->time <= cur_time.sec) { DUER_LOGE("The alarm is expired\n"); duer_report_alarm_event(alarm->id, alarm->token, SET_ALERT_FAIL); continue; } delay = (alarm->time - cur_time.sec) * 1000 + cur_time.usec / 1000; alarm->handle = baidu_timer_create(duer_alarm_callback, NULL, TIMER_TYPE_ONCE, alarm, delay); if (!alarm->handle) { DUER_LOGE("Failed to create timer\n"); duer_report_alarm_event(alarm->id, alarm->token, SET_ALERT_FAIL); continue; } rs = baidu_timer_start(alarm->handle); if (rs != TIMER_RET_OK) { DUER_LOGE("Failed to start timer\n"); duer_report_alarm_event(alarm->id, alarm->token, SET_ALERT_FAIL); continue; } /* * The alarms is storaged in the ram, hence the alarms will be lost after close the device. * You could stoage them into flash or sd card, and restore them after restart the device * according to your request. */ iot_mutex_lock(s_alarm_mutex, 0); duer_alarm_list_push(alarm); iot_mutex_unlock(s_alarm_mutex); duer_report_alarm_event(alarm->id, alarm->token, SET_ALERT_SUCCESS); } } static int duer_alarm_delete(const int id, const char *token) { duerapp_alarm_node *target_alarm = NULL; DUER_LOGI("delete alarm: token %s", token); iot_mutex_lock(s_alarm_mutex, 0); target_alarm = duer_find_target_alarm(token); if (!target_alarm) { DUER_LOGE("Cannot find the target alarm\n"); iot_mutex_unlock(s_alarm_mutex); duer_report_alarm_event(id, token, DELETE_ALERT_FAIL); return BCA_ERR_INTERNAL; } duer_alarm_list_remove(target_alarm); iot_mutex_unlock(s_alarm_mutex); duer_free_alarm_node(target_alarm); duer_report_alarm_event(id, token, DELETE_ALERT_SUCCESS); return BCA_NO_ERR; } void duer_init_alarm() { static bool is_first_time = true; /** * The init function might be called sevaral times when ca re-connect, * but some operations only need to be done once. */ if (is_first_time) { is_first_time = false; s_alarm_mutex = iot_mutex_create(); s_alarm_thread.start(duer_alarm_thread); #ifdef BAIDU_STACK_MONITOR register_thread(&s_alarm_thread, "duer_alarm_thread"); #endif } duer_alarm_initialize(duer_alarm_set, duer_alarm_delete); } }
25.833333
99
0.604692
ghsecuritylab
48d8f8775f3a096dcde034aee4c13a4a099db4cd
115
cpp
C++
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
source/qt_Kviewer/s4KlogicItem.cpp
chinsaiki/s4-gui
c8a11aad28150da71127b89370bea9b7e2530fee
[ "MIT" ]
null
null
null
#include "qt_Kviewer/s4KlogicItem.h" #include "qt_Kviewer/s4Kinstrument_scene.h" namespace S4{ namespace QT{ } }
12.777778
43
0.773913
chinsaiki
48d9dfad5c420c628d213b122d110468a011f4dc
5,937
cpp
C++
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
5
2020-04-11T06:53:46.000Z
2022-01-05T05:39:11.000Z
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
201
2019-09-05T03:46:21.000Z
2022-01-08T04:44:16.000Z
test/psim/core/state_field_test.cpp
kylekrol/psim
a4817117189f0f5597452076e6e138f70f51d4e8
[ "MIT" ]
10
2019-10-12T17:24:34.000Z
2022-02-25T01:20:14.000Z
/** @file test/psim/core/state_field_test.cpp * @author Kyle Krol */ #include <gtest/gtest.h> #include <psim/core/state_field.hpp> #include <psim/core/state_field_lazy.hpp> #include <psim/core/state_field_valued.hpp> #include <psim/core/types.hpp> #include <stdexcept> TEST(StateField, TestCast) { psim::StateFieldValued<psim::Real> field("default"); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW(base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW(base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } } TEST(StateField, TestCastWritable) { // Test for non-writable state fields { psim::StateFieldLazy<psim::Real> field( "default", []() { return psim::Real(); }); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> *field_ptr = &field; EXPECT_THROW( field_ptr->template cast_writable<psim::Real>(), std::runtime_error); } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; EXPECT_THROW( base_field.template cast_writable<psim::Real>(), std::runtime_error); } } // Test for writable state fields { psim::StateFieldValued<psim::Real> field("default"); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(&(base_field.cast<psim::Real>()), &field); EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); EXPECT_THROW( base_field.template cast<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(&(base_field.template cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(&(base_field.cast<psim::Real>()), &field); // EXPECT_THROW(base_field.cast<psim::Integer>(), std::runtime_error); // ^ throws a state assertion error } } } TEST(StateField, TestGet) { psim::StateFieldValued<psim::Real> field("default", 2.0); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get<psim::Integer>(), std::runtime_error); } // Test for `StateFieldBase const` { psim::StateFieldBase const &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get<psim::Integer>(), std::runtime_error); // ^ throws a static assertion error } // Test for `StateField const` { psim::StateField<psim::Real> const &base_field = field; ASSERT_EQ(base_field.template get<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get<psim::Integer>(), std::runtime_error); // ^ throws a static assertion error } } TEST(StateField, TestGetWritable) { // Test for non-writable state fields { psim::StateFieldLazy<psim::Real> field( "default", []() { return psim::Real(); }); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; EXPECT_THROW( base_field.template get_writable<psim::Real>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; EXPECT_THROW( base_field.template get_writable<psim::Real>(), std::runtime_error); } } // Test for writable state fields { psim::StateFieldValued<psim::Real> field("default", 2.0); // Test for `StateFieldBase` { psim::StateFieldBase &base_field = field; ASSERT_EQ(base_field.template get_writable<psim::Real>(), 2.0); EXPECT_THROW(base_field.template get_writable<psim::Integer>(), std::runtime_error); } // Test for `StateField` { psim::StateField<psim::Real> &base_field = field; ASSERT_EQ(base_field.template get_writable<psim::Real>(), 2.0); // EXPECT_THROW(base_field.get_writable<psim::Integer>(), // std::runtime_error); // ^ throws a static assertion error } } }
27.359447
80
0.644096
kylekrol
48ddb84cca2894ad7aecd0a9483cae2a49f8e7c8
422
cpp
C++
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
126
2019-12-22T17:49:08.000Z
2021-12-14T18:45:51.000Z
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
7
2019-12-25T18:03:41.000Z
2021-02-20T06:25:27.000Z
999_Practice_Set_2/Day_004/041_decimal_to_binary.cpp
Gandham-Srinithya/Data-Structure-and-Algorithms
177d03105188c83a157947ca9870bf8037e92528
[ "MIT" ]
54
2019-12-26T06:28:39.000Z
2022-02-01T05:04:43.000Z
#include <iostream> using namespace std; int decimalToBinary(int decimal) { int x = 1; int binary=0; while(x <= decimal) { x*=2; } x/=2; while(x>0) { int last = decimal/x; decimal-=last*x; x/=2; binary*=10; binary+=last; } return binary; } int main() { int n; cin>>n; cout<<decimalToBinary(n)<<endl; return 0; }
12.057143
35
0.483412
Gandham-Srinithya
48de7bf0f1731b7c20c9ecc2a2f190011978cdc6
13,463
cpp
C++
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
resource/csdk/security/provisioning/unittest/ocprovisioningmanager.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/* ***************************************************************** * * Copyright 2015 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * *****************************************************************/ #include <gtest/gtest.h> #include "ocprovisioningmanager.h" #include "experimental/logger.h" #ifdef __cplusplus extern "C" { #endif #include "../src/ocprovisioningmanager.c" #include "tools.h" #ifdef __cplusplus } #endif #undef TAG #define TAG "OTM_OCPROVISIONINGMANAGER" #define SVR_DB_FILE_NAME TAG".dat" #define PM_DB_FILE_NAME TAG".db" static OCProvisionDev_t *pDev1 = NULL; static OCProvisionDev_t *pDev2 = NULL; class PM : public ::testing::Test { public: static void SetUpTestCase() { IOT_Init(PM_DB_FILE_NAME); pDev1 = createProvisionDev(); pDev2 = createProvisionDev(); pDev2->endpoint.port = 9998; ConvertStrToUuid("33333355-3333-3333-3333-111111111111", &pDev2->doxm->deviceID); } static void TearDownTestCase() { IOT_DeInit(PM_DB_FILE_NAME); } OicSecAcl_t acl1; OicSecAcl_t acl2; }; static void provisioningCB (void *UNUSED1, size_t UNUSED2, OCProvisionResult_t *UNUSED3, bool UNUSED4) { //dummy callback (void) UNUSED1; (void) UNUSED2; (void) UNUSED3; (void) UNUSED4; } static OCStackResult OTMLoadSecretCallback(OTMContext_t *otmCtx) { //dummy callback (void) otmCtx; return OC_STACK_OK; } TEST_F(PM, OCProvisionPairwiseDevicesTestNullDevice1) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128, NULL, &acl1, pDev2, &acl2, &provisioningCB)); } TEST_F(PM, OCProvisionPairwiseDevicesTestNullDevice2) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128, pDev1, &acl1, NULL, &acl2, &provisioningCB)); } TEST_F(PM, OCProvisionPairwiseDevicesTestSamelDeviceId) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128, pDev1, &acl1, pDev1, &acl2, &provisioningCB)); } TEST_F(PM, OCProvisionPairwiseDevicesTestNullCallback) { EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128, pDev1, &acl1, pDev2, &acl2, NULL)); } TEST_F(PM, OCProvisionPairwiseDevicesTestInvalidKeySize) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, 0, pDev1, &acl1, pDev2, &acl2, &provisioningCB)); } TEST_F(PM, OCProvisionPairwiseDevices) { PDMDeleteDevice(&pDev1->doxm->deviceID); PDMDeleteDevice(&pDev2->doxm->deviceID); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&pDev1->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&pDev2->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev1->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev2->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_256, pDev1, &acl1, pDev2, &acl2, &provisioningCB)); EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID)); EXPECT_EQ(OC_STACK_INVALID_PARAM, OCProvisionPairwiseDevices(NULL, SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_256, pDev1, &acl1, pDev2, &acl2, &provisioningCB)); } TEST_F(PM, OCGetDevInfoFromNetwork) { OCProvisionDev_t *pOwnedDevList = NULL; OCProvisionDev_t *pUnownedDevList = NULL; EXPECT_EQ(OC_STACK_OK, OCGetDevInfoFromNetwork(4, &pOwnedDevList, &pUnownedDevList)); } TEST_F(PM, OCUnlinkDevicesTestNullDevice1) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, NULL, pDev2, provisioningCB)); } TEST_F(PM, OCUnlinkDevicesTestNullDevice2) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, pDev1, NULL, provisioningCB)); } TEST_F(PM, OCUnlinkDevicesTestNullCallback) { EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCUnlinkDevices(NULL, pDev1, pDev2, NULL)); } TEST_F(PM, OCUnlinkDevicesTestSamelDeviceId) { EXPECT_EQ(OC_STACK_INVALID_PARAM, OCUnlinkDevices(NULL, pDev1, pDev1, provisioningCB)); } TEST_F(PM, OCUnlinkDevicesTest) { PDMDeleteDevice(&pDev1->doxm->deviceID); PDMDeleteDevice(&pDev2->doxm->deviceID); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&pDev1->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&pDev2->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev1->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev2->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, OCUnlinkDevices(NULL, pDev1, pDev2, provisioningCB)); } TEST_F(PM, OCRemoveDeviceTestNullTargetDevice) { unsigned short waitTime = 10 ; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, NULL, provisioningCB)); } TEST_F(PM, OCRemoveDeviceWithUuidTestNullTargetDevice) { unsigned short waitTime = 10 ; OicUuid_t uuid; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDeviceWithUuid(NULL, waitTime, NULL, provisioningCB)); EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCRemoveDeviceWithUuid(NULL, waitTime, &uuid, NULL)); } TEST_F(PM, OCRemoveDeviceTestNullResultCallback) { unsigned short waitTime = 10; EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCRemoveDevice(NULL, waitTime, pDev1, NULL)); } TEST_F(PM, OCRemoveDeviceTestZeroWaitTime) { unsigned short waitTime = 0; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCRemoveDevice(NULL, waitTime, pDev1, provisioningCB)); } TEST_F(PM, OCGetDevInfoFromNetworkTestNullUnOwnedDeviceInfo) { unsigned short waitTime = 10; OCProvisionDev_t *ownedList = NULL; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, &ownedList, NULL)); } TEST_F(PM, OCGetDevInfoFromNetworkTestNullOwnedDeviceInfo) { unsigned short waitTime = 10; OCProvisionDev_t *unownedList = NULL; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, NULL, &unownedList)); } TEST_F(PM, OCGetDevInfoFromNetworkTestZeroWaitTime) { unsigned short waitTime = 0; OCProvisionDev_t *ownedList = NULL; OCProvisionDev_t *unownedList = NULL; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetDevInfoFromNetwork(waitTime, &ownedList, &unownedList)); } TEST_F(PM, OCGetLinkedStatusTestNULLDeviceID) { OCUuidList_t *list = NULL; size_t noOfDevices = 0; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCGetLinkedStatus(NULL, &list, &noOfDevices)); } TEST_F(PM, OCDeleteUuidListTestNullUuidList) { OCDeleteUuidList(NULL); EXPECT_EQ(1, 1); } TEST_F(PM, OCDeleteACLListTestNullACLList) { OCDeleteACLList(NULL); EXPECT_EQ(1, 1); } TEST_F(PM, OCDeleteDiscoveredDevicesTestNullProvisionDevList) { OCDeleteDiscoveredDevices(NULL); EXPECT_EQ(1, 1); } TEST_F(PM, OCSetOwnerTransferCallbackDataTestNULLCallback) { OicSecOxm_t ownershipTransferMethod = OIC_JUST_WORKS; EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCSetOwnerTransferCallbackData(ownershipTransferMethod, NULL)); } TEST_F(PM, OCSetOwnerTransferCallbackDataTestInvalidOXMType) { OicSecOxm_t ownershipTransferMethod = OIC_OXM_COUNT; OTMCallbackData_t stOTMCallbackData = { &OTMLoadSecretCallback, NULL, NULL, NULL}; EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSetOwnerTransferCallbackData(ownershipTransferMethod, &stOTMCallbackData)); } TEST_F(PM, UpdateLinkResults) { Linkdata_t *link = (Linkdata_t *)OICMalloc(sizeof(Linkdata_t)); link->pDev1 = NULL; link->pDev1Acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t)); link->pDev2 = NULL; link->pDev2Acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t)); // link->ctx = ctx; link->numOfResults = 2; // link->resultCallback = resultCallback; link->currentCountResults = 0; link->resArr = (OCProvisionResult_t *)OICCalloc(link->numOfResults, sizeof(OCProvisionResult_t)); UpdateLinkResults(NULL, 1, OC_STACK_OK); UpdateLinkResults(link, 1, OC_STACK_OK); link->pDev1 = createProvisionDev(); UpdateLinkResults(link, 1, OC_STACK_OK); link->pDev2 = createProvisionDev(); UpdateLinkResults(link, 2, OC_STACK_OK); freeProvisionDev((OCProvisionDev_t *)link->pDev1); freeProvisionDev((OCProvisionDev_t *)link->pDev2); OICFree(link->pDev2Acl); OICFree(link->pDev1Acl); OICFree(link->resArr); OICFree(link); } static void prcb(void *ctx, size_t nOfRes, OCProvisionResult_t *arr, bool hasError) { OC_UNUSED(nOfRes); OC_UNUSED(arr); OC_UNUSED(hasError); OC_UNUSED(ctx); OIC_LOG_V(DEBUG, TAG, "%s", __func__); } Linkdata_t *createLinkData() { Linkdata_t *link = (Linkdata_t *)OICMalloc(sizeof(Linkdata_t)); link->pDev1 = createProvisionDev(); link->pDev1Acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t)); link->pDev2 = createProvisionDev(); link->pDev2Acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t)); link->numOfResults = 2; link->currentCountResults = 0; link->resArr = (OCProvisionResult_t *) OICMalloc(sizeof(OCProvisionResult_t) * link->numOfResults); link->resultCallback = prcb; return link; } void freeLinkData(Linkdata_t *link) { freeProvisionDev((OCProvisionDev_t *)link->pDev2); freeProvisionDev((OCProvisionDev_t *)link->pDev1); OICFree(link->resArr); OICFree(link->pDev2Acl); OICFree(link->pDev1Acl); OICFree(link); } TEST_F(PM, AclProv2CB) { OCProvisionResult_t *arr = (OCProvisionResult_t *)OICCalloc(1, sizeof(OCProvisionResult_t)); AclProv2CB(NULL, 1, arr, false); Linkdata_t *link = createLinkData(); AclProv2CB((void *)link, 1, arr, false); Linkdata_t *link1 = createLinkData(); AclProv2CB((void *)link1, 1, arr, true); OICFree(arr); } TEST_F(PM, ProvisionCredsCB) { Linkdata_t *link = createLinkData(); OCProvisionResult_t *arr = (OCProvisionResult_t *)OICCalloc(1, sizeof(OCProvisionResult_t)); ProvisionCredsCB(NULL, 1, arr, false); ProvisionCredsCB((void *)link, 1, arr, false); Linkdata_t *link1 = createLinkData(); ProvisionCredsCB((void *)link1, 1, arr, true); OICFree(arr); } TEST_F(PM, AclProv1CB) { Linkdata_t *link = createLinkData(); OCProvisionResult_t *arr = (OCProvisionResult_t *)OICCalloc(1, sizeof(OCProvisionResult_t)); AclProv1CB(NULL, 1, arr, false); AclProv1CB((void *)link, 1, arr, true); Linkdata_t *link1 = createLinkData(); AclProv1CB((void *)link1, 1, arr, false); OICFree(arr); } TEST_F(PM, RemoveDeviceInfoFromLocal) { OCProvisionDev_t *pDev = createProvisionDev(); PDMAddDevice(&pDev->doxm->deviceID); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, RemoveDeviceInfoFromLocal(pDev)); freeProvisionDev(pDev); } static void provisionResultCB(void *ctx, size_t nOfRes, OCProvisionResult_t *arr, bool hasError) { OC_UNUSED(ctx); OC_UNUSED(nOfRes); OC_UNUSED(arr); OC_UNUSED(hasError); OIC_LOG_V(DEBUG, TAG, "%s: has error: %d", __func__, hasError); } TEST_F(PM, OCRemoveDevice) { void *ctx = NULL; OCProvisionDev_t *pDev = createProvisionDev(); // EXPECT_EQ(OC_STACK_OK, PDMAddDevice(&pDev->doxm->deviceID)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, OCRemoveDevice(ctx, 1, pDev, provisionResultCB)); freeProvisionDev(pDev); } TEST_F(PM, OCRemoveDeviceWithUuid) { void *ctx = NULL; OicUuid_t *uuid1 = createUuidWith("33333333-3333-3333-3333-000000000000"); OicUuid_t *uuid2 = createUuidWith("33333333-3333-3333-3333-000000000001"); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(uuid1)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(uuid1, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, PDMAddDevice(uuid2)); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(uuid2, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_OK, PDMLinkDevices(uuid1, uuid2)); EXPECT_EQ(OC_STACK_OK, OCRemoveDeviceWithUuid(ctx, 1, uuid1, provisionResultCB)); freeUuid(uuid1); freeUuid(uuid2); } TEST_F(PM, OCResetDevice) { void *ctx = NULL; OCProvisionDev_t *pDev = createProvisionDev(); EXPECT_EQ(OC_STACK_OK, PDMSetDeviceState(&pDev->doxm->deviceID, PDM_DEVICE_ACTIVE)); EXPECT_EQ(OC_STACK_INVALID_PARAM, OCResetDevice(ctx, 0, pDev, provisionResultCB)); EXPECT_EQ(OC_STACK_INVALID_CALLBACK, OCResetDevice(ctx, 1, pDev, NULL)); EXPECT_EQ(OC_STACK_OK, OCResetDevice(ctx, 1, pDev, provisionResultCB)); freeProvisionDev(pDev); }
31.529274
103
0.721013
jonghenhan
48e402a279e54f54ab56e5d057de0f3300f6cece
9,435
cpp
C++
src/project/SEProjectProj.cpp
ysbing/voo
329d6a72ede6dd5903ca4d824bb3c49a5502f5c3
[ "Apache-2.0" ]
56
2022-01-29T04:52:27.000Z
2022-03-31T06:52:15.000Z
src/project/SEProjectProj.cpp
jumpingfrog0/VOO
af191ece986f997cf98f85016aa7288c323210c3
[ "Apache-2.0" ]
null
null
null
src/project/SEProjectProj.cpp
jumpingfrog0/VOO
af191ece986f997cf98f85016aa7288c323210c3
[ "Apache-2.0" ]
16
2022-01-29T04:52:39.000Z
2022-03-31T07:48:53.000Z
#include "SEProjectProj.h" #include <QDebug> #include <QDir> #include <QFile> #include <QFileInfo> #include <QJsonDocument> #include <QJsonObject> #include <QTextStream> #include <QTimer> #include <QUrl> #include <QUuid> #include <QtGlobal> #include "SEProject.h" #include "base/http/SEHttpClient.h" #include "base/utils/AppConstance.h" #include "src/base/utils/fileutils.h" #include "user/Login.h" ProjType SEProjectProj::projTypeWithString(QString c) { if (c.toLower() == "timeline") { return Timeline; } else if (c.toLower() == "effect") { return Effect; } else if (c.toLower() == "file") { return File; } else { return UnKnow; } } QString SEProjectProj::stringWithProjType(ProjType projType) { switch (projType) { case Timeline: return "Timeline"; case Effect: return "Effect"; case File: return "File"; default: return ""; } } QString SEProjectProj::id() const { return m_id; } QString SEProjectProj::title() const { return m_title; } QString SEProjectProj::remoteId() const { return m_remoteId; } QString SEProjectProj::version() const { return m_version; } QString SEProjectProj::anchor() const { return m_anchor; } QString SEProjectProj::summary() const { return m_summary; } ProjType SEProjectProj::type() const { return m_type; } QString SEProjectProj::thumb() const { return FileUtils::getFileAbsolutePath(m_rootPath, m_thumb); } QString SEProjectProj::inputList() const { return FileUtils::getFileAbsolutePath(m_rootPath, m_inputList); } QString SEProjectProj::inputConfig() const { return m_inputConfig; } QDateTime SEProjectProj::createTimestamp() const { return m_createTimestamp; } QDateTime SEProjectProj::lastChangedTimestamp() const { return m_lastChangedTimestamp; } QString SEProjectProj::projectDir() const { return m_rootPath; } bool SEProjectProj::isDebug() const { return m_isDebug; } bool SEProjectProj::isTemp() const { return m_isTemp; } void SEProjectProj::setTitle(QString title) { m_title = title; } void SEProjectProj::updateCreateTimestamp() { m_createTimestamp = QDateTime::currentDateTime(); } void SEProjectProj::setAnchor(QString s) { m_anchor = s; } void SEProjectProj::setSummary(QString s) { m_summary = s; } void SEProjectProj::setType(ProjType t) { m_type = t; } void SEProjectProj::setThumb(QString s) { m_thumb = s; } void SEProjectProj::setFile(QString filePath) { QFileInfo info(filePath); switch (m_type) { case Timeline: m_skyFile = "bundle://" + info.fileName(); break; case Effect: m_ofFile = "bundle://" + info.fileName(); break; case File: default: m_resFile = "bundle://" + info.fileName(); break; } } void SEProjectProj::setRemoteId(QString remoteId) { m_remoteId = remoteId; } QString SEProjectProj::entryFile() { switch (m_type) { case Timeline: return FileUtils::realPath(m_rootPath, m_skyFile); case Effect: return FileUtils::realPath(m_rootPath, m_ofFile); case File: default: return FileUtils::realPath(m_rootPath, m_resFile); } } SEProjectProj::SEProjectProj(QString projectFile) { QFileInfo projFile(projectFile); m_rootPath = projFile.absolutePath(); QDir dir(m_rootPath); if (!dir.exists()) { qInfo("open root_dir fail, not found!"); return; } if (projFile.exists()) { QString context = FileUtils::readJson(projFile.filePath()); qDebug() << "projFile json : " << context; auto jsonObject = QJsonDocument::fromJson(context.toUtf8()).object(); m_id = jsonObject.value("id").toString(); m_title = jsonObject.value("title").toString().replace(":", ""); m_remoteId = jsonObject.value("remoteId").toString(); m_version = jsonObject.value("version").toString(); m_anchor = jsonObject.value("anchor").toString(); m_summary = jsonObject.value("summary").toString(); QString t = jsonObject.value("type").toString(); m_type = projTypeWithString(t); m_thumb = jsonObject.value("thumb").toString(); if (m_thumb.isEmpty()) { m_thumb = "cover.jpg"; } m_inputList = jsonObject.value("inputList").toString(); if (m_inputList.isEmpty()) { m_inputList = "inputList.conf"; } m_skyFile = jsonObject.value("skyFile").toString(); if (m_skyFile.isEmpty()) { m_skyFile = "timeline.sky"; } m_ofFile = jsonObject.value("ofFile").toString(); m_resFile = jsonObject.value("resFile").toString(); m_inputConfig = jsonObject.value("inputConfig").toString(); m_createTimestamp = QDateTime::fromTime_t(jsonObject.value("createTimestamp").toDouble()); m_lastChangedTimestamp = QDateTime::fromTime_t(jsonObject.value("lastChangedTimestamp").toDouble()); m_isDebug = jsonObject.value("isDebug").toBool(); m_extraData = jsonObject.value("extra").toObject(); } else { qDebug("SEProjectProj init"); QUuid IID_MyInterface(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee); m_id = IID_MyInterface.toString(); m_title = dir.dirName(); m_remoteId = ""; m_version = AppConstance::appVer(); m_anchor = "unknow"; m_summary = ""; m_type = Timeline; m_thumb = "cover.jpg"; m_inputList = "inputList.conf"; m_skyFile = "timeline.sky"; m_ofFile = ""; m_resFile = ""; m_inputConfig = ""; m_createTimestamp = QDateTime::currentDateTime(); m_lastChangedTimestamp = m_createTimestamp; m_isDebug = true; m_isTemp = true; } } QString SEProjectProj::projFilePath(QString root_dir) { QString oldProjFile = findProjectFile(root_dir); if (oldProjFile.length() > 10) { return oldProjFile; } else { return QFileInfo(root_dir, QString("template.") + PROJ_SUFFIX).filePath(); } } QString SEProjectProj::findProjectFile(QString root_dir) { QDir dir(root_dir); if (!dir.exists()) { qInfo("open root_dir fail, not found!"); return ""; } dir.setFilter(QDir::Files); QFileInfoList list = dir.entryInfoList(); if (list.count() == 0) { return ""; } int i = 0; QFileInfo projFile; bool finded = false; do { QFileInfo fileInfo = list.at(i); if (fileInfo.suffix() == PROJ_SUFFIX) { projFile = fileInfo; finded = true; break; } i++; } while (i < list.size()); if (!finded) { return ""; } return QDir::toNativeSeparators(projFile.absoluteFilePath()); } void SEProjectProj::createFile(QString projectFile) { SEProjectProj newProjFile(projectFile); QFileInfo file(projectFile); if (file.exists()) { QFile::remove(projectFile); } // create empty file newProjFile.realSave(file.absoluteDir().absolutePath()); } void SEProjectProj::save(QString root_dir) { if (!SEProject::isQuit() && m_type == Timeline) { QImage image = SEProject::current()->dom()->previewController()->getSkyTimelineView()->snapFrame(); qDebug() << "SEProjectProj::snapFrame " << &image; if (!image.isNull()) { QString imagePath = thumb(); if (QFile::exists(imagePath)) { QFile::remove(imagePath); } image.save(imagePath, "JPG"); } } this->realSave(root_dir); } void SEProjectProj::realSave(QString root_dir) { QString prjFilePath = projFilePath(root_dir); QFile file(prjFilePath); m_lastChangedTimestamp = QDateTime::currentDateTime(); if (file.open(QIODevice::WriteOnly)) { QJsonObject root; root.insert("id", m_id); root.insert("title", m_title); root.insert("remoteId", m_remoteId); root.insert("version", m_version); root.insert("anchor", m_anchor); root.insert("summary", m_summary); root.insert("type", stringWithProjType(m_type)); root.insert("thumb", m_thumb); root.insert("inputList", m_inputList); root.insert("skyFile", m_skyFile); root.insert("ofFile", m_ofFile); root.insert("resFile", m_resFile); root.insert("inputConfig", m_inputConfig); root.insert("createTimestamp", QString::number(m_createTimestamp.toTime_t())); root.insert("lastChangedTimestamp", QString::number(m_lastChangedTimestamp.toTime_t())); root.insert("isDebug", QString::number(m_isDebug)); root.insert("extra", m_extraData); QJsonDocument doc(root); QByteArray jsonData = doc.toJson(QJsonDocument::Compact); file.write(jsonData); file.close(); } else { qInfo("SEProjectProj updateFile fail! File: %s", file.fileName().toStdString().c_str()); } } QJsonValue SEProjectProj::getExtraData(const QString &key) const { return m_extraData.value(key); } void SEProjectProj::setExtraData(const QString &key, const QJsonValue &value) { m_extraData.insert(key, value); } void SEProjectProj::setIsTemp(bool isTemp) { m_isTemp = isTemp; }
30.047771
108
0.630207
ysbing
48e7e68b78f7409dcf2aa8a0d06ed1180f1852ab
3,575
cc
C++
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/src/inet/networklayer/common/L3Tools.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
1
2021-07-02T13:32:40.000Z
2021-07-02T13:32:40.000Z
// // Copyright (C) 2017 OpenSim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include "inet/networklayer/common/L3Tools.h" #ifdef WITH_IPv4 #include "inet/networklayer/ipv4/Ipv4Header_m.h" #endif #ifdef WITH_IPv6 #include "inet/networklayer/ipv6/Ipv6Header.h" #endif #ifdef WITH_NEXTHOP #include "inet/networklayer/nexthop/NextHopForwardingHeader_m.h" #endif namespace inet { const Protocol *findNetworkProtocol(Packet *packet) { auto networkProtocolInd = packet->findTag<NetworkProtocolInd>(); return networkProtocolInd == nullptr ? nullptr : networkProtocolInd->getProtocol(); } const Protocol& getNetworkProtocol(Packet *packet) { auto protocol = findNetworkProtocol(packet); if (protocol == nullptr) throw cRuntimeError("Network protocol not found"); else return *protocol; } const Ptr<const NetworkHeaderBase> findNetworkProtocolHeader(Packet *packet) { auto networkProtocolInd = packet->findTag<NetworkProtocolInd>(); return networkProtocolInd == nullptr ? nullptr : dynamicPtrCast<const NetworkHeaderBase>(networkProtocolInd->getNetworkProtocolHeader()); } const Ptr<const NetworkHeaderBase> getNetworkProtocolHeader(Packet *packet) { const auto& header = findNetworkProtocolHeader(packet); if (header == nullptr) throw cRuntimeError("Network protocol header not found"); else return header; } const Ptr<const NetworkHeaderBase> peekNetworkProtocolHeader(const Packet *packet, const Protocol& protocol) { #ifdef WITH_IPv4 if (protocol == Protocol::ipv4) return packet->peekAtFront<Ipv4Header>(); #endif #ifdef WITH_IPv6 if (protocol == Protocol::ipv6) return packet->peekAtFront<Ipv6Header>(); #endif #ifdef WITH_NEXTHOP if (protocol == Protocol::nextHopForwarding) return packet->peekAtFront<NextHopForwardingHeader>(); #endif // TODO: add other L3 protocols throw cRuntimeError("Unknown protocol: %s", protocol.getName()); } void insertNetworkProtocolHeader(Packet *packet, const Protocol& protocol, const Ptr<NetworkHeaderBase>& header) { auto networkProtocolInd = packet->addTagIfAbsent<NetworkProtocolInd>(); networkProtocolInd->setProtocol(&protocol); networkProtocolInd->setNetworkProtocolHeader(header); insertProtocolHeader(packet, protocol, header); } const Ptr<NetworkHeaderBase> removeNetworkProtocolHeader(Packet *packet, const Protocol& protocol) { #ifdef WITH_IPv4 if (protocol == Protocol::ipv4) return removeNetworkProtocolHeader<Ipv4Header>(packet); #endif #ifdef WITH_IPv6 if (protocol == Protocol::ipv6) return removeNetworkProtocolHeader<Ipv6Header>(packet); #endif #ifdef WITH_NEXTHOP if (protocol == Protocol::nextHopForwarding) return removeNetworkProtocolHeader<NextHopForwardingHeader>(packet); #endif // TODO: add other L3 protocols throw cRuntimeError("Unknown protocol: %s", protocol.getName()); } } // namespace inet
33.101852
141
0.75049
ntanetani
48e8674d6d5517f40558d623134166ad6e310637
12,945
cpp
C++
platform_bionic-android-vts-12.0_r2/libc/bionic/fdsan.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
1
2019-05-04T02:30:08.000Z
2019-05-04T02:30:08.000Z
platform_bionic-android-vts-12.0_r2/libc/bionic/fdsan.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
platform_bionic-android-vts-12.0_r2/libc/bionic/fdsan.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <android/fdsan.h> #include <errno.h> #include <inttypes.h> #include <signal.h> #include <stdarg.h> #include <stdatomic.h> #include <string.h> #include <sys/cdefs.h> #include <sys/mman.h> #include <sys/syscall.h> #include <unistd.h> #include <async_safe/log.h> #include <platform/bionic/reserved_signals.h> #include <sys/system_properties.h> #include "private/bionic_fdtrack.h" #include "private/bionic_globals.h" #include "private/bionic_inline_raise.h" #include "pthread_internal.h" extern "C" int __close(int fd); pid_t __get_cached_pid(); static constexpr const char* kFdsanPropertyName = "debug.fdsan"; template<size_t inline_fds> FdEntry* FdTableImpl<inline_fds>::at(size_t idx) { if (idx < inline_fds) { return &entries[idx]; } // Try to create the overflow table ourselves. FdTableOverflow* local_overflow = atomic_load(&overflow); if (__predict_false(!local_overflow)) { struct rlimit rlim = { .rlim_max = 32768 }; getrlimit(RLIMIT_NOFILE, &rlim); rlim_t max = rlim.rlim_max; if (max == RLIM_INFINITY) { // This isn't actually possible (the kernel has a hard limit), but just // in case... max = 32768; } if (idx > max) { // This can happen if an fd is created and then the rlimit is lowered. // In this case, just return nullptr and ignore the fd. return nullptr; } size_t required_count = max - inline_fds; size_t required_size = sizeof(FdTableOverflow) + required_count * sizeof(FdEntry); size_t aligned_size = __BIONIC_ALIGN(required_size, PAGE_SIZE); size_t aligned_count = (aligned_size - sizeof(FdTableOverflow)) / sizeof(FdEntry); void* allocation = mmap(nullptr, aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (allocation == MAP_FAILED) { async_safe_fatal("fdsan: mmap failed: %s", strerror(errno)); } FdTableOverflow* new_overflow = reinterpret_cast<FdTableOverflow*>(allocation); new_overflow->len = aligned_count; if (atomic_compare_exchange_strong(&overflow, &local_overflow, new_overflow)) { local_overflow = new_overflow; } else { // Someone beat us to it. Deallocate and use theirs. munmap(allocation, aligned_size); } } size_t offset = idx - inline_fds; if (local_overflow->len < offset) { return nullptr; } return &local_overflow->entries[offset]; } void __libc_init_fdsan() { constexpr auto default_level = ANDROID_FDSAN_ERROR_LEVEL_FATAL; android_fdsan_set_error_level_from_property(default_level); } static FdTable& GetFdTable() { return __libc_shared_globals()->fd_table; } // Exposed to the platform to allow crash_dump to print out the fd table. extern "C" void* android_fdsan_get_fd_table() { return &GetFdTable(); } static FdEntry* GetFdEntry(int fd) { if (fd < 0) { return nullptr; } return GetFdTable().at(fd); } __printflike(1, 0) static void fdsan_error(const char* fmt, ...) { auto& fd_table = GetFdTable(); auto error_level = atomic_load(&fd_table.error_level); if (error_level == ANDROID_FDSAN_ERROR_LEVEL_DISABLED) { return; } struct { size_t size; char buf[512]; } abort_message; va_list va; va_start(va, fmt); if (error_level == ANDROID_FDSAN_ERROR_LEVEL_FATAL) { async_safe_fatal_va_list("fdsan", fmt, va); } else { async_safe_format_log_va_list(ANDROID_LOG_ERROR, "fdsan", fmt, va); va_end(va); va_start(va, fmt); size_t len = async_safe_format_buffer_va_list(abort_message.buf, sizeof(abort_message.buf), fmt, va); abort_message.size = len + sizeof(size_t); } va_end(va); switch (error_level) { case ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE: atomic_compare_exchange_strong(&fd_table.error_level, &error_level, ANDROID_FDSAN_ERROR_LEVEL_DISABLED); __BIONIC_FALLTHROUGH; case ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS: inline_raise(BIONIC_SIGNAL_DEBUGGER, &abort_message); break; case ANDROID_FDSAN_ERROR_LEVEL_FATAL: inline_raise(SIGABRT); abort(); case ANDROID_FDSAN_ERROR_LEVEL_DISABLED: break; } } uint64_t android_fdsan_create_owner_tag(android_fdsan_owner_type type, uint64_t tag) { if (tag == 0) { return 0; } if (__predict_false((type & 0xff) != type)) { async_safe_fatal("invalid android_fdsan_owner_type value: %x", type); } uint64_t result = static_cast<uint64_t>(type) << 56; uint64_t mask = (static_cast<uint64_t>(1) << 56) - 1; result |= tag & mask; return result; } const char* android_fdsan_get_tag_type(uint64_t tag) { uint64_t type = tag >> 56; switch (type) { case ANDROID_FDSAN_OWNER_TYPE_FILE: return "FILE*"; case ANDROID_FDSAN_OWNER_TYPE_DIR: return "DIR*"; case ANDROID_FDSAN_OWNER_TYPE_UNIQUE_FD: return "unique_fd"; case ANDROID_FDSAN_OWNER_TYPE_FILEINPUTSTREAM: return "FileInputStream"; case ANDROID_FDSAN_OWNER_TYPE_FILEOUTPUTSTREAM: return "FileOutputStream"; case ANDROID_FDSAN_OWNER_TYPE_RANDOMACCESSFILE: return "RandomAccessFile"; case ANDROID_FDSAN_OWNER_TYPE_PARCELFILEDESCRIPTOR: return "ParcelFileDescriptor"; case ANDROID_FDSAN_OWNER_TYPE_SQLITE: return "sqlite"; case ANDROID_FDSAN_OWNER_TYPE_ART_FDFILE: return "ART FdFile"; case ANDROID_FDSAN_OWNER_TYPE_DATAGRAMSOCKETIMPL: return "DatagramSocketImpl"; case ANDROID_FDSAN_OWNER_TYPE_SOCKETIMPL: return "SocketImpl"; case ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE: return "ZipArchive"; case ANDROID_FDSAN_OWNER_TYPE_GENERIC_00: default: return "native object of unknown type"; case ANDROID_FDSAN_OWNER_TYPE_GENERIC_FF: // If bits 48 to 56 are set, this is a sign-extended generic native pointer uint64_t high_bits = tag >> 48; if (high_bits == (1 << 16) - 1) { return "native object of unknown type"; } return "Java object of unknown type"; } } uint64_t android_fdsan_get_tag_value(uint64_t tag) { // Lop off the most significant byte and sign extend. return static_cast<uint64_t>(static_cast<int64_t>(tag << 8) >> 8); } int android_fdsan_close_with_tag(int fd, uint64_t expected_tag) { if (__get_thread()->is_vforked()) { return __close(fd); } FDTRACK_CLOSE(fd); FdEntry* fde = GetFdEntry(fd); if (!fde) { return __close(fd); } uint64_t tag = expected_tag; if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, 0)) { const char* expected_type = android_fdsan_get_tag_type(expected_tag); uint64_t expected_owner = android_fdsan_get_tag_value(expected_tag); const char* actual_type = android_fdsan_get_tag_type(tag); uint64_t actual_owner = android_fdsan_get_tag_value(tag); if (expected_tag && tag) { fdsan_error( "attempted to close file descriptor %d, " "expected to be owned by %s 0x%" PRIx64 ", actually owned by %s 0x%" PRIx64, fd, expected_type, expected_owner, actual_type, actual_owner); } else if (expected_tag && !tag) { fdsan_error( "attempted to close file descriptor %d, " "expected to be owned by %s 0x%" PRIx64 ", actually unowned", fd, expected_type, expected_owner); } else if (!expected_tag && tag) { fdsan_error( "attempted to close file descriptor %d, " "expected to be unowned, actually owned by %s 0x%" PRIx64, fd, actual_type, actual_owner); } else if (!expected_tag && !tag) { // This should never happen: our CAS failed, but expected == actual? async_safe_fatal("fdsan atomic_compare_exchange_strong failed unexpectedly while closing"); } } int rc = __close(fd); // If we were expecting to close with a tag, abort on EBADF. if (expected_tag && rc == -1 && errno == EBADF) { fdsan_error("double-close of file descriptor %d detected", fd); } return rc; } uint64_t android_fdsan_get_owner_tag(int fd) { FdEntry* fde = GetFdEntry(fd); if (!fde) { return 0; } return fde->close_tag; } void android_fdsan_exchange_owner_tag(int fd, uint64_t expected_tag, uint64_t new_tag) { if (__get_thread()->is_vforked()) { return; } FdEntry* fde = GetFdEntry(fd); if (!fde) { return; } uint64_t tag = expected_tag; if (!atomic_compare_exchange_strong(&fde->close_tag, &tag, new_tag)) { if (expected_tag && tag) { fdsan_error( "failed to exchange ownership of file descriptor: fd %d is " "owned by %s 0x%" PRIx64 ", was expected to be owned by %s 0x%" PRIx64, fd, android_fdsan_get_tag_type(tag), android_fdsan_get_tag_value(tag), android_fdsan_get_tag_type(expected_tag), android_fdsan_get_tag_value(expected_tag)); } else if (expected_tag && !tag) { fdsan_error( "failed to exchange ownership of file descriptor: fd %d is " "unowned, was expected to be owned by %s 0x%" PRIx64, fd, android_fdsan_get_tag_type(expected_tag), android_fdsan_get_tag_value(expected_tag)); } else if (!expected_tag && tag) { fdsan_error( "failed to exchange ownership of file descriptor: fd %d is " "owned by %s 0x%" PRIx64 ", was expected to be unowned", fd, android_fdsan_get_tag_type(tag), android_fdsan_get_tag_value(tag)); } else if (!expected_tag && !tag) { // This should never happen: our CAS failed, but expected == actual? async_safe_fatal( "fdsan atomic_compare_exchange_strong failed unexpectedly while exchanging owner tag"); } } } android_fdsan_error_level android_fdsan_get_error_level() { return GetFdTable().error_level; } android_fdsan_error_level android_fdsan_set_error_level(android_fdsan_error_level new_level) { if (__get_thread()->is_vforked()) { return android_fdsan_get_error_level(); } return atomic_exchange(&GetFdTable().error_level, new_level); } android_fdsan_error_level android_fdsan_set_error_level_from_property( android_fdsan_error_level default_level) { const prop_info* pi = __system_property_find(kFdsanPropertyName); if (!pi) { return android_fdsan_set_error_level(default_level); } struct callback_data { android_fdsan_error_level default_value; android_fdsan_error_level result; }; callback_data data; data.default_value = default_level; __system_property_read_callback( pi, [](void* arg, const char*, const char* value, uint32_t) { callback_data* data = static_cast<callback_data*>(arg); if (strcasecmp(value, "1") == 0 || strcasecmp(value, "fatal") == 0) { data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_FATAL); } else if (strcasecmp(value, "warn") == 0) { data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS); } else if (strcasecmp(value, "warn_once") == 0) { data->result = android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE); } else { if (strlen(value) != 0 && strcasecmp(value, "0") != 0) { async_safe_format_log(ANDROID_LOG_ERROR, "libc", "debug.fdsan set to unknown value '%s', disabling", value); } data->result = android_fdsan_set_error_level(data->default_value); } }, &data); return data.result; } int close(int fd) { int rc = android_fdsan_close_with_tag(fd, 0); if (rc == -1 && errno == EINTR) { return 0; } return rc; }
33.363402
99
0.69803
webos21
48ea917edb1ea6085842e06dcf134ff0055369a5
3,951
cpp
C++
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
src/Audio.cpp
noloitering/NoSFX
0ed636db4c403c7cb8a6ffb1714db2b46d105329
[ "Zlib" ]
null
null
null
#include "Audio.h" using namespace NoSFX; AudioManager::AudioManager(std::shared_ptr< Music > music, float vol, float pitch, bool play) { InitAudioDevice(); if ( vol >= 1 ) { volume.master = 1; } else if ( vol > 0 ) { volume.master = vol; } else { volume.master = 0; } SetMasterVolume(volume.master); if ( music ) { SetMusicPitch(*(music), pitch); track = music; if ( play ) { PlayMusicStream(*(track)); } } } AudioManager::AudioManager(std::shared_ptr< Music > music, const Volume& vol, const Pitch& pitch, bool play) { InitAudioDevice(); SetMasterVolume(vol.master); volume = vol; pitches = pitch; if ( music ) { track = music; SetMusicPitch(*(track), pitch.music); SetMusicVolume(*(track), vol.music); if ( play ) { PlayMusicStream(*(track)); } } } void AudioManager::update() { if ( track ) { UpdateMusicStream(*(track)); float timePlayed = GetMusicTimePlayed(*(track))/GetMusicTimeLength(*(track)); if ( timePlayed > 1 ) { StopMusicStream(*(track)); } } } void AudioManager::play(std::shared_ptr< Sound > sound) { SetSoundVolume(*(sound), volume.sfx); SetSoundPitch(*(sound), pitches.sfx); PlaySoundMulti(*(sound)); } void AudioManager::play(std::shared_ptr< Sound > sound, float vol, float pitch) { SetSoundVolume(*(sound), vol); SetSoundPitch(*(sound), pitch); PlaySoundMulti(*(sound)); } void AudioManager::stream(std::shared_ptr< Music > music, bool loop) { music->looping = loop; SetMusicVolume(*(music), volume.music); SetMusicPitch(*(music), pitches.music); track = music; PlayMusicStream(*(music)); } void AudioManager::stream(std::shared_ptr< Music > music, float vol, float pitch, bool loop) { music->looping = loop; SetMusicVolume(*(music), vol); SetMusicPitch(*(music), pitch); track = music; PlayMusicStream(*(music)); } void AudioManager::adjustVolume(const Volume& vol) { volume = vol; SetMasterVolume(volume.master); if ( track ) { SetMusicVolume(*(track), volume.music); } } void AudioManager::adjustPitch(const Pitch& pitch) { pitches = pitch; if ( track ) { SetMusicVolume(*(track), pitches.music); } } void AudioManager::adjustTrackVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } if ( track ) { SetMusicVolume(*(track), vol); } } void AudioManager::adjustMusicVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.music = vol; if ( track ) { SetMusicVolume(*(track), volume.music); } } void AudioManager::adjustSFXVolume(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.sfx = vol; } void AudioManager::adjustSoundVolume(std::shared_ptr< Sound > sound, float vol) { SetSoundVolume(*(sound), vol); } void AudioManager::adjustMaster(float vol) { if ( vol >= 1 ) { vol = 1; } else if ( vol < 0 ) { vol = 0; } volume.master = vol; SetMasterVolume(volume.master); } void AudioManager::adjustTrackPitch(float pitch) { if ( track ) { SetMusicPitch(*(track), pitch); } } void AudioManager::adjustMusicPitch(float pitch) { pitches.music = pitch; adjustTrackPitch(pitch); } void AudioManager::adjustSFXPitch(float pitch) { pitches.sfx = pitch; } void AudioManager::adjustSoundPitch(std::shared_ptr< Sound > sound, float pitch) { SetSoundPitch(*(sound), pitch); } void AudioManager::pauseTrack() { PauseMusicStream(*(track)); } void AudioManager::resumeTrack() { if ( trackPlayed() >= 1 ) { ResumeMusicStream(*(track)); } else { PlayMusicStream(*(track)); } } void AudioManager::stopTrack() { StopMusicStream(*(track)); } void AudioManager::seekTrack(float pos) { SeekMusicStream(*(track), pos); } bool AudioManager::trackPlaying() { return IsMusicStreamPlaying(*(track)); } float AudioManager::trackLength() { return GetMusicTimeLength(*(track)); } float AudioManager::trackPlayed() { return GetMusicTimePlayed(*(track)); }
16.060976
108
0.660086
noloitering
48ec48a27482e7ed71f133ea6d5f0ac818e64a5a
1,019
cpp
C++
DMOPC/dmopc20c3p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
DMOPC/dmopc20c3p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
DMOPC/dmopc20c3p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#ifndef LOCAL #pragma GCC optimize("O3") #pragma GCC target("sse4") #endif #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; const int MM = 3e4+5; int n, a[MM], psa[MM], ans; int dp[MM], pre[MM]; //dp[index][cnt] = max{last length} int mx1[MM], mx2[MM]; void go(){ memset(dp, 0, sizeof dp); dp[0] = 1e9; for(int i = 0; i <= n; i++) psa[i] = psa[i-1]+a[i]; for(int j = 1; j <= n; j++){ swap(pre, dp); dp[0] = 0; int l = 0; for(int i = 1; i <= n; i++){ while(psa[i]-psa[l] > pre[l]) l++; if(psa[i]-psa[l] <= pre[l]) dp[i] = psa[i]-psa[l]; else dp[i] = 0; if(dp[i]) mx1[i] = j; } } } int main(){ #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif cin>>n; for(int i = 1; i <= n; i++) cin>>a[i]; go(); swap(mx1, mx2); reverse(a+1, a+1+n); go(); reverse(mx2+1, mx2+1+n); for(int i = 1; i <= n; i++) ans = max(ans, mx1[i]+mx2[i+1]); cout<<ans<<'\n'; }
17.271186
38
0.479882
crackersamdjam
48f0b52da3268d26c99b9e6a2e3b98518b135c5e
428
cpp
C++
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
DearPyGui/src/core/PythonUtilities/mvPythonExceptions.cpp
iqxd/DearPyGui
ad6209cb9b7e2a6466a49ce71a438d1d349f0374
[ "MIT" ]
null
null
null
#define PY_SSIZE_T_CLEAN #include <Python.h> #include <frameobject.h> #include <string> #include "mvPythonTranslator.h" #include "mvGlobalIntepreterLock.h" namespace Marvel { void ThrowPythonException(const std::string& message) { std::string fullMessage = "Line: %d \t" + message; int line = PyFrame_GetLineNumber(PyEval_GetFrame()); PyErr_Format(PyExc_Exception, fullMessage.c_str(), line); PyErr_Print(); } }
19.454545
59
0.742991
iqxd
f70a943e238450ef3c4c3c3937d3ac87541e073a
3,267
cpp
C++
src/external_source_ui.cpp
indjev99/Sixty-Six-Bot
7a09e4fade6671ebf51f8721b860b7f48653d7a9
[ "MIT" ]
null
null
null
src/external_source_ui.cpp
indjev99/Sixty-Six-Bot
7a09e4fade6671ebf51f8721b860b7f48653d7a9
[ "MIT" ]
null
null
null
src/external_source_ui.cpp
indjev99/Sixty-Six-Bot
7a09e4fade6671ebf51f8721b860b7f48653d7a9
[ "MIT" ]
null
null
null
#include "external_source_ui.h" #include "printing.h" #include "config.h" #include "util.h" #include <iostream> Move stringToMove(const std::string& moveStr) { Move move; move.type = M_CLOSE; if (stringMatch(moveStr, move.toString())) return move; move.type = M_EXCHANGE; if (stringMatch(moveStr, move.toString())) return move; move.type = M_PLAY; for (int code = 0; code < NUM_SUITS * NUM_RANKS; ++code) { move.score = 0; move.card = Card(code); if (stringMatch(moveStr, move.toString())) return move; if (!isMarriageRank(move.card.rank)) continue; move.score = 1; if (stringMatch(moveStr, move.toString())) return move; } return Move(); } Move inputMove() { std::string moveStr; Move move; do { std::cin >> moveStr; move = stringToMove(moveStr); } while (move.type == M_NONE); return move; } Card inputCard() { Move cardMove; do { cardMove = inputMove(); } while (cardMove.type != M_PLAY || cardMove.score); return cardMove.card; } ExternalSourceUI::ExternalSourceUI(bool printing): printing(printing) {} bool ExternalSourceUI::getLeading() { std::cout << std::endl; std::cout << "Leading (0/1): "; bool leading; std::cin >> leading; moveUpOneLine(); if (printing) { if (leading) std::cout << "You are leading" << std::endl; else std::cout << "Opponent is leading" << std::endl; } else moveUpOneLine(); return leading; } Card ExternalSourceUI::getTrumpCard() { if (!printing) std::cout << std::endl; std::cout << "Trump card: "; Card trumpCard = inputCard(); moveUpOneLine(); if (printing) { std::cout << "Trump card: "; printCard(trumpCard); std::cout << std::endl; } else moveUpOneLine(); return trumpCard; } std::vector<Card> ExternalSourceUI::getHand() { if (!printing) std::cout << std::endl; std::cout << "Hand: "; std::vector<Card> hand(HAND_SIZE); for (Card& card : hand) { card = inputCard(); } moveUpOneLine(); if (printing) { std::cout << "Hand:"; for (Card& card : hand) { std::cout << " "; printCard(card); } std::cout << std::endl; } else moveUpOneLine(); return hand; } Card ExternalSourceUI::getDrawnCard() { if (!printing) std::cout << std::endl; std::cout << "Drawn card: "; Card drawnCard = inputCard(); moveUpOneLine(); if (printing) { std::cout << "Drawn card: "; printCard(drawnCard); std::cout << std::endl; } else moveUpOneLine(); return drawnCard; } Move ExternalSourceUI::getMove() { if (!printing) std::cout << std::endl; std::cout << "Opponent's move: "; Move move = inputMove(); moveUpOneLine(); if (printing) { std::cout << "Opponent's move: "; printMove(move); std::cout << std::endl; } else moveUpOneLine(); return move; } void ExternalSourceUI::giveMove(Move move) { if (!printing) return; std::cout << "Your move: "; printMove(move); std::cout << std::endl; }
19.217647
65
0.563208
indjev99
f70b496324744403c23597e19012e584c08a599b
667
cpp
C++
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
parser/src/Simp.cpp
AnZhuoKaiFaZhe/ctl2snf
935574f871e05068c9931d2444cfd50759fae0bc
[ "MIT" ]
null
null
null
// // Created by mzy on 2021-06-03. // #include "Simp.hpp" Tree<ASTNode>* simp(Tree<ASTNode>* n,Tree<ASTNode>* l,Tree<ASTNode>* r){ switch (n->root.type) { case NodeType_t::LogicAnd: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return r; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return l; return n; case NodeType_t::LogicOr: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return l; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return r; return n; } }
33.35
91
0.574213
AnZhuoKaiFaZhe
f70e82ed932ea8fe65fe964d8675f22c2d8386f3
2,543
cpp
C++
libnd4j/include/execution/cpu/ContextBuffers.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
2,206
2019-06-12T18:57:14.000Z
2022-03-29T08:14:27.000Z
libnd4j/include/execution/cpu/ContextBuffers.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
1,685
2019-06-12T17:41:33.000Z
2022-03-29T21:45:15.000Z
libnd4j/include/execution/cpu/ContextBuffers.cpp
steljord2/deeplearning4j
4653c97a713cc59e41d4313ddbafc5ff527f8714
[ "Apache-2.0" ]
572
2019-06-12T22:13:57.000Z
2022-03-31T16:46:46.000Z
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <execution/AffinityManager.h> #include <execution/ContextBuffers.h> namespace sd { ContextBuffers::ContextBuffers() { _deviceId = AffinityManager::currentDeviceId(); } ContextBuffers::~ContextBuffers() { // no-op } ContextBuffers::ContextBuffers(void* rPointer, void* sPointer, void* aPointer, bool isOwner) { _reductionPointer = rPointer; _scalarPointer = sPointer; _allocationPointer = aPointer; _allocated = isOwner; } ContextBuffers::ContextBuffers(const ContextBuffers& other) { // } void ContextBuffers::initialize() { // no-op } void* ContextBuffers::reductionBuffer() { return _reductionPointer; } void* ContextBuffers::scalarBuffer() { return _scalarPointer; } void* ContextBuffers::allocationBuffer() { return _allocationPointer; } void ContextBuffers::setReductionBuffer(void* pointer) { _reductionPointer = pointer; } void ContextBuffers::setScalarBuffer(void* pointer) { _scalarPointer = pointer; } void ContextBuffers::setAllocationBuffer(void* pointer) { _allocationPointer = pointer; } void ContextBuffers::triggerOwnership(bool isOwner) { _allocated = isOwner; } int ContextBuffers::deviceId() { return _deviceId; } void* ContextBuffers::execStream() { return _execStream; } void* ContextBuffers::specialStream() { return _specialStream; } bool ContextBuffers::isInitialized() { return true; } void ContextBuffers::release() { // } ContextBuffers& ContextBuffers::operator=(const ContextBuffers& other) { return *this; } ContextBuffers& ContextBuffers::operator=(ContextBuffers&& other) { return *this; } sd::ErrorReference* ContextBuffers::errorReference() { return &_errorReference; } } // namespace sd
32.189873
94
0.711365
steljord2
f70f523674c5a3c39d45f96b8253a261d75537c6
1,891
cpp
C++
Engine/WindowInspector.cpp
elliotjb/CulverinEngine-Project3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
2
2018-01-20T18:17:22.000Z
2018-01-20T18:17:28.000Z
Engine/WindowInspector.cpp
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
null
null
null
Engine/WindowInspector.cpp
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
1
2018-06-16T16:12:11.000Z
2018-06-16T16:12:11.000Z
#include "Application.h" #include "WindowInspector.h" #include "ModuleWindow.h" #include "GameObject.h" #include "Component.h" Inspector::Inspector() : WindowManager() { active.push_back(Active()); name = "Inspector"; } Inspector::~Inspector() { active.clear(); selected_object = nullptr; } bool Inspector::Start() { return true; } update_status Inspector::Update(float dt) { if (active[0].active) ShowInspector(); return UPDATE_CONTINUE; } void Inspector::ShowInspector() { static int width; static int height; SDL_GetWindowSize(App->window->window, &width, &height); ImGui::SetNextWindowPos(ImVec2(width - 300, 20)); ImGui::SetNextWindowSize(ImVec2(300, height - 20 - (height - 700))); if (!BeginDock("Inspector", NULL, ImGuiWindowFlags_NoScrollbar)) { EndDock(); return; } ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(12, 3)); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6, 2)); if (selected_object != nullptr) { selected_object->ShowInspectorInfo(); } ImGui::PopStyleVar(2); EndDock(); } void Inspector::LinkObject(GameObject * obj) { if (obj != nullptr) { selected_object = obj; if (selected_object->GetParent() != nullptr) { GameObject* parent_open = selected_object->GetParent(); while (parent_open != nullptr) { parent_open->set_next_tree_node_open = true; parent_open = parent_open->GetParent(); } } } } void Inspector::SetLinkObjectNull() { selected_object = nullptr; } GameObject* Inspector::GetSelected() const { return selected_object; } void Inspector::SetComponentCopy(Component* copy) { if (copy != nullptr) { copied = copy; } } bool Inspector::AnyComponentCopied() { return (copied != nullptr); } void Inspector::SetLinkComponentNull() { copied = nullptr; } Component * Inspector::GetComponentCopied() { return copied; } bool Inspector::CleanUp() { return true; }
17.190909
69
0.707562
elliotjb
f71847bfbead41a06b5b9259c735f6bbc0405553
575
cpp
C++
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1038A - Equality.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("files/input.txt", "r", stdin); freopen("files/output.txt", "w", stdout); #endif int n, k; cin >> n >> k; string s; cin >> s; map<char, int> freq; for (int i = 0; i < k; ++i) freq['A' + i] = 0; for ( auto ch: s ) freq[ch]++; auto min = min_element(freq.begin(), freq.end(), [](auto a, auto b) { return a.second < b.second; }); cout << min->second * k << endl; return 0; }
21.296296
73
0.518261
naimulcsx
f71c1bb2d46372b72552be3a8b8d3cfb43d3a2bc
11,580
cpp
C++
src/model/test/Blind_GTest.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
354
2015-01-10T17:46:11.000Z
2022-03-29T10:00:00.000Z
src/model/test/Blind_GTest.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3,243
2015-01-02T04:54:45.000Z
2022-03-31T17:22:22.000Z
src/model/test/Blind_GTest.cpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
157
2015-01-07T15:59:55.000Z
2022-03-30T07:46:09.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include <gtest/gtest.h> #include "ModelFixture.hpp" #include "../Blind.hpp" #include "../Blind_Impl.hpp" using namespace openstudio; using namespace openstudio::model; TEST_F(ModelFixture, Blind_GettersSetters) { Model m; Blind blind(m); // Slat Orientation: String // Check Idd default: "Horizontal" EXPECT_EQ("Horizontal", blind.slatOrientation()); // Test a valid choice EXPECT_TRUE(blind.setSlatOrientation("Vertical")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Test an invalid choice EXPECT_FALSE(blind.setSlatOrientation("BadChoice")); EXPECT_EQ("Vertical", blind.slatOrientation()); // Slat Width: Double // Check Idd default: 0.025 EXPECT_EQ(0.025, blind.slatWidth()); EXPECT_TRUE(blind.setSlatWidth(0.01)); EXPECT_EQ(0.01, blind.slatWidth()); // Slat Separation: Double // Check Idd default: 0.01875 EXPECT_EQ(0.01875, blind.slatSeparation()); EXPECT_TRUE(blind.setSlatSeparation(0.01)); EXPECT_EQ(0.01, blind.slatSeparation()); // Slat Thickness: Double // Check Idd default: 0.001 EXPECT_EQ(0.001, blind.slatThickness()); EXPECT_TRUE(blind.setSlatThickness(0.021)); EXPECT_EQ(0.021, blind.slatThickness()); blind.resetSlatThickness(); EXPECT_EQ(0.001, blind.slatThickness()); // Slat Angle: Double // Check Idd default: 45 EXPECT_EQ(45, blind.slatAngle()); EXPECT_TRUE(blind.setSlatAngle(22.5)); EXPECT_EQ(22.5, blind.slatAngle()); blind.resetSlatAngle(); EXPECT_EQ(45, blind.slatAngle()); // Slat Conductivity: Double // Check Idd default: 221.0 EXPECT_EQ(221.0, blind.slatConductivity()); EXPECT_TRUE(blind.setSlatConductivity(110.5)); EXPECT_EQ(110.5, blind.slatConductivity()); blind.resetSlatConductivity(); EXPECT_EQ(221.0, blind.slatConductivity()); // Slat Beam Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); EXPECT_TRUE(blind.setSlatBeamSolarTransmittance(0.35)); EXPECT_EQ(0.35, blind.slatBeamSolarTransmittance()); blind.resetSlatBeamSolarTransmittance(); EXPECT_EQ(0.0, blind.slatBeamSolarTransmittance()); // Front Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamSolarReflectance(0.205)); EXPECT_EQ(0.205, blind.frontSideSlatBeamSolarReflectance()); // Back Side Slat Beam Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamSolarReflectance(0.105)); EXPECT_EQ(0.105, blind.backSideSlatBeamSolarReflectance()); // Slat Diffuse Solar Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseSolarTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseSolarTransmittance(0.31)); EXPECT_EQ(0.31, blind.slatDiffuseSolarTransmittance()); // Front Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseSolarReflectance(0.225)); EXPECT_EQ(0.225, blind.frontSideSlatDiffuseSolarReflectance()); // Back Side Slat Diffuse Solar Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseSolarReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseSolarReflectance(0.336)); EXPECT_EQ(0.336, blind.backSideSlatDiffuseSolarReflectance()); // Slat Beam Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatBeamVisibleTransmittance()); EXPECT_TRUE(blind.setSlatBeamVisibleTransmittance(0.112)); EXPECT_EQ(0.112, blind.slatBeamVisibleTransmittance()); // Front Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatBeamVisibleReflectance(0.145)); EXPECT_EQ(0.145, blind.frontSideSlatBeamVisibleReflectance()); blind.resetFrontSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatBeamVisibleReflectance()); // Back Side Slat Beam Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatBeamVisibleReflectance(0.185)); EXPECT_EQ(0.185, blind.backSideSlatBeamVisibleReflectance()); blind.resetBackSideSlatBeamVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatBeamVisibleReflectance()); // Slat Diffuse Visible Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); EXPECT_TRUE(blind.setSlatDiffuseVisibleTransmittance(0.015)); EXPECT_EQ(0.015, blind.slatDiffuseVisibleTransmittance()); blind.resetSlatDiffuseVisibleTransmittance(); EXPECT_EQ(0.0, blind.slatDiffuseVisibleTransmittance()); // Front Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setFrontSideSlatDiffuseVisibleReflectance(0.055)); EXPECT_EQ(0.055, blind.frontSideSlatDiffuseVisibleReflectance()); blind.resetFrontSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.frontSideSlatDiffuseVisibleReflectance()); // Back Side Slat Diffuse Visible Reflectance: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); EXPECT_TRUE(blind.setBackSideSlatDiffuseVisibleReflectance(0.085)); EXPECT_EQ(0.085, blind.backSideSlatDiffuseVisibleReflectance()); blind.resetBackSideSlatDiffuseVisibleReflectance(); EXPECT_EQ(0.5, blind.backSideSlatDiffuseVisibleReflectance()); // Slat Infrared Hemispherical Transmittance: Double // Check Idd default: 0.0 EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); EXPECT_TRUE(blind.setSlatInfraredHemisphericalTransmittance(0.095)); EXPECT_EQ(0.095, blind.slatInfraredHemisphericalTransmittance()); blind.resetSlatInfraredHemisphericalTransmittance(); EXPECT_EQ(0.0, blind.slatInfraredHemisphericalTransmittance()); // Front Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setFrontSideSlatInfraredHemisphericalEmissivity(0.451)); EXPECT_EQ(0.451, blind.frontSideSlatInfraredHemisphericalEmissivity()); blind.resetFrontSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.frontSideSlatInfraredHemisphericalEmissivity()); // Back Side Slat Infrared Hemispherical Emissivity: Double // Check Idd default: 0.9 EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); EXPECT_TRUE(blind.setBackSideSlatInfraredHemisphericalEmissivity(0.455)); EXPECT_EQ(0.455, blind.backSideSlatInfraredHemisphericalEmissivity()); blind.resetBackSideSlatInfraredHemisphericalEmissivity(); EXPECT_EQ(0.9, blind.backSideSlatInfraredHemisphericalEmissivity()); // Blind to Glass Distance: Double // Check Idd default: 0.050 EXPECT_EQ(0.050, blind.blindtoGlassDistance()); EXPECT_TRUE(blind.setBlindtoGlassDistance(0.033)); EXPECT_EQ(0.033, blind.blindtoGlassDistance()); blind.resetBlindtoGlassDistance(); EXPECT_EQ(0.050, blind.blindtoGlassDistance()); // Blind Top Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); EXPECT_TRUE(blind.setBlindTopOpeningMultiplier(0.259)); EXPECT_EQ(0.259, blind.blindTopOpeningMultiplier()); blind.resetBlindTopOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindTopOpeningMultiplier()); // Blind Bottom Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); EXPECT_TRUE(blind.setBlindBottomOpeningMultiplier(0.278)); EXPECT_EQ(0.278, blind.blindBottomOpeningMultiplier()); blind.resetBlindBottomOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindBottomOpeningMultiplier()); // Blind Left Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindLeftSideOpeningMultiplier(0.324)); EXPECT_EQ(0.324, blind.blindLeftSideOpeningMultiplier()); blind.resetBlindLeftSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindLeftSideOpeningMultiplier()); // Blind Right Side Opening Multiplier: Double // Check Idd default: 0.5 EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); EXPECT_TRUE(blind.setBlindRightSideOpeningMultiplier(0.165)); EXPECT_EQ(0.165, blind.blindRightSideOpeningMultiplier()); blind.resetBlindRightSideOpeningMultiplier(); EXPECT_EQ(0.5, blind.blindRightSideOpeningMultiplier()); // Minimum Slat Angle: Double // Check Idd default: 0 EXPECT_EQ(0, blind.minimumSlatAngle()); EXPECT_TRUE(blind.setMinimumSlatAngle(13.0)); EXPECT_EQ(13.0, blind.minimumSlatAngle()); blind.resetMinimumSlatAngle(); EXPECT_EQ(0, blind.minimumSlatAngle()); // Maximum Slat Angle: Double // Check Idd default: 180 EXPECT_EQ(180, blind.maximumSlatAngle()); EXPECT_TRUE(blind.setMaximumSlatAngle(74.0)); EXPECT_EQ(74.0, blind.maximumSlatAngle()); blind.resetMaximumSlatAngle(); EXPECT_EQ(180, blind.maximumSlatAngle()); }
45.411765
125
0.75924
muehleisen
f71fbd4c04cf222da4973ed3470714f656cd8a3e
807
cpp
C++
wrapper/Lua/funcs/Interface.cpp
arrayfire/arrayfire-lua
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
[ "BSD-3-Clause" ]
10
2015-09-21T07:20:20.000Z
2019-07-29T10:36:50.000Z
wrapper/Lua/funcs/Interface.cpp
arrayfire/arrayfire-lua
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
[ "BSD-3-Clause" ]
3
2015-09-20T06:15:41.000Z
2017-02-27T01:38:04.000Z
wrapper/Lua/funcs/Interface.cpp
arrayfire/arrayfire_lua
5cd1e7702cd37d3bae60cfbc819c01cda1d0f6ec
[ "BSD-3-Clause" ]
5
2015-09-21T10:12:43.000Z
2021-03-05T02:07:50.000Z
#include <arrayfire.h> #ifdef WANT_CUDA #include <../cuda.h> #endif #ifdef WANT_OPENCL #include <../opencl.h> #endif // ^^^ TODO: probably not right! #include "../funcs.h" static const struct luaL_Reg interface_funcs[] = { #if AF_API_VERSION >= 32 #if WANT_OPENCL { // af_err afcl_get_context (cl_context * ctx, const bool retain); }, { // af_err afcl_get_device_id (cl_device_id * id); }, #endif #if WANT_CUDA { // af_err afcu_get_native_id (int * nativeid, int id); }, #endif #if WANT_OPENCL { // af_err afcl_get_queue (cl_command_queue * queue, const bool retain); }, #endif #if WANT_CUDA { // af_err afcu_get_stream (cudaStream_t * stream, int id); }, #endif #endif { NULL, NULL } }; int Interface (lua_State * L) { luaL_register(L, NULL, interface_funcs); return 0; }
15.519231
73
0.675341
arrayfire
f72434e9f0124e599fd2c79d8dc8e033a49265c3
10,430
cxx
C++
smtk/geometry/testing/cxx/TestGeometry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/geometry/testing/cxx/TestGeometry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/geometry/testing/cxx/TestGeometry.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/geometry/Backend.h" #include "smtk/geometry/Cache.h" #include "smtk/geometry/Generator.h" #include "smtk/geometry/Manager.h" #include "smtk/geometry/Resource.h" #include "smtk/operation/Manager.h" #include "smtk/resource/DerivedFrom.h" #include "smtk/common/testing/cxx/helpers.h" #include <memory> #include <sstream> #include <string> namespace detail { class ResourceA; // Example of a custom "geometry" format for a backend. // We cannot use smtk::geometry::GeometryForBackend<int> // because integers are not automatically initialized. // Here, we just wrap an integer so that Format is // initialized by default and convertible to a bool. // Usually, you will GeometryForBackend a shared or // smart pointer to some more complex structure. struct Format { int m_data = 0; Format() = default; Format(int data) : m_data(data) { } Format(const Format& other) = default; operator bool() const { return m_data <= 0; } operator int() const { return m_data <= 0 ? -1 : m_data; } }; class Backend1 : public smtk::geometry::Backend { public: Backend1() = default; ~Backend1() override = default; std::string name() const override { return "Backend1"; } }; class Backend2 : public smtk::geometry::Backend { public: Backend2() = default; ~Backend2() override = default; std::string name() const override { return "Backend2"; } template<typename Geometry> int geometry(const Geometry& p, const smtk::resource::PersistentObject::Ptr& obj) { int val; try { const auto& provider = dynamic_cast<const smtk::geometry::GeometryForBackend<Format>&>(*p); val = provider.data(obj); } catch (std::bad_cast&) { val = -1; } return val; } }; class ComponentA : public smtk::resource::Component { friend class ResourceA; public: smtkTypeMacro(ComponentA); smtkSuperclassMacro(smtk::resource::PersistentObject); smtkSharedFromThisMacro(smtk::resource::PersistentObject); const smtk::resource::ResourcePtr resource() const override { return this->m_resource; } int value() const { return m_value; } void setValue(int v) { m_value = v; } const smtk::common::UUID& id() const override { return m_id; } bool setId(const smtk::common::UUID& id) override { m_id = id; return true; } std::string name() const override { std::ostringstream result; result << "Component " << m_value << " (" << m_id << ")"; return result.str(); } private: ComponentA(smtk::resource::ResourcePtr resource) : m_resource(resource) { } const smtk::resource::ResourcePtr m_resource; int m_value; smtk::common::UUID m_id; }; class ResourceA : public smtk::resource::DerivedFrom<ResourceA, smtk::geometry::Resource> { public: smtkTypeMacro(ResourceA); smtkCreateMacro(ResourceA); smtkSharedFromThisMacro(smtk::resource::PersistentObject); ComponentA::Ptr newComponent() { ComponentA::Ptr shared(new ComponentA(shared_from_this())); shared->setId(smtk::common::UUID::random()); m_components.insert(shared); return std::static_pointer_cast<ComponentA>(shared); } smtk::resource::ComponentPtr find(const smtk::common::UUID& id) const override { auto it = std::find_if(m_components.begin(), m_components.end(), [&](const ComponentA::Ptr& c) { return c->id() == id; }); return (it != m_components.end() ? *it : smtk::resource::ComponentPtr()); } std::function<bool(const smtk::resource::Component&)> queryOperation( const std::string& /*unused*/) const override { return [](const smtk::resource::Component& /*unused*/) { return true; }; } void visit(smtk::resource::Component::Visitor& visitor) const override { std::for_each(m_components.begin(), m_components.end(), visitor); } bool erase(const ComponentA::Ptr& comp) { return m_components.erase(comp) > 0; } std::size_t size() const { return m_components.size(); } protected: ResourceA() : smtk::resource::DerivedFrom<ResourceA, smtk::geometry::Resource>() { } private: std::unordered_set<ComponentA::Ptr> m_components; }; class Geometry2 : public smtk::geometry::Cache<smtk::geometry::GeometryForBackend<Format>> { public: Geometry2(const ResourceA::Ptr& parent) : m_parent(parent) { } ~Geometry2() override = default; const smtk::geometry::Backend& backend() const override { static Backend2 data; return data; } smtk::geometry::Resource::Ptr resource() const override { return m_parent.lock(); } void queryGeometry(const smtk::resource::PersistentObject::Ptr& obj, CacheEntry& entry) const override { auto comp = std::dynamic_pointer_cast<ComponentA>(obj); if (comp && comp->value() >= 0) { entry.m_geometry = comp->value(); entry.m_generation = Initial; } else { entry.m_generation = Invalid; } } void geometricBounds(const Format& value, BoundingBox& bds) const override { bds[0] = bds[2] = bds[4] = +0.0; bds[1] = bds[3] = bds[5] = static_cast<double>((int)value); } // Ensure every component with renderable geometry has a cache entry. void update() const override { std::cout << " Updating geometry before iteration\n"; auto rsrc = m_parent.lock(); if (rsrc) { smtk::resource::Component::Visitor visitor = [this](const smtk::resource::Component::Ptr& comp) { auto compA = std::dynamic_pointer_cast<ComponentA>(comp); if (compA && compA->value() >= 0) { m_cache[compA->id()] = CacheEntry{ Initial, compA->value() }; } else { m_cache.erase(compA->id()); } }; rsrc->visit(visitor); // Also erase the cache entry for the resource itself (since // we know it does not have valid geometry). m_cache.erase(rsrc->id()); } } ResourceA::WeakPtr m_parent; }; class RegisterResourceABackend2 : public smtk::geometry::Supplier<RegisterResourceABackend2> { public: bool valid(const smtk::geometry::Specification& in) const override { Backend2 backend; return std::get<1>(in).index() == backend.index(); } smtk::geometry::GeometryPtr operator()(const smtk::geometry::Specification& in) override { auto rsrc = std::dynamic_pointer_cast<ResourceA>(std::get<0>(in)); if (rsrc) { auto* provider = new Geometry2(rsrc); return smtk::geometry::GeometryPtr(provider); } throw std::invalid_argument("Not a test resource."); return nullptr; } }; static bool registeredA2 = RegisterResourceABackend2::registerClass(); } // namespace detail using namespace detail; int TestGeometry(int /*unused*/, char** const /*unused*/) { // Create managers auto resourceManager = smtk::resource::Manager::create(); auto operationManager = smtk::operation::Manager::create(); auto geometryManager = smtk::geometry::Manager::create(); // Cause creation of resources to create geometry objects for all registered backends geometryManager->registerResourceManager(resourceManager); // Register ResourceA resourceManager->registerResource<ResourceA>(); // Create a new ResourceA type auto resourceA = resourceManager->create<ResourceA>(); resourceA->setName("Resource A"); auto comp42 = resourceA->newComponent(); auto comp43 = resourceA->newComponent(); auto compM1 = resourceA->newComponent(); auto compM2 = resourceA->newComponent(); comp42->setValue(42); comp43->setValue(43); compM1->setValue(-1); compM2->setValue(-2); int count = 0; auto visitor = [&count](const smtk::geometry::Backend& visited) { std::cout << " Found " << visited.name() << "\n"; ++count; }; geometryManager->visitBackends(visitor); smtkTest(count == 0, "Expected 0 backends before registration."); count = 0; std::cout << "Registering backends\n"; geometryManager->registerBackend<detail::Backend1>(); geometryManager->registerBackend<detail::Backend2>(); geometryManager->visitBackends(visitor); smtkTest(count == 2, "Expected 2 backends after registration."); count = 0; std::cout << "Unregistering 1 backend\n"; geometryManager->unregisterBackend<detail::Backend1>(); geometryManager->visitBackends(visitor); smtkTest(count == 1, "Expected 1 backend after unregistration."); auto& geomA1 = resourceA->geometry(detail::Backend1{}); smtkTest(geomA1 == nullptr, "Expected no geometry for Backend1"); auto& geomA2 = resourceA->geometry(detail::Backend2{}); smtkTest(geomA2 != nullptr, "Expected a geometry for Backend2"); // Test that the caching geometry provider calls Geometry2::update() std::cout << "Visiting renderables\n"; smtk::geometry::Geometry::BoundingBox bbox; count = 0; geomA2->visit([&geomA2, &bbox, &count]( const smtk::resource::PersistentObject::Ptr& obj, smtk::geometry::Geometry::GenerationNumber) { if (obj) { // Here is an example of how to fetch the "actual" // data from a geometry instance using a specific backend: detail::Backend2 renderer; int geom = renderer.geometry(geomA2, obj); geomA2->bounds(obj, bbox); std::cout << " object \"" << obj->name() << "\" geometry " << geom << "\n"; smtkTest(geom > 0, "Did not expect to visit object with invalid geometry."); smtkTest(bbox[1] >= bbox[0], "Expected a valid bounding box."); ++count; } return false; }); smtkTest(count == 2, "Expected to visit 2 components with valid \"geometry\"."); auto generation = geomA2->generationNumber(compM1); smtkTest( generation == smtk::geometry::Geometry::Invalid, "Expected invalid generation number for component with negative value."); smtk::geometry::Geometry::BoundingBox bds; geomA2->bounds(compM1, bds); smtkTest( bds[1] < bds[0] && bds[3] < bds[2] && bds[5] < bds[4], "Expected invalid bounds for component with no \"geometry\"."); return 0; }
29.052925
100
0.662416
jcfr
f72726336c53431cac227d0e2884a824c6cddd5f
344
cpp
C++
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
66
2017-09-29T07:09:59.000Z
2020-01-12T06:45:08.000Z
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
5
2017-12-13T13:12:05.000Z
2018-01-18T10:34:02.000Z
libraries/glua/glua_api_types.cpp
tiaotiao00/HSR00qianbao
a88afebeb98e786389f369447bcf9c3a2a352cfa
[ "MIT" ]
11
2017-12-05T07:02:05.000Z
2018-01-28T02:52:50.000Z
#include <glua/glua_api_types.h> #include <glua/hsrcore_lua_api.h> GluaModuleByteStream::GluaModuleByteStream() { is_bytes = false; contract_level = CONTRACT_LEVEL_TEMP; contract_state = CONTRACT_STATE_VALID; } GluaModuleByteStream::~GluaModuleByteStream() { contract_apis.clear(); offline_apis.clear(); contract_emit_events.clear(); }
20.235294
45
0.793605
tiaotiao00
f729b82eed46a2762653e8db87479c1ff28d01fe
30,395
cpp
C++
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
52
2015-02-19T21:22:19.000Z
2022-01-24T07:59:07.000Z
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
5
2016-05-22T16:39:57.000Z
2020-09-19T20:29:20.000Z
src/MuiTextArea.cpp
kritzikratzi/ofxMightyUI
63eaa7fcc8739e019f27500f68c4129a18be5434
[ "MIT" ]
14
2015-05-19T10:04:52.000Z
2021-05-12T09:07:22.000Z
/* * TextArea.cpp * * Text TextArea * - Supports vertical and horizontal alignments * - Call commit() after changing text, fontSize, fontName or any of the other variables (except bounds!). * - fg variable affects text color (no commit needed) * - Only support multiline */ #include "MuiTextArea.h" #include "Root.h" #include <regex> #include <GLFW/glfw3.h> // how nasty is this?? mui::TextAreaInternal * internal(mui::TextArea * tf){ return tf->internalData(); } #define STB_TEXTEDIT_STRING mui::TextArea #define STB_TEXTEDIT_CHARTYPE uint32_t #define STB_TEXTEDIT_POSITIONTYPE int //TODO: utf8 support #define STB_TEXTEDIT_STRINGLEN(obj) ((int)internal(obj)->utf32.size()) #define STB_TEXTEDIT_CHARARR_LEN(arr,len) (len) #define STB_TEXTEDIT_LAYOUTROW(r,obj,n) mui::TextAreaInternal::layout_func(r,obj,n) #define STB_TEXTEDIT_GETWIDTH(obj,n,i) mui::TextAreaInternal::layout_width(obj,n,i) #define STB_TEXTEDIT_KEYTOTEXT(key) (((key) & KEYDOWN_BIT) ? 0 : (key)) // this only returns the first byte of a multi byte sequence :( #define STB_TEXTEDIT_GETCHAR(tc,i) (internal(tc)->utf32[i]) #define STB_TEXTEDIT_NEWLINE '\n' #define STB_TEXTEDIT_IS_SPACE(ch) isspace(ch) #define STB_TEXTEDIT_DELETECHARS mui::TextAreaInternal::delete_chars #define STB_TEXTEDIT_INSERTCHARS mui::TextAreaInternal::insert_chars #define KEYDOWN_BIT 0x8000 #define STB_TEXTEDIT_K_SHIFT 0x4000 #define STB_TEXTEDIT_K_CONTROL 0x2000 #define STB_TEXTEDIT_K_LEFT (KEYDOWN_BIT | 1) // actually use VK_LEFT, SDLK_LEFT, etc #define STB_TEXTEDIT_K_RIGHT (KEYDOWN_BIT | 2) // VK_RIGHT #define STB_TEXTEDIT_K_UP (KEYDOWN_BIT | 3) // VK_UP #define STB_TEXTEDIT_K_DOWN (KEYDOWN_BIT | 4) // VK_DOWN #define STB_TEXTEDIT_K_LINESTART (KEYDOWN_BIT | 5) // VK_HOME #define STB_TEXTEDIT_K_LINEEND (KEYDOWN_BIT | 6) // VK_END #define STB_TEXTEDIT_K_TEXTSTART (STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_TEXTEND (STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_DELETE (KEYDOWN_BIT | 7) // VK_DELETE #define STB_TEXTEDIT_K_BACKSPACE (KEYDOWN_BIT | 8) // VK_BACKSPACE #define STB_TEXTEDIT_K_UNDO (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'z') #define STB_TEXTEDIT_K_REDO (KEYDOWN_BIT | STB_TEXTEDIT_K_CONTROL | 'y') #define STB_TEXTEDIT_K_INSERT (KEYDOWN_BIT | 9) // VK_INSERT #define STB_TEXTEDIT_K_WORDLEFT (STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_WORDRIGHT (STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_CONTROL) #define STB_TEXTEDIT_K_PGUP (KEYDOWN_BIT | 10) // VK_PGUP -- not implemented #define STB_TEXTEDIT_K_PGDOWN (KEYDOWN_BIT | 11) // VK_PGDOWN -- not implemented #define STB_TEXTEDIT_MOVEWORDLEFT mui::TextAreaInternal::move_to_word_previous #define STB_TEXTEDIT_MOVEWORDRIGHT mui::TextAreaInternal::move_to_word_next #include "../libs/stb_textedit/include/stb_textedit/stb_textedit.h" #pragma mark UTF8-Helpers inline int mui::TextArea::octect_size( uint32_t codepoint ){ if (codepoint < 0x80) // two octets return 1; else if (codepoint < 0x800) // two octets return 2; else if (codepoint < 0x10000) // three octets return 3; else // four octets return 4; } int mui::TextArea::utf8_expected_len( char first ){ switch((unsigned char)first){ case 0xc0: return 2; case 0xe0: return 3; case 0xf0: return 4; default: return 1; } } string mui::TextArea::utf32_to_utf8( uint32_t codepoint ){ if (codepoint < 0x80) // one octet return string({(char)codepoint}); else if (codepoint < 0x800) { // two octets return string({ (char)((codepoint >> 6) | 0xc0), (char)((codepoint & 0x3f) | 0x80) }); } else if (codepoint < 0x10000) { // three octets return string({ (char)((codepoint >> 12) | 0xe0), (char)(((codepoint >> 6) & 0x3f) | 0x80), (char)((codepoint & 0x3f) | 0x80) }); } else { return string({ (char)((codepoint >> 18) | 0xf0), (char)(((codepoint >> 12) & 0x3f) | 0x80), (char)(((codepoint >> 6) & 0x3f) | 0x80), (char)((codepoint & 0x3f) | 0x80) }); } } inline size_t mui::TextArea::utf8_strlen(const string & line ){ size_t i = 0; for( auto c : ofUTF8Iterator(line) ){ ++i; } return i; } inline size_t mui::TextArea::utf8_to_utf32(const string & text, vector<uint32_t> & utf32, vector<size_t> & utf8_positions){ size_t i = 0; size_t pos = 0; utf32.clear(); utf8_positions.clear(); for( auto c : ofUTF8Iterator(text) ){ utf32.push_back(c); utf8_positions.push_back(pos); pos += octect_size(c); ++i; } return i; } inline vector<uint32_t> mui::TextArea::utf8_to_utf32(const string & text){ vector<uint32_t> res; for( auto c : ofUTF8Iterator(text) ){ res.push_back(c); } return res; } // define the functions we need void mui::TextArea::layout_func_impl(void *row_ptr, mui::TextArea *data, int start_i) { StbTexteditRow * row = (StbTexteditRow*)row_ptr; const ofRectangle &boundingBox = data->boundingBox; ofRectangle size = mui::Helpers::alignBox( data, boundingBox.width, boundingBox.height, data->horizontalAlign, data->verticalAlign ); // mui::Helpers::getFontStash().getTextBounds(data->text, data->fontStyle, boundingBox.x, boundingBox.y); // figure out where we currently are int pos = 0; float y = 0; for( int i = 0; i < data->lines.size(); i++){ const StyledLine & line = data->lines[i]; int lineLen = (int)data->utf32_line_length[i]; if( pos >= start_i ){ assert(line.elements.size()>0); row->num_chars = lineLen; row->x0 = size.x + line.elements.front().x; row->x1 = row->x0 + line.lineW; row->baseline_y_delta = 0; //??? row->ymin = size.y + y; row->ymax = size.y + y + line.lineH; return; } pos += lineLen; y += line.lineH; } row->num_chars = 0; row->x0 = size.x; row->x1 = size.x+size.width; row->baseline_y_delta = 0; row->ymin = y; row->ymax = y + 10; } // n: line starts at index n // i: is the char offset within the line // return value: is advance to the next letter (taking kerning and maybe other funny things into account) // i think it is: equivalent to: xpos(n+i+1)-xpos(n+i) float mui::TextArea::layout_width_impl(mui::TextArea * data, int n, int i ){ // if(i==0) return data->find_xpos_right(n); // else return data->find_xpos_right(n+i)-data->find_xpos_right(n+i-1); if(i==0) return data->getEditorCursorForIndex(n+1).rect.x; else return data->getEditorCursorForIndex(n+i+1).rect.x-data->getEditorCursorForIndex(n+i).rect.x; } // pos is the position in utf32 chars int mui::TextArea::delete_chars_impl(mui::TextArea *data, int pos, int num) { if(num==0) return 0; size_t from = data->idx_utf8(pos); size_t to = data->idx_utf8(pos+num); if(from==to) return 0; data->text.erase(data->text.begin()+from, data->text.begin()+to); data->commit(); // do an immediate commit() here? return 1; } // pos is the position in unicode chars // newtext is utf32 encoded! int mui::TextArea::insert_chars_impl(mui::TextArea *data, int pos, const STB_TEXTEDIT_CHARTYPE *newtext, int num){ size_t idx; if(pos==0) idx = 0; else if(pos<data->utf32.size()) idx = data->utf8_positions[pos-1]+octect_size(data->utf32[pos-1]); else idx = data->text.length(); idx = min(data->text.size(), idx); stringstream str; int len = 0; for( int i = 0; i < num; i++){ uint32_t ch = newtext[i]; if(data->onCharacterAdded.notifyRequireAll(ch)){ str << utf32_to_utf8(ch); len ++; } } string text = str.str(); if (data->onInsert) text = data->onInsert(text); data->text.insert(idx, text); data->commit(); return len; // always succeeds } int mui::TextArea::is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) { return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; } static bool is_cool_coding_char(STB_TEXTEDIT_CHARTYPE c){ const static char * chars = "[]|{}().!=+-_,;:^&|#"; for(int i = strlen(chars)-1;i>=0; i--){ if((uint32_t)chars[i] == c) return true; } return false; } int mui::TextArea::move_to_word_previous_impl( STB_TEXTEDIT_STRING *str, int c ) { --c; // always move at least one character while( c >= 0 && !is_word_boundary( str, c ) && !is_cool_coding_char(STB_TEXTEDIT_GETCHAR(str,c))) --c; if( c < 0 ) c = 0; return c; } int mui::TextArea::move_to_word_next_impl( STB_TEXTEDIT_STRING *str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(str); ++c; // always move at least one character while( c < len && !is_word_boundary( str, c ) && !is_cool_coding_char(STB_TEXTEDIT_GETCHAR(str,c))) ++c; if( c > len ) c = len; return c; } #define STB_TEXTEDIT_IMPLEMENTATION #include "../libs/stb_textedit/include/stb_textedit/stb_textedit.h" #undef STB_TEXTEDIT_IMPLEMENTATION // this exists only because it's not possible to forward declare unnamed structs class mui::TextArea::EditorState : public STB_TexteditState{ }; mui::TextArea::TextArea( std::string text_, float x_, float y_, float width_, float height_ ) : mui::ScrollPane( x_, y_, width_, height_ ), text( text_), fontSize(-1), horizontalAlign(Left), verticalAlign(Middle),fontName(""),lastInteraction(0),selectAllOnFocus(false){ editor_view = new mui::TextAreaView(this, 0, 0, width, height); editor_view->cursor = mui::Cursor::IBeam; view->add(editor_view); state = new EditorState(); focusTransferable = false; stb_textedit_initialize_state(state,0); if( fontSize < 0 ) fontSize = mui::MuiConfig::fontSize; commit(); state->cursor = strlenWithLineStarts; }; mui::TextArea::~TextArea(){ editor_view->remove(); delete editor_view; delete state; } // internally redirect those, so that it goes straight into the real textarea and not the scroller bool mui::TextArea::hasFocus(){return editor_view->hasFocus(); } bool mui::TextArea::hasFocus( ofTouchEventArgs &touch ){ return editor_view->hasFocus(touch); }; bool mui::TextArea::requestFocus( ofTouchEventArgs &args ){ return editor_view->requestFocus(args); }; // internally redirect those, so that it goes straight into the real textarea and not the scroller bool mui::TextArea::hasKeyboardFocus(){ return editor_view->hasKeyboardFocus(); }; bool mui::TextArea::requestKeyboardFocus(){ return editor_view->requestKeyboardFocus(); }; //-------------------------------------------------------------- void mui::TextArea::update(){ mui::ScrollPane::update(); fontStyle.fontSize = fontSize; fontStyle.color = fg; fontStyle.fontID = fontName; } const string mui::TextArea::getText(){ return text; } void mui::TextArea::setText( string text ){ state->select_start = 0; state->select_end = strlenWithLineStarts; state->cursor = state->select_end; vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, text_utf32.size()?&text_utf32[0]:nullptr, (int)text_utf32.size()); } void mui::TextArea::setTextAndNotify( string text ){ setText(text); ofNotifyEvent(onChange, text, this); } //-------------------------------------------------------------- void mui::TextArea::drawBackground(){ Container::drawBackground(); } //-------------------------------------------------------------- void mui::TextArea::layout(){ mui::ScrollPane::layout(); } void mui::TextArea::sizeToFit( float padX, float padY ){ commit(); // update bounding box width = boundingBox.width + padX; height = boundingBox.height + padY; layout(); // tell ourselves about the size change } void mui::TextArea::sizeToFitWidth( float padX ){ commit(); width = boundingBox.width + padX; layout(); } void mui::TextArea::sizeToFitHeight( float padY ){ commit(); height = boundingBox.height + padY; layout(); } //-------------------------------------------------------------- //deprecated ofRectangle mui::TextArea::box( float t, float r, float b, float l ){ ofRectangle size = Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign ); return ofRectangle( size.x - boundingBox.x - l, size.y - boundingBox.y + t, boundingBox.width + l + r, boundingBox.height + t + b ); } //-------------------------------------------------------------- void mui::TextArea::commit(){ mui::Helpers::loadFont(fontName); if (!multiLine) canScrollX = canScrollY = false; fontStyle.fontSize = fontSize; fontStyle.color = fg; fontStyle.fontID = fontName; boundingBox = Helpers::getFontStash().getTextBounds(text, fontStyle, 0, 0); vector<StyledText> blocks{ {text,fontStyle} }; lines = Helpers::getFontStash().layoutLines(blocks, softWrap?editor_view->width:9999999); lineNumberSourceToDisplay.clear(); lineNumberDisplayToSource.clear(); int lineNumSrc = 0; int lineNumDisp = 0; int lastLineStart = 0; for( auto & line : lines ){ auto & last = line.elements.back(); lineNumberDisplayToSource.push_back(lineNumSrc); if(last.content.styledText.text == "\n"){ lineNumberSourceToDisplay.push_back(lastLineStart); lineNumSrc ++; lastLineStart = lineNumDisp+1; } lineNumDisp ++; } lineNumberSourceToDisplay.push_back(lastLineStart); if(lines.size() == 0){ lines = Helpers::getFontStash().layoutLines({{" ",fontStyle}}, 10); } strlenWithLineStarts = 0; utf32_line_length.clear(); utf32.clear(); utf8_positions.clear(); utf32.reserve(text.size()*1.5); utf8_positions.reserve(text.size()*1.5); size_t pos = 0; for(uint32_t ch : ofUTF8Iterator(text)){ utf32.push_back(ch); utf8_positions.push_back(pos); pos += octect_size(ch); } bool first = false; for( int i = 0; i < lines.size(); i++){ StyledLine & line = lines[i]; utf32_line_length.push_back(0); for( auto el : line.elements ){ utf32_line_length[i] += (int)utf8_strlen(el.content.styledText.text); } strlenWithLineStarts += utf32_line_length[i]; if( first ) first = false; else strlenWithLineStarts ++; } // Orient y on a simple uppercase character // Otherwise things go up and down unexpectedly ofRectangle baselineSize = Helpers::getFontStash().getTextBounds("M", fontStyle, 0, 0); boundingBox.height = baselineSize.height; boundingBox.y = baselineSize.y; if(true/*autoChangeHeight*/){ float h = 0; for( int i = (int)lines.size()-1;i>=0;i--){ StyledLine & line = lines[i]; for(int j = (int)line.elements.size()-1; j>=0; j--){ h = MAX(h,line.elements[j].baseLineY); } } // add one more line! to be sure we have enough space for the decenders if (multiLine) h += baselineSize.height / 3; h = max(minHeight, h - baselineSize.y); editor_view->width = viewportWidth; if (autoChangeHeight) { editor_view->height = h; height = h; } else { h = max(viewportHeight, h); if (h != editor_view->height) { editor_view->height = h; MUI_ROOT->needsLayout = true; } } } mui::ScrollPane::commit(); } bool mui::TextArea::keyPressed( ofKeyEventArgs &key ){ lastInteraction = ofGetElapsedTimeMillis(); short redoPt = state->undostate.redo_point; short undoPt = state->undostate.undo_point; short undoWhere = state->undostate.undo_rec[MIN(98,undoPt)].where; bool certainlyChanged = false; int keyMask = (ofGetKeyPressed(OF_KEY_SHIFT)?STB_TEXTEDIT_K_SHIFT:0) | #if defined(TARGET_OSX) (ofGetKeyPressed(OF_KEY_ALT)?STB_TEXTEDIT_K_CONTROL:0) #else (ofGetKeyPressed(OF_KEY_CONTROL)?STB_TEXTEDIT_K_CONTROL:0) #endif ; #ifdef _WIN32 // windows is funny with ctrl shortcuts if (ofGetKeyPressed(OF_KEY_CONTROL) && key.key >= 1 && key.key <= 26) { key.key = key.codepoint = 'a' + (key.key - 1); } #endif switch(key.key){ case OF_KEY_HOME: stb_textedit_key(this, state, STB_TEXTEDIT_K_LINESTART|keyMask); break; case OF_KEY_END: stb_textedit_key(this, state, STB_TEXTEDIT_K_LINEEND|keyMask); break; case OF_KEY_UP: // on osx cmd+up goes to the start if(ofGetKeyPressed(OF_KEY_COMMAND)) stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTSTART); else stb_textedit_key(this, state, STB_TEXTEDIT_K_UP|keyMask); break; case OF_KEY_DOWN: // on osx cmd+down goes to the end if(ofGetKeyPressed(OF_KEY_COMMAND)) stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTEND); else stb_textedit_key(this, state, STB_TEXTEDIT_K_DOWN|keyMask); break; case OF_KEY_LEFT: if(MUI_ROOT->getKeyPressed(OF_KEY_SUPER)) stb_textedit_key(this, state, STB_TEXTEDIT_K_LINESTART|keyMask ); else stb_textedit_key(this, state, STB_TEXTEDIT_K_LEFT|keyMask); break; case OF_KEY_RIGHT: if(MUI_ROOT->getKeyPressed(OF_KEY_SUPER)) stb_textedit_key(this, state, STB_TEXTEDIT_K_LINEEND|keyMask ); else stb_textedit_key(this, state, STB_TEXTEDIT_K_RIGHT|keyMask); break; case OF_KEY_BACKSPACE: stb_textedit_key(this, state, STB_TEXTEDIT_K_BACKSPACE|keyMask); break; case OF_KEY_DEL: stb_textedit_key(this, state, STB_TEXTEDIT_K_DELETE|keyMask); break; case OF_KEY_RETURN: stb_textedit_key(this, state, STB_TEXTEDIT_NEWLINE|keyMask); break; case OF_KEY_PAGE_UP: break; case OF_KEY_PAGE_DOWN: break; case OF_KEY_ESC: // do nothing! break; default: //ok, what about other shortcuts? ... if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.keycode==GLFW_KEY_A ){ state->select_start = 0; state->select_end = (int)strlenWithLineStarts; state->cursor = state->select_end; } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'z'){ if (ofGetKeyPressed(OF_KEY_SHIFT)) stb_text_redo(this, state); else stb_text_undo(this, state); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && (key.codepoint == 'Z' || key.codepoint == 'y')){ stb_text_redo(this, state); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'x'){ ofGetWindowPtr()->setClipboardString(getSelectedText()); stb_textedit_key(this, state, STB_TEXTEDIT_K_DELETE ); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'c'){ ofGetWindowPtr()->setClipboardString(getSelectedText()); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION) && key.codepoint == 'v'){ string text = ofGetWindowPtr()->getClipboardString(); vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, &text_utf32[0], (int)text_utf32.size()); } else if (key.key == OF_KEY_TAB && state->select_start != state->select_end) { // go back to prev line break if (state->select_start > state->select_end) swap(state->select_start, state->select_end); while (state->select_start > 0 && STB_TEXTEDIT_GETCHAR(this, state->select_start -1) != '\n'){ state->select_start--; } string text = getSelectedText(); if (ofGetKeyPressed(OF_KEY_SHIFT)) { if (text[0] == '\t') text = text.substr(1); std::regex e("\n\t"); text = regex_replace(text, e, "\n"); } else { std::regex e("\n"); text = "\t" + regex_replace(text, e, "\n\t"); } insertTextAtCursor(text,true); } else if(MUI_ROOT->getKeyPressed(MUI_KEY_ACTION)){ // a shortcut of sorts, but not for us. return false; } else{ uint32_t codept = key.codepoint; if (!utf8::internal::is_code_point_valid(codept)){ // what is it? don't know! ignore it! return true; } else if( codept == 0x09 ){ // control character, but ok } else if( codept < 0x1F || codept == 0x7F || (codept >= 0x0080 && codept <= 0x009F) ){ // control character return true; } // the next 20 or so lines are basically a verbatim copy from // stb_textedit_key() with a tiny change: // a char doesn't have a fixed size // EditorData * str = this; // can't add newline in single-line mode if (codept == '\n' && state->single_line) break; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(this)) { stb_text_makeundo_replace(this, state, state->cursor, 1, 1); STB_TEXTEDIT_DELETECHARS(this, state->cursor, 1); if (STB_TEXTEDIT_INSERTCHARS(this, state->cursor, &codept, 1)) { ++state->cursor; state->has_preferred_x = 0; certainlyChanged = true; } } else { stb_textedit_delete_selection(this,state); // implicity clamps if (STB_TEXTEDIT_INSERTCHARS(this, state->cursor, &codept, 1)) { stb_text_makeundo_insert(state, state->cursor, 1); ++state->cursor; state->has_preferred_x = 0; certainlyChanged = true; } } } } if(certainlyChanged || undoPt != state->undostate.undo_point || redoPt != state->undostate.redo_point || undoWhere != state->undostate.undo_rec[MIN(98,state->undostate.undo_point)].where ){ ofNotifyEvent(onChange, text, this); } // check if we need to scroll { EditorCursor cursor = getEditorCursorForIndex(state->cursor); scrollIntoView(cursor.rect); } return true; } bool mui::TextArea::keyReleased( ofKeyEventArgs &key ){ return true; } mui::TextArea::EditorCursor mui::TextArea::getEditorCursorForIndex( int cursorPos ){ EditorCursor result; ofRectangle size = mui::Helpers::alignBox( this, boundingBox.width, boundingBox.height, horizontalAlign, verticalAlign ); //TODO: this should be cached int pos = 0; float yy = 0; ofRectangle bounds; for( int lineIdx = 0; lineIdx < lines.size(); lineIdx++ ){ StyledLine &line = lines[lineIdx]; int len = utf32_line_length[lineIdx]; if( pos + len <= cursorPos ){ pos += len; yy += line.lineH; } else{ for( vector<LineElement>::iterator elementIt = line.elements.begin(); elementIt != line.elements.end(); ++elementIt ){ LineElement &el = *elementIt; len = (int)utf8_strlen(el.content.styledText.text); if( pos + len <= cursorPos ){ pos += len; } else{ float x; switch(el.content.type){ case SEPARATOR_INVISIBLE: case SEPARATOR: x = el.area.x + el.area.width; case WORD_BLOCK: // it's here, and we know the offset inside the word already. // now let's find it within the string. size_t len = cursorPos-pos; ofRectangle size = mui::Helpers::getFontStash().getTextBounds(substr_utf8(pos, len), el.content.styledText.style, 0, 0); // this could be wrong. hard to tell for my purpose. (layout_width) x = el.x + size.x + size.width; } string sub = substr_utf8(pos,cursorPos-pos); bounds.height = line.lineH; bounds.x = size.x - boundingBox.x + x + bounds.width; bounds.y = size.y - boundingBox.y + yy - line.lineH*0.9; bounds.width = 0; bounds.height = line.lineH; result.rect = bounds; result.lineIt = lines.begin()+lineIdx; result.elementIt = elementIt; return result; } } break; } } if( bounds == ofRectangle() ){ // still nothing? must be at last position! if( lines.size() > 0 ){ float lineH = lines.back().lineH; bounds = lines.back().elements.back().area; bounds.x = size.x - boundingBox.x + bounds.x; bounds.y = size.y - boundingBox.y + yy - 2*lineH; bounds.height = lineH; result.lineIt = lines.end()-1; // there should be always at least one element on each line, // even if it's just a SEPARATOR_INVISIBLE result.elementIt = lines.back().elements.end()-1; result.rect = bounds; } else{ result.lineIt = lines.end(); } } // this is SLOW! // maybe at least remember it? return result; } int mui::TextArea::state_select_min(){ return min(state->select_start,state->select_end); } int mui::TextArea::state_select_max(){ return max(state->select_start,state->select_end); } int mui::TextArea::state_select_len(){ int res = state->select_start - state->select_end; return res<0?-res:res; } string mui::TextArea::getSelectedText(){ return substr_utf8(state_select_min(),state_select_len()); } void mui::TextArea::insertTextAtCursor(string text, bool select){ size_t sel_start = state->select_start; vector<uint32_t> text_utf32 = utf8_to_utf32(text); stb_textedit_paste(this, state, &text_utf32[0], (int)text_utf32.size()); commit(); if (select) { setSelectedRange(sel_start, sel_start + text_utf32.size()); } } int mui::TextArea::getCursorLine(){ int cursor = state->cursor; for(int i = 0; i < lines.size(); i++){ if(utf32_line_length[i]<cursor){ cursor -= utf32_line_length[i]; } else{ return lineNumberDisplayToSource[i]; } } return max(0,(int)lineNumberDisplayToSource.back()); } int mui::TextArea::getCursorColumn(){ int cursor = state->cursor; for(int i = 0; i < lines.size(); i++){ if(utf32_line_length[i]<cursor){ cursor -= utf32_line_length[i]; } else{ return cursor; } } return lines.size()==0?0:max(0,(int)utf32_line_length[0]-1); } ofVec2f mui::TextArea::getCursorPosition(){ EditorCursor c = getEditorCursorForIndex(state->cursor); return {c.rect.x, (*c.elementIt).baseLineY}; } void mui::TextArea::selectAll(){ stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTSTART); stb_textedit_key(this, state, STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT); } void mui::TextArea::selectNothing(){ state->select_start = state->select_end; } void mui::TextArea::setSelectedRange(size_t start, size_t end){ if(utf32.size()==0) return; start = CLAMP(start,0,utf32.size()-1); end = CLAMP(end,0,utf32.size()-1); state->select_start = min(start,end); state->select_end = max(start,end); } pair<size_t,size_t> mui::TextArea::getSelectedRange(){ return make_pair(state->select_start,state->select_end); } #pragma mark Editor Data size_t mui::TextArea::idx_utf8(size_t utf32_idx){ int sz = utf8_positions.size(); return sz==0?0:(utf32_idx<sz? utf8_positions[utf32_idx]: (utf8_positions[sz-1]+octect_size(utf32[sz-1])) ); } string mui::TextArea::substr_utf8( size_t utf32_index, size_t len){ size_t N = utf32.size(); if(len==0 || N == 0) return ""; size_t from = idx_utf8(utf32_index); size_t to = idx_utf8(CLAMP(utf32_index+len-1,0,N-1)) + octect_size(utf32[CLAMP(utf32_index+len-1,0,N-1)]); return text.substr(from,to-from); } void mui::TextAreaInternal::layout_func(void *row, TextArea *data, int start_i){ return mui::TextArea::layout_func_impl(row,data,start_i); } float mui::TextAreaInternal::layout_width(mui::TextArea * data, int n, int i ){ return mui::TextArea::layout_width_impl(data, n, i ); } int mui::TextAreaInternal::delete_chars(mui::TextArea *data, int pos, int num){ return mui::TextArea::delete_chars_impl(data, pos, num); } int mui::TextAreaInternal::insert_chars(mui::TextArea *data, int pos, const uint32_t *newtext, int num){ return mui::TextArea::insert_chars_impl(data, pos, newtext, num); } int mui::TextAreaInternal::move_to_word_previous( mui::TextArea *str, int c ){ return mui::TextArea::move_to_word_previous_impl( str, c ); } int mui::TextAreaInternal::move_to_word_next( mui::TextArea *str, int c ){ return mui::TextArea::move_to_word_next_impl( str, c ); } //-------------------------------------------------------------- mui::TextAreaView::TextAreaView(mui::TextArea * textArea, float x_, float y_, float width_, float height_) :t(textArea), mui::Container(x_,y_,width_,height_){ focusTransferable = false; } //-------------------------------------------------------------- mui::TextAreaView::~TextAreaView() { } //-------------------------------------------------------------- void mui::TextAreaView::draw() { ofRectangle size = Helpers::alignBox(this, t->boundingBox.width, t->boundingBox.height, t->horizontalAlign, t->verticalAlign); if (hasKeyboardFocus() && t->state->select_start != t->state->select_end) { int left = t->state_select_min(); int right = t->state_select_max(); ofSetColor(fg*0.5 + bg*0.5); mui::TextArea::EditorCursor from = t->getEditorCursorForIndex(left); mui::TextArea::EditorCursor to = t->getEditorCursorForIndex(right); ofRectangle rect = from.rect; float yy = rect.y; bool reset = false; if (from.lineIt != to.lineIt) { // selec to end of line rect.width = (*from.lineIt).lineW - rect.x; ofDrawRectangle(rect); from.lineIt++; reset = true; yy += (*from.lineIt).lineH; } while (from.lineIt != to.lineIt) { StyledLine &line = *from.lineIt; float x = size.x - t->boundingBox.x + line.elements.front().x; float y = yy; ofDrawRectangle(x, y, line.lineW, line.lineH); yy += line.lineH; ++from.lineIt; reset = true; } if (from.lineIt != t->lines.end()) { StyledLine &line = *from.lineIt; float x = reset ? (size.x - t->boundingBox.x + line.elements.front().x) : from.rect.x; float y = reset ? yy : from.rect.y; ofDrawRectangle(x, y, to.rect.x + to.rect.width - x, line.lineH); ++from.lineIt; } } // mui::Helpers::getFontStash().drawColumn(text, fontStyle, size.x-boundingBox.x, size.y-boundingBox.y, width); mui::Helpers::getFontStash().drawLines(t->lines, size.x - t->boundingBox.x, size.y - t->boundingBox.y, MuiConfig::debugDraw); if (hasKeyboardFocus()) { if (t->drawActiveBorder) { ofSetColor(200); ofNoFill(); ofDrawRectangle(0.5, 0.5, width - 1, height - 1); ofFill(); } // getting the time is slow, but it can only happen // for a single textfield here because of the focus (so we're fine) uint64_t time = ofGetElapsedTimeMillis(); if (((time - t->lastInteraction) % 1000) < 500) { ofSetColor(255); ofRectangle bounds = t->getEditorCursorForIndex(t->state->cursor).rect; ofDrawRectangle(bounds.x + bounds.width, bounds.y + 2, 2, bounds.height - 2); } } ofSetColor(255); } void mui::TextAreaView::touchDown(ofTouchEventArgs &touch) { t->lastInteraction = ofGetElapsedTimeMillis(); if (t->selectAllOnFocus && !hasKeyboardFocus()) { t->selectAll(); } else { stb_textedit_click(t, t->state, touch.x, touch.y); } requestKeyboardFocus(); } void mui::TextAreaView::touchUp(ofTouchEventArgs &touch) { } void mui::TextAreaView::touchUpOutside(ofTouchEventArgs &touch) { } void mui::TextAreaView::touchMoved(ofTouchEventArgs &touch) { stb_textedit_drag(t, t->state, touch.x, touch.y); } void mui::TextAreaView::touchMovedOutside(ofTouchEventArgs &touch) { stb_textedit_drag(t, t->state, touch.x, touch.y); } void mui::TextAreaView::mouseScroll(ofMouseEventArgs &args) { t->mouseScroll(args); }
30.857868
190
0.676921
kritzikratzi
f72e91096e08bad14971818b061f7bd92afd36ed
2,158
cpp
C++
core/FluffiTester/testApplications/src/linux/DebuggerTester.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
96
2019-09-19T10:28:05.000Z
2022-02-28T11:53:06.000Z
core/FluffiTester/testApplications/src/linux/DebuggerTester.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
123
2019-11-19T09:47:14.000Z
2021-10-19T03:10:51.000Z
core/FluffiTester/testApplications/src/linux/DebuggerTester.cpp
sears-s/fluffi
5f2f6d019041a6268199b69bf2f34487b18b84fe
[ "MIT" ]
23
2019-11-11T06:04:56.000Z
2022-02-11T15:35:26.000Z
/* Copyright 2017-2020 Siemens AG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author(s): Thomas Riedmaier */ #include <chrono> #include <thread> #include <string> #include <stdio.h> //g++ -std=c++11 DebuggerTester.cpp -o DebuggerTester int main(int argc, char* argv[]) { printf("hello world from debugger tester\n"); if (argc < 2) { return -1; } int whattoDo = std::stoi(argv[1]); switch (whattoDo) { case 0: //do nothing printf("option 0: do nothing\n"); break; case 1: //access violation { printf("option 1: pre exception\n"); int * test = (int *)0x12345678; *test = 0x11223344; printf("option 1: post exception\n"); } break; case 2: //div by zero { printf("option 2: pre exception\n"); int a = 0; int b = 1 / a; *(int*)b = 0x182; printf("option 2: post exception\n"); } break; case 3: //hang printf("option 3: do pre sleep\n"); fflush(stdout); for(int i=0; i<10; i++){ printf("option 3: sleeping\n"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } printf("option 3: do post sleep\n"); fflush(stdout); break; default: break; } return 0; }
26.975
82
0.698332
sears-s
f72ea536fbd1ab386b96f493d9c83c123905bc85
1,871
cc
C++
tensorflow/contrib/factorization/ops/factorization_ops.cc
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
680
2016-12-03T14:38:28.000Z
2022-02-16T04:06:45.000Z
tensorflow/contrib/factorization/ops/factorization_ops.cc
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
38
2016-11-17T08:43:51.000Z
2019-11-12T12:27:04.000Z
tensorflow/contrib/factorization/ops/factorization_ops.cc
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
[ "Apache-2.0" ]
250
2016-12-05T10:37:17.000Z
2022-03-18T21:26:55.000Z
// Copyright 2016 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // ============================================================================== #include "tensorflow/core/framework/op.h" namespace tensorflow { REGISTER_OP("WALSComputePartialLhsAndRhs") .Input("factors: float32") .Input("factor_weights: float32") .Input("unobserved_weights: float32") .Input("input_weights: float32") .Input("input_indices: int64") .Input("input_values: float32") .Input("input_block_size: int64") .Input("input_is_transpose: bool") .Output("partial_lhs: float32") .Output("partial_rhs: float32") .Doc(R"( Computes the partial left-hand side and right-hand side of WALS update. factors: Matrix of size m * k. factor_weights: Vector of size m. Corresponds to column weights unobserved_weights: Scalar. Weight for unobserved input entries. input_weights: Vector of size n. Corresponds to row weights. input_indices: Indices for the input SparseTensor. input_values: Values for the input SparseTensor. input_block_size: Scalar. Number of rows spanned by input. input_is_transpose: If true, logically transposes the input for processing. partial_lhs: 3-D tensor with size input_block_size x k x k. partial_rhs: Matrix with size input_block_size x k. )"); } // namespace tensorflow
39.808511
81
0.721005
connectthefuture
f72fbfb118491d9658517a41feba8e1f12c5e7f8
529
cpp
C++
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
1
2019-07-15T00:27:37.000Z
2019-07-15T00:27:37.000Z
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
baekjoon/2156.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <algorithm> using namespace std; int main(){ int n; scanf("%d",&n); int arr[n+1],D[n+1],i; for (i=0;i<n;i++){ scanf("%d",&arr[i]); } for (i=0;i<n;i++){ if (i==0){D[i] = arr[0];} else if (i==1){D[i] = arr[0]+arr[1];} else if (i==2){D[i] = max({D[i-1],arr[2]+arr[0],arr[2]+arr[1]});} else{ D[i] = max({D[i-1],arr[i]+D[i-2],arr[i]+arr[i-1]+D[i-3]}); } } printf("%d",D[n-1]); return 0; }
22.041667
73
0.425331
3-24
f730000977e3f3c5d38f1cc8f45305e50d49f622
10,155
cpp
C++
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
9
2019-01-17T13:11:06.000Z
2022-02-22T10:38:16.000Z
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
null
null
null
osrMain/DX11RenderMain.cpp
OSRTeam/OpenSoundRefenation
3118ea723a2ba94af33ab34bc65eafbd52f7169a
[ "Apache-2.0", "MIT" ]
3
2019-08-09T16:01:37.000Z
2020-08-08T09:58:02.000Z
/********************************************************* * Copyright (C) VERTVER, 2018. All rights reserved. * OpenSoundRefenation - WINAPI open-source DAW * MIT-License ********************************************************** * Module Name: OSR User Interface ********************************************************** * DX11RenderMain.cpp * Direct3D11 main implementation *********************************************************/ #include "stdafx.h" #include <d3dcompiler.h> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3dcompiler.lib") OSRCODE DX11Render::CreateRenderWindow(HWND WindowHandle) { HRESULT hr = NULL; DXGI_SWAP_CHAIN_DESC &sd = m_pChainDesc; DXGI_ADAPTER_DESC LegacyDesc = {}; DXGI_ADAPTER_DESC1 Desc = {}; if (!WindowHandle) { return DX_OSR_BAD_ARGUMENT; } MainHwnd = WindowHandle; // if our PC doesn't support DXGIFactor1 - try to use older if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&m_pDXGIFactory)))) { FAILEDX2(CreateDXGIFactory(IID_PPV_ARGS(&m_pLegacyDXGIFactory))); } if (!m_pDXGIFactory) { if (!m_pLegacyDXGIFactory) { return DX_OSR_BAD_HW; } else { FAILEDX2(m_pLegacyDXGIFactory->QueryInterface(IID_PPV_ARGS(&m_pDXGIFactory))); } } //#TODO: take set adapters for user if (m_pLegacyDXGIFactory) { m_pDXGIFactory->EnumAdapters(NULL, &m_pLegacyDXGIAdapter); m_pLegacyDXGIAdapter->QueryInterface(IID_PPV_ARGS(&m_pDXGIAdapter)); _RELEASE(m_pLegacyDXGIAdapter); _RELEASE(m_pLegacyDXGIFactory); m_pDXGIAdapter->GetDesc(&LegacyDesc); } else { m_pDXGIFactory->EnumAdapters1(NULL, &m_pDXGIAdapter); m_pDXGIAdapter->GetDesc1(&Desc); } sd.BufferDesc.Height = 0; sd.BufferDesc.Width = 0; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferCount = 2; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.OutputWindow = MainHwnd; sd.Windowed = TRUE; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; D3D_FEATURE_LEVEL pFeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 }; D3D_FEATURE_LEVEL FeatureLevel = {}; hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, pFeatureLevels, sizeof(pFeatureLevels) / sizeof(pFeatureLevels[0]), D3D11_SDK_VERSION, &sd, &m_pDXGISwapChain, &m_pDevice, &FeatureLevel, &m_pContext ); if (FAILED(hr)) { FAILEDX2( //-V568 D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, &pFeatureLevels[1], sizeof(pFeatureLevels) / sizeof(pFeatureLevels[0] - 1), D3D11_SDK_VERSION, &sd, &m_pDXGISwapChain, &m_pDevice, &FeatureLevel, &m_pContext )); } ID3D11Texture2D* pBackBuffer = nullptr; m_pDXGISwapChain->GetBuffer(NULL, IID_PPV_ARGS(&pBackBuffer)); m_pDevice->CreateRenderTargetView(pBackBuffer, NULL, &m_pRenderTargetView); _RELEASE(pBackBuffer); return OSR_SUCCESS; } OSRCODE DX11Render::LoadShader( LPCWSTR lpShaderName, LPCSTR* lpShaderFile ) { DWORD dwShaderWritten = 0; DWORD dwShaderSize = 0; LPCSTR lpShader = nullptr; LPWSTR StaticBuf = nullptr; WSTRING_PATH szPathToDir = { 0 }; GetApplicationDirectory(&StaticBuf); memcpy(szPathToDir, StaticBuf, 520); _snwprintf_s(szPathToDir, sizeof(WSTRING_PATH), L"%s%s", szPathToDir, L"\\Shaders"); //-V575 DWORD dwGetDir = GetFileAttributesW(szPathToDir); if (dwGetDir == INVALID_FILE_ATTRIBUTES || !(dwGetDir & FILE_ATTRIBUTE_DIRECTORY)) { if (!CreateDirectoryW(szPathToDir, nullptr)) { DWORD dwError = GetLastError(); if (!IsProcessWithAdminPrivilege() && dwError == ERROR_ACCESS_DENIED) { if (THROW4(L"Can't create temp directory because access denied. Re-run application with 'Administrator' privilege?")) { RunWithAdminPrivilege(); } } else { THROW1(L"Can't create temp directory"); } } } else { _snwprintf_s(szPathToDir, sizeof(WSTRING_PATH), L"%s%s%s", szPathToDir, L"\\", lpShaderName); //-V575 HANDLE hFile = CreateFileW(szPathToDir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (!hFile || hFile == INVALID_HANDLE_VALUE) { return FS_OSR_BAD_HANDLE; } FILE_STANDARD_INFO fileInfo = {}; GetFileInformationByHandleEx(hFile, FileStandardInfo, &fileInfo, sizeof(fileInfo)); dwShaderSize = fileInfo.EndOfFile.LowPart; lpShader = (LPCSTR)FastAlloc(dwShaderSize); ReadFile(hFile, (LPVOID)lpShader, dwShaderSize, &dwShaderWritten, nullptr); CloseHandle(hFile); } if (!lpShader) { return FS_OSR_BAD_PATH; } *lpShaderFile = lpShader; return OSR_SUCCESS; } OSRCODE DX11Render::BeginRenderBlur( ID3D11DeviceContext* pCustomDeviceContext, DWORD Height, DWORD Width ) { if (Width > 10000 || !Width) Width = 1; if (Height > 10000 || !Height) Height = 1; static D3D11_TEXTURE2D_DESC textureDesc = { }; bool RestartRenderTargets = false; if (textureDesc.Width != Width || textureDesc.Height != Height) { RestartRenderTargets = true; } textureDesc.ArraySize = 1; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.Height = Height; textureDesc.MipLevels = 1; textureDesc.MiscFlags = 0; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.Width = Width; static D3D11_SHADER_RESOURCE_VIEW_DESC textureDescSR = { }; textureDescSR.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDescSR.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; textureDescSR.Texture2D.MipLevels = 1; textureDescSR.Texture2D.MostDetailedMip = 0; if (RestartRenderTargets) { _RELEASE(pTargetView1); _RELEASE(pTargetView2); _RELEASE(pTargetView3); _RELEASE(pResourceView1); _RELEASE(pResourceView2); _RELEASE(pResourceView3); _RELEASE(pTexture1); _RELEASE(pTexture2); _RELEASE(pTexture3); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture1)); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture2)); FAILEDX2(m_pDevice->CreateTexture2D(&textureDesc, nullptr, &pTexture3)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture1, nullptr, &pTargetView1)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture2, nullptr, &pTargetView2)); FAILEDX2(m_pDevice->CreateRenderTargetView(pTexture3, nullptr, &pTargetView3)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture1, &textureDescSR, &pResourceView1)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture2, &textureDescSR, &pResourceView2)); FAILEDX2(m_pDevice->CreateShaderResourceView(pTexture3, &textureDescSR, &pResourceView3)); } static LPCSTR lpShader = nullptr; if (!lpShader) { OSRFAIL2(LoadShader(L"MBlur.hlsl", &lpShader), L"Can't load shader"); } if (!vertexShaderBlur) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "VSSimpleBlur", "vs_4_0", 0, 0, &vertexShaderBlur, nullptr)); FAILEDX2(m_pDevice->CreateVertexShader(vertexShaderBlur->GetBufferPointer(), vertexShaderBlur->GetBufferSize(), nullptr, &pBlurVertexShader)); } if (!pBlurPixelShaderU) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "PSSimpleBlurU", "ps_4_0", 0, 0, &pixelShaderBlurU, nullptr)); FAILEDX2(m_pDevice->CreatePixelShader(pixelShaderBlurU->GetBufferPointer(), pixelShaderBlurU->GetBufferSize(), nullptr, &pBlurPixelShaderU)); } if (!pBlurPixelShaderV) { FAILEDX2(D3DCompile(lpShader, strlen(lpShader), nullptr, nullptr, nullptr, "PSSimpleBlurV", "ps_4_0", 0, 0, &pixelShaderBlurV, nullptr)); FAILEDX2(m_pDevice->CreatePixelShader(pixelShaderBlurV->GetBufferPointer(), pixelShaderBlurV->GetBufferSize(), nullptr, &pBlurPixelShaderV)); } if (!m_pDisplaySizeBuffer) { D3D11_BUFFER_DESC pDesc = {}; pDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pDesc.ByteWidth = sizeof(float) * 4; pDesc.CPUAccessFlags = 0;// D3D11_CPU_ACCESS_WRITE; pDesc.MiscFlags = 0; pDesc.StructureByteStride = 0; pDesc.Usage = D3D11_USAGE_DEFAULT;// DYNAMIC; FAILEDX2(m_pDevice->CreateBuffer(&pDesc, nullptr, &m_pDisplaySizeBuffer)); } pCustomDeviceContext->OMSetRenderTargets(1, &pTargetView1, nullptr); float ffgfdgfdg[4] = { 0.07f, 0.07f, 0.07f, 1.00f }; pCustomDeviceContext->ClearRenderTargetView(pTargetView1, ffgfdgfdg); return OSR_SUCCESS; } OSRCODE DX11Render::EndRenderBlur( ID3D11DeviceContext* pCustomDeviceContext, DWORD Height, DWORD Width ) { ID3D11Buffer* Buf = nullptr; UINT ba1 = 0; UINT ba2 = 0; // stage 1 D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(D3D11_VIEWPORT)); vp.Width = Width; vp.Height = Height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; pCustomDeviceContext->RSSetViewports(1, &vp); const D3D11_RECT r = { 0, 0, Width, Height }; pCustomDeviceContext->RSSetScissorRects(1, &r); float DisplaySize[4] = { Width, Height , 0.0, 0.0}; pCustomDeviceContext->UpdateSubresource(m_pDisplaySizeBuffer, 0, nullptr, &DisplaySize[0], 0, 0); if (m_pDisplaySizeBuffer) { pCustomDeviceContext->PSSetConstantBuffers(5, 1, &m_pDisplaySizeBuffer); } pCustomDeviceContext->VSSetShader(pBlurVertexShader, nullptr, 0); pCustomDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); pCustomDeviceContext->IASetVertexBuffers(0, 1, &Buf, &ba1, &ba2); pCustomDeviceContext->IASetIndexBuffer(nullptr, DXGI_FORMAT_R16_UINT, 0); pCustomDeviceContext->IASetInputLayout(nullptr); pCustomDeviceContext->OMSetRenderTargets(1, &pTargetView2, nullptr); pCustomDeviceContext->PSSetShaderResources(0, 1, &pResourceView1); pCustomDeviceContext->PSSetShader(pBlurPixelShaderU, nullptr, 0); pCustomDeviceContext->Draw(3, 0); // stage 2 pCustomDeviceContext->OMSetRenderTargets(1, &m_pRenderTargetView, nullptr); pCustomDeviceContext->PSSetShaderResources(0, 1, &pResourceView2); pCustomDeviceContext->PSSetShader(pBlurPixelShaderV, nullptr, 0); pCustomDeviceContext->Draw(3, 0); return OSR_SUCCESS; }
31.055046
144
0.742885
OSRTeam
f730c11c7760a16388ec888a459f61c0e1f8fb1f
4,565
cpp
C++
markcore/ut/use_markcore.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
markcore/ut/use_markcore.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
markcore/ut/use_markcore.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author:liu.hao(33852613@163.com) Time:2018-2 info: ***************************************************************************************************/ #include <markcore.h> #include <gtest/gtest.h> //////////////////////////////////////////////////////////////////////////////////////////////////// TEST(mkheaders, pragma) { #ifdef __WINDOWS__ // 链接基础库 #pragma comment(lib, "shell32.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "user32.lib") #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Mpr.lib") #pragma comment(lib, "DbgHelp.lib") //关闭部分编译警告 // 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' #pragma warning(disable:4251) // 'function': was declared deprecated #pragma warning(disable:4996) // 'this' : used in base member initializer list #pragma warning(disable:4355) // 'symbol name': attributes not present on previous declaration. #pragma warning(disable: 4985) // 'virtual function overrides' : previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers #pragma warning(disable: 4373) // 'keyword' : ignored on left of 'type' when no variable is declared #pragma warning(disable: 4091) #endif } TEST(mkheaders, PrintMacro) { //操作系统版本,在begin.cmake中定义 #ifdef __WINDOWS__ MK_PRINT("__WINDOWS__ = %d", __WINDOWS__); #endif #ifdef __LINUX__ MK_PRINT("__LINUX__ = %d", __LINUX__); #endif //编译器版本 #ifdef _MSC_VER MK_PRINT("_MSC_VER = %d", _MSC_VER); #endif #ifdef __GNUC__ MK_PRINT("__GNUC__ = %d", __GNUC__); #endif //VC版本 #ifdef WINVER MK_PRINT("WINVER = 0x%04x", WINVER); #endif #ifdef _WIN32_WINNT MK_PRINT("_WIN32_WINNT = 0x%04x", _WIN32_WINNT); #endif #ifdef _WIN32_WINDOWS MK_PRINT("_WIN32_WINDOWS = 0x%04x", _WIN32_WINDOWS); #endif #ifdef _WIN32_IE MK_PRINT("_WIN32_IE = 0x%04x", _WIN32_IE); #endif //windows常用头文件 #ifdef _WINSOCK2API_ MK_PRINT("_WINSOCK2API_ is used"); #endif #ifdef _WINSOCKAPI_ MK_PRINT("_WINSOCKAPI_ is used"); #endif #ifdef _INC_TCHAR MK_PRINT("_INC_TCHAR is used"); #endif //64位宏 #ifdef __x86_64__ MK_PRINT("__x86_64__ is used"); #endif #ifdef __ia64__ MK_PRINT("__ia64__ is used"); #endif #ifdef __PPC64__ MK_PRINT("__PPC64__ is used"); #endif #ifdef __powerpc64__ MK_PRINT("__powerpc64__ is used"); #endif #ifdef __mips64 MK_PRINT("__mips64 is used"); #endif #ifdef __arch64__ MK_PRINT("__arch64__ is used"); #endif #ifdef __aarch64__ MK_PRINT("__aarch64__ is used"); #endif #ifdef _WIN64 MK_PRINT("_WIN64 = %d", _WIN64); #endif #ifdef __64BIT__ MK_PRINT("__64BIT__ is used"); #endif //unicode宏,在begin.cmake中定义 #ifdef _UNICODE MK_PRINT("_UNICODE = %d", _UNICODE); #endif #ifdef UNICODE MK_PRINT("UNICODE = %d", UNICODE); #endif //debug宏 #ifdef _DEBUG MK_PRINT("_DEBUG = %d", _DEBUG); MK_PRINT("__DEBUG__ is used"); #endif //va_copy宏 #ifdef va_copy MK_PRINT("va_copy is used"); #endif #ifdef __va_copy MK_PRINT("__va_copy is used"); #endif //__FUNC_NAME__宏 #ifdef __FUNC_NAME__ MK_PRINT(_T("__FUNC_NAME__ = %s"), __FUNC_NAME__); #endif } TEST(mkheaders, mkChar) { const mkChar* ch1 = _T("abcecdrgg"); MK_PRINT(_T("ch1 = %s"), ch1); const mkChar ch3[] = _T("123456789"); //mk_char 长度 #define CONSTANT_STRING_LEN(str) ((sizeof(str)/sizeof(mkChar)) - 1) int size3 = CONSTANT_STRING_LEN(ch3); MK_PRINT(_T("ch3 = %s, size = %d"), ch3, size3); } TEST(mkheaders, int64) { int64 i1 = -123456; uint64 i2 = 123456; MK_PRINT(_T("i1 = %lld, i2 = %lld"), i1, i2); } TEST(mkheaders, MK_ASSERT) { MK_ASSERT(true); //MK_ASSERT(false); }
24.153439
146
0.62322
unihykes
f73c165749ddd353556967b987f6ac880665b7e8
2,887
cpp
C++
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
libStat3rd/Statistical/RegressionFactory.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "RegressionFactory.hpp" using namespace EnjoLib; RegressionFactory::RegressionFactory() { //ctor } RegressionFactory::~RegressionFactory() { //dtor } /* #include "RegressionRegression3.hpp" #include "RegressionMKL.hpp" #include "RegressionNumpy.hpp" #include "RegressionNewmat10.hpp" */ /* Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateRegression3() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionRegression3()); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateDefault() { //return CreateNewmat(); /// TODO: Errors in tests, just like MKL! Ergo: wrong Regression or tests! return CreateMKL(); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateMKL() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionMKL()); } #ifdef USE_LIB_NEWMAT Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateNewmat() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionNewmat10()); } #endif Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateNumpy() { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionNumpy()); } EIGENTYPE_DEFAULT, EIGENTYPE_EIGEN3, EIGENTYPE_MKL, EIGENTYPE_NEWMAT, EIGENTYPE_NUMPY */ #include "3rdParty/RegressionGSL.hpp" #include "3rdParty/RegressionEigen.hpp" //#include "RegressionAF.h" #include <Util/Except.hpp> #include <Template/CorradePointer.h> Corrade::Containers::Pointer<RegressionAbstract> RegressionFactory::CreateDefault() const { return Create(RegressionAbstract::RegType::REG_EIGEN); } Corrade::Containers::Pointer<RegressionAbstract> RegressionFactory::Create(const RegressionAbstract::RegType & eigType) const { return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); } /* #include "RegressionGSL.h" #include "RegressionEigen.h" //#include "RegressionAF.h" #include <Util/Except.hpp> #include <Template/CorradePointer.h> Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::Create(const RegressionAbstract::RegType & type) { switch (type) { case RegType::REG_GSL: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionGSL()); case RegType::REG_EIGEN: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); //case RegType::REG_AFIRE: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionAF()); case RegType::REG_AFIRE: return Corrade::Containers::Pointer<RegressionAbstract>(new RegressionEigen()); } throw EnjoLib::ExceptRuntimeError("RegressionAbstract::Create() Not handled."); } Corrade::Containers::Pointer<RegressionAbstract> RegressionAbstract::CreateDefault() { return Create(RegType::REG_EIGEN); } */
31.725275
125
0.764808
EnjoMitch
f73e335112f0fe4fc726fb6f647602c6cc30e053
2,671
cpp
C++
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
10
2020-02-28T21:00:25.000Z
2021-11-18T03:24:57.000Z
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
null
null
null
MidiNote.cpp
christofmuc/juce-utils
e5d7e0b4ac6f3c0d43d3f3cff779f5f8e72275e4
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2021 Christof Ruch * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "MidiNote.h" #include <cmath> MidiNote::MidiNote(double frequency, double frequencyA4 /* = 440.0 */) : frequency_(frequency), frequencyA4_(frequencyA4) { midiNote_ = frequencyToNoteNumber(frequency, frequencyA4_); } MidiNote::MidiNote(int noteNumber, double frequencyA4 /* = 440.0 */) : midiNote_(noteNumber), frequencyA4_(frequencyA4) { frequency_ = noteNumberToFrequency(noteNumber, frequencyA4_); } int MidiNote::frequencyToNoteNumber(double frequency, double frequencyA4 /* = 440.0 */) { // https://en.wikipedia.org/wiki/Piano_key_frequencies if (frequency > 0.0) { return (int) std::round(12 * std::log2(frequency / frequencyA4) + 69); } else { return 0; } } double MidiNote::noteNumberToFrequency(int noteNumber, double frequencyA4 /* = 440.0 */) { // 69 is MIDI for A4 return frequencyA4 * std::pow(2.0, (noteNumber - 69) / 12.0); } int MidiNote::noteNumber() const { return midiNote_; } double MidiNote::frequency() const { return frequency_; } double MidiNote::cents() { // A wild ride: http://www.sengpielaudio.com/calculator-centsratio.htm if (frequency_ > 0.0) { return 1200.0 * std::log2(frequency_ / noteNumberToFrequency(midiNote_, frequencyA4_)); } else { return 0.0; } } std::string MidiNote::name() const { // Ok, JUCE can do this for us if (midiNote_ > 0) { return MidiMessage::getMidiNoteName(midiNote_, true, true, 4).toStdString(); } else { return "-"; } }
30.701149
121
0.70161
christofmuc
f73e981b7bc00748e93715b88575d1b799756d94
11,357
cpp
C++
libscaler/libscaler-v4l2.cpp
Exynos7580/android_hardware_samsung_slsi_exynos5
3f00062f02f255c38e217a411f6d1711c287fb54
[ "Apache-2.0" ]
null
null
null
libscaler/libscaler-v4l2.cpp
Exynos7580/android_hardware_samsung_slsi_exynos5
3f00062f02f255c38e217a411f6d1711c287fb54
[ "Apache-2.0" ]
null
null
null
libscaler/libscaler-v4l2.cpp
Exynos7580/android_hardware_samsung_slsi_exynos5
3f00062f02f255c38e217a411f6d1711c287fb54
[ "Apache-2.0" ]
1
2020-02-02T00:36:55.000Z
2020-02-02T00:36:55.000Z
/* * Copyright (C) 2014 The Android Open Source Project * Copyright@ Samsung Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! * \file libscaler-v4l2.cpp * \brief source file for Scaler HAL * \author Cho KyongHo <pullip.cho@samsung.com> * \date 2014/05/12 * * <b>Revision History: </b> * - 2014.05.12 : Cho KyongHo (pullip.cho@samsung.com) \n * Create */ #include <cstring> #include <cstdlib> #include "libscaler-v4l2.h" void CScalerV4L2::Initialize(int instance) { snprintf(m_cszNode, SC_MAX_NODENAME, SC_DEV_NODE "%d", SC_NODE(instance)); m_fdScaler = exynos_v4l2_open(m_cszNode, O_RDWR); if (m_fdScaler < 0) { SC_LOGERR("Failed to open '%s'", m_cszNode); return; } unsigned int cap = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_VIDEO_CAPTURE_MPLANE; if (!exynos_v4l2_querycap(m_fdScaler, cap)) { SC_LOGERR("Failed to query capture on '%s'", m_cszNode); close(m_fdScaler); m_fdScaler = -1; } else { m_fdValidate = -m_fdScaler; } } CScalerV4L2::CScalerV4L2(int instance, int allow_drm) { m_fdScaler = -1; m_iInstance = instance; m_nRotDegree = 0; m_fStatus = 0; memset(&m_frmSrc, 0, sizeof(m_frmSrc)); memset(&m_frmDst, 0, sizeof(m_frmDst)); m_frmSrc.fdAcquireFence = -1; m_frmDst.fdAcquireFence = -1; m_frmSrc.name = "output"; m_frmDst.name = "capture"; m_frmSrc.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; m_frmDst.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; Initialize(instance); if(Valid()) { if (allow_drm) SetFlag(m_fStatus, SCF_ALLOW_DRM); SC_LOGD("Successfully opened '%s'; returned fd %d; drmmode %s", m_cszNode, m_fdScaler, allow_drm ? "enabled" : "disabled"); } } CScalerV4L2::~CScalerV4L2() { if (m_fdScaler >= 0) close(m_fdScaler); m_fdScaler = -1; } bool CScalerV4L2::Stop() { if (!ResetDevice(m_frmSrc)) { SC_LOGE("Failed to stop Scaler for the output frame"); return false; } if (!ResetDevice(m_frmDst)) { SC_LOGE("Failed to stop Scaler for the cature frame"); return false; } return true; } bool CScalerV4L2::Run() { if (!DevSetCtrl()) return false; if (!DevSetFormat()) return false; if (!ReqBufs()) return false; if (!StreamOn()) return false; if (!QBuf()) return false; return DQBuf(); } bool CScalerV4L2::DevSetCtrl() { if (!TestFlag(m_fStatus, SCF_ROTATION_FRESH)) { SC_LOGD("Skipping rotation and flip setting due to no change"); return true; } if (!Stop()) return false; if (exynos_v4l2_s_ctrl(m_fdScaler, V4L2_CID_ROTATE, m_nRotDegree) < 0) { SC_LOGERR("Failed V4L2_CID_ROTATE with degree %d", m_nRotDegree); return false; } if (exynos_v4l2_s_ctrl(m_fdScaler, V4L2_CID_VFLIP, TestFlag(m_fStatus, SCF_HFLIP)) < 0) { SC_LOGERR("Failed V4L2_CID_VFLIP - %d", TestFlag(m_fStatus, SCF_VFLIP)); return false; } if (exynos_v4l2_s_ctrl(m_fdScaler, V4L2_CID_HFLIP, TestFlag(m_fStatus, SCF_VFLIP)) < 0) { SC_LOGERR("Failed V4L2_CID_HFLIP - %d", TestFlag(m_fStatus, SCF_HFLIP)); return false; } SC_LOGD("Successfully set CID_ROTATE(%d), CID_VFLIP(%d) and CID_HFLIP(%d)", m_nRotDegree, TestFlag(m_fStatus, SCF_VFLIP), TestFlag(m_fStatus, SCF_HFLIP)); ClearFlag(m_fStatus, SCF_ROTATION_FRESH); if (TestFlag(m_fStatus, SCF_CSC_FRESH) && TestFlag(m_fStatus, SCF_CSC_WIDE)) { if (exynos_v4l2_s_ctrl(m_fdScaler, V4L2_CID_CSC_RANGE, TestFlag(m_fStatus, SCF_CSC_WIDE) ? 1 : 0) < 0) { SC_LOGERR("Failed V4L2_CID_CSC_RANGE to %d", TestFlag(m_fStatus, SCF_CSC_WIDE)); return false; } ClearFlag(m_fStatus, SCF_CSC_FRESH); } return true; } bool CScalerV4L2::ResetDevice(FrameInfo &frm) { if (!DQBuf(frm)) return false; if (TestFlag(frm.flags, SCFF_STREAMING)) { if (exynos_v4l2_streamoff(m_fdScaler, frm.type) < 0 ) { SC_LOGERR("Failed STREAMOFF for the %s", frm.name); return false; } ClearFlag(frm.flags, SCFF_STREAMING); } SC_LOGD("VIDIC_STREAMOFF is successful for the %s", frm.name); if (TestFlag(frm.flags, SCFF_REQBUFS)) { v4l2_requestbuffers reqbufs; memset(&reqbufs, 0, sizeof(reqbufs)); reqbufs.type = frm.type; reqbufs.memory = frm.memory; if (exynos_v4l2_reqbufs(m_fdScaler, &reqbufs) < 0 ) { SC_LOGERR("Failed to REQBUFS(0) for the %s", frm.name); return false; } ClearFlag(frm.flags, SCFF_REQBUFS); } SC_LOGD("VIDIC_REQBUFS(0) is successful for the %s", frm.name); return true; } bool CScalerV4L2::DevSetFormat(FrameInfo &frm) { if (!TestFlag(frm.flags, SCFF_BUF_FRESH)) { SC_LOGD("Skipping S_FMT for the %s since it is already done", frm.name); return true; } if (!ResetDevice(frm)) { SC_LOGE("Failed to VIDIOC_S_FMT for the %s", frm.name); return false; } v4l2_format fmt; fmt.type = frm.type; fmt.fmt.pix_mp.pixelformat = frm.color_format; fmt.fmt.pix_mp.width = frm.width; fmt.fmt.pix_mp.height = frm.height; if (exynos_v4l2_s_fmt(m_fdScaler, &fmt) < 0) { SC_LOGERR("Failed S_FMT(fmt: %d, w:%d, h:%d) for the %s", fmt.fmt.pix_mp.pixelformat, fmt.fmt.pix_mp.width, fmt.fmt.pix_mp.height, frm.name); return false; } // returned fmt.fmt.pix_mp.num_planes and fmt.fmt.pix_mp.plane_fmt[i].sizeimage frm.out_num_planes = fmt.fmt.pix_mp.num_planes; for (int i = 0; i < frm.out_num_planes; i++) frm.out_plane_size[i] = fmt.fmt.pix_mp.plane_fmt[i].sizeimage; v4l2_crop crop; crop.type = frm.type; crop.c = frm.crop; if (exynos_v4l2_s_crop(m_fdScaler, &crop) < 0) { SC_LOGERR("Failed S_CROP(fmt: %d, l:%d, t:%d, w:%d, h:%d) for the %s", crop.type, crop.c.left, crop.c.top, crop.c.width, crop.c.height, frm.name); return false; } if (frm.out_num_planes > SC_MAX_PLANES) { SC_LOGE("Number of planes exceeds %d of %s", frm.out_num_planes, frm.name); return false; } ClearFlag(frm.flags, SCFF_BUF_FRESH); SC_LOGD("Successfully S_FMT and S_CROP for the %s", frm.name); return true; } bool CScalerV4L2::DevSetFormat() { if (!DevSetFormat(m_frmSrc)) return false; return DevSetFormat(m_frmDst); } bool CScalerV4L2::QBuf(FrameInfo &frm, int *pfdReleaseFence) { v4l2_buffer buffer; v4l2_plane planes[SC_MAX_PLANES]; if (!TestFlag(frm.flags, SCFF_REQBUFS)) { SC_LOGE("Trying to QBUF without REQBUFS for %s is not allowed", frm.name); return false; } if (!DQBuf(frm)) return false; memset(&buffer, 0, sizeof(buffer)); memset(&planes, 0, sizeof(planes)); buffer.type = frm.type; buffer.memory = frm.memory; buffer.index = 0; buffer.length = frm.out_num_planes; if (pfdReleaseFence) { buffer.flags = V4L2_BUF_FLAG_USE_SYNC; buffer.reserved = frm.fdAcquireFence; } buffer.m.planes = planes; for (unsigned long i = 0; i < buffer.length; i++) { planes[i].length = frm.out_plane_size[i]; if (V4L2_TYPE_IS_OUTPUT(buffer.type)) planes[i].bytesused = planes[i].length; if (buffer.memory == V4L2_MEMORY_DMABUF) planes[i].m.fd = reinterpret_cast<int>(frm.addr[i]); else planes[i].m.userptr = reinterpret_cast<unsigned long>(frm.addr[i]); } if (exynos_v4l2_qbuf(m_fdScaler, &buffer) < 0) { SC_LOGERR("Failed to QBUF for the %s", frm.name); return false; } SetFlag(frm.flags, SCFF_QBUF); if (pfdReleaseFence) { if (frm.fdAcquireFence >= 0) close(frm.fdAcquireFence); frm.fdAcquireFence = -1; *pfdReleaseFence = static_cast<int>(buffer.reserved); } SC_LOGD("Successfully QBUF for the %s", frm.name); return true; } bool CScalerV4L2::ReqBufs(FrameInfo &frm) { v4l2_requestbuffers reqbufs; if (TestFlag(frm.flags, SCFF_REQBUFS)) { SC_LOGD("Skipping REQBUFS for the %s since it is already done", frm.name); return true; } memset(&reqbufs, 0, sizeof(reqbufs)); reqbufs.type = frm.type; reqbufs.memory = frm.memory; reqbufs.count = 1; if (exynos_v4l2_reqbufs(m_fdScaler, &reqbufs) < 0) { SC_LOGERR("Failed to REQBUFS for the %s", frm.name); return false; } SetFlag(frm.flags, SCFF_REQBUFS); SC_LOGD("Successfully REQBUFS for the %s", frm.name); return true; } bool CScalerV4L2::SetRotate(int rot, int flip_h, int flip_v) { if ((rot % 90) != 0) { SC_LOGE("Rotation of %d degree is not supported", rot); return false; } SetRotDegree(rot); if (flip_h) SetFlag(m_fStatus, SCF_VFLIP); else ClearFlag(m_fStatus, SCF_VFLIP); if (flip_v) SetFlag(m_fStatus, SCF_HFLIP); else ClearFlag(m_fStatus, SCF_HFLIP); SetFlag(m_fStatus, SCF_ROTATION_FRESH); return true; } bool CScalerV4L2::StreamOn(FrameInfo &frm) { if (!TestFlag(frm.flags, SCFF_REQBUFS)) { SC_LOGE("Trying to STREAMON without REQBUFS for %s is not allowed", frm.name); return false; } if (!TestFlag(frm.flags, SCFF_STREAMING)) { if (exynos_v4l2_streamon(m_fdScaler, frm.type) < 0 ) { SC_LOGERR("Failed StreamOn for the %s", frm.name); return false; } SetFlag(frm.flags, SCFF_STREAMING); SC_LOGD("Successfully VIDIOC_STREAMON for the %s", frm.name); } return true; } bool CScalerV4L2::DQBuf(FrameInfo &frm) { if (!TestFlag(frm.flags, SCFF_QBUF)) return true; v4l2_buffer buffer; v4l2_plane plane[SC_NUM_OF_PLANES]; memset(&buffer, 0, sizeof(buffer)); buffer.type = frm.type; buffer.memory = frm.memory; if (V4L2_TYPE_IS_MULTIPLANAR(buffer.type)) { memset(plane, 0, sizeof(plane)); buffer.length = frm.out_num_planes; buffer.m.planes = plane; } ClearFlag(frm.flags, SCFF_QBUF); if (exynos_v4l2_dqbuf(m_fdScaler, &buffer) < 0 ) { SC_LOGERR("Failed to DQBuf the %s", frm.name); return false; } if (buffer.flags & V4L2_BUF_FLAG_ERROR) { SC_LOGE("Error occurred while processing streaming data"); return false; } SC_LOGD("Successfully VIDIOC_DQBUF for the %s", frm.name); return true; }
26.168203
93
0.624637
Exynos7580
f7412a4093edfe75070815544a4e3b310ade5fbf
75
cpp
C++
S3DWrapper10/Wrapper.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
27
2020-11-12T19:24:54.000Z
2022-03-27T23:10:45.000Z
S3DWrapper10/Wrapper.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
2
2020-11-02T06:30:39.000Z
2022-02-23T18:39:55.000Z
S3DWrapper10/Wrapper.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
3
2021-08-16T00:21:08.000Z
2022-02-23T19:19:36.000Z
#include "StdAfx.h" #include "Wrapper.h" #include "DXGISwapChainWrapper.h"
18.75
33
0.76
bo3b
f7451eb7c142df31100dcc499730a8cf2a995ae5
6,424
hpp
C++
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
src/math/Quaternion.hpp
jmitchell24/cpp-utility-lib
76e7bae9f07b741c409a282604a999ab86fc0702
[ "Apache-2.0" ]
null
null
null
// Copyright 2013, James Mitchell, All rights reserved. #pragma once #include "../Types.hpp" #include "../string/Types.hpp" #include "../string/Segment.hpp" #include "../typetraits/CallTraits.hpp" #include "Matrix4x4.hpp" #include "Vector4D.hpp" namespace util { template <typename N> struct QuatN { typedef N Num; typedef Num& NumRef; typedef best_param<Num> NumParam; typedef Vec3N<Num> Vec3; typedef Vec3& Vec3Ref; typedef best_param<Vec3> Vec3Param; typedef Vec4N<Num> Vec4; typedef Vec4& Vec4Ref; typedef best_param<Vec4> Vec4Param; typedef Mat44N<Num> Mat44; typedef Mat44& Mat44Ref; typedef best_param<Mat44> Mat44Param; typedef QuatN<Num> Quat; typedef Quat& QuatRef; typedef best_param<Quat> QuatParam; typedef typename Vec4::Components Components; union { struct { union { struct { Num x,y,z; }; Vec3 complex; }; union { Num w, real; }; }; Components components; Vec4 vector; }; inline QuatN() : vector() {} inline QuatN(Quat&& q) : vector(std::move(q.vector)) {} inline QuatN(Quat const& q) : vector(q.vector) {} template <typename P> inline explicit QuatN(QuatN<P> const& q) : components(q.components) {} inline explicit QuatN(Vec4Param v) : vector(v) {} inline QuatN(Vec3Param complex, NumParam real) : complex(complex), real(real) {} inline QuatN(NumParam x, NumParam y, NumParam z, NumParam w) : x(x), y(y), z(z), w(w) {} inline Quat conjugate() const // conjugate { return Quat(-complex, real); } inline Num length() const { return vector.length(); } inline Quat normal() const { return Quat(vector.normal()); } inline Quat inverse() const { return conjugate() / normal(); } inline static Quat euler(NumParam x, NumParam y, NumParam z) { Num const c1 = std::cos(z / (Num)2),c2 = std::cos(y / (Num)2),c3 = std::cos(x / (Num)2), s1 = std::sin(z / (Num)2),s2 = std::sin(y / (Num)2),s3 = std::sin(x / (Num)2); return Quat( c1*c2*s3 - s1*s2*c3, c1*s2*c3 + s1*c2*s3, s1*c2*c3 - c1*s2*s3, c1*c2*c3 + s1*s2*s3); } inline static Quat euler(Vec3Param v) { return euler(v.x, v.y, v.z); } inline Mat44 matrix() const { typename Mat44::Components const components = { +w,-z,+y,+x, +z,+w,-x,+y, -y,+x,+w,+z, -x,-y,-z,+w }; return Mat44(components); } inline Mat44 rightMatrix() const { typename Mat44::Components const components = { +w,-z, y,-x, +z,+w,-x,-y, -y,+x,+w,-z, +x,+y,+z,+w }; return Mat44(components); } inline Mat44 rotation() const { typename Mat44::Components const components = { (Num)1-(Num)2*y*y - (Num)2*z*z, (Num)2*x*y - (Num)2*z*w, (Num)2*x*z + (Num)2*y*w, (Num)0, (Num)2*x*y + (Num)2*z*w, (Num)1-(Num)2*x*x - (Num)2*z*z, (Num)2*y*z - (Num)2*x*w, (Num)0, (Num)2*x*z - (Num)2*y*w, (Num)2*y*z + (Num)2*x*w, (Num)1-(Num)2*x*x - (Num)2*y*y, (Num)0, (Num)0 , (Num)0 , (Num)0 , (Num)1 }; return Mat44(components); } Vec3 rotatedVector(Vec3Param v) const { return (*this * Quat(v, Num()) * conjugate()).complex; } inline Quat operator* (NumParam s) const { return Quat(vector * s); } inline Quat operator/ (NumParam s) const { return Quat(vector / s); } inline Quat operator+ (NumParam s) const { return Quat(vector + s); } inline Quat operator- (NumParam s) const { return Quat(vector - s); } inline Quat operator+ (QuatParam q) const { return Quat(vector + q.vector); } inline Quat operator- (QuatParam q) const { return Quat(vector - q.vector); } inline Quat operator/ (QuatParam q) const { return Quat(vector / q.vector); } inline Quat operator* (QuatParam q) const { return Quat(y*q.z - z*q.y + x*q.w + w*q.x, z*q.x - x*q.z + y*q.w + w*q.y, x*q.y - y*q.x + z*q.w + w*q.z, w*q.w - x*q.x - y*q.y - z*q.z); } inline Quat& operator = (QuatParam q) { vector = q.vector; return *this; } inline Quat& operator*= (QuatParam q) { return *this = *this * q; } inline Quat& operator/= (QuatParam q) { return *this = *this / q; } inline Quat& operator+= (QuatParam q) { return *this = *this + q; } inline Quat& operator-= (QuatParam q) { return *this = *this - q; } inline Quat& operator*= (NumParam n) { return *this = *this * n; } inline Quat& operator/= (NumParam n) { return *this = *this / n; } inline Quat& operator+= (NumParam n) { return *this = *this + n; } inline Quat& operator-= (NumParam n) { return *this = *this - n; } inline bool tryParse(Segment const& s) { return vector.tryParse(s); } inline string_t str() const { return vector.str(); } DEFINE_OBJECT_OSTREAM_OPERATOR(Quat) DEFINE_OBJECT_ISTREAM_OPERATOR(Quat) }; template <typename N> using QuatT = QuatN<N>; typedef QuatT<real_t> Quat; typedef QuatT<float> Quatf; typedef QuatT<double> Quatd; extern template struct QuatN<float>; extern template struct QuatN<double>; }
29.603687
119
0.475716
jmitchell24
f74657909e9fe922540ca914440d658265313dca
12,286
cpp
C++
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
9
2019-05-20T12:06:36.000Z
2022-03-24T19:11:06.000Z
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
null
null
null
src/ADBDriverDLL/src/DriverNetSyncInternal.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
3
2020-07-06T04:51:33.000Z
2021-07-26T20:08:02.000Z
/* MIT License Android remote Viewer, GUI ADB tools Android Viewer developed to view and control your android device from a PC. ADB exchange Android Viewer, support scale view, input tap from mouse, input swipe from keyboard, save/copy screenshot, etc.. Copyright (c) 2016-2019 PS GitHub: https://github.com/ClnViewer/ADB-Android-Viewer Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "DriverInternal.h" #include "DriverConst.h" #include "Utils/extTraceFunction.h" #include <errno.h> #define ADBSYNCDATA_SIZE static_cast<int32_t>(sizeof(DriverNet::ADBSYNCDATA)) #define ADBSYNCID_SIZE static_cast<int32_t>(sizeof(((DriverNet::ADBSYNCDATA*)0)->id)) #define TRACE_DBG_STR_0 "pkt.rsz = %d, pkt.asz = %d" #define TRACE_DBG_STR_1 "ecode = %d, errno = %d, error: %s" #define TRACE_DBG_STR_2 ", errno = %d, error: %s" namespace GameDev { DriverNet::SyncTagType DriverNet::receiveData(SOCKET client, std::unique_ptr<char[]> & dbuf, DriverNet::ADBSYNCPKT & pkt) { tracer(); struct timeval tms{}; fd_set fds{}; FD_ZERO(&fds); FD_SET(client, &fds); tms.tv_sec = 5; tms.tv_usec = 0; errno = 0; pkt.buff = nullptr; switch (::select(client + 1, &fds, nullptr, nullptr, &tms)) { case SOCKET_ERROR: { if (DriverNet::GetNetBlock()) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz = -2; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } case 0: /// timeout { if (!errno) trace_return(DriverNet::SyncTagType::SYNC_TAG_END); pkt.rsz = -3; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } default: { switch ((pkt.rsz = ::recv(client, dbuf.get(), 65536, 0))) { case 0: /// disconnect { pkt.rsz = -4; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } case SOCKET_ERROR: { if (DriverNet::GetNetBlock()) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz = -1; trace_info( TRACE_DBG_STR_1, pkt.rsz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } default: { if (pkt.rsz > 0) { pkt.buff = dbuf.get(); trace_return(DriverNet::SyncTagType::SYNC_TAG_OKAY); } trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } } break; } } } bool DriverNet::receivedDataWrite(FILE *fpp, DriverNet::ADBSYNCPKT & pkt) { tracer(); if (!pkt.buff) trace_return(false); errno = 0; size_t sz = static_cast<size_t>(pkt.rsz); if (::fwrite(pkt.buff, 1, sz, fpp) != sz) trace_return(false); pkt.asz -= pkt.rsz; trace_info( TRACE_DBG_STR_0 TRACE_DBG_STR_2, pkt.rsz, pkt.asz, errno, ((errno) ? strerror(errno) : "-") ); trace_return(true); } DriverNet::SyncTagType DriverNet::parseDataTag(DriverNet::ADBSYNCPKT & pkt, DriverNet::ADBSYNCDATA const & req) { tracer(); do { if (req.sz >= (UINT_MAX - 1)) { trace_break(pkt.rsz = -9); } pkt.asz = static_cast<int32_t>(req.sz); trace_info( TRACE_DBG_STR_0 ", req.sz = %u", pkt.rsz, pkt.asz, req.sz ); if (pkt.asz <= 0) { trace_break(pkt.rsz = -5); } if (pkt.rsz < 0) { trace_break(pkt.rsz = -7); } else if (pkt.rsz == 0) { trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } else if (pkt.rsz <= ADBSYNCDATA_SIZE) trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); pkt.rsz -= ADBSYNCDATA_SIZE; pkt.buff += ADBSYNCDATA_SIZE; trace_info( TRACE_DBG_STR_0 ", buffer offset = %d", pkt.rsz, pkt.asz, ADBSYNCDATA_SIZE ); trace_return(DriverNet::SyncTagType::SYNC_TAG_OKAY); } while (0); trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } DriverNet::SyncTagType DriverNet::parseData(SOCKET client, FILE *fpp, DriverNet::ADBSYNCPKT & pkt, bool isrecursive) { tracer(); DriverNet::ADBSYNCDATA req{}; DriverNet::SyncTagType type; if (!pkt.buff) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); if (pkt.rsz < ADBSYNCDATA_SIZE) type = DriverNet::SyncTagType::SYNC_TAG_NONE; else { req = SyncDataFromBuff(pkt.buff); type = trace_call(SyncDataType<DriverNet::ADBSYNCDATA>, req); } trace_info( "switch -> " TRACE_DBG_STR_0 ", case = %s", pkt.rsz, pkt.asz, enumtostring(type) ); switch (type) { case DriverNet::SyncTagType::SYNC_TAG_DATA: { if ((!isrecursive) && (!sendOkay(client))) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); type = trace_call(parseDataTag, pkt, req); if (type == DriverNet::SyncTagType::SYNC_TAG_OKAY) trace_break(0); trace_info( "warning: parseDataTag return (%s), no tagged", enumtostring(type) ); if (isrecursive) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); trace_return(type); } case DriverNet::SyncTagType::SYNC_TAG_DONE: { pkt.rsz = pkt.asz = 0; trace_return(DriverNet::SyncTagType::SYNC_TAG_END); } case DriverNet::SyncTagType::SYNC_TAG_NONE: { if (pkt.asz <= 0) { pkt.rsz = -6; trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } if (pkt.rsz < 0) { pkt.rsz = -9; trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } else if (pkt.rsz == 0) { trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); } break; } default: { trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } } trace_info( "switch -> " TRACE_DBG_STR_0 ", calc = %d", pkt.rsz, pkt.asz, (pkt.rsz - pkt.asz - ADBSYNCID_SIZE) ); if (pkt.rsz <= pkt.asz) { if (!receivedDataWrite(fpp, pkt)) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); trace_return(DriverNet::SyncTagType::SYNC_TAG_CONTINUE); } int32_t asz = pkt.asz, rsz = (pkt.rsz - asz); pkt.rsz = asz; if (!receivedDataWrite(fpp, pkt)) trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); if ((rsz - ADBSYNCDATA_SIZE) >= 0) { pkt.rsz = rsz; pkt.asz = rsz; pkt.buff += asz; /* /// Debug last block: std::string fname("__SyncFileReceive_bin_"); fname += std::to_string(cnt++); FILE __AUTO(__autofile) * fp = ::fopen(fname.c_str(), "ab+"); fwrite(pkt.buff, 1, pkt.rsz, fp); */ return trace_call(parseData, client, fpp, pkt, true); } trace_return(DriverNet::SyncTagType::SYNC_TAG_ERROR); } bool DriverNet::sendOkay(SOCKET client) { tracer(); DriverNet::ADBSYNCDATA req = SyncDataMake(DriverNet::SyncTagType::SYNC_TAG_OKAY, 0U); bool ret = (::send(client, (const char*)&req, sizeof(req), 0) == static_cast<int32_t>(sizeof(req))); trace_return(ret); } bool DriverNet::receiveErrors(DriverNet::ADBSYNCPKT & pkt, std::string & rs) { # if defined(_BUILD_WARNING_0) switch (pkt.rsz) { case -1: rs = DriverNet::GetNetError(__LINE__); break; case -2: rs.assign(DriverConst::ls_errorSFR2); break; case -3: rs.assign(DriverConst::ls_errorSFR3); break; case -4: rs.assign(DriverConst::ls_errorSFR4); break; case -5: rs.assign(DriverConst::ls_errorSFR5); break; case -6: rs.assign(DriverConst::ls_errorSFR6); break; case -7: rs.assign(DriverConst::ls_errorSFR7); break; case -8: rs.assign(DriverConst::ls_errorSFR8); break; case -9: rs.assign(DriverConst::ls_errorSFR9); break; case -10: rs.assign(DriverConst::ls_errorSFR10); break; case 0: { if (pkt.asz) rs.assign(DriverConst::ls_errorSFR00); else rs.assign(DriverConst::ls_errorSFR0); break; } } # endif return !((pkt.rsz < 0) || (pkt.asz)); } }
34.222841
121
0.479652
ClnViewer