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
109
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
48.5k
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
9f53d7d339f4508c9640959cb2f8cbcdc2df1d51
2,066
cpp
C++
libraries/chain/webassembly/mos-vm-oc.cpp
moschain/moschain-master
418531f281a8a1fb58621bb7f38ad3202edce46f
[ "MIT" ]
null
null
null
libraries/chain/webassembly/mos-vm-oc.cpp
moschain/moschain-master
418531f281a8a1fb58621bb7f38ad3202edce46f
[ "MIT" ]
null
null
null
libraries/chain/webassembly/mos-vm-oc.cpp
moschain/moschain-master
418531f281a8a1fb58621bb7f38ad3202edce46f
[ "MIT" ]
null
null
null
#include <mos/chain/webassembly/mos-vm-oc.hpp> #include <mos/chain/wasm_mos_constraints.hpp> #include <mos/chain/wasm_mos_injection.hpp> #include <mos/chain/apply_context.hpp> #include <mos/chain/exceptions.hpp> #include <vector> #include <iterator> namespace mos { namespace chain { namespace webassembly { namespace mosvmoc { class mosvmoc_instantiated_module : public wasm_instantiated_module_interface { public: mosvmoc_instantiated_module(const digest_type& code_hash, const uint8_t& vm_version, mosvmoc_runtime& wr) : _code_hash(code_hash), _vm_version(vm_version), _mosvmoc_runtime(wr) { } ~mosvmoc_instantiated_module() { _mosvmoc_runtime.cc.free_code(_code_hash, _vm_version); } void apply(apply_context& context) override { const code_descriptor* const cd = _mosvmoc_runtime.cc.get_descriptor_for_code_sync(_code_hash, _vm_version); MOS_ASSERT(cd, wasm_execution_error, "MOS VM OC instantiation failed"); _mosvmoc_runtime.exec.execute(*cd, _mosvmoc_runtime.mem, context); } const digest_type _code_hash; const uint8_t _vm_version; mosvmoc_runtime& _mosvmoc_runtime; }; mosvmoc_runtime::mosvmoc_runtime(const boost::filesystem::path data_dir, const mosvmoc::config& mosvmoc_config, const chainbase::database& db) : cc(data_dir, mosvmoc_config, db), exec(cc) { } mosvmoc_runtime::~mosvmoc_runtime() { } std::unique_ptr<wasm_instantiated_module_interface> mosvmoc_runtime::instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t> initial_memory, const digest_type& code_hash, const uint8_t& vm_type, const uint8_t& vm_version) { return std::make_unique<mosvmoc_instantiated_module>(code_hash, vm_type, *this); } //never called. MOS VM OC overrides eosio_exit to its own implementation void mosvmoc_runtime::immediately_exit_currently_running_module() {} }}}}
37.563636
167
0.707164
moschain
9f5627660d1ac41bcdd6b017984e6a090b0a579c
1,178
hpp
C++
include/argot/conc/expand/expansion_operator.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
49
2018-05-09T23:17:45.000Z
2021-07-21T10:05:19.000Z
include/argot/conc/expand/expansion_operator.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
null
null
null
include/argot/conc/expand/expansion_operator.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
2
2019-08-04T03:51:36.000Z
2020-12-28T06:53:29.000Z
/*============================================================================== Copyright (c) 2018 Matt Calabrese Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef ARGOT_CONC_EXPAND_EXPANSION_OPERATOR_HPP_ #define ARGOT_CONC_EXPAND_EXPANSION_OPERATOR_HPP_ #include <argot/concepts/concurrent_expandable.hpp> #include <argot/detail/forward.hpp> #include <argot/gen/access_raw_concept_map.hpp> #include <argot/gen/requires.hpp> namespace argot { namespace concurrent_expansion_operator { template< class Exp , ARGOT_REQUIRES( ConcurrentExpandable< Exp&& > )() > [[nodiscard]] constexpr auto operator ~( Exp&& exp ) { return access_raw_concept_map< ConcurrentExpandable< Exp&& > > ::expand( ARGOT_FORWARD( Exp )( exp ) ); } } // namespace argot(::concurrent_expansion_operator) namespace operators { using concurrent_expansion_operator::operator ~; } // namespace argot(::operators) } // namespace argot #endif // ARGOT_CONC_EXPAND_EXPANSION_OPERATOR_HPP_
30.205128
80
0.662139
mattcalabrese
9f56818db0dda76c839b0c53a9b7698665ac279c
82
cpp
C++
_WinMain/GameObject.cpp
SinJunghyeon/Battle-City
6e1427f6ea939e48ef3da65789d40372c005a8fb
[ "MIT" ]
null
null
null
_WinMain/GameObject.cpp
SinJunghyeon/Battle-City
6e1427f6ea939e48ef3da65789d40372c005a8fb
[ "MIT" ]
null
null
null
_WinMain/GameObject.cpp
SinJunghyeon/Battle-City
6e1427f6ea939e48ef3da65789d40372c005a8fb
[ "MIT" ]
null
null
null
#include "GameObject.h" void GameObject::Move() { } GameObject::GameObject() { }
9.111111
24
0.682927
SinJunghyeon
9f56f0487f8ab67087ec4f1436670af39c32c34c
5,466
cpp
C++
RVAF-GUI/teechart/gaugepointerrange.cpp
YangQun1/RVAF-GUI
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
[ "BSD-2-Clause" ]
4
2018-03-31T10:45:19.000Z
2021-10-09T02:57:13.000Z
RVAF-GUI/teechart/gaugepointerrange.cpp
P-Chao/RVAF-GUI
3bbeed7d2ffa400f754f095e7c08400f701813d4
[ "BSD-2-Clause" ]
1
2018-04-22T05:12:36.000Z
2018-04-22T05:12:36.000Z
RVAF-GUI/teechart/gaugepointerrange.cpp
YangQun1/RVAF-GUI
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
[ "BSD-2-Clause" ]
5
2018-01-13T15:57:14.000Z
2019-11-12T03:23:18.000Z
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "gaugepointerrange.h" // Dispatch interfaces referenced by this interface #include "brush.h" #include "pen.h" #include "gradient.h" #include "teeshadow.h" ///////////////////////////////////////////////////////////////////////////// // CGaugePointerRange properties ///////////////////////////////////////////////////////////////////////////// // CGaugePointerRange operations CBrush1 CGaugePointerRange::GetBrush() { LPDISPATCH pDispatch; InvokeHelper(0x60020000, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CBrush1(pDispatch); } BOOL CGaugePointerRange::GetDraw3D() { BOOL result; InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CGaugePointerRange::SetDraw3D(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } long CGaugePointerRange::GetHorizontalSize() { long result; InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CGaugePointerRange::SetHorizontalSize(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } long CGaugePointerRange::GetVerticalSize() { long result; InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CGaugePointerRange::SetVerticalSize(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } BOOL CGaugePointerRange::GetInflateMargins() { BOOL result; InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CGaugePointerRange::SetInflateMargins(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } CPen1 CGaugePointerRange::GetPen() { LPDISPATCH pDispatch; InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CPen1(pDispatch); } long CGaugePointerRange::GetStyle() { long result; InvokeHelper(0x7, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CGaugePointerRange::SetStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x7, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } BOOL CGaugePointerRange::GetVisible() { BOOL result; InvokeHelper(0x8, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CGaugePointerRange::SetVisible(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } BOOL CGaugePointerRange::GetDark3D() { BOOL result; InvokeHelper(0x49, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL); return result; } void CGaugePointerRange::SetDark3D(BOOL bNewValue) { static BYTE parms[] = VTS_BOOL; InvokeHelper(0x49, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, bNewValue); } void CGaugePointerRange::DrawPointer(long DC, BOOL Is3D, long px, long py, long tmpHoriz, long tmpVert, unsigned long AColor, long AStyle) { static BYTE parms[] = VTS_I4 VTS_BOOL VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4 VTS_I4; InvokeHelper(0x9, DISPATCH_METHOD, VT_EMPTY, NULL, parms, DC, Is3D, px, py, tmpHoriz, tmpVert, AColor, AStyle); } CGradient CGaugePointerRange::GetGradient() { LPDISPATCH pDispatch; InvokeHelper(0x835, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CGradient(pDispatch); } long CGaugePointerRange::GetTransparency() { long result; InvokeHelper(0x231e, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CGaugePointerRange::SetTransparency(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x231e, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } CTeeShadow CGaugePointerRange::GetShadow() { LPDISPATCH pDispatch; InvokeHelper(0x270f, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL); return CTeeShadow(pDispatch); } long CGaugePointerRange::GetGaugeStyle() { long result; InvokeHelper(0x12d, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } void CGaugePointerRange::SetGaugeStyle(long nNewValue) { static BYTE parms[] = VTS_I4; InvokeHelper(0x12d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); } double CGaugePointerRange::GetEndValue() { double result; InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); return result; } void CGaugePointerRange::SetEndValue(double newValue) { static BYTE parms[] = VTS_R8; InvokeHelper(0xc9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); } double CGaugePointerRange::GetStartValue() { double result; InvokeHelper(0xca, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL); return result; } void CGaugePointerRange::SetStartValue(double newValue) { static BYTE parms[] = VTS_R8; InvokeHelper(0xca, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue); }
24.511211
139
0.709294
YangQun1
9f5f1cb969f3b4ad35874559a61e2fa45120f3d5
935
cpp
C++
tu/game_1.cpp
eoserv/mainclone-eoserv
e18e87f169140b6c0da80b9d866f672e8f6dced5
[ "Zlib" ]
2
2020-01-14T10:44:21.000Z
2020-01-15T08:01:55.000Z
tu/game_1.cpp
eoserv/mainclone-eoserv
e18e87f169140b6c0da80b9d866f672e8f6dced5
[ "Zlib" ]
null
null
null
tu/game_1.cpp
eoserv/mainclone-eoserv
e18e87f169140b6c0da80b9d866f672e8f6dced5
[ "Zlib" ]
null
null
null
/* $Id$ * EOSERV is released under the zlib license. * See LICENSE.txt for more info. */ #include "../src/character.cpp" #include "../src/command_source.cpp" #include "../src/map.cpp" #include "../src/npc.cpp" #include "../src/npc_ai.cpp" #include "../src/npc_data.cpp" #include "../src/party.cpp" #include "../src/player.cpp" #include "../src/world.cpp" #include "../src/npc_ai/npc_ai_magic.cpp" #include "../src/npc_ai/npc_ai_ranged.cpp" #include "../src/npc_ai/npc_ai_hw2016_apozen.cpp" #include "../src/npc_ai/npc_ai_hw2016_apozenskull.cpp" #include "../src/npc_ai/npc_ai_hw2016_banshee.cpp" #include "../src/npc_ai/npc_ai_hw2016_crane.cpp" #include "../src/npc_ai/npc_ai_hw2016_cursed_mask.cpp" #include "../src/npc_ai/npc_ai_hw2016_dark_magician.cpp" #include "../src/npc_ai/npc_ai_hw2016_inferno_grenade.cpp" #include "../src/npc_ai/npc_ai_hw2016_skeleton_warlock.cpp" #include "../src/npc_ai/npc_ai_hw2016_tentacle.cpp"
32.241379
59
0.736898
eoserv
9f61b4015d2b5d53db52124b775dc5ef2b6f1102
8,947
cpp
C++
libs/besiq/correct.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
1
2015-10-21T14:22:12.000Z
2015-10-21T14:22:12.000Z
libs/besiq/correct.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2019-05-26T20:52:31.000Z
2019-05-28T16:19:49.000Z
libs/besiq/correct.cpp
hoehleatsu/besiq
94959e2819251805e19311ce377919e6bccb7bf9
[ "BSD-3-Clause" ]
2
2016-11-06T14:58:37.000Z
2019-05-26T14:03:13.000Z
#include <algorithm> #include <iostream> #include <glm/models/binomial.hpp> #include <besiq/io/resultfile.hpp> #include <besiq/io/metaresult.hpp> #include <besiq/method/scaleinv_method.hpp> #include <besiq/correct.hpp> struct heap_result { std::pair<std::string, std::string> variant_pair; float pvalue; bool operator<(const heap_result &other) const { return other.pvalue > pvalue; } }; void run_top(metaresultfile *result, float alpha, uint64_t num_top, size_t column, const std::string &output_path) { std::ostream &output = std::cout; std::vector<std::string> header = result->get_header( ); output << "snp1 snp2\tP\n"; std::vector<heap_result> heap; std::make_heap( heap.begin( ), heap.end( ) ); std::pair<std::string, std::string> pair; float *values = new float[ header.size( ) ]; float cur_min = FLT_MAX; while( result->read( &pair, values ) ) { heap_result res; res.pvalue = values[ column ]; if( res.pvalue == result_get_missing( ) || res.pvalue > cur_min ) { continue; } res.variant_pair = pair; heap.push_back( res ); std::push_heap( heap.begin( ), heap.end( ) ); if( heap.size( ) > num_top ) { std::pop_heap( heap.begin( ), heap.end( ) ); float new_min = heap.back( ).pvalue; heap.pop_back( ); cur_min = std::min( cur_min, new_min ); } } std::sort_heap( heap.begin( ), heap.end( ) ); for(int i = 0; i < heap.size( ); i++) { output << heap[ i ].variant_pair.first << " " << heap[ i ].variant_pair.second; output << "\t" << heap[ i ].pvalue << "\n"; } } void run_bonferroni(metaresultfile *result, float alpha, uint64_t num_tests, size_t column, const std::string &output_path) { if( num_tests == 0 ) { num_tests = result->num_pairs( ); } std::ostream &output = std::cout; std::vector<std::string> header = result->get_header( ); output << "snp1 snp2"; for(int i = 0; i < header.size( ); i++) { output << "\t" << header[ i ]; } output << "\tP_adjusted\n"; std::pair<std::string, std::string> pair; float *values = new float[ header.size( ) ]; while( result->read( &pair, values ) ) { float p = values[ column ]; if( p == result_get_missing( ) ) { continue; } float adjusted_p = std::min( p * num_tests, 1.0f ); if( adjusted_p <= alpha ) { output << pair.first << " " << pair.second; for(int i = 0; i < header.size( ); i++) { output << "\t" << values[ i ]; } output << "\t" << adjusted_p << "\n"; } } } resultfile * do_common_stages(metaresultfile *result, const std::vector<std::string> &snp_names, const correction_options &options, const std::string &output_path) { float *values = new float[ result->get_header( ).size( ) ]; char const *levels[] = { "1", "2", "3", "4" }; std::string filename = output_path + std::string( ".level" ) + levels[ 0 ]; bresultfile *stage_file = new bresultfile( filename, snp_names ); if( stage_file == NULL || !stage_file->open( ) ) { return NULL; } stage_file->set_header( result->get_header( ) ); std::vector<uint64_t> num_tests( options.num_tests ); if( num_tests[ 0 ] == 0 ) { num_tests[ 0 ] = result->num_pairs( ); } std::pair<std::string, std::string> pair; while( result->read( &pair, values ) ) { if( values[ 0 ] == result_get_missing( ) ) { continue; } float adjusted = std::min( 1.0f, values[ 0 ] * num_tests[ 0 ] / options.weight[ 0 ] ); if( adjusted <= options.alpha ) { values[ 0 ] = adjusted; stage_file->write( pair, values ); } } delete stage_file; for(int i = 1; i < 3; i++) { bresultfile *prev_file = new bresultfile( filename ); if( prev_file == NULL || !prev_file->open( ) ) { return NULL; } filename = output_path + std::string( ".level" ) + levels[ i ]; stage_file = new bresultfile( filename, snp_names ); if( stage_file == NULL || !stage_file->open( ) ) { return NULL; } stage_file->set_header( result->get_header( ) ); if( num_tests[ i ] == 0 ) { num_tests[ i ] = prev_file->num_pairs( ); } while( prev_file->read( &pair, values ) ) { if( values[ i ] == result_get_missing( ) ) { continue; } float adjusted = std::min( values[ i ] * num_tests[ i ] / options.weight[ i ], 1.0f ); if( adjusted <= options.alpha ) { values[ i ] = adjusted; stage_file->write( pair, values ); } } delete stage_file; delete prev_file; } delete values; bresultfile *last_stage = new bresultfile( filename ); if( last_stage != NULL && last_stage->open( ) ) { return last_stage; } else { return NULL; } } void do_last_stage(resultfile *last_stage, const correction_options &options, genotype_matrix_ptr genotypes, method_data_ptr data, const std::string &output_path) { std::ostream &output = std::cout; std::vector<std::string> header = last_stage->get_header( ); model_matrix *model_matrix = new factor_matrix( data->covariate_matrix, data->phenotype.n_elem ); scaleinv_method method( data, *model_matrix, options.model == "normal" ); std::vector<std::string> method_header = method.init( ); output << "snp1 snp2"; for(int i = 0; i < method_header.size( ); i++) { output << "\tP_" << method_header[ i ]; } output << "\tP_combined\n"; uint64_t num_tests = options.num_tests[ 3 ]; if( num_tests == 0 ) { num_tests = last_stage->num_pairs( ); } std::pair<std::string, std::string> pair; float *values = new float[ header.size( ) ]; float *method_values = new float[ method_header.size( ) ]; while( last_stage->read( &pair, values ) ) { std::fill( method_values, method_values + method_header.size( ), result_get_missing( ) ); /* Skip N and last p-value */ float pre_p = *std::max_element( values, values + header.size( ) - 2 ); float min_p = 1.0; float max_p = 0.0; snp_row const *snp1 = genotypes->get_row( pair.first ); snp_row const *snp2 = genotypes->get_row( pair.second ); method.run( *snp1, *snp2, method_values ); std::vector<float> p_values; for(int i = 0; i < method_header.size( ); i++) { float adjusted_p = result_get_missing( ); if( method_values[ i ] != result_get_missing( ) ) { adjusted_p = std::min( std::max( method_values[ i ] * num_tests / options.weight[ header.size( ) - 2 ], pre_p ), 1.0f ); min_p = std::min( min_p, adjusted_p ); max_p = std::max( max_p, adjusted_p ); } p_values.push_back( adjusted_p ); } if( min_p > options.alpha ) { continue; } output << pair.first << " " << pair.second; bool any_missing = false; for(int i = 0; i < p_values.size( ); i++) { if( p_values[ i ] != result_get_missing( ) ) { output << "\t" << p_values[ i ]; } else { any_missing = true; output << "\tNA"; } } if( !any_missing ) { output << "\t" << max_p << "\n"; } else { output << "\tNA\n"; } } delete model_matrix; delete[] values; delete[] method_values; } void run_static(metaresultfile *result, genotype_matrix_ptr genotypes, method_data_ptr data, const correction_options &options, const std::string &output_path) { resultfile *last_stage = do_common_stages( result, genotypes->get_snp_names( ), options, output_path ); if( last_stage == NULL ) { return; } do_last_stage( last_stage, options, genotypes, data, output_path ); delete last_stage; } void run_adaptive(metaresultfile *result, genotype_matrix_ptr genotypes, method_data_ptr data, const correction_options &options, const std::string &output_path) { correction_options adaptive_options( options ); for(int i = 0; i < adaptive_options.num_tests.size( ); i++) { adaptive_options.num_tests[ i ] = 0; } run_static( result, genotypes, data, adaptive_options, output_path ); }
29.048701
157
0.545546
hoehleatsu
9f62e3b68cf61d15204f5a94461f72a8bf4bfaab
9,863
cpp
C++
threepp/renderers/gl/SpriteRenderer.cpp
Graphics-Physics-Libraries/three.cpp-imported
788b4202e15fa245a4b60e2da0b91f7d4d0592e1
[ "MIT" ]
76
2017-12-20T05:09:04.000Z
2022-01-24T10:20:15.000Z
threepp/renderers/gl/SpriteRenderer.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
5
2018-06-06T15:41:01.000Z
2019-11-30T15:10:25.000Z
threepp/renderers/gl/SpriteRenderer.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
23
2017-10-12T16:46:33.000Z
2022-03-16T06:16:03.000Z
// // Created by byter on 22.10.17. // #include "SpriteRenderer.h" #include <algorithm> #include <array> #include <sstream> #include "Renderer_impl.h" namespace three { namespace gl { using namespace std; struct SpriteRendererData { GLint position_att; GLint uv_att; GLint projectionMatrix; GLint map; GLint opacity; GLint color; GLint scale; GLint rotation; GLint uvOffset; GLint uvScale; GLint modelViewMatrix; GLint fogType, fogDensity, fogNear, fogFar, fogColor, fogDepth; GLint alphaTest; SpriteRendererData(QOpenGLFunctions *f, GLuint program) { position_att = f->glGetAttribLocation(program, "position"); uv_att = f->glGetAttribLocation(program, "uv"); uvOffset = f->glGetUniformLocation(program, "uvOffset"); uvScale = f->glGetUniformLocation(program, "uvScale"); rotation = f->glGetUniformLocation(program, "rotation"); scale = f->glGetUniformLocation(program, "scale"); color = f->glGetUniformLocation(program, "color"); map = f->glGetUniformLocation(program, "map"); opacity = f->glGetUniformLocation(program, "opacity"); modelViewMatrix = f->glGetUniformLocation(program, "modelViewMatrix"); projectionMatrix = f->glGetUniformLocation(program, "projectionMatrix"); fogType = f->glGetUniformLocation(program, "fogType"); fogDensity = f->glGetUniformLocation(program, "fogDensity"); fogNear = f->glGetUniformLocation(program, "fogNear"); fogFar = f->glGetUniformLocation(program, "fogFar"); fogColor = f->glGetUniformLocation(program, "fogColor"); fogDepth = f->glGetUniformLocation(program, "fogDepth"); alphaTest = f->glGetUniformLocation(program, "alphaTest"); } }; SpriteRenderer::~SpriteRenderer() { if(_data) delete _data; } void SpriteRenderer::init() { array<float, 16> vertices = { -0.5f, -0.5f, 0, 0, 0.5f, -0.5f, 1, 0, 0.5f, 0.5f, 1, 1, -0.5f, 0.5f, 0, 1 }; array<uint16_t, 6> faces = { 0, 1, 2, 0, 2, 3 }; _r.glGenBuffers(1, &_vertexBuffer); _r.glGenBuffers(1, &_elementBuffer); _r.glBindBuffer( GL_ARRAY_BUFFER, _vertexBuffer ); _r.glBufferData( GL_ARRAY_BUFFER, 16 * sizeof(float), vertices.data(), GL_STATIC_DRAW ); _r.glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _elementBuffer ); _r.glBufferData( GL_ELEMENT_ARRAY_BUFFER, 12, faces.data(), GL_STATIC_DRAW ); GLuint vshader = _r.glCreateShader( GL_VERTEX_SHADER ); GLuint fshader = _r.glCreateShader( GL_FRAGMENT_SHADER ); static const char * vertexShader = "#define SHADER_NAME SpriteMaterial" "uniform mat4 modelViewMatrix;" "uniform mat4 projectionMatrix;" "uniform float rotation;" "uniform vec2 scale;" "uniform vec2 uvOffset;" "uniform vec2 uvScale;" "in vec2 position;" "in vec2 uv;" "out vec2 vUV;" "out float fogDepth;" "void main() {" " vUV = uvOffset + uv * uvScale;" " vec2 alignedPosition = position * scale;" " vec2 rotatedPosition;" " rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;" " rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;" " vec4 mvPosition;" " mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );" " mvPosition.xy += rotatedPosition;" " gl_Position = projectionMatrix * mvPosition;" " fogDepth = - mvPosition.z;" "}"; stringstream ss; ss << "precision " << _capabilities.precisionS() << " float;" << endl << vertexShader; const char *vsource = ss.str().data(); _r.glShaderSource(vshader, 1, &vsource, nullptr); static const char * fragmentShader = "#define SHADER_NAME SpriteMaterial" "uniform vec3 color;" "uniform sampler2D map;" "uniform float opacity;" "uniform int fogType;" "uniform vec3 fogColor;" "uniform float fogDensity;" "uniform float fogNear;" "uniform float fogFar;" "uniform float alphaTest;" "in vec2 vUV;" "in float fogDepth;" "out vec4 fragColor;" "void main() {" " vec4 texture = texture( map, vUV );" " fragColor = vec4( color * texture.xyz, texture.a * opacity );" " if ( fragColor.a < alphaTest ) discard;" " if ( fogType > 0 ) {" " float fogFactor = 0.0;" " if ( fogType == 1 ) {" " fogFactor = smoothstep( fogNear, fogFar, fogDepth );" " } else {" " const float LOG2 = 1.442695;" " fogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );" " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );" " }" " fragColor.rgb = mix( fragColor.rgb, fogColor, fogFactor );" " }" "}"; ss.clear(); ss << "precision " << _capabilities.precisionS() << " float;" << endl << fragmentShader; const char *fsource = ss.str().data(); _r.glShaderSource(fshader, 1, &fsource, nullptr); _r.glCompileShader(vshader); _r.glCompileShader(fshader); _r.glAttachShader( _program, vshader ); _r.glAttachShader( _program, fshader ); _r.glLinkProgram( _program ); /*var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); canvas.width = 8; canvas.height = 8; var context = canvas.getContext( '2d' ); context.fillStyle = 'white'; context.fillRect( 0, 0, 8, 8 ); texture = new CanvasTexture( canvas );*/ } void SpriteRenderer::render(vector<Sprite::Ptr> &sprites, Scene::Ptr scene, Camera::Ptr camera) { if (sprites.empty()) return; // setup gl if (!_linked) { init(); _linked = true; } _state.useProgram(_program); _state.initAttributes(); _state.enableAttribute( _data->position_att ); _state.enableAttribute( _data->uv_att ); _state.disableUnusedAttributes(); _state.disable( GL_CULL_FACE ); _state.enable( GL_BLEND ); _r.glBindBuffer( GL_ARRAY_BUFFER, _vertexBuffer ); _r.glVertexAttribPointer( _data->position_att, 2, GL_FLOAT, GL_FALSE, 2 * 8, (const void *)0 ); _r.glVertexAttribPointer( _data->uv_att, 2, GL_FLOAT, GL_FALSE, 2 * 8, (const void *)8 ); _r.glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, _elementBuffer ); _r.glUniformMatrix4fv(_data->projectionMatrix, sizeof(camera->projectionMatrix()), GL_FALSE, camera->projectionMatrix().elements()); _state.activeTexture( GL_TEXTURE0 ); _r.glUniform1i( _data->map, 0 ); GLint oldFogType = 0; GLint sceneFogType = 0; Fog::Ptr fog = scene->fog(); if ( fog ) { _r.glUniform3f( _data->fogColor, fog->color().r, fog->color().g, fog->color().b ); if(CAST(fog, f, DefaultFog)) { _r.glUniform1f( _data->fogNear, f->near() ); _r.glUniform1f( _data->fogFar, f->far() ); _r.glUniform1i( _data->fogType, 1 ); oldFogType = 1; sceneFogType = 1; } else if(CAST(fog, f, FogExp2)) { _r.glUniform1f( _data->fogDensity, f->density() ); _r.glUniform1i( _data->fogType, 2 ); oldFogType = 2; sceneFogType = 2; } } else { _r.glUniform1i( _data->fogType, 0 ); oldFogType = 0; sceneFogType = 0; } // update positions and sort for (const Sprite::Ptr sprite : sprites) { sprite->modelViewMatrix.multiply(camera->matrixWorldInverse(), sprite->matrixWorld()); //sprite->z() = - sprite.modelViewMatrix.elements[ 14 ]; } sort(sprites.begin(), sprites.end(), [] (const Sprite::Ptr &a, const Sprite::Ptr &b) -> bool { if ( a->renderOrder() != b->renderOrder()) { return a->renderOrder() < b->renderOrder(); } else { float za = a->modelViewMatrix.elements()[ 14 ]; float zb = b->modelViewMatrix.elements()[ 14 ]; if (za != zb) return zb < za; else return b->id() < a->id(); } }); // render all sprites float scale[2]; for (Sprite::Ptr sprite : sprites) { SpriteMaterial *material = sprite->material()->typer; if (!material->visible) continue; sprite->onBeforeRender.emitSignal(_r, scene, camera, *sprite, nullptr); _r.glUniform1f( _data->alphaTest, material->alphaTest ); _r.glUniformMatrix4fv(_data->modelViewMatrix, 1, GL_FALSE, sprite->modelViewMatrix.elements() ); sprite->matrixWorld().decompose( _spritePosition, _spriteRotation, _spriteScale ); scale[ 0 ] = _spriteScale.x(); scale[ 1 ] = _spriteScale.y(); GLint fogType = scene->fog() && material->fog ? sceneFogType : 0; if ( oldFogType != fogType ) { _r.glUniform1i( _data->fogType, fogType ); oldFogType = fogType; } if (material->map) { _r.glUniform2f( _data->uvOffset, material->map->offset().x(), material->map->offset().y()); _r.glUniform2f( _data->uvScale, material->map->repeat().x(), material->map->repeat().y()); } else { _r.glUniform2f( _data->uvOffset, 0, 0 ); _r.glUniform2f( _data->uvScale, 1, 1 ); } _r.glUniform1f( _data->opacity, material->opacity); _r.glUniform3f( _data->color, material->color.r, material->color.g, material->color.b ); _r.glUniform1f( _data->rotation, material->rotation ); _r.glUniform2fv(_data->scale, 1, scale); _state.setBlending( material->blending, material->blendEquation, material->blendSrc, material->blendDst, material->blendEquationAlpha, material->blendSrcAlpha, material->blendDstAlpha, material->premultipliedAlpha ); _state.depthBuffer.setTest( material->depthTest ); _state.depthBuffer.setMask( material->depthWrite ); _state.colorBuffer.setMask( material->colorWrite ); if(material->map) _textures.setTexture2D(material->map, 0); else if(_texture) _textures.setTexture2D( _texture, 0 ); _r.glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); sprite->onAfterRender.emitSignal( _r, scene, camera, *sprite, nullptr ); } // restore gl _state.enable( GL_CULL_FACE ); _state.reset(); } } }
27.021918
108
0.648484
Graphics-Physics-Libraries
9f6489be8a18135a225e571b433c0bcc38753a3b
7,936
cpp
C++
editor/gui/src/materialexplorer.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
editor/gui/src/materialexplorer.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
editor/gui/src/materialexplorer.cpp
lizardkinger/blacksun
0119948726d2a057c13d208044c7664a8348a1ea
[ "Linux-OpenIB" ]
null
null
null
/*************************************************************************** * Copyright (C) 2006 by The Hunter * * hunter@localhost * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "./include/materialexplorer.h" namespace BSGui { const unsigned long MaterialExplorer::materialEditorMagic = 112186UL; MaterialExplorer::MaterialExplorer(QWidget* parent) : QListWidget(parent) { materialManager = BSRenderer::MaterialManager::getInstance(); sceneManager = BSScene::SceneManager::getInstance(); connect(materialManager, SIGNAL(materialAdded(int)), this, SLOT(addMaterial(int))); connect(materialManager, SIGNAL(materialRemoved(int)), this, SLOT(removeMaterial(int))); connect(materialManager, SIGNAL(materialChanged(int)), this, SLOT(updateMaterial(int))); connect(this, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(setMaterialName(QListWidgetItem*))); int materialNumber = materialManager->getStandardMaterialID(); actionRenameCurrentItem = new QAction(tr("Rename"), this); actionDeleteCurrentItem = new QAction(tr("Delete"), this); actionEditCurrentItem = new QAction(tr("Edit"), this); actionApplyCurrentItem = new QAction(tr("Apply"), this); QListWidgetItem* itemToAdd = new QListWidgetItem; itemToAdd->setText(QString::fromStdString(materialManager->getMaterial(materialNumber)->getName())); itemToAdd->setData(Qt::UserRole, materialNumber); itemToAdd->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); addItem(itemToAdd); connect(actionDeleteCurrentItem, SIGNAL(triggered()), this, SLOT(deleteCurrentItem())); connect(actionRenameCurrentItem, SIGNAL(triggered()), this, SLOT(renameCurrentItem())); connect(actionEditCurrentItem, SIGNAL(triggered()), this, SLOT(editCurrentItem())); connect(actionApplyCurrentItem, SIGNAL(triggered()), this, SLOT(applyCurrentItem())); connect(&sceneManager->getSelBuffer(), SIGNAL(selectionChanged()), this, SLOT(setSelectedMaterial())); //connect(sceneManager, SIGNAL(sceneChanged()), this, SLOT(setSelectedMaterial())); } void MaterialExplorer::renameCurrentItem() { editItem(currentItem()); } void MaterialExplorer::deleteCurrentItem() { QListWidgetItem* item = currentItem(); int materialNumber = item->data(Qt::UserRole).toInt(); materialManager->removeMaterial(materialNumber); } void MaterialExplorer::applyCurrentItem() { QListWidgetItem* item = currentItem(); BSScene::SelectionBuffer* selectionBuffer = &BSScene::SceneManager::getInstance()->getSelBuffer(); selectionBuffer->setMaterial(item->data(Qt::UserRole).toInt()); setSelectedMaterial(); } void MaterialExplorer::editCurrentItem() { QObject* materialEditor = getMaterialEditorPlugin(); if(materialEditor != NULL) { QMetaObject::invokeMethod(materialEditor, "execute"); } } void MaterialExplorer::contextMenuEvent(QContextMenuEvent* event) { QObject* materialEditor = getMaterialEditorPlugin(); QListWidgetItem* item = itemAt(event->pos()); if(item != NULL) { QMenu* menu = new QMenu(this); menu->addAction(actionApplyCurrentItem); if(item->data(Qt::UserRole).toInt() != materialManager->getStandardMaterialID()) { menu->addAction(actionRenameCurrentItem); menu->addAction(actionDeleteCurrentItem); if(materialEditor != NULL) { menu->addAction(actionEditCurrentItem); } } menu->exec(event->globalPos()); } } void MaterialExplorer::addMaterial(int materialNumber) { for(int i = 0 ; i < count() ; i++) { if(item(i)->data(Qt::UserRole).toInt() == materialNumber) { return; } } QListWidgetItem* itemToAdd = new QListWidgetItem; itemToAdd->setText(QString::fromStdString(materialManager->getMaterial(materialNumber)->getName())); itemToAdd->setData(Qt::UserRole, materialNumber); itemToAdd->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); addItem(itemToAdd); } void MaterialExplorer::removeMaterial(int materialNumber) { delete findMaterial(materialNumber); } void MaterialExplorer::updateMaterial(int materialNumber) { QListWidgetItem* itemToUpdate = findMaterial(materialNumber); if(itemToUpdate != NULL) { findMaterial(materialNumber)->setText(QString::fromStdString(materialManager->getMaterial(materialNumber)->getName())); } } QListWidgetItem* MaterialExplorer::findMaterial(int materialNumber) { QListWidgetItem* itemToFind = NULL; for(int i = 0 ; i < count() ; i++) { itemToFind = item(i); if(itemToFind->data(Qt::UserRole).toInt() == materialNumber) { return itemToFind; } } return itemToFind; } void MaterialExplorer::setSelectedMaterial() { for(int i = 0 ; i < count() ; i++) { item(i)->setData(Qt::ForegroundRole, Qt::black); } BSScene::SelectionBuffer* selectionBuffer = &BSScene::SceneManager::getInstance()->getSelBuffer(); std::list<BSScene::SceneObject*> objectList = selectionBuffer->getSelectedObjects(); for(std::list<BSScene::SceneObject*>::iterator i = objectList.begin() ; i != objectList.end() ; ++i) { int currentId = (*i)->getMaterialID(); qDebug() << currentId; for(int i = 0 ; i < count() ; i++) { QListWidgetItem* current = item(i); if(current->data(Qt::UserRole).toInt() == currentId) { current->setData(Qt::ForegroundRole, Qt::blue); break; } } } } QObject* MaterialExplorer::getMaterialEditorPlugin() { QObject* materialManager = NULL; PlgInt* interface = BSPlgMgr::PlgMgr::getInstance()->getPlgInstance(materialEditorMagic,Version(1,0,0)); if(interface != NULL) { if(BSPlgMgr::PlgMgr::getInstance()->getStatus(materialEditorMagic)) { materialManager = dynamic_cast<QObject*>(interface); if(materialManager != NULL) { const QMetaObject* materialManagerMeta = materialManager->metaObject(); if(materialManagerMeta->indexOfMethod(QMetaObject::normalizedSignature("execute()")) > -1 ) { return materialManager; } } } } return NULL; } void MaterialExplorer::setMaterialName(QListWidgetItem* item) { int materialNumber = item->data(Qt::UserRole).toInt(); Material* materialToEdit = materialManager->getMaterial(materialNumber); materialToEdit->setName(item->data(Qt::DisplayRole).toString().toStdString()); } }
37.971292
127
0.62563
lizardkinger
9f6c95e21ec191d53dce4ce07a912fc811df04cc
25,502
cpp
C++
test/custom_types_Test.cpp
mbeckh/llamalog
0441f3c6ce8871a343186f5c9ca35e8df4e8d542
[ "Apache-2.0" ]
null
null
null
test/custom_types_Test.cpp
mbeckh/llamalog
0441f3c6ce8871a343186f5c9ca35e8df4e8d542
[ "Apache-2.0" ]
15
2020-06-11T22:43:54.000Z
2020-10-25T11:49:17.000Z
test/custom_types_Test.cpp
mbeckh/llamalog
0441f3c6ce8871a343186f5c9ca35e8df4e8d542
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Michael Beckh 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 "llamalog/custom_types.h" #include "llamalog/LogLine.h" #include <fmt/format.h> #include <gtest/gtest.h> #include <string> #include <type_traits> namespace llamalog::test { namespace t = testing; namespace { thread_local int g_instancesCreated; thread_local int g_destructorCalled; thread_local int g_copyConstructorCalled; thread_local int g_moveConstructorCalled; class custom_types_Test : public t::Test { protected: void SetUp() override { g_instancesCreated = 0; g_destructorCalled = 0; g_copyConstructorCalled = 0; g_moveConstructorCalled = 0; } }; class TriviallyCopyable final { public: explicit TriviallyCopyable(int value) : m_value(value) { // empty } TriviallyCopyable(const TriviallyCopyable&) = default; TriviallyCopyable(TriviallyCopyable&&) = default; ~TriviallyCopyable() = default; public: TriviallyCopyable& operator=(const TriviallyCopyable&) = default; TriviallyCopyable& operator=(TriviallyCopyable&&) = default; public: int GetInstanceNo() const { return m_instanceNo; } int GetValue() const { return m_value; } private: int m_instanceNo = ++g_instancesCreated; int m_value; }; static_assert(std::is_trivially_copyable_v<TriviallyCopyable>); class MoveConstructible final { public: explicit MoveConstructible(int value) : m_value(value) { // empty } MoveConstructible(const MoveConstructible& other) noexcept : m_value(other.m_value) { ++g_copyConstructorCalled; } MoveConstructible(MoveConstructible&& other) noexcept : m_value(other.m_value) { ++g_moveConstructorCalled; } ~MoveConstructible() { ++g_destructorCalled; } public: MoveConstructible& operator=(const MoveConstructible&) = delete; MoveConstructible& operator=(MoveConstructible&&) = delete; public: int GetInstanceNo() const { return m_instanceNo; } int GetValue() const { return m_value; } private: const int m_instanceNo = ++g_instancesCreated; int m_value; }; static_assert(!std::is_trivially_copyable_v<MoveConstructible>); static_assert(std::is_nothrow_move_constructible_v<MoveConstructible>); class CopyConstructible final { public: explicit CopyConstructible(int value) : m_value(value) { // empty } CopyConstructible(const CopyConstructible& other) noexcept : m_value(other.m_value) { ++g_copyConstructorCalled; } CopyConstructible(CopyConstructible&& other) = delete; ~CopyConstructible() { ++g_destructorCalled; } public: CopyConstructible& operator=(const CopyConstructible&) = delete; CopyConstructible& operator=(CopyConstructible&&) = delete; public: int GetInstanceNo() const { return m_instanceNo; } int GetValue() const { return m_value; } private: const int m_instanceNo = ++g_instancesCreated; int m_value; }; static_assert(!std::is_trivially_copyable_v<CopyConstructible>); static_assert(!std::is_nothrow_move_constructible_v<CopyConstructible>); static_assert(std::is_nothrow_copy_constructible_v<CopyConstructible>); } // namespace } // namespace llamalog::test template <> struct fmt::formatter<llamalog::test::TriviallyCopyable> { public: template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const llamalog::test::TriviallyCopyable& arg, FormatContext& ctx) { return format_to(ctx.out(), "T_{}_{}", arg.GetInstanceNo(), arg.GetValue()); } }; llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::TriviallyCopyable& arg) { return logLine.AddCustomArgument(arg); } llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::TriviallyCopyable* const arg) { return logLine.AddCustomArgument(arg); } template <> struct fmt::formatter<llamalog::test::MoveConstructible> { public: template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const llamalog::test::MoveConstructible& arg, FormatContext& ctx) { return format_to(ctx.out(), "M_{}_{}", arg.GetInstanceNo(), arg.GetValue()); } }; llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::MoveConstructible& arg) { return logLine.AddCustomArgument(arg); } llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::MoveConstructible* const arg) { return logLine.AddCustomArgument(arg); } template <> struct fmt::formatter<llamalog::test::CopyConstructible> { public: template <typename ParseContext> constexpr auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const llamalog::test::CopyConstructible& arg, FormatContext& ctx) { return format_to(ctx.out(), "C_{}_{}", arg.GetInstanceNo(), arg.GetValue()); } }; llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::CopyConstructible& arg) { return logLine.AddCustomArgument(arg); } llamalog::LogLine& operator<<(llamalog::LogLine& logLine, const llamalog::test::CopyConstructible* const arg) { return logLine.AddCustomArgument(arg); } namespace llamalog::test { namespace { LogLine GetLogLine(const char* const pattern = "{}") { return LogLine(Priority::kDebug, "file.cpp", 99, "myfunction()", pattern); } } // namespace // // TriviallyCopyable // TEST_F(custom_types_Test, TriviallyCopyable_IsValue_PrintValue) { { LogLine logLine = GetLogLine(); { const TriviallyCopyable arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); logLine << arg; EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); const std::string str = logLine.GetLogMessage(); // everything is just copied as raw binary data EXPECT_EQ("T_1_7", str); EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); } TEST_F(custom_types_Test, TriviallyCopyable_IsValueWithCustomFormat_ThrowError) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const TriviallyCopyable arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); logLine << arg; EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); #pragma warning(suppress : 4834) EXPECT_THROW(logLine.GetLogMessage(), fmt::format_error); EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); } TEST_F(custom_types_Test, TriviallyCopyable_IsPointer_PrintValue) { { LogLine logLine = GetLogLine(); { const TriviallyCopyable value(7); const TriviallyCopyable* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); logLine << arg; EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); const std::string str = logLine.GetLogMessage(); // everything is just copied as raw binary data EXPECT_EQ("T_1_7", str); EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); } TEST_F(custom_types_Test, TriviallyCopyable_IsPointerWithCustomFormat_PrintValue) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const TriviallyCopyable value(7); const TriviallyCopyable* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); logLine << arg; EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); const std::string str = logLine.GetLogMessage(); // everything is just copied as raw binary data EXPECT_EQ("T_1_7", str); EXPECT_EQ(1, g_instancesCreated); } EXPECT_EQ(1, g_instancesCreated); } TEST_F(custom_types_Test, TriviallyCopyable_IsNullptr_PrintNull) { { LogLine logLine = GetLogLine(); { const TriviallyCopyable* const arg = nullptr; ASSERT_EQ(0, g_instancesCreated); logLine << arg; EXPECT_EQ(0, g_instancesCreated); } EXPECT_EQ(0, g_instancesCreated); const std::string str = logLine.GetLogMessage(); // everything is just copied as raw binary data EXPECT_EQ("(null)", str); EXPECT_EQ(0, g_instancesCreated); } EXPECT_EQ(0, g_instancesCreated); } TEST_F(custom_types_Test, TriviallyCopyable_IsNullptrWithCustomFormat_PrintNull) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const TriviallyCopyable* const arg = nullptr; ASSERT_EQ(0, g_instancesCreated); logLine << arg; EXPECT_EQ(0, g_instancesCreated); } EXPECT_EQ(0, g_instancesCreated); const std::string str = logLine.GetLogMessage(); // everything is just copied as raw binary data EXPECT_EQ("nullptr", str); EXPECT_EQ(0, g_instancesCreated); } EXPECT_EQ(0, g_instancesCreated); } // // MoveConstructible // TEST_F(custom_types_Test, MoveConstructible_IsValue_PrintValue) { { LogLine logLine = GetLogLine(); { const MoveConstructible arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("M_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, MoveConstructible_IsValueWithCustomFormat_ThrowError) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const MoveConstructible arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); #pragma warning(suppress : 4834) EXPECT_THROW(logLine.GetLogMessage(), fmt::format_error); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, MoveConstructible_IsPointer_PrintValue) { { LogLine logLine = GetLogLine(); { const MoveConstructible value(7); const MoveConstructible* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("M_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, MoveConstructible_IsPointerWithCustomFormat_PrintValue) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const MoveConstructible value(7); const MoveConstructible* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("M_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(1, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, MoveConstructible_IsNullptr_PrintNull) { { LogLine logLine = GetLogLine(); { const MoveConstructible* const arg = nullptr; ASSERT_EQ(0, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("(null)", str); // no need to print string of x'es EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } TEST_F(custom_types_Test, MoveConstructible_IsNullptrWithCustomFormat_PrintNull) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const MoveConstructible* const arg = nullptr; ASSERT_EQ(0, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("nullptr", str); // no need to print string of x'es EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } // // CopyConstructible // TEST_F(custom_types_Test, CopyConstructible_IsValue_PrintValue) { { LogLine logLine = GetLogLine(); { const CopyConstructible arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("C_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, CopyConstructible_IsValueWithCustomFormat_ThrowError) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const CopyConstructible arg(7); ASSERT_EQ(1, arg.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); #pragma warning(suppress : 4834) EXPECT_THROW(logLine.GetLogMessage(), fmt::format_error); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, CopyConstructible_IsPointer_PrintValue) { { LogLine logLine = GetLogLine(); { const CopyConstructible value(7); const CopyConstructible* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("C_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, CopyConstructible_IsPointerWithCustomFormat_PrintValue) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const CopyConstructible value(7); const CopyConstructible* const arg = &value; ASSERT_EQ(1, value.GetInstanceNo()); ASSERT_EQ(1, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(2, g_instancesCreated); EXPECT_EQ(1, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(1, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("C_3_7", str); // no need to print string of x'es EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(2, g_destructorCalled); } EXPECT_EQ(3, g_instancesCreated); EXPECT_EQ(2, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(3, g_destructorCalled); } TEST_F(custom_types_Test, CopyConstructible_IsNullptr_PrintNull) { { LogLine logLine = GetLogLine(); { const CopyConstructible* arg = nullptr; ASSERT_EQ(0, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("(null)", str); // no need to print string of x'es EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } TEST_F(custom_types_Test, CopyConstructible_IsNullptrWithCustomFormat_PrintNull) { { LogLine logLine = GetLogLine("{:?nullptr}"); { const CopyConstructible* arg = nullptr; ASSERT_EQ(0, g_instancesCreated); ASSERT_EQ(0, g_copyConstructorCalled); ASSERT_EQ(0, g_moveConstructorCalled); ASSERT_EQ(0, g_destructorCalled); logLine << arg; EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); // force an internal buffer re-allocation logLine << std::string(256, 'x'); EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); const std::string str = logLine.GetLogMessage(); EXPECT_EQ("nullptr", str); // no need to print string of x'es EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } EXPECT_EQ(0, g_instancesCreated); EXPECT_EQ(0, g_copyConstructorCalled); EXPECT_EQ(0, g_moveConstructorCalled); EXPECT_EQ(0, g_destructorCalled); } } // namespace llamalog::test
29.078677
111
0.751549
mbeckh
9f6ef8242a0a780ac9eba841cb7f4307d495fcf5
826
cpp
C++
landscaper/src/physics.cpp
llGuy/landscaper
7b9874c73bd7f5f07a340b9043fdeace032b6c49
[ "MIT" ]
null
null
null
landscaper/src/physics.cpp
llGuy/landscaper
7b9874c73bd7f5f07a340b9043fdeace032b6c49
[ "MIT" ]
null
null
null
landscaper/src/physics.cpp
llGuy/landscaper
7b9874c73bd7f5f07a340b9043fdeace032b6c49
[ "MIT" ]
null
null
null
#include "physics.h" #include "detail.h" physics_handler::physics_handler(void) : gravity_at_sea(-10.5f) { } //auto physics_handler::move(entity & ent, action a, f32 td) -> void //{ /*using detail::up; ent.momentum = glm::vec3(0.0f); glm::vec3 lateral_dir = { ent.direction.x, 0, ent.direction.z }; switch (a) { case action::forward: { ent.momentum = glm::normalize(lateral_dir); break; } case action::back: { ent.momentum = glm::normalize(-lateral_dir); break; } case action::up: { ent.momentum = up; break; } case action::down: { ent.momentum = -up; break; } case action::left: { ent.momentum = glm::normalize(-glm::cross(lateral_dir, up)); break; } case action::right: { ent.momentum = glm::normalize(glm::cross(lateral_dir, up)); break; } } ent.position += ent.momentum * ent.speed * 20.0f * td;*/ //}
28.482759
91
0.664649
llGuy
9f7158aa0fcab43d6d2482e15e7f841fc5ebbafc
619
cpp
C++
src/scene/encounter/encounter.cpp
selcia-eremeev/chen
96a2f4fbe444b26668983fb4c3f360d1a22cd2f7
[ "MIT" ]
1
2021-03-22T16:03:24.000Z
2021-03-22T16:03:24.000Z
src/scene/encounter/encounter.cpp
selcia-eremeev/chen
96a2f4fbe444b26668983fb4c3f360d1a22cd2f7
[ "MIT" ]
9
2021-03-23T20:08:51.000Z
2021-03-27T20:44:09.000Z
src/scene/encounter/encounter.cpp
selcia-eremeev/chen
96a2f4fbe444b26668983fb4c3f360d1a22cd2f7
[ "MIT" ]
null
null
null
#include "scene/encounter/encounter.hpp" int Encounter::Initialize(void) { RESOURCES->LoadGraph("encounter", "resources\\movies\\encounter.mp4"); DxLib::PlayMovieToGraph(RESOURCES->graphics["encounter"]); return 0; } int Encounter::Update(void) { if (!DxLib::GetMovieStateToGraph(RESOURCES->graphics["encounter"])) { DxLib::SetDrawBright(0, 0, 0); SCENEMGR->scene.push(std::make_shared<Battle>()); SCENEMGR->scene.top()->Initialize(); } return 0; } int Encounter::Render(void) { DxLib::DrawGraph(0, 0, RESOURCES->graphics["encounter"], FALSE); return 0; } int Encounter::Terminate(void) { return 0; }
24.76
71
0.712439
selcia-eremeev
9f7a0f5775fb937a8d1625bd2c3a6644c4f2aa28
9,343
cpp
C++
src/craft/interfaces/WorldInterface.cpp
dkoeplin/Craft
87fda0d7c072820f40ffea379986f0adf421849f
[ "MIT" ]
null
null
null
src/craft/interfaces/WorldInterface.cpp
dkoeplin/Craft
87fda0d7c072820f40ffea379986f0adf421849f
[ "MIT" ]
null
null
null
src/craft/interfaces/WorldInterface.cpp
dkoeplin/Craft
87fda0d7c072820f40ffea379986f0adf421849f
[ "MIT" ]
null
null
null
#include "WorldInterface.h" #include <cmath> #include "GL/glew.h" #include "GLFW/glfw3.h" #include "craft/draw/Crosshairs.h" #include "craft/draw/Render.h" #include "craft/draw/Text.h" #include "craft/interfaces/DebugInterface.h" #include "craft/items/Item.h" #include "craft/physics/Physics.h" #include "craft/player/Player.h" #include "craft/session/Session.h" #include "craft/session/Window.h" #include "craft/util/Logging.h" #include "craft/world/World.h" WorldInterface::WorldInterface(Session *session, World *world, Player *player) : Interface(session), world(world), player(player) { REQUIRE(player, "[WorldInterface] Player was null"); REQUIRE(world, "[WorldInterface] World was null"); REQUIRE(session, "[WorldInterface] Session was null"); } bool WorldInterface::on_mouse_button(MouseButton button, MouseAction action, ButtonMods mods) { if (action != MouseAction::Press) { return true; } bool control = mods.control() || mods.super(); switch (button) { case MouseButton::Left: { if (control) on_right_click(); else on_left_click(); return true; } case MouseButton::Right: { if (control) on_light(); else on_right_click(); return true; } case MouseButton::Middle: { on_middle_click(); return true; } } } bool WorldInterface::on_scroll(double dx, double dy) { static double ypos = 0; ypos += dy; if (ypos < -SCROLL_THRESHOLD) { player->item_index = (player->item_index + 1) % item_count; ypos = 0; } if (ypos > SCROLL_THRESHOLD) { player->item_index = (player->item_index == 0) ? item_count - 1 : player->item_index - 1; ypos = 0; } return true; } bool WorldInterface::on_key_press(Key key, int scancode, ButtonMods mods) { bool control = mods.control() || mods.super(); if (key == Key::Escape) { session->window()->defocus(); return true; } else if (key == player->keys.Debug) { session->get_or_open_interface<DebugInterface>(); return true; } else if (key == player->keys.Chat) { session->suppress_next_char(); session->show_chat(/*cmd*/ false); return true; } else if (key == player->keys.Command) { session->suppress_next_char(); session->show_chat(/*cmd*/ true); return true; } else if (key == player->keys.Sign) { // TODO: sign window /*if (BlockFace block = world->hit_test_face(player->state)) { session->set_sign(block.x, block.y, block.z, block.face, typing_buffer + 1); }*/ return true; } else if (key == Key::Enter) { if (control) { on_right_click(); } else { on_left_click(); } return true; } else if (key == player->keys.Ortho) { player->ortho = (player->ortho != 0) ? 0 : 64; } else if (key == player->keys.Zoom) { player->fov = (player->fov <= 15) ? 75 : player->fov - 30; } else if (key == player->keys.Fly) { player->flying = !player->flying; return true; } else if (key.value >= '1' && key.value <= '9') { player->item_index = key.value - '1'; return true; } else if (key == Key::Key0) { player->item_index = 9; return true; } else if (key == player->keys.Next) { player->item_index = (player->item_index + 1) % item_count; return true; } else if (key == player->keys.Prev) { player->item_index = (player->item_index == 0) ? item_count - 1 : player->item_index - 1; return true; } else if (key == player->keys.Observe) { observe1 = world->next_player(observe1); return true; } else if (key == player->keys.Inset) { observe2 = world->next_player(observe2); return true; } return false; } bool WorldInterface::mouse_movement(double x, double y, double dx, double dy, double dt) { State &s = player->state; s.rx += dx * MOVE_SENSITIVITY; if (INVERT_MOUSE) { s.ry += dy * MOVE_SENSITIVITY; } else { s.ry -= dy * MOVE_SENSITIVITY; } if (s.rx < 0) { s.rx += RADIANS(360); } if (s.rx >= RADIANS(360)) { s.rx -= RADIANS(360); } s.ry = MAX(s.ry, -RADIANS(90)); s.ry = MIN(s.ry, RADIANS(90)); return true; } bool WorldInterface::held_keys(double dt) { int sz = 0; int sx = 0; float m = dt * KEY_SENSITIVITY; State &state = player->state; if (is_key_pressed(player->keys.Forward)) sz--; if (is_key_pressed(player->keys.Backward)) sz++; if (is_key_pressed(player->keys.Left)) sx--; if (is_key_pressed(player->keys.Right)) sx++; if (is_key_pressed(Key::Left)) state.rx -= m; if (is_key_pressed(Key::Right)) state.rx += m; if (is_key_pressed(Key::Up)) state.ry += m; if (is_key_pressed(Key::Down)) state.ry -= m; FVec3 vec = get_motion_vector(player->flying, sz, sx, state.rx, state.ry); float accel = player->flying ? FLYING_SPEED*FLYING_SPEED : WALKING_SPEED*WALKING_SPEED; float max_speed = player->flying ? FLYING_SPEED : WALKING_SPEED; float current_speed = player->velocity.len(); if ((sx != 0 || sz != 0) && current_speed < max_speed) { player->accel = vec * accel; } else if (sx == 0 && sz == 0 && current_speed > 0) { auto a = player->velocity / current_speed; player->accel = a * -accel; } else { player->accel = {}; } if (is_key_pressed(player->keys.Jump)) { if (player->flying) { player->accel.y = max_speed; } else if (player->velocity.y == 0) { player->accel.y = 8; } else { player->accel.y = 0; } } return true; } void WorldInterface::on_light() { Block block = world->hit_test(player->state); if (block.y > 0 && block.y < 256 && is_destructable(block.w)) { session->toggle_light(block); } } void WorldInterface::on_left_click() { Block block = world->hit_test(player->state); if (block.y > 0 && block.y < 256 && is_destructable(block.w)) { session->set_block({block.loc(), 0}); if (is_plant(world->get_block_material(block))) { session->set_block({block.loc(), 0}); } } } void WorldInterface::on_right_click() { Block block = world->hit_test(player->state); if (block.y > 0 && block.y < 256 && is_obstacle(block.w)) { if (!player_intersects_block(2, player->state, block)) { session->set_block({block, items[player->item_index]}); } } } void WorldInterface::on_middle_click() { Block block = world->hit_test(player->state); for (int i = 0; i < item_count; i++) { if (items[i] == block.w) { player->item_index = i; break; } } } bool WorldInterface::render(bool top) { int height = window->height(); int width = window->width(); int scale = window->scale(); float ts = 0.0f; // RENDER 3-D SCENE // Player *target = observe1 ? observe1 : player; glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); session->render_sky(Render::sky(), target, width, height); glClear(GL_DEPTH_BUFFER_BIT); session->render_chunks(Render::block(), target, width, height); session->render_signs(Render::text(), target, width, height); session->render_players(Render::text(), target, width, height); if (SHOW_WIREFRAME) { session->render_wireframe(Render::line(), target, width, height); } glClear(GL_DEPTH_BUFFER_BIT); // RENDER HUD // if (SHOW_CROSSHAIRS) { render_crosshairs(window, Render::line()); } if (SHOW_ITEM) { render_item(Render::block(), world, target); } if (SHOW_PLAYER_NAMES) { if (target != player) { render_text(window, Render::text(), Justify::Center, width / 2.0f, ts, ts, target->name); } if (auto *other = world->closest_player_in_view(target)) { render_text(window, Render::text(), Justify::Center, width / 2, height / 2 - ts - 24, ts, other->name); } } // RENDER PICTURE IN PICTURE // if (observe2 && observe2 != player) { float pw = 256 * scale; float ph = 256 * scale; int offset = 32 * scale; int pad = 3 * scale; int sw = pw + pad * 2; int sh = ph + pad * 2; glEnable(GL_SCISSOR_TEST); glScissor(width - sw - offset + pad, offset - pad, sw, sh); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); glClear(GL_DEPTH_BUFFER_BIT); glViewport(width - pw - offset, offset, pw, ph); session->render_sky(Render::sky(), observe2, pw, ph); glClear(GL_DEPTH_BUFFER_BIT); session->render_chunks(Render::block(), observe2, pw, ph); session->render_signs(Render::text(), observe2, pw, ph); session->render_players(Render::block(), observe2, pw, ph); glClear(GL_DEPTH_BUFFER_BIT); if (SHOW_PLAYER_NAMES) { render_text(window, Render::text(), Justify::Center, pw / 2, ts, ts, observe2->name); } } return false; }
31.887372
115
0.582361
dkoeplin
9f7ca4bc381d80d3d88b2cc91ff8935038e8ee96
17,531
cpp
C++
Peridigm/Code/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.cpp
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
Peridigm/Code/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.cpp
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
Peridigm/Code/Energy_damage_criterion/src/damage/Peridigm_EnergyReleaseDamageModel.cpp
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
/*! \file Peridigm_EnergyReleaseDamageModel.cpp */ //@HEADER // ************************************************************************ // // Peridigm // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? // David J. Littlewood [email protected] // John A. Mitchell [email protected] // Michael L. Parks [email protected] // Stewart A. Silling [email protected] // // ************************************************************************ ////////////////////////////////////////////////////////////////////////////////////// // Routine developed for Peridigm by // DLR Composite Structures and Adaptive Systems // __/|__ // /_/_/_/ // www.dlr.de/fa/en |/ DLR ////////////////////////////////////////////////////////////////////////////////////// // Questions? // Christian Willberg [email protected] // Martin Raedel [email protected] ////////////////////////////////////////////////////////////////////////////////////// //@HEADER #include "Peridigm_EnergyReleaseDamageModel.hpp" #include "Peridigm_Field.hpp" #include "material_utilities.h" #include <thread> #include <Teuchos_Assert.hpp> #include <Epetra_SerialComm.h> #include <Sacado.hpp> #include <boost/math/special_functions/fpclassify.hpp> using namespace std; PeridigmNS::EnergyReleaseDamageModel::EnergyReleaseDamageModel(const Teuchos::ParameterList& params) : DamageModel(params), m_applyThermalStrains(false), m_modelCoordinatesFieldId(-1), m_coordinatesFieldId(-1), m_damageFieldId(-1), m_bondDamageFieldId(-1), m_deltaTemperatureFieldId(-1), m_dilatationFieldId(-1), m_weightedVolumeFieldId(-1), m_horizonFieldId(-1), m_damageModelFieldId(-1), m_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()) { if (params.isParameter("Critical Energy")) { m_criticalEnergyTension = params.get<double>("Critical Energy Tension"); m_criticalEnergyCompression = params.get<double>("Critical Energy Compression"); m_criticalEnergyShear = params.get<double>("Critical Energy Shear"); } else { if (params.isParameter("Critical Energy Tension")) m_criticalEnergyTension = params.get<double>("Critical Energy Tension"); else m_criticalEnergyTension = -1.0; if (params.isParameter("Critical Energy Compression")) m_criticalEnergyCompression = params.get<double>("Critical Energy Compression"); else m_criticalEnergyCompression = -1.0; if (params.isParameter("Critical Energy Shear")) m_criticalEnergyShear = params.get<double>("Critical Energy Shear"); else m_criticalEnergyShear = -1.0; m_type = 1; if (params.isType<string>("Energy Criterion")) m_type = 1; if (params.isType<string>("Power Law")) m_type = 2; if (params.isType<string>("Separated")) m_type = 3; } m_pi = 3.14159; if (params.isParameter("Thermal Expansion Coefficient")) { m_alpha = params.get<double>("Thermal Expansion Coefficient"); m_applyThermalStrains = true; } PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self(); m_modelCoordinatesFieldId = fieldManager.getFieldId("Model_Coordinates"); m_coordinatesFieldId = fieldManager.getFieldId("Coordinates"); m_volumeFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, "Volume"); m_weightedVolumeFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, "Weighted_Volume"); m_dilatationFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::TWO_STEP, "Dilatation"); m_damageFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, "Damage"); m_bondDamageFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::BOND, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::TWO_STEP, "Bond_Damage"); m_horizonFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::ELEMENT, PeridigmNS::PeridigmField::SCALAR, PeridigmNS::PeridigmField::CONSTANT, "Horizon"); m_damageModelFieldId = fieldManager.getFieldId(PeridigmNS::PeridigmField::NODE, PeridigmNS::PeridigmField::VECTOR, PeridigmNS::PeridigmField::TWO_STEP, "Damage_Model_Data"); m_fieldIds.push_back(m_volumeFieldId); m_fieldIds.push_back(m_modelCoordinatesFieldId); m_fieldIds.push_back(m_coordinatesFieldId); m_fieldIds.push_back(m_weightedVolumeFieldId); m_fieldIds.push_back(m_dilatationFieldId); m_fieldIds.push_back(m_volumeFieldId); m_fieldIds.push_back(m_damageFieldId); m_fieldIds.push_back(m_damageModelFieldId); m_fieldIds.push_back(m_bondDamageFieldId); m_fieldIds.push_back(m_horizonFieldId); } PeridigmNS::EnergyReleaseDamageModel::~EnergyReleaseDamageModel() { } void PeridigmNS::EnergyReleaseDamageModel::initialize(const double dt, const int numOwnedPoints, const int* ownedIDs, const int* neighborhoodList, PeridigmNS::DataManager& dataManager) const { double *damage, *bondDamage; dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage); dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage); // Initialize damage to zero int neighborhoodListIndex(0); int bondIndex(0); int nodeId, numNeighbors; int iID, iNID; for (iID = 0; iID < numOwnedPoints; ++iID) { nodeId = ownedIDs[iID]; damage[nodeId] = 0.0; numNeighbors = neighborhoodList[neighborhoodListIndex++]; neighborhoodListIndex += numNeighbors; for (iNID = 0; iNID < numNeighbors; ++iNID) { bondDamage[bondIndex] = 0.0; bondIndex += 1; } } } void PeridigmNS::EnergyReleaseDamageModel::computeDamage(const double dt, const int numOwnedPoints, const int* ownedIDs, const int* neighborhoodList, PeridigmNS::DataManager& dataManager) const { double *x, *y, *damage, *bondDamageNP1, *horizon; double *cellVolume, *weightedVolume, *damageModel; double criticalEnergyTension(-1.0), criticalEnergyCompression(-1.0), criticalEnergyShear(-1.0); // for temperature dependencies easy to extent double *deltaTemperature = NULL; double m_alpha = 0; dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage); dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x); dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y); dataManager.getData(m_weightedVolumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&weightedVolume); dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&cellVolume); ////////////////////////////////////////////////////////////// // transfer of data is done in ComputeDilation --> PeridigmMaterial.cpp ////////////////////////////////////////////////////////////// dataManager.getData(m_damageModelFieldId, PeridigmField::STEP_NP1)->ExtractView(&damageModel); dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon); //////////////////////////////////// //////////////////////////////////// // transfer of data is done in ComputeDilation --> PeridigmMaterial.cpp dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamageNP1); //////////////////////////////////////////////////// double trialDamage(0.0); int neighborhoodListIndex(0), bondIndex(0); int nodeId, numNeighbors, neighborID, iID, iNID; double totalDamage; double alphaP1, alphaP2; double nodeInitialX[3], nodeCurrentX[3], relativeExtension(0.0); double bondEnergyIsotropic(0.0), bondEnergyDeviatoric(0.0); double omegaP1, omegaP2; double critDev, critIso, critComp; double BulkMod1, BulkMod2; double degradationFactor = 1.0; // Optional parameter if bond should be degradated and not fully destroyed instantaneously double avgHorizon, quadhorizon; //--------------------------- // INITIALIZE PROCESS STEP t //--------------------------- if (m_criticalEnergyTension > 0.0) criticalEnergyTension = m_criticalEnergyTension; if (m_criticalEnergyCompression > 0.0) criticalEnergyCompression = m_criticalEnergyCompression; if (m_criticalEnergyShear > 0.0) criticalEnergyShear = m_criticalEnergyShear; // Update the bond damage // Break bonds if the bond energy potential is greater than the critical bond energy potential //--------------------------- // DAMAGE ANALYSIS //--------------------------- bondIndex = 0; for (iID = 0; iID < numOwnedPoints; ++iID) { numNeighbors = neighborhoodList[neighborhoodListIndex++]; nodeId = ownedIDs[iID]; nodeInitialX[0] = x[nodeId*3]; nodeInitialX[1] = x[nodeId*3+1]; nodeInitialX[2] = x[nodeId*3+2]; nodeCurrentX[0] = y[nodeId*3]; nodeCurrentX[1] = y[nodeId*3+1]; nodeCurrentX[2] = y[nodeId*3+2]; double dilatationP1 = damageModel[3*nodeId]; alphaP1 = 15.0 * damageModel[3*nodeId+2]; // weightedVolume is already included in --> Perdigm_Material.cpp; for (iNID = 0; iNID < numNeighbors; ++iNID) { trialDamage = 0.0; neighborID = neighborhoodList[neighborhoodListIndex++]; double zeta = distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2], x[neighborID*3], x[neighborID*3+1], x[neighborID*3+2]); double dY = distance(nodeCurrentX[0], nodeCurrentX[1], nodeCurrentX[2], y[neighborID*3], y[neighborID*3+1], y[neighborID*3+2]); relativeExtension = (dY - zeta)/zeta; // the direction switches between both bonds. This results in a switch of the forces // as well. Therefore, all forces and bond deformations are normalized. double eP = dY - zeta; //double normZeta = sqrt(zeta*zeta); alphaP2 = 15.0 * damageModel[3*neighborID+2]; // weightedVolume is already included in --> Perdigm_Material.cpp; BulkMod1 = damageModel[3*nodeId+1]; // weightedVolume is already included in the variable --> Perdigm_Material.cpp; BulkMod2 = damageModel[3*neighborID+1]; // weightedVolume is already included in the variable --> Perdigm_Material.cpp; double dilatationP2 = damageModel[3*neighborID]; omegaP1 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[nodeId]); omegaP2 = MATERIAL_EVALUATION::scalarInfluenceFunction(zeta, horizon[neighborID]); double eiP1 = dilatationP1 * zeta / 3.0; double eiP2 = dilatationP2 * zeta / 3.0; double tiP1 = 3*BulkMod1*omegaP1*dilatationP1*zeta; double tiP2 = 3*BulkMod2*omegaP2*dilatationP2*zeta; double edP1 = eP - sqrt(eiP1*eiP1); double edP2 = eP - sqrt(eiP2*eiP2); double tdP1 = omegaP1*alphaP1*edP1; double tdP2 = omegaP2*alphaP2*edP2; // absolute values of energy, because it is positive and coordinate errors are avoided. bondEnergyIsotropic = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tiP1*eiP1*tiP1*eiP1) + sqrt(tiP2*eiP2*tiP2*eiP2)); bondEnergyDeviatoric = (1.0 - bondDamageNP1[bondIndex])*(sqrt(tdP1*edP1*tdP2*edP2) + sqrt(tdP2*edP2*tdP2*edP2)); // the average horizon is taken, if multiple horizons are used avgHorizon = 0.5*(horizon[nodeId]+horizon[neighborID]); // geometrical part of the energy value quadhorizon = 16.0 /( m_pi * avgHorizon * avgHorizon * avgHorizon * avgHorizon ); // the factor 16 can be split in three parts: // 4 comes from the integration from Foster et al. (2009) Journal for Multiscale Computational Engineering; // 2 comes from the force split motivated by the bond based formulation Bobaru et al. (2017) "Handbook of Peridynamik Modeling", page 48 ; // 2 comes from the energy formulation itself critIso = 0.0; if (relativeExtension>0&&criticalEnergyTension != -1.0){ critIso = (bondEnergyIsotropic/(criticalEnergyTension*quadhorizon)); } critDev = 0.0; if (criticalEnergyShear != -1.0){ critDev = (bondEnergyDeviatoric/(criticalEnergyShear*quadhorizon)); } critComp = 0.0; if (relativeExtension < 0.0 && criticalEnergyCompression != -1.0){ critComp = (bondEnergyIsotropic/(criticalEnergyCompression*quadhorizon)); critIso = 0.0; } if (m_type == 1){ // Energy Criterion by Foster et al.(2009) Journal for Multiscale Computational Engineering; double bondEnergy = sqrt((tdP1+tiP1)*(tdP1+tiP1)*eP*eP) + sqrt((tdP2 + tiP2)*(tdP2 + tiP2)*eP*eP); critIso = bondEnergy/(criticalEnergyTension*quadhorizon); if (m_criticalEnergyTension > 0.0 && critIso > 1.0 ) { trialDamage = bondDamageNP1[bondIndex] + degradationFactor; } } if (m_type == 2){// Power Law if (m_criticalEnergyTension > 0.0 &&critIso*critIso + critDev*critDev + critComp*critComp > 1.0) { trialDamage = bondDamageNP1[bondIndex] + degradationFactor; } } if (m_type == 3){ // Separated if (m_criticalEnergyTension > 0.0 &&critIso > 1.0) { trialDamage = bondDamageNP1[bondIndex] + degradationFactor; } if (m_criticalEnergyTension > 0.0 && critDev > 1.0) { trialDamage = bondDamageNP1[bondIndex] + degradationFactor; } if (m_criticalEnergyCompression > 0.0 && critComp > 1.0) { trialDamage = bondDamageNP1[bondIndex] + degradationFactor; } } if (trialDamage > bondDamageNP1[bondIndex]) { if (trialDamage>1)trialDamage = 1; bondDamageNP1[bondIndex] = trialDamage; } bondIndex += 1; } } // Update the element damage (percent of bonds broken) neighborhoodListIndex = 0; bondIndex = 0; for (iID = 0; iID < numOwnedPoints; ++iID) { nodeId = ownedIDs[iID]; numNeighbors = neighborhoodList[neighborhoodListIndex++]; //neighborhoodListIndex += numNeighbors; damageModel[3*nodeId] = 0.0; damageModel[3*nodeId+1] = 0.0; damageModel[3*nodeId+2] = 0.0; totalDamage = 0.0; for (iNID = 0; iNID < numNeighbors; ++iNID) { neighborID = neighborhoodList[neighborhoodListIndex++]; // must be zero to avoid synchronization errors damageModel[3*neighborID] = 0.0; damageModel[3*neighborID+1] = 0.0; damageModel[3*neighborID+2] = 0.0; totalDamage += bondDamageNP1[bondIndex]; bondIndex += 1; } if (numNeighbors > 0) totalDamage /= numNeighbors; else totalDamage = 0.0; damage[nodeId] = totalDamage; } }
44.951282
177
0.630825
oldninja
9f7cb6fbc5ccfadc1b4bcbd36dd33ee91a8f0976
2,166
cpp
C++
src/llri-vk/detail/queue.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
2
2022-02-08T07:11:32.000Z
2022-02-08T08:10:31.000Z
src/llri-vk/detail/queue.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
1
2022-02-14T18:26:31.000Z
2022-02-14T18:26:31.000Z
src/llri-vk/detail/queue.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
null
null
null
/** * @file queue.cpp * Copyright (c) 2021 Leon Brands, Rythe Interactive * SPDX-License-Identifier: MIT */ #include <llri/llri.hpp> #include <llri-vk/utils.hpp> namespace llri { result Queue::impl_submit(const submit_desc& desc) { std::vector<VkCommandBuffer> buffers(desc.numCommandLists); for (size_t i = 0; i < desc.numCommandLists; i++) buffers[i] = static_cast<VkCommandBuffer>(desc.commandLists[i]->m_ptr); std::vector<VkSemaphore> waitSemaphores(desc.numWaitSemaphores); std::vector<VkPipelineStageFlags> waitSemaphoreStages(desc.numWaitSemaphores, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); for (size_t i = 0; i < desc.numWaitSemaphores; i++) waitSemaphores[i] = static_cast<VkSemaphore>(desc.waitSemaphores[i]->m_ptr); std::vector<VkSemaphore> signalSemaphores(desc.numSignalSemaphores); for (size_t i = 0; i < desc.numSignalSemaphores; i++) signalSemaphores[i] = static_cast<VkSemaphore>(desc.signalSemaphores[i]->m_ptr); VkSubmitInfo info; info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; info.pNext = nullptr; info.commandBufferCount = desc.numCommandLists; info.pCommandBuffers = buffers.data(); info.waitSemaphoreCount = desc.numWaitSemaphores; info.pWaitSemaphores = waitSemaphores.data(); info.signalSemaphoreCount = desc.numSignalSemaphores; info.pSignalSemaphores = signalSemaphores.data(); info.pWaitDstStageMask = waitSemaphoreStages.data(); VkFence fence = VK_NULL_HANDLE; if (desc.fence != nullptr) { fence = static_cast<VkFence>(desc.fence->m_ptr); desc.fence->m_signaled = true; } const auto r = static_cast<VolkDeviceTable*>(m_device->m_functionTable)-> vkQueueSubmit(static_cast<VkQueue>(m_ptrs[0]), 1, &info, fence); return detail::mapVkResult(r); } result Queue::impl_waitIdle() { const auto r = static_cast<VolkDeviceTable*>(m_device->m_functionTable)->vkQueueWaitIdle(static_cast<VkQueue>(m_ptrs[0])); return detail::mapVkResult(r); } }
38
130
0.672207
Rythe-Interactive
9f883e0a57c86ef1fd04f25a1215f843662d4b5a
10,227
cpp
C++
test/Mutex.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
1
2021-09-12T21:05:45.000Z
2021-09-12T21:05:45.000Z
test/Mutex.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
2
2020-01-24T18:00:15.000Z
2020-02-03T21:15:54.000Z
test/Mutex.cpp
kubasejdak/osal
6e43ba761572444b2f56b529e501f40c00d4e718
[ "BSD-2-Clause" ]
2
2020-06-15T16:27:58.000Z
2021-09-12T21:05:49.000Z
///////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @copyright BSD 2-Clause License /// /// Copyright (c) 2020-2021, Kuba Sejdak <[email protected]> /// 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. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE /// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR /// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE /// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// ///////////////////////////////////////////////////////////////////////////////////// #include <osal/Mutex.h> #include <osal/Thread.hpp> #include <osal/sleep.hpp> #include <osal/timestamp.hpp> #include <catch2/catch.hpp> TEST_CASE("Mutex creation and destruction", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eInvalidArgument); } TEST_CASE("Invalid parameters to mutex creation and destruction functions", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } auto error = osalMutexCreate(nullptr, type); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexDestroy(nullptr); REQUIRE(error == OsalError::eInvalidArgument); } TEST_CASE("Lock and unlock from one thread", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexLock(&mutex); REQUIRE(error == OsalError::eOk); error = osalMutexUnlock(&mutex); REQUIRE(error == OsalError::eOk); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("Invalid arguments passed to mutex functions in one thread", "[unit][c][mutex]") { auto error = osalMutexLock(nullptr); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexTryLock(nullptr); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexTryLockIsr(nullptr); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexTimedLock(nullptr, 3); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexUnlock(nullptr); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexUnlockIsr(nullptr); REQUIRE(error == OsalError::eInvalidArgument); } TEST_CASE("Lock called from two threads", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexLock(&mutex); REQUIRE(error == OsalError::eOk); auto func = [&mutex] { auto start = osal::timestamp(); auto error = osalMutexLock(&mutex); if (error != OsalError::eOk) REQUIRE(error == OsalError::eOk); auto end = osal::timestamp(); if ((end - start) < 100ms) REQUIRE((end - start) >= 100ms); error = osalMutexUnlock(&mutex); if (error != OsalError::eOk) REQUIRE(error == OsalError::eOk); }; osal::Thread thread(func); osal::sleep(120ms); error = osalMutexUnlock(&mutex); REQUIRE(error == OsalError::eOk); thread.join(); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("TryLock called from second thread", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexLock(&mutex); REQUIRE(error == OsalError::eOk); auto func = [&mutex] { auto start = osal::timestamp(); while (osalMutexTryLock(&mutex) != OsalError::eOk) osal::sleep(10ms); auto end = osal::timestamp(); if ((end - start) < 100ms) REQUIRE((end - start) >= 100ms); auto error = osalMutexUnlock(&mutex); if (error != OsalError::eOk) REQUIRE(error == OsalError::eOk); }; osal::Thread thread(func); osal::sleep(120ms); error = osalMutexUnlock(&mutex); REQUIRE(error == OsalError::eOk); thread.join(); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("TryLock and unlock called from ISR", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexTryLockIsr(&mutex); REQUIRE(error == OsalError::eOk); auto func = [&mutex] { auto start = osal::timestamp(); while (osalMutexTryLockIsr(&mutex) != OsalError::eOk) osal::sleep(10ms); auto end = osal::timestamp(); if ((end - start) < 100ms) REQUIRE((end - start) >= 100ms); auto error = osalMutexUnlock(&mutex); if (error != OsalError::eOk) REQUIRE(error == OsalError::eOk); }; osal::Thread thread(func); osal::sleep(120ms); error = osalMutexUnlockIsr(&mutex); REQUIRE(error == OsalError::eOk); thread.join(); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("Recursive tryLock called from ISR", "[unit][c][mutex]") { OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, OsalMutexType::eRecursive); REQUIRE(error == OsalError::eOk); error = osalMutexTryLockIsr(&mutex); REQUIRE(error == OsalError::eInvalidArgument); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("TimedLock called from second thread, timeout", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexLock(&mutex); REQUIRE(error == OsalError::eOk); auto func = [&mutex] { auto start = osal::timestamp(); constexpr std::uint32_t cTimeoutMs = 100; auto error = osalMutexTimedLock(&mutex, cTimeoutMs); if (error != OsalError::eTimeout) REQUIRE(error == OsalError::eTimeout); auto end = osal::timestamp(); if ((end - start) < 100ms) REQUIRE((end - start) >= 100ms); }; osal::Thread thread(func); thread.join(); error = osalMutexUnlock(&mutex); REQUIRE(error == OsalError::eOk); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); } TEST_CASE("TimedLock called from second thread, success", "[unit][c][mutex]") { OsalMutexType type{}; SECTION("Non recursive mutex") { type = OsalMutexType::eNonRecursive; } SECTION("Recursive mutex") { type = OsalMutexType::eRecursive; } SECTION("Default mutex") { type = cOsalMutexDefaultType; } OsalMutex mutex{}; auto error = osalMutexCreate(&mutex, type); REQUIRE(error == OsalError::eOk); error = osalMutexLock(&mutex); REQUIRE(error == OsalError::eOk); auto func = [&mutex] { auto start = osal::timestamp(); constexpr std::uint32_t cTimeoutMs = 100; if (auto error = osalMutexTimedLock(&mutex, cTimeoutMs)) REQUIRE(!error); auto end = osal::timestamp(); if ((end - start) > 100ms) REQUIRE((end - start) <= 100ms); if (auto error = osalMutexUnlock(&mutex)) REQUIRE(!error); }; osal::Thread thread(func); osal::sleep(50ms); error = osalMutexUnlock(&mutex); REQUIRE(error == OsalError::eOk); thread.join(); error = osalMutexDestroy(&mutex); REQUIRE(error == OsalError::eOk); }
29.22
95
0.640364
kubasejdak
9f8a5c913bc22e3bb31414f77cb356d62a46fc6d
820
hpp
C++
humble-crap/commandline-interface.hpp
lukesalisbury/humble-crap
814c551cfdfa2687d531b50d350a0d2a6f5cf832
[ "Unlicense" ]
2
2015-02-02T23:40:03.000Z
2016-02-17T17:58:18.000Z
humble-crap/commandline-interface.hpp
lukesalisbury/humble-crap
814c551cfdfa2687d531b50d350a0d2a6f5cf832
[ "Unlicense" ]
null
null
null
humble-crap/commandline-interface.hpp
lukesalisbury/humble-crap
814c551cfdfa2687d531b50d350a0d2a6f5cf832
[ "Unlicense" ]
null
null
null
#ifndef CLI_INTERFACE_HPP #define CLI_INTERFACE_HPP #include <QObject> #include <QCoreApplication> class CommandLineTask { }; class CommandLineInterface : public QObject { Q_OBJECT public: CommandLineInterface(QCoreApplication * a, QObject * parent = nullptr); ~CommandLineInterface(); signals: void taskCompleted(); void taskFailed(); public slots: void downloadTaskSuccess(int downloadID); void downloadTaskFailure(int downloadID); void taskSuccess(QString key, QString text); void taskFailure(QString key, QString text); void exitSuccessfully(); void exitWithFailure(); void orderSuccess(); void orderFailure(); void mainTask(); private: QCoreApplication * app; int task = 0; void downloadOrder(QString key); void checkForExit(); }; #endif // CLI_INTERFACE_HPP
16.4
73
0.740244
lukesalisbury
9f8a93ac56f39e2e5538bc2d0dbc39b854615437
1,192
cpp
C++
Shoot/src/GraphicExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
Shoot/src/GraphicExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
Shoot/src/GraphicExtensionHandler.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: July 6th 2013 */ #include "Shoot.h" #include "GraphicExtensionHandler.h" #if SHOOT_PLATFORM == SHOOT_PLATFORM_IOS || SHOOT_PLATFORM == SHOOT_PLATFORM_ANDROID #include "OpenGLExtensionHandlerES2.h" #elif !defined(DX11) #include "OpenGLExtensionHandlerWin32.h" #endif namespace shoot { //! static variables initialization GraphicExtensionHandler* GraphicExtensionHandler::m_spInstance = NULL; //! CreateInstance void GraphicExtensionHandler::CreateInstance() { if(m_spInstance) { #ifndef SHOOT_EDITOR SHOOT_ASSERT(false, "Multiple GraphicExtensionHandler instances detected"); #endif // SHOOT_EDITOR return; } #if defined(DX11) m_spInstance = snew GraphicExtensionHandler(); #elif SHOOT_PLATFORM == SHOOT_PLATFORM_IOS || SHOOT_PLATFORM == SHOOT_PLATFORM_ANDROID m_spInstance = snew OpenGLExtensionHandlerES2(); #else m_spInstance = snew OpenGLExtensionHandlerWin32(); #endif } //! destroys the driver void GraphicExtensionHandler::DestroyInstance() { sdelete(m_spInstance); } //! Constructor GraphicExtensionHandler::GraphicExtensionHandler() { for(int i=0; i<E_Count; ++i) { m_bHasExtension[i] = false; } } }
20.20339
86
0.756711
franticsoftware
9f915c4603e8f83b4352c452f8072cb37d48dc1e
4,790
cpp
C++
src/Systems/DX9RenderSystem/DX9RenderErrorHelper.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Systems/DX9RenderSystem/DX9RenderErrorHelper.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Systems/DX9RenderSystem/DX9RenderErrorHelper.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "DX9RenderErrorHelper.h" #include "Kernel/Logger.h" #include "Config/Utils.h" namespace Mengine { namespace Helper { const Char * getDX9ErrorMessage( HRESULT _hr ) { switch( _hr ) { #if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) MENGINE_MESSAGE_CASE( D3D_OK, "Ok" ); MENGINE_MESSAGE_CASE( D3DERR_WRONGTEXTUREFORMAT, "Wrong texture format" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDCOLOROPERATION, "Unsupported color operation" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDCOLORARG, "Unsupported color arg" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDALPHAOPERATION, "Unsupported alpha operation" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDALPHAARG, "Unsupported alpha arg" ); MENGINE_MESSAGE_CASE( D3DERR_TOOMANYOPERATIONS, "Too many operations" ); MENGINE_MESSAGE_CASE( D3DERR_CONFLICTINGTEXTUREFILTER, "Conflicting texture filter" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDFACTORVALUE, "Unsupported factor value" ); MENGINE_MESSAGE_CASE( D3DERR_CONFLICTINGRENDERSTATE, "Conflicting render state" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDTEXTUREFILTER, "Unsupported texture filter" ); MENGINE_MESSAGE_CASE( D3DERR_CONFLICTINGTEXTUREPALETTE, "Conflicting texture palette" ); MENGINE_MESSAGE_CASE( D3DERR_DRIVERINTERNALERROR, "Driver internal error" ); MENGINE_MESSAGE_CASE( D3DERR_NOTFOUND, "Not found" ); MENGINE_MESSAGE_CASE( D3DERR_MOREDATA, "More data" ); MENGINE_MESSAGE_CASE( D3DERR_DEVICELOST, "Device lost" ); MENGINE_MESSAGE_CASE( D3DERR_DEVICENOTRESET, "Device not reset" ); MENGINE_MESSAGE_CASE( D3DERR_NOTAVAILABLE, "Not available" ); MENGINE_MESSAGE_CASE( D3DERR_OUTOFVIDEOMEMORY, "Out of video memory" ); MENGINE_MESSAGE_CASE( D3DERR_INVALIDDEVICE, "Invalid device" ); MENGINE_MESSAGE_CASE( D3DERR_INVALIDCALL, "Invalid call" ); MENGINE_MESSAGE_CASE( D3DERR_DRIVERINVALIDCALL, "Driver invalid call" ); MENGINE_MESSAGE_CASE( D3DERR_WASSTILLDRAWING, "Was Still Drawing" ); MENGINE_MESSAGE_CASE( D3DOK_NOAUTOGEN, "The call succeeded but there won't be any mipmaps generated" ); MENGINE_MESSAGE_CASE( D3DERR_DEVICEREMOVED, "Hardware device was removed" ); MENGINE_MESSAGE_CASE( S_NOT_RESIDENT, "Resource not resident in memory" ); MENGINE_MESSAGE_CASE( S_RESIDENT_IN_SHARED_MEMORY, "Resource resident in shared memory" ); MENGINE_MESSAGE_CASE( S_PRESENT_MODE_CHANGED, "Desktop display mode has changed" ); MENGINE_MESSAGE_CASE( S_PRESENT_OCCLUDED, "Client window is occluded (minimized or other fullscreen)" ); MENGINE_MESSAGE_CASE( D3DERR_DEVICEHUNG, "Hardware adapter reset by OS" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDOVERLAY, "Overlay is not supported" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDOVERLAYFORMAT, "Overlay format is not supported" ); MENGINE_MESSAGE_CASE( D3DERR_CANNOTPROTECTCONTENT, "Contect protection not available" ); MENGINE_MESSAGE_CASE( D3DERR_UNSUPPORTEDCRYPTO, "Unsupported cryptographic system" ); MENGINE_MESSAGE_CASE( D3DERR_PRESENT_STATISTICS_DISJOINT, "Presentation statistics are disjoint" ); #endif default: return "Unknown error."; } } } ////////////////////////////////////////////////////////////////////////// DX9ErrorHelper::DX9ErrorHelper( const Char * _file, uint32_t _line, const Char * _method ) : m_file( _file ) , m_line( _line ) , m_method( _method ) { } ////////////////////////////////////////////////////////////////////////// DX9ErrorHelper::~DX9ErrorHelper() { } ////////////////////////////////////////////////////////////////////////// bool DX9ErrorHelper::operator == ( HRESULT _hr ) const { if( _hr == S_OK ) { return false; } const Char * message = Helper::getDX9ErrorMessage( _hr ); LOGGER_VERBOSE_LEVEL( ConstString::none(), LM_ERROR, LCOLOR_RED, nullptr, 0 )("[DX9] file '%s' line %u call '%s' get error: %s (hr:%x)" , m_file , m_line , m_method , message , (uint32_t)_hr ); return true; } ////////////////////////////////////////////////////////////////////////// }
51.505376
143
0.602296
irov
9f915e83118f6cf2fd3b289f69af404bc8725906
1,172
cpp
C++
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
1
2020-09-30T10:36:06.000Z
2020-09-30T10:36:06.000Z
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; // d=array of denominations // sample // 4 2 // 1 2 // output // 3 int coin_change(int n, int *d,int num_den, int **storage){ if(n<0){ return 0; } if(n==0){ return 1; } if(num_den==0){ return 0; } if(storage[n][num_den]>-1){ return storage[n][num_den]; } int first = coin_change(n-d[0],d,num_den,storage); int second = coin_change(n,d+1,num_den-1,storage); storage[n][num_den]=first+second; return first+second; } int main(){ int n; //rupees cin>>n; int num_den; //no of den of coins cin>>num_den; int *d=new int[num_den]; for(int i=0;i<num_den;i++){ cin>>d[i]; } int **storage=new int*[n+1]; for(int i=0;i<=n;i++){ storage[i]=new int[num_den+1]; } for(int i=0;i<=n;i++){ for(int j=0;j<=num_den;j++){ storage[i][j]=-1; } } // for(int i=0;i<n;i++){ // for(int j=0;j<num_den;j++){ // cout<<storage[i][j]<<" "; // } // cout<<"\n"; // } cout<<coin_change(n,d,num_den,storage)<<endl; }
20.928571
58
0.503413
meyash
7a0912953604c5a3096fe228d4e161be1c38cbb0
10,236
cpp
C++
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
4
2017-06-20T10:05:31.000Z
2019-05-04T14:25:23.000Z
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
null
null
null
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
3
2015-08-18T11:04:55.000Z
2018-07-25T12:56:01.000Z
#include "opencv2/opencv.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/nonfree/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/nonfree/nonfree.hpp" #include <fstream> using namespace cv; using namespace std; const double ANGLE_W = .3; const double SIZE_W = .3; const double DIST_W = .4; #define FEATURE_THRESHHOLD 120 #define FRAME_BLUR 1 enum { NONE, FF, OO, JJ, MM, TH }; #define NUM_SOUNDS 6 // Compare key points by location // Sorts top to bottom and left to right (I think) bool compKeyPointsLocY(KeyPoint a, KeyPoint b) { if (a.pt.y < b.pt.y) return true; if (a.pt.y == b.pt.y && a.pt.x < b.pt.x) return true; return false; } // Compare key points by location // Sorts left to right and top to bottom(I think) bool compKeyPointsLocX(KeyPoint a, KeyPoint b) { if (a.pt.x < b.pt.x) return true; if (a.pt.x == b.pt.x && a.pt.y < b.pt.y) return true; return false; } // Compare key points based on size // Biggest first, smallest last bool compKeyPointsSize(KeyPoint a, KeyPoint b) { return a.size > b.size; } // Compare key points based on angle // Biggest first, smallest last bool compKeyPointsAngle(KeyPoint a, KeyPoint b) { return a.angle > b.angle; } /* std::vector<float> convertToFloatArray(std::vector<KeyPoint> pts) { // Trim down to the 80 biggest features if (pts.size() > 20) { std::sort(pts.begin(), pts.end(), compKeyPointsSize); pts.erase(pts.begin() + 20, pts.end()); } //Sort by location to try and standardize their order std::sort(pts.begin(), pts.end(), compKeyPointsLoc); std::vector<float> arr; for(int i=0; i<pts.size(); i++) { arr.push_back( pts[i].pt.x ); arr.push_back( pts[i].pt.y ); arr.push_back( pts[i].size ); arr.push_back( pts[i].angle ); } //Make the vector 80 long if it isn't already while (arr.size() < 80) { arr.push_back(0); } return arr; } */ // Calculates the distance between two features float distFeature(KeyPoint a, KeyPoint b) { return (a.pt.x - b.pt.x)*(a.pt.x - b.pt.x) + (a.pt.y - b.pt.y)*(a.pt.y - b.pt.y); } // This functiion takes in the new features and // tries to align them with the old ones so that // features[0][0] and features [1][0] will be consecutive // frames of the same feature std::vector<KeyPoint> alignNewFeatures(std::vector<KeyPoint> oldF, std::vector<KeyPoint> newF) { std::vector<KeyPoint> outF; for (int i=0; i < oldF.size(); i++) { float minDist = 1000; KeyPoint closest; int indexClosest = -1; // Find which feature from 'newF' is closest to this feature for (int j=0; j < newF.size(); j++) { if (distFeature(newF[j], oldF[i]) < minDist) { minDist = distFeature(newF[j], oldF[i]); closest = newF[j]; indexClosest = j; } } // If closest is close enough (such that it's probably the same feature) // Add it to the output vector and remove it from newF if (minDist < 20) { outF.push_back(closest); newF.erase(newF.begin() + indexClosest); } else if (oldF[i].size == 0 && indexClosest > -1) { // If it was a placeholder feature last frame outF.push_back(closest); newF.erase(newF.begin() + indexClosest); } else { // Otherwise set this feature to the correct location, but 0 size KeyPoint k(oldF[i].pt, 0); outF.push_back(k); } } //Throw all the new features (ones that weren't in last frame) into open spots (where size has been 0 for two frames) for (int i=0; i<oldF.size(); i++) { if (oldF[i].size == 0 && outF[i].size == 0 && newF.size() > 0) { outF[i] = newF[0]; newF.erase(newF.begin()); } } for (int i=0; i<newF.size(); i++) { outF.push_back(newF[i]); } return outF; } // Trims the features that aren't apparent thoughout most frames // THe threshhold is the percent of frames features must persist in std::vector<std::vector<KeyPoint> > trimBadFeatures(std::vector<std::vector<KeyPoint> > arr, double threshhold) { std::vector<std::vector<KeyPoint> > outF; if (arr.size() < 1) return outF; // First make it a nice rectangle by adding filler points // This makes trimming it easier/neater int maxLen = arr[arr.size() - 1].size(); for (int i=0; i < arr.size(); i++) { while (arr[i].size() < maxLen) { KeyPoint k(0,0,0); arr[i].push_back(k); } } // Now we start firguring which features to keep for (int j=0; j < maxLen; j++) { // Loop through one feature across all its frames to see if it persists int numAppearances = 0; KeyPoint kp = arr[0][j]; for (int i=0; i < arr.size(); i++) { if (distFeature(kp, arr[i][j]) < 20 && arr[i][j].size > 0) { numAppearances++; } kp = arr[i][j]; } // If the feature is a good one, add it to the output if (numAppearances > arr.size() * threshhold){ for (int i=0; i < arr.size(); i++) { if (outF.size() <= i) { std::vector<KeyPoint> kpArr; kpArr.push_back(arr[i][j]); outF.insert(outF.begin(), kpArr); } else { outF[i].push_back(arr[i][j]); } } } } return outF; } // Sorts the array while keeping features aligned // Yes I know its an insertion sort. // If that bothers you, make a Pull Request std::vector<std::vector<KeyPoint> > sortFeatures(std::vector<std::vector<KeyPoint> > arr) { std::vector<std::vector<KeyPoint> > outF; if (arr.size() < 1 || arr[0].size() < 1) return outF; // Initialize output vector to be right number of frames for (int i=0; i < arr.size(); i++) { std::vector<KeyPoint> kpArr; outF.push_back(kpArr); } // Find element that should go last, add it, repeat while (arr[0].size() > 0) { int indexOfMin = 0; KeyPoint smallest = arr[0][0]; // Find which is smallest for (int i=0; i < arr[0].size(); i++) { if (arr[0][i].pt.x < smallest.pt.x || (arr[0][i].pt.x == smallest.pt.x && arr[0][i].pt.y < smallest.pt.y)) { indexOfMin = i; smallest = arr[0][i]; } } // Insert elements into 'outF' and remove them from 'arr' for (int i=0; i < arr.size(); i++) { outF[i].push_back(arr[i][indexOfMin]); arr[i].erase(arr[i].begin() + indexOfMin); } } return outF; } // Returns how dissimilar two points are // Based on location, size, and angle int calcDiff(KeyPoint a, KeyPoint b) { int dist = distFeature(a, b); int ds = abs(a.size - b.size); int da = abs(cos(a.angle) - cos(b.angle)); // Using cosine makes it so that 179 and -179 are close together return dist + ds + da*10; } // Returns % accuracy of feed more or less // Uses |(theoretical - actual) / theoretical| double calcPerformance(KeyPoint lib, KeyPoint feed) { double dist = calcDiff(lib, feed) / 20; double size, angle; if (lib.size != 0) size = abs(lib.size - feed.size) / lib.size; else size = dist; if (lib.angle != -1) angle = abs(lib.angle - feed.angle) / lib.angle; else angle = dist; return ANGLE_W*angle + SIZE_W*size + DIST_W*(1 - dist); } // Compare two matrices of features to see how similar they are double compareFeatures(std::vector<std::vector<KeyPoint> > lib, std::vector<std::vector<KeyPoint> > feed) { #if 0 int diff = 0; // Keeps track of how similar the two vectors are int numWrong = 0; //Keeps track of features that aren't in both // Resize feed to be the same number of frames as lib if (feed.size() > lib.size()) { feed.erase(feed.begin(), feed.begin() + (feed.size() - lib.size() - 1)); } if (lib.size() < 1 || feed.size() < 1) return 10000000; // Iterate through one array // Find the distance feedetween each feature and its closest counterpart for (int i=0; i < lib.size() && i < feed.size(); i++) { for (int j=0; j < lib[i].size(); j++) { // Find nearest feature from other array int distMin = 10000; KeyPoint nearest(0,0,0); for (int k=0; k < feed[i].size(); k++) { if (distFeature(lib[i][j], feed[i][k]) < distMin){ distMin = distFeature(lib[i][j], feed[i][k]); nearest = feed[i][k]; } } if (distMin > 30) diff += calcDiff(lib[i][j], nearest); else numWrong++; } } return diff; #else double performance = 0; double maxPerformance = 0; // Resize feed to be the same number of frames as lib if (feed.size() > lib.size()) { feed.erase(feed.begin(), feed.begin() + (feed.size() - lib.size())); } if (lib.size() < 1 || feed.size() < 1) return 0; // Iterate through one array // Find the distance feedetween each feature and its closest counterpart for (int i=0; i < lib.size() && i < feed.size(); i++) { for (int j=0; j < lib[i].size(); j++) { // Find nearest feature from other array int distMin = 10000; KeyPoint nearest(0,0,0); for (int k=0; k < feed[i].size(); k++) { if (distFeature(lib[i][j], feed[i][k]) < distMin){ distMin = distFeature(lib[i][j], feed[i][k]); nearest = feed[i][k]; } } if (distMin < 20) performance += calcPerformance(lib[i][j], nearest); maxPerformance++; } } return performance / maxPerformance; #endif } Mat combineImages(std::vector<Mat> images) { assert(images.size() >= 1); double weight = 1. / images.size(); Mat outImage = weight * images[0]; for (int i=1; i < images.size(); i++) { outImage += weight * images[i]; } return outImage; } void whichSound(double diffs[]) { // Find what the highest value is double highest = 0; for (int i=0; i < NUM_SOUNDS; i++) { if (diffs[i] > highest) highest = diffs[i]; } // Now figure out which letter has that value if (highest == diffs[NONE]) { printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM_~______\n"); } else if (highest == diffs[FF]) { printf("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__F_____\n"); } else if (highest == diffs[OO]) { printf("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO___O____\n"); } else if (highest == diffs[JJ]) { printf("JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ____J___\n"); } else if (highest == diffs[MM]) { printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM_____M__\n"); } else if (highest == diffs[TH]) { printf("THTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTH______TH\n"); } //printf("NONE: %.3f FF: %.3f OO: %.3f JJ: %.3f MM: %.3f TH: %.3f\n", diffs[NONE], diffs[FF], diffs[OO], diffs[JJ], diffs[MM], diffs[TH]); }
30.105882
139
0.648789
JoshVorick
7a0c65a7178771a71e152c0fe5e1d767fdc3287d
4,617
cpp
C++
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
1
2019-09-01T05:40:51.000Z
2019-09-01T05:40:51.000Z
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
null
null
null
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
null
null
null
// contains the code that controls the LCD screen #include "main.hpp" // what port the LCD screen goes into #define LCD_PORT uart1 // amount of milliseconds between each LCD update #define LCD_POLL_SPEED 100ul // the different types of things the LCD can do enum LoopState { // select the autonomous program AUTON_SELECT, // display primary/backup battery voltage DISPLAY_BATTERY, // control the lift from the LCD LIFT_CONTROL }; // tracks the state of the buttons class ButtonState { public: ButtonState(FILE* lcdPort): lcdPort(lcdPort), current(0), previous(0) {} // polls all the lcd buttons void poll() { previous = current; current = lcdReadButtons(lcdPort); } // checks if a button was pressed bool pressed(unsigned int button) const { return current & button; } // checks if a button was just pressed bool justPressed(unsigned int button) const { return pressed(button) && !(previous & button); } private: FILE* lcdPort; unsigned int current; unsigned int previous; }; // corresponds to state_t enum // takes a reference to the ButtonState, returns what the LoopState should be // changed to static LoopState autonSelect(const ButtonState& buttons); static LoopState displayBattery(const ButtonState& buttons); static LoopState liftControl(const ButtonState& buttons); // declared in main.hpp void lcd::controller(void*) { lcdInit(LCD_PORT); lcdClear(LCD_PORT); lcdSetBacklight(LCD_PORT, false); // the action that should be taken, kinda like a state machine LoopState loopState = LIFT_CONTROL; // tells loop functions what buttons are being pressed ButtonState buttons(LCD_PORT); // used for timing cyclic delays unsigned long time = millis(); while (true) { buttons.poll(); // do a different loop action based on loopState switch (loopState) { case AUTON_SELECT: loopState = autonSelect(buttons); break; case DISPLAY_BATTERY: loopState = displayBattery(buttons); break; case LIFT_CONTROL: loopState = liftControl(buttons); break; } // wait a bit before receiving input again taskDelayUntil(&time, LCD_POLL_SPEED); } } LoopState autonSelect(const ButtonState& buttons) { // so we don't have to type "auton::" 5 billion times using namespace auton; // used for printing the name of an autonomous program static const char* autonNames[AUTONID_MAX + 1] = { "Nothing", "Forward+Backward", "MG+Cone Left", "MG+Cone Right", "Score Stationary" }; // see if the left/right buttons were just pressed bool left = buttons.justPressed(LCD_BTN_LEFT); bool right = buttons.justPressed(LCD_BTN_RIGHT); // if left, go up the autonNames list if (left && !right) { autonid = (AutonID) (autonid - 1); if (autonid < AUTONID_MIN || autonid > AUTONID_MAX) { // go back to the end of the list autonid = AUTONID_MAX; } } // if right, go down the autonNames list else if (!left && right) { autonid = (AutonID) (autonid + 1); if (autonid < AUTONID_MIN || autonid > AUTONID_MAX) { // go back to the start of the list autonid = AUTONID_MIN; } } lcdSetText(LCD_PORT, 1, ROBOT_NAME " will do:"); lcdSetText(LCD_PORT, 2, autonNames[autonid]); // if auton selected or enabled by comp switch, start displaying battery if (buttons.justPressed(LCD_BTN_CENTER)) { return DISPLAY_BATTERY; } return AUTON_SELECT; } LoopState displayBattery(const ButtonState& buttons) { lcdPrint(LCD_PORT, 1, "Primary: %.1fV", powerLevelMain() / 1000.0f); lcdPrint(LCD_PORT, 2, "Backup: %.1fV", powerLevelBackup() / 1000.0f); if (buttons.justPressed(LCD_BTN_CENTER)) { return LIFT_CONTROL; } return DISPLAY_BATTERY; } LoopState liftControl(const ButtonState& buttons) { lcdPrint(LCD_PORT, 1, "lift pos = %.1f", motor::getLiftPos()); lcdSetText(LCD_PORT, 2, "v ^"); if (buttons.pressed(LCD_BTN_LEFT)) { motor::setLift(-127); } else if (buttons.pressed(LCD_BTN_RIGHT)) { motor::setLift(127); } else if (!isJoystickConnected(1)) { motor::setLift(0); } if (buttons.justPressed(LCD_BTN_CENTER)) { return AUTON_SELECT; } return LIFT_CONTROL; }
27.319527
77
0.633745
calhighrobotics
7a0db341149b2c2e860b1eb16612ac80ea171d69
3,086
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file ScalaFpgaRawHeader.hpp * * \copydoc Copyright * \author kd * \date Sep 17, 2015 *///------------------------------------------------------------------- #ifndef IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN #define IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/datablocks/snippets/Snippet.hpp> #include <ibeosdk/inttypes.hpp> #include <ibeosdk/misc/deprecatedwarning.hpp> #include <istream> #include <ostream> //====================================================================== namespace ibeosdk { //====================================================================== class ScalaFpgaRawHeader : public Snippet { public: static std::streamsize getSerializedSize_static() { return 16; } public: ScalaFpgaRawHeader(); virtual ~ScalaFpgaRawHeader(); public: //! Equality predicate bool operator==(const ScalaFpgaRawHeader& other) const; bool operator!=(const ScalaFpgaRawHeader& other) const; public: virtual std::streamsize getSerializedSize() const { return getSerializedSize_static(); } virtual bool deserialize(std::istream& is); virtual bool serialize(std::ostream& os) const; public: uint16_t getScanCounter() const { return m_scanCounter; } uint16_t getMinApdOffset() const { return m_minApdOffset; } uint16_t getMaxApdOffset() const { return m_maxApdOffset; } uint16_t getFrequencyInteger() const { return m_frequencyInteger; } uint16_t getFrequencyFractional() const { return m_frequencyFractional; } IBEOSDK_DEPRECATED uint16_t getFreqencyFractional() const { return m_frequencyFractional; } uint16_t getDeviceId() const { return m_deviceId; } public: void setScanCounter(const uint16_t scanCounter) { m_scanCounter = scanCounter; } IBEOSDK_DEPRECATED void setMminApdOffset(const uint16_t minApdOffset) {m_minApdOffset = minApdOffset; } void setMinApdOffset(const uint16_t minApdOffset) {m_minApdOffset = minApdOffset; } void setMaxApdOffset(const uint16_t maxApdOffset) { m_maxApdOffset = maxApdOffset; } void setFrequencyInteger(const uint16_t freqInteger) { m_frequencyInteger = freqInteger; } void setFrequencyFractional(const uint16_t freqFrac) { m_frequencyFractional = freqFrac; } IBEOSDK_DEPRECATED void setFreqencyFractional(const uint16_t freqFrac) { m_frequencyFractional = freqFrac; } void setDeviceId(const uint16_t deviceId) { m_deviceId = deviceId; } public: static const uint16_t blockId; protected: uint16_t m_scanCounter; uint16_t m_minApdOffset; uint16_t m_maxApdOffset; uint16_t m_frequencyInteger; uint16_t m_frequencyFractional; uint16_t m_deviceId; uint16_t m_reservedHeader7; }; // ScalaFpgaRawHeader //====================================================================== } // namespace ibeosdk //====================================================================== #endif // IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN //======================================================================
33.912088
109
0.647116
tomcamp0228
7a1035590685403ce70b496c3e2ead8986d64c4f
923
cpp
C++
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
// // Created by alexweiss on 8/14/19. // #include "AutoModeRunner.hpp" namespace auton { AutoModeRunner::AutoModeRunner() { thread_ = new pros::Task(AutoModeRunner::runAuton, this, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "AUTO RUNNER"); thread_->suspend(); } void AutoModeRunner::setAutoMode(std::shared_ptr<AutoModeBase> new_auto_mode) { mode_ = new_auto_mode; } void AutoModeRunner::start() { if(mode_) thread_->resume(); } void AutoModeRunner::stop() { if(mode_) thread_->suspend(); } std::shared_ptr<AutoModeBase> AutoModeRunner::getAutoMode() { return mode_; } void AutoModeRunner::runAuton(void* param) { AutoModeRunner* instance = static_cast<AutoModeRunner*>(param); instance->mode_->run(); while(1) pros::Task::delay(50); }; AutoModeRunner::AutoModeRunnerManager AutoModeRunner::instance; }
24.945946
83
0.668472
roboFiddle
7a182ec33426d72818a4bc08ef7e208dd9e30e9a
1,704
cpp
C++
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
/**----------------------------------------------------------------------------------------------------------------- * @file subscriber_client.cpp * @brief Send message to superline server, Implement with POSX.1 semaphore and shared memory * * Copyright (c) 2019-2019 Jim Zhang [email protected] *------------------------------------------------------------------------------------------------------------------ */ #include <superline/producer/superline_client.hpp> using namespace NS_SUPERLINE; /* -------------------------------------------------------------------------------------------------------------------- * * FUNCTIONS IMPLEMENT * -------------------------------------------------------------------------------------------------------------------- */ /** * @brief Send data to superline server (consumer) * @param[in] data * @param[in] size - size of the data * @param[out] None * @return None * @note 1. The client will block if superline has already full * 2. *** EACH DATA SIZE SHALL NOT LARGER THAN BLOCK SIZE **/ void superline_client::send( const void *data, int size ) { P(_shminfo.sem_0_spc); /**< Wating for free space on superline */ P(_shminfo.sem_wrmtx); /**< Multi-process mutex lock */ int _size = (size > _shminfo.m_head->_size)?(_shminfo.m_head->_size):(size); memmove(_shminfo.offset + _shminfo.m_head->wr_inx * _shminfo.m_head->_size, data, _size); _shminfo.m_head->wr_inx += 1; _shminfo.m_head->wr_inx %= (_shminfo.m_head->blocks); /**< Loop write */ V(_shminfo.sem_wrmtx); /**< Multi-process mutext unlock */ V(_shminfo.sem_1_spc); /**< Acc non-free space for superline */ return; }
34.77551
116
0.484155
Jim-CodeHub
7a188b7ccb884ffb7f1c2a4ef903d4997b126b47
37
cpp
C++
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
5
2021-10-19T18:30:43.000Z
2022-03-19T22:02:02.000Z
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
12
2022-03-09T13:40:21.000Z
2022-03-31T12:47:48.000Z
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
null
null
null
#include "PNGLastModificationTime.h"
18.5
36
0.837838
BitPaw
7a1b20619b66ea7e98af60ef3644e1f1899e607d
921
hpp
C++
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
1
2021-08-24T11:52:51.000Z
2021-08-24T11:52:51.000Z
// SPDX-License-Identifier: MIT // Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval #ifndef TRIANGULAR_RULE_H_V7Y5S #define TRIANGULAR_RULE_H_V7Y5S #include <zisa/config.hpp> #include <zisa/math/barycentric.hpp> #include <zisa/math/max_quadrature_degree.hpp> #include <zisa/memory/array.hpp> namespace zisa { struct TriangularRule { array<double, 1> weights; array<Barycentric2D, 1> points; TriangularRule(int_t n_points); TriangularRule(const TriangularRule &qr) = default; TriangularRule(TriangularRule &&qr) = default; }; /// Compute weights and quadrature points. /** * References: * [1] D.A. Dunavant, High degree efficient symmetrical Gaussian quadrature * rules for the triangle, 1985. */ TriangularRule make_triangular_rule(int_t deg); constexpr int_t MAX_TRIANGULAR_RULE_DEGREE = 5; const TriangularRule &cached_triangular_quadrature_rule(int_t deg); } // namespace zisa #endif
24.891892
77
0.765472
1uc
7a2739c116f4f730377e2f9ed25c37e9efe11126
3,807
cpp
C++
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
#include "Light.h" uint32_t ns::DirectionalLight::number_(0); uint32_t ns::PointLight::number_(0); uint32_t ns::SpotLight::number_(0); ns::LightBase_::LightBase_(const glm::vec3& color) { color_ = color; } void ns::LightBase_::setColor(const glm::vec3& color) { if (color.x < .0f || color.y < .0f || color.z < .0f) return; color_ = color; } const glm::vec3& ns::LightBase_::color() const { return color_; } ns::attenuatedLightBase_::attenuatedLightBase_(const glm::vec3& color, float attenuation) : LightBase_(color) { setAttenuation(attenuation); } void ns::attenuatedLightBase_::setAttenuation(float attenuationValue) { attenuation_ = std::max(attenuationValue, .0f); } float ns::attenuatedLightBase_::attenuationValue() { return attenuation_; } //-------------------------------- // directional light //-------------------------------- ns::DirectionalLight ns::DirectionalLight::nullDirectionalLightObject(glm::vec3(0, 1, 0), NS_BLACK); ns::DirectionalLight::DirectionalLight(const glm::vec3& direction, const glm::vec3& color) : LightBase_(color), DirectionalObject3d(glm::vec3(0), direction) { setDirection(direction); } void ns::DirectionalLight::send(const Shader& shader) { char name[18], buffer[40]; sprintf_s(name, "dirLights[%d]", number_); sprintf_s(buffer, "%s.direction", name); shader.set(buffer, glm::normalize(-direction())); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); number_++; } uint32_t ns::DirectionalLight::number() { return number_; } void ns::DirectionalLight::clear() { number_ = 0; } ns::DirectionalLight& ns::DirectionalLight::nullLight() { return nullDirectionalLightObject; } //-------------------------------- // point light //-------------------------------- ns::PointLight::PointLight(const glm::vec3& position, float attenuation, const glm::vec3& color) : attenuatedLightBase_(color, attenuation), Object3d(position) {} void ns::PointLight::send(const Shader& shader) { char name[20], buffer[42]; sprintf_s(name, "pointLights[%d]", number_); sprintf_s(buffer, "%s.position", name); shader.set(buffer, WorldPosition()); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); sprintf_s(buffer, "%s.attenuation", name); shader.set(buffer, attenuation_); number_++; } uint32_t ns::PointLight::number() { return number_; } void ns::PointLight::clear() { number_ = 0; } //-------------------------------- // spot light //-------------------------------- ns::SpotLight::SpotLight(const glm::vec3& position, float attenuation, const glm::vec3& color, const glm::vec3& direction, float innerAngle, float outerAngle) : attenuatedLightBase_(color, attenuation), DirectionalObject3d(position, direction) { setAngle(innerAngle, outerAngle); setDirection(direction); } void ns::SpotLight::setAngle(float innerAngle, float outerAngle) { innerCutOff_ = glm::cos(glm::radians(innerAngle)); outerCutOff_ = glm::cos(glm::radians(outerAngle)); } void ns::SpotLight::send(const Shader& shader) { char name[20], buffer[42]; sprintf_s(name, "spotLights[%d]", number_); sprintf_s(buffer, "%s.position", name); shader.set(buffer, WorldPosition()); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); sprintf_s(buffer, "%s.attenuation", name); shader.set(buffer, attenuation_); sprintf_s(buffer, "%s.direction", name); shader.set(buffer, glm::normalize(-direction())); sprintf_s(buffer, "%s.innerCutOff", name); shader.set(buffer, innerCutOff_); sprintf_s(buffer, "%s.outerCutOff", name); shader.set(buffer, outerCutOff_); number_++; } uint32_t ns::SpotLight::number() { return number_; } void ns::SpotLight::clear() { number_ = 0; } void ns::clearLights() { PointLight::clear(); DirectionalLight::clear(); SpotLight::clear(); }
20.917582
158
0.67481
nicolas92g
7a28ef1353726be2c5934ea8363add2c2c9dd997
304
cpp
C++
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
#include "fireFist.hpp" #include "Character.hpp" FireFist::FireFist(int fireDamage) : Skill("Fire fist"), m_fireDamage(fireDamage) {} void FireFist::Use(std::shared_ptr<Character> self, std::shared_ptr<Character> enemy) { noused(self); enemy->getDamage(m_fireDamage); }
21.714286
54
0.674342
snow482
7a299f471b1e2e2625c2c334cd4b9c5a65881633
803
hpp
C++
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
3
2021-10-09T03:24:57.000Z
2022-01-12T04:19:42.000Z
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
100
2019-10-01T05:29:03.000Z
2022-03-31T17:28:52.000Z
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
1
2021-11-29T20:46:15.000Z
2021-11-29T20:46:15.000Z
#pragma once #include "Membrane/Scene.hpp" #include <Clove/SubSystem.hpp> namespace clove { class EntityManager; } namespace membrane { /** * @brief The sub system that is active while the game is running. * Deliberately does not handle editor events to simulate the game running. */ class RuntimeSubSystem : public clove::SubSystem { //VARIABLES private: Scene currentScene; //FUNCTIONS public: RuntimeSubSystem(); Group getGroup() const override; void onAttach() override; clove::InputResponse onInputEvent(clove::InputEvent const &inputEvent) override { return clove::InputResponse::Ignored; } void onUpdate(clove::DeltaTime const deltaTime) override; void onDetach() override; }; }
25.09375
129
0.666252
AGarlicMonkey
7a2b93a436713b7ee3b72fb1487b459dbc6940bb
1,022
cpp
C++
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
65
2017-04-04T20:33:44.000Z
2019-12-02T23:06:58.000Z
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
46
2017-04-21T12:26:38.000Z
2019-12-15T05:31:47.000Z
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
51
2017-04-12T10:53:32.000Z
2019-11-20T13:05:54.000Z
#include <CorePCH.hpp> #include <Math/Plane.hpp> using namespace Poly; Plane::eObjectLocation Plane::GetAABoxLocation(const AABox& box) const { auto vertices = box.GetVertices(); eObjectLocation guessedLocation = GetPointLocation(vertices[0]); for (Vector vert : vertices) { eObjectLocation loc = GetPointLocation(vert); if (loc == eObjectLocation::INTERSECTS || loc != guessedLocation) return eObjectLocation::INTERSECTS; } // guess was ok return guessedLocation; } Plane::eObjectLocation Plane::GetPointLocation(const Vector& point) const { const float dot = (point - Point).Dot(Normal); if (dot > 0) return eObjectLocation::FRONT; else if (dot < 0) return eObjectLocation::BEHIND; else return eObjectLocation::INTERSECTS; } //------------------------------------------------------------------------------ namespace Poly { std::ostream & operator<<(std::ostream& stream, const Plane& rect) { return stream << "Plane[Point: " << rect.Point << " Normal: " << rect.Normal << " ]"; } }
23.767442
87
0.654599
PiotrMoscicki
7a39bf7245d2b1d2b4d008920dd168fea1f7a132
663
hpp
C++
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
#pragma once #include <string> namespace link { class Rtti { public: Rtti(const std::string name, const Rtti* base); ~Rtti(); const std::string get_name() const; bool is_exactly(const Rtti& type) const; bool is_derived(const Rtti& base_type) const; private: std::string name; const Rtti* base; }; } #define LINK_DECLARE_RTTI \ public: \ static const link::Rtti TYPE; \ virtual const link::Rtti& get_type () const { return TYPE; } #define LINK_IMPLEMENT_RTTI(nsname,classname,baseclassname) \ const link::Rtti classname::TYPE(#nsname"."#classname,&baseclassname::TYPE)
21.387097
79
0.641026
martinnnnnn
7a3b510d0854f26140d3a9cb16581bca1a4a9441
383
cc
C++
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
#include "console.h" using namespace std; void Console::Log(const char* str, const size_t& maxWidth) { char* x = new char[maxWidth]; for (size_t i = 0; i < maxWidth; i++) { if (*str != '\0') { x[i] = *str; str++; } else { x[i] = '.'; } } x[maxWidth - 1] = '\0'; cout << x; delete[] x; }
17.409091
60
0.420366
5aitama
7a3c4665b43702de0eb94923c656d96c0050dfb4
2,591
cpp
C++
tests/src/netlib/tests_port_layer.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2021-07-16T14:19:50.000Z
2021-07-16T14:19:50.000Z
tests/src/netlib/tests_port_layer.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2018-06-05T11:03:30.000Z
2018-06-05T11:03:30.000Z
tests/src/netlib/tests_port_layer.cpp
tum-ei-rcs/mart-common
6f8f18ac23401eb294d96db490fbdf78bf9b316c
[ "MIT" ]
null
null
null
#include <mart-netlib/port_layer.hpp> #include <catch2/catch.hpp> #include <iostream> namespace pl = mart::nw::socks::port_layer; namespace socks = mart::nw::socks; // call ech function at least once to ensure the implementation is there TEST_CASE( "net_port-layer_check_function_implementation_exists" ) { CHECK( pl::startup() ); [[maybe_unused]] auto nh = pl::to_native( pl::handle_t::Invalid ); [[maybe_unused]] int d = pl::to_native( socks::Domain::Inet ); [[maybe_unused]] int t = pl::to_native( socks::TransportType::Datagram ); [[maybe_unused]] int p = pl::to_native( socks::Protocol::Tcp ); socks::ReturnValue<pl::handle_t> ts = pl::socket( socks::Domain::Inet, socks::TransportType::Datagram, socks::Protocol::Default ); CHECK( ts.success() ); CHECK( ts.value_or( pl::handle_t::Invalid ) != pl::handle_t::Invalid ); pl::close_socket( ts.value_or( pl::handle_t::Invalid ) ); pl::handle_t s2 = pl::socket( socks::Domain::Inet, socks::TransportType::Datagram ).value_or( pl::handle_t::Invalid ); CHECK( s2 != pl::handle_t::Invalid ); pl::SockaddrIn addr{}; CHECK( set_blocking( s2, false ) ); CHECK( !accept( s2 ) ); CHECK( !accept( s2, addr ) ); // CHECK( connect( s2,addr ) ); // TODO: connect to empty works on some platforms but not on all connect( s2, addr ); // CHECK( !bind( s2, addr ) ); bind( s2, addr ); // CHECK( !listen( s2, 10 ) ); listen( s2, 10 ); } TEST_CASE( "net_port-layer_getaddrinfo" ) { CHECK( pl::startup() ); socks::AddrInfoHints hints{}; hints.flags = 0; hints.family = socks::Domain::Unspec; hints.socktype = socks::TransportType::Stream; auto info1 = pl::getaddrinfo( "www.google.de", "https", hints ); if( !info1.success() ) { std::cout << "Error in getaddrinfo:" << info1.error_code().raw_value() << std::endl; } CHECK( info1.success() ); auto& sockaddr_list = info1.value(); for( const auto& e : sockaddr_list ) { socks::ReturnValue<pl::handle_t> res = pl::socket( e.family, e.socktype, e.protocol ); CHECK( res.success() ); auto handle = res.value(); std::cout << "Connecting to (to_string) : " << pl::to_string( e.addr->to_Sockaddr() ) << std::endl; char buffer[30]{}; pl::inet_net_to_pres( e.addr->to_Sockaddr().to_native_ptr(), buffer, sizeof( buffer ) ); std::cout << "Connecting to (inet_net_to_pres): " << &( buffer[0] ) << std::endl; auto con_res = pl::connect( handle, e.addr->to_Sockaddr() ); if( !con_res.success() ) { std::cout << "Failed with error code: " << con_res.raw_value() << std::endl; } CHECK( pl::close_socket( handle ).success() ); } }
34.092105
112
0.656503
Mike-Bal
7a41ee456370b9225fbfc9cdc293ff95944e7a1a
371
cpp
C++
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
#include "nChooseKIterator.hpp" #include <algorithm> namespace treeDAG { namespace util { bool NChooseKProcessor::atEnd(const std::vector<bool> & mask) const { return mask.back(); } void NChooseKProcessor::increment(std::vector<bool> & mask) { mask.back() = !std::next_permutation(mask.begin(), mask.end() - 1); } } // util namespace } // treeDAG namespace
17.666667
71
0.695418
thomasfannes
7a439686fd6777a0a1e1ee0cd233eca26e0a0c8e
1,231
cpp
C++
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
#include <iostream> #include <RepeatedIn.h> #include <IndexError.h> #include <DblArr.h> #include <stdlib.h> #include <typeinfo> using namespace std; void tst(int n)throw(IndexError){ RepeatedIn ccin; DblArr x(n); int N; for(int i=0;i<n;i++) { x[i]=5.*rand()/RAND_MAX; } cout<<x<<endl; for(int i=0;i<5;i++){ try{ cout<<"index:";ccin>>N; cout<<"x["<<N<<"]="<<x[N]<<endl; } catch ( IndexError &e ){ throw e; }catch(...){ cerr<<"exception in tst() at line "<<__LINE__<<endl; throw; } } } int main( ) { int b; unsigned u; bool res = false; RepeatedIn ccin; do{ try { cout<<"Enter unsigned:"; ccin>>u; cout<<"Accepted: "<<u<<endl; b=__LINE__; tst(u); } catch ( IndexError &e ){ e.rep(cerr); cerr<<"Exception in main() at line "<<b<< " invoking tst("<<u<<")." <<endl; cerr << e.what( ) << " by "<< typeid( e ).name( ) << endl; res=true; } cout<<endl; if(res){res=!res;cout<<"Resumption:\n";} }while(1); return 0; }
20.180328
68
0.450853
Rossoner40
7a4616e9eac44cc3892e15d925e9ee5b4238b84e
955
hpp
C++
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
103
2016-02-08T21:04:11.000Z
2021-08-05T21:50:03.000Z
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
12
2015-12-29T23:53:52.000Z
2018-01-01T16:12:28.000Z
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
13
2016-02-24T12:25:31.000Z
2020-08-24T19:47:29.000Z
// Copyright (c) 2017-2019 nyorain // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #pragma once #ifndef NYTL_INCLUDE_FWD_RECT #define NYTL_INCLUDE_FWD_RECT #include <cstdlib> // std::size_t #include <cstdint> // std::uint8_t namespace nytl { template<std::size_t D, typename T> class Rect; template<typename T> using Rect2 = Rect<2, T>; template<typename T> using Rect3 = Rect<3, T>; template<typename T> using Rect4 = Rect<4, T>; using Rect2i = Rect<2, int>; using Rect2ui = Rect<2, unsigned int>; using Rect2f = Rect<2, float>; using Rect2d = Rect<2, double>; using Rect3i = Rect<3, int>; using Rect3ui = Rect<3, unsigned int>; using Rect3d = Rect<3, double>; using Rect3f = Rect<3, float>; using Rect4i = Rect<4, int>; using Rect4ui = Rect<4, unsigned int>; using Rect4d = Rect<4, double>; using Rect4f = Rect<4, float>; } #endif // header guard
24.487179
80
0.713089
nyorain
7a46d7a42f61926e7e19240bc46cdaee53253e0b
1,089
hpp
C++
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once /** * \brief Return a vector containing integers in the range [\p stt, \p stp) */ inline auto Range(int stt, int stp) { std::vector<int> range; range.reserve(std::abs(stp - stt) + 1); int stride = (stp - stt) >= 0 ? 1 : -1; for (int i = stt; i < stp; i += stride) { range.push_back(i); } return range; } /** * \brief Return a vector containing the integers in the interval [0, \p stp) */ inline auto Range(int stp) { return Range(0, stp); }
26.560976
77
0.673095
tp-ntouran
7a484eb8403730b712a19d67c78b3e9ee0f22cea
587
cpp
C++
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
76
2018-02-20T11:30:52.000Z
2022-03-31T12:45:06.000Z
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
27
2018-11-20T14:32:49.000Z
2021-11-24T15:26:45.000Z
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
24
2018-02-21T01:45:26.000Z
2022-03-07T07:06:49.000Z
// // OpenTissue, A toolbox for physical based simulation and animation. // Copyright (C) 2007 Department of Computer Science, University of Copenhagen // #include <OpenTissue/configuration.h> #define BOOST_AUTO_TEST_MAIN #include <OpenTissue/utility/utility_push_boost_filter.h> #include <boost/test/auto_unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/test_tools.hpp> #include <OpenTissue/utility/utility_pop_boost_filter.h> BOOST_AUTO_TEST_SUITE(opentissue_dynamics_multibody_mbd); BOOST_AUTO_TEST_CASE(no_test_yet) { } BOOST_AUTO_TEST_SUITE_END();
26.681818
78
0.819421
ricortiz
7a4a78300d55ccaea3f07104f1870a684a56764c
6,936
cpp
C++
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
11
2015-02-12T04:34:43.000Z
2021-10-10T06:24:55.000Z
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
null
null
null
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
8
2015-06-30T11:51:30.000Z
2021-10-10T06:24:56.000Z
// // testLayer.cpp // HelloCpp // // Created by Yang Chao (wantnon) on 13-11-6. // // #include "testLayer.h" bool CtestLayer::init(){ CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); CCSize winSize=CCDirector::sharedDirector()->getWinSize(); float ZEye=CCDirector::sharedDirector()->getZEye(); //enable touch setTouchEnabled( true ); //enable update scheduleUpdate(); //update eye pos updateEyePos(); //----------------------------- //root3d m_root3d=new Cc3dRoot(); m_root3d->autorelease(); m_root3d->init(); m_root3d->setNodeName("root3d"); this->addChild(m_root3d); //camera Cc3dCamera*camera=m_root3d->getCamera3D(); m_r=(winSize.height/2)/tanf(camera->getFovy()/2*M_PI/180); camera->setEyePos(cc3dv4(0, 0, m_r, 1)); camera->setCenter(cc3dv4(0, 0, 0, 1)); camera->setUp(cc3dv4(0, 1, 0, 0)); camera->setProjectionMode(ec3dPerspectiveMode); //lightSource Cc3dLightSource*lightSource=new Cc3dLightSource(); lightSource->autorelease(); lightSource->init(); m_root3d->addChild(lightSource); lightSource->setAmbient(cc3dv4(0.8, 0.8, 0.8, 1)); lightSource->setPosition3D(cc3dv4(600, 900, 1200, 1)); //program Cc3dProgram*program=c3dGetProgram_c3dClassicLighting(); //actor3D m_actor3D=c3dSimpleLoadActor("toolKitRes/model/apple_cfc"); m_actor3D->setLightSource(lightSource); m_actor3D->setCamera3D(camera); m_actor3D->setPassUnifoCallback(passUnifoCallback_classicLighting); m_actor3D->setProgram(program); m_actor3D->setNodeName("actor3D"); m_root3d->addChild(m_actor3D,0); m_actor3D->scale3D(4, 4, 4); m_actor3D->setPosition3D(Cc3dVector4(0,-130,0,1)); //submit m_actor3D->submit(GL_STATIC_DRAW); //controlButton_swithProjMode { CCScale9Sprite* btnUp=CCScale9Sprite::create("button.png"); CCScale9Sprite* btnDn=CCScale9Sprite::create("button_dn.png"); CCLabelTTF*title=CCLabelTTF::create("proj mode", "Helvetica", 30); CCControlButton* controlButton=CCControlButton::create(title, btnUp); controlButton->setBackgroundSpriteForState(btnDn,CCControlStateHighlighted); controlButton->setPreferredSize(CCSize(180,80)); controlButton->setPosition(ccp(400,100)); controlButton->addTargetWithActionForControlEvents(this, (SEL_CCControlHandler)(&CtestLayer::switchProjModeCallBack), CCControlEventTouchDown); this->addChild(controlButton); m_controlButton_swithProjMode=controlButton; } //controlButton_transform { CCScale9Sprite* btnUp=CCScale9Sprite::create("button.png"); CCScale9Sprite* btnDn=CCScale9Sprite::create("button_dn.png"); CCLabelTTF*title=CCLabelTTF::create("transform", "Helvetica", 30); CCControlButton* controlButton=CCControlButton::create(title, btnUp); controlButton->setBackgroundSpriteForState(btnDn,CCControlStateHighlighted); controlButton->setPreferredSize(CCSize(180,80)); controlButton->setPosition(ccp(700,100)); controlButton->addTargetWithActionForControlEvents(this, (SEL_CCControlHandler)(&CtestLayer::transformCallBack), CCControlEventTouchDown); this->addChild(controlButton); m_controlButton_transform=controlButton; } //projection mode label m_pLabel=CCLabelTTF::create("proj mode: Perspective", "Arial", 35); m_pLabel->setPosition(ccp(origin.x + visibleSize.width*(3.0/4), origin.y + visibleSize.height - m_pLabel->getContentSize().height-100)); this->addChild(m_pLabel, 1); return true; } void CtestLayer::updateEyePos(){ float cosA=cosf(m_A*M_PI/180); float sinA=sinf(m_A*M_PI/180); float cosB=cosf(m_B*M_PI/180); float sinB=sinf(m_B*M_PI/180); m_eyePos.setx(m_r*cosB*sinA); m_eyePos.sety(m_r*sinB); m_eyePos.setz(m_r*cosB*cosA); m_eyePos.setw(1); } void CtestLayer::switchProjModeCallBack(CCObject *senderz, cocos2d::extension::CCControlEvent controlEvent){ Cc3dCamera*camera=m_root3d->getCamera3D(); switch(camera->getProjectionMode()) { case ec3dPerspectiveMode:{ camera->setProjectionMode(ec3dOrthographicMode); m_pLabel->setString("proj mode: Orthographic"); }break; case ec3dOrthographicMode:{ camera->setProjectionMode(ec3dPerspectiveMode); m_pLabel->setString("proj mode: Perspective"); }break; } } void CtestLayer::transformCallBack(CCObject *senderz, CCControlEvent controlEvent){ if(m_isDoUpdate){ //restore inital matrix m_actor3D->setTransform3D(m_initialMat); //stop update m_isDoUpdate=false; }else{ //store inital matrix m_initialMat=m_actor3D->getTransform3D(); //start update m_isDoUpdate=true; } } void CtestLayer::update(float dt){ if(m_isDoUpdate==false)return; m_actor3D->rotate3D(cc3dv4(0, 1, 0, 0), 120*dt); } void CtestLayer::ccTouchesEnded(CCSet* touches, CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; } } void CtestLayer::ccTouchesMoved(cocos2d::CCSet* touches , cocos2d::CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; //----update eyePos m_A+=-(m_mosPos.x-m_mosPosf.x)*0.4; m_B+=(m_mosPos.y-m_mosPosf.y)*0.4; if(m_B>89.9)m_B=89.9; if(m_B<-89.9)m_B=-89.9; updateEyePos(); m_root3d->getCamera3D()->setEyePos(m_eyePos); } } void CtestLayer::ccTouchesBegan(CCSet* touches, CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //note: for 3d mode, CCDirector::convertToGL() not works as we expected // CCPoint pointInWinSpace = CCDirector::sharedDirector()->convertToGL(pointInWinSpace); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; } }
31.384615
151
0.643454
wantnon2
7a5844762dcaf766018b7c7ceef18282378acb4e
1,351
hpp
C++
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_MATH_FRACTIONAL_PART_HPP #define SPROUT_MATH_FRACTIONAL_PART_HPP #include <limits> #include <type_traits> #include <sprout/config.hpp> #include <sprout/math/detail/config.hpp> #include <sprout/math/integer_part.hpp> #include <sprout/type_traits/enabler_if.hpp> namespace sprout { namespace math { namespace detail { template< typename FloatType, typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR FloatType fractional_part(FloatType x) { return x == std::numeric_limits<FloatType>::infinity() || x == -std::numeric_limits<FloatType>::infinity() ? FloatType(0) : x == std::numeric_limits<FloatType>::quiet_NaN() ? std::numeric_limits<FloatType>::quiet_NaN() : x - sprout::math::integer_part(x) ; } template< typename IntType, typename sprout::enabler_if<std::is_integral<IntType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR double fractional_part(IntType x) { return sprout::math::detail::fractional_part(static_cast<double>(x)); } } // namespace detail using sprout::math::detail::fractional_part; } // namespace math using sprout::math::fractional_part; } // namespace sprout #endif // #ifndef SPROUT_MATH_FRACTIONAL_PART_HPP
31.418605
126
0.706884
osyo-manga
7a58da0624821c6e4c15b30faaf1535da7ef94da
17,586
cpp
C++
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
2
2022-01-01T22:26:57.000Z
2022-02-14T04:03:32.000Z
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
null
null
null
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
null
null
null
#include "TestFW.hpp" #include "Definitions.hpp" #include "BitBoardUtils.hpp" #include <cassert> #include "GameState.hpp" #include <vector> #include "MoveGeneration.hpp" namespace Tests { auto add_process_move_tests(TestFW::UnitTest &unit_tests) -> void { TestFW::TestCase process_move_test_case("Process Move"); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Kasparov vs. Topalov, Wijk aan Zee 1999", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "d7d6", "d2d4", "g8f6", "b1c3", "g7g6", "c1e3", "f8g7", "d1d2", "c7c6", "f2f3", "b7b5", "g1e2", "b8d7", "e3h6", "g7h6", "d2h6", "c8b7", "a2a3", "e7e5", "e1c1", "d8e7", "c1b1", "a7a6", "e2c1", "e8c8", "c1b3", "e5d4", "d1d4", "c6c5", "d4d1", "d7b6", "g2g3", "c8b8", "b3a5", "b7a8", "f1h3", "d6d5", "h6f4", "b8a7", "h1e1", "d5d4", "c3d5", "b6d5", "e4d5", "e7d6", "d1d4", "c5d4", "e1e7", "a7b6", "f4d4", "b6a5", "b2b4", "a5a4", "d4c3", "d6d5", "e7a7", "a8b7", "a7b7", "d5c4", "c3f6", "a4a3", "f6a6", "a3b4", "c2c3", "b4c3", "a6a1", "c3d2", "a1b2", "d2d1", "h3f1", "d8d2", "b7d7", "d2d7", "f1c4", "b5c4", "b2h8", "d7d3", "h8a8", "c4c3", "a8a4", "d1e1", "f3f4", "f7f5", "b1c1", "d3d2", "a4a7"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Morphy vs. Allies, Paris Opera 1858", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "e7e5", "g1f3", "d7d6", "d2d4", "c8g4", "d4e5", "g4f3", "d1f3", "d6e5", "f1c4", "g8f6", "f3b3", "d8e7", "b1c3", "c7c6", "c1g5", "b7b5", "c3b5", "c6b5", "c4b5", "b8d7", "e1c1", "a8d8", "d1d7", "d8d7", "h1d1", "e7e6", "b5d7", "f6d7", "b3b8", "d7b8", "d1d8"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Aronian vs. Anand, Wijk aan Zee 2013", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "d7d5", "c2c4", "c7c6", "g1f3", "g8f6", "b1c3", "e7e6", "e2e3", "b8d7", "f1d3", "d5c4", "d3c4", "b7b5", "c4d3", "f8d6", "e1g1", "e8g8", "d1c2", "c8b7", "a2a3", "a8c8", "f3g5", "c6c5", "g5h7", "f6g4", "f2f4", "c5d4", "e3d4", "d6c5", "d3e2", "d7e5", "e2g4", "c5d4", "g1h1", "e5g4", "h7f8", "f7f5", "f8g6", "d8f6", "h2h3", "f6g6", "c2e2", "g6h5", "e2d3", "d4e3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Karpov vs. Kasparov, World Championship 1985, game 16", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "c7c5", "g1f3", "e7e6", "d2d4", "c5d4", "f3d4", "b8c6", "d4b5", "d7d6", "c2c4", "g8f6", "b1c3", "a7a6", "b5a3", "d6d5", "c4d5", "e6d5", "e4d5", "c6b4", "f1e2", "f8c5", "e1g1", "e8g8", "e2f3", "c8f5", "c1g5", "f8e8", "d1d2", "b7b5", "a1d1", "b4d3", "a3b1", "h7h6", "g5h4", "b5b4", "c3a4", "c5d6", "h4g3", "a8c8", "b2b3", "g7g5", "g3d6", "d8d6", "g2g3", "f6d7", "f3g2", "d6f6", "a2a3", "a6a5", "a3b4", "a5b4", "d2a2", "f5g6", "d5d6", "g5g4", "a2d2", "g8g7", "f2f3", "f6d6", "f3g4", "d6d4", "g1h1", "d7f6", "f1f4", "f6e4", "d2d3", "e4f2", "f4f2", "g6d3", "f2d2", "d4e3", "d2d3", "c8c1", "a4b2", "e3f2", "b1d2", "c1d1", "b2d1", "e8e1",}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Byrne vs. Fischer, New York 1956", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"g1f3", "g8f6", "c2c4", "g7g6", "b1c3", "f8g7", "d2d4", "e8g8", "c1f4", "d7d5", "d1b3", "d5c4", "b3c4", "c7c6", "e2e4", "b8d7", "a1d1", "d7b6", "c4c5", "c8g4", "f4g5", "b6a4", "c5a3", "a4c3", "b2c3", "f6e4", "g5e7", "d8b6", "f1c4", "e4c3", "e7c5", "f8e8", "e1f1", "g4e6", "c5b6", "e6c4", "f1g1", "c3e2", "g1f1", "e2d4", "f1g1", "d4e2", "g1f1", "e2c3", "f1g1", "a7b6", "a3b4", "a8a4", "b4b6", "c3d1", "h2h3", "a4a2", "g1h2", "d1f2", "h1e1", "e8e1", "b6d8", "g7f8", "f3e1", "c4d5", "e1f3", "f2e4", "d8b8", "b7b5", "h3h4", "h7h5", "f3e5", "g8g7", "h2g1", "f8c5", "g1f1", "e4g3", "f1e1", "c5b4", "e1d1", "d5b3", "d1c1", "g3e2", "c1b1", "e2c3", "b1c1", "a2c2"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Ivanchuk vs. Yusupov, Brussels 1991", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"c2c4", "e7e5", "g2g3", "d7d6", "f1g2", "g7g6", "d2d4", "b8d7", "b1c3", "f8g7", "g1f3", "g8f6", "e1g1", "e8g8", "d1c2", "f8e8", "f1d1", "c7c6", "b2b3", "d8e7", "c1a3", "e5e4", "f3g5", "e4e3", "f2f4", "d7f8", "b3b4", "c8f5", "c2b3", "h7h6", "g5f3", "f6g4", "b4b5", "g6g5", "b5c6", "b7c6", "f3e5", "g5f4", "e5c6", "e7g5", "a3d6", "f8g6", "c3d5", "g5h5", "h2h4", "g6h4", "g3h4", "h5h4", "d5e7", "g8h8", "e7f5", "h4h2", "g1f1", "e8e6", "b3b7", "e6g6", "b7a8", "h8h7", "a8g8", "h7g8", "c6e7", "g8h7", "e7g6", "f7g6", "f5g7", "g4f2", "d6f4", "h2f4", "g7e6", "f4h2", "d1b1", "f2h3", "b1b7", "h7h8", "b7b8", "h2b8", "g2h3", "b8g3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Short vs. Timman, Tilburg 1991", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "g8f6", "e4e5", "f6d5", "d2d4", "d7d6", "g1f3", "g7g6", "f1c4", "d5b6", "c4b3", "f8g7", "d1e2", "b8c6", "e1g1", "e8g8", "h2h3", "a7a5", "a2a4", "d6e5", "d4e5", "c6d4", "f3d4", "d8d4", "f1e1", "e7e6", "b1d2", "b6d5", "d2f3", "d4c5", "e2e4", "c5b4", "b3c4", "d5b6", "b2b3", "b6c4", "b3c4", "f8e8", "e1d1", "b4c5", "e4h4", "b7b6", "c1e3", "c5c6", "e3h6", "g7h8", "d1d8", "c8b7", "a1d1", "h8g7", "d8d7", "e8f8", "h6g7", "g8g7", "d1d4", "a8e8", "h4f6", "g7g8", "h3h4", "h7h5", "g1h2", "e8c8", "h2g3", "c8e8", "g3f4", "b7c8", "f4g5"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Bai Jinshi vs. Ding Liren, Chinese League 2017", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "g8f6", "c2c4", "e7e6", "b1c3", "f8b4", "g1f3", "e8g8", "c1g5", "c7c5", "e2e3", "c5d4", "d1d4", "b8c6", "d4d3", "h7h6", "g5h4", "d7d5", "a1d1", "g7g5", "h4g3", "f6e4", "f3d2", "e4c5", "d3c2", "d5d4", "d2f3", "e6e5", "f3e5", "d4c3", "d1d8", "c3b2", "e1e2", "f8d8", "c2b2", "c5a4", "b2c2", "a4c3", "e2f3", "d8d4", "h2h3", "h6h5", "g3h2", "g5g4", "f3g3", "d4d2", "c2b3", "c3e4", "g3h4", "b4e7", "h4h5", "g8g7", "h2f4", "c8f5", "f4h6", "g7h7", "b3b7", "d2f2", "h6g5", "a8h8", "e5f7", "f5g6", "h5g4", "c6e5"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Rotlewi vs. Rubinstein, Lodz 1907", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "d7d5", "g1f3", "e7e6", "e2e3", "c7c5", "c2c4", "b8c6", "b1c3", "g8f6", "d4c5", "f8c5", "a2a3", "a7a6", "b2b4", "c5d6", "c1b2", "e8g8", "d1d2", "d8e7", "f1d3", "d5c4", "d3c4", "b7b5", "c4d3", "f8d8", "d2e2", "c8b7", "e1g1", "c6e5", "f3e5", "d6e5", "f2f4", "e5c7", "e3e4", "a8c8", "e4e5", "c7b6", "g1h1", "f6g4", "d3e4", "e7h4", "g2g3", "c8c3", "g3h4", "d8d2", "e2d2", "b7e4", "d2g2", "c3h3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Geller vs. Euwe, Zurich 1953", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "g8f6", "c2c4", "e7e6", "b1c3", "f8b4", "e2e3", "c7c5", "a2a3", "b4c3", "b2c3", "b7b6", "f1d3", "c8b7", "f2f3", "b8c6", "g1e2", "e8g8", "e1g1", "c6a5", "e3e4", "f6e8", "e2g3", "c5d4", "c3d4", "a8c8", "f3f4", "a5c4", "f4f5", "f7f6", "f1f4", "b6b5", "f4h4", "d8b6", "e4e5", "c4e5", "f5e6", "e5d3", "d1d3", "b6e6", "d3h7", "g8f7", "c1h6", "f8h8", "h7h8", "c8c2", "a1c1", "c2g2", "g1f1", "e6b3", "f1e1", "b3f3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 1", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "b8a6", "d1h5", "a6b4", "f1c4", "b4c2", "e1d1", "c2e3", "d2e3", "d7d5", "c4d5", "c8e6", "c1d2", "d8d7", "d5e6", "e8d8", "e6d7"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 2", []() { GameState game_state; std::vector<std::string> moves{"e2e4", "g8h6", "d2d4", "h6f5", "e4f5"}; for (std::size_t i = 0; i < moves.size(); i += 2) { game_state.init(); for (std::size_t j = 0; j <= i; j++) { auto move = moves[j]; TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 3", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "b8c6", "d2d4", "d7d5", "e4d5", "d8d5", "g1f3", "d5e4", "d1e2", "e4e2", "f1e2", "c8g4", "b1c3", "a8d8", "c1e3", "d8d6", "e1c1", "g4h3", "g2h3"}; bool rook_moved = false; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); if (!rook_moved && game_state.has_rook_A_moved<Colors::BLACK>()) { rook_moved = true; } else if (rook_moved) { TFW_ASSERT_EQ(true, game_state.has_rook_A_moved<Colors::BLACK>()); } } TFW_ASSERT_EQ(true, game_state.has_rook_A_moved<Colors::BLACK>()); std::string illegal_black_queen_side_castle = "e8c8"; TFW_ASSERT_EQ(false, GameUtils::process_user_move(game_state, illegal_black_queen_side_castle)); })); unit_tests.test_cases.push_back(process_move_test_case); } }
66.362264
119
0.387808
eunmann
7a5a717b88036f76c2144b9d9dfbc4b3d47c7ece
7,250
cc
C++
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
null
null
null
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
1
2021-03-02T17:12:23.000Z
2021-03-02T17:12:23.000Z
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
null
null
null
/// \file the ila example of svma accelerator: /// support vector machine accelerator for biomedical purposes, // receives MMIO instruction /// Isabel Greene ([email protected]) /// #include <ilang/ilang++.h> #include <svma_ila.h> #include <ilang/util/log.h> namespace ilang { namespace svma { Ila GetSVMAIla(const std::string& model_name) { // construct the model auto m = ilang::Ila("SVMA"); std::cout << "made svma\n"; // inputs m.NewBvInput("mode", 1); m.NewBvInput("addr_in", 32); m.NewBvInput("data_in", 32); // internal arch state m.NewBvState("base_addr_sv", 32); m.NewBvState("base_addr_tv", 32); m.NewBvState("tau", 32); m.NewBvState("c", 32); m.NewBvState("b", 32); m.NewBvState("fv_dim", 32); m.NewBvState("num_sv", 32); m.NewBvState("th", 32); m.NewBvState("shift1", 8); m.NewBvState("shift2", 8); m.NewBvState("shift3", 8); m.NewBvState("cmd_bits", 16); // the memory m.NewMemState("mem", 32, 32); // the output m.NewBvState("score", 32); m.NewBvState("output_proc", 32); // internal state m.NewBvState("run_svma", 1); m.NewBvState("interrupt_enable", 1); m.NewBvState("reformulation", 1); m.NewBvState("kernel", 2); m.NewBvState("order_poly", 1); m.NewBvState("output", 1); m.NewBvState("done", 1); m.NewBvState("child_state", 2); m.AddInit(m.state("child_state") == 0); std::cout << "declared all the state\n"; m.SetValid(m.input("addr_in") >= 0x0000 & m.input("addr_in") < 0x25C2); std::cout << "did the valid\n"; { // SVM_SV_BASEADDR_L std::cout << "inside SVM_SV_BASEADDR\n"; auto instr = m.NewInstr("SVM_SV_BASEADDR"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A4)); instr.SetUpdate(m.state("base_addr_sv"), m.input("data_in")); } { // SVM_TV_BASEADDR_L std::cout << "inside SVM_TV_BASEADDR\n"; auto instr = m.NewInstr("SVM_TV_BASEADDR"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A8)); instr.SetUpdate(m.state("base_addr_tv"), m.input("data_in")); } { // SVM_GAMMA (tau) std::cout << "inside SVM_GAMMA \n"; auto instr = m.NewInstr("SVM_GAMMA"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AA)); instr.SetUpdate(m.state("tau"), m.input("data_in")); } { // SVM_C std::cout << "inside SVM_C\n"; auto instr = m.NewInstr("SVM_C"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AC)); instr.SetUpdate(m.state("c"), m.input("data_in")); } { // SVM_B std::cout << "inside SVM_B\n"; auto instr = m.NewInstr("SVM_B"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AE)); instr.SetUpdate(m.state("b"), m.input("data_in")); } { // SVM_FV_DIM std::cout << "inside SVM_FV_DIM\n"; auto instr = m.NewInstr("SVM_FV_DIM"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B0)); // instr.SetUpdate(m.state("fv_dim"), m.input("data_in")); } { // SVM_NUMSV std::cout << "inside SVM_NUMSV\n"; auto instr = m.NewInstr("SVM_NUMSV"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B2)); instr.SetUpdate(m.state("num_sv"), m.input("data_in")); } { // SVM_SHIFT12 std::cout << "inside SVM_SHIFT12\n"; auto instr = m.NewInstr("SVM_SHIFT12"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B4)); instr.SetUpdate(m.state("shift1"), Extract(m.input("data_in"), 7, 0)); instr.SetUpdate(m.state("shift2"), Extract(m.input("data_in"), 15, 8)); } { // SVM_SHIFT3 std::cout << "inside SVM_SHIFT3\n"; auto instr = m.NewInstr("SVM_SHIFT3"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B6)); instr.SetUpdate(m.state("shift3"), Extract(m.input("data_in"), 7, 0)); } { // SVM_TH std::cout << "inside SVM_TH\n"; auto instr = m.NewInstr("SVM_TH"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B8)); instr.SetUpdate(m.state("th"), m.input("data_in")); } { // SVM_CMD_STATUS std::cout << "inside SVM_CMD_STATUS\n"; auto instr = m.NewInstr("SVM_CMD_STATUS"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A0)); // child valid bit instr.SetUpdate(m.state("run_svma"), SelectBit(m.input("data_in"), 7)); // child decode bits instr.SetUpdate(m.state("interrupt_enable"), SelectBit(m.input("data_in"), 6)); instr.SetUpdate(m.state("reformulation"), SelectBit(m.input("data_in"), 5)); instr.SetUpdate(m.state("kernel"), Extract(m.input("data_in"), 4, 3)); instr.SetUpdate(m.state("order_poly"), SelectBit(m.input("data_in"), 2)); DefineLinearChild(m); DefineLinearReformChild(m); DefineTwoPolyChild(m); DefineTwoPolyReformChild(m); DefineFourPolyChild(m); DefineRBFChild(m); } { // SVM_STORE_DATA std::cout << "inside STORE_DATA\n"; auto instr = m.NewInstr("STORE_DATA"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") < 0x25A2)); auto update_memory_at_addrin = Store(m.state("mem"), m.input("addr_in"), m.input("data_in")); instr.SetUpdate(m.state("mem"), update_memory_at_addrin); std::cout << "outside STORE_DATA\n"; } { // SVM_CMD_STATUS std::cout << "inside SVM_CMD_STATUS_OUT\n"; auto instr = m.NewInstr("SVM_CMD_STATUS_OUT"); instr.SetDecode((m.input("mode") == 0) & (m.input("addr_in") == 0x25A0)); auto combined = Concat(m.state("done"), m.state("output")); instr.SetUpdate(m.state("output_proc"), Concat(BvConst(0, 30), combined)); } { // SVM_SCORE std::cout << "inside SVM_SCORE\n"; auto instr = m.NewInstr("SVM_SCORE"); instr.SetDecode((m.input("mode") == 0) & (m.input("addr_in") == 0x25BA)); instr.SetUpdate(m.state("output_proc"), m.state("score")); } return m; } }; };
30.590717
105
0.50331
igreene2
7a61c19f1895879ada93ff5139c44c67c1dc87a3
1,803
cpp
C++
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
#include "tileset_glfw/textures.h" #include <iostream> #include <GLFW/glfw3.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace opengl { namespace { std::map<std::string, const assets::tileset*> tilesets; // TODO: !!! std::map<std::pair<std::string, std::string>, std::tuple<int, int, void*>> images; } void add(const std::string& id, const assets::tileset& tileset) { tilesets.emplace(std::make_pair(id, &tileset)); } void* get_texture(const std::string& tileset, const std::string& id, int& width, int& height) { auto it_images = images.find(std::make_pair(tileset, id)); if (it_images != images.end()) { width = std::get<0>(it_images->second); height = std::get<1>(it_images->second); return std::get<2>(it_images->second); } auto it = tilesets.find(tileset); if (it != tilesets.end()) { auto tile = it->second->get(id); unsigned char* image_data = stbi_load(tile.filename.c_str(), &width, &height, NULL, 4); GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); void* ret = (void*)(intptr_t)my_opengl_texture; images[std::make_pair(tileset, id)] = std::make_tuple(width, height, ret); return ret; } throw std::runtime_error("Tileset (or tile) not found"); } }
37.5625
109
0.622296
sword-and-sorcery
7a64f46225b59710178fb26e1fc9e32b985119ee
663
cpp
C++
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
#include <tdme/gui/nodes/GUINode_Flow.h> #include <string> #include <tdme/utils/Enum.h> using std::string; using tdme::gui::nodes::GUINode_Flow; using tdme::utils::Enum; GUINode_Flow::GUINode_Flow(const string& name, int ordinal) : Enum(name, ordinal) { } GUINode_Flow* tdme::gui::nodes::GUINode_Flow::INTEGRATED = new GUINode_Flow("INTEGRATED", 0); GUINode_Flow* tdme::gui::nodes::GUINode_Flow::FLOATING = new GUINode_Flow("FLOATING", 1); GUINode_Flow* GUINode_Flow::valueOf(const string& a0) { if (FLOATING->getName() == a0) return FLOATING; if (INTEGRATED->getName() == a0) return INTEGRATED; // TODO: throw exception here maybe return nullptr; }
23.678571
93
0.731523
mahula
7a654faac16def890e44cd51be734a7e23df592b
8,208
cc
C++
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 Garratt Gallagher. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpio.h" #include "grainfather2.h" #include "brew_session.h" #include <utility> #include <deque> #include <mutex> #include <list> #include <functional> #include <iostream> using std::placeholders::_1; using std::placeholders::_2; int BrewSession::InitSession(const char *spreadsheet_id) { printf("Initializing session\n"); // ------------------------------------------------------------------ // Initialize the logger, which reads from the google sheet int logger_status = brew_logger_.SetSession(spreadsheet_id); if (logger_status < 0) { printf("Failed to set session\n"); return -1; } if (logger_status > 0) { printf("Restarting sessions currently not supported\n"); return -1; } brew_recipe_ = brew_logger_.ReadRecipe(); // Start Scale Loop if(scale_.InitLoop(std::bind(&BrewSession::OnScaleError, this)) < 0) { printf("Scale did not initialize correctly\n"); return -1; } // Log the weight every 10 seconds scale_.SetPeriodicWeightCallback(10*1000*1000, std::bind(&BrewLogger::LogWeight, &brew_logger_, _1, _2)); // Set the function that the winch controller uses to see if it should abort movement winch_controller_.SetAbortCheck(std::bind(&ScaleFilter::HasKettleLifted, &scale_)); // ------------------------------------------------------------------ // Initialize the Grainfather serial interface // Make sure things are working if (grainfather_serial_.Init(std::bind(&BrewLogger::LogBrewState, &brew_logger_, _1)) < 0) { printf("Grainfather connection did not initialize correctly\n"); return -1; } if(grainfather_serial_.TestCommands() < 0) { printf("Grainfather serial interface did not pass tests.\n"); return -1; } // Load Recipe from spreadsheet // Connect to Grainfather // Load Session if(grainfather_serial_.LoadSession(brew_recipe_.GetSessionCommand().c_str())) { std::cout<<"Failed to Load Brewing Session into Grainfather. Exiting" <<std::endl; return -1; } drain_duration_s_ = brew_logger_.GetDrainTime() * 60; // Okay, initializations complete! printf("Initialization complete.\n"); return 0; } int BrewSession::PrepareSetup() { user_interface_.PleaseFillWithWater(brew_recipe_.initial_volume_liters); printf("Initializing session\n"); brew_logger_.LogWeightEvent(WeightEvent::InitWater, scale_.GetWeightStartingNow()); if (grainfather_serial_.HeatForMash()) return -1; user_interface_.PleaseAddHops(brew_recipe_.hops_grams, brew_recipe_.hops_type); user_interface_.PleasePositionWinches(); // Get weight with water and winch brew_logger_.LogWeightEvent(WeightEvent::InitRig, scale_.GetWeightStartingNow()); std::cout << "Waiting for temp. " << std::endl; while (!grainfather_serial_.IsMashTemp()) { // wait for temperature usleep(1000000); // sleep a second } // The OnMashTemp should just turn the buzzer off. user_interface_.PleaseAddGrain(); // Take weight with grain brew_logger_.LogWeightEvent(WeightEvent::InitGrain, scale_.GetWeightStartingNow()); if(user_interface_.PleaseFinalizeForMash()) return -1; // Okay, we are now ready for Automation! return 0; } int BrewSession::Mash() { if (grainfather_serial_.StartMash()) return -1; // Sleep while the pump starts SleepSeconds(5); //Watch for draining scale_.EnableDrainingAlarm(std::bind(&BrewSession::OnDrainAlarm, this)); while (!grainfather_serial_.IsMashDone()) { // wait for mash to complete SleepSeconds(1); // TODO: debug prints // std::cout << "Waiting for temp. Target: " << full_state_.state.target_temp; // std::cout << " Current: " << full_state_.state.current_temp << std::endl; } return 0; } void BrewSession::Fail(const char *segment) { std::cout << "Encountered Failure during " << segment; std::cout << " stage." << std::endl; GlobalPause(); } void BrewSession::GlobalPause() { // TODO: figure out how to pause timer, how to interrupt other waits // if (full_state_.state.timer_on) { // grainfather_serial_.PauseTimer(); // } TurnPumpOff(); grainfather_serial_.TurnHeatOff(); // tweet out a warning! } // Shut everything down because of error. void BrewSession::QuitSession() { GlobalPause(); grainfather_serial_.QuitSession(); } int BrewSession::Drain() { // std::cout << "Triggered: Mash is completed" << std::endl; // TODO: debug print if (grainfather_serial_.StartSparge()) return -1; // Might as well turn off valves: if (TurnPumpOff()) return -1; brew_logger_.LogWeightEvent(WeightEvent::AfterMash, scale_.GetWeightStartingNow()); // Now we wait for a minute or so to for fluid to drain from hoses SleepMinutes(1); // Raise a little bit to check that we are not caught if (winch_controller_.RaiseToDrain_1() < 0) return -1; SleepSeconds(3); if (scale_.HasKettleLifted()) { std::cout << "We lifted the kettle!" << std::endl; return -1; } // TODO: wait any more? // Raise the rest of the way std::cout << "RaiseStep2" << std::endl; if (winch_controller_.RaiseToDrain_2()) return -1; SleepMinutes(1); // After weight has settled from lifting the mash out brew_logger_.LogWeightEvent(WeightEvent::AfterLift, scale_.GetWeightStartingNow()); // Drain for 45 minutes // TODO: detect drain stopping SleepMinutes(drain_duration_s_); std::cout << "Draining is complete" << std::endl; brew_logger_.LogWeightEvent(WeightEvent::AfterDrain, scale_.GetWeightStartingNow()); if (winch_controller_.MoveToSink()) return -1; return 0; } // When Mash complete // Pump Off, valves closed // measure after_mash_weight, tweet loss // wait for minute, raise // wait 45 minutes // move to sink // advance to boil int BrewSession::Boil() { if (grainfather_serial_.HeatToBoil()) return -1; while (!grainfather_serial_.IsBoilTemp()) { // wait for Boil temp usleep(1000000); // sleep a second } std::cout << "Boiling Temp reached" << std::endl; if (winch_controller_.LowerHops()) return -1; //Watch for draining, because we are opening the valves if(PumpToKettle()) return -1; if (grainfather_serial_.StartBoil()) return -1; while (!grainfather_serial_.IsBoilDone()) { // wait for Boil temp usleep(1000000); // sleep a second } if(TurnPumpOff()) return -1; if (grainfather_serial_.QuitSession()) return -1; // Wait one minute before raising hops for lines to drain SleepMinutes(1); if (winch_controller_.RaiseHops()) return -1; SleepMinutes(1); // sleep for 1 minute to drain brew_logger_.LogWeightEvent(WeightEvent::AfterBoil, scale_.GetWeightStartingNow()); return 0; } int BrewSession::Decant() { std::cout << "Decanting" << std::endl; if (PumpToCarboy()) return -1; ActivateChillerPump(); while (!scale_.CheckEmpty()) { // wait kettle to empty usleep(500000); // sleep .5 second } DeactivateChillerPump(); if (TurnPumpOff()) return -1; return 0; } // TODO: make a function that handles the pump serial, valve status // and scale callbacks int BrewSession::TurnPumpOff() { SetFlow(NO_PATH); if (grainfather_serial_.TurnPumpOff()) return -1; // with the valves shut, can safely stop worrying about draining for the moment scale_.DisableDrainingAlarm(); return 0; } int BrewSession::PumpToKettle() { SetFlow(KETTLE); if (grainfather_serial_.TurnPumpOn()) return -1; scale_.EnableDrainingAlarm(std::bind(&BrewSession::OnDrainAlarm, this)); return 0; } int BrewSession::PumpToCarboy() { scale_.DisableDrainingAlarm(); SetFlow(CHILLER); if (grainfather_serial_.TurnPumpOn()) return -1; return 0; } int BrewSession::Run(const char *spreadsheet_id) { if (InitSession(spreadsheet_id)) { Fail("Init"); return -1; } if (PrepareSetup()) { Fail("Prepare"); return -1; } if (Mash()) { Fail("Mash"); return -1; } if (Drain()) { Fail("Drain"); return -1; } if (Boil()) { Fail("Boil"); return -1; } if (Decant()) { Fail("Decant"); return -1; } std::cout << "Brew finished with no problems!" << std::endl; return 0; }
32.442688
94
0.691399
garratt
7a66925f148b9c18dd2659af0b13cc577c79237c
2,739
cpp
C++
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-07-21T07:04:08.000Z
2021-07-21T07:04:08.000Z
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-08-07T12:46:32.000Z
2021-08-15T13:19:33.000Z
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-08-07T13:05:33.000Z
2021-08-07T13:05:33.000Z
#include<iostream> //.........................................................................Class Definition For Row class Block{ private: // Private Access Specifier Scope int Page_Number; int Status; public: // Public Access Specifier Scope void Set_PN(int); void Set_ST(int); int Get_PN(); int Get_ST(); }; //.......................................................................Class Definition for Frame class Frame{ private: // Private Access Specifier Scope int N, i; Block *frm; public: //.......................Function Decleration Frame(int); void Flush(); bool Full_Frame(); // 'true' when Frame is Full else returns 'false' void Add_Page(int, int); // Add Block at the end of the Queue void Disp_Frame(); // Display the Frame Components /*Returns 1 when target page is not found else 0*/ int Page_Replace(int, int, int); // Page_Replace Fucntion void FIFO(int [], int); // FIFO Page Replacement Algorithm void Incr_Stat(); // Increment the Statuses by 1 bool Search_Page(int, int &); void Set_ST_Index(int, int); int Find_Max_Stat(); // Return the target Page Number having maximum status void operator =(Frame); void Set_ST_Optimal(int[], int, int); // Set Status Optimal Function Sets the Status of the Frames acording to the Optimal Strategy }; //.......................................................................Result Class class Result{ private : // Private Scope int N; int fs; bool *H_M; // Hit_Miss_Array if 'true' then Hit else Miss Frame **Val_Frm; public: // Public Scope Result(int, int); void Ins_Res(int, bool, Frame); void Hit_Miss(int); void print_frm(int); }; //........................................................................Replace Class class Rplc{ private: //............Private Scope int Frame_Size; int *A=NULL; int N; float AT_FIFO, AT_LRU, AT_Optimal; // Access Time for every Algorithms Frame *f=NULL; Result *Res=NULL; public: //............Public Scope Rplc(int); void Insert_Page(int); void Print_Result(int); int FIFO(); // Returns the total Number of Page Faults (FIFO) int LRU(); // Returns the total Number of Page Faults (LRU) int Optimal(); // Returns the total Number of Page Faults (Optimal Page Replacement Algorithm) void Find_Access_Time(float, float); void Print_AT(); };
33.814815
140
0.514421
Siddhartha-Dhar
7a675430737d89d7246a9bdddf02cfadbae35e5e
3,928
hpp
C++
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
#pragma once /*! \file function.hpp \brief Function classes declarations. \author Garth Santor \date 2021-10-29 \copyright Garth Santor, Trinh Han ============================================================= Declarations of the Function classes derived from Operation. Includes the subclasses: OneArgFunction Abs Arccos Arcsin Arctan Ceil Cos Exp Floor Lb Ln Log Result Sin Sqrt Tan TwoArgFunction Arctan2 Max Min Pow ThreeArgFunction ============================================================= Revision History ------------------------------------------------------------- Version 2021.10.02 C++ 20 validated Version 2019.11.05 C++ 17 cleanup Version 2016.11.02 Added 'override' keyword where appropriate. Version 2014.10.30 Removed binary function Version 2012.11.13 C++ 11 cleanup Version 2009.11.26 Alpha release. ============================================================= Copyright Garth Santor/Trinh Han The copyright to the computer program(s) herein is the property of Garth Santor/Trinh Han, Canada. The program(s) may be used and/or copied only with the written permission of Garth Santor/Trinh Han or in accordance with the terms and conditions stipulated in the agreement/contract under which the program(s) have been supplied. =============================================================*/ #include <ee/operation.hpp> #include <ee/integer.hpp> #include <vector> /*! Function token base class. */ class Function : public Operation { }; /*! One argument function token base class. */ class OneArgFunction : public Function { public: [[nodiscard]] virtual unsigned number_of_args() const override { return 1; } }; /*! Absolute value function token. */ class Abs : public OneArgFunction { }; /*! arc cosine function token. */ class Arccos : public OneArgFunction { }; /*! arc sine function token. */ class Arcsin : public OneArgFunction { }; /*! arc tangent function token. Argument is the slope. */ class Arctan : public OneArgFunction { }; /*! ceil function token. */ class Ceil : public OneArgFunction { }; /*! cosine function token. */ class Cos : public OneArgFunction { }; /*! exponential function token. pow(e,x), where 'e' is the euler constant and 'x' is the exponent. */ class Exp : public OneArgFunction { }; /*! floor function token. */ class Floor : public OneArgFunction { }; /*! logarithm base 2 function token. */ class Lb : public OneArgFunction { }; /*! natural logarithm function token. */ class Ln : public OneArgFunction { }; /*! logarithm base 10 function token. */ class Log : public OneArgFunction { }; /*! previous result token. Argument is the 1-base index of the result. */ class Result : public OneArgFunction { }; /*! sine function token. */ class Sin : public OneArgFunction { }; /*! Square root token. */ class Sqrt : public OneArgFunction { }; /*! tangeant function. */ class Tan : public OneArgFunction { }; /*! Two argument function token base class. */ class TwoArgFunction : public Function { public: [[nodiscard]] virtual unsigned number_of_args() const override { return 2; } }; /*! 2 parameter arc tangent function token. First argument is the change in Y, second argument is the change in X. */ class Arctan2 : public TwoArgFunction { }; /*! Maximum of 2 elements function token. */ class Max : public TwoArgFunction { }; /*! Minimum of 2 elements function token. */ class Min : public TwoArgFunction { }; /*! Pow function token. First argument is the base, second the exponent. */ class Pow : public TwoArgFunction { }; /*! Three argument function token base class. */ class ThreeArgFunction : public Function { public: virtual unsigned number_of_args() const override { return 3; } };
25.341935
106
0.62831
ygor-rezende
7a74070c20510abfe143167aca5f0e563cf903d8
746
cpp
C++
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
/* * call.cpp * * Created on: Jan 17, 2015 * Author: radoslav */ #include "call.h" #include "constructor-call.h" #include "function-call.h" #include "strtok.h" void Call::parse(const char*& code) { name = Identifier(code); if (!gotoToken(code, " \t\n\r") || *code != '(') { type = CALL_INVALID; return; } code++; while (gotoToken(code, ", \t\n\r") && *code != ')') arguments.push_back(ExpressionTree::createExpressionTree(code)); if (*code != ')') type = CALL_INVALID; else code++; } Call* Call::create(const char*& code) { return peekToken(code, " \t\n\r") != "new" ? (Call*) new ConstructorCall(code) : (Call*) new FunctionCall(code); } Call::Call(const char*& code): Value(VALUE_CALL) { parse(code); }
16.577778
113
0.612601
rgeorgiev583
7a764c97dd2e828e58570985f7357348f8f93012
587
hpp
C++
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #ifndef CLI_ARGUMENTS_HPP #define CLI_ARGUMENTS_HPP #include <string> #include <unordered_map> namespace cli { class Arguments { public: Arguments(); ~ Arguments(); bool contains(char id) const; std::string const & get(char id) const; void set(char id, std::string const & value); private: std::unordered_map<char, std::string> values; }; } #endif
20.964286
70
0.689949
falk-werner
7a796768d7400ffddb6a87734e1311cb9b188af4
29,241
hpp
C++
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:38 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.EventSystems.UIBehaviour #include "UnityEngine/EventSystems/UIBehaviour.hpp" // Including type: UnityEngine.EventSystems.IInitializePotentialDragHandler #include "UnityEngine/EventSystems/IInitializePotentialDragHandler.hpp" // Including type: UnityEngine.EventSystems.IBeginDragHandler #include "UnityEngine/EventSystems/IBeginDragHandler.hpp" // Including type: UnityEngine.EventSystems.IEndDragHandler #include "UnityEngine/EventSystems/IEndDragHandler.hpp" // Including type: UnityEngine.EventSystems.IDragHandler #include "UnityEngine/EventSystems/IDragHandler.hpp" // Including type: UnityEngine.EventSystems.IScrollHandler #include "UnityEngine/EventSystems/IScrollHandler.hpp" // Including type: UnityEngine.UI.ICanvasElement #include "UnityEngine/UI/ICanvasElement.hpp" // Including type: UnityEngine.UI.ILayoutElement #include "UnityEngine/UI/ILayoutElement.hpp" // Including type: UnityEngine.UI.ILayoutGroup #include "UnityEngine/UI/ILayoutGroup.hpp" // Including type: UnityEngine.Vector2 #include "UnityEngine/Vector2.hpp" // Including type: UnityEngine.Bounds #include "UnityEngine/Bounds.hpp" // Including type: UnityEngine.DrivenRectTransformTracker #include "UnityEngine/DrivenRectTransformTracker.hpp" // Including type: System.Enum #include "System/Enum.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Scrollbar class Scrollbar; // Skipping declaration: MovementType because it is already included! // Skipping declaration: ScrollbarVisibility because it is already included! // Forward declaring type: CanvasUpdate struct CanvasUpdate; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Vector3 because it is already included! // Forward declaring type: RectTransform class RectTransform; // Forward declaring type: Matrix4x4 struct Matrix4x4; // Forward declaring type: Transform class Transform; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Autogenerated type: UnityEngine.UI.ScrollRect class ScrollRect : public UnityEngine::EventSystems::UIBehaviour, public UnityEngine::EventSystems::IInitializePotentialDragHandler, public UnityEngine::EventSystems::IEventSystemHandler, public UnityEngine::EventSystems::IBeginDragHandler, public UnityEngine::EventSystems::IEndDragHandler, public UnityEngine::EventSystems::IDragHandler, public UnityEngine::EventSystems::IScrollHandler, public UnityEngine::UI::ICanvasElement, public UnityEngine::UI::ILayoutElement, public UnityEngine::UI::ILayoutGroup, public UnityEngine::UI::ILayoutController { public: // Nested type: UnityEngine::UI::ScrollRect::MovementType struct MovementType; // Nested type: UnityEngine::UI::ScrollRect::ScrollbarVisibility struct ScrollbarVisibility; // Nested type: UnityEngine::UI::ScrollRect::ScrollRectEvent class ScrollRectEvent; // Autogenerated type: UnityEngine.UI.ScrollRect/MovementType struct MovementType : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static constexpr const int Unrestricted = 0; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static UnityEngine::UI::ScrollRect::MovementType _get_Unrestricted(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static void _set_Unrestricted(UnityEngine::UI::ScrollRect::MovementType value); // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Elastic static constexpr const int Elastic = 1; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Elastic static UnityEngine::UI::ScrollRect::MovementType _get_Elastic(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Elastic static void _set_Elastic(UnityEngine::UI::ScrollRect::MovementType value); // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Clamped static constexpr const int Clamped = 2; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Clamped static UnityEngine::UI::ScrollRect::MovementType _get_Clamped(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Clamped static void _set_Clamped(UnityEngine::UI::ScrollRect::MovementType value); // Creating value type constructor for type: MovementType MovementType(int value_ = {}) : value{value_} {} }; // UnityEngine.UI.ScrollRect/MovementType // Autogenerated type: UnityEngine.UI.ScrollRect/ScrollbarVisibility struct ScrollbarVisibility : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static constexpr const int Permanent = 0; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_Permanent(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static void _set_Permanent(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static constexpr const int AutoHide = 1; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_AutoHide(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static void _set_AutoHide(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static constexpr const int AutoHideAndExpandViewport = 2; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_AutoHideAndExpandViewport(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static void _set_AutoHideAndExpandViewport(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // Creating value type constructor for type: ScrollbarVisibility ScrollbarVisibility(int value_ = {}) : value{value_} {} }; // UnityEngine.UI.ScrollRect/ScrollbarVisibility // private UnityEngine.RectTransform m_Content // Offset: 0x18 UnityEngine::RectTransform* m_Content; // private System.Boolean m_Horizontal // Offset: 0x20 bool m_Horizontal; // private System.Boolean m_Vertical // Offset: 0x21 bool m_Vertical; // private UnityEngine.UI.ScrollRect/MovementType m_MovementType // Offset: 0x24 UnityEngine::UI::ScrollRect::MovementType m_MovementType; // private System.Single m_Elasticity // Offset: 0x28 float m_Elasticity; // private System.Boolean m_Inertia // Offset: 0x2C bool m_Inertia; // private System.Single m_DecelerationRate // Offset: 0x30 float m_DecelerationRate; // private System.Single m_ScrollSensitivity // Offset: 0x34 float m_ScrollSensitivity; // private UnityEngine.RectTransform m_Viewport // Offset: 0x38 UnityEngine::RectTransform* m_Viewport; // private UnityEngine.UI.Scrollbar m_HorizontalScrollbar // Offset: 0x40 UnityEngine::UI::Scrollbar* m_HorizontalScrollbar; // private UnityEngine.UI.Scrollbar m_VerticalScrollbar // Offset: 0x48 UnityEngine::UI::Scrollbar* m_VerticalScrollbar; // private UnityEngine.UI.ScrollRect/ScrollbarVisibility m_HorizontalScrollbarVisibility // Offset: 0x50 UnityEngine::UI::ScrollRect::ScrollbarVisibility m_HorizontalScrollbarVisibility; // private UnityEngine.UI.ScrollRect/ScrollbarVisibility m_VerticalScrollbarVisibility // Offset: 0x54 UnityEngine::UI::ScrollRect::ScrollbarVisibility m_VerticalScrollbarVisibility; // private System.Single m_HorizontalScrollbarSpacing // Offset: 0x58 float m_HorizontalScrollbarSpacing; // private System.Single m_VerticalScrollbarSpacing // Offset: 0x5C float m_VerticalScrollbarSpacing; // private UnityEngine.UI.ScrollRect/ScrollRectEvent m_OnValueChanged // Offset: 0x60 UnityEngine::UI::ScrollRect::ScrollRectEvent* m_OnValueChanged; // private UnityEngine.Vector2 m_PointerStartLocalCursor // Offset: 0x68 UnityEngine::Vector2 m_PointerStartLocalCursor; // protected UnityEngine.Vector2 m_ContentStartPosition // Offset: 0x70 UnityEngine::Vector2 m_ContentStartPosition; // private UnityEngine.RectTransform m_ViewRect // Offset: 0x78 UnityEngine::RectTransform* m_ViewRect; // protected UnityEngine.Bounds m_ContentBounds // Offset: 0x80 UnityEngine::Bounds m_ContentBounds; // private UnityEngine.Bounds m_ViewBounds // Offset: 0x98 UnityEngine::Bounds m_ViewBounds; // private UnityEngine.Vector2 m_Velocity // Offset: 0xB0 UnityEngine::Vector2 m_Velocity; // private System.Boolean m_Dragging // Offset: 0xB8 bool m_Dragging; // private System.Boolean m_Scrolling // Offset: 0xB9 bool m_Scrolling; // private UnityEngine.Vector2 m_PrevPosition // Offset: 0xBC UnityEngine::Vector2 m_PrevPosition; // private UnityEngine.Bounds m_PrevContentBounds // Offset: 0xC4 UnityEngine::Bounds m_PrevContentBounds; // private UnityEngine.Bounds m_PrevViewBounds // Offset: 0xDC UnityEngine::Bounds m_PrevViewBounds; // private System.Boolean m_HasRebuiltLayout // Offset: 0xF4 bool m_HasRebuiltLayout; // private System.Boolean m_HSliderExpand // Offset: 0xF5 bool m_HSliderExpand; // private System.Boolean m_VSliderExpand // Offset: 0xF6 bool m_VSliderExpand; // private System.Single m_HSliderHeight // Offset: 0xF8 float m_HSliderHeight; // private System.Single m_VSliderWidth // Offset: 0xFC float m_VSliderWidth; // private UnityEngine.RectTransform m_Rect // Offset: 0x100 UnityEngine::RectTransform* m_Rect; // private UnityEngine.RectTransform m_HorizontalScrollbarRect // Offset: 0x108 UnityEngine::RectTransform* m_HorizontalScrollbarRect; // private UnityEngine.RectTransform m_VerticalScrollbarRect // Offset: 0x110 UnityEngine::RectTransform* m_VerticalScrollbarRect; // private UnityEngine.DrivenRectTransformTracker m_Tracker // Offset: 0x118 UnityEngine::DrivenRectTransformTracker m_Tracker; // private readonly UnityEngine.Vector3[] m_Corners // Offset: 0x120 ::Array<UnityEngine::Vector3>* m_Corners; // public UnityEngine.RectTransform get_content() // Offset: 0x11F3370 UnityEngine::RectTransform* get_content(); // public System.Void set_content(UnityEngine.RectTransform value) // Offset: 0x11F3378 void set_content(UnityEngine::RectTransform* value); // public System.Boolean get_horizontal() // Offset: 0x11F3380 bool get_horizontal(); // public System.Void set_horizontal(System.Boolean value) // Offset: 0x11F3388 void set_horizontal(bool value); // public System.Boolean get_vertical() // Offset: 0x11F3394 bool get_vertical(); // public System.Void set_vertical(System.Boolean value) // Offset: 0x11F339C void set_vertical(bool value); // public UnityEngine.UI.ScrollRect/MovementType get_movementType() // Offset: 0x11F33A8 UnityEngine::UI::ScrollRect::MovementType get_movementType(); // public System.Void set_movementType(UnityEngine.UI.ScrollRect/MovementType value) // Offset: 0x11F33B0 void set_movementType(UnityEngine::UI::ScrollRect::MovementType value); // public System.Single get_elasticity() // Offset: 0x11F33B8 float get_elasticity(); // public System.Void set_elasticity(System.Single value) // Offset: 0x11F33C0 void set_elasticity(float value); // public System.Boolean get_inertia() // Offset: 0x11F33C8 bool get_inertia(); // public System.Void set_inertia(System.Boolean value) // Offset: 0x11F33D0 void set_inertia(bool value); // public System.Single get_decelerationRate() // Offset: 0x11F33DC float get_decelerationRate(); // public System.Void set_decelerationRate(System.Single value) // Offset: 0x11F33E4 void set_decelerationRate(float value); // public System.Single get_scrollSensitivity() // Offset: 0x11F33EC float get_scrollSensitivity(); // public System.Void set_scrollSensitivity(System.Single value) // Offset: 0x11F33F4 void set_scrollSensitivity(float value); // public UnityEngine.RectTransform get_viewport() // Offset: 0x11F33FC UnityEngine::RectTransform* get_viewport(); // public System.Void set_viewport(UnityEngine.RectTransform value) // Offset: 0x11F3404 void set_viewport(UnityEngine::RectTransform* value); // public UnityEngine.UI.Scrollbar get_horizontalScrollbar() // Offset: 0x11F34FC UnityEngine::UI::Scrollbar* get_horizontalScrollbar(); // public System.Void set_horizontalScrollbar(UnityEngine.UI.Scrollbar value) // Offset: 0x11F3504 void set_horizontalScrollbar(UnityEngine::UI::Scrollbar* value); // public UnityEngine.UI.Scrollbar get_verticalScrollbar() // Offset: 0x11F368C UnityEngine::UI::Scrollbar* get_verticalScrollbar(); // public System.Void set_verticalScrollbar(UnityEngine.UI.Scrollbar value) // Offset: 0x11F3694 void set_verticalScrollbar(UnityEngine::UI::Scrollbar* value); // public UnityEngine.UI.ScrollRect/ScrollbarVisibility get_horizontalScrollbarVisibility() // Offset: 0x11F381C UnityEngine::UI::ScrollRect::ScrollbarVisibility get_horizontalScrollbarVisibility(); // public System.Void set_horizontalScrollbarVisibility(UnityEngine.UI.ScrollRect/ScrollbarVisibility value) // Offset: 0x11F3824 void set_horizontalScrollbarVisibility(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // public UnityEngine.UI.ScrollRect/ScrollbarVisibility get_verticalScrollbarVisibility() // Offset: 0x11F382C UnityEngine::UI::ScrollRect::ScrollbarVisibility get_verticalScrollbarVisibility(); // public System.Void set_verticalScrollbarVisibility(UnityEngine.UI.ScrollRect/ScrollbarVisibility value) // Offset: 0x11F3834 void set_verticalScrollbarVisibility(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // public System.Single get_horizontalScrollbarSpacing() // Offset: 0x11F383C float get_horizontalScrollbarSpacing(); // public System.Void set_horizontalScrollbarSpacing(System.Single value) // Offset: 0x11F3844 void set_horizontalScrollbarSpacing(float value); // public System.Single get_verticalScrollbarSpacing() // Offset: 0x11F38E0 float get_verticalScrollbarSpacing(); // public System.Void set_verticalScrollbarSpacing(System.Single value) // Offset: 0x11F38E8 void set_verticalScrollbarSpacing(float value); // public UnityEngine.UI.ScrollRect/ScrollRectEvent get_onValueChanged() // Offset: 0x11F38F0 UnityEngine::UI::ScrollRect::ScrollRectEvent* get_onValueChanged(); // public System.Void set_onValueChanged(UnityEngine.UI.ScrollRect/ScrollRectEvent value) // Offset: 0x11F38F8 void set_onValueChanged(UnityEngine::UI::ScrollRect::ScrollRectEvent* value); // protected UnityEngine.RectTransform get_viewRect() // Offset: 0x11F3900 UnityEngine::RectTransform* get_viewRect(); // public UnityEngine.Vector2 get_velocity() // Offset: 0x11F3A0C UnityEngine::Vector2 get_velocity(); // public System.Void set_velocity(UnityEngine.Vector2 value) // Offset: 0x11F3A14 void set_velocity(UnityEngine::Vector2 value); // private UnityEngine.RectTransform get_rectTransform() // Offset: 0x11F3A1C UnityEngine::RectTransform* get_rectTransform(); // private System.Void UpdateCachedData() // Offset: 0x11F3CD0 void UpdateCachedData(); // private System.Void EnsureLayoutHasRebuilt() // Offset: 0x11F4D54 void EnsureLayoutHasRebuilt(); // public System.Void StopMovement() // Offset: 0x11F4DD8 void StopMovement(); // protected System.Void SetContentAnchoredPosition(UnityEngine.Vector2 position) // Offset: 0x11F55F8 void SetContentAnchoredPosition(UnityEngine::Vector2 position); // protected System.Void LateUpdate() // Offset: 0x11F5710 void LateUpdate(); // protected System.Void UpdatePrevData() // Offset: 0x11F4830 void UpdatePrevData(); // private System.Void UpdateScrollbars(UnityEngine.Vector2 offset) // Offset: 0x11F4618 void UpdateScrollbars(UnityEngine::Vector2 offset); // public UnityEngine.Vector2 get_normalizedPosition() // Offset: 0x11F5DA4 UnityEngine::Vector2 get_normalizedPosition(); // public System.Void set_normalizedPosition(UnityEngine.Vector2 value) // Offset: 0x11F6198 void set_normalizedPosition(UnityEngine::Vector2 value); // public System.Single get_horizontalNormalizedPosition() // Offset: 0x11F5EF0 float get_horizontalNormalizedPosition(); // public System.Void set_horizontalNormalizedPosition(System.Single value) // Offset: 0x11F61EC void set_horizontalNormalizedPosition(float value); // public System.Single get_verticalNormalizedPosition() // Offset: 0x11F6048 float get_verticalNormalizedPosition(); // public System.Void set_verticalNormalizedPosition(System.Single value) // Offset: 0x11F6200 void set_verticalNormalizedPosition(float value); // private System.Void SetHorizontalNormalizedPosition(System.Single value) // Offset: 0x11F6214 void SetHorizontalNormalizedPosition(float value); // private System.Void SetVerticalNormalizedPosition(System.Single value) // Offset: 0x11F6228 void SetVerticalNormalizedPosition(float value); // protected System.Void SetNormalizedPosition(System.Single value, System.Int32 axis) // Offset: 0x11F623C void SetNormalizedPosition(float value, int axis); // static private System.Single RubberDelta(System.Single overStretching, System.Single viewSize) // Offset: 0x11F554C static float RubberDelta(float overStretching, float viewSize); // private System.Boolean get_hScrollingNeeded() // Offset: 0x11F6458 bool get_hScrollingNeeded(); // private System.Boolean get_vScrollingNeeded() // Offset: 0x11F64C0 bool get_vScrollingNeeded(); // private System.Void UpdateScrollbarVisibility() // Offset: 0x11F5DFC void UpdateScrollbarVisibility(); // static private System.Void UpdateOneScrollbarVisibility(System.Boolean xScrollingNeeded, System.Boolean xAxisEnabled, UnityEngine.UI.ScrollRect/ScrollbarVisibility scrollbarVisibility, UnityEngine.UI.Scrollbar scrollbar) // Offset: 0x11F70B0 static void UpdateOneScrollbarVisibility(bool xScrollingNeeded, bool xAxisEnabled, UnityEngine::UI::ScrollRect::ScrollbarVisibility scrollbarVisibility, UnityEngine::UI::Scrollbar* scrollbar); // private System.Void UpdateScrollbarLayout() // Offset: 0x11F6D88 void UpdateScrollbarLayout(); // protected System.Void UpdateBounds() // Offset: 0x11F40BC void UpdateBounds(); // static System.Void AdjustBounds(UnityEngine.Bounds viewBounds, UnityEngine.Vector2 contentPivot, UnityEngine.Vector3 contentSize, UnityEngine.Vector3 contentPos) // Offset: 0x11F71B4 static void AdjustBounds(UnityEngine::Bounds& viewBounds, UnityEngine::Vector2& contentPivot, UnityEngine::Vector3& contentSize, UnityEngine::Vector3& contentPos); // private UnityEngine.Bounds GetBounds() // Offset: 0x11F6B38 UnityEngine::Bounds GetBounds(); // static UnityEngine.Bounds InternalGetBounds(UnityEngine.Vector3[] corners, UnityEngine.Matrix4x4 viewWorldToLocalMatrix) // Offset: 0x11F72F4 static UnityEngine::Bounds InternalGetBounds(::Array<UnityEngine::Vector3>* corners, UnityEngine::Matrix4x4& viewWorldToLocalMatrix); // private UnityEngine.Vector2 CalculateOffset(UnityEngine.Vector2 delta) // Offset: 0x11F50F0 UnityEngine::Vector2 CalculateOffset(UnityEngine::Vector2 delta); // static UnityEngine.Vector2 InternalCalculateOffset(UnityEngine.Bounds viewBounds, UnityEngine.Bounds contentBounds, System.Boolean horizontal, System.Boolean vertical, UnityEngine.UI.ScrollRect/MovementType movementType, UnityEngine.Vector2 delta) // Offset: 0x11F74F8 static UnityEngine::Vector2 InternalCalculateOffset(UnityEngine::Bounds& viewBounds, UnityEngine::Bounds& contentBounds, bool horizontal, bool vertical, UnityEngine::UI::ScrollRect::MovementType movementType, UnityEngine::Vector2& delta); // protected System.Void SetDirty() // Offset: 0x11F384C void SetDirty(); // protected System.Void SetDirtyCaching() // Offset: 0x11F342C void SetDirtyCaching(); // protected System.Void .ctor() // Offset: 0x11F3AC8 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static ScrollRect* New_ctor(); // public System.Void Rebuild(UnityEngine.UI.CanvasUpdate executing) // Offset: 0x11F3C1C // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::Rebuild(UnityEngine.UI.CanvasUpdate executing) void Rebuild(UnityEngine::UI::CanvasUpdate executing); // public System.Void LayoutComplete() // Offset: 0x11F490C // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::LayoutComplete() void LayoutComplete(); // public System.Void GraphicUpdateComplete() // Offset: 0x11F4910 // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::GraphicUpdateComplete() void GraphicUpdateComplete(); // protected override System.Void OnEnable() // Offset: 0x11F4914 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x11F4AB4 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDisable() void OnDisable(); // public override System.Boolean IsActive() // Offset: 0x11F4CC4 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Boolean UIBehaviour::IsActive() bool IsActive(); // public System.Void OnScroll(UnityEngine.EventSystems.PointerEventData data) // Offset: 0x11F4E44 // Implemented from: UnityEngine.EventSystems.IScrollHandler // Base method: System.Void IScrollHandler::OnScroll(UnityEngine.EventSystems.PointerEventData data) void OnScroll(UnityEngine::EventSystems::PointerEventData* data); // public System.Void OnInitializePotentialDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F512C // Implemented from: UnityEngine.EventSystems.IInitializePotentialDragHandler // Base method: System.Void IInitializePotentialDragHandler::OnInitializePotentialDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnInitializePotentialDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnBeginDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F51B4 // Implemented from: UnityEngine.EventSystems.IBeginDragHandler // Base method: System.Void IBeginDragHandler::OnBeginDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnBeginDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnEndDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F52E4 // Implemented from: UnityEngine.EventSystems.IEndDragHandler // Base method: System.Void IEndDragHandler::OnEndDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnEndDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F5308 // Implemented from: UnityEngine.EventSystems.IDragHandler // Base method: System.Void IDragHandler::OnDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnDrag(UnityEngine::EventSystems::PointerEventData* eventData); // protected override System.Void OnRectTransformDimensionsChange() // Offset: 0x11F6454 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnRectTransformDimensionsChange() void OnRectTransformDimensionsChange(); // public System.Void CalculateLayoutInputHorizontal() // Offset: 0x11F6528 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Void ILayoutElement::CalculateLayoutInputHorizontal() void CalculateLayoutInputHorizontal(); // public System.Void CalculateLayoutInputVertical() // Offset: 0x11F652C // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Void ILayoutElement::CalculateLayoutInputVertical() void CalculateLayoutInputVertical(); // public System.Single get_minWidth() // Offset: 0x11F6530 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_minWidth() float get_minWidth(); // public System.Single get_preferredWidth() // Offset: 0x11F6538 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_preferredWidth() float get_preferredWidth(); // public System.Single get_flexibleWidth() // Offset: 0x11F6540 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_flexibleWidth() float get_flexibleWidth(); // public System.Single get_minHeight() // Offset: 0x11F6548 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_minHeight() float get_minHeight(); // public System.Single get_preferredHeight() // Offset: 0x11F6550 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_preferredHeight() float get_preferredHeight(); // public System.Single get_flexibleHeight() // Offset: 0x11F6558 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_flexibleHeight() float get_flexibleHeight(); // public System.Int32 get_layoutPriority() // Offset: 0x11F6560 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Int32 ILayoutElement::get_layoutPriority() int get_layoutPriority(); // public System.Void SetLayoutHorizontal() // Offset: 0x11F6568 // Implemented from: UnityEngine.UI.ILayoutController // Base method: System.Void ILayoutController::SetLayoutHorizontal() void SetLayoutHorizontal(); // public System.Void SetLayoutVertical() // Offset: 0x11F6C2C // Implemented from: UnityEngine.UI.ILayoutController // Base method: System.Void ILayoutController::SetLayoutVertical() void SetLayoutVertical(); // private UnityEngine.Transform UnityEngine.UI.ICanvasElement.get_transform() // Offset: 0x11F76EC // Implemented from: UnityEngine.UI.ICanvasElement // Base method: UnityEngine.Transform ICanvasElement::get_transform() UnityEngine::Transform* UnityEngine_UI_ICanvasElement_get_transform(); }; // UnityEngine.UI.ScrollRect } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect*, "UnityEngine.UI", "ScrollRect"); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect::MovementType, "UnityEngine.UI", "ScrollRect/MovementType"); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect::ScrollbarVisibility, "UnityEngine.UI", "ScrollRect/ScrollbarVisibility"); #pragma pack(pop)
51.120629
553
0.757943
Futuremappermydud
7a7c5c97f5aa712eebe55dc8d0ac8f0efc2cf4ac
8,616
cc
C++
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
9
2015-12-23T21:18:28.000Z
2018-11-25T10:10:12.000Z
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
1
2016-01-08T20:56:21.000Z
2016-01-08T20:56:21.000Z
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
6
2015-12-04T18:23:49.000Z
2018-11-06T03:52:58.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Copyright 2015 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include <string.h> #include <sstream> #include "base/logger.h" #include "base/ptr_utils.h" #include "net/udp_listener.h" #ifdef WIN32 #undef PostMessage // Allow 'this' in initializer list #pragma warning(disable : 4355) #endif static uint16_t Htons(uint16_t hostshort) { uint8_t result_bytes[2]; result_bytes[0] = (uint8_t)((hostshort >> 8) & 0xFF); result_bytes[1] = (uint8_t)(hostshort & 0xFF); uint16_t result; memcpy(&result, result_bytes, 2); return result; } UDPListener::UDPListener(pp::Instance* instance, UDPDelegateInterface* delegate, const std::string& host, uint16_t port) : instance_(instance), delegate_(delegate), callback_factory_(this), network_monitor_(instance_), stop_listening_(false) { Start(host, port); } UDPListener::~UDPListener() {} bool UDPListener::IsConnected() { if (!udp_socket_.is_null()) return true; return false; } void UDPListener::Start(const std::string& host, uint16_t port) { if (IsConnected()) { WRN() << "Already connected."; return; } udp_socket_ = pp::UDPSocket(instance_); if (udp_socket_.is_null()) { ERR() << "Could not create UDPSocket."; return; } if (!pp::HostResolver::IsAvailable()) { ERR() << "HostResolver not available."; return; } resolver_ = pp::HostResolver(instance_); if (resolver_.is_null()) { ERR() << "Could not create HostResolver."; return; } PP_NetAddress_IPv4 ipv4_addr = {Htons(port), {0, 0, 0, 0}}; local_host_ = pp::NetAddress(instance_, ipv4_addr); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnResolveCompletion); PP_HostResolver_Hint hint = {PP_NETADDRESS_FAMILY_UNSPECIFIED, 0}; resolver_.Resolve(host.c_str(), port, hint, callback); DINF() << "Resolving..."; } void UDPListener::OnNetworkListCompletion(int32_t result, pp::NetworkList network_list) { if (result != PP_OK) { ERR() << "Update Network List failed: " << result; return; } int count = network_list.GetCount(); DINF() << "Number of networks found: " << count; for (int i = 0; i < network_list.GetCount(); i++) { DINF() << "network: " << i << ", name: " << network_list.GetName(i).c_str(); } /* pp::CompletionCallback callback = */ /* callback_factory_.NewCallback(&UDPListener::OnSetOptionCompletion); */ DINF() << "Binding..."; /* udp_socket_.SetOption(PP_UDPSOCKET_OPTION_MULTICAST_IF, pp::Var(0), * callback); */ pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnConnectCompletion); udp_socket_.Bind(local_host_, callback); } void UDPListener::OnJoinedCompletion(int32_t result) { DINF() << "OnJoined result: " << result; pp::NetAddress addr = udp_socket_.GetBoundAddress(); INF() << "Bound to: " << addr.DescribeAsString(true).AsString(); Receive(); } void UDPListener::OnSetOptionCompletion(int32_t result) { if (result != PP_OK) { ERR() << "SetOption failed: " << result; return; } pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnConnectCompletion); udp_socket_.Bind(local_host_, callback); } void UDPListener::OnResolveCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Resolve failed: " << result; return; } pp::CompletionCallbackWithOutput<pp::NetworkList> netlist_callback = callback_factory_.NewCallbackWithOutput( &UDPListener::OnNetworkListCompletion); network_monitor_.UpdateNetworkList(netlist_callback); pp::NetAddress addr = resolver_.GetNetAddress(0); INF() << "Resolved: " << addr.DescribeAsString(true).AsString(); group_addr_ = addr; } void UDPListener::Stop() { if (!IsConnected()) { WRN() << "Not connected."; return; } udp_socket_.Close(); udp_socket_ = pp::UDPSocket(); INF() << "Closed connection."; } void UDPListener::Send(const std::string& message) { if (!IsConnected()) { WRN() << "Cant send, not connected."; return; } if (send_outstanding_) { WRN() << "Already sending."; return; } if (!remote_host_) { ERR() << "Can't send packet: remote host not set yet."; return; } uint32_t size = message.size(); const char* data = message.c_str(); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnSendCompletion); int32_t result; result = udp_socket_.SendTo(data, size, *remote_host_, callback); if (result < 0) { if (result == PP_OK_COMPLETIONPENDING) { DINF() << "Sending bytes."; send_outstanding_ = true; } else { WRN() << "Send return error: " << result; } } else { DINF() << "Sent bytes synchronously: " << result; } } void UDPListener::SendPacket(PacketRef packet) { if (!IsConnected()) { ERR() << "Can't send packet: not connected."; return; } packets_.push(packet); SendPacketsInternal(); } void UDPListener::SendPacketsInternal() { if (!remote_host_) { ERR() << "Can't send packet: remote host not set yet."; return; } if (send_outstanding_ || packets_.empty()) return; while (!send_outstanding_ && !packets_.empty()) { PacketRef packet = packets_.front(); uint32_t size = packet->size(); const char* data = reinterpret_cast<char*>(packet->data()); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnSendPacketCompletion); int32_t result; result = udp_socket_.SendTo(data, size, *remote_host_, callback); if (result < 0) { if (result == PP_OK_COMPLETIONPENDING) { // will send, just wait completion now send_outstanding_ = true; } else { ERR() << "Error sending packet: " << result; } } else { // packet sent synchronously packets_.pop(); } } } void UDPListener::Receive() { memset(receive_buffer_, 0, kBufferSize); pp::CompletionCallbackWithOutput<pp::NetAddress> callback = callback_factory_.NewCallbackWithOutput( &UDPListener::OnReceiveFromCompletion); udp_socket_.RecvFrom(receive_buffer_, kBufferSize, callback); } void UDPListener::OnConnectCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Connection failed: " << result; return; } pp::CompletionCallback joinCallback = callback_factory_.NewCallback(&UDPListener::OnJoinedCompletion); udp_socket_.JoinGroup(group_addr_, joinCallback); } void UDPListener::OnReceiveFromCompletion(int32_t result, pp::NetAddress source) { if (!remote_host_) { INF() << "Setting remote host to: " << source.DescribeAsString(true).AsString(); remote_host_ = make_unique<pp::NetAddress>(source); } OnReceiveCompletion(result); } void UDPListener::OnReceiveCompletion(int32_t result) { if (result < 0) { ERR() << "Receive failed with error: " << result; return; } delegate_->OnReceived(receive_buffer_, result); /* PostMessage(std::string("Received: ") + std::string(receive_buffer_, * result)); */ if (!stop_listening_) Receive(); } void UDPListener::OnSendCompletion(int32_t result) { if (result < 0) { ERR() << "Send failed with error: " << result; } else { DINF() << "Sent " << result << " bytes."; } send_outstanding_ = false; } void UDPListener::OnSendPacketCompletion(int32_t result) { if (result < 0) { ERR() << "SendPacket failed with error: " << result; } packets_.pop(); send_outstanding_ = false; SendPacketsInternal(); } void UDPListener::OnLeaveCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Could not rejoin multicast group: " << result; return; } auto rejoinCallback = callback_factory_.NewCallback(&UDPListener::OnRejoinCompletion); udp_socket_.JoinGroup(group_addr_, rejoinCallback); } void UDPListener::OnRejoinCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Could not leave multicast group: " << result; return; } } void UDPListener::OnNetworkTimeout() { auto leaveCallback = callback_factory_.NewCallback(&UDPListener::OnLeaveCompletion); udp_socket_.LeaveGroup(group_addr_, leaveCallback); } void UDPListener::StopListening() { stop_listening_ = true; } void UDPListener::StartListening() { stop_listening_ = false; Receive(); }
26.925
80
0.666086
maxsong11
18528f1718cf409c430581856e0e283feec890e6
27
cpp
C++
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
1
2019-07-10T07:35:58.000Z
2019-07-10T07:35:58.000Z
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
null
null
null
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
null
null
null
#include "http_method.hpp"
13.5
26
0.777778
pozitiffcat
1856afa93da83c4b693e43da18982be2e90199cf
484
cpp
C++
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<string.h> #include<algorithm> using namespace std; int main() { string s; cin>>s; int len = s.length(); int n1 = len/3,n3 = len/3, n2 = len-n1-n3; //不能n1=n2=n3 if(len%3 == 0) { n1--;n3--;n2 +=2;} for(int i=0; i<n1; i++){ cout<<s[i]; for(int j=1; j<=n2-2; j++) cout<<" "; cout<<s[len-i-1]<<endl; } for(int i=n1; i<len-n1; i++) cout<<s[i]; cout<<endl; return 0; }
21.043478
59
0.491736
zofvbeaf
185707fd55ea6faf75bbdb73bbf5aa8529f77874
3,158
cpp
C++
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
16
2019-05-23T08:10:39.000Z
2021-12-21T11:20:37.000Z
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
null
null
null
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
2
2019-05-23T18:37:43.000Z
2021-08-24T21:29:40.000Z
#include "ECMapMover.h" #include "Map.h" #include "Game.h" #include "MapGrid.h" #include "Node.h" using namespace qge; ECMapMover::ECMapMover(Entity *entity): EntityController(entity), borderThreshold_(10) { assert(entity != nullptr); // listen to when entity moves connect(entity,&Entity::moved,this,&ECMapMover::onEntityMoved); } /// Sets the border threshold. Whenever the controlled entity gets within /// this distance to any of the borders of its map, it will be transported /// to the next map in that direction. void ECMapMover::setBorderThreshold(double threshold) { borderThreshold_ = threshold; } /// Returns the border threshold. /// See setBorderThreshold() for more info. double ECMapMover::borderThreshold() { return borderThreshold_; } /// Executed when the controlled entity moves. /// Will see if it should move to new border map. void ECMapMover::onEntityMoved(Entity *controlledEntity, QPointF fromPos, QPointF toPos) { // do nothing if controlled entity is not in a map Entity* entity = entityControlled(); Map* entitysMap = entity->map(); if (entitysMap == nullptr) return; // do nothing if entitys map is not in a map grid Game* entitysGame = entitysMap->game(); if (entitysGame == nullptr) return; MapGrid* mapGrid = entitysGame->mapGrid(); if (mapGrid == nullptr) return; if (!mapGrid->contains(entitysMap)) return; // other wise, move entity to next maps // set up variables Node mapPos = mapGrid->positionOf(entitysMap); QPointF entityPos = entity->pos(); // if entity moved high up enough, move to top map if (entityPos.y() < borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x(),mapPos.y()-1); if (m){ double fracAlong = entity->x() / entitysMap->width(); m->addEntity(entity); entity->setPos(QPointF(fracAlong * m->width(),m->height() - borderThreshold_*2)); } } // if entity moved low enough, move to bot map if (entityPos.y() > entitysMap->height() - borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x(),mapPos.y()+1); if (m){ double fracAlong = entity->x() / entitysMap->width(); m->addEntity(entity); entity->setPos(QPointF(fracAlong * m->width(),borderThreshold_*2)); } } // if entity moved left enough, move to left map if (entityPos.x() < borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x()-1,mapPos.y()); if (m){ double fracAlong = entity->y() / entitysMap->height(); m->addEntity(entity); entity->setPos(QPointF(m->width() - borderThreshold_*2,fracAlong * m->height())); } } // if entity moved right enough, move to right map if (entityPos.x() > entitysMap->width() - borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x()+1,mapPos.y()); if (m){ double fracAlong = entity->y() / entitysMap->height(); m->addEntity(entity); entity->setPos(QPointF(borderThreshold_*2,fracAlong * m->height())); } } }
30.960784
93
0.624763
JamesMBallard
185894efec17052bd63aa3fe982827369c8edc6d
775
hh
C++
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
#ifndef __BULKRENAME_FILE_GUARD__ #define __BULKRENAME_FILE_GUARD__ #include "node.hh" #include <fstream> #include <string.h> #include <iostream> #include <string> #include <cstdio> class filehandler_t { public: filehandler_t() { char* tmpname = strdup("/tmp/tmpfileXXXXXXXXXX"); mkstemp(tmpname); tmpfile = tmpname; free(tmpname); out = ::std::ofstream(tmpfile); } ~filehandler_t() { out.close(); in.close(); } void write_out(const nodetree_t&); void read_in(const nodetree_t&); void edit() const; void propagate_rename(const nodetree_t&) const; private: ::std::string tmpfile; ::std::ifstream in; ::std::ofstream out; }; #endif//__BULKRENAME_FILE_GUARD__
17.222222
57
0.636129
deurzen
185a633de3a64811253334a39e0ac7f71e4e31c6
7,366
cpp
C++
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
76
2015-03-31T01:36:17.000Z
2021-12-29T08:16:25.000Z
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
68
2016-11-28T18:58:26.000Z
2018-08-10T13:33:35.000Z
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
17
2015-04-24T03:52:32.000Z
2022-03-11T23:28:02.000Z
#include "gmock/gmock.h" #include "../mock.hpp" #include <sstream> #include <streambuf> #include <utility> #include "MockRawIOManipulator.hpp" #include "../spec/io/MockIOManipulator.hpp" #include "../spec/verifier/MockVerifier.hpp" #include "tcframe/driver/TestCaseDriver.hpp" using ::testing::_; using ::testing::Eq; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::Test; using ::testing::Truly; using std::istreambuf_iterator; using std::istringstream; using std::move; using std::ostringstream; namespace tcframe { class TestCaseDriverTests : public Test { public: static int T; static int N; protected: MOCK(RawIOManipulator) rawIOManipulator; MOCK(IOManipulator) ioManipulator; MOCK(Verifier) verifier; TestCase sampleTestCase = TestCaseBuilder() .setName("foo_sample_1") .setSubtaskIds({1, 2}) .setData(new SampleTestCaseData("42\n", "yes\n")) .build(); TestCase officialTestCase = TestCaseBuilder() .setName("foo_1") .setDescription("N = 42") .setSubtaskIds({1, 2}) .setData(new OfficialTestCaseData([&]{N = 42;})) .build(); MultipleTestCasesConfig multipleTestCasesConfig = MultipleTestCasesConfigBuilder() .Counter(T) .build(); MultipleTestCasesConfig multipleTestCasesConfigWithOutputPrefix = MultipleTestCasesConfigBuilder() .Counter(T) .OutputPrefix("Case #%d: ") .build(); ostream* out = new ostringstream(); TestCaseDriver driver = createDriver(MultipleTestCasesConfig()); TestCaseDriver driverWithMultipleTestCases = createDriver(multipleTestCasesConfig); TestCaseDriver driverWithMultipleTestCasesWithOutputPrefix = createDriver(multipleTestCasesConfigWithOutputPrefix); TestCaseDriver createDriver(MultipleTestCasesConfig multipleTestCasesConfig) { return {&rawIOManipulator, &ioManipulator, &verifier, multipleTestCasesConfig}; } void SetUp() { ON_CALL(verifier, verifyConstraints(_)) .WillByDefault(Return(ConstraintsVerificationResult())); ON_CALL(verifier, verifyMultipleTestCasesConstraints()) .WillByDefault(Return(MultipleTestCasesConstraintsVerificationResult())); } struct InputStreamContentIs { string content_; explicit InputStreamContentIs(string content) : content_(move(content)) {} bool operator()(istream* in) const { return content_ == string(istreambuf_iterator<char>(*in), istreambuf_iterator<char>()); } }; }; int TestCaseDriverTests::T; int TestCaseDriverTests::N; TEST_F(TestCaseDriverTests, GenerateInput_Sample) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseInput(Truly(InputStreamContentIs("42\n")))); EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, print(out, "42\n")); } driver.generateInput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, GenerateInput_Official) { { InSequence sequence; EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(ioManipulator, printInput(out)); } N = 0; driver.generateInput(officialTestCase, out); EXPECT_THAT(N, Eq(42)); } TEST_F(TestCaseDriverTests, GenerateInput_Failed_Verification) { ConstraintsVerificationResult failedResult({}, {1}); ON_CALL(verifier, verifyConstraints(_)) .WillByDefault(Return(failedResult)); try { driver.generateInput(officialTestCase, out); FAIL(); } catch (FormattedError& e) { EXPECT_THAT(e, Eq(failedResult.asFormattedError())); } } TEST_F(TestCaseDriverTests, GenerateSampleOutput) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driver.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput) { istringstream in; EXPECT_CALL(ioManipulator, parseOutput(&in)); driver.validateOutput(&in); } TEST_F(TestCaseDriverTests, GenerateInput_MultipleTestCases_Sample) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseInput(Truly(InputStreamContentIs("42\n")))); EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, printLine(out, "1")); EXPECT_CALL(rawIOManipulator, print(out, "42\n")); } driverWithMultipleTestCases.generateInput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, GenerateInput_MultipleTestCases_Official) { { InSequence sequence; EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, printLine(out, "1")); EXPECT_CALL(ioManipulator, printInput(out)); } N = 0; driverWithMultipleTestCases.generateInput(officialTestCase, out); EXPECT_THAT(N, Eq(42)); } TEST_F(TestCaseDriverTests, GenerateSampleOutput_MultipleTestCases) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driverWithMultipleTestCases.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases) { istringstream in("yes\n"); EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); driver.validateOutput(&in); } TEST_F(TestCaseDriverTests, GenerateSampleOutput_MultipleTestCases_WithOutputPrefix) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "Case #1: ")); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driverWithMultipleTestCasesWithOutputPrefix.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases_WithOutputPrefix) { istringstream in("Case #1: yes\n"); EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); driverWithMultipleTestCasesWithOutputPrefix.validateOutput(&in); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases_WithOutputPrefix_Failed) { istringstream in("yes\n"); try { driverWithMultipleTestCasesWithOutputPrefix.validateOutput(&in); FAIL(); } catch (runtime_error& e) { EXPECT_THAT(e.what(), StrEq("Output must start with \"Case #1: \"")); } } TEST_F(TestCaseDriverTests, ValidateMultipleTestCasesInput) { EXPECT_CALL(verifier, verifyMultipleTestCasesConstraints()); driverWithMultipleTestCases.validateMultipleTestCasesInput(3); EXPECT_THAT(T, Eq(3)); } TEST_F(TestCaseDriverTests, ValidateMultipleTestCasesInput_Failed) { MultipleTestCasesConstraintsVerificationResult failedResult({"desc"}); ON_CALL(verifier, verifyMultipleTestCasesConstraints()) .WillByDefault(Return(failedResult)); try { driverWithMultipleTestCases.validateMultipleTestCasesInput(3); FAIL(); } catch (FormattedError& e) { EXPECT_THAT(e, Eq(failedResult.asFormattedError())); } } }
33.481818
119
0.706489
tcgen
185ad667e2140f0aeddd86cc3cb6970d9175e079
333
hpp
C++
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <QtWidgets\QWidget> #include <QtCore\QTimeLine> #include "image_item.hpp" class image_scaler { public: image_scaler(QWidget * _widget, image_item ** _image); void add_steps(int _steps); private: int _destination_level; QTimeLine _scaler; static double scaling_function(double _x); };
15.857143
55
0.762763
terrakuh
18663000d41284c595c75793284e23e783255fc9
3,609
cpp
C++
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
5
2019-12-02T12:28:57.000Z
2021-04-07T21:21:13.000Z
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
null
null
null
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
1
2020-01-09T14:25:42.000Z
2020-01-09T14:25:42.000Z
/*! * @file sr_main.cpp * @author Marc-Anton Boehm-von Thenen * @date 27/06/2018 * @copyright SmartRay GmbH (www.smartray.com) */ #include "sr_pch.h" #include <functional> #include <iostream> #include "application/sr_state.h" #include "application/sr_handler_factory.h" #include <tcp_server_client/sr_server.h> //<--------------------------------------------- int main( int aArgC, char* aArgV[] ) { if (aArgC != 2) { std::cerr << "Usage: ./property_server <port> \n"; return 1; } std::string const port = aArgV[1]; asio::io_context asioIOContext; CStdSharedPtr_t<CTCPServer> tcpServer = nullptr; try { CStdSharedPtr_t<CTCPSession> session = nullptr; std::atomic<bool> connected(false); auto connectionSuccessHandler = [&] (CStdSharedPtr_t<CTCPSession> aSession) { connected.store(true); session = aSession; }; auto const tcpThreadFn = [&](std::string const &aPort) -> int32_t { tcp::endpoint endPoint(tcp::v4(), std::atoi(aPort.c_str())); tcpServer = makeStdSharedPtr<CTCPServer>(asioIOContext, endPoint, connectionSuccessHandler); tcpServer->start(); asioIOContext.run(); return 0; }; std::future<int32_t> tcpThreadResult = std::async(std::launch::async, tcpThreadFn, port); while(!connected.load()) { std::cout << "Waiting for connection...\n"; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } CStdSharedPtr_t<CHandlerFactory> handlerFactory = makeStdSharedPtr<CHandlerFactory>(session); CStdSharedPtr_t<CState> state = makeStdSharedPtr<CState>(handlerFactory); std::string serializedState = std::string(); bool const &stateInitialized = state->initialize(); bool const serialized = stateInitialized && state->getSerializedState(serializedState); CTCPMessage const outputMessage = CTCPMessage::create(serializedState); tcpServer->getSession()->writeMessage(outputMessage); std::string command = std::string(); while(1) { std::cin >> command; if(!command.compare("exit")) { break; } if(!command.compare("write_property")) { std::string path{}; (std::cin >> path); std::string index{}; (std::cin >> index); std::string value{}; (std::cin >> value); std::string outputCommand = CString::formatString("writeProperty/%s/%s/%s", path.c_str(), index.c_str(), value.c_str()); CTCPMessage outputMessage = CTCPMessage::create(outputCommand); tcpServer->getSession()->writeMessage(outputMessage); } } asioIOContext.stop(); std::future_status status = std::future_status::ready; do { std::cout << "Waiting for TCP thread to return...\n"; status = tcpThreadResult.wait_for(std::chrono::milliseconds(500)); } while(std::future_status::ready != status); int32_t const tcpThreadReturned = tcpThreadResult.get(); std::cout << "TCP thread returned status code: " << tcpThreadReturned << "\n"; return tcpThreadReturned; } catch(std::exception const &e) { std::cerr << "Exception: " << e.what() << "\n"; return -1; } }
28.872
136
0.563591
BoneCrasher
18766da2fb8b4a197e862b8f6772a05660f0cc66
1,194
cpp
C++
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
#include "orm/store_mark/store.h" namespace orm::store_mark { test::mock::Store& Store::mock() { return mMock; } std::shared_ptr<orm::core::Property> Store::query(std::int64_t identity) { return mMock.query(identity); } bool Store::commit() { return mMock.commit(); } std::shared_ptr<orm::core::Property> Store::fetch() { return mMock.fetch(); } bool Store::insert(std::int64_t identity, std::shared_ptr<orm::core::Property>&& record) { return mMock.insert(identity, std::forward<std::shared_ptr<orm::core::Property>>(record)); } bool Store::insert(std::int64_t identity, const std::shared_ptr<orm::core::Property>& record) { return mMock.insert(identity, record); } bool Store::update(std::int64_t identity, std::shared_ptr<orm::core::Property>&& record) { return mMock.update(identity, std::forward<std::shared_ptr<orm::core::Property>>(record)); } bool Store::update(std::int64_t identity, const std::shared_ptr<orm::core::Property>& record) { return mMock.update(identity, record); } bool Store::remove(std::int64_t identity) { return mMock.remove(identity); } std::unique_ptr<orm::store::Store> Store::clone() { return mMock.clone(); } } // orm::store_mark namespace
25.956522
95
0.717755
ironbit
187727753cbf4ffc33b237b442477bf1452f9cf8
347
hpp
C++
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
#ifndef __MAINVIEW_H__ #define __MAINVIEW_H__ #include "../scenario.hpp" #include "../context.hpp" #include "../scenarioContext.hpp" #include "../view.hpp" class MainView: public View { private: int subview; public: MainView(Context context); void init(); void loop(SceCtrlData pad, SceCtrlData pad_prev); }; #endif // __MAINVIEW_H__
18.263158
51
0.720461
Tau5
18779c3b9615171d49bdd7503a8e2d6be74892ea
1,334
cpp
C++
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to return max value that can be put in knapsack of capacity W. int knapSack(int W, int wt[], int val[], int n) { // Your code here vector<vector<int>> dp(W+1,vector<int>(n+1)); for(int i=0;i<W+1;i++){ for(int j=0;j<n+1;j++){ if(i==0 or j==0) dp[i][j] = 0; else if(wt[j-1]>i) dp[i][j] = dp[i][j-1]; else dp[i][j] = max(dp[i-wt[j-1]][j-1]+val[j-1],dp[i][j-1]); } } // for(auto e:dp){ // for(auto f:e) cout<<f<<" "; // cout<<endl; // } return dp[W][n]; } }; // { Driver Code Starts. int main() { //taking total testcases int t; cin>>t; while(t--) { //reading number of elements and weight int n, w; cin>>n>>w; int val[n]; int wt[n]; //inserting the values for(int i=0;i<n;i++) cin>>val[i]; //inserting the weights for(int i=0;i<n;i++) cin>>wt[i]; Solution ob; //calling method knapSack() cout<<ob.knapSack(w, wt, val, n)<<endl; } return 0; } // } Driver Code Ends
21.516129
77
0.450525
Coderangshu
187bcf9d3a46194b1e9ad708a033401e9f6f5cf6
283
hpp
C++
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
11
2018-01-10T12:35:04.000Z
2018-08-29T01:47:48.000Z
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
null
null
null
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
2
2018-01-10T13:04:08.000Z
2018-01-10T13:24:12.000Z
#ifndef STRATEGY_HPP #define STRATEGY_HPP #include "game.hpp" game_state_t strategy_init(const game_state_t & state); game_state_t strategy_step(const game_state_t & state, bool *moved); game_state_t strategy_term(game_state_t state); void strategy_print_internal_state(); #endif
23.583333
68
0.823322
fyquah95
187f1e267bf275dd1c60a0dfafa60bf3658cf60d
168
hpp
C++
src/include/streamer/manipulation.hpp
philip1337/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
2
2017-07-23T23:27:03.000Z
2017-07-24T06:18:13.000Z
src/include/streamer/manipulation.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
src/include/streamer/manipulation.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
#ifndef MANIPULATION_HPP #define MANIPULATION_HPP #pragma once #include "config.hpp" STREAMER_BEGIN_NS int Streamer_GetUpperBound(int type); STREAMER_END_NS #endif
12.923077
37
0.827381
philip1337
18869220aaac503fc651d518f224e5118ec6d1b1
210
cpp
C++
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
1
2020-08-21T01:26:47.000Z
2020-08-21T01:26:47.000Z
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
null
null
null
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
1
2020-08-21T01:26:55.000Z
2020-08-21T01:26:55.000Z
#include <boss.hpp> #include "ballstatus.hpp" BallStatus& BallStatus::operator=(const BallStatus& rhs) { Memory::Copy(&mRailCode, &rhs.mRailCode, sizeof(BallStatus) - sizeof(uint32)); return *this; }
23.333333
82
0.709524
BonexGoo
188d5a14490cc58d8bf29d451376f39297ddea5e
35,755
cc
C++
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
31
2020-06-23T13:53:47.000Z
2022-03-28T08:09:00.000Z
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2020-11-01T21:35:47.000Z
2021-08-29T11:40:50.000Z
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2021-03-22T15:32:22.000Z
2022-02-02T14:57:56.000Z
#include <pybind11/pybind11.h> #include <omnetpp.h> #include <omnetpp/ccomponent.h> /* * make public all the protected members of cComponent * we want to expose to python */ class cComponentPublicist : public omnetpp::cComponent { public: using omnetpp::cComponent::initialize; using omnetpp::cComponent::numInitStages; using omnetpp::cComponent::finish; using omnetpp::cComponent::handleParameterChange; using omnetpp::cComponent::refreshDisplay; }; void bind_cComponent(pybind11::module &m) { pybind11::class_<omnetpp::cComponent> py_cComponent( m, "_cComponent", R"docstring( `cComponent` provides parameters, properties, display string, RNG mapping, initialization and finalization support, simulation signals support, and several other services to its subclasses. Initialize and finish functions may be provided by the user, to perform special tasks at the beginning and the end of the simulation. The functions are made protected because they are supposed to be called only via `callInitialize()` and `callFinish()`. The initialization process was designed to support multi-stage initialization of compound modules (i.e. initialization in several 'waves'). (Calling the `initialize()` function of a simple module is hence a special case). The initialization process is performed on a module like this. First, the number of necessary initialization stages is determined by calling `numInitStages()`, then `initialize(stage)` is called with `0,1,...numstages-1` as argument. The default implementation of `numInitStages()` and `initialize(stage)` provided here defaults to single-stage initialization, that is, `numInitStages()` returns 1 and initialize(stage) simply calls initialize() if stage is 0. )docstring" ); pybind11::enum_<omnetpp::cComponent::ComponentKind>(py_cComponent, "ComponentKind") .value("KIND_MODULE", omnetpp::cComponent::ComponentKind::KIND_MODULE) .value("KIND_CHANNEL", omnetpp::cComponent::ComponentKind::KIND_CHANNEL) .value("KIND_OTHER", omnetpp::cComponent::ComponentKind::KIND_OTHER) .export_values(); /* * cComponent is abstract and we don't need to instantiate it from python * so do not add init method. * py_cComponent.def( pybind11::init<const char*>(), R"docstring( Constructor. Note that module and channel objects should not be created directly, via their `cComponentType` objects. `cComponentType.create()` will do all housekeeping associated with creating the module (assigning an ID to the module, inserting it into the `simulation` object, etc.). )docstring", pybind11::arg("name") = nullptr ); */ py_cComponent.def( "initialize", pybind11::overload_cast<>(&cComponentPublicist::initialize), R"docstring( Single-stage initialization hook. This default implementation does nothing. )docstring" ); py_cComponent.def( "initialize", pybind11::overload_cast<int>(&cComponentPublicist::initialize), R"docstring( Multi-stage initialization hook. This default implementation does single-stage init, that is, calls initialize() if stage is 0. )docstring", pybind11::arg("stage") ); py_cComponent.def( "numInitStages", &cComponentPublicist::numInitStages, R"docstring( Multi-stage initialization hook, should be redefined to return the number of initialization stages required. This default implementation does single-stage init, that is, returns 1. )docstring" ); py_cComponent.def( "finish", &cComponentPublicist::finish, R"docstring( Finish hook. `finish()` is called after end of simulation if it terminated without error. This default implementation does nothing. )docstring" ); py_cComponent.def( "handleParameterChange", &cComponentPublicist::handleParameterChange, R"docstring( This method is called by the simulation kernel to notify the module or channel that the value of an existing parameter has changed. Redefining this method allows simple modules and channels to be react on parameter changes, for example by re-reading the value. This default implementation does nothing. The parameter name is `None` if more than one parameter has changed. To make it easier to write predictable components, the function is NOT called on uninitialized components (i.e. when `initialized()` returns `False`). For each component, the function is called (with `None` as a parname) after the last stage of the initialization, so that the module gets a chance to update its cached parameters. Also, one must be extremely careful when changing parameters from inside handleParameterChange(), to avoid creating an infinite notification loop. )docstring", pybind11::arg("parname") ); py_cComponent.def( "refreshDisplay", &cComponentPublicist::refreshDisplay, R"docstring( This method is called on all components of the simulation by graphical user interfaces (Qtenv, Tkenv) whenever GUI contents need to be refreshed after processing some simulation events. Components that contain visualization-related code are expected to override `refreshDisplay()`, and move visualization code display string manipulation, canvas figures maintenance, OSG scene graph update, etc.) into it. As it is unpredictable when and whether this method is invoked, the simulation logic should not depend on it. It is advisable that code in `refreshDisplay()` does not alter the state of the model at all. This behavior is gently encouraged by having this method declared as const. (Data members that do need to be updated inside refreshDisplay(), i.e. those related to visualization, may be declared mutable to allow that). Tkenv and Qtenv invoke `refreshDisplay()` with similar strategies: in Step and Run mode, after each event; in Fast Run and Express Run mode, every time the screen is refereshed, which is typically on the order of once per second. Cmdenv does not invoke `refreshDisplay()` at all. Note that overriding `refreshDisplay()` is generally preferable to doing display updates as part of event handling: it results in essentially zero per-event runtime overhead, and potentially more consistent information being displayed (as all components refresh their visualization, not only the one which has just processed an event.) )docstring" ); py_cComponent.def( "getId", &omnetpp::cComponent::getId, R"docstring( Returns the component's ID in the simulation object (cSimulation). Component IDs are guaranteed to be unique during a simulation run (that is, IDs of deleted components are not reused for new components.) )docstring" ); py_cComponent.def( "getNedTypeName", &omnetpp::cComponent::getNedTypeName, R"docstring( Returns the fully qualified NED type name of the component (i.e. the simple name prefixed with the package name and any existing enclosing NED type names). This method is a shortcut to `self.getComponentType().getFullName()`. )docstring" ); py_cComponent.def( "isModule", &omnetpp::cComponent::isModule, R"docstring( Returns true for cModule and subclasses, otherwise false. )docstring" ); py_cComponent.def( "isChannel", &omnetpp::cComponent::isChannel, R"docstring( Returns true for channels, and false otherwise. )docstring" ); py_cComponent.def( "getSimulation", &omnetpp::cComponent::getSimulation, R"docstring( Returns the simulation the component is part of. Currently may only be invoked if the component's simulation is the active one (see cSimulation::getActiveSimulation()). )docstring", pybind11::return_value_policy::reference ); py_cComponent.def( "getSystemModule", &omnetpp::cComponent::getSystemModule, R"docstring( Returns the toplevel module in the current simulation. This is a shortcut to `self.getSimulation().getSystemModule()`. )docstring" ); py_cComponent.def( "getNumParams", &omnetpp::cComponent::getNumParams, R"docstring( Returns total number of the component's parameters. )docstring" ); py_cComponent.def( "par", pybind11::overload_cast<int>(&omnetpp::cComponent::par), R"docstring( Returns reference to the parameter identified with its index k. Throws an error if the parameter does not exist. )docstring", pybind11::arg("k"), pybind11::return_value_policy::reference ); py_cComponent.def( "par", pybind11::overload_cast<const char *>(&omnetpp::cComponent::par), R"docstring( Returns reference to the parameter specified with its name. Throws an error if the parameter does not exist. )docstring", pybind11::arg("parname"), pybind11::return_value_policy::reference ); py_cComponent.def( "findPar", &omnetpp::cComponent::findPar, R"docstring( Returns index of the parameter specified with its name. Returns -1 if the object doesn't exist. )docstring", pybind11::arg("parname") ); py_cComponent.def( "hasPar", &omnetpp::cComponent::hasPar, R"docstring( Check if a parameter exists. )docstring", pybind11::arg("parname") ); py_cComponent.def( "getRNG", &omnetpp::cComponent::getRNG, R"docstring( Returns the global RNG mapped to local RNG number k. For large indices (k >= map size) the global RNG k is returned, provided it exists. )docstring", pybind11::arg("k") ); py_cComponent.def( "intrand", &omnetpp::cComponent::intrand, R"docstring( Produces a random integer in the range [0,r) using the RNG given with its index. )docstring", pybind11::arg("r"), pybind11::arg("rng") = 0 ); py_cComponent.def( "dblrand", &omnetpp::cComponent::dblrand, R"docstring( Produces a random double in the range [0,1) using the RNG given with its index. )docstring", pybind11::arg("rng") = 0 ); py_cComponent.def( "uniform", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::uniform, pybind11::const_), R"docstring( Returns a random variate with uniform distribution in the range [a,b). :param a, b: the interval, a < b :param rng: index of the component RNG to use, see `getRNG(int)` )docstring", pybind11::arg("a"), pybind11::arg("a"), pybind11::arg("rng") = 0 ); py_cComponent.def( "uniform", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::uniform, pybind11::const_), R"docstring( SimTime version of uniform(double, double, int), for convenience. )docstring", pybind11::arg("a"), pybind11::arg("a"), pybind11::arg("rng") = 0 ); py_cComponent.def( "exponential", pybind11::overload_cast<double, int>(&omnetpp::cComponent::exponential, pybind11::const_), R"docstring( Returns a random variate from the exponential distribution with the given mean (that is, with parameter lambda=1/mean). :param mean: mean value :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "exponential", pybind11::overload_cast<omnetpp::SimTime, int>(&omnetpp::cComponent::exponential, pybind11::const_), R"docstring( SimTime version of exponential(double,int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "normal", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::normal, pybind11::const_), R"docstring( Returns a random variate from the normal distribution with the given mean and standard deviation. :param mean: mean of the normal distribution :param stddev: standard deviation of the normal distribution :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "normal", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::normal, pybind11::const_), R"docstring( SimTime version of normal(double, double, int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "truncnormal", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::truncnormal, pybind11::const_), R"docstring( Normal distribution truncated to nonnegative values. It is implemented with a loop that discards negative values until a nonnegative one comes. This means that the execution time is not bounded: a large negative mean with much smaller stddev is likely to result in a large number of iterations. The mean and stddev parameters serve as parameters to the normal distribution <i>before</i> truncation. The actual random variate returned will have a different mean and standard deviation. :param mean: mean of the normal distribution :param stddev: standard deviation of the normal distribution :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "truncnormal", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::truncnormal, pybind11::const_), R"docstring( SimTime version of truncnormal(double,double,int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "gamma_d", &omnetpp::cComponent::gamma_d, R"docstring( Returns a random variate from the gamma distribution with parameters alpha>0, theta>0. Alpha is known as the "shape" parameter, and theta as the "scale" parameter. Some sources in the literature use the inverse scale parameter beta = 1 / theta, called the "rate" parameter. Various other notations can be found in the literature; our usage of (alpha,theta) is consistent with Wikipedia and Mathematica (Wolfram Research). Gamma is the generalization of the Erlang distribution for non-integer k values, which becomes the alpha parameter. The chi-square distribution is a special case of the gamma distribution. For alpha=1, Gamma becomes the exponential distribution with mean=theta. The mean of this distribution is alpha*theta, and variance is alpha*theta<sup>2</sup>. Generation: if alpha=1, it is generated as exponential(theta). For alpha>1, we make use of the acceptance-rejection method in "A Simple Method for Generating Gamma Variables", George Marsaglia and Wai Wan Tsang, ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000. The alpha < 1 case makes use of the alpha > 1 algorithm, as suggested by the above paper. .. note:: The name gamma_d is chosen to avoid ambiguity with a function of the same name :param alpha: >0 the "shape" parameter :param theta: >0 the "scale" parameter :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("alpha"), pybind11::arg("theta"), pybind11::arg("rng") = 0 ); py_cComponent.def( "beta", &omnetpp::cComponent::beta, R"docstring( Returns a random variate from the beta distribution with parameters alpha1, alpha2. Generation is using relationship to Gamma distribution: if Y1 has gamma distribution with alpha=alpha1 and beta=1 and Y2 has gamma distribution with alpha=alpha2 and beta=2, then Y = Y1/(Y1+Y2) has beta distribution with parameters alpha1 and alpha2. :param alpha1, alpha2: >0 :param rng :index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("alpha1"), pybind11::arg("alpha2"), pybind11::arg("rng") = 0 ); py_cComponent.def( "erlang_k", &omnetpp::cComponent::erlang_k, R"docstring( Returns a random variate from the Erlang distribution with k phases and mean mean. This is the sum of k mutually independent random variables, each with exponential distribution. Thus, the kth arrival time in the Poisson process follows the Erlang distribution. Erlang with parameters m and k is gamma-distributed with alpha=k and beta=m/k. Generation makes use of the fact that exponential distributions sum up to Erlang. :param k: number of phases, k>0 :param mean: >0 :@param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("k"), pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "chi_square", &omnetpp::cComponent::chi_square, R"docstring( Returns a random variate from the chi-square distribution with k degrees of freedom. The chi-square distribution arises in statistics. If Yi are k independent random variates from the normal distribution with unit variance, then the sum-of-squares (sum(Yi^2)) has a chi-square distribution with k degrees of freedom. The expected value of this distribution is k. Chi_square with parameter k is gamma-distributed with alpha=k/2, beta=2. Generation is using relationship to gamma distribution. :param k: degrees of freedom, k>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("k"), pybind11::arg("rng") = 0 ); py_cComponent.def( "student_t", &omnetpp::cComponent::student_t, R"docstring( Returns a random variate from the student-t distribution with i degrees of freedom. If Y1 has a normal distribution and Y2 has a chi-square distribution with k degrees of freedom then X = Y1 / sqrt(Y2/k) has a student-t distribution with k degrees of freedom. Generation is using relationship to gamma and chi-square. :param i: degrees of freedom, i>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("i"), pybind11::arg("rng") = 0 ); py_cComponent.def( "cauchy", &omnetpp::cComponent::cauchy, R"docstring( Returns a random variate from the Cauchy distribution (also called Lorentzian distribution) with parameters a,b where b>0. This is a continuous distribution describing resonance behavior. It also describes the distribution of horizontal distances at which a line segment tilted at a random angle cuts the x-axis. Generation uses inverse transform. :param a: :param b: b>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "triang", &omnetpp::cComponent::triang, R"docstring( Returns a random variate from the triangular distribution with parameters a <= b <= c. Generation uses inverse transform. :param a, b, c: a <= b <= c :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("c"), pybind11::arg("rng") = 0 ); py_cComponent.def( "lognormal", &omnetpp::cComponent::lognormal, R"docstring( Returns a random variate from the lognormal distribution with "scale" parameter m and "shape" parameter w. m and w correspond to the parameters of the underlying normal distribution (m: mean, w: standard deviation.) Generation is using relationship to normal distribution. :param m: "scale" parameter, m>0 :param w: "shape" parameter, w>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("m"), pybind11::arg("w"), pybind11::arg("rng") = 0 ); py_cComponent.def( "weibull", &omnetpp::cComponent::weibull, R"docstring( Returns a random variate from the Weibull distribution with parameters a, b > 0, where a is the "scale" parameter and b is the "shape" parameter. Sometimes Weibull is given with alpha and beta parameters, then alpha=b and beta=a. The Weibull distribution gives the distribution of lifetimes of objects. It was originally proposed to quantify fatigue data, but it is also used in reliability analysis of systems involving a "weakest link," e.g. in calculating a device's mean time to failure. When b=1, Weibull(a,b) is exponential with mean a. Generation uses inverse transform. :param a: the "scale" parameter, a>0 :param b: the "shape" parameter, b>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "pareto_shifted", &omnetpp::cComponent::pareto_shifted, R"docstring( Returns a random variate from the shifted generalized Pareto distribution. Generation uses inverse transform. :param a, b: the usual parameters for generalized Pareto :param c: shift parameter for left-shift :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("c"), pybind11::arg("rng") = 0 ); py_cComponent.def( "intuniform", &omnetpp::cComponent::intuniform, R"docstring( Returns a random integer with uniform distribution in the range [a,b], inclusive. (Note that the function can also return b.) :param a, b: the interval, a<b :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "intuniformexcl", &omnetpp::cComponent::intuniformexcl, R"docstring( Returns a random integer with uniform distribution over [a,b), that is, from [a,b-1]. :param a, b: the interval, a<b :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "bernoulli", &omnetpp::cComponent::bernoulli, R"docstring( Returns the result of a Bernoulli trial with probability p, that is, 1 with probability p and 0 with probability (1-p). Generation is using elementary look-up. :param p: 0=<p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "binomial", &omnetpp::cComponent::binomial, R"docstring( Returns a random integer from the binomial distribution with parameters n and p, that is, the number of successes in n independent trials with probability p. Generation is using the relationship to Bernoulli distribution (runtime is proportional to n). :param n: n>=0 :param p: 0<=p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("n"), pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "geometric", &omnetpp::cComponent::geometric, R"docstring( Returns a random integer from the geometric distribution with parameter p, that is, the number of independent trials with probability p until the first success. This is the n=1 special case of the negative binomial distribution. Generation uses inverse transform. :param p: 0<p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "negbinomial", &omnetpp::cComponent::negbinomial, R"docstring( Returns a random integer from the negative binomial distribution with parameters n and p, that is, the number of failures occurring before n successes in independent trials with probability p of success. Generation is using the relationship to geometric distribution (runtime is proportional to n). :param n: n>=0 :param p: 0<p<1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("n"), pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "poisson", &omnetpp::cComponent::poisson, R"docstring( Returns a random integer from the Poisson distribution with parameter lambda, that is, the number of arrivals over unit time where the time between successive arrivals follow exponential distribution with parameter lambda. Lambda is also the mean (and variance) of the distribution. Generation method depends on value of lambda: - 0<lambda<=30: count number of events - lambda>30: Acceptance-Rejection due to Atkinson (see Banks, page 166) :param lambda: > 0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("lambda"), pybind11::arg("rng") = 0 ); py_cComponent.def_static( "registerSignal", &omnetpp::cComponent::registerSignal, R"docstring( Returns the signal ID (handle) for the given signal name. Signal names and IDs are global. The signal ID for a particular name gets assigned at the first registerSignal() call; further registerSignal() calls for the same name will return the same ID. )docstring", pybind11::arg("name") ); py_cComponent.def_static( "getSignalName", &omnetpp::cComponent::getSignalName, R"docstring( The inverse of `registerSignal()`: returns the name of the given signal, or `None` for invalid signal handles. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, long, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the long value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("l"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, double, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the double value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("d"), pybind11::arg("details") = nullptr); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const omnetpp::SimTime&, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the simtime_t value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("t"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const char*, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the given string as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("s"), pybind11::arg("details") = nullptr); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const omnetpp::cObject*, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the given object as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("obj"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, bool, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the boolean value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("b"), pybind11::arg("details") = nullptr ); py_cComponent.def( "mayHaveListeners", &omnetpp::cComponent::mayHaveListeners, R"docstring( If producing a value for a signal has a significant runtime cost, this method can be used to check beforehand whether the given signal possibly has any listeners at all. if not, emitting the signal can be skipped. This method has a constant cost but may return false positive. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "hasListeners", &omnetpp::cComponent::hasListeners, R"docstring( Returns true if the given signal has any listeners. In the current implementation, this involves checking listener lists in ancestor modules until the first listener is found, or up to the root. This method may be useful if producing the data for an emit() call would be expensive compared to a hasListeners() call. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "recordScalar", pybind11::overload_cast<const char *, double, const char *>(&omnetpp::cComponent::recordScalar), R"docstring( Records a double into the scalar result file. )docstring", pybind11::arg("name"), pybind11::arg("value"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "recordScalar", pybind11::overload_cast<const char *, omnetpp::simtime_t, const char *>(&omnetpp::cComponent::recordScalar), R"docstring( Convenience method, delegates to recordScalar(const char *, double, const char*). )docstring", pybind11::arg("name"), pybind11::arg("value"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "hasGUI", &omnetpp::cComponent::hasGUI, R"docstring( Returns true if the current environment is a graphical user interface. (For example, it returns true if the simulation is running over Tkenv/Qtenv, and false if it's running over Cmdenv.) Modules can examine this flag to decide whether or not they need to bother with visualization, e.g. dynamically update display strings or draw on canvases. This method delegates to cEnvir::isGUI(). )docstring" ); py_cComponent.def( "getDisplayString", &omnetpp::cComponent::getDisplayString, R"docstring( Returns the display string which defines presentation when the module is displayed as a submodule in a compound module graphics. )docstring", pybind11::return_value_policy::reference ); py_cComponent.def( "setDisplayString", &omnetpp::cComponent::setDisplayString, R"docstring( Shortcut to `getDisplayString().set(dispstr)` )docstring", pybind11::arg("dispstr") ); py_cComponent.def( "bubble", &omnetpp::cComponent::bubble, R"docstring( When the models is running under Tkenv or Qtenv, it displays the given text in the network graphics, as a bubble above the module's icon. )docstring", pybind11::arg("text") ); py_cComponent.def( "recordStatistic", pybind11::overload_cast<omnetpp::cStatistic *, const char *>(&omnetpp::cComponent::recordStatistic), R"docstring( Records the given statistics into the scalar result file. Delegates to cStatistic::recordAs(). Note that if the statistics object is a histogram, this operation may invoke its transform() method. )docstring", pybind11::arg("stats"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "recordStatistic", pybind11::overload_cast<const char *, omnetpp::cStatistic *, const char *>(&omnetpp::cComponent::recordStatistic), R"docstring( Records the given statistics into the scalar result file. Delegates to cStatistic::recordAs(). Note that if the statistics object is a histogram, this operation may invoke its transform() method. )docstring", pybind11::arg("name"), pybind11::arg("stats"), pybind11::arg("unit") = nullptr ); }
38.695887
127
0.646315
ranarashadmahmood
188deba36441ae6ebeafde6fc6f303409baa2ba8
451
cpp
C++
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
9
2018-07-21T00:30:35.000Z
2021-09-04T02:54:11.000Z
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
null
null
null
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
1
2021-12-03T14:12:41.000Z
2021-12-03T14:12:41.000Z
/// \file S_LookAt.cpp /// \date 06/08/2018 /// \project OOM-Engine /// \package Composite /// \author Vincent STEHLY--CALISTO #include "SDK/SDK.hpp" /*virtual */ void S_LookAt::Start() { GetTransform()->LookAt(mp_target->GetTransform()); } /*virtual */ void S_LookAt::Update() { GetTransform()->LookAt(mp_target->GetTransform()); } void S_LookAt::SetTarget(Oom::CGameObject* p_game_object) { mp_target = p_game_object; }
19.608696
57
0.660754
Aredhele
1897978d06090c03b05b161c0623079c38bab094
1,416
hpp
C++
android-31/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" namespace android::os::health { class TimerStat; } class JString; namespace android::os::health { class HealthStats : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit HealthStats(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} HealthStats(QJniObject obj); // Constructors // Methods JString getDataType() const; jlong getMeasurement(jint arg0) const; jint getMeasurementKeyAt(jint arg0) const; jint getMeasurementKeyCount() const; JObject getMeasurements(jint arg0) const; jint getMeasurementsKeyAt(jint arg0) const; jint getMeasurementsKeyCount() const; JObject getStats(jint arg0) const; jint getStatsKeyAt(jint arg0) const; jint getStatsKeyCount() const; android::os::health::TimerStat getTimer(jint arg0) const; jint getTimerCount(jint arg0) const; jint getTimerKeyAt(jint arg0) const; jint getTimerKeyCount() const; jlong getTimerTime(jint arg0) const; JObject getTimers(jint arg0) const; jint getTimersKeyAt(jint arg0) const; jint getTimersKeyCount() const; jboolean hasMeasurement(jint arg0) const; jboolean hasMeasurements(jint arg0) const; jboolean hasStats(jint arg0) const; jboolean hasTimer(jint arg0) const; jboolean hasTimers(jint arg0) const; }; } // namespace android::os::health
27.764706
152
0.738701
YJBeetle
18a1a13ed16965bcbc7647a731537a22cba44e44
5,197
cpp
C++
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
#include "CustomArduboy.h" #include "Arduboy_audio.h" const byte PROGMEM tune_pin_to_timer_PGM[] = { 3, 1 }; volatile byte *_tunes_timer1_pin_port; volatile byte _tunes_timer1_pin_mask; volatile byte *_tunes_timer3_pin_port; volatile byte _tunes_timer3_pin_mask; byte _tune_pins[AVAILABLE_TIMERS]; #define LOWEST_NOTE 52 #define FIRST_NOTE_IN_INT_ARRAY 52 #define HIGHEST_NOTE 82 // Table of midi note frequencies * 2 // They are times 2 for greater accuracy, yet still fits in a word. // Generated from Excel by =ROUND(2*440/32*(2^((x-9)/12)),0) for 0<x<128 // The lowest notes might not work, depending on the Arduino clock frequency // Ref: http://www.phy.mtu.edu/~suits/notefreqs.html //const uint8_t PROGMEM _midi_byte_note_frequencies[] = { //16,17,18,19,21,22,23,24,26,28, // note 0 to 9 //29,31,33,35,37,39,41,44,46,49, // note 10 to 19 //52,55,58,62,65,69,73,78,82,87, // note 20 to 29 //92,98,104,110,117,123,131,139,147,156, // note 30 to 39 //165,175,185,196,208,220,233,247 // note 40 to 47 //}; const unsigned int PROGMEM _midi_word_note_frequencies[] = { //262,277,294, //note 48 to 50 /*311,*/330,349,370,392,415,440,466,494,523, //note 51 to 60 554,587,622,659,698,740,784,831,880,932, //note 61 to 70 988,1047,1109,1175,1245,1319,1397,1480,1568,1661, //note 71 to 80 1760,1865//,1976,2093,2217,2349,2489,2637,2794,2960, //note 81 to 90 //3136,3322,3520,3729,3951,4186,4435,4699,4978,5274, //note 91 to 100 //5588,5920,6272,6645,7040,7459,7902,8372,8870,9397, //note 101 to 110 //9956,10548,11175,11840,12544,13290,14080,14917,15804,16744, //note 111 to 120 //17740,18795,19912,21096,22351,23680,25088 //note 121 to 127 }; unsigned int NoteToFrequency(byte note) { return pgm_read_word(_midi_word_note_frequencies + note - FIRST_NOTE_IN_INT_ARRAY); } /* AUDIO */ void ArduboyAudio::on() { power_timer1_enable(); power_timer3_enable(); } void ArduboyAudio::off() { power_timer1_disable(); power_timer3_disable(); } void ArduboyAudio::begin() { on(); } /* TUNES */ void ArduboyTunes::initChannel(byte pin, byte chan) { byte timer_num; // we are all out of timers if (chan >= AVAILABLE_TIMERS) return; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); _tune_pins[chan] = pin; pinMode(pin, OUTPUT); switch (timer_num) { case 1: // 16 bit timer TCCR1A = 0; TCCR1B = 0; bitWrite(TCCR1B, WGM12, 1); bitWrite(TCCR1B, CS10, 1); _tunes_timer1_pin_port = portOutputRegister(digitalPinToPort(pin)); _tunes_timer1_pin_mask = digitalPinToBitMask(pin); break; case 3: // 16 bit timer TCCR3A = 0; TCCR3B = 0; bitWrite(TCCR3B, WGM32, 1); bitWrite(TCCR3B, CS30, 1); _tunes_timer3_pin_port = portOutputRegister(digitalPinToPort(pin)); _tunes_timer3_pin_mask = digitalPinToBitMask(pin); playNote(0, 60); /* start and stop channel 0 (timer 3) on middle C so wait/delay works */ stopNote(0); break; } } void ArduboyTunes::playNote(byte chan, byte note) { byte timer_num; byte prescalar_bits; unsigned int frequency2; /* frequency times 2 */ unsigned long ocr; // we can't plan on a channel that does not exist if (chan >= AVAILABLE_TIMERS) return; // we only have frequencies for a certain range of notes if ((note < LOWEST_NOTE) || (note > HIGHEST_NOTE)) return; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); //if (note < 48) // frequency2 = pgm_read_byte(_midi_byte_note_frequencies + note - LOWEST_NOTE); //else frequency2 = pgm_read_word(_midi_word_note_frequencies + note - FIRST_NOTE_IN_INT_ARRAY); //****** 16-bit timer ********* // two choices for the 16 bit timers: ck/1 or ck/64 ocr = F_CPU / frequency2 - 1; prescalar_bits = 0b001; if (ocr > 0xffff) { ocr = F_CPU / frequency2 / 64 - 1; prescalar_bits = 0b011; } // Set the OCR for the given timer, then turn on the interrupts switch (timer_num) { case 1: TCCR1B = (TCCR1B & 0b11111000) | prescalar_bits; OCR1A = ocr; bitWrite(TIMSK1, OCIE1A, 1); break; case 3: TCCR3B = (TCCR3B & 0b11111000) | prescalar_bits; OCR3A = ocr; bitWrite(TIMSK3, OCIE3A, 1); break; } } void ArduboyTunes::stopNote(byte chan) { byte timer_num; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); switch (timer_num) { case 1: TIMSK1 &= ~(1 << OCIE1A); // disable the interrupt *_tunes_timer1_pin_port &= ~(_tunes_timer1_pin_mask); // keep pin low after stop break; case 3: *_tunes_timer3_pin_port &= ~(_tunes_timer3_pin_mask); // keep pin low after stop break; } } void ArduboyTunes::closeChannels(void) { byte timer_num; for (uint8_t chan=0; chan < AVAILABLE_TIMERS; chan++) { timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); switch (timer_num) { case 1: TIMSK1 &= ~(1 << OCIE1A); break; case 3: TIMSK3 &= ~(1 << OCIE3A); break; } digitalWrite(_tune_pins[chan], 0); } } // TIMER 1 ISR(TIMER1_COMPA_vect) { *_tunes_timer1_pin_port ^= _tunes_timer1_pin_mask; // toggle the pin } // TIMER 3 ISR(TIMER3_COMPA_vect) { }
28.091892
96
0.675005
Lswbanban
18a67c1af6a1acb3f30fa8032f9d7e1c055c7db6
1,675
cpp
C++
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
#include "Triangulation.h" #include <iostream> Triangulation::Triangulation( const Eigen::MatrixXd& P0, const Eigen::MatrixXd& P1, const Eigen::VectorXd& x0, const Eigen::VectorXd& x1): P(P0, P1), x(x0, x1) { } Triangulation::Triangulation(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& _P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& _x): P(_P), x(_x) { } Eigen::VectorXd Triangulation::solve() const { return Triangulation::solve(P, x); } Eigen::VectorXd Triangulation::solve(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& x) { Eigen::MatrixXd A = buildMatrixA(P, x); //std::cout << "A:\n" << A << std::endl << std::endl; Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinV); Eigen::VectorXd X = svd.matrixV().rightCols(1); X /= X(3); return X; } Eigen::MatrixXd Triangulation::buildMatrixA(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& x) { Eigen::MatrixXd A(4, 4); #if 0 A.row(0) = x.first.x() * P.first.row(2) - P.first.row(0); A.row(1) = x.first.y() * P.first.row(2) - P.first.row(1); A.row(2) = x.second.x() * P.second.row(2) - P.second.row(0); A.row(3) = x.second.y() * P.second.row(2) - P.second.row(1); #else A.row(0) = (x.first.x() * P.first.row(2) - P.first.row(0)).normalized(); A.row(1) = (x.first.y() * P.first.row(2) - P.first.row(1)).normalized(); A.row(2) = (x.second.x() * P.second.row(2) - P.second.row(0)).normalized(); A.row(3) = (x.second.y() * P.second.row(2) - P.second.row(1)).normalized(); #endif return A; }
24.275362
97
0.619701
diegomazala
18aabab0761eaa85dc96d77a702af78561d28097
8,874
cpp
C++
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
3
2020-11-23T23:53:30.000Z
2021-12-26T16:14:23.000Z
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
4
2020-12-05T17:58:31.000Z
2020-12-13T00:54:28.000Z
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
1
2021-09-24T21:04:12.000Z
2021-09-24T21:04:12.000Z
//----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QNetworkConfigurationManager> #include <QNetworkReply> #include <QProcessEnvironment> #include <QUrlQuery> #include "Common/Logging.h" #include "WeatherModel.h" //----------------------------------------------------------------------------- static const double ZERO_KELVIN = 273.15; WeatherModel::WeatherModel(QObject* parent) : QObject(parent), _src(nullptr), _nam(nullptr), _ns(nullptr), _nErrors(0), _minMsBeforeNewRequest(baseMsBeforeNewRequest), m_weatherDataAppId(QProcessEnvironment::systemEnvironment().value("QPF_WEATHERDATA_APPID")) { if (m_weatherDataAppId.isEmpty()) { qCCritical(weatherModelLog()) << "Critical error: QPF_WEATHERDATA_APPID not set. Unable to retrieve weather data."; } _delayedCityRequestTimer.setSingleShot(true); _delayedCityRequestTimer.setInterval(1000); // 1 s _requestNewWeatherTimer.setSingleShot(false); _requestNewWeatherTimer.setInterval(20 * 60 * 1000); // 20 mins _throttle.invalidate(); connect(&_delayedCityRequestTimer, SIGNAL(timeout()), this, SLOT(queryCity())); connect(&_requestNewWeatherTimer, SIGNAL(timeout()), this, SLOT(refreshWeather())); _requestNewWeatherTimer.start(); _nam = new QNetworkAccessManager; QNetworkConfigurationManager ncm; _ns = new QNetworkSession(ncm.defaultConfiguration(), this); connect(_ns, SIGNAL(opened()), this, SLOT(networkSessionOpened())); if (_ns->isOpen()) { this->networkSessionOpened(); } _ns->open(); } WeatherModel::~WeatherModel() { _ns->close(); if (_src) { _src->stopUpdates(); } } bool WeatherModel::ready() const { return _ready; } bool WeatherModel::hasSource() const { return (_src != nullptr); } void WeatherModel::hadError(bool tryAgain) { qCDebug(weatherModelLog) << "hadError, will " << (tryAgain ? "" : "not ") << "rety"; _throttle.start(); if (_nErrors < 10) { ++_nErrors; } _minMsBeforeNewRequest = (_nErrors + 1) * baseMsBeforeNewRequest; if (tryAgain) { _delayedCityRequestTimer.start(); } } void WeatherModel::refreshWeather() { if (_city.isEmpty()) { qCDebug(weatherModelLog) << "Cannot refresh weather, no city"; return; } qCDebug(weatherModelLog) << "refreshing weather"; QUrl url("http://api.openweathermap.org/data/2.5/weather"); QUrlQuery query; query.addQueryItem("q", _city); query.addQueryItem("mode", "json"); query.addQueryItem("APPID", m_weatherDataAppId); url.setQuery(query); QNetworkReply* rep = _nam->get(QNetworkRequest(url)); connect(rep, &QNetworkReply::finished, this, [this, rep]() { handleWeatherNetworkData(rep); }); } bool WeatherModel::hasValidCity() const { return (!(_city.isEmpty()) && _city.size() > 1 && _city != ""); } bool WeatherModel::hasValidWeather() const { return hasValidCity() && (!(_now.weatherIcon().isEmpty()) && (_now.weatherIcon().size() > 1) && _now.weatherIcon() != ""); } QString WeatherModel::city() const { return _city; } void WeatherModel::setCity(const QString& value) { _city = value; emit cityChanged(); refreshWeather(); } WeatherData* WeatherModel::weather() const { return const_cast<WeatherData*>(&(_now)); } void WeatherModel::queryCity() { // Don't update more than once a minute to keep server load low if (_throttle.isValid() && _throttle.elapsed() < _minMsBeforeNewRequest) { qCDebug(weatherModelLog) << "delaying query of city"; if (_delayedCityRequestTimer.isActive()) { _delayedCityRequestTimer.start(); } } qCDebug(weatherModelLog) << "requested city"; _throttle.start(); _minMsBeforeNewRequest = (_nErrors + 1) * baseMsBeforeNewRequest; QString latitude, longitude; longitude.setNum(_coord.longitude()); latitude.setNum(_coord.latitude()); QUrl url("http://api.openweathermap.org/data/2.5/weather"); QUrlQuery query; query.addQueryItem("lat", latitude); query.addQueryItem("lon", longitude); query.addQueryItem("mode", "json"); query.addQueryItem("APPID", m_weatherDataAppId); url.setQuery(query); qCDebug(weatherModelLog) << "submitting API request"; QNetworkReply* rep = _nam->get(QNetworkRequest(url)); // connect up the signal right away connect(rep, &QNetworkReply::finished, this, [this, rep]() { handleGeoNetworkData(rep); }); } void WeatherModel::networkSessionOpened() { _src = QGeoPositionInfoSource::createDefaultSource(this); if (_src) { connect(_src, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); connect(_src, SIGNAL(error(QGeoPositionInfoSource::Error)), this, SLOT(positionError(QGeoPositionInfoSource::Error))); _src->startUpdates(); } else { qCDebug(weatherModelLog) << "Could not create default source."; } } void WeatherModel::positionUpdated(QGeoPositionInfo gpsPos) { qCDebug(weatherModelLog) << "WeatherModel::positionUpdated(...)"; _coord = gpsPos.coordinate(); queryCity(); } void WeatherModel::positionError(QGeoPositionInfoSource::Error e) { qCDebug(weatherModelLog) << "WeatherModel::positionError(...): " << e; } void WeatherModel::handleGeoNetworkData(QNetworkReply* networkReply) { qCDebug(weatherModelLog) << "WeatherModel::handleGeoNetworkData(...)"; if (!networkReply) { hadError(false); // should retry? return; } if (!networkReply->error()) { _nErrors = 0; if (!_throttle.isValid()) { _throttle.start(); } _minMsBeforeNewRequest = baseMsBeforeNewRequest; //convert coordinates to city name QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jo = document.object(); QJsonValue jv = jo.value(QStringLiteral("name")); const QString city = jv.toString(); qCDebug(weatherModelLog) << "got city: " << city; if (city != _city) { _city = city; emit cityChanged(); refreshWeather(); } } else { hadError(true); } networkReply->deleteLater(); } static QString niceTemperatureString(double t) { return QString::number((t - ZERO_KELVIN), 'f', 1)/* + QChar(0xB0)*/; } void WeatherModel::handleWeatherNetworkData(QNetworkReply* networkReply) { qCDebug(weatherModelLog) << "WeatherModel::handleWeatherNetworkData(...)"; if (!networkReply) { return; } if (!networkReply->error()) { foreach (WeatherData* inf, _forecast) { delete inf; } _forecast.clear(); QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); if (document.isObject()) { QJsonObject obj = document.object(); QJsonObject tempObject; QJsonValue val; if (obj.contains(QStringLiteral("weather"))) { val = obj.value(QStringLiteral("weather")); QJsonArray weatherArray = val.toArray(); val = weatherArray.at(0); tempObject = val.toObject(); _now.setWeatherDescription(tempObject.value(QStringLiteral("description")).toString()); _now.setWeatherIcon(tempObject.value("icon").toString()); } if (obj.contains(QStringLiteral("main"))) { val = obj.value(QStringLiteral("main")); tempObject = val.toObject(); val = tempObject.value(QStringLiteral("temp")); _now.setTemperature(niceTemperatureString(val.toDouble())); } } } networkReply->deleteLater(); //retrieve the forecast // QUrl url("http://api.openweathermap.org/data/2.5/forecast/daily"); // QUrlQuery query; // query.addQueryItem("q", d->city); // query.addQueryItem("mode", "json"); // query.addQueryItem("cnt", "5"); // query.addQueryItem("APPID", d->app_ident); // url.setQuery(query); // QNetworkReply *rep = d->nam->get(QNetworkRequest(url)); // // connect up the signal right away // connect(rep, &QNetworkReply::finished, this, [this, rep]() { // handleForecastNetworkData(rep); // }); // Move this to handleForecastNetworkData emit weatherChanged(); } void WeatherModel::handleForecastNetworkData(QNetworkReply* networkReply) { Q_UNUSED(networkReply) qCDebug(weatherModelLog) << "WeatherModel::handleForecastNetworkData(...)"; }
29.878788
126
0.630156
patrickn
18ad9c5af589eab8c064ad9cb769055557a78b39
1,614
cpp
C++
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
/* Secret Salsa Matthew Carlin Copyright 2019 */ #include "honey.h" #include <string> #include <array> using namespace Honey; using namespace std; position player_position; int step_width; float frame_delay; int current_frame; bool quit = false; void initialize() { player_position = { hot_config.getInt("walk", "starting_x"), hot_config.getInt("walk", "starting_y") }; step_width = hot_config.getInt("walk", "step_width"); frame_delay = hot_config.getFloat("walk", "frame_delay"); graphics.addImages("Art/", { "Walk1", "Walk2", "Walk3", "Walk4", }); current_frame = 4; } void logic() { if (input.keyPressed("quit") > 0) { quit = true; } if (input.threeQuickKey("escape")) { quit = true; } if (!timing.check("animate") || timing.since("animate") > frame_delay) { current_frame += 1; if (current_frame > 4) current_frame = 1; if (current_frame == 2 || current_frame == 4) { player_position.x += 85; } else { player_position.x += 5; } timing.mark("animate"); } if (player_position.x > hot_config.getInt("layout", "screen_width")) { player_position.x = -250; } } void render() { graphics.clearScreen("#EEEEEE"); graphics.setColor("#FFFFFF", 1.0); graphics.drawImage( "Walk" + to_string(current_frame), player_position.x, player_position.y ); } int main(int argc, char* args[]) { StartHoney("Secret Salsa WorldBuilder"); graphics.draw2D(); initialize(); while (!quit) { input.processInput(); logic(); render(); graphics.updateDisplay(); } }
16.989474
74
0.627633
bugsbycarlin
18ae5a2da6dfcf3eff7523efdd669f7314a3dc93
8,356
cpp
C++
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
6
2022-03-24T15:40:03.000Z
2022-03-30T09:40:20.000Z
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
7
2022-03-24T18:53:52.000Z
2022-03-30T10:15:50.000Z
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
1
2022-03-20T21:22:09.000Z
2022-03-20T21:22:09.000Z
#include "api/sys/common/ByteBuffer.hpp" #include "api/sys/trace/Trace.hpp" #define CLASS_ABBR "B_BUFFER" using namespace carpc; ByteBuffer::ByteBuffer( const size_t capacity ) { if( true == allocate( capacity ) ) fill( ); } ByteBuffer::ByteBuffer( const void* p_buffer, const size_t size ) { if( false == allocate( size ) ) { SYS_ERR( "unable to allocate %zu bytes", size ); return; } if( false == push( p_buffer, size ) ) { SYS_ERR( "unable to fullfil buffer" ); return; } // SYS_INF( "created: " ); // dump( ); } ByteBuffer::ByteBuffer( const ByteBuffer& buffer ) { if( false == allocate( buffer.m_size ) ) { SYS_ERR( "unable to allocate %zu bytes", buffer.m_size ); return; } if( false == push( buffer ) ) { SYS_ERR( "unable to fullfil buffer" ); return; } // SYS_INF( "created: " ); // dump( ); } ByteBuffer::~ByteBuffer( ) { reset( ); } void ByteBuffer::dump( ) const { // leads to core dump // std::stringstream ss; // for( size_t i = 0; i < m_size; ++i ) // ss << std::setfill('0') << std::setw(2) << std::showbase << std::hex << static_cast< size_t >( mp_buffer[i] ) << " "; // SYS_INF( "%s", ss.str( ).c_str( ) ); for( size_t i = 0; i < m_size; ++i ) printf( "%#x ", static_cast< uint8_t* >( mp_buffer )[i] ); printf( "\n" ); } void ByteBuffer::info( ) const { SYS_INF( "address: %p / capacity: %zu / size: %zu", mp_buffer, m_capacity, m_size ); } void ByteBuffer::fill( const char symbol ) { memset( mp_buffer, symbol, m_capacity ); } bool ByteBuffer::allocate( const size_t capacity ) { // Nothing to allocate if( 0 == capacity ) return false; // Buffer already allocated if( nullptr != mp_buffer ) return false; mp_buffer = malloc( capacity ); // Allocate error if( nullptr == mp_buffer ) return false; m_capacity = capacity; return true; } bool ByteBuffer::reallocate( const size_t capacity, const bool is_store ) { // Nothing to allocate if( 0 == capacity ) return false; // What is the sense of reallocation? if( capacity == m_capacity ) return false; // Allocating buffer because is was not allocated before if( nullptr == mp_buffer ) return allocate( capacity ); // Storing previous data during reallocation is requested but // current data size is more then requested capacity if( true == is_store && m_size > capacity ) return false; void* p_buffer = malloc( capacity ); // Allocate error if( nullptr == p_buffer ) return false; // Copying current data to new buffer => size will be the same if( true == is_store ) memcpy( p_buffer, mp_buffer, m_size ); // Storing data was not requested => size should be 0 else m_size = 0; free( mp_buffer ); mp_buffer = p_buffer; m_capacity = capacity; return true; } bool ByteBuffer::trancate( ) { if( m_size == m_capacity ) return true; return reallocate( m_size, true ); } void ByteBuffer::reset( ) { if( nullptr != mp_buffer ) free( mp_buffer ); // Reset data mp_buffer = nullptr; m_size = m_capacity = 0; } /***************************************** * * Read / Write buffer methods * ****************************************/ bool ByteBuffer::write( const void* p_buffer, const size_t size, const bool is_reallocate ) { // Nothing to push if( 0 == size ) return false; // Buffer is not allocated if( nullptr == p_buffer ) return false; // Buffer is not allocated if( nullptr == mp_buffer ) return false; // Reallocating buffer is requested with saving prevous content if( ( m_capacity - m_size ) < size ) { if( true == is_reallocate ) { if( false == reallocate( m_size + size, true ) ) return false; } else return false; } memcpy( static_cast< uint8_t* >( mp_buffer ) + m_size, p_buffer, size ); return true; } bool ByteBuffer::read( const void* p_buffer, const size_t size ) { // Not enough data to pop if( size > m_size ) return false; // Nothing to pop if( 0 == size ) return false; // Buffer is not allocated if( nullptr == p_buffer ) return false; // Buffer is not allocated if( nullptr == mp_buffer ) return false; memcpy( const_cast< void* >( p_buffer ), static_cast< uint8_t* >( mp_buffer ) + m_size - size, size ); return true; } /***************************************** * * Push buffer methods * ****************************************/ bool ByteBuffer::push( void* p_buffer, const size_t size, const bool is_reallocate ) { return push( const_cast< const void* >( p_buffer ), size, is_reallocate ); } bool ByteBuffer::push( const void* p_buffer, const size_t size, const bool is_reallocate ) { if( false == write( p_buffer, size, is_reallocate ) ) return false; m_size += size; return true; } bool ByteBuffer::push( const void* const p_buffer, const bool is_reallocate ) { if( false == write( &p_buffer, sizeof( void* ), is_reallocate ) ) return false; m_size += sizeof( void* ); return true; } bool ByteBuffer::push( const std::string& string, const bool is_reallocate ) { const void* p_buffer = static_cast< const void* >( string.c_str( ) ); const size_t size = string.size( ); return push_buffer_with_size( p_buffer, size, is_reallocate ); } bool ByteBuffer::push( const ByteBuffer& _buffer, const bool is_reallocate ) { const void* p_buffer = _buffer.mp_buffer; const size_t size = _buffer.m_size; return push_buffer_with_size( p_buffer, size, is_reallocate ); } bool ByteBuffer::push_buffer_with_size( const void* p_buffer, const size_t size, const bool is_reallocate ) { // Backup buffer state. size_t size_backup = m_size; // It should be possible to store next amount of bytes: content size + size of content. if( ( m_capacity - m_size ) < ( size + sizeof( size ) ) && false == is_reallocate ) return false; // Storing buffer content if( false == push( p_buffer, size, is_reallocate ) ) return false; // Storing size of buffer. In case of error prevoius buffer state will be restored. // In this case stored buffer content will be deleted. if( false == push( size, is_reallocate ) ) { m_size = size_backup; return false; } return true; } /***************************************** * * Pop buffer methods * ****************************************/ bool ByteBuffer::pop( void* p_buffer, const size_t size ) { return pop( const_cast< const void* >( p_buffer ), size ); } bool ByteBuffer::pop( const void* p_buffer, const size_t size ) { if( false == read( p_buffer, size ) ) return false; m_size -= size; return true; } bool ByteBuffer::pop( const void*& p_buffer ) { if( false == read( &p_buffer, sizeof( void* ) ) ) return false; m_size -= sizeof( void* ); return true; } bool ByteBuffer::pop( std::string& string ) { // Backup buffer state. size_t size_backup = m_size; size_t size = 0; // Reading size of string content if( false == pop( size ) ) return false; // Error in case of rest of data in buffer less then size to be read. // push previously poped data to restore previous buffer state. if( size > m_size ) { m_size = size_backup; return false; } char p_buffer[ size + 1 ]; // +1 for termitating '\0' if( false == pop( static_cast< void* >( p_buffer ), size ) ) return false; // Adding termitating '\0' p_buffer[ size + 1 - 1 ] = 0; string = p_buffer; return true; } bool ByteBuffer::pop( ByteBuffer& _buffer ) { // Backup buffer state. size_t size_backup = m_size; size_t size = 0; // Reading size of string content if( false == pop( size ) ) return false; // Error in case of rest of data in buffer less then size to be read. // push previously poped data to restore previous buffer state. if( size > m_size ) { m_size = size_backup; return false; } void* p_buffer = malloc( size ); if( false == pop( p_buffer, size ) ) { free( p_buffer ); return false; } if( false == _buffer.push( p_buffer, size ) ) { free( p_buffer ); return false; } free( p_buffer ); return true; }
23.275766
126
0.61034
dterletskiy
18b624c1e5950224ef77b44e0e041667b8d75fe3
5,707
cc
C++
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
11
2019-08-21T04:35:36.000Z
2021-07-13T02:11:21.000Z
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
null
null
null
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
1
2020-03-30T07:39:53.000Z
2020-03-30T07:39:53.000Z
#include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <sys/types.h> #include <set> #include <map> #include <unordered_map> #include <sparsepp/spp.h> #include <thread> #include <iostream> #include <sstream> #include <string> #include <exception> #include <chrono> #include "utils.h" #include "kv_string.h" #include "KeyFile.h" #include "params.h" std::shared_ptr<spp::sparse_hash_map<int64_t , int32_t>> KeyFile::keyOrderMaparray_[16]; int KeyFile::mapCnt_ = 0; std::mutex KeyFile::mutex_[16]; std::condition_variable KeyFile::Condition_; KeyFile::KeyFile(DataAgent* agent, int id, bool exist) :keyFilePosition_(0), keyOrderMap_(new spp::sparse_hash_map<int64_t , int32_t>()) { // 设置链接的接口 // 构建索引(在第一个findkey调用) // 设置目前索引含有key的量:keyFilePosition_ agent_ = agent; id_ = id; this->keyCacheBuffer_ = new char[4000000*8]; //四百万个8byte //int keyNum = ConstructKeyOrderMap(0); //keyFilePosition_ = keyNum; // 下面与预判有关 this->state_ = 0; keyOrderMaparray_[id_] = this->keyOrderMap_; } KeyFile::~KeyFile() { KV_LOG(INFO) << "~KeyFile id:" << id_; mapCnt_ = 0; if(keyCacheBuffer_ != nullptr) delete []keyCacheBuffer_; } // 构建 map<key, order> int KeyFile::ConstructKeyOrderMap(int begin) { //printf("\nstart KeyFile::ConstructKeyOrderMap\n"); int32_t pos = begin; int64_t k = 0; int len = 0; std::lock_guard<std::mutex> lock(mutex_[id_]); if( (len = agent_->GetKeys(KV_OP_META_GET, pos, this->keyCacheBuffer_, 0, pos)) > 0) { // 接收一次,获取 keyFile //printf("start build map:%d\n", id_); KV_LOG(INFO) << "start build map:" << id_; for (; pos < len; ++pos) { k = *(int64_t*)(this->keyCacheBuffer_ + pos * sizeof(int64_t)); try { this->keyOrderMap_->insert(pair<int64_t, int32_t>(k, pos)); } catch(const std::exception& e) { std::cerr << e.what() << "keyOrderMap_->insert\n"; delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return -1; } } } else { delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return -1; } this->keyFilePosition_ = len;//max(len, this->keyFilePosition_); //printf("id:%d,build Map success,len: %d, setting agent.valueFilePositon\n",id_, len); KV_LOG(INFO) << "id:" << id_ << ",build Map success,len:" << len << "setting agent.valueFilePositon"; this->agent_->SetValueFilePosition(this->keyFilePosition_); delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return pos; } int64_t KeyFile::FindKey(int64_t key, int &fileId) { //printf("FindKey,id:%d\n", id_); if (unlikely(this->keyOrderMap_->empty())) { // 不存在, 构建 Map if(this->ConstructKeyOrderMap(0) == -1) return -1; std::this_thread::sleep_for(std::chrono::milliseconds(100));// 确保其他线程进入了map构建阶段 // 将构建好的map放到全局map数组 //keyOrderMaparray_[id_] = this->keyOrderMap_; // 先找本线程id的map,找到则说明是功能测试,单线程 spp::sparse_hash_map<int64_t, int32_t>::const_iterator iter = keyOrderMaparray_[id_]->find(key); if (iter != keyOrderMaparray_[id_]->end() ) { fileId = id_; return iter->second; } //printf("for find,id:%d\n", id_); spp::sparse_hash_map<int64_t, int32_t>::const_iterator isiter; // for循环查找每个map for(int i = 0; i < 16; ++i) { if(i == id_) continue; std::lock_guard<std::mutex> lock(mutex_[i]); isiter = keyOrderMaparray_[i]->find(key); if (isiter != keyOrderMaparray_[i]->end() ) { fileId = i; return isiter->second; } } } else if (unlikely(this->keyOrderMap_->size() < (this->keyFilePosition_))) { // Map 数量落后(kill 阶段重新写入数据), 继续构建 keyOrderMap_ this->ConstructKeyOrderMap(this->keyOrderMap_->size()); } // 将构建好的map放到全局map数组 //keyOrderMaparray_[id_] = this->keyOrderMap_; // 先找本线程id的map,找到则说明是功能测试,单线程 spp::sparse_hash_map<int64_t, int32_t>::const_iterator iter = keyOrderMaparray_[id_]->find(key); if (iter != keyOrderMaparray_[id_]->end() ) { fileId = id_; return iter->second; } //printf("for find,id:%d\n", id_); spp::sparse_hash_map<int64_t, int32_t>::const_iterator isiter; // for循环查找每个map for(int i = 0; i < 16; ++i) { if(i == id_) continue; isiter = keyOrderMaparray_[i]->find(key); if (isiter != keyOrderMaparray_[i]->end() ) { fileId = i; return isiter->second; } } return -1; } int64_t KeyFile::GetKeyPosition(KVString & key, int &fileId) { int64_t pos = this->FindKey(*(int64_t*)(key.Buf()), fileId); // KV_LOG(INFO) << "cfk:" << *((uint64_t*)key.Buf()) << " pos:" << pos; if (this->state_ == 0) { // 0 : 随机读,判断状态 JudgeStage(pos); } return pos; } int KeyFile::GetState() { return this->state_; } void KeyFile::SetKey(KVString & key) { ++this->keyFilePosition_; } void KeyFile::JudgeStage(int pos) { if(pos == 0) { this->state_ = 1; return; } int key_num = keyFilePosition_;//4000000;keyFilePosition_ int partition = pos / (PARTITION_SIZE * 1024 / 4); if (partition == ((key_num-1) / (PARTITION_SIZE * 1024 / 4))) { this->state_ = 2; return; } this->state_ = 0; } size_t KeyFile::GetKeyFilePosition(){ return this->keyFilePosition_; } void KeyFile::SetKeyFilePosition(int pos) { this->keyFilePosition_ = pos; }
31.882682
127
0.591204
chenshuaihao
18bc87786c4905941d79352bf2755a679164a3e0
2,072
hpp
C++
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
7
2019-04-09T16:25:49.000Z
2021-12-07T10:29:52.000Z
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
null
null
null
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
4
2019-08-07T07:43:27.000Z
2021-05-21T07:54:14.000Z
#pragma once #include "boost/utility/string_ref.hpp" #include <base/magic.hpp> namespace minips { namespace lib { template<typename Sample> class Parser { public: /** * Parsing logic for one line in file * * @param line a line read from the input file */ static Sample parse_libsvm(boost::string_ref line) { // check the LibSVM format and complete the parsing // hints: you may use boost::tokenizer, std::strtok_r, std::stringstream or any method you like // so far we tried all the tree and found std::strtok_r is fastest :) SVMItem item; char* pos; std::unique_ptr<char> buffer(new char[line.size() + 1]); strncpy(buffer.get(), line.data(), line.size()); buffer.get()[line.size()] = '\0'; char* token = strtok_r(buffer.get(), " \t:", &pos); int i = -1; int index; double value; while (token != nullptr) { if (i == 0) { index = std::atoi(token) - 1; i = 1; } else if (i == 1) { value = std::atof(token); item.first.push_back(std::make_pair(index, value)); i = 0; } else { // the class label item.second = std::atof(token); i = 0; } token = strtok_r(nullptr, " \t:", &pos); } return item; } static Sample parse_mnist(boost::string_ref line) { // check the MNIST format and complete the parsing // TODO: may be done in the future } // You may implement other parsing logic }; // class Parser } // namespace lib } // namespace minips
34.533333
111
0.441602
RickAi
18bd8329ff859f91d153112c30c047d8e0b27648
32,359
cc
C++
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
1
2016-01-18T12:41:28.000Z
2016-01-18T12:41:28.000Z
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
/* Copyright (c) 2010-2013 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <stdint.h> #include "Common.h" #include "Fence.h" #include "Log.h" #include "LogCleaner.h" #include "ShortMacros.h" #include "Segment.h" #include "SegmentIterator.h" #include "ServerConfig.h" #include "WallTime.h" namespace RAMCloud { /** * Construct a new LogCleaner object. The cleaner will not perform any garbage * collection until the start() method is invoked. * * \param context * Overall information about the RAMCloud server. * \param config * Server configuration from which the cleaner will extract any runtime * parameters that affect its operation. * \param segmentManager * The SegmentManager to query for newly cleanable segments, allocate * survivor segments from, and report cleaned segments to. * \param replicaManager * The ReplicaManager to use in backing up segments written out by the * cleaner. * \param entryHandlers * Class responsible for entries stored in the log. The cleaner will invoke * it when they are being relocated during cleaning, for example. */ LogCleaner::LogCleaner(Context* context, const ServerConfig* config, SegmentManager& segmentManager, ReplicaManager& replicaManager, LogEntryHandlers& entryHandlers) : context(context), segmentManager(segmentManager), replicaManager(replicaManager), entryHandlers(entryHandlers), writeCostThreshold(config->master.cleanerWriteCostThreshold), disableInMemoryCleaning(config->master.disableInMemoryCleaning), numThreads(config->master.cleanerThreadCount), candidates(), candidatesLock("LogCleaner::candidatesLock"), segletSize(config->segletSize), segmentSize(config->segmentSize), doWorkTicks(0), doWorkSleepTicks(0), inMemoryMetrics(), onDiskMetrics(), threadMetrics(numThreads), threadsShouldExit(false), threads() { if (!segmentManager.initializeSurvivorReserve(numThreads * SURVIVOR_SEGMENTS_TO_RESERVE)) throw FatalError(HERE, "Could not reserve survivor segments"); if (writeCostThreshold == 0) disableInMemoryCleaning = true; for (int i = 0; i < numThreads; i++) threads.push_back(NULL); } /** * Destroy the cleaner. Any running threads are stopped first. */ LogCleaner::~LogCleaner() { stop(); TEST_LOG("destroyed"); } /** * Start the log cleaner, if it isn't already running. This spins a thread that * continually cleans if there's work to do until stop() is called. * * The cleaner will not do any work until explicitly enabled via this method. * * This method may be called any number of times, but it is not thread-safe. * That is, do not call start() and stop() in parallel. */ void LogCleaner::start() { for (int i = 0; i < numThreads; i++) { if (threads[i] == NULL) threads[i] = new std::thread(cleanerThreadEntry, this, context); } } /** * Halt the cleaner thread (if it is running). Once halted, it will do no more * work until start() is called again. * * This method may be called any number of times, but it is not thread-safe. * That is, do not call start() and stop() in parallel. */ void LogCleaner::stop() { threadsShouldExit = true; Fence::sfence(); for (int i = 0; i < numThreads; i++) { if (threads[i] != NULL) { threads[i]->join(); delete threads[i]; threads[i] = NULL; } } threadsShouldExit = false; } /** * Fill in the provided protocol buffer with metrics, giving other modules and * servers insight into what's happening in the cleaner. */ void LogCleaner::getMetrics(ProtoBuf::LogMetrics_CleanerMetrics& m) { m.set_poll_usec(POLL_USEC); m.set_max_cleanable_memory_utilization(MAX_CLEANABLE_MEMORY_UTILIZATION); m.set_live_segments_per_disk_pass(MAX_LIVE_SEGMENTS_PER_DISK_PASS); m.set_survivor_segments_to_reserve(SURVIVOR_SEGMENTS_TO_RESERVE); m.set_min_memory_utilization(MIN_MEMORY_UTILIZATION); m.set_min_disk_utilization(MIN_DISK_UTILIZATION); m.set_do_work_ticks(doWorkTicks); m.set_do_work_sleep_ticks(doWorkSleepTicks); inMemoryMetrics.serialize(*m.mutable_in_memory_metrics()); onDiskMetrics.serialize(*m.mutable_on_disk_metrics()); threadMetrics.serialize(*m.mutable_thread_metrics()); } /****************************************************************************** * PRIVATE METHODS ******************************************************************************/ static volatile uint32_t threadCnt; /** * Static entry point for the cleaner thread. This is invoked via the * std::thread() constructor. This thread performs continuous cleaning on an * as-needed basis. */ void LogCleaner::cleanerThreadEntry(LogCleaner* logCleaner, Context* context) { LOG(NOTICE, "LogCleaner thread started"); CleanerThreadState state; state.threadNumber = __sync_fetch_and_add(&threadCnt, 1); try { while (1) { Fence::lfence(); if (logCleaner->threadsShouldExit) break; logCleaner->doWork(&state); } } catch (const Exception& e) { DIE("Fatal error in cleaner thread: %s", e.what()); } LOG(NOTICE, "LogCleaner thread stopping"); } /** * Main cleaning loop, constantly invoked via cleanerThreadEntry(). If there * is cleaning to be done, do it now return. If no work is to be done, sleep for * a bit before returning (and getting called again), rather than banging on the * CPU. */ void LogCleaner::doWork(CleanerThreadState* state) { MetricCycleCounter _(&doWorkTicks); threadMetrics.noteThreadStart(); // Update our list of candidates whether we need to clean or not (it's // better not to put off work until we really need to clean). candidatesLock.lock(); segmentManager.cleanableSegments(candidates); candidatesLock.unlock(); int memUtil = segmentManager.getAllocator().getMemoryUtilization(); bool lowOnMemory = (segmentManager.getAllocator().getMemoryUtilization() >= MIN_MEMORY_UTILIZATION); bool notKeepingUp = (segmentManager.getAllocator().getMemoryUtilization() >= MEMORY_DEPLETED_UTILIZATION); bool lowOnDiskSpace = (segmentManager.getSegmentUtilization() >= MIN_DISK_UTILIZATION); bool haveWorkToDo = (lowOnMemory || lowOnDiskSpace); if (haveWorkToDo) { if (state->threadNumber == 0) { if (lowOnDiskSpace || notKeepingUp) doDiskCleaning(lowOnDiskSpace); else doMemoryCleaning(); } else { int threshold = 90 + 2 * static_cast<int>(state->threadNumber); if (memUtil >= std::min(99, threshold)) doMemoryCleaning(); else haveWorkToDo = false; } } threadMetrics.noteThreadStop(); if (!haveWorkToDo) { MetricCycleCounter __(&doWorkSleepTicks); // Jitter the sleep delay a little bit (up to 10%). It's not a big deal // if we don't, but it can make some locks look artificially contended // when there's no cleaning to be done and threads manage to caravan // together. useconds_t r = downCast<useconds_t>(generateRandom() % POLL_USEC) / 10; usleep(POLL_USEC + r); } } /** * Perform an in-memory cleaning pass. This takes a segment and compacts it, * re-packing all live entries together sequentially, allowing us to reclaim * some of the dead space. */ uint64_t LogCleaner::doMemoryCleaning() { TEST_LOG("called"); MetricCycleCounter _(&inMemoryMetrics.totalTicks); if (disableInMemoryCleaning) return 0; uint32_t freeableSeglets; LogSegment* segment = getSegmentToCompact(freeableSeglets); if (segment == NULL) return 0; // Allocate a survivor segment to write into. This call may block if one // is not available right now. MetricCycleCounter waitTicks(&inMemoryMetrics.waitForFreeSurvivorTicks); LogSegment* survivor = segmentManager.allocSideSegment( SegmentManager::FOR_CLEANING | SegmentManager::MUST_NOT_FAIL, segment); assert(survivor != NULL); waitTicks.stop(); inMemoryMetrics.totalBytesInCompactedSegments += segment->getSegletsAllocated() * segletSize; uint64_t entriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveEntriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t scannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveScannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint32_t bytesAppended = 0; for (SegmentIterator it(*segment); !it.isDone(); it.next()) { LogEntryType type = it.getType(); Buffer buffer; it.appendToBuffer(buffer); Log::Reference reference = segment->getReference(it.getOffset()); RelocStatus s = relocateEntry(type, buffer, reference, survivor, inMemoryMetrics, &bytesAppended); if (expect_false(s == RELOCATION_FAILED)) throw FatalError(HERE, "Entry didn't fit into survivor!"); entriesScanned[type]++; scannedEntryLengths[type] += buffer.getTotalLength(); if (expect_true(s == RELOCATED)) { liveEntriesScanned[type]++; liveScannedEntryLengths[type] += buffer.getTotalLength(); } } // Be sure to update the usage statistics for the new segment. This // is done once here, rather than for each relocated entry because // it avoids the expense of atomically updating two separate fields. survivor->liveBytes += bytesAppended; for (size_t i = 0; i < TOTAL_LOG_ENTRY_TYPES; i++) { inMemoryMetrics.totalEntriesScanned[i] += entriesScanned[i]; inMemoryMetrics.totalLiveEntriesScanned[i] += liveEntriesScanned[i]; inMemoryMetrics.totalScannedEntryLengths[i] += scannedEntryLengths[i]; inMemoryMetrics.totalLiveScannedEntryLengths[i] += liveScannedEntryLengths[i]; } // The survivor segment has at least as many seglets allocated as the one // we've compacted (it was freshly allocated, so it has the maximum number // of seglets). We can therefore free the difference (which ensures a 0 net // gain) plus the number extra seglets that getSegmentToCompact() told us // we could free. That value was carefully calculated to ensure that future // disk cleaning will make forward progress (not use more seglets after // cleaning than before). uint32_t segletsToFree = survivor->getSegletsAllocated() - segment->getSegletsAllocated() + freeableSeglets; survivor->close(); bool r = survivor->freeUnusedSeglets(segletsToFree); assert(r); uint64_t bytesFreed = freeableSeglets * segletSize; inMemoryMetrics.totalBytesFreed += bytesFreed; inMemoryMetrics.totalBytesAppendedToSurvivors += survivor->getAppendedLength(); inMemoryMetrics.totalSegmentsCompacted++; MetricCycleCounter __(&inMemoryMetrics.compactionCompleteTicks); segmentManager.compactionComplete(segment, survivor); return static_cast<uint64_t>( static_cast<double>(bytesFreed) / Cycles::toSeconds(_.stop())); } /** * Perform a disk cleaning pass if possible. Doing so involves choosing segments * to clean, extracting entries from those segments, writing them out into new * "survivor" segments, and alerting the segment manager upon completion. */ uint64_t LogCleaner::doDiskCleaning(bool lowOnDiskSpace) { TEST_LOG("called"); MetricCycleCounter _(&onDiskMetrics.totalTicks); // Obtain the segments we'll clean in this pass. We're guaranteed to have // the resources to clean what's returned. LogSegmentVector segmentsToClean; getSegmentsToClean(segmentsToClean); if (segmentsToClean.size() == 0) return 0; // Extract the currently live entries of the segments we're cleaning and // sort them by age. EntryVector entries; getSortedEntries(segmentsToClean, entries); uint64_t maxLiveBytes = 0; uint32_t segletsBefore = 0; foreach (LogSegment* segment, segmentsToClean) { uint64_t liveBytes = segment->liveBytes; if (liveBytes == 0) onDiskMetrics.totalEmptySegmentsCleaned++; maxLiveBytes += liveBytes; segletsBefore += segment->getSegletsAllocated(); } // Relocate the live entries to survivor segments. LogSegmentVector survivors; uint64_t entryBytesAppended = relocateLiveEntries(entries, survivors); uint32_t segmentsAfter = downCast<uint32_t>(survivors.size()); uint32_t segletsAfter = 0; foreach (LogSegment* segment, survivors) segletsAfter += segment->getSegletsAllocated(); TEST_LOG("used %u seglets and %u segments", segletsAfter, segmentsAfter); // If this doesn't hold, then our statistics are wrong. Perhaps // MasterService is issuing a log->free(), but is leaving a reference in // the hash table. assert(entryBytesAppended <= maxLiveBytes); uint32_t segmentsBefore = downCast<uint32_t>(segmentsToClean.size()); assert(segletsBefore >= segletsAfter); assert(segmentsBefore >= segmentsAfter); uint64_t memoryBytesFreed = (segletsBefore - segletsAfter) * segletSize; uint64_t diskBytesFreed = (segmentsBefore - segmentsAfter) * segmentSize; onDiskMetrics.totalMemoryBytesFreed += memoryBytesFreed; onDiskMetrics.totalDiskBytesFreed += diskBytesFreed; onDiskMetrics.totalSegmentsCleaned += segmentsToClean.size(); onDiskMetrics.totalSurvivorsCreated += survivors.size(); onDiskMetrics.totalRuns++; if (lowOnDiskSpace) onDiskMetrics.totalLowDiskSpaceRuns++; MetricCycleCounter __(&onDiskMetrics.cleaningCompleteTicks); segmentManager.cleaningComplete(segmentsToClean, survivors); return static_cast<uint64_t>( static_cast<double>(memoryBytesFreed) / Cycles::toSeconds(_.stop())); } /** * Choose the best segment to clean in memory. We greedily choose the segment * with the most freeable seglets. Care is taken to ensure that we determine the * number of freeable seglets that will keep the segment under our maximum * cleanable utilization after compaction. This ensures that we will always be * able to use the compacted version of this segment during disk cleaning. * * \param[out] outFreeableSeglets * The maximum number of seglets the caller should free from this segment * is returned here. Freeing any more may make it impossible to clean the * resulting compacted segment on disk, which may deadlock the system if * it prevents freeing up tombstones in other segments. */ LogSegment* LogCleaner::getSegmentToCompact(uint32_t& outFreeableSeglets) { MetricCycleCounter _(&inMemoryMetrics.getSegmentToCompactTicks); Lock guard(candidatesLock); size_t bestIndex = -1; uint32_t bestDelta = 0; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; uint32_t liveBytes = candidate->liveBytes; uint32_t segletsNeeded = (100 * (liveBytes + segletSize - 1)) / segletSize / MAX_CLEANABLE_MEMORY_UTILIZATION; uint32_t segletsAllocated = candidate->getSegletsAllocated(); uint32_t delta = segletsAllocated - segletsNeeded; if (segletsNeeded < segletsAllocated && delta > bestDelta) { bestIndex = i; bestDelta = delta; } } // If we don't think any memory can be safely freed then either we're full // up with live objects (in which case nothing's wrong and we can't actually // do anything), or we have a lot of dead tombstones sitting around that is // causing us to assume that we're full when we really aren't. This can // happen because we don't (and can't easily) keep track of which tombstones // are dead, so all are presumed to be alive. When objects are large and // tombstones are relatively small, this accounting error is usually // harmless. However, when storing very small objects, tombstones are // relatively large and our percentage error can be significant. Also, one // can imagine what'd happen if the cleaner somehow groups tombstones // together into their own segments that always appear to have 100% live // entries. // // So, to address this we'll try compacting the candidate segment with the // most tombstones that has not been compacted in a while. Hopefully this // will choose the one with the most dead tombstones and shake us out of // any deadlock. // // It's entirely possible that we'd want to do this earlier (before we run // out of candidates above, rather than as a last ditch effort). It's not // clear to me, however, when we'd decide and what would give the best // overall performance. // // Did I ever mention how much I hate tombstones? if (bestIndex == static_cast<size_t>(-1)) { __uint128_t bestGoodness = 0; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; uint32_t tombstoneCount = candidate->getEntryCount(LOG_ENTRY_TYPE_OBJTOMB); uint64_t timeSinceLastCompaction = WallTime::secondsTimestamp() - candidate->lastCompactionTimestamp; __uint128_t goodness = (__uint128_t)tombstoneCount * timeSinceLastCompaction; if (goodness > bestGoodness) { bestIndex = i; bestGoodness = goodness; } } // Still no dice. Looks like we're just full of live data. if (bestIndex == static_cast<size_t>(-1)) return NULL; // It's not safe for the compactor to free any memory this time around // (it could be that no tombstones were dead, or we will free too few to // allow us to free seglets while still guaranteeing forward progress // of the disk cleaner). // // If we do free enough memory, we'll get it back in a subsequent pass. // The alternative would be to have a separate algorithm that just // counts dead tombstones and updates the liveness counters. That is // slightly more complicated. Perhaps if this becomes frequently enough // we can optimise that case. bestDelta = 0; } LogSegment* best = candidates[bestIndex]; candidates[bestIndex] = candidates.back(); candidates.pop_back(); outFreeableSeglets = bestDelta; return best; } void LogCleaner::sortSegmentsByCostBenefit(LogSegmentVector& segments) { MetricCycleCounter _(&onDiskMetrics.costBenefitSortTicks); // Sort segments so that the best candidates are at the front of the vector. // We could probably use a heap instead and go a little faster, but it's not // easy to say how many top candidates we'd want to track in the heap since // they could each have significantly different numbers of seglets. std::sort(segments.begin(), segments.end(), CostBenefitComparer()); } /** * Compute the best segments to clean on disk and return a set of them that we * are guaranteed to be able to clean while consuming no more space in memory * than they currently take up. * * \param[out] outSegmentsToClean * Vector in which segments chosen for cleaning are returned. * \return * Returns the total number of seglets allocated in the segments chosen for * cleaning. */ void LogCleaner::getSegmentsToClean(LogSegmentVector& outSegmentsToClean) { MetricCycleCounter _(&onDiskMetrics.getSegmentsToCleanTicks); Lock guard(candidatesLock); foreach (LogSegment* segment, candidates) { onDiskMetrics.allSegmentsDiskHistogram.storeSample( segment->getDiskUtilization()); } sortSegmentsByCostBenefit(candidates); uint32_t totalSeglets = 0; uint64_t totalLiveBytes = 0; uint64_t maximumLiveBytes = MAX_LIVE_SEGMENTS_PER_DISK_PASS * segmentSize; vector<size_t> chosenIndices; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; int utilization = candidate->getMemoryUtilization(); if (utilization > MAX_CLEANABLE_MEMORY_UTILIZATION) continue; uint64_t liveBytes = candidate->liveBytes; if ((totalLiveBytes + liveBytes) > maximumLiveBytes) break; totalLiveBytes += liveBytes; totalSeglets += candidate->getSegletsAllocated(); outSegmentsToClean.push_back(candidate); chosenIndices.push_back(i); } // Remove chosen segments from the list of candidates. At this point, we've // committed to cleaning what we chose and have guaranteed that we have the // necessary resources to complete the operation. reverse_foreach(size_t i, chosenIndices) { candidates[i] = candidates.back(); candidates.pop_back(); } TEST_LOG("%lu segments selected with %u allocated segments", chosenIndices.size(), totalSeglets); } /** * Sort the given segment entries by their timestamp. Used to sort the survivor * data that is written out to multiple segments during disk cleaning. This * helps to segregate data we expect to live longer from those likely to be * shorter lived, which in turn can reduce future cleaning costs. * * This happens to sort younger objects first, but the opposite should work just as * well. * * \param entries * Vector containing the entries to sort. */ void LogCleaner::sortEntriesByTimestamp(EntryVector& entries) { MetricCycleCounter _(&onDiskMetrics.timestampSortTicks); std::sort(entries.begin(), entries.end(), TimestampComparer()); } /** * Extract a complete list of entries from the given segments we're going to * clean and sort them by age. * * \param segmentsToClean * Vector containing the segments to extract entries from. * \param[out] outEntries * Vector containing sorted live entries in the segment. */ void LogCleaner::getSortedEntries(LogSegmentVector& segmentsToClean, EntryVector& outEntries) { MetricCycleCounter _(&onDiskMetrics.getSortedEntriesTicks); foreach (LogSegment* segment, segmentsToClean) { for (SegmentIterator it(*segment); !it.isDone(); it.next()) { LogEntryType type = it.getType(); Buffer buffer; it.appendToBuffer(buffer); uint32_t timestamp = entryHandlers.getTimestamp(type, buffer); outEntries.push_back( Entry(segment, it.getOffset(), timestamp)); } } sortEntriesByTimestamp(outEntries); // TODO(Steve): Push all of this crap into LogCleanerMetrics. It already // knows about the various parts of cleaning, so why not have simple calls // into it at interesting points of cleaning and let it extract the needed // metrics? foreach (LogSegment* segment, segmentsToClean) { onDiskMetrics.totalMemoryBytesInCleanedSegments += segment->getSegletsAllocated() * segletSize; onDiskMetrics.totalDiskBytesInCleanedSegments += segmentSize; onDiskMetrics.cleanedSegmentMemoryHistogram.storeSample( segment->getMemoryUtilization()); onDiskMetrics.cleanedSegmentDiskHistogram.storeSample( segment->getDiskUtilization()); } TEST_LOG("%lu entries extracted from %lu segments", outEntries.size(), segmentsToClean.size()); } /** * Given a vector of entries from segments being cleaned, write them out to * survivor segments in order and alert their owning module (MasterService, * usually), that they've been relocated. * * \param entries * Vector the entries from segments being cleaned that may need to be * relocated. * \param outSurvivors * The new survivor segments created to hold the relocated live data are * returned here. * \return * The number of live bytes appended to survivors is returned. This value * includes any segment metadata overhead. This makes it directly * comparable to the per-segment liveness statistics that also include * overhead. */ uint64_t LogCleaner::relocateLiveEntries(EntryVector& entries, LogSegmentVector& outSurvivors) { MetricCycleCounter _(&onDiskMetrics.relocateLiveEntriesTicks); LogSegment* survivor = NULL; uint64_t currentSurvivorBytesAppended = 0; uint64_t entryBytesAppended = 0; uint64_t entriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveEntriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t scannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveScannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint32_t bytesAppended = 0; foreach (Entry& entry, entries) { Buffer buffer; LogEntryType type = entry.segment->getEntry(entry.offset, buffer); Log::Reference reference = entry.segment->getReference(entry.offset); RelocStatus s = relocateEntry(type, buffer, reference, survivor, onDiskMetrics, &bytesAppended); if (s == RELOCATION_FAILED) { if (survivor != NULL) { survivor->liveBytes += bytesAppended; bytesAppended = 0; closeSurvivor(survivor); } // Allocate a survivor segment to write into. This call may block if // one is not available right now. MetricCycleCounter waitTicks( &onDiskMetrics.waitForFreeSurvivorsTicks); survivor = segmentManager.allocSideSegment( SegmentManager::FOR_CLEANING | SegmentManager::MUST_NOT_FAIL, NULL); assert(survivor != NULL); waitTicks.stop(); outSurvivors.push_back(survivor); currentSurvivorBytesAppended = survivor->getAppendedLength(); s = relocateEntry(type, buffer, reference, survivor, onDiskMetrics, &bytesAppended); if (s == RELOCATION_FAILED) throw FatalError(HERE, "Entry didn't fit into empty survivor!"); } entriesScanned[type]++; scannedEntryLengths[type] += buffer.getTotalLength(); if (s == RELOCATED) { liveEntriesScanned[type]++; liveScannedEntryLengths[type] += buffer.getTotalLength(); } if (survivor != NULL) { uint32_t newSurvivorBytesAppended = survivor->getAppendedLength(); entryBytesAppended += (newSurvivorBytesAppended - currentSurvivorBytesAppended); currentSurvivorBytesAppended = newSurvivorBytesAppended; } } if (survivor != NULL) { survivor->liveBytes += bytesAppended; closeSurvivor(survivor); } // Ensure that the survivors have been synced to backups before proceeding. foreach (survivor, outSurvivors) { MetricCycleCounter __(&onDiskMetrics.survivorSyncTicks); survivor->replicatedSegment->sync(survivor->getAppendedLength()); } for (size_t i = 0; i < TOTAL_LOG_ENTRY_TYPES; i++) { onDiskMetrics.totalEntriesScanned[i] += entriesScanned[i]; onDiskMetrics.totalLiveEntriesScanned[i] += liveEntriesScanned[i]; onDiskMetrics.totalScannedEntryLengths[i] += scannedEntryLengths[i]; onDiskMetrics.totalLiveScannedEntryLengths[i] += liveScannedEntryLengths[i]; } return entryBytesAppended; } /** * Close a survivor segment we've written data to as part of a disk cleaning * pass and tell the replicaManager to begin flushing it asynchronously to * backups. Any unused seglets in the survivor will will be freed for use in * new segments. * * \param survivor * The new disk segment we've written survivor data to. */ void LogCleaner::closeSurvivor(LogSegment* survivor) { MetricCycleCounter _(&onDiskMetrics.closeSurvivorTicks); onDiskMetrics.totalBytesAppendedToSurvivors += survivor->getAppendedLength(); survivor->close(); // Once the replicatedSegment is told that the segment is closed, it will // begin replicating the contents. By closing survivors as we go, we can // overlap backup writes with filling up new survivors. survivor->replicatedSegment->close(); // Immediately free any unused seglets. bool r = survivor->freeUnusedSeglets(survivor->getSegletsAllocated() - survivor->getSegletsInUse()); assert(r); } /****************************************************************************** * LogCleaner::CostBenefitComparer inner class ******************************************************************************/ /** * Construct a new comparison functor that compares segments by cost-benefit. * Used when selecting among candidate segments by first sorting them. */ LogCleaner::CostBenefitComparer::CostBenefitComparer() : now(WallTime::secondsTimestamp()), version(Cycles::rdtsc()) { } /** * Calculate the cost-benefit ratio (benefit/cost) for the given segment. */ uint64_t LogCleaner::CostBenefitComparer::costBenefit(LogSegment* s) { // If utilization is 0, cost-benefit is infinity. uint64_t costBenefit = -1UL; int utilization = s->getDiskUtilization(); if (utilization != 0) { uint64_t timestamp = s->getAge(); // This generally shouldn't happen, but is possible due to: // 1) Unsynchronized TSCs across cores (WallTime uses rdtsc). // 2) Unsynchronized clocks and "newer" recovered data in the log. if (timestamp > now) { LOG(WARNING, "timestamp > now"); timestamp = now; } uint64_t age = now - timestamp; costBenefit = ((100 - utilization) * age) / utilization; } return costBenefit; } /** * Compare two segment's cost-benefit ratios. Higher values (better cleaning * candidates) are better, so the less than comparison is inverted. */ bool LogCleaner::CostBenefitComparer::operator()(LogSegment* a, LogSegment* b) { // We must ensure that we maintain the weak strictly ordered constraint, // otherwise surprising things may happen in the stl algorithms when // segment statistics change and alter the computed cost-benefit of a // segment from one comparison to the next during the same sort operation. if (a->costBenefitVersion != version) { a->costBenefit = costBenefit(a); a->costBenefitVersion = version; } if (b->costBenefitVersion != version) { b->costBenefit = costBenefit(b); b->costBenefitVersion = version; } return a->costBenefit > b->costBenefit; } } // namespace
37.891101
83
0.665719
taschik
18c778b01f3f7a81a4a3286822b0eded2795264d
9,718
hpp
C++
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
1
2021-12-13T12:34:27.000Z
2021-12-13T12:34:27.000Z
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
62
2020-07-17T07:33:00.000Z
2021-05-22T15:30:20.000Z
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
1
2021-12-13T12:34:30.000Z
2021-12-13T12:34:30.000Z
/* Cam Mannett 2020 * * See LICENSE file */ #pragma once #include "malbolge/utility/signal.hpp" #include "malbolge/virtual_memory.hpp" namespace malbolge { /** Represents a virtual CPU. * * This class can not be copied, but can be moved. */ class virtual_cpu { public: /** Execution state. */ enum class execution_state { READY, ///< Ready to run RUNNING, ///< Program running PAUSED, ///< Program paused WAITING_FOR_INPUT, ///< Similar to paused, except the program will ///< resume when input data provided STOPPED, ///< Program stopped, cannot be resumed or ran again NUM_STATES ///< Number of execution states }; /** vCPU register identifiers. */ enum class vcpu_register { A, ///< Accumulator C, ///< Code pointer D, ///< Data pointer NUM_REGISTERS ///< Number of registers }; /** Signal type to indicate the program running state, and any exception in * case of error. * * In case of an error the execution state is always STOPPED. * @tparam execution_state Execution state * @tparam std::exception_ptr Exception pointer, null if no error */ using state_signal_type = utility::signal<execution_state, std::exception_ptr>; /** Signal type carrying program output data. * * @tparam char Character output from program */ using output_signal_type = utility::signal<char>; /** Signal type fired when a breakpoint is hit. * * @tparam math::ternary Address the breakpoint resides at */ using breakpoint_hit_signal_type = utility::signal<math::ternary>; /** Address value result callback type. * * @param address Address in virtual memory that was requested * @param value Value at @a address */ using address_value_callback_type = std::function<void (math::ternary address, math::ternary value)>; /** Register value result callback type. * * @param reg Requested register * @param address If @a reg is C or D then it contains an address * @param value The value of the register if @a address is empty, otherwise * the value at @a address */ using register_value_callback_type = std::function<void (vcpu_register reg, std::optional<math::ternary> address, math::ternary value)>; /** Constructor. * * Although it is not emitted in the state signal, the instance begins in * a execution_state::READY state. * @param vmem Virtual memory containing the initialised memory space * (including program data) */ explicit virtual_cpu(virtual_memory vmem); /** Move constructor. * * @param other Instance to move from */ virtual_cpu(virtual_cpu&& other) noexcept = default; /** Move assignment operator. * * @param other Instance to move from * @return A reference to this */ virtual_cpu& operator=(virtual_cpu&& other) noexcept = default; virtual_cpu(const virtual_cpu&) = delete; virtual_cpu& operator=(const virtual_cpu&) = delete; /** Destructor. */ ~virtual_cpu(); /** Runs or resumes program execution. * * If the program is already running or waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void run(); /** Pauses a running program. * * If the program is already paused or waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void pause(); /** Advances the program by a single execution. * * If the program is running, this will pause it and then advance by a * single execution. If the program is waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void step(); /** Adds @a data to the input queue for the program. * * If the program is waiting for input, then calling this will resume * program execution. * @param data Input add to add * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void add_input(std::string data); /** Adds a breakpoint to the program. * * If another breakpoint is already at the given address, it is replaced. * Breakpoints can be added to the program whilst in any non-STOPPED state, * but results can be unpredicatable if the program is running. * * The breakpoint-hit signal is fired when a breakpoint is reached. The * signal is fired when then code pointer reaches the address i.e. * @em before the instruction is executed, so you need to step to see the * result of the instruction execution. * @param address Address to attach a breakpoint * @param ignore_count Number of times the breakpoint is hit before the * breakpoint_hit_signal_type signal is fired * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void add_breakpoint(math::ternary address, std::size_t ignore_count = 0); /** Removes a breakpoint at the given address. * * This is a no-op if there is no breakpoint at @a address. * @param address vmem address to remove a breakpoint from * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void remove_breakpoint(math::ternary address); /** Asynchronously returns the value at a given vmem address via @a cb. * * @param address vmem address * @param cb Called with the result * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void address_value(math::ternary address, address_value_callback_type cb) const; /** Asynchronously returns the address and/or value of a given register. * * @param reg Register to query * @param cb For C and D registers returns the address held in the register * and the value it points at, for the A register it only returns the value * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void register_value(vcpu_register reg, register_value_callback_type cb) const; /** Register @a slot to be called when the state signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ state_signal_type::connection register_for_state_signal(state_signal_type::slot_type slot); /** Register @a slot to be called when the output signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ output_signal_type::connection register_for_output_signal(output_signal_type::slot_type slot); /** Register @a slot to be called when the breakpoint hit signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ breakpoint_hit_signal_type::connection register_for_breakpoint_hit_signal(breakpoint_hit_signal_type::slot_type slot); private: void impl_check() const; class impl_t; std::shared_ptr<impl_t> impl_; }; /** Textual streaming operator for virtual_cpu::vcpu_register. * * @param stream Output stream * @param register_id Instance to stream * @return @a stream */ std::ostream& operator<<(std::ostream& stream, virtual_cpu::vcpu_register register_id); /** Textual streaming operator for virtual_cpu::execution_state. * * @param stream Output stream * @param state Instance to stream * @return @a stream */ std::ostream& operator<<(std::ostream& stream, virtual_cpu::execution_state state); }
36.261194
87
0.666392
cmannett85
18c8052bf09362fa35b1e958280afa0aceb9f5b0
764
hh
C++
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
1
2017-01-27T12:53:50.000Z
2017-01-27T12:53:50.000Z
/*! * \file sha_algorithms.hh * \brief Header file for the lightweight security library. * \author [email protected] * \copyright Copyright (c) 2017 ygarcia. All rights reserved * \license This project is released under the MIT License * \version 0.1 */ #pragma once /*! \namespace security * \brief security namespace */ namespace security { /*! * \enum sha_algorithms_t * \brief List of supported sha algorithms */ enum sha_algorithms_t : uint8_t { // TODO Add 224,226,384,512 sha1 = 0x00, /*!< Secure Hash Algorithm SHA-1 */ sha256 = 0x01, /*!< Secure Hash Algorithm SHA-256 */ sha384 = 0x02 /*!< Secure Hash Algorithm SHA-384 */ }; // End of enum sha_algorithms_t } // End of namespace security
28.296296
63
0.663613
YannGarcia
18cd127a29a1d3773239a5ffb2432d85d8bcb02b
8,028
cpp
C++
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
/**************************************************************************************** * LvDisplayDriver.h - A LittlevGL Display Driver for ILI9341 * Created on Dec. 03, 2019 * Copyright (c) 2019 Ed Nelson (https://github.com/enelson1001) * Licensed under MIT License (see LICENSE file) * * Derivative Works * Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF * Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) * Licensed under the Apache License, Version 2.0 (the "License"); * * LittlevGL - A powerful and easy-to-use embedded GUI * Copyright (c) 2016 Gábor Kiss-Vámosi (https://github.com/littlevgl/lvgl) * Licensed under MIT License ***************************************************************************************/ #include "gui/LvDisplayDriver.h" #include <esp_freertos_hooks.h> #include <smooth/core/logging/log.h> #include <smooth/core/io/spi/SpiDmaFixedBuffer.h> using namespace smooth::core::io::spi; using namespace smooth::application::display; using namespace smooth::core::logging; namespace redstone { // Class Constants static const char* TAG = "LvDisplayDriver"; static IRAM_ATTR LvDisplayDriver* ptrLvDisplayDriver; // Constructor LvDisplayDriver::LvDisplayDriver() : spi_host(VSPI_HOST), // Use VSPI as host spi_master( spi_host, // host VSPI DMA_1, // use DMA GPIO_NUM_23, // mosi gpio pin GPIO_NUM_19, // miso gpio pin (full duplex) GPIO_NUM_18, // clock gpio pin MAX_DMA_LEN) // max transfer size { } // Initialize the display driver bool LvDisplayDriver::initialize() { Log::info(TAG, "initializing ........"); ili9341_initialized = init_ILI9341(); if (ili9341_initialized) { // M5Stack requires a different setting for a portrait screen display->set_rotation(0x68); // set callback pointer to this object ptrLvDisplayDriver = this; // initialize LittlevGL graphics library lv_init(); // create two small buffers, used by LittlevGL to draw screen content static SpiDmaFixedBuffer<uint8_t, MAX_DMA_LEN> display_buf1; static SpiDmaFixedBuffer<uint8_t, MAX_DMA_LEN> display_buf2; if (display_buf1.is_buffer_allocated() && display_buf2.is_buffer_allocated()) { static lv_color1_t* buf1 = reinterpret_cast<lv_color1_t*>(display_buf1.data()); static lv_color1_t* buf2 = reinterpret_cast<lv_color1_t*>(display_buf2.data()); // initialize a descriptor for the buffer static lv_disp_buf_t disp_buf; lv_disp_buf_init(&disp_buf, buf1, buf2, MAX_DMA_LEN / COLOR_SIZE); //lv_disp_buf_init(&disp_buf, buf1, NULL, MAX_DMA_LEN/COLOR_SIZE); // initialize and register a display driver lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = ili9341_flush_cb; lv_disp_drv_register(&disp_drv); // LittlevGL graphics library's tick - runs every 1ms esp_register_freertos_tick_hook(lv_tick_task); } else { ili9341_initialized = false; } } return ili9341_initialized; } // Initialize the ILI9341 bool LvDisplayDriver::init_ILI9341() { auto device = spi_master.create_device<ILI9341>( GPIO_NUM_14, // chip select gpio pin GPIO_NUM_27, // data command gpio pin GPIO_NUM_33, // reset gpio pin GPIO_NUM_32, // backlight gpio pin 0, // spi command_bits 0, // spi address_bits, 0, // bits_between_address_and_data_phase, 0, // spi_mode = 0, 128, // spi positive_duty_cycle, 0, // spi cs_ena_posttrans, SPI_MASTER_FREQ_16M, // spi-sck = 16MHz 0, // full duplex (4-wire) 7, // queue_size, true, // use pre-trans callback true); // use post-trans callback bool res = device->init(spi_host); if (res) { device->reset_display(); res &= device->send_init_cmds(); device->set_back_light(true); display = std::move(device); } else { Log::error(TAG, "Initializing of SPI Device: ILI9341 --- FAILED"); } return res; } // A class instance callback to flush the display buffer and thereby write colors to screen void LvDisplayDriver::display_drv_flush(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map) { uint32_t x1 = area->x1; uint32_t y1 = area->y1; uint32_t x2 = area->x2; uint32_t y2 = area->y2; uint32_t number_of_bytes_to_flush = (x2 - x1 + 1) * (y2 - y1 + 1) * COLOR_SIZE; uint32_t number_of_dma_blocks_with_complete_lines_to_send = number_of_bytes_to_flush / MAX_DMA_LEN; uint32_t number_of_bytes_in_not_complete_lines_to_send = number_of_bytes_to_flush % MAX_DMA_LEN; uint32_t start_row = y1; uint32_t end_row = y1 + LINES_TO_SEND - 1; // Drawing area that has a height of LINES_TO_SEND while (number_of_dma_blocks_with_complete_lines_to_send--) { display->send_lines(x1, start_row, x2, end_row, reinterpret_cast<uint8_t*>(color_map), MAX_DMA_LEN); display->wait_for_send_lines_to_finish(); // color_map is pointer to type lv_color_t were the data type is based on color size so the // color_map pointer may have a data type of uint8_t or uint16_t or uint32_t. MAX_DMA_LEN is // a number based on uint8_t so we need to divide MAX_DMA_LEN by the color size to increment // color_map pointer correctly color_map += MAX_DMA_LEN / COLOR_SIZE; // update start_row and end_row since we have sent a quantity of LINES_TO_SEND rows start_row = end_row + 1; end_row = start_row + LINES_TO_SEND - 1; } // Drawing area that has a height of less than LINE_TO_SEND if (number_of_bytes_in_not_complete_lines_to_send) { end_row = y2; display->send_lines(x1, start_row, x2, end_row, reinterpret_cast<uint8_t*>(color_map), number_of_bytes_in_not_complete_lines_to_send); display->wait_for_send_lines_to_finish(); } // Inform the lvgl graphics library that we are ready for flushing buffer lv_disp_t* disp = lv_refr_get_disp_refreshing(); lv_disp_flush_ready(&disp->driver); } // The "C" style callback required by LittlevGL void IRAM_ATTR LvDisplayDriver::ili9341_flush_cb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map) { if (ptrLvDisplayDriver != nullptr) { ptrLvDisplayDriver->display_drv_flush(drv, area, color_map); } } // The lv_tick_task that is required by LittlevGL for internal timing void IRAM_ATTR LvDisplayDriver::lv_tick_task(void) { lv_tick_inc(portTICK_RATE_MS); // 1 ms tick_task } }
40.341709
118
0.565272
enelson1001
18d1fa45078e1f1e037d2d2b84088bd5c7ff7016
264
cpp
C++
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
8
2015-01-02T21:40:55.000Z
2016-05-12T10:48:09.000Z
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
#include "SubtractionOperatorNode.h" namespace Three { std::string SubtractionOperatorNode::nodeName() const { return "Subtraction Operator"; } void SubtractionOperatorNode::accept(ASTVisitor& visitor) { visitor.visit(*this); } }
22
63
0.685606
mattmassicotte
18d479e04481497d84db0ebcade886391c34a155
2,801
cpp
C++
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/boolean/include/functions/seldec.hpp> #include <boost/simd/sdk/simd/io.hpp> #include <boost/dispatch/meta/as_integer.hpp> #include <nt2/sdk/unit/tests/relation.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/type_expr.hpp> #include <boost/simd/include/constants/one.hpp> #include <boost/simd/include/constants/zero.hpp> #include <boost/simd/include/constants/mone.hpp> NT2_TEST_CASE_TPL ( seldec_signed_int__2_0, BOOST_SIMD_INTEGRAL_SIGNED_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Mone<T>()), boost::simd::Mtwo<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Mone<T>()); } NT2_TEST_CASE_TPL ( seldec_unsigned_int__2_0, BOOST_SIMD_UNSIGNED_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Two<T>()), boost::simd::One<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Valmax<T>()); } NT2_TEST_CASE_TPL( seldec_floating, BOOST_SIMD_REAL_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Two<T>()), boost::simd::One<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Mone<T>()); }
41.80597
98
0.650125
psiha
18de0b122c448eeb1dfa08698cefb228782d2d7f
1,281
cpp
C++
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
/*BISMILLAH THE WHITE WOLF NO DREAM IS TOO BIG AND NO DREAMER IS TOO SMALL*/ #include<bits/stdc++.h> using namespace std; #define io ios_base::sync_with_stdio(false) #define ll long long #define ull unsigned long long #define vi vector<int> #define vll vector<long long> #define pb push_back #define mod 1000000007 #define pii pair<int, int> #define PI 2*acos(0.0) int wasp[500005]; void climax() { for(int i = 1; i <= 500000; i++) { int even = 2*i, x = 0; while(even%2 == 0) { even/= 2; x++; } wasp[i] = wasp[i-1] + x; } } int trailer(int x) { int aa=0; while(x>=5) { x = x/5; aa += x; } return aa; } int main() { io; climax(); int t; cin>>t; for(int i = 1; i<=t; i++) { int n, r, p, q; cin>>n>>r>>p>>q; int x = 0, ans, two = p, y = 0; while(p%5 == 0) { x++; p/=5; } while(two%2==0) { y++; two/=2; } x = trailer(n) - trailer(r) - trailer(n-r) + x*q; y = y*q + wasp[n/2] - wasp[r/2] - wasp[(n-r)/2]; ans = min(x, y); cout << "Case " << i <<": " <<ans <<"\n"; } return 0; }
17.547945
57
0.440281
BRAINIAC2677
18e2d45e5d9bbd28f4cb0a08a12d5c82384b3fc8
7,154
hpp
C++
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
1
2021-07-14T19:59:59.000Z
2021-07-14T19:59:59.000Z
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
null
null
null
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
1
2017-11-10T17:05:58.000Z
2017-11-10T17:05:58.000Z
// // GvmClusterPairs.hpp // GvmCpp // // Created by Mo DeJong on 8/14/15. // // 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 // // Maintains a heap of cluster pairs. #import "GvmCommon.hpp" #import "GvmClusterPair.hpp" namespace Gvm { // S // // Cluster vector space. // V // // Cluster vector type. // K // // Type of key. // FP // // Floating point type. template<typename S, typename V, typename K, typename FP> class GvmClusterPairs { public: static inline int ushift_left(int n) { #if defined(DEBUG) assert(n >= 0); #endif // DEBUG uint32_t un = (uint32_t) n; un <<= 1; return un; } static inline int ushift_right(int n) { #if defined(DEBUG) assert(n >= 0); #endif // DEBUG uint32_t un = (uint32_t) n; un >>= 1; return un; } // Pairs is an array of pointers to GvmClusterPair objects. // This data structure makes it easy to move an item // allocated on the heap around in the array without having // to copy the object data which is critical for performance. GvmClusterPair<S,V,K,FP> **pairs; // Cluster pairs are allocated as a solid block of (N * N) instances // so that these pointers can be sorted and rearranged without use // of shared_ptr for each cluster pair object. GvmClusterPair<S,V,K,FP> *pairsArray; int size; // The size of the pairs allocation. This size is defined at object // construction time and cannot be changed during object lifetime // for performance reasons. int capacity; // The number of pairsArray values that have been used. int pairsUsed; GvmClusterPairs<S,V,K,FP>(int inCapacity) : size(0), capacity(inCapacity), pairsUsed(0) { // For N clusters, allocate solid block of (N * N) cluster pairs, // this allocation represents a significant amount of the memory // used by the library. assert(capacity > 0); pairsArray = new GvmClusterPair<S,V,K,FP>[capacity]; assert(pairsArray); if ((0)) { fprintf(stdout, "alloc pairsArray of size %d bytes : 0x%p\n", (int)(capacity * sizeof(GvmClusterPair<S,V,K,FP>)), pairsArray); } // pairs is an array of pointers into pairsArray // initialized to nullptr. pairs = new GvmClusterPair<S,V,K,FP>*[capacity](); assert(pairs); if ((0)) { fprintf(stdout, "alloc pairs of size %d bytes : 0x%p\n", (int)(capacity * sizeof(GvmClusterPair<S,V,K,FP>*)), pairs); } return; } ~GvmClusterPairs<S,V,K,FP>() { if ((0)) { fprintf(stdout, "dealloc pairs 0x%p\n", pairs); } delete [] pairs; if ((0)) { fprintf(stdout, "dealloc pairsArray 0x%p\n", pairsArray); } delete [] pairsArray; } // Copy constructor explicitly deleted GvmClusterPairs<S,V,K,FP>(GvmClusterPairs<S,V,K,FP> &that) = delete; GvmClusterPairs<S,V,K,FP>(const GvmClusterPairs<S,V,K,FP> &that) = delete; // Operator= explicitly deleted GvmClusterPairs<S,V,K,FP>& operator=(GvmClusterPairs<S,V,K,FP>& x) = delete; GvmClusterPairs<S,V,K,FP>& operator=(const GvmClusterPairs<S,V,K,FP>& x) = delete; // add() should be passed a pair pointer returned by newSharedPair. void add(GvmClusterPair<S,V,K,FP> *pair) { int i = size; // Note that grow() logic is not supported here since the object // uses a fixed max size for pairs so that this add() method // can execute a more optimal execution path. #if defined(DEBUG) if (i >= capacity) { assert(0); } #endif // DEBUG size = i + 1; if (i == 0) { pairs[0] = pair; pair->index = 0; } else { heapifyUp(i, pair); } return; } // add cluster pair and return ref to shared pair object that was just added GvmClusterPair<S,V,K,FP>* newSharedPair(GvmCluster<S,V,K,FP> &c1, GvmCluster<S,V,K,FP> &c2) { assert(pairsUsed <= (capacity-1)); GvmClusterPair<S,V,K,FP> *pairPtr = &pairsArray[pairsUsed]; pairsUsed++; pairPtr->set(&c1, &c2); return pairPtr; } GvmClusterPair<S,V,K,FP>* peek() { return size == 0 ? nullptr : pairs[0]; } bool remove(GvmClusterPair<S,V,K,FP> *pair) { int i = indexOf(pair); if (i == -1) return false; removeAt(i); return true; } void reprioritize(GvmClusterPair<S,V,K,FP> *pair) { int i = indexOf(pair); #if defined(DEBUG) if (i == -1) { assert(0); } #endif // DEBUG pair->update(); GvmClusterPair<S,V,K,FP> *parent = (i == 0) ? nullptr : pairs[ ushift_right(i - 1) ]; if (parent != nullptr && parent->value > pair->value) { heapifyUp(i, pair); } else { heapifyDown(i, pair); } } int getSize() { return size; } void clear() { for (int i = 0; i < size; i++) { GvmClusterPair<S,V,K,FP> *e = pairs[i]; e->index = -1; //pairs[i] = e; } size = 0; } int indexOf(GvmClusterPair<S,V,K,FP> *pair) { #if defined(DEBUG) assert(pair != nullptr); #endif // DEBUG return pair->index; } void removeAt(int i) { int s = --size; if (s == i) { // removing last element pairs[i]->index = -1; pairs[i] = nullptr; } else { // Move pair object from one array slot to another GvmClusterPair<S,V,K,FP> *moved = pairs[s]; pairs[s] = nullptr; moved->index = -1; heapifyDown(i, moved); if (pairs[i] == moved) { heapifyUp(i, moved); if (pairs[i] != moved) { return; } } } return; } void heapifyUp(int k, GvmClusterPair<S,V,K,FP> *pair) { auto pairValue = pair->value; while (k > 0) { int parent = ushift_right(k - 1); GvmClusterPair<S,V,K,FP> *e = pairs[parent]; if (pairValue >= e->value) break; pairs[k] = e; e->index = k; k = parent; } pairs[k] = pair; pair->index = k; } void heapifyDown(int k, GvmClusterPair<S,V,K,FP> *pair) { auto pairValue = pair->value; int half = ushift_right(size); while (k < half) { int child = ushift_left(k) + 1; GvmClusterPair<S,V,K,FP> *c = pairs[child]; int right = child + 1; if (right < size && c->value > pairs[right]->value) { child = right; c = pairs[child]; } if (pairValue <= c->value) break; pairs[k] = c; c->index = k; k = child; } pairs[k] = pair; pair->index = k; } }; // end class GvmClusterPairs }
25.368794
134
0.549623
mdejong
18e2e6bfbd3fd5f5c12860dc3b002123cc118a69
1,581
cc
C++
src/mpsrc/wavy_listen.cc
etolabo/kumofs
b0f7ce8263194dbfa92d10ae75849e676e77c067
[ "Apache-2.0" ]
38
2015-01-21T09:57:36.000Z
2021-12-13T11:05:19.000Z
src/mpsrc/wavy_listen.cc
frsyuki/kastor
8bdbf5011aa8cf486b3efd50d7ad471b7a0dfae7
[ "Apache-2.0" ]
3
2015-12-15T12:43:13.000Z
2021-07-30T10:31:42.000Z
src/mpsrc/wavy_listen.cc
frsyuki/kastor
8bdbf5011aa8cf486b3efd50d7ad471b7a0dfae7
[ "Apache-2.0" ]
2
2015-03-19T18:54:38.000Z
2019-03-19T13:37:29.000Z
// // mp::wavy::core::listen // // Copyright (C) 2008 FURUHASHI Sadayuki // // 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 "wavy_core.h" #include "mp/exception.h" namespace mp { namespace wavy { class core::impl::listen_handler : public handler { public: listen_handler(int fd, core* c, listen_callback_t callback) : handler(fd), m_core(c), m_callback(callback) { } ~listen_handler() { } void read_event() { while(true) { int err = 0; int sock = ::accept(fd(), NULL, NULL); if(sock < 0) { if(errno == EAGAIN || errno == EINTR) { return; } else { err = errno; } } else if(sock == 0) { err = errno; } try { m_core->submit(m_callback, sock, err); } catch(...) { } if(err) { throw system_error(errno, "mp::wvy::accept: accept failed"); } } } private: core* m_core; listen_callback_t m_callback; }; void core::listen(int lsock, listen_callback_t callback) { add<impl::listen_handler>(lsock, this, callback); } } // namespace wavy } // namespace mp
21.657534
78
0.648956
etolabo
18eb9ca0a127bc8f5f252f662cbd648ed2d14ddd
3,308
cpp
C++
MeetingManager/MeetingManager/MeetingManager.cpp
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
1
2021-06-23T08:41:55.000Z
2021-06-23T08:41:55.000Z
MeetingManager/MeetingManager/MeetingManager.cpp
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
null
null
null
MeetingManager/MeetingManager/MeetingManager.cpp
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
null
null
null
#pragma execution_character_set("utf-8") #include "MeetingManager.h" #include <QDebug> #include <QIcon> #include <QItemDelegate> #include <QListWidgetItem> #include <QPainter> #include <QPushButton> #include <QStandardItem> #include <QStandardItemModel> namespace { static const int MeetingIconRole = Qt::UserRole + 1; } class MeetingNavDelegate : public QItemDelegate { public: MeetingNavDelegate(QObject* parent) : QItemDelegate(parent){}; void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (option.state & QStyle::State_Selected) { QBrush brush(QColor("#c7e2fb")); QRect fill_rect(option.rect.x(), option.rect.y(), option.rect.width(), option.rect.height()); painter->fillRect(fill_rect, brush); } else if (option.state & QStyle::State_MouseOver) { QBrush brush(QColor("#e2effc")); QRect fill_rect(option.rect.x(), option.rect.y(), option.rect.width(), option.rect.height()); painter->fillRect(fill_rect, brush); } QString title = index.data(Qt::DisplayRole).toString(); QString iconPath = index.data(MeetingIconRole).toString(); //头像显示区域 QRect iconRect = QRect(option.rect.x() + 20, option.rect.y() + 10, 30, 30); QPixmap icon(iconPath); painter->drawPixmap(iconRect, icon); // QRect titleRect = QRect(option.rect.x() + 30 + 30, option.rect.y(), 100, 50); painter->drawText(titleRect, title, QTextOption(Qt::AlignVCenter)); } QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override { return QSize(100, 50); } }; MeetingManager::MeetingManager(QWidget* parent) : QWidget(parent) { ui.setupUi(this); addMeetingType(); } void MeetingManager::addMeetingType() { auto* model = new QStandardItemModel(this); auto* delegate = new MeetingNavDelegate(this); ui.listMeetingNav->setModel(model); ui.listMeetingNav->setItemDelegate(delegate); auto* allHistory = new QStandardItem(QIcon("Resources/history.png"), tr("我的会议")); allHistory->setData(QString("Resources/history.png"), MeetingIconRole); auto* voice = new QStandardItem(QIcon("Resources/voice.png"), tr("语音会议")); voice->setData(QString("Resources/voice.png"), MeetingIconRole); auto* video = new QStandardItem(QIcon("Resources/video.png"), tr("视频会议")); video->setData(QString("Resources/video.png"), MeetingIconRole); auto* live = new QStandardItem(QIcon("Resources/live.png"), tr("直播")); live->setData(QString("Resources/live.png"), MeetingIconRole); model->appendRow(allHistory); model->appendRow(voice); model->appendRow(video); model->appendRow(live); auto* pButtonContainer = new QWidget(ui.tabWidget); pButtonContainer->resize(QSize(100, ui.tabWidget->tabBar()->height())); auto* pLayout = new QHBoxLayout; pButtonContainer->setLayout(pLayout); auto* pButton = new QPushButton(ui.tabWidget); pLayout->addWidget(pButton); // TabBar 按钮 //ui.tabWidget->setCornerWidget(pButtonContainer); }
34.458333
75
0.64994
hyq5436
18f0a76921521335b2ea6c2663514844d5b095b9
3,483
cpp
C++
codes/CF/CF_1427E.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/CF/CF_1427E.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/CF/CF_1427E.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//misaka and rin will carry me to cm #include <iostream> #include <cstdio> #include <cstring> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <array> #include <tuple> #include <random> #include <chrono> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; //i will learn from moo. /* Input */ template<class T> void read(T &x) { cin >> x; } template<class H, class T> void read(pair<H, T> &p) { cin >> p.first >> p.second; } template<class T, size_t S> void read(array<T, S> &a) { for (T &i : a) read(i); } template<class T> void read(vector<T> &v) { for (T &i : v) read(i); } template<class H, class... T> void read(H &h, T &...t) { read(h); read(t...); } /* Output */ template<class H, class T> ostream &operator<<(ostream &o, pair<H, T> &p) { o << p.first << " " << p.second; return o; } template<class T, size_t S> ostream &operator<<(ostream &o, array<T, S> &a) { string s; for (T i : a) o << s << i, s = " "; return o; } template<class T> ostream &operator<<(ostream &o, vector<T> &v) { string s; for (T i : v) o << s << i, s = " "; return o; } template<class T> void write(T x) { cout << x; } template<class H, class... T> void write(const H &h, const T &...t) { write(h); write(t...); } void print() { write('\n'); } template<class H, class... T> void print(const H &h, const T &...t) { write(h); if (sizeof...(t)) write(' '); print(t...); } /* Misc */ template <typename T> void ckmin(T &a, const T &b) { a = min(a, b); } template <typename T> void ckmax(T &a, const T &b) { a = max(a, b); } inline int hsb(ll x){ assert(x > 0); return 63-__builtin_clzll(x); } vector<ll> gen; int ope = 0; struct basis{ const int H = 63; ll arr[70]; //64 actually basis(){ memset(arr, 0, sizeof(arr)); } ll B(int x){ return arr[x]; } ll norm(ll x, int p = 0){ for(ll i = H; ~i; i--){ if(p){ print(B(i), '^', x); if(B(i)^x) gen.push_back(B(i)^x); ope++; } if(B(i) && ((x^B(i)) < x)){ x ^= B(i); } } return x; } void insert(ll x){ if(x == 0) return ; if(B(hsb(x)) == 0){ arr[hsb(x)] = x; return ; } insert(norm(x, 1)); } void erase(int x){ arr[x] = 0; } }; #define uid(a, b) uniform_int_distribution<int>(a, b)(rng) mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); void solve(){ //freopen("out.txt", "w", stdout); const int bckt = 1400, tot = 1e5; ll aa; read(aa); ope++; int scam = 44 - hsb(aa); basis exist = basis(); cout << tot << "\n"; print(aa, '^', aa); //yes for(ll t = aa; t<=(1ll << 44); t*=2ll){ print(t, '+', t); ope++; gen.push_back(t); exist.insert(t); if(t > (1ll << (44))) gen.push_back(t); } for(int i = 0; i<bckt; i++){ ll a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)]; //print(a, b); while(a == b || (a + b) >= (1ll << 44)){ a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)]; //print(a, b, exist.norm(a+b), (a+b >= (1ll << 44))); } print(a, '+', b); ope++; exist.insert(a+b); } while(ope < tot){ ll a = gen[uid(0, sz(gen)-1)], b = gen[uid(0, sz(gen)-1)]; print(a, '^', b); ope++; } assert(exist.B(0) > 0); } int main(){ cin.tie(0) -> sync_with_stdio(0); int T = 1; //cin >> T; while(T--){ solve(); } return 0; }
23.856164
135
0.547229
chessbot108
18f90c444b68cf7840eee9a0bd2bc08ee2daac98
3,643
cpp
C++
Hack and Slash/Hack and Slash/src/Math.cpp
JoanStinson/Hack_and_Slash
c76b5eea3455091c77fe35542bc773b3786d1896
[ "MIT" ]
2
2021-03-25T22:39:22.000Z
2021-03-31T03:42:33.000Z
Hack and Slash/Hack and Slash/src/Math.cpp
JoanStinson/HackAndSlash
c76b5eea3455091c77fe35542bc773b3786d1896
[ "MIT" ]
null
null
null
Hack and Slash/Hack and Slash/src/Math.cpp
JoanStinson/HackAndSlash
c76b5eea3455091c77fe35542bc773b3786d1896
[ "MIT" ]
null
null
null
#include "Math.h" #include <limits> #include <algorithm> namespace math { bool math::collBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) { SDL_Rect intersection; return SDL_IntersectRect(&r1, &r2, &intersection) ? true : false; } float math::angleBetweenTwoPoints(float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; return atan2(dy, dx) * 180 / M_PI; } float math::angleBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) { float x1 = r1.x + (r1.w / 2); float y1 = r1.y + (r1.h / 2); float x2 = r2.x + (r2.w / 2); float y2 = r2.y + (r2.h / 2); return angleBetweenTwoPoints(x1, y1, x2, y2); } float math::distBetweenTwoPoints(float x1, float y1, float x2, float y2) { return abs(sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))); } float math::distBetweenTwoRects(SDL_Rect &r1, SDL_Rect &r2) { SDL_Point p1, p2; p1.x = r1.x + r1.w / 2; p1.y = r1.y + r1.h / 2; p2.x = r2.x + r2.w / 2; p2.y = r2.y + r2.h / 2; return abs(sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2))); } /*! Return type: gives 0-1 depending on where collision is. 1 means, no collisions, 0 means collide immediately and 0.5 is half way etc. * params: movingBox is entity being checked * xv and vy are the velocities our moving box is moving at * otherbox is some other entities collision box we may collide with * normalx and normaly let us know which side of otherBox we collided with. these are pass by reference */ float math::sweptAABB(SDL_Rect &boxA, float vx, float vy, SDL_Rect &boxB, float &normalX, float &normalY) { float xInvEntry, xInvExit; float yInvEntry, yInvExit; // Find the distance between the objects on the near and far sides or both x and y if (vx > 0.0f) { xInvEntry = boxB.x - (boxA.x + boxA.w); xInvExit = (boxB.x + boxB.w) - boxA.x; } else { xInvEntry = (boxB.x + boxB.w) - boxA.x; xInvExit = boxB.x - (boxA.x + boxA.w); } if (vy > 0.0f) { yInvEntry = boxB.y - (boxA.y + boxA.h); yInvExit = (boxB.y + boxB.h) - boxA.y; } else { yInvEntry = (boxB.y + boxB.h) - boxA.y; yInvExit = boxB.y - (boxA.y + boxA.h); } // Find time of collision and time of leacing for each axis (if statement is to prevent dividing by zero) float xEntry, xExit; float yEntry, yExit; if (vx == 0.0f) { xEntry = -std::numeric_limits<float>::infinity(); xExit = std::numeric_limits<float>::infinity(); } else { xEntry = xInvEntry / vx; xExit = xInvExit / vx; } if (vy == 0.0f) { yEntry = -std::numeric_limits<float>::infinity(); yExit = std::numeric_limits<float>::infinity(); } else { yEntry = yInvEntry / vy; yExit = yInvExit / vy; } // Find the earliest/latest times of collision float entryTime = std::max(xEntry, yEntry); float exitTime = std::min(xExit, yExit); // If there was NO collision if (entryTime > exitTime || xEntry < 0.0f && yEntry < 0.0f || xEntry > 1.0f || yEntry > 1.0f) { normalX = 0.0f; normalY = 0.0f; return 1.0f; } else { // There was a collision // Work out which sides/normals of the otherbox we collided with if (xEntry > yEntry) { // Assume we hit otherbox on the x axis if (xInvEntry < 0.0f) { normalX = 1; // Hit right hand side normalY = 0; // Not hit top or bottom } else { normalX = -1; // Hit left hand side normalY = 0; // Not hit top or bottom of box } } else { // Assume we hit otherbox on y axis if (yEntry < 0.0f) { normalX = 0; normalY = 1; } else { normalX = 0; normalY = -1; } } // Return the time of collision return entryTime; } } }
26.985185
137
0.61625
JoanStinson
18fa3ce4f7cf2dd9e3ce3b109c46690492205261
1,565
hpp
C++
lib/tracer.hpp
ConteDevel/xpertium
dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a
[ "MIT" ]
null
null
null
lib/tracer.hpp
ConteDevel/xpertium
dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a
[ "MIT" ]
null
null
null
lib/tracer.hpp
ConteDevel/xpertium
dbf03f922f893176b87fc0fe6c0e05fb0fb68c4a
[ "MIT" ]
null
null
null
#ifndef TRACER_HPP #define TRACER_HPP #include "rule.hpp" #include <iostream> #include <string> #include <type_traits> #include <vector> namespace xpertium { template <typename val_t> class base_tracer_t { public: base_tracer_t() {} virtual ~base_tracer_t() {} virtual void push_fact(val_t fact) = 0; virtual void push_rule(const rule_t<val_t> *rule, val_t out) = 0; virtual void print() = 0; virtual void clear() = 0; }; template <typename val_t> class tracer_t : public base_tracer_t<val_t> { std::vector<std::string> m_trace; public: virtual void push_fact(val_t fact) override { std::string str = "+ fact: <" + to_string(fact) + ">"; m_trace.push_back(std::move(str)); } virtual void push_rule(const rule_t<val_t> *rule, val_t out) override { std::string str = "+ "; if (rule->target()) { str += "tget: "; } else { str += "rule: "; } str += "<" + rule->id() + "> -> <" + to_string(out) + ">"; m_trace.push_back(std::move(str)); } virtual void print() override { std::cout << "Trace: " << std::endl; for (auto it = m_trace.begin(); it != m_trace.end(); ++it) { std::cout << (*it) << std::endl; } } virtual void clear() override { m_trace.clear(); } private: auto to_string(val_t val) { if constexpr (std::is_same<val_t, std::string>::value) { return static_cast<std::string>(val); } else { return std::to_string(val); } } }; } #endif // TRACER_HPP
25.241935
75
0.578914
ConteDevel
18ff5467385e0c0e2201d272009d823513ac52c1
4,829
cpp
C++
ui/osx/tabcontrol.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
28
2017-04-30T13:56:13.000Z
2022-03-20T06:54:37.000Z
ui/osx/tabcontrol.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
72
2017-04-25T03:42:58.000Z
2021-12-04T06:35:28.000Z
ui/osx/tabcontrol.cpp
plonk/peercast-0.1218
30fc2401dc798336429a979fe7aaca8883e63ed9
[ "PSF-2.0", "Apache-2.0", "OpenSSL", "MIT" ]
12
2017-04-16T06:25:24.000Z
2021-07-07T13:28:27.000Z
// ------------------------------------------------ // tabcontrol.cpp // PeerCast // // Created by mode7 on Fri Apr 02 2004. // Copyright (c) 2002-2004 peercast.org. All rights reserved. // ------------------------------------------------ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // ------------------------------------------------ #include "tabcontrol.h" #include "osxapp.h" static int tabList[] = { 2, 1001, 1002 }; static ControlID skTabItemID = { 'PCTB', 0 }; TabControl::TabControl( const int signature, const int id, WindowRef windowRef ) :mControlID ( ) , mWindowRef ( windowRef ) , mEventHandler ( TabControl::handler ) , mYPAddress ('PCCG', 1000) , mDJMessage ('PCCG', 1001) , mPassword ('PCCG', 1002) , mMaxRelays ('PCCG', 1003) , mLastTabIndex ( 1 ) { mControlID.signature = signature; mControlID.id = id; setInitialTab( windowRef ); } OSStatus TabControl::installHandler() { ControlRef tabControlRef; static const EventTypeSpec tabControlEvents[] = { { kEventClassControl, kEventControlHit } , { kEventClassWindow, kEventWindowActivated } }; GetControlByID( getWindow(), &getID(), &tabControlRef ); return InstallControlEventHandler( tabControlRef , mEventHandler.eventHandler() , GetEventTypeCount(tabControlEvents) , tabControlEvents , this , NULL ); } //------------------------------------------------------------------------ void TabControl::updateSettings() { if( !servMgr || !chanMgr ) return; mLock.on(); mYPAddress.setText( mWindowRef, servMgr->rootHost ); mDJMessage.setText( mWindowRef, chanMgr->broadcastMsg ); mPassword.setText( mWindowRef, servMgr->password ); mMaxRelays.setIntValue( mWindowRef, servMgr->maxRelays ); mLock.off(); } //------------------------------------------------------------------------ void TabControl::saveSettings() { if( !servMgr || !chanMgr ) return; mLock.on(); chanMgr->broadcastMsg.set(mDJMessage.getString( mWindowRef, kCFStringEncodingUnicode ), String::T_ASCII); servMgr->rootHost = mYPAddress.getString( mWindowRef, kCFStringEncodingASCII ); strncpy( servMgr->password, mPassword.getString( mWindowRef, kCFStringEncodingASCII ), 64 ); servMgr->setMaxRelays( mMaxRelays.getIntValue( mWindowRef ) ); mLock.off(); } //------------------------------------------------------------------------ void TabControl::setInitialTab(WindowRef window) { ControlID controlID = skTabItemID; for(short i=1; i<tabList[0]+1; ++i) { controlID.id = tabList[i]; SetControlVisibility( getControlRef( window, controlID ), false, true ); } // set SetControlValue( getControlRef(window, mControlID), mLastTabIndex ); controlID.id = tabList[mLastTabIndex]; SetControlVisibility( getControlRef(window, controlID), true, true ); } ControlRef TabControl::getControlRef( WindowRef window, const ControlID& controlID ) { ControlRef controlRef = NULL; GetControlByID( window, &controlID, &controlRef ); return controlRef; } OSStatus TabControl::handler( EventHandlerCallRef inCallRef, EventRef inEvent, void* inUserData ) { switch( GetEventKind( inEvent ) ) { case kEventControlHit: { TabControl& tControl = *static_cast<TabControl *>(inUserData); WindowRef window = static_cast<WindowRef>(tControl.getWindow()); ControlRef tabControl = getControlRef( window, tControl.getID() ); const short controlValue = GetControlValue( tabControl ); if( controlValue != tControl.mLastTabIndex ) { tControl.updateSettings(); switchItem( window, tabControl, controlValue ); tControl.mLastTabIndex = controlValue; return noErr; } } break; } return eventNotHandledErr; } void TabControl::switchItem( WindowRef window, ControlRef tabControl, const short currentTabIndex ) { ControlRef selectedPaneControl = NULL; ControlID controlID = skTabItemID; for(short i=1; i<tabList[0]+1; ++i) { controlID.id = tabList[i]; ControlRef userPaneControl = getControlRef( window, controlID ); if( i == currentTabIndex ) { selectedPaneControl = userPaneControl; } else { SetControlVisibility( userPaneControl, false, true ); } } if( selectedPaneControl != NULL ) { (void)ClearKeyboardFocus( window ); SetControlVisibility( selectedPaneControl, true, true ); } Draw1Control( tabControl ); }
28.916168
106
0.6579
plonk
7a03aedfb9c28a9dd5dbd06551bede105e01773e
15,976
cpp
C++
teapoy/src/sni/sys.cpp
lyramilk/teapoy
5b450a243432b058512ed7b1c6f810cb0d207f91
[ "Apache-2.0" ]
1
2017-09-07T02:28:58.000Z
2017-09-07T02:28:58.000Z
teapoy/src/sni/sys.cpp
lyramilk/teapoy
5b450a243432b058512ed7b1c6f810cb0d207f91
[ "Apache-2.0" ]
null
null
null
teapoy/src/sni/sys.cpp
lyramilk/teapoy
5b450a243432b058512ed7b1c6f810cb0d207f91
[ "Apache-2.0" ]
null
null
null
#include <libmilk/scriptengine.h> #include <libmilk/log.h> #include <libmilk/dict.h> #include <libmilk/codes.h> #include <libmilk/json.h> #include <libmilk/sha1.h> #include <libmilk/md5.h> #include <libmilk/inotify.h> #include "script.h" #include "env.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pwd.h> #include <sys/wait.h> #include <sys/stat.h> #include <time.h> #include <string.h> #include <errno.h> namespace lyramilk{ namespace teapoy{ namespace native { static lyramilk::log::logss log(lyramilk::klog,"teapoy.native"); lyramilk::data::var teapoy_import(const lyramilk::data::array& args,const lyramilk::data::map& senv) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::map::const_iterator it_env_eng = senv.find(lyramilk::script::engine::s_env_engine()); if(it_env_eng != senv.end()){ lyramilk::data::datawrapper* urd = it_env_eng->second.userdata(); if(urd && urd->name() == lyramilk::script::engine_datawrapper::class_name()){ lyramilk::script::engine_datawrapper* urdp = (lyramilk::script::engine_datawrapper*)urd; if(urdp->eng){ // 在文件所在目录查找包含文件 lyramilk::data::string filename = urdp->eng->filename(); std::size_t pos = filename.rfind('/'); if(pos != filename.npos){ filename = filename.substr(0,pos + 1) + args[0].str(); } // 在环境变量指定的目录中查找文件。 struct stat st = {0}; if(0 !=::stat(filename.c_str(),&st)){ filename = env::get(urdp->eng->name() + ".require").str(); if(!filename.empty() && filename.at(filename.size() - 1) != '/') filename.push_back('/'); filename += args[0].str(); } // 写入包含信息,防止重复载入 lyramilk::data::var& v = urdp->eng->get_userdata("require"); v.type(lyramilk::data::var::t_array); lyramilk::data::array& ar = v; lyramilk::data::array::iterator it = ar.begin(); for(;it!=ar.end();++it){ lyramilk::data::string str = *it; if(str == args[0].str()){ //log(lyramilk::log::warning,__FUNCTION__) << D("请不要重复包含文件%s",str.c_str()) << std::endl; return false; } } ar.push_back(args[0].str()); // 执行包含文件。 if(urdp->eng->load_module(filename)){ return true; } } } } return false; } struct engineitem { lyramilk::data::string filename; lyramilk::data::string type; lyramilk::data::array args; unsigned long long msec; }; static void* thread_task(void* _p) { engineitem* p = (engineitem*)_p; engineitem ei = *p; delete p; struct stat st0; while(0 !=::stat(ei.filename.c_str(),&st0)){ sleep(10); } lyramilk::script::engines* pool = engine_pool::instance()->get("js"); lyramilk::script::engines::ptr eng = pool->get(); if(!eng){ log(lyramilk::log::error,"task") << D("获取启动脚本失败") << std::endl; return nullptr; } while(!eng->load_file(ei.filename)){ sleep(10); } while(true){ struct stat st1; while(0 !=::stat(ei.filename.c_str(),&st1)){ sleep(10); } if(st1.st_mtime != st0.st_mtime){ st0.st_mtime = st1.st_mtime; log(lyramilk::log::warning,"task") << D("重新加载%s",ei.filename.c_str()) << std::endl; eng->reset(); eng->load_file(ei.filename); } lyramilk::data::var v; if(eng->call("ontimer",ei.args,&v)){ if(v.type() == lyramilk::data::var::t_bool && (bool)v == false)break; } eng->gc(); usleep(ei.msec * 1000); }; pthread_exit(0); return nullptr; } static void* thread_once_task(void* _p) { engineitem* p = (engineitem*)_p; engineitem ei = *p; delete p; struct stat st0; while(0 !=::stat(ei.filename.c_str(),&st0)){ sleep(10); } lyramilk::script::engine* eng = engine_pool::instance()->create_script_instance("js"); if(!eng){ log(lyramilk::log::error,"once_task") << D("获取启动脚本失败") << std::endl; return nullptr; } while(!eng->load_file(ei.filename)){ sleep(10); } do{ struct stat st1; while(0 !=::stat(ei.filename.c_str(),&st1)){ sleep(10); } if(st1.st_mtime != st0.st_mtime){ st0.st_mtime = st1.st_mtime; log(lyramilk::log::warning,"once_task") << D("重新加载%s",ei.filename.c_str()) << std::endl; eng->reset(); eng->load_file(ei.filename); } lyramilk::data::var v; if(eng->call("onthread",ei.args,&v)){ if(v.type() == lyramilk::data::var::t_bool && (bool)v == false)break; } eng->gc(); }while(false); engine_pool::instance()->destory_script_instance("js",eng); pthread_exit(0); return nullptr; } lyramilk::data::var task(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_int); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_str); pthread_t id_1; engineitem* p = new engineitem; p->type = args[0].str(); p->msec = args[1]; p->filename = args[2].str(); if(args.size() > 3){ MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,3,lyramilk::data::var::t_array); p->args = args[3]; } int ret = pthread_create(&id_1,NULL,thread_task,p); pthread_detach(id_1); return 0 == ret; } lyramilk::data::var task_once(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str); pthread_t id_1; engineitem* p = new engineitem; p->type = args[0].str(); p->filename = args[1].str(); if(args.size() > 2){ MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_array); p->args = args[2]; } int ret = pthread_create(&id_1,NULL,thread_once_task,p); pthread_detach(id_1); return 0 == ret; } lyramilk::data::var daemon(const lyramilk::data::array& args,const lyramilk::data::map& env) { ::daemon(1,0); return true; } lyramilk::data::var crand(const lyramilk::data::array& args,const lyramilk::data::map& env) { if(args.size() > 0){ MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int); unsigned int seed = args[0]; srand(seed); } return rand(); } lyramilk::data::var msleep(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int); unsigned long long usecond = args[0]; return usleep(usecond * 1000); } lyramilk::data::var su(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::string username = args[0]; // useradd -s /sbin/nologin username struct passwd *pw = getpwnam(username.c_str()); if(pw){ if(setgid(pw->pw_gid) == 0 && setuid(pw->pw_uid) == 0){ log(__FUNCTION__) << D("切换到用户[%s]",username.c_str()) << std::endl; log(__FUNCTION__) << D("切换到用户组[%s]",username.c_str()) << std::endl; return true; } } log(lyramilk::log::warning,__FUNCTION__) << D("切换到用户[%s]失败%s",username.c_str(),strerror(errno)) << std::endl; return false; } lyramilk::data::var add_require_dir(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); TODO(); return true; } lyramilk::data::var serialize(const lyramilk::data::array& args,const lyramilk::data::map& env) { if(args.size() < 1) throw lyramilk::exception(D("%s参数不足",__FUNCTION__)); lyramilk::data::var v = args[0]; lyramilk::data::stringstream ss; v.serialize(ss); lyramilk::data::string str = ss.str(); lyramilk::data::chunk bstr((const unsigned char*)str.c_str(),str.size()); return bstr; } lyramilk::data::var deserialize(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_bin); lyramilk::data::string seq = args[0]; lyramilk::data::var v; lyramilk::data::stringstream ss(seq); v.deserialize(ss); return v; } lyramilk::data::var json_stringify(const lyramilk::data::array& args,const lyramilk::data::map& env) { if(args.size() < 1) throw lyramilk::exception(D("%s参数不足",__FUNCTION__)); lyramilk::data::string jsonstr; lyramilk::data::var v = args[0]; lyramilk::data::json::stringify(v,&jsonstr); return jsonstr; } lyramilk::data::var json_parse(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::var v; lyramilk::data::json::parse(args[0],&v); return v; } lyramilk::data::var system(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::string str = args[0]; lyramilk::data::string ret; FILE *pp = popen(str.c_str(), "r"); char tmp[1024]; while (fgets(tmp, sizeof(tmp), pp) != NULL) { ret.append(tmp); } pclose(pp); return ret; } lyramilk::data::var decode(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str); lyramilk::data::string type = args[0]; lyramilk::data::string str = args[1]; return lyramilk::data::codes::instance()->decode(type,str); } lyramilk::data::var encode(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_str); lyramilk::data::string type = args[0]; lyramilk::data::string str = args[1]; return lyramilk::data::codes::instance()->encode(type,str); } lyramilk::data::var sha1(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::string str = args[0]; lyramilk::cryptology::sha1 c1; c1 << str; return c1.get_key().str(); } lyramilk::data::var md5_16(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::string str = args[0]; lyramilk::cryptology::md5 c1; c1 << str; return c1.get_key().str16(); } lyramilk::data::var md5_32(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); lyramilk::data::string str = args[0]; lyramilk::cryptology::md5 c1; c1 << str; return c1.get_key().str32(); } lyramilk::data::string inline md5(lyramilk::data::string str) { lyramilk::cryptology::md5 c1; c1 << str; return c1.get_key().str32(); } lyramilk::data::var http_digest_authentication(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,1,lyramilk::data::var::t_map); lyramilk::data::string emptystr; lyramilk::data::string algorithm = args[0]; lyramilk::data::map m = args[1]; lyramilk::data::string realm = m["realm"].conv(emptystr); if(realm.empty()) return lyramilk::data::var::nil; lyramilk::data::string nonce = m["nonce"].conv(emptystr); if(nonce.empty()) return lyramilk::data::var::nil; lyramilk::data::string cnonce = m["cnonce"].conv(emptystr); if(cnonce.empty()) return lyramilk::data::var::nil; lyramilk::data::string nc = m["nc"].conv(emptystr); if(nc.empty()) return lyramilk::data::var::nil; lyramilk::data::string qop = m["qop"].conv(emptystr); if(qop.empty()) return lyramilk::data::var::nil; lyramilk::data::string uri = m["uri"].conv(emptystr); if(uri.empty()) return lyramilk::data::var::nil; lyramilk::data::string method = m["method"].conv(emptystr); if(method.empty()) return lyramilk::data::var::nil; lyramilk::data::string HA1 = m["HA1"].conv(emptystr); lyramilk::data::string HA2 = m["HA2"].conv(emptystr); lyramilk::data::string HD = m["HD"].conv(emptystr); if(HA1.empty()){ MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,2,lyramilk::data::var::t_str); MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,3,lyramilk::data::var::t_str); lyramilk::data::string username = args[2]; lyramilk::data::string password = args[3]; if(algorithm == "MD5"){ HA1 = md5(username + ":" + realm + ":" + password); }else if(algorithm == "MD5-sess"){ HA1 = md5(md5(username + ":" + realm + ":" + password) + ":" + nonce + ":" + cnonce); } } if(qop == "auth-int"){ lyramilk::data::string body = m["body"].conv(emptystr); if(body.empty()) return lyramilk::data::var::nil; if(HD.empty()) HD = nonce + ":" + nc + ":" + cnonce + ":" + qop; if(uri.empty()){ }else{ if(HA2.empty()) HA2 = md5(method + ":" + uri + ":" + md5(body)); } }else if(qop == ""){ if(HD.empty()) HD = nonce; if(uri.empty()){ if(HA2.empty()) HA2 = md5(method); }else{ if(HA2.empty()) HA2 = md5(method + ":" + uri); } }else if(qop == "auth"){ if(HD.empty()) HD = nonce + ":" + nc + ":" + cnonce + ":" + qop; if(uri.empty()){ if(HA2.empty()) HA2 = md5(method); }else{ if(HA2.empty()) HA2 = md5(method + ":" + uri); } }else{ return lyramilk::data::var::nil; } return md5(HA1 + ":" + HD + ":" + HA2); } lyramilk::data::var bin2str(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_bin); return args[0].str(); } lyramilk::data::var srand(const lyramilk::data::array& args,const lyramilk::data::map& env) { MILK_CHECK_SCRIPT_ARGS_LOG(log,lyramilk::log::warning,__FUNCTION__,args,0,lyramilk::data::var::t_int); int seed = args[0]; ::srand(seed); return true; } lyramilk::data::var rand(const lyramilk::data::array& args,const lyramilk::data::map& env) { return ::rand(); } static int define(lyramilk::script::engine* p) { int i = 0; { p->define("require",teapoy_import);++i; p->define("task",task);++i; p->define("create_thread",task_once);++i; p->define("daemon",daemon);++i; p->define("crand",crand);++i; p->define("msleep",msleep);++i; p->define("su",su);++i; p->define("add_require_dir",add_require_dir);++i; p->define("serialize",serialize);++i; p->define("deserialize",deserialize);++i; p->define("json_stringify",json_stringify);++i; p->define("json_parse",json_parse);++i; p->define("system",system);++i; p->define("decode",decode);++i; p->define("encode",encode);++i; p->define("sha1",sha1);++i; p->define("md5_16",md5_16);++i; p->define("md5_32",md5_32);++i; p->define("md5",md5_32);++i; p->define("bin2str",bin2str);++i; p->define("srand",srand);++i; p->define("rand",rand);++i; p->define("http_digest_authentication",http_digest_authentication);++i; } return i; } static __attribute__ ((constructor)) void __init() { lyramilk::teapoy::script_interface_master::instance()->regist("sys",define); } }}}
31.264188
113
0.659176
lyramilk
7a0452eb3f7c791a6759324a8cc74c66ba20d538
1,190
hpp
C++
components/esm/records.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/esm/records.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
components/esm/records.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef OPENMW_ESM_RECORDS_H #define OPENMW_ESM_RECORDS_H #include "defs.hpp" #include "loadacti.hpp" #include "loadalch.hpp" #include "loadappa.hpp" #include "loadarmo.hpp" #include "loadbody.hpp" #include "loadbook.hpp" #include "loadbsgn.hpp" #include "loadcell.hpp" #include "loadclas.hpp" #include "loadclot.hpp" #include "loadcont.hpp" #include "loadcrea.hpp" #include "loadcrec.hpp" #include "loadinfo.hpp" #include "loaddial.hpp" #include "loaddoor.hpp" #include "loadench.hpp" #include "loadfact.hpp" #include "loadglob.hpp" #include "loadgmst.hpp" #include "loadingr.hpp" #include "loadland.hpp" #include "loadlevlist.hpp" #include "loadligh.hpp" #include "loadlock.hpp" #include "loadrepa.hpp" #include "loadprob.hpp" #include "loadltex.hpp" #include "loadmgef.hpp" #include "loadmisc.hpp" #include "loadnpc.hpp" #include "loadnpcc.hpp" #include "loadpgrd.hpp" #include "loadrace.hpp" #include "loadregn.hpp" #include "loadscpt.hpp" #include "loadskil.hpp" #include "loadsndg.hpp" #include "loadsoun.hpp" #include "loadspel.hpp" #include "loadsscr.hpp" #include "loadstat.hpp" #include "loadweap.hpp" // Special records which are not loaded from ESM #include "attr.hpp" #endif
22.884615
48
0.755462
Bodillium
bb43114a487af71d36c85fab409165ca69ed9b9a
3,221
cpp
C++
stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
86
2018-05-24T12:03:44.000Z
2022-03-13T03:01:25.000Z
stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
1
2019-05-30T01:38:40.000Z
2019-10-26T07:15:01.000Z
stlsoft/test/winstl/findvolume_sequence_test/findvolume_sequence_test.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
14
2018-07-16T08:29:12.000Z
2021-08-23T06:21:30.000Z
// findvolume_sequence_test.cpp // // Updated: 22nd April 2004 // This will cause various compile-time messages to be emitted. When you get // sick of them just comment out or remove this #define #define _STLSOFT_COMPILE_VERBOSE #include <stlsoft.h> #include <winstl.h> #include <stlsoft_simple_algorithms.h> #include <winstl_findvolume_sequence.h> winstl_ns_using(findvolume_sequence_a) winstl_ns_using(findvolume_sequence_w) #include <stdio.h> #include <wchar.h> #include <functional> #include <algorithm> #if !defined(_WIN32_WINNT) || \ (_WIN32_WINNT < 0x0500) static FARPROC GetKernel32ProcOrTerminate(LPSTR procName) { // We're incrementing KERNEL32's reference count, but that's ok, // because it's KERNEL32. Not to be recommended normally. FARPROC fp = ::GetProcAddress(::LoadLibrary("Kernel32"), procName); return (fp != NULL) ? fp : (::ExitProcess(1), FARPROC(0)); } HANDLE WINAPI FindFirstVolumeA(LPSTR lpszVolumeName, DWORD cchBufferLength) { return (*reinterpret_cast<HANDLE (WINAPI *)(LPSTR , DWORD )>(GetKernel32ProcOrTerminate("FindFirstVolumeA")))(lpszVolumeName, cchBufferLength); } HANDLE WINAPI FindFirstVolumeW(LPWSTR lpszVolumeName, DWORD cchBufferLength) { return (*reinterpret_cast<HANDLE (WINAPI *)(LPWSTR , DWORD )>(GetKernel32ProcOrTerminate("FindFirstVolumeW")))(lpszVolumeName, cchBufferLength); } BOOL WINAPI FindNextVolumeA(HANDLE hFindVolume, LPSTR lpszVolumeName, DWORD cchBufferLength) { return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE, LPSTR , DWORD )>(GetKernel32ProcOrTerminate("FindNextVolumeA")))(hFindVolume, lpszVolumeName, cchBufferLength); } BOOL WINAPI FindNextVolumeW(HANDLE hFindVolume, LPWSTR lpszVolumeName, DWORD cchBufferLength) { return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE, LPWSTR , DWORD )>(GetKernel32ProcOrTerminate("FindNextVolumeW")))(hFindVolume, lpszVolumeName, cchBufferLength); } BOOL WINAPI FindVolumeClose(HANDLE hFindVolume) { return (*reinterpret_cast<BOOL (WINAPI *)(HANDLE)>(GetKernel32ProcOrTerminate("FindVolumeClose")))(hFindVolume); } #endif /* !_WIN32_WINNT || (_WIN32_WINNT < 0x0500) */ // Because of the difficulties that Borland and GNU compilers have with // these definitions, this functional looks extremely complex. When // writing for a single compiler, or for a set that includes the 'better' // compilers (Intel, Metrowerks, Comeau, Digital Mars) it would not be // an issue. struct print_path { public: void operator ()(winstl_ns_qual(findvolume_sequence_a)::value_type const &value) { fprintf(stdout, "%s\n", (const char *)value); } void operator ()(winstl_ns_qual(findvolume_sequence_w)::value_type const &value) { fwprintf(stdout, L"%s\n", (const wchar_t *)value); } }; int main(int /* argc */, char ** /*argv*/) { winstl_ns_qual(findvolume_sequence_a) volumes_a; winstl_ns_qual(findvolume_sequence_w) volumes_w; printf("Current volumes (ANSI):\n"); stlsoft_ns_qual(for_each_preinc)(volumes_a.begin(), volumes_a.end(), print_path()); printf("Current volumes (Unicode):\n"); stlsoft_ns_qual(for_each_postinc)(volumes_w.begin(), volumes_w.end(), print_path()); return 0; }
33.206186
164
0.73859
masscry
bb435e8bd2d9eef2a964efa8005a5374741e7147
3,553
hpp
C++
src/include/1_2/CL/cl2xrt.hpp
AlphaBu/XRT
72d34d637d3292e56871f9384888e6aed73b5969
[ "Apache-2.0" ]
359
2018-10-05T03:05:08.000Z
2022-03-31T06:28:16.000Z
src/include/1_2/CL/cl2xrt.hpp
AlphaBu/XRT
72d34d637d3292e56871f9384888e6aed73b5969
[ "Apache-2.0" ]
5,832
2018-10-02T22:43:29.000Z
2022-03-31T22:28:05.000Z
src/include/1_2/CL/cl2xrt.hpp
AlphaBu/XRT
72d34d637d3292e56871f9384888e6aed73b5969
[ "Apache-2.0" ]
442
2018-10-02T23:06:29.000Z
2022-03-21T08:34:44.000Z
/** * Copyright (C) 2021 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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. */ #ifndef XRT_CL2XRT_HPP #define XRT_CL2XRT_HPP #include "experimental/xrt_bo.h" #include "experimental/xrt_device.h" #include "experimental/xrt_kernel.h" #include <CL/cl.h> #if defined(_WIN32) # ifdef XOCL_SOURCE # define XOCL_EXPORT __declspec(dllexport) # else # define XOCL_EXPORT __declspec(dllimport) # endif #else # define XOCL_EXPORT __attribute__((visibility("default"))) #endif #ifdef __cplusplus // C++ extensions that allow host applications to move from OpenCL // objects to corresponding XRT native C++ objects namespace xrt { namespace opencl { /** * get_xrt_device() - Retrieve underlying xrt::device object * * @device: OpenCL device ID * Return: xrt::device object associated with the OpenCL device */ XOCL_EXPORT xrt::device get_xrt_device(cl_device_id device); /** * get_xrt_bo() - Retrieve underlying xrt::bo object * * @device: OpenCL device ID * @mem: OpenCL memory object to convert to xrt::bo * Return: xrt::bo object associated with the OpenCL buffer * * OpenCL memory objects are created in a cl_context and are * not uniquely associated with one single device. It is * possible the cl_mem buffer has not been associated with a * device and if so, the returned xrt::bo object is empty. */ XOCL_EXPORT xrt::bo get_xrt_bo(cl_device_id device, cl_mem mem); /** * get_xrt_kernel() - Retrieve underlying xrt::kernel object * * @device: OpenCL device ID * @kernel: OpenCL kernel object to convert to xrt::kernel * Return: xrt::kernel object associated with the OpenCL kernel * * OpenCL kernel objects are created in a cl_context and are not * uniquely associated with a single cl_device. However, a * xrt::kernel objects is created for each device in the context in * which the cl_kernel objects was created. This function returns the * xrt::kernel object for specified device and kernel pair. */ XOCL_EXPORT xrt::kernel get_xrt_kernel(cl_device_id device, cl_kernel kernel); /** * get_xrt_run() - Retrieve underlying xrt::run object * * @device: OpenCL device ID * @kernel: OpenCL kernel object to convert to xrt::run * Return: xrt::run object associated with the OpenCL kernel * * OpenCL kernel object is associated with an xrt::kernel object for * each device in the context in which the cl_kernel was created. * This function returns the xrt::run object corresponding to the * xrt::kernel object that in turn is associated with the cl_device * and cl_kernel pair. * * The returned run object reflects any scalar argument that were set * on the cl_kernel object, but does not reflect the global memory * objects as these are not mapped to a device until the enqueue * operation. * * The returned run object is cloned and detached from the cl_kernel * meaning that any changes to the run object are not reflected * in the cl_kernel object. */ XOCL_EXPORT xrt::run get_xrt_run(cl_device_id device, cl_kernel kernel); }} // opencl, xrt #endif // __cplusplus #endif
31.166667
76
0.748382
AlphaBu
bb43e4b192ad4725033d5404103b4cf334583627
796
cpp
C++
EraseSecure/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
EraseSecure/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
EraseSecure/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string orginal, processed, flipped; int proc_num; cin >> proc_num >> orginal >> processed; if(proc_num%2 == 0){ if(orginal == processed){ cout << "Deletion succeeded" << endl; } else{ cout << "Deletion failed" << endl; } } else{ int stop = orginal.size(); for(int i = 0; i < stop; i++){ if(orginal[i]=='1'){ flipped += "0"; } else{ flipped += "1"; } } if(flipped == processed){ cout << "Deletion succeeded" << endl; } else{ cout << "Deletion failed" << endl; } } return 0; }
21.513514
49
0.430905
KalawelaLo
bb4ba5442d4b040866523fa2e0d7fdd29772dad3
12,686
cpp
C++
lib/src/PyParse/PyVectorFunction.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
null
null
null
lib/src/PyParse/PyVectorFunction.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
null
null
null
lib/src/PyParse/PyVectorFunction.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
1
2021-04-13T19:06:43.000Z
2021-04-13T19:06:43.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "Python.h" #include "PyVectorFunction.H" #include "CH_assert.H" #include <iostream> #include "NamespaceHeader.H" using namespace std; //----------------------------------------------------------------------- bool PyVectorFunction:: isValid(PyObject* a_pyObject) { // If the object is a 2-tuple with valid contents, it's also okay. if (PyTuple_Check(a_pyObject) && (PyTuple_Size(a_pyObject) == 2) && PyVectorFunction::isValid(PyTuple_GetItem(a_pyObject, 0), PyTuple_GetItem(a_pyObject, 1))) return true; // If we are given a vector, we can interpret the function as constant // in both space and time. if (PySequence_Check(a_pyObject) && (PySequence_Length(a_pyObject) == SpaceDim)) { bool isVector = true; for (int d = 0; d < SpaceDim; ++d) { PyObject* item = PySequence_GetItem(a_pyObject, d); if (!PyFloat_Check(item) && !PyInt_Check(item)) isVector = false; Py_DECREF(item); } return isVector; } // Otherwise, if it can't be called, it is an abomination. if (!PyCallable_Check(a_pyObject)) return false; // Try to call it at time 0 at the origin. PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15)); } double t = 0.0; PyObject* result = PyObject_CallFunction(a_pyObject, (char*)"Od", x, t); if (result == NULL) { // The 2-argument form doesn't work. Try the single-argument form. PyErr_Clear(); result = PyObject_CallFunctionObjArgs(a_pyObject, x, NULL); if (result == NULL) { // Nope. No good. PyErr_Clear(); Py_DECREF(x); return false; } } Py_DECREF(x); // The result should be interpretable as a vector. bool isVector = (PySequence_Check(result) && (PySequence_Length(result) == SpaceDim)); if (isVector) { for (int d = 0; d < SpaceDim; ++d) { PyObject* item = PySequence_GetItem(result, d); if (!PyFloat_Check(item) && !PyInt_Check(item)) isVector = false; Py_DECREF(item); } } Py_DECREF(result); return isVector; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- bool PyVectorFunction:: isValid(PyObject* a_pyFunction, PyObject* a_pyDerivs) { // First of all, if they can't be called, they are abominations. if (!PyCallable_Check(a_pyFunction) || !PyCallable_Check(a_pyDerivs)) return false; // Try to call it at time 0 at the origin. PyObject* order = PyTuple_New(SpaceDim); PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(order, d, PyInt_FromLong(1)); PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15)); } double t = 0.0; PyObject* result = PyObject_CallFunction(a_pyFunction, (char*)"Od", x, t); PyObject* derivResult; if (result == NULL) { // The 2-argument form doesn't work. Try the single-argument form. PyErr_Clear(); result = PyObject_CallFunctionObjArgs(a_pyFunction, x, NULL); if (result == NULL) { // Nope. No good. PyErr_Clear(); Py_DECREF(order); Py_DECREF(x); return false; } // Okay, the single-argument form of the function works, which means // that it is constant in time. Therefore, the 2-argument form of // the derivative should work. derivResult = PyObject_CallFunction(a_pyDerivs, (char*)"OO", order, x); if (derivResult == NULL) { // Well, we almost made it. PyErr_Clear(); Py_DECREF(order); Py_DECREF(x); return false; } } else { // The 2-argument form of the function works, which means // that it is time-dependent. Therefore, the 3-argument form of // the derivative should work. derivResult = PyObject_CallFunction(a_pyDerivs, (char*)"OOd", order, x, t); if (derivResult == NULL) { // No luck. PyErr_Clear(); Py_DECREF(order); Py_DECREF(x); return false; } } Py_DECREF(order); Py_DECREF(x); // The result should be interpretable as a vector. bool funcIsVector = (PySequence_Check(result) && (PySequence_Length(result) == SpaceDim)); bool derivIsVector = (PySequence_Check(derivResult) && (PySequence_Length(derivResult) == SpaceDim)); if (funcIsVector && derivIsVector) { for (int d = 0; d < SpaceDim; ++d) { PyObject* funcItem = PySequence_GetItem(result, d); PyObject* derivItem = PySequence_GetItem(result, d); if (!PyFloat_Check(funcItem) && !PyInt_Check(funcItem)) funcIsVector = false; if (!PyFloat_Check(derivItem) && !PyInt_Check(derivItem)) funcIsVector = false; Py_DECREF(funcItem); Py_DECREF(derivItem); } } Py_DECREF(result); Py_DECREF(derivResult); return (funcIsVector && derivIsVector); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- PyVectorFunction:: PyVectorFunction(PyObject* a_pyObject): VectorFunction(false, false), m_func(a_pyObject), m_derivs(NULL) { CH_assert(a_pyObject != NULL); CH_assert(isValid(a_pyObject)); // If the object is a 2-tuple with valid contents, crack it open. if (PyTuple_Check(a_pyObject) && (PyTuple_Size(a_pyObject) == 2) && isValid(PyTuple_GetItem(a_pyObject, 0), PyTuple_GetItem(a_pyObject, 1))) { m_func = PyTuple_GetItem(a_pyObject, 0); m_derivs = PyTuple_GetItem(a_pyObject, 1); } // If we are given a vector, we can interpret the function as constant // in both space and time. else if (PySequence_Check(a_pyObject) && (PySequence_Length(a_pyObject) == SpaceDim)) { m_isConstant = m_isHomogeneous = true; return; } // Figure out whether the function takes one or two arguments. PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15)); } double t = 0.0; PyObject* result = PyObject_CallFunction(a_pyObject, (char*)"Od", x, t); Py_DECREF(x); if (result == NULL) { // The 2-argument form doesn't work, so the function is constant in time. PyErr_Clear(); m_isConstant = true; } Py_XDECREF(result); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- PyVectorFunction:: PyVectorFunction(PyObject* a_pyFunction, PyObject* a_pyDerivs): VectorFunction(false, false), m_func(a_pyFunction), m_derivs(a_pyDerivs) { CH_assert(a_pyFunction != NULL); CH_assert(a_pyDerivs != NULL); CH_assert(isValid(a_pyFunction, a_pyDerivs)); Py_INCREF(a_pyFunction); Py_INCREF(a_pyDerivs); // Figure out whether the function takes one or two arguments. PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15)); } double t = 0.0; PyObject* result = PyObject_CallFunction(a_pyFunction, (char*)"Od", x, t); Py_DECREF(x); if (result == NULL) { // The 2-argument form doesn't work, so the function is constant in time. PyErr_Clear(); m_isConstant = true; } Py_XDECREF(result); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- PyVectorFunction:: ~PyVectorFunction() { Py_XDECREF(m_func); Py_XDECREF(m_derivs); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- RealVect PyVectorFunction:: operator()(const RealVect& a_x, Real a_t) const { // If we're constant and homogeneous, interpret the function // as a vector. RealVect v; if (m_isConstant && m_isHomogeneous) { for (int d = 0; d < SpaceDim; ++d) { PyObject* item = PyTuple_GetItem(m_func, d); v[d] = (PyFloat_Check(item)) ? PyFloat_AsDouble(item) : static_cast<double>(PyInt_AsLong(item)); } return v; } // Construct a d-tuple for a_x. PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(x, d, PyFloat_FromDouble(a_x[d])); } // Call the function with our arguments. PyObject* result; if (isConstant()) { result = PyObject_CallFunctionObjArgs(m_func, x, NULL); } else { result = PyObject_CallFunction(m_func, (char*)"Od", x, static_cast<double>(a_t)); } Py_DECREF(x); if (PyErr_Occurred()) { PyErr_Print(); MayDay::Error("Evaluation of Python-supplied vector function failed."); } // Extract our vector. CH_assert(PySequence_Check(result) && (PySequence_Length(result) == SpaceDim)); for (int d = 0; d < SpaceDim; ++d) { PyObject* item = PySequence_GetItem(result, d); v[d] = (PyFloat_Check(item)) ? static_cast<double>(PyFloat_AsDouble(item)) : static_cast<double>(PyInt_AsLong(item)); Py_DECREF(item); } Py_DECREF(result); return v; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- RealVect PyVectorFunction:: derivative(const IntVect& a_order, const RealVect& a_x, Real a_t) const { // If the order is zero, return the function's value. if (a_order == IntVect::Zero) return (*this)(a_x, a_t); // If the function is homogeneous, return 0 for all derivatives. if (m_isHomogeneous) return RealVect::Zero; // If we don't have a mechanism for evaluating derivatives, // we are unable to continue. if (m_derivs == NULL) MayDay::Error("This vector function does not define derivatives"); // Construct d-tuples for a_order and a_x. PyObject* order = PyTuple_New(SpaceDim); PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(order, d, PyInt_FromLong(a_order[d])); PyTuple_SetItem(x, d, PyFloat_FromDouble(a_x[d])); } // Call the function with our arguments. PyObject* result; if (isConstant()) { result = PyObject_CallFunction(m_derivs, (char*)"OO", order, x); } else { result = PyObject_CallFunction(m_derivs, (char*)"OOd", order, x, static_cast<double>(a_t)); } Py_DECREF(order); Py_DECREF(x); if (PyErr_Occurred()) { PyErr_Print(); MayDay::Error("Evaluation of Python-supplied vector function derivative failed."); } RealVect v; CH_assert(PySequence_Check(result) && (PySequence_Length(result) == SpaceDim)); for (int d = 0; d < SpaceDim; ++d) { PyObject* item = PySequence_GetItem(result, d); v[d] = (PyFloat_Check(item)) ? static_cast<double>(PyFloat_AsDouble(item)) : static_cast<double>(PyInt_AsLong(item)); Py_DECREF(item); } Py_DECREF(result); return v; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- bool PyVectorFunction:: hasDerivative(const IntVect& a_order) const { // We always have the zeroth order derivative. :-P if ((a_order == IntVect::Zero) || m_isHomogeneous) return true; // If we don't have a mechanism for evaluating derivatives, // we are unable to continue. if (m_derivs == NULL) return false; // Construct d-tuples for a_order and a_x. PyObject* order = PyTuple_New(SpaceDim); PyObject* x = PyTuple_New(SpaceDim); for (int d = 0; d < SpaceDim; ++d) { PyTuple_SetItem(order, d, PyInt_FromLong(a_order[d])); PyTuple_SetItem(x, d, PyFloat_FromDouble(1e-15)); } // Call the function with our arguments. PyObject* result; if (isConstant()) { result = PyObject_CallFunction(m_derivs, (char*)"OO", order, x); } else { result = PyObject_CallFunction(m_derivs, (char*)"OOd", order, x, static_cast<double>(0.0)); } Py_DECREF(order); Py_DECREF(x); if (PyErr_Occurred()) { PyErr_Clear(); return false; } Py_DECREF(result); return true; } //----------------------------------------------------------------------- #include "NamespaceFooter.H"
29.297921
87
0.580719
rmrsk
bb51fbadc27935f9a34938e73987c0f622e9da94
2,479
cpp
C++
src/timeopt/problem.cpp
ggory15/hpp_timeopt_python
3100d044be65bae521913bea0b9ed902cc5d346c
[ "BSD-2-Clause" ]
null
null
null
src/timeopt/problem.cpp
ggory15/hpp_timeopt_python
3100d044be65bae521913bea0b9ed902cc5d346c
[ "BSD-2-Clause" ]
1
2019-10-23T20:24:14.000Z
2019-10-31T05:23:05.000Z
src/timeopt/problem.cpp
ggory15/hpp_timeopt_python
3100d044be65bae521913bea0b9ed902cc5d346c
[ "BSD-2-Clause" ]
2
2019-01-17T13:16:08.000Z
2019-03-25T13:24:47.000Z
// Copyright (c) 2018-2019, CNRS // Authors: Sanghyun Kim <[email protected]> #include "timeopt/problem.hpp" #include <momentumopt/cntopt/ContactPlanFromFile.hpp> #include <fstream> #include <iomanip> namespace timeopt { ProblemInfo::ProblemInfo() : phases_() // pre-allocation , init_com_(Vector3d::Ones()*1000) , final_com_(Vector3d::Ones()*1000) , mass_(0.0) { init_state_ = new InitialState(); contact_state_ = new ContactState(); planner_ = new ContactPlanner(); } ProblemInfo::ProblemInfo(const Index size) : phases_(size) // pre-allocation , init_com_(Vector3d::Ones()*1000) , final_com_(Vector3d::Ones()*1000) , mass_(0.0) { init_state_ = new InitialState(); contact_state_ = new ContactState(size); planner_ = new ContactPlanner(); } void ProblemInfo::setConfigurationFile(const std::string & file_location) const throw (std::invalid_argument) { if (init_com_.norm() > 1000){ const std::string exception_message("Initial COM does not seem to be a valid value."); } if (final_com_.norm() > 1000){ const std::string exception_message("Final COM does not seem to be a valid value."); } if (mass_ < 0.001){ const std::string exception_message("Robot's Mass does not seem to be a valid value."); } init_state_->save(); contact_state_->save(); planner_->initialize(file_location, *init_state_, *contact_state_); planner_->setTimehorizon(contact_state_->getTimeHorizon()); planner_->saveToFile(); } void ProblemInfo::setTimeoptSolver(const std::string & file){ std::string cfg_file; cfg_file = file.substr(0, file.size()-5)+"_final.yaml"; planner_setting_.initialize(cfg_file); dynamic_state_.fillInitialRobotState(cfg_file); ref_sequence_.resize(planner_setting_.get(momentumopt::PlannerIntParam_NumTimesteps)); } void ProblemInfo::solve(){ momentumopt::ContactPlanFromFile contact_plan; contact_plan.initialize(planner_setting_); contact_plan.optimize(dynamic_state_); dyn_optimizer_.initialize(planner_setting_, dynamic_state_, &contact_plan); dyn_optimizer_.optimize(ref_sequence_); time_traj_.resize(getNumSize()); int size = getNumSize(); time_traj_(0) = dyn_optimizer_.dynamicsSequence().dynamicsState(0).time(); for (int i=1; i<size; i++) time_traj_(i) = dyn_optimizer_.dynamicsSequence().dynamicsState(i).time() + time_traj_(i-1); } }
32.194805
111
0.696652
ggory15
bb57a1994515696061ad300d1f0be7e6f7559710
3,121
cpp
C++
src/particle_dynamics/PDApp.cpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
src/particle_dynamics/PDApp.cpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
src/particle_dynamics/PDApp.cpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
# include "PDApp.hpp" using namespace std; // ------------------------------------------------------------------------- // Constructor: // ------------------------------------------------------------------------- PDApp::PDApp(const GetPot& input_params) { // --------------------------------------- // Assign variables from 'input_params': // --------------------------------------- p.NX = input_params("Domain/nx",1); p.NY = input_params("Domain/ny",1); p.NZ = input_params("Domain/nz",1); p.dx = input_params("Domain/dx",1.0); p.dy = input_params("Domain/dy",1.0); p.dz = input_params("Domain/dz",1.0); p.dt = input_params("Time/dt",1.0); p.iskip = input_params("Output/iskip",1); p.jskip = input_params("Output/jskip",1); p.kskip = input_params("Output/kskip",1); p.LX = p.NX*p.dx; p.LY = p.NY*p.dy; p.LZ = p.NZ*p.dz; // get number of particles to determin if greater than zero numberOfParticles = input_params("PDApp/N",0); // --------------------------------------- // Get some MPI parameters: // --------------------------------------- p.np = MPI::COMM_WORLD.Get_size(); // # of processors p.rank = MPI::COMM_WORLD.Get_rank(); // my processor number // --------------------------------------- // Set dimensions: // --------------------------------------- ptrdiff_t locsize, locnx, offx; fftw_mpi_init(); locsize = fftw_mpi_local_size_3d(p.NX,p.NY,p.NZ,MPI_COMM_WORLD,&locnx,&offx); p.nx = locnx; p.ny = p.NY; p.nz = p.NZ; p.xOff = offx; // --------------------------------------- // Create a PD object: // --------------------------------------- pd_object = new PDParticles(p,input_params); } // ------------------------------------------------------------------------- // Destructor: // ------------------------------------------------------------------------- PDApp::~PDApp() { delete pd_object; } // ------------------------------------------------------------------------- // Initialize system: // ------------------------------------------------------------------------- void PDApp::initSystem() { pd_object->initParticles(); } // ------------------------------------------------------------------------- // Take one step forward in time: // ------------------------------------------------------------------------- void PDApp::stepForward(int step) { // ---------------------------------------- // Set the time step: // ---------------------------------------- current_step = step; pd_object->setTimeStep(current_step); // ---------------------------------------- // Update Particles system: // ---------------------------------------- pd_object->updateParticles(); } // ------------------------------------------------------------------------- // Write output: // ------------------------------------------------------------------------- void PDApp::writeOutput(int step) { pd_object->setTimeStep(step); if(numberOfParticles > 0) pd_object->outputParticles(); }
26.008333
81
0.360141
flowzario
bb5fe46dc2f7860e7d9508c915a012f26cb07f11
12,666
hpp
C++
include/RootMotion/FinalIK/IKSolverLookAt.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/IKSolverLookAt.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/IKSolverLookAt.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: RootMotion.FinalIK.IKSolver #include "RootMotion/FinalIK/IKSolver.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: RootMotion::FinalIK namespace RootMotion::FinalIK { } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Forward declaring type: AnimationCurve class AnimationCurve; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Size: 0xC8 #pragma pack(push, 1) // Autogenerated type: RootMotion.FinalIK.IKSolverLookAt class IKSolverLookAt : public RootMotion::FinalIK::IKSolver { public: // Nested type: RootMotion::FinalIK::IKSolverLookAt::LookAtBone class LookAtBone; // public UnityEngine.Transform target // Size: 0x8 // Offset: 0x58 UnityEngine::Transform* target; // Field size check static_assert(sizeof(UnityEngine::Transform*) == 0x8); // public RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] spine // Size: 0x8 // Offset: 0x60 ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* spine; // Field size check static_assert(sizeof(::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*) == 0x8); // public RootMotion.FinalIK.IKSolverLookAt/LookAtBone head // Size: 0x8 // Offset: 0x68 RootMotion::FinalIK::IKSolverLookAt::LookAtBone* head; // Field size check static_assert(sizeof(RootMotion::FinalIK::IKSolverLookAt::LookAtBone*) == 0x8); // public RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] eyes // Size: 0x8 // Offset: 0x70 ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* eyes; // Field size check static_assert(sizeof(::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*) == 0x8); // [RangeAttribute] Offset: 0xE0869C // public System.Single bodyWeight // Size: 0x4 // Offset: 0x78 float bodyWeight; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE086B4 // public System.Single headWeight // Size: 0x4 // Offset: 0x7C float headWeight; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE086CC // public System.Single eyesWeight // Size: 0x4 // Offset: 0x80 float eyesWeight; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE086E4 // public System.Single clampWeight // Size: 0x4 // Offset: 0x84 float clampWeight; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE086FC // public System.Single clampWeightHead // Size: 0x4 // Offset: 0x88 float clampWeightHead; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE08714 // public System.Single clampWeightEyes // Size: 0x4 // Offset: 0x8C float clampWeightEyes; // Field size check static_assert(sizeof(float) == 0x4); // [RangeAttribute] Offset: 0xE0872C // public System.Int32 clampSmoothing // Size: 0x4 // Offset: 0x90 int clampSmoothing; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: clampSmoothing and: spineWeightCurve char __padding10[0x4] = {}; // public UnityEngine.AnimationCurve spineWeightCurve // Size: 0x8 // Offset: 0x98 UnityEngine::AnimationCurve* spineWeightCurve; // Field size check static_assert(sizeof(UnityEngine::AnimationCurve*) == 0x8); // public UnityEngine.Vector3 spineTargetOffset // Size: 0xC // Offset: 0xA0 UnityEngine::Vector3 spineTargetOffset; // Field size check static_assert(sizeof(UnityEngine::Vector3) == 0xC); // Padding between fields: spineTargetOffset and: spineForwards char __padding12[0x4] = {}; // protected UnityEngine.Vector3[] spineForwards // Size: 0x8 // Offset: 0xB0 ::Array<UnityEngine::Vector3>* spineForwards; // Field size check static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8); // protected UnityEngine.Vector3[] headForwards // Size: 0x8 // Offset: 0xB8 ::Array<UnityEngine::Vector3>* headForwards; // Field size check static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8); // protected UnityEngine.Vector3[] eyeForward // Size: 0x8 // Offset: 0xC0 ::Array<UnityEngine::Vector3>* eyeForward; // Field size check static_assert(sizeof(::Array<UnityEngine::Vector3>*) == 0x8); // Creating value type constructor for type: IKSolverLookAt IKSolverLookAt(UnityEngine::Transform* target_ = {}, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* spine_ = {}, RootMotion::FinalIK::IKSolverLookAt::LookAtBone* head_ = {}, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>* eyes_ = {}, float bodyWeight_ = {}, float headWeight_ = {}, float eyesWeight_ = {}, float clampWeight_ = {}, float clampWeightHead_ = {}, float clampWeightEyes_ = {}, int clampSmoothing_ = {}, UnityEngine::AnimationCurve* spineWeightCurve_ = {}, UnityEngine::Vector3 spineTargetOffset_ = {}, ::Array<UnityEngine::Vector3>* spineForwards_ = {}, ::Array<UnityEngine::Vector3>* headForwards_ = {}, ::Array<UnityEngine::Vector3>* eyeForward_ = {}) noexcept : target{target_}, spine{spine_}, head{head_}, eyes{eyes_}, bodyWeight{bodyWeight_}, headWeight{headWeight_}, eyesWeight{eyesWeight_}, clampWeight{clampWeight_}, clampWeightHead{clampWeightHead_}, clampWeightEyes{clampWeightEyes_}, clampSmoothing{clampSmoothing_}, spineWeightCurve{spineWeightCurve_}, spineTargetOffset{spineTargetOffset_}, spineForwards{spineForwards_}, headForwards{headForwards_}, eyeForward{eyeForward_} {} // public System.Void SetLookAtWeight(System.Single weight) // Offset: 0x1BE41A4 void SetLookAtWeight(float weight); // public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight) // Offset: 0x1BE4228 void SetLookAtWeight(float weight, float bodyWeight); // public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight) // Offset: 0x1BE42D4 void SetLookAtWeight(float weight, float bodyWeight, float headWeight); // public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight) // Offset: 0x1BE439C void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight); // public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight, System.Single clampWeight) // Offset: 0x1BE4488 void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight); // public System.Void SetLookAtWeight(System.Single weight, System.Single bodyWeight, System.Single headWeight, System.Single eyesWeight, System.Single clampWeight, System.Single clampWeightHead, System.Single clampWeightEyes) // Offset: 0x1BE4594 void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight, float clampWeight, float clampWeightHead, float clampWeightEyes); // public System.Boolean SetChain(UnityEngine.Transform[] spine, UnityEngine.Transform head, UnityEngine.Transform[] eyes, UnityEngine.Transform root) // Offset: 0x1BE5158 bool SetChain(::Array<UnityEngine::Transform*>* spine, UnityEngine::Transform* head, ::Array<UnityEngine::Transform*>* eyes, UnityEngine::Transform* root); // protected System.Boolean get_spineIsValid() // Offset: 0x1BE4AE4 bool get_spineIsValid(); // protected System.Boolean get_spineIsEmpty() // Offset: 0x1BE4CBC bool get_spineIsEmpty(); // protected System.Void SolveSpine() // Offset: 0x1BE58FC void SolveSpine(); // protected System.Boolean get_headIsValid() // Offset: 0x1BE4BC8 bool get_headIsValid(); // protected System.Boolean get_headIsEmpty() // Offset: 0x1BE4CE0 bool get_headIsEmpty(); // protected System.Void SolveHead() // Offset: 0x1BE5B28 void SolveHead(); // protected System.Boolean get_eyesIsValid() // Offset: 0x1BE4BD8 bool get_eyesIsValid(); // protected System.Boolean get_eyesIsEmpty() // Offset: 0x1BE4D5C bool get_eyesIsEmpty(); // protected System.Void SolveEyes() // Offset: 0x1BE5D84 void SolveEyes(); // protected UnityEngine.Vector3[] GetForwards(ref UnityEngine.Vector3[] forwards, UnityEngine.Vector3 baseForward, UnityEngine.Vector3 targetForward, System.Int32 bones, System.Single clamp) // Offset: 0x1BE62B0 ::Array<UnityEngine::Vector3>* GetForwards(::Array<UnityEngine::Vector3>*& forwards, UnityEngine::Vector3 baseForward, UnityEngine::Vector3 targetForward, int bones, float clamp); // protected System.Void SetBones(UnityEngine.Transform[] array, ref RootMotion.FinalIK.IKSolverLookAt/LookAtBone[] bones) // Offset: 0x1BE5208 void SetBones(::Array<UnityEngine::Transform*>* array, ::Array<RootMotion::FinalIK::IKSolverLookAt::LookAtBone*>*& bones); // public override System.Void StoreDefaultLocalState() // Offset: 0x1BE46DC // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::StoreDefaultLocalState() void StoreDefaultLocalState(); // public override System.Void FixTransforms() // Offset: 0x1BE480C // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::FixTransforms() void FixTransforms(); // public override System.Boolean IsValid(ref System.String message) // Offset: 0x1BE4950 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Boolean IKSolver::IsValid(ref System.String message) bool IsValid(::Il2CppString*& message); // public override RootMotion.FinalIK.IKSolver/Point[] GetPoints() // Offset: 0x1BE4D80 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: RootMotion.FinalIK.IKSolver/Point[] IKSolver::GetPoints() ::Array<RootMotion::FinalIK::IKSolver::Point*>* GetPoints(); // public override RootMotion.FinalIK.IKSolver/Point GetPoint(UnityEngine.Transform transform) // Offset: 0x1BE4FB8 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: RootMotion.FinalIK.IKSolver/Point IKSolver::GetPoint(UnityEngine.Transform transform) RootMotion::FinalIK::IKSolver::Point* GetPoint(UnityEngine::Transform* transform); // protected override System.Void OnInitiate() // Offset: 0x1BE53AC // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::OnInitiate() void OnInitiate(); // protected override System.Void OnUpdate() // Offset: 0x1BE57F8 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::OnUpdate() void OnUpdate(); // public System.Void .ctor() // Offset: 0x1BE6750 // Implemented from: RootMotion.FinalIK.IKSolver // Base method: System.Void IKSolver::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static IKSolverLookAt* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::IKSolverLookAt::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<IKSolverLookAt*, creationType>())); } }; // RootMotion.FinalIK.IKSolverLookAt #pragma pack(pop) static check_size<sizeof(IKSolverLookAt), 192 + sizeof(::Array<UnityEngine::Vector3>*)> __RootMotion_FinalIK_IKSolverLookAtSizeCheck; static_assert(sizeof(IKSolverLookAt) == 0xC8); } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKSolverLookAt*, "RootMotion.FinalIK", "IKSolverLookAt");
50.86747
1,130
0.706063
darknight1050
bb60f6a1b1d41a32bd5ac791dfccd0d914f586f4
3,143
hpp
C++
lib/charLib.hpp
captainpeng/6-6
67ba91f0a7d639b3778fc78bb5a253812d2c3029
[ "MIT", "Unlicense" ]
null
null
null
lib/charLib.hpp
captainpeng/6-6
67ba91f0a7d639b3778fc78bb5a253812d2c3029
[ "MIT", "Unlicense" ]
null
null
null
lib/charLib.hpp
captainpeng/6-6
67ba91f0a7d639b3778fc78bb5a253812d2c3029
[ "MIT", "Unlicense" ]
null
null
null
/*! * \autor captainpeng * \date 2018-12-29 * \update 2018-12-29 * \version 1.0 * \copyright */ #ifndef charLib_hpp #define charLib_hpp #include<cctype> #include<cwctype> namespace my{ template<typename CharT> class charLib; template<> class charLib<char>{ public: using charType=char; static inline bool isalnum(charType ch){ return static_cast<bool>(std::isalnum(ch)); } static inline bool isalpha(charType ch){ return static_cast<bool>(std::isalpha(ch)); } static inline bool islower(charType ch){ return static_cast<bool>(std::islower(ch)); } static inline bool isupper(charType ch){ return static_cast<bool>(std::isupper(ch)); } static inline bool isdigit(charType ch){ return static_cast<bool>(std::isdigit(ch)); } static inline bool isxdigit(charType ch){ return static_cast<bool>(std::isxdigit(ch)); } static inline bool iscntrl(charType ch){ return static_cast<bool>(std::iscntrl(ch)); } static inline bool isgraph(charType ch){ return static_cast<bool>(std::isgraph(ch)); } static inline bool isspace(charType ch){ return static_cast<bool>(std::isspace(ch)); } static inline bool isblank(charType ch){ return static_cast<bool>(std::isblank(ch)); } static inline bool isprint(charType ch){ return static_cast<bool>(std::isprint(ch)); } static inline bool ispunct(charType ch){ return static_cast<bool>(std::ispunct(ch)); } static inline charType tolower(charType ch){ return static_cast<charType>(std::tolower(ch)); } static inline charType toupper(charType ch){ return static_cast<charType>(std::toupper(ch)); } }; template<> class charLib<wchar_t>{ public: using charType=wchar_t; static inline bool isalnum(charType ch){ return static_cast<bool>(std::iswalnum(ch)); } static inline bool isalpha(charType ch){ return static_cast<bool>(std::iswalpha(ch)); } static inline bool islower(charType ch){ return static_cast<bool>(std::iswlower(ch)); } static inline bool isupper(charType ch){ return static_cast<bool>(std::iswupper(ch)); } static inline bool isdigit(charType ch){ return static_cast<bool>(std::iswdigit(ch)); } static inline bool isxdigit(charType ch){ return static_cast<bool>(std::iswxdigit(ch)); } static inline bool iscntrl(charType ch){ return static_cast<bool>(std::iswcntrl(ch)); } static inline bool isgraph(charType ch){ return static_cast<bool>(std::iswgraph(ch)); } static inline bool isspace(charType ch){ return static_cast<bool>(std::iswspace(ch)); } static inline bool isblank(charType ch){ return static_cast<bool>(std::iswblank(ch)); } static inline bool isprint(charType ch){ return static_cast<bool>(std::iswprint(ch)); } static inline bool ispunct(charType ch){ return static_cast<bool>(std::iswpunct(ch)); } static inline charType tolower(charType ch){ return static_cast<charType>(std::towlower(ch)); } static inline charType toupper(charType ch){ return static_cast<charType>(std::towupper(ch)); } }; } #endif
21.09396
53
0.689787
captainpeng
bb6303130e8fe80b35a4a2da7dfc83c4d54ac643
3,363
cpp
C++
src/Window.cpp
jparimaa/varjo-dx11-minimal
489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d
[ "MIT" ]
null
null
null
src/Window.cpp
jparimaa/varjo-dx11-minimal
489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d
[ "MIT" ]
null
null
null
src/Window.cpp
jparimaa/varjo-dx11-minimal
489e9db74edfbaa1e745e6eaa5eb12dc202bfc3d
[ "MIT" ]
null
null
null
#include "Window.h" #include "Log.h" #include "Utility.h" #include <wrl/client.h> namespace { LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_ACTIVATEAPP: break; case WM_CHAR: if (wParam == 0x1B) // ESC { PostQuitMessage(0); } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP: break; case WM_INPUT: case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEWHEEL: case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_MOUSEHOVER: break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } } // namespace Window::Window() { } Window::~Window() { releaseDXPtr(m_swapChain); } void Window::init(HINSTANCE hInstance, int nCmdShow, IUnknown* device) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_APPLICATION); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = nullptr; wcex.lpszClassName = "varjo-test"; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_APPLICATION); if (!RegisterClassEx(&wcex)) { printError("Could not register window class"); abort(); } m_instanceHandle = hInstance; RECT rc = {0, 0, m_width, m_height}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); m_windowHandle = CreateWindow("varjo-test", "Direct3D", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance, nullptr); if (!m_windowHandle) { printError("Could not create window"); abort(); } ShowWindow(m_windowHandle, nCmdShow); Microsoft::WRL::ComPtr<IDXGIFactory> factory = nullptr; const HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); DXGI_SWAP_CHAIN_DESC swapChainDesc{}; swapChainDesc.BufferCount = swapChainLength; swapChainDesc.BufferDesc.Width = m_width; swapChainDesc.BufferDesc.Height = m_height; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferDesc.RefreshRate.Numerator = 60; swapChainDesc.BufferDesc.RefreshRate.Denominator = 1; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.OutputWindow = m_windowHandle; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = TRUE; HRESULT result = factory->CreateSwapChain(device, &swapChainDesc, &m_swapChain); checkHresult(result); } IDXGISwapChain* Window::getSwapChain() { return m_swapChain; } void Window::present() { m_swapChain->Present(1, 0); }
25.671756
189
0.679453
jparimaa
bb66baedfe2a51e6d6513d303d87005b1a4a3d01
245
hpp
C++
tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
tests/EnjoLibTest/src/ThreadedLoopTplTest.hpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#ifndef THREADEDLOOPTPLTEST_HPP #define THREADEDLOOPTPLTEST_HPP class ThreadedLoopTplTest { public: ThreadedLoopTplTest(); virtual ~ThreadedLoopTplTest(); protected: private: }; #endif // THREADEDLOOPTPLTEST_HPP
14.411765
39
0.722449
hlp2