blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
dcfa040adbb5e5bc7a263ecc5a42ac8850f2ab10
229f25ccda6d721f31c6d4de27a7bb85dcc0f929
/solutions/Light oj/1170 - Counting Perfect BST/solution.cpp
a8db49cb822450c4318927e6670010c91c618e4a
[]
no_license
camil0palacios/Competitive-programming
e743378a8791a66c90ffaae29b4fd4cfb58fff59
4211fa61e516cb986b3404d87409ad1a49f78132
refs/heads/master
2022-11-01T20:35:21.541132
2022-10-27T03:13:42
2022-10-27T03:13:42
155,419,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
cpp
solution.cpp
#include <bits/stdc++.h> #define endl '\n' #define ll long long using namespace std; const int MXN = 1000010; const ll MOD = 100000007; ll powers[203800], it; ll catalan[MXN]; ll fact[2*MXN + 5]; void precalc() { it = 0; for(ll i = 2; i <= 100001; i++) { ll num = i * i; while(num <= 10000000001LL) { powers[it++] = num; num *= i; } } sort(powers, powers + it); it = unique(powers, powers + it) - powers; powers[it++] = 10001000000LL; } ll powmod(ll a, ll b = MOD - 2) { ll ans = 1; while(b) { if(b & 1) ans = (ans * a) % MOD; a = (a * a) % MOD; b >>= 1; } return ans; } ll calcatalan() { fact[0] = fact[1] = 1; for(int i = 2; i < 2*MXN; i++) { fact[i] = (fact[i - 1] * i) % MOD; } catalan[0] = catalan[1] = 1; for(int i = 2; i < MXN; i++) { catalan[i] = fact[2 * i]; ll div = (fact[i] * fact[i + 1]) % MOD; div = powmod(div); catalan[i] = (catalan[i] * div) % MOD; } } void sol() { ll a, b; cin >> a >> b; int l = lower_bound(powers, powers + it, a) - powers; int r = lower_bound(powers, powers + it, b) - powers; if(powers[r] > b)r--; int x = r - l + 1; if(!x)cout << 0 << endl; else cout << catalan[x] << endl; } int main() { // ios_base::sync_with_stdio(false); cin.tie(NULL); precalc(); calcatalan(); int t; cin >> t; for(int cs = 1; cs <= t; cs++) { cout << "Case " << cs << ": "; sol(); } return 0; }
e670f50aa11360fd6cbb76ae66f6fabb8eb23ffe
eb061074ad2edc79f5025fc0845aae8cbe90bed9
/src/kernel/latte.cpp
a8766403b367bc961b2a28f0415a5de772f319a1
[]
no_license
dobrypd/LatteCompiler
e8204d54a737c872652a717018704d92c2318e94
5ba6b99684802a1ad540e3876afb5bf02d5c31cc
refs/heads/master
2016-09-06T21:26:35.294825
2013-02-21T10:03:20
2013-02-21T10:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,500
cpp
latte.cpp
/* * Author: Piotr Dobrowolski * pd291528@students.mimuw.edu.pl * */ #include <iostream> #include <stdlib.h> #include <stdio.h> #include "Absyn.H" #include "ParserManager.h" #include "ASTChecker.h" #include "ErrorHandler.h" #include "FunctionLoader.h" #include "ReturnsChecker.h" #include "ASCreator.h" using std::cerr; using std::cout; using std::endl; #ifndef NDEBUG const bool debug=true; #else const bool debug=false; #endif // Architecture and system based constants. enum arch_t {x86, x86_64}; #ifdef _ARCH_x86_64 const int arch = x86_64; #error Currently cannot build x86_64 late compiler. #else #ifdef _ARCH_x86 const int arch = x86; #else #error You must define one of _ARCH_x86 _ARCH_x86_64. #endif #endif const char* compiler_executable = "gcc"; const char* linker_executable = "gcc"; // ld const char* compiler_flags = "-c"; const char* linker_flags = "./lib/runtime.o"; #ifdef _ARCH_x86_64 const char* compiler_arch_flags = "-m64"; const char* linker_arch_flags = ""; #endif #ifdef _ARCH_x86 const char* compiler_arch_flags = "-m32"; const char* linker_arch_flags = // "-melf_i386 -l:./lib/lib32/libc.a ./lib/lib32/crt?.o"; "-m32"; #endif const char* stdin_in_filename = "from_stdin.lat"; const char* default_output_filename = "a.out"; // Constants end. void show_help(char* prog_name) { cout << "using " << prog_name << " [options] infile..." << endl << "options:" << endl << "-h\t- show this help message," << endl << "-o\t- define output file " << "(default this same as infile for assembler code (*.s) " << "and a.out for binary)." << endl << endl << "infile...\t- list of input files, if none - get from stdin." << endl; } struct Arguments { bool wrong; bool help; int input_count; char** input_files; char* output_file; }; Arguments parse_args(int argc, char** argv) { Arguments args; args.wrong = false; args.help = false; args.input_count = 0; args.input_files = 0; args.output_file = 0; int c; while ((c = getopt(argc, argv, "ho:")) != -1) { switch (c) { case 'h': args.help = true; break; case 'o': args.output_file = optarg; break; case '?': args.wrong = true; break; default: abort(); break; } } args.input_count = argc - optind; if (argc > optind) args.input_files = argv + optind; return args; } /* * Open stream (file or stdio). */ FILE* open_file(short files, char* file_name) { FILE* input = 0; if (files > 0) { input = fopen(file_name, "r"); if (!input) { cerr << "Cannot open file: " << file_name << endl; exit(EXIT_FAILURE); } if (debug) cerr << "Opened " << file_name << endl; } else { if (debug) cerr << "Will load Latte program from stdio." << endl; input = stdin; } return input; } std::string create_out_name(const char* input_file_name, const char* extension) { std::string ofn(input_file_name); size_t found = ofn.rfind('.'); if (found != std::string::npos){ ofn = ofn.substr(0, found); } ofn += "."; ofn += extension; return ofn; } /* * Will close file after parse, or in case of an error. */ int check_file(FILE* input, const char* file_name, frontend::ParserManager& parser_mngr, frontend::Environment& env, Visitable*& ast_root) { if (not parser_mngr.try_to_parse()) { if (fclose(input) != 0) { cerr << "ERROR" << endl; cerr << "Cannot close file stream " << file_name << endl; } std::cerr << "ERROR" << std::endl; return EXIT_FAILURE; } // Parse. ast_root = parser_mngr.get(); // Close file. if (fclose(input) != 0) { cerr << "ERROR" << endl; cerr << "Cannot close file stream " << file_name << endl; return EXIT_FAILURE; } frontend::ErrorHandler file_error_handler(file_name); // Load functions. frontend::FunctionLoader function_loader(file_error_handler, env); function_loader.check(ast_root); if (!file_error_handler.has_errors()){ // Type check (without returns). Ident pr_name(file_name); frontend::ASTChecker checker(file_error_handler, env, pr_name); checker.check(ast_root); } if (!file_error_handler.has_errors()){ // Returns checker. frontend::ReturnsChecker returns_checker(file_error_handler, env); returns_checker.check(ast_root); } // End of semantic check, typecheck and tree optimization. if (file_error_handler.has_errors()){ std::cerr << "ERROR" << std::endl; file_error_handler.flush(); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* * Compile using ast. */ void compile_file(Visitable* ast_root, const char* input_file_name, frontend::Environment& env) { // Create assembly file. std::string assembly_file_name = create_out_name(input_file_name, "s"); backend::ASCreator as_generator(input_file_name, assembly_file_name, env); as_generator.generate(ast_root); // Call assembler to create output binary file. FILE* cmd = NULL; std::string command(compiler_executable); command.append(" "); command.append(compiler_flags); command.append(" "); command.append(compiler_arch_flags); command.append(" -o"); command.append(create_out_name(input_file_name, "o")); command.append(" "); command.append(assembly_file_name); if (debug) cout << command << endl; cmd = popen(command.c_str(), "r"); pclose(cmd); } /* * Link compiled files. */ void link_files(const int number_of_inputs, char** input_files, bool is_from_stdin, const char* output_file_name) { // Call linker. FILE* cmd = NULL; std::string command(linker_executable); command.append(" "); command.append(linker_flags); command.append(" "); command.append(linker_arch_flags); command.append(" -o"); command.append(output_file_name); for(short i = 0; i < number_of_inputs; i++) { command.append(" "); if (is_from_stdin) command.append(create_out_name(stdin_in_filename, "o")); else command.append(create_out_name(input_files[i], "o")); } if (debug) cout << command << endl; cmd = popen(command.c_str(), "r"); pclose(cmd); } /* * Parse arguments, open files, check and compile all of it. */ int main(int argc, char** argv) { // Parse arguments. Arguments arguments(parse_args(argc, argv)); if (arguments.help or arguments.wrong) { show_help(argv[0]); return arguments.wrong ? EXIT_SUCCESS : EXIT_FAILURE; } short number_of_inputs = arguments.input_count == 0 ? 1 : arguments.input_count; for(short i = 0; i < number_of_inputs; i++) { if (debug) std::cout << std::endl << "-- checking file " << ((arguments.input_count > 0) ? arguments.input_files[i] : stdin_in_filename) << " --" << std::endl << std::endl; FILE* input = open_file(arguments.input_count, (arguments.input_count > 0) ? arguments.input_files[i] : NULL); frontend::ParserManager parser_mngr(input); frontend::Environment env; Visitable* ast_root; int check_status = check_file(input, (arguments.input_count > 0) ? arguments.input_files[i] : stdin_in_filename, parser_mngr, env, ast_root); if (check_status == 0) { compile_file(ast_root, (arguments.input_count > 0) ? arguments.input_files[i] : stdin_in_filename, env); } else { return EXIT_FAILURE; } } link_files(number_of_inputs, arguments.input_files, (arguments.input_count == 0), (arguments.output_file != NULL) ? arguments.output_file : default_output_filename); std::cerr << "OK" << std::endl; return EXIT_SUCCESS; }
46ddc2e01da3dc0203e84b8b26a4dff7080315ae
42116af1de0bd7bf4b6ffd61df92cd43134350da
/Handle-fw/SC182029-FISTS-V1R0/SC182029-FISTS-V1R0.ino
cc02ead2d02b9cccfaf538e1c053d7926b740e48
[ "CC-BY-4.0" ]
permissive
TaISLab/WalKit
b19e98c6d1dd09dffddfecba42393c34aa78bade
e142461568d6e14769d5ae74012704ba7e2f406e
refs/heads/master
2023-07-10T01:24:32.471347
2022-07-14T11:57:52
2022-07-14T11:57:52
239,744,056
4
0
null
null
null
null
UTF-8
C++
false
false
10,341
ino
SC182029-FISTS-V1R0.ino
/* ================================================================ Proyecto: Modulo de empuñadura en andador para UMA Placa de desarrollo: Arduino Función: Mide el peso ejercido sobre la empuñadura del andador, establece un color, una vibración y recibe/envía los datos a través del BUS CAN Autor: Justo Barroso Fontalba Fecha: 14/03/2019 ================================================================ */ /* ================================================================ Librerías ================================================================ */ #include <SPI.h> #include <HX711.h> #include <mcp_can.h> /* ================================================================ Definición de pines ================================================================ */ //ATMega328 TQFP // Pin IDE //Pin puerto, Pin Físico #define RGB_RED_GATE 10 //PB2, 14 #define RGB_GREEN_GATE 6 //PD6, 10 #define RGB_BLUE_GATE 5 //PD5, 9 #define MOTOR_GATE 9 //PB1, 13 #define HX711_DATA 17 //PC3, 26 #define HX711_SCK 16 //PC2, 25 #define MCP2515_STBY 8 //PB0, 12 #define MCP2515_CS 4 //PD4, 2 #define MCP2515_INT 3 //PD3, 1 #define ID_CHG 14 //PC0, 23 //#define MCP2515_SI 11 //PB3, 15 //#define MCP2515_SO 12 //PB4, 16 //#define MCP2515_SCK 13 //PB5, 17 //Arduino UNO //#define HX711_DATA 3 //#define HX711_SCK 4 //#define MCP2515_CS 10 //#define MCP2515_INT 2 //#define MOTOR_GATE 1 //PD4, 2 //Constantes //#define MOTOR_PWM_50 77 //#define MOTOR_PWM_75 115 //#define MOTOR_PWM_100 153 #define ID_RIGHT 0x011 //Identificador del modulo derecho #define ID_LEFT 0x021 //Identificador del modulo izquierdo /* ================================================================ Definición de funciones ================================================================ */ void setColor( uint8_t red, uint8_t green, uint8_t blue ); //Establece el color RBG del LED void setMotor( uint8_t motor ); //Establece la tensión media de funcionamiento en el Motor float readHX711(); //Lee el valor del sensor //void readHX711Serie(); //Prueba del sensor void sendHX711(); //Compone mensaje y envía /* ================================================================ Definición de estructuras ================================================================ */ typedef union { float value; uint8_t bytes[4]; } FLOATUNION_t; FLOATUNION_t weight; /* ================================================================ Definición de variables ================================================================ */ static long unsigned int rxId; //Identificador del mensaje static byte len = 0; //Longitud del mensaje static byte rxBuf[8]; //Array datos de recepción static byte txBuf[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //Array datos de envió static byte id_device = ID_LEFT; /* ================================================================ Drivers ================================================================ */ HX711 loadcell; /* ================================================================ Inicialización ================================================================ */ MCP_CAN CAN0( MCP2515_CS ); // Establece el CS en el pin 10 void setup() { /* //TIMER 1, frecuencia de interrupción 50 Hz: cli(); //Interrupciones deshabilitadas TCCR1A = 0; // Registro TCCR1A a 0 TCCR1B = 0; // Registro TCCR1B a 0 TCNT1 = 0; // Valor del contador a 0 //Configuración del registro de comparación para 50Hz OCR1A = 39999; // = 16000000 / ( 8 * 50 ) - 1 ( debe ser <65536 ) //CTC mode habilitado TCCR1B |= ( 1 << WGM12 ); //Configuración del los registros CS12, CS11 y CS10 para prescaler 8 TCCR1B |= ( 0 << CS12 ) | ( 1 << CS11 ) | ( 0 << CS10 ); //Configuración del registro para interrupción TIMSK1 |= ( 1 << OCIE1A ); sei(); //Interrupciones habilitadas */ //Configuración de pines pinMode( RGB_RED_GATE, OUTPUT ); pinMode( RGB_GREEN_GATE, OUTPUT ); pinMode( RGB_BLUE_GATE, OUTPUT ); pinMode( MOTOR_GATE, OUTPUT ); pinMode( MCP2515_INT, INPUT_PULLUP ); // Interrupción MCP2515 pinMode( MCP2515_STBY, OUTPUT ); // CS MCP2515 pinMode( ID_CHG, INPUT_PULLUP ); // Selección izquierda/derecha digitalWrite( MCP2515_STBY, LOW ); // Modo normal activo MCP2562 //Establece la posición del modulo en el andador if ( digitalRead( ID_CHG ) == 0 ) { id_device = ID_RIGHT; } //Inicialización de puerto serie, velocidad 115200 baudios Serial.begin( 115200 ); //Inicialización MCP2515, mascara y filtros activados, velocidad 500kb/s, cristal 16MHz if ( CAN0.begin( MCP_STDEXT, CAN_500KBPS, MCP_16MHZ ) == CAN_OK ) { Serial.println( "MCP2515 Initialized Successfully!" ); } else { Serial.println( "Error Initializing MCP2515..." ); } //Establece mascaras y filtros para los dispositivos CAN0.init_Mask( 0, 0, 0x001F0000 ); // Iniciando primera mascara CAN0.init_Filt( 0, 0, 0x00100000 ); // Iniciando primer filtro, ID 0x10 (rPi) CAN0.init_Mask( 1, 0, 0x001F0000 ); // Iniciando segunda mascara //Configuración del MCP2515 CAN0.setMode( MCP_NORMAL ); // Modo normal para permitir el envió de mensajes //Configuración del sensor HX711 //Variables de configuración del HX711 //const uint32_t LOADCELL_OFFSET = 50682624; //const uint32_t LOADCELL_DIVIDER = 5895655; //Inicialización de HX711 con el pin de datos como entrada, el pin de reloj como salida y el factor de ganancia (64 o 128 Canal A y 32 Canal B) loadcell.begin( HX711_DATA, HX711_SCK ); loadcell.set_scale( 2280.f ); // Este valor es obtenido de calibrar la escala con diferentes pesos //loadcell.set_offset( LOADCELL_OFFSET ); //Factor de corrección loadcell.tare(); //Establece la escala en 0 //Configurando la interrupción por pin attachInterrupt( digitalPinToInterrupt( MCP2515_INT ), readCAN, LOW ); for (int i = 0; i < 3; i++) { digitalWrite( RGB_GREEN_GATE, HIGH ); delay(200); digitalWrite( RGB_GREEN_GATE, LOW ); delay(200); } } /* ================================================================ Bucle principal ================================================================ */ void loop() { //Test de escala de color //setColor( 255, 255, 255 ); //Rojo, Verde, Azul. Establece un color //Test de velocidad de giro //setMotor( 153 ); //La tensión máxima del motor DC es 3V, entonces 255*(3V/5V) = 153, superar el valor hace que el motor trabaje por encima de su tensión máxima //Test lectura de célula de carga //readHX711Serie(); //Lee el canal analógico y envía por el puerto serie el valor pesado if ( txBuf[1] == 0b0000100 || txBuf[1] == 0b0001000) { weight.value = readHX711(); // Llamada a función para obtención del valor del peso sendHX711(); if ( txBuf[1] == 0b0000100 ) { txBuf[1] = 0b0000000; } } } /* ================================================================ Interrupciones ================================================================ */ //Rutina de interrupción del timer 1 ISR( TIMER1_COMPA_vect ) { //Esta configurada para enviar cada 20 ms, pendiente de confirmación } void readCAN() { CAN0.readMsgBuf( &rxId, &len, rxBuf ); // Leer datos: len = longitud de los datos, buf = bytes de datos if ( rxBuf[0] == id_device ) { if ( ( rxBuf[1] & 0b00000001 ) == 0b00000001 ) { setColor( rxBuf[2], rxBuf[3], rxBuf[4]); Serial.print( "LED: " ); for ( int i = 0; i < 3; i++) { Serial.print( rxBuf[i + 2] ); Serial.print( " " ); } Serial.println(); } if ( ( rxBuf[1] & 0b00000010 ) == 0b00000010 ) { setMotor( ( rxBuf[5] * 0x64 ) / 0xAE ); Serial.print( "Motor: " ); Serial.println( ( rxBuf[5] * 0x64 ) / 0xAE ); } if ( ( rxBuf[1] & 0b00001100 ) == 0b00000100 ) { txBuf[1] = 0b00000100; Serial.println( "Modo Normal" ); } if ( ( rxBuf[1] & 0b00001100 ) == 0b00001000 ) { txBuf[1] = 0b0001000; Serial.println( "Modo Continuo" ); } } } /* ================================================================ Funciones ================================================================ */ void setColor( uint8_t red, uint8_t green, uint8_t blue ) { analogWrite( RGB_RED_GATE, red ); //Pin PWM y valor entre 0 y 255 para establecer el color en escala RGB. analogWrite( RGB_GREEN_GATE, green ); analogWrite( RGB_BLUE_GATE, blue ); } void setMotor( uint8_t motor ) { analogWrite( MOTOR_GATE, motor ); //Pin PWM y valor entre 0 y 255, a través de la tensión media de salida se establece la velocidad de giro. } float readHX711() { static float loadcellValue; loadcell.power_up(); // Célula activa loadcellValue = loadcell.get_units(); loadcell.power_down(); // Célula en reposo return loadcellValue; } /* void readHX711Serie() { loadcell.power_up(); Serial.print( "one reading:\t" ); Serial.print( loadcell.get_units(), 1 ); Serial.print( "\t| average:\t" ); Serial.println( loadcell.get_units(10), 1 ); loadcell.power_down(); } */ //Construcción de la trama de envió, vuelca los valores en txBuf. void sendHX711() { // Copia un array en otro: array1 + posición de inicio, array2 + posición de inicio, tamaño de los datos a copiar memcpy( txBuf + 2, weight.bytes, sizeof( weight.bytes) ); // Envió de trama: id_device, Estructura CAN estándar, Longitud del mensaje = 8 bytes, 'txBuf' = Array de datos a enviar byte sndStat = CAN0.sendMsgBuf( id_device, 0, 8, txBuf ); if ( sndStat == CAN_OK ) { Serial.println( "Mensaje enviado!" ); } else { Serial.println( "Error al enviar el mensaje..." ); } } /* ================================================================ Fin ================================================================ */
b8f006a009dc07cc6138e751c3804abc475f4243
eef2a60bb909f9f077e6bf72af54666d10ffd686
/DX11_Base/src/win/Window.h
9ca75b068c61fa9e1f31cc7f0115580086cebccf
[ "MIT" ]
permissive
futamase/DX11_lib
94df35a7e05c8644fde6bd0fdb52ca9da362a572
b7f979565b6fb94a4eeca45aa390620e951b8595
refs/heads/master
2020-04-26T18:17:41.477333
2019-03-04T12:42:57
2019-03-04T12:42:57
173,740,539
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,635
h
Window.h
/** * @file Window.h * @brief ウィンドウを管理する */ #pragma once #include <cstdio> #include <Windows.h> #include <tchar.h> #include <string> /**@namespace Win */ namespace Win { using tstring = std::basic_string < TCHAR >; /**@brief ウィンドウを管理する */ class Window { private: HWND m_hWnd; HINSTANCE m_hInstance; tstring m_appName; UINT m_width, m_height; //! 不要になるかも public: /**@brief コンストラクタ *@param[in] AppName タイトルバーに表示する名前 *@param[in] hInstance インスタンスハンドル *@param[in] width ウィンドウの幅 *@param[in] height ウィンドウの高さ */ Window(const tstring& AppName, HINSTANCE hInstance, UINT width, UINT height); /**@brief デストラクタ*/ ~Window(); /**@brief ウィンドウハンドルを返す *@return ウィンドウハンドル */ HWND GetHWnd() const { return m_hWnd; } /**@brief ウィンドウをスクリーンの中央に移動する */ void MoveToCenter(); /**@brief ウィンドウの幅を返す *@return ウィンドウの幅 */ static float Width(); /**@brief ウィンドウの高さを返す *@return ウィンドウの高さ */ static float Height(); static void CursorEnable(bool enable); /**@brief アイコンを設定する(未実装) *@param fileName 画像ファイルへのパス */ void SetIcon(const tstring& fileName); BOOL SetTitle(const tstring& title); static Window* I() { return s_instance; } private: static Window* s_instance; }; BOOL Resize(UINT width, UINT height); }
319f59f4a3b8cb908c2c40d94f6399ff0040f415
98f87bb7324a20f0d65d825666851dd8fb83ccb1
/CF/palind.cpp
479389ee3e2d25af71603f468ca12042dabe607c
[]
no_license
perticascatalin/ProblemSolving
b1de0b8c986583ced6cf42974fc4d16d34dcb5c6
ae5ffba9475b25c1fe97c30d5e39dc0cfaa61845
refs/heads/master
2023-03-14T20:22:01.360934
2023-02-22T12:18:27
2023-02-22T12:18:27
234,737,794
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
cpp
palind.cpp
#include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <vector> #include <string> #include <list> #include <algorithm> using namespace std; #define NM 105 int pal[NM][NM]; int pos[NM]; int is_pal[NM]; int used[NM]; vector <string> words; list <int> front; list <int> back; int middle; int main() { // ifstream cin("palind.in"); int N, M; cin >> N >> M; for (int i = 0; i < N; ++i) { string str; cin >> str; words.push_back(str); } memset(pal, 0, sizeof(pal)); memset(pos, 0, sizeof(pos)); memset(is_pal, 0, sizeof(is_pal)); memset(used, 0, sizeof(used)); middle = -1; for (int i = 0; i < N; ++i) { string a = words[i].c_str(); string c = words[i].c_str(); reverse(c.begin(), c.end()); for (int j = i + 1; j < N; ++j) { string b = words[j].c_str(); if (c.compare(b) == 0) { pal[i][j] = 1; pal[j][i] = 1; pos[i] = j; pos[j] = i; } } if (c.compare(a) == 0) is_pal[i] = 1; } for (int i = 0; i < N; ++i) { if (used[i]) continue; if (pos[i]) { front.push_back(i); back.push_front(pos[i]); used[i] = 1; used[pos[i]] = 1; } if (is_pal[i] && !used[i]) { middle = i; used[i] = 1; } } int l = 2 * front.size() * M; if (middle != -1) l += M; cout << l << endl; string final_str = ""; for (list<int>::iterator it = front.begin(); it != front.end(); ++it) { final_str += words[*it]; } if (middle != -1) final_str += words[middle]; for (list<int>::iterator it = back.begin(); it != back.end(); ++it) { final_str += words[*it]; } cout << final_str << endl; // for (int i = 0; i < N; ++i) cout << words[i] << endl; // for (int i = 0; i < N; ++i) // { // for (int j = 0; j < N; ++j) cout << pal[i][j] << " "; // cout << endl; // } // cout << endl; // for (int i = 0; i < N; ++i) cout << is_pal[i] << " "; cout << endl; return 0; }
8c2f7bfb721518b38db29de902faec04c222caa5
1b3d343ce1e8dfbacc3c698294798d0abd52c9a2
/Deploy/Instance/EEuclideo.50.50.2.tpp
d88ba066a415318146a528f36a385f718be56c85
[]
no_license
lyandut/MyTravelingPurchaser
3ecdf849bd19473e92742ed4c6d8d99078351fd0
dca14f3d31e185c1a6f7bbd4a2e7a5cb3b0bd08c
refs/heads/master
2020-05-02T06:10:47.227729
2019-04-19T07:50:53
2019-04-19T07:50:53
177,788,811
0
1
null
2019-04-19T07:50:54
2019-03-26T12:56:50
C++
UTF-8
C++
false
false
9,071
tpp
EEuclideo.50.50.2.tpp
NAME : TYPE : TPP COMMENT : DIMENSION : 50 EDGE_WEIGHT_TYPE : EUC_2D DISPLAY_DATA_TYPE : COORD_DISPLAY NODE_COORD_SECTION : 1 320 383 2 883 49 3 82 344 4 795 534 5 375 735 6 612 441 7 28 711 8 872 270 9 294 162 10 585 95 11 156 485 12 261 252 13 902 471 14 832 249 15 99 368 16 73 419 17 751 956 18 468 834 19 276 240 20 344 651 21 975 957 22 69 644 23 941 250 24 938 80 25 836 9 26 236 297 27 270 488 28 175 742 29 296 424 30 841 665 31 497 236 32 392 429 33 704 202 34 706 944 35 547 333 36 896 480 37 402 876 38 100 320 39 102 14 40 400 938 41 23 636 42 212 293 43 101 387 44 11 397 45 812 852 46 38 285 47 64 431 48 715 769 49 633 397 50 689 156 DEMAND_SECTION : 50 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 1 12 1 13 1 14 1 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1 36 1 37 1 38 1 39 1 40 1 41 1 42 1 43 1 44 1 45 1 46 1 47 1 48 1 49 1 50 1 OFFER_SECTION : 1 0 2 21 49 7 1 47 8 1 46 7 1 43 4 1 41 8 1 37 1 1 34 5 1 33 9 1 30 9 1 28 6 1 25 10 1 23 7 1 22 5 1 18 3 1 16 6 1 14 1 1 12 4 1 10 9 1 7 10 1 5 3 1 3 5 1 3 25 50 6 1 49 10 1 47 10 1 45 5 1 43 5 1 41 6 1 40 5 1 36 2 1 33 1 1 31 3 1 30 5 1 28 7 1 26 2 1 24 9 1 22 8 1 16 9 1 14 7 1 13 1 1 11 10 1 8 1 1 7 5 1 6 5 1 5 8 1 4 4 1 3 5 1 4 21 49 10 1 47 2 1 44 7 1 43 5 1 41 6 1 38 7 1 37 7 1 34 1 1 31 2 1 28 10 1 26 8 1 23 4 1 21 6 1 16 3 1 15 10 1 13 2 1 10 5 1 7 1 1 5 5 1 4 8 1 3 5 1 5 29 50 5 1 49 10 1 47 3 1 46 3 1 45 6 1 44 8 1 43 5 1 41 1 1 40 2 1 39 2 1 37 9 1 33 9 1 31 6 1 30 10 1 28 3 1 26 10 1 25 8 1 22 1 1 18 9 1 16 6 1 14 1 1 13 10 1 12 4 1 10 8 1 8 4 1 7 9 1 5 9 1 4 2 1 3 3 1 6 27 49 7 1 47 2 1 44 5 1 43 6 1 41 5 1 38 5 1 37 3 1 36 3 1 34 7 1 33 4 1 31 2 1 30 9 1 28 6 1 26 6 1 24 8 1 23 6 1 21 5 1 16 9 1 13 10 1 11 8 1 10 1 1 7 5 1 6 10 1 5 10 1 4 2 1 3 1 1 2 10 1 7 20 49 2 1 47 5 1 43 4 1 41 9 1 37 4 1 34 4 1 31 9 1 30 5 1 29 5 1 28 6 1 25 6 1 23 9 1 18 8 1 16 2 1 15 4 1 12 8 1 10 3 1 7 8 1 5 2 1 3 1 1 8 23 50 1 1 49 9 1 47 5 1 45 3 1 43 3 1 42 5 1 41 3 1 40 2 1 37 6 1 36 7 1 33 5 1 30 6 1 28 6 1 24 8 1 22 6 1 16 10 1 14 3 1 11 2 1 8 9 1 7 8 1 6 10 1 5 2 1 2 1 1 9 25 49 7 1 48 1 1 47 6 1 44 6 1 43 5 1 41 6 1 38 3 1 37 3 1 34 6 1 31 7 1 30 4 1 28 2 1 26 7 1 23 9 1 22 6 1 21 7 1 15 3 1 13 1 1 11 6 1 10 8 1 7 1 1 6 7 1 5 3 1 4 3 1 3 10 1 10 28 50 3 1 49 9 1 47 10 1 45 7 1 43 5 1 41 7 1 40 2 1 37 7 1 34 5 1 32 1 1 31 2 1 30 1 1 29 7 1 28 2 1 26 6 1 25 9 1 23 7 1 22 3 1 18 8 1 16 5 1 14 6 1 12 8 1 10 3 1 8 6 1 7 10 1 5 1 1 4 9 1 3 1 1 11 27 49 1 1 48 6 1 47 2 1 44 3 1 43 8 1 42 1 1 41 8 1 38 1 1 36 4 1 33 1 1 31 9 1 30 4 1 28 8 1 26 9 1 24 1 1 22 3 1 21 1 1 16 9 1 14 4 1 13 5 1 11 5 1 7 7 1 6 4 1 5 2 1 4 3 1 3 1 1 2 4 1 12 19 48 3 1 47 7 1 43 7 1 41 1 1 37 9 1 34 6 1 31 9 1 30 9 1 28 4 1 25 2 1 23 1 1 18 9 1 15 4 1 12 2 1 10 8 1 7 5 1 6 10 1 5 8 1 3 4 1 13 28 50 2 1 49 5 1 47 8 1 45 8 1 43 7 1 41 9 1 40 4 1 37 9 1 36 6 1 34 10 1 32 9 1 31 4 1 30 4 1 29 2 1 28 9 1 24 2 1 23 9 1 22 6 1 16 4 1 13 6 1 11 2 1 10 7 1 8 10 1 7 5 1 6 2 1 5 6 1 4 9 1 2 10 1 14 17 49 8 1 46 10 1 44 10 1 41 6 1 38 5 1 33 6 1 31 3 1 28 10 1 26 4 1 23 5 1 21 9 1 15 3 1 13 1 1 10 3 1 7 5 1 5 6 1 4 7 1 15 24 50 8 1 48 3 1 45 1 1 43 1 1 40 8 1 37 4 1 36 4 1 32 7 1 31 3 1 30 6 1 28 8 1 25 7 1 24 8 1 22 7 1 18 7 1 16 8 1 13 7 1 12 1 1 11 2 1 8 1 1 7 9 1 6 3 1 4 8 1 3 3 1 16 26 49 3 1 47 2 1 44 4 1 43 8 1 41 4 1 38 6 1 37 6 1 36 1 1 34 6 1 31 3 1 30 7 1 29 10 1 26 3 1 24 2 1 23 1 1 21 4 1 16 7 1 13 8 1 11 9 1 10 4 1 7 10 1 6 2 1 5 9 1 4 7 1 2 1 1 1 4 1 17 26 49 6 1 48 5 1 46 9 1 45 2 1 43 4 1 41 10 1 37 4 1 33 4 1 31 7 1 30 3 1 28 4 1 25 1 1 23 2 1 22 4 1 18 7 1 15 8 1 14 9 1 13 4 1 12 4 1 10 3 1 9 5 1 7 7 1 6 5 1 5 3 1 4 3 1 3 3 1 18 27 50 10 1 49 9 1 48 1 1 47 8 1 45 5 1 43 2 1 41 5 1 40 3 1 37 1 1 36 5 1 32 7 1 31 10 1 30 2 1 28 5 1 26 9 1 24 8 1 22 7 1 16 8 1 13 8 1 11 4 1 8 9 1 7 5 1 6 5 1 5 3 1 4 10 1 3 5 1 2 8 1 19 25 49 7 1 47 10 1 46 4 1 44 5 1 41 3 1 38 5 1 34 9 1 33 9 1 31 2 1 30 10 1 29 4 1 28 4 1 26 6 1 24 5 1 23 8 1 21 5 1 16 3 1 15 8 1 13 4 1 11 1 1 10 2 1 7 1 1 5 5 1 4 3 1 2 9 1 20 22 50 10 1 48 10 1 45 7 1 43 4 1 41 5 1 40 8 1 37 8 1 31 1 1 30 7 1 28 8 1 25 7 1 22 1 1 18 4 1 16 5 1 13 8 1 12 10 1 10 2 1 8 3 1 6 6 1 5 7 1 4 4 1 3 1 1 21 29 49 6 1 48 6 1 47 8 1 45 4 1 44 6 1 43 5 1 41 7 1 38 1 1 37 3 1 35 1 1 33 9 1 31 3 1 30 10 1 28 9 1 26 1 1 24 5 1 22 4 1 21 6 1 16 2 1 14 7 1 13 3 1 11 4 1 9 10 1 7 7 1 6 1 1 5 6 1 4 10 1 3 1 1 2 7 1 22 22 49 3 1 48 3 1 46 10 1 43 9 1 41 4 1 37 5 1 33 7 1 31 4 1 30 4 1 28 4 1 25 10 1 23 9 1 22 4 1 18 5 1 16 7 1 15 1 1 12 5 1 10 10 1 7 7 1 6 6 1 5 8 1 3 9 1 23 23 50 5 1 47 4 1 45 6 1 43 7 1 41 9 1 40 9 1 37 5 1 35 8 1 31 5 1 29 1 1 28 2 1 24 8 1 23 1 1 22 1 1 16 7 1 13 3 1 11 5 1 10 7 1 8 9 1 5 9 1 4 5 1 3 7 1 2 6 1 24 26 49 8 1 48 9 1 47 1 1 46 6 1 43 8 1 41 10 1 37 3 1 33 2 1 31 8 1 30 6 1 28 5 1 26 3 1 24 3 1 23 8 1 21 2 1 16 5 1 15 3 1 13 1 1 12 5 1 11 7 1 10 2 1 7 4 1 6 8 1 5 6 1 4 6 1 3 9 1 25 21 50 9 1 48 5 1 45 4 1 43 4 1 41 1 1 40 3 1 37 9 1 31 6 1 30 6 1 28 7 1 25 10 1 22 6 1 17 4 1 13 7 1 11 10 1 8 7 1 7 3 1 6 5 1 5 9 1 4 2 1 3 2 1 26 19 49 2 1 47 10 1 43 10 1 41 5 1 37 5 1 35 9 1 31 7 1 29 7 1 28 1 1 26 1 1 24 1 1 21 10 1 16 2 1 13 1 1 11 2 1 7 7 1 5 9 1 4 5 1 2 6 1 27 23 49 2 1 48 1 1 46 7 1 43 3 1 41 10 1 37 2 1 33 5 1 31 7 1 30 4 1 28 9 1 25 3 1 24 10 1 23 9 1 17 6 1 16 10 1 15 6 1 12 8 1 11 9 1 10 3 1 7 10 1 6 1 1 5 5 1 3 6 1 28 21 50 5 1 47 2 1 45 6 1 43 6 1 41 1 1 40 10 1 35 4 1 31 4 1 30 1 1 29 9 1 28 2 1 24 5 1 22 7 1 16 1 1 13 5 1 10 3 1 7 2 1 6 2 1 5 4 1 4 1 1 2 10 1 29 26 49 3 1 47 2 1 46 8 1 44 8 1 43 2 1 41 9 1 39 6 1 37 1 1 34 1 1 33 7 1 31 9 1 28 7 1 26 9 1 25 8 1 23 7 1 22 1 1 21 4 1 18 4 1 14 7 1 13 8 1 12 9 1 10 10 1 7 2 1 5 10 1 4 1 1 3 1 1 30 22 50 5 1 48 1 1 45 2 1 43 2 1 41 3 1 40 3 1 37 8 1 31 1 1 30 8 1 27 5 1 25 3 1 24 1 1 22 7 1 17 4 1 16 10 1 13 7 1 11 6 1 7 7 1 6 9 1 5 3 1 4 4 1 3 5 1 31 18 49 8 1 47 5 1 43 7 1 41 6 1 37 10 1 35 5 1 31 10 1 29 5 1 26 9 1 24 1 1 21 5 1 16 3 1 13 5 1 10 9 1 7 1 1 5 8 1 4 2 1 2 3 1 32 24 49 10 1 48 4 1 46 8 1 43 10 1 41 10 1 37 7 1 33 5 1 31 3 1 30 4 1 28 8 1 26 6 1 25 7 1 24 7 1 23 3 1 19 8 1 16 6 1 14 6 1 12 2 1 11 8 1 10 5 1 7 3 1 6 7 1 5 3 1 3 9 1 33 21 50 10 1 47 10 1 45 5 1 41 3 1 40 6 1 35 4 1 31 1 1 30 4 1 29 3 1 27 3 1 24 1 1 23 9 1 22 4 1 16 10 1 13 1 1 11 10 1 10 9 1 7 3 1 5 8 1 4 6 1 2 7 1 34 18 49 3 1 46 1 1 43 2 1 41 6 1 37 2 1 33 5 1 31 8 1 28 9 1 26 1 1 23 3 1 20 5 1 14 7 1 13 1 1 10 5 1 7 2 1 5 3 1 4 2 1 3 6 1 35 24 50 8 1 49 4 1 48 8 1 45 2 1 43 1 1 41 5 1 39 6 1 37 6 1 31 7 1 30 1 1 27 1 1 25 3 1 24 5 1 22 2 1 19 9 1 16 2 1 13 6 1 12 4 1 11 2 1 7 6 1 6 5 1 5 7 1 4 9 1 3 9 1 36 18 49 2 1 47 8 1 43 2 1 41 4 1 37 8 1 35 1 1 31 7 1 29 8 1 26 3 1 23 6 1 20 7 1 16 6 1 12 4 1 10 1 1 7 10 1 5 3 1 4 10 1 2 9 1 37 20 48 1 1 47 9 1 46 1 1 43 7 1 41 8 1 37 3 1 33 1 1 30 6 1 28 3 1 24 8 1 23 1 1 16 6 1 14 1 1 13 5 1 11 6 1 10 7 1 6 3 1 5 3 1 4 8 1 3 7 1 38 25 50 7 1 49 10 1 47 6 1 45 10 1 43 6 1 41 3 1 39 7 1 37 8 1 35 6 1 31 8 1 29 9 1 27 9 1 25 9 1 23 1 1 22 9 1 19 10 1 16 8 1 13 7 1 12 5 1 10 10 1 7 1 1 5 3 1 4 2 1 3 8 1 2 8 1 39 18 49 3 1 46 5 1 43 8 1 41 1 1 37 4 1 33 7 1 31 9 1 28 8 1 26 8 1 23 3 1 22 8 1 20 8 1 14 10 1 12 9 1 10 9 1 7 5 1 5 6 1 4 2 1 40 27 50 7 1 49 9 1 48 1 1 45 2 1 44 9 1 43 4 1 41 1 1 39 3 1 38 3 1 37 3 1 31 9 1 30 1 1 27 6 1 26 7 1 24 6 1 23 3 1 22 3 1 21 6 1 16 4 1 13 1 1 11 8 1 10 5 1 7 8 1 6 2 1 5 7 1 4 8 1 3 9 1 41 28 50 9 1 49 4 1 47 8 1 45 9 1 43 3 1 41 3 1 37 4 1 35 6 1 33 6 1 31 1 1 29 7 1 28 3 1 26 5 1 25 7 1 23 8 1 22 6 1 20 8 1 19 7 1 16 3 1 14 5 1 12 9 1 10 2 1 9 5 1 7 8 1 5 6 1 4 1 1 3 5 1 2 10 1 42 17 48 8 1 46 1 1 43 3 1 41 7 1 37 3 1 33 7 1 30 7 1 28 8 1 24 1 1 23 2 1 16 9 1 14 3 1 11 5 1 10 5 1 6 5 1 5 8 1 3 10 1 43 25 50 2 1 49 6 1 47 4 1 45 6 1 44 4 1 43 7 1 41 10 1 39 10 1 38 6 1 37 9 1 35 3 1 31 9 1 29 4 1 27 9 1 26 1 1 23 7 1 22 8 1 21 8 1 16 1 1 13 4 1 10 2 1 7 8 1 5 4 1 4 3 1 2 5 1 44 19 49 5 1 46 1 1 43 8 1 41 7 1 37 2 1 33 2 1 31 10 1 28 7 1 26 5 1 22 10 1 20 1 1 19 10 1 16 9 1 14 2 1 12 1 1 10 2 1 7 5 1 5 10 1 3 6 1 45 20 49 6 1 48 3 1 44 9 1 43 4 1 39 8 1 37 7 1 31 1 1 30 1 1 28 8 1 27 4 1 24 2 1 22 9 1 16 7 1 13 10 1 11 7 1 7 5 1 6 6 1 5 10 1 4 3 1 3 10 1 46 30 50 6 1 49 3 1 47 6 1 45 4 1 44 8 1 43 3 1 41 4 1 40 7 1 39 1 1 37 10 1 35 2 1 33 6 1 31 8 1 29 1 1 28 8 1 26 5 1 23 5 1 22 10 1 19 4 1 16 7 1 14 5 1 13 5 1 12 3 1 10 9 1 8 5 1 7 1 1 5 5 1 4 5 1 3 4 1 2 8 1 47 18 48 10 1 46 1 1 43 1 1 41 10 1 37 2 1 33 4 1 30 1 1 28 7 1 24 4 1 22 1 1 16 2 1 14 3 1 11 10 1 10 3 1 7 4 1 6 10 1 5 3 1 3 5 1 48 18 49 6 1 47 8 1 44 10 1 41 8 1 39 8 1 34 4 1 31 3 1 29 1 1 27 1 1 23 1 1 22 5 1 16 3 1 13 7 1 10 8 1 7 1 1 5 2 1 4 9 1 2 7 1 49 25 49 3 1 48 1 1 46 7 1 44 2 1 43 8 1 41 8 1 39 1 1 37 10 1 33 1 1 31 2 1 30 2 1 28 5 1 26 8 1 22 5 1 19 3 1 14 3 1 13 7 1 12 2 1 11 2 1 10 3 1 7 4 1 6 2 1 5 6 1 4 5 1 3 10 1 50 19 49 4 1 48 7 1 44 3 1 43 1 1 39 4 1 37 3 1 31 9 1 30 5 1 27 9 1 24 10 1 22 7 1 16 9 1 13 7 1 11 4 1 7 7 1 6 1 1 5 1 1 4 10 1 3 1 1 EOF
6735ad5a1d9d256af3457a19b2bff718b06a3631
3fa764606c1c2deb24623cf3448d338b8338c47d
/mycontactlistener.cpp
b162b571285507b92284cec1e125c99faa66980d
[]
no_license
IvelinChalov/Bob-s-world
de6a6fd0714750a073e010903070a899c6acaa44
db5b4fab2f85dda61c2d8b2b11d410b70aae43dc
refs/heads/master
2021-01-10T16:26:53.208169
2016-02-17T18:56:37
2016-02-17T18:56:37
51,916,453
0
0
null
null
null
null
UTF-8
C++
false
false
22,503
cpp
mycontactlistener.cpp
#include "mycontactlistener.h" #include <string> #include <cmath> #include "Entity.h" #include <iostream> #include <QDebug> // if(!have_joint) { // b2RopeJointDef rope_joint_def; // rope_joint_def.collideConnected = true; // rope_joint_def.bodyA = contact->GetFixtureA()->GetBody(); // rope_joint_def.bodyB = contact->GetFixtureB()->GetBody(); // rope_joint_def.maxLength = 2; // world->CreateJoint(&rope_joint_def); // have_joint = true; // }else{ // b2JointEdge* edge_joint = real_world.physics_body[*entityA].body->GetJointList(); // b2RopeJoint* rj = (b2RopeJoint*)edge_joint->joint; // world->DestroyJoint(rj); // have_joint = false; // } using namespace std; b2Vec2 direction(0, -1); int circle_id = 0; bool inside = false; bool teleportA_flag = false; bool teleportB_flag = false; void MyContactListener::BeginContact(b2Contact* contact) { void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData(); int* entityA = static_cast<int*>(bodyUserDataA); std::string entityA_name = real_world.name_vec[*entityA].name; void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData(); int* entityB = static_cast<int*>(bodyUserDataB); std::string entityB_name = real_world.name_vec[*entityB].name; //Moving platform if ((entityA_name == "moving_platform") && (entityB_name != "goal" && entityB_name != "wrecking_ball" && entityB_name != "circle" && entityB_name != "elavator_motor" && entityB_name != "domino")) { change_moving_platform_direction(*entityA); }else if((entityB_name == "moving_platform") && (entityA_name != "goal" && entityA_name != "wrecking_ball" && entityA_name != "circle" && entityA_name != "elavator_motor" && entityA_name != "domino")) { change_moving_platform_direction(*entityB); } //For Elevator------------------------------------------------ b2Vec2 zero(0, 0); if(entityA_name == "elavator_platform" && entityB_name == "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityA].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; //zero = real_world.physics_body_vec[*entityA].body->GetLinearVelocity(); //real_world.physics_body_vec[*entityB].body->SetLinearVelocity(zero); pj->EnableMotor(true); pj->SetMotorSpeed(0.3); pj->SetMaxMotorForce(500); real_world.sticky_id[*entityB].on_platform = true; real_world.sticky_id[*entityB].platform_id = *entityA; if(pj->GetJointTranslation() <= pj->GetLowerLimit() || pj->GetJointTranslation() >= pj->GetUpperLimit()) { real_world.sticky_id[*entityB].on_platform = false; // real_world.physics_body_vec[*entityB].body->SetLinearVelocity(b2Vec2(-(real_world.physics_body_vec[*entityA].body->GetLinearVelocity().x * 0.99), -real_world.physics_body_vec[*entityA].body->GetLinearVelocity().y )); // real_world.physics_body_vec[*entityB].body->SetAngularVelocity(0); } }else if(entityB_name == "elavator_platform" && entityA_name == "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityB].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; //zero = real_world.physics_body_vec[*entityB].body->GetLinearVelocity(); //real_world.physics_body_vec[*entityA].body->SetLinearVelocity(zero); pj->EnableMotor(true); pj->SetMotorSpeed(0.3); pj->SetMaxMotorForce(500); real_world.sticky_id[*entityA].on_platform = true; real_world.sticky_id[*entityA].platform_id = *entityB; // cout<<"min = "<<pj->GetLowerLimit() * MTOP<<" current = "<<pj->GetJointTranslation() * MTOP<<endl; // cout<<"max = "<<pj->GetUpperLimit() * MTOP<<" current = "<<pj->GetJointTranslation() * MTOP<<endl; // if(pj->GetJointTranslation() <= pj->GetLowerLimit() || pj->GetJointTranslation() >= pj->GetUpperLimit()) { // cout<<"COLLISION !!\n"; // // pj->EnableMotor(true); // //pj->SetMotorSpeed (pj->GetMotorSpeed() * -1); // real_world.physics_body_vec[*entityA].body->SetLinearVelocity(b2Vec2(-(real_world.physics_body_vec[*entityA].body->GetLinearVelocity().x * 0.99), -real_world.physics_body_vec[*entityA].body->GetLinearVelocity().y )); // real_world.physics_body_vec[*entityA].body->SetAngularVelocity(0); // } }else{ if(entityA_name == "elavator_platform" && entityA_name != "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityA].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->EnableMotor(false); } if(entityB_name == "elavator_platform" && entityA_name != "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityB].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->EnableMotor(false); } } //For spring---------------------------------- if(entityA_name == "spring_platform" && (entityB_name == "goal" || entityB_name == "wrecking_ball" || entityB_name == "domino" || entityB_name == "circle")) { activate_spring_motor(*entityA); }else if(entityB_name == "spring_platform" && (entityA_name == "goal" || entityA_name == "wrecking_ball" || entityA_name == "domino" || entityA_name == "circle")) { activate_spring_motor(*entityB); }else if(entityA_name == "spring_platform" && entityA_name != "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityA].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->EnableMotor(false); } //For teleport ------------------------------------------------ if(entityA_name == "teleportA" && (entityB_name == "circle" || entityB_name == "domino" )) { teleport_objectA(*entityA, *entityB, 0, contact); }else if(entityB_name == "teleportA" && (entityA_name == "circle" || entityA_name == "domino" )) { teleport_objectA(*entityB, *entityA, 1, contact); } if(entityA_name == "teleportB" && (entityB_name == "circle" || entityB_name == "domino" )) { teleport_objectB(*entityA, *entityB, 0, contact); }else if(entityB_name == "teleportB" && (entityA_name == "circle" || entityA_name == "domino" )) { teleport_objectB(*entityB, *entityA, 1, contact); } //For fan------------------------------------------------- if(entityA_name == "fan") { cout<<"inside A\n"; real_world.ent_flag_vec[*entityB].is_inside = true; real_world.ent_flag_vec[*entityB].fan_id = *entityA; //cout<<"mass = "<<contact->GetFixtureA()->GetBody()->GetMass(); }else if(entityB_name == "fan") { cout<<"inside B\n"; real_world.ent_flag_vec[*entityA].is_inside = true; real_world.ent_flag_vec[*entityA].fan_id = *entityB; // cout<<"mass = "<<contact->GetFixtureB()->GetBody()->GetMass(); } if(entityA_name == "fan_button") { cout<<"button A\n"; real_world.fan_vec[*entityA].is_on = !real_world.fan_vec[*entityA].is_on; if(real_world.fan_vec[*entityA].is_on) { real_world.color_vec[*entityA].selected_color = 1; real_world.textures_vec[*entityA].selected_texture = 3; int id = real_world.fan_vec[*entityA].fan_id; real_world.mask[id] = real_world.mask[id] + RENDER_MASK; real_world.textures_vec[id].selected_texture = 0; }else { real_world.color_vec[*entityA].selected_color = 0; real_world.textures_vec[*entityA].selected_texture = 0; int id = real_world.fan_vec[*entityA].fan_id; real_world.mask[id] = real_world.mask[id] - RENDER_MASK; real_world.textures_vec[id].selected_texture = 0; } cout<<"on = "<<real_world.fan_vec[*entityA].is_on<<endl; }else if(entityB_name == "fan_button") { cout<<"button B\n"; real_world.fan_vec[*entityB].is_on = !real_world.fan_vec[*entityB].is_on; if(real_world.fan_vec[*entityB].is_on) { real_world.color_vec[*entityB].selected_color = 1; real_world.textures_vec[*entityB].selected_texture = 3; int id = real_world.fan_vec[*entityB].fan_id; real_world.mask[id] = real_world.mask[id] + RENDER_MASK; real_world.textures_vec[id].selected_texture = 0; }else { real_world.color_vec[*entityB].selected_color = 0; real_world.textures_vec[*entityB].selected_texture = 0; int id = real_world.fan_vec[*entityB].fan_id; real_world.mask[id] = real_world.mask[id] - RENDER_MASK; real_world.textures_vec[id].selected_texture = 0; } cout<<"on = "<<real_world.fan_vec[*entityB].is_on<<endl; } //balloon------------------------- if(entityA_name == "balloon") { float balloon_mass = contact->GetFixtureA()->GetBody()->GetMass(); float gravity = contact->GetFixtureA()->GetBody()->GetGravityScale() * world->GetGravity().y; float force = balloon_mass * gravity; cout<<"balloon force = "<<force<<endl; }else if(entityB_name == "balloon") { float balloon_mass = contact->GetFixtureA()->GetBody()->GetMass(); float gravity = contact->GetFixtureA()->GetBody()->GetGravityScale() * world->GetGravity().y; float force = balloon_mass * gravity; cout<<"balloon force = "<<force<<endl; } if(entityA_name == "balloon_platform") { b2Vec2 vel = contact->GetFixtureB()->GetBody()->GetLinearVelocity(); vel *= 0; real_world.physics_body_vec[*entityB].body->SetLinearVelocity(vel); real_world.physics_body_vec[*entityB].body->SetAngularVelocity(0); // float balloon_mass = contact->GetFixtureA()->GetBody()->GetMass(); // float gravity = contact->GetFixtureA()->GetBody()->GetGravityScale() * world->GetGravity().y; // float force = balloon_mass * gravity; cout<<"Contact A "<<endl; }else if(entityB_name == "balloon") { b2Vec2 vel = contact->GetFixtureA()->GetBody()->GetLinearVelocity(); vel *= 0; real_world.physics_body_vec[*entityA].body->SetLinearVelocity(vel); real_world.physics_body_vec[*entityA].body->SetAngularVelocity(0); cout<<"Contact B "<<endl; // float balloon_mass = contact->GetFixtureA()->GetBody()->GetMass(); // float gravity = contact->GetFixtureA()->GetBody()->GetGravityScale() * world->GetGravity().y; // float force = balloon_mass * gravity; // cout<<"balloon_platform force = "<<force<<endl; } //FOR MOVING DOWN ON A COLLISION WITH MOTOR // if(entityA_name == "elavator_platform" && entityB_name == "motor") { // b2JointEdge* j = real_world.physics_body[*entityA].body->GetJointList(); // b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; // pj->SetMotorSpeed (-0.5); // }else if(entityB_name == "elavator_platform" && entityA_name == "motor") { // b2JointEdge* j = real_world.physics_body[*entityB].body->GetJointList(); // b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; // pj->SetMotorSpeed (-0.5); // } // if (entityB_name == "elevator" && entityA_name == "circle") { // contact->GetFixtureB()->GetBody()->SetLinearVelocity(direction); // circle_id = *entityA; // }else if(entityA_name == "elevator" && entityB_name == "circle") { // contact->GetFixtureA()->GetBody()->SetLinearVelocity(direction); // circle_id = *entityB; // } // if (entityB_name == "elevator" && entityA_name != "circle") { // b2Vec2 vel(0, 0); // direction.x = contact->GetFixtureB()->GetBody()->GetLinearVelocity().x * mul; // direction.y = contact->GetFixtureB()->GetBody()->GetLinearVelocity().y * mul; // b2Vec2 a(10 * PTOM, 0); // real_world.physics_body[circle_id].body->ApplyLinearImpulse(a, real_world.physics_body[circle_id].body->GetPosition(), true); // contact->GetFixtureB()->GetBody()->SetLinearVelocity(vel); // contact->GetFixtureB()->GetBody()->SetAngularVelocity(0); // }else if(entityA_name == "elevator" && entityB_name != "circle") { // direction.x = contact->GetFixtureA()->GetBody()->GetLinearVelocity().x * mul; // direction.y = contact->GetFixtureA()->GetBody()->GetLinearVelocity().y * mul; // b2Vec2 vel(0, 0); // b2Vec2 a(10 * PTOM, 0); // real_world.physics_body[circle_id].body->ApplyLinearImpulse(a, real_world.physics_body[circle_id].body->GetPosition(), true); // contact->GetFixtureA()->GetBody()->SetLinearVelocity(vel); // contact->GetFixtureA()->GetBody()->SetAngularVelocity(0); // } // cout<<"direction = "<<direction.y<<endl; } void MyContactListener::EndContact(b2Contact* contact) { void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData(); int* entityA = static_cast<int*>(bodyUserDataA); std::string entityA_name = real_world.name_vec[*entityA].name; void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData(); int* entityB = static_cast<int*>(bodyUserDataB); std::string entityB_name = real_world.name_vec[*entityB].name; if(entityA_name == "elavator_platform" && entityA_name != "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityA].body->GetJointList(); if(j) { b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->EnableMotor(true); } } if(entityB_name == "elavator_platform" && entityA_name != "circle") { b2JointEdge* j = real_world.physics_body_vec[*entityB].body->GetJointList(); if(j) { b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->EnableMotor(true); } } //For fan--------------------------------------------- if(entityA_name == "fan") { cout<<"inside A\n"; real_world.ent_flag_vec[*entityB].is_inside = false; }else if(entityB_name == "fan") { cout<<"inside B\n"; real_world.ent_flag_vec[*entityA].is_inside = false; } // if(entityA_name == "fan" && entityB_name == "circle") { // cout<<"inside A\n"; // real_world.ent_flag_vec[*entityB].is_inside = false; // }else if(entityA_name == "circle" && entityB_name == "fan") { // cout<<"inside B\n"; // real_world.ent_flag_vec[*entityA].is_inside = false; // } // if (entityA_name == "circle" && entityB_name == "moving_platform") { // real_world.for_delete_vec[*entityB].for_delete = false; // } else if(entityA_name == "moving_platform" && entityB_name == "circle") { // real_world.for_delete_vec[*entityA].for_delete = false; // } // void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData(); // int* entityA = static_cast<int*>(bodyUserDataA); // std::string entityA_name = real_world.name[*entityA].name; // void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData(); // int* entityB = static_cast<int*>(bodyUserDataB); // std::string entityB_name = real_world.name[*entityB].name; // if ( entityA_name == "circle" && entityB_name == "obstacle") { // real_world.color_vec[*entityA].red = 1.0f; // real_world.color_vec[*entityA].green = 1.0f; // real_world.color_vec[*entityA].blue = 1.0f; // }else if(entityA_name == "obstacle" && entityB_name == "circle") { // real_world.color_vec[*entityB].red = 1.0f; // real_world.color_vec[*entityB].green = 1.0f; // real_world.color_vec[*entityB].blue = 1.0f; // } // if (entityA_name == "circle" && entityB_name == "slippery_obstacle") { // contact->GetFixtureA()->SetFriction(0.1f); // contact->GetFixtureB()->SetFriction(0.1f); // } else if(entityA_name == "slippery_obstacle" && entityB_name == "circle") { // contact->GetFixtureA()->SetFriction(0.1f); // contact->GetFixtureB()->SetFriction(0.1f); // } } void MyContactListener::PreSolve (b2Contact *contact, const b2Manifold *oldManifold) { void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData(); int* entityA = static_cast<int*>(bodyUserDataA); std::string entityA_name = real_world.name_vec[*entityA].name; void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData(); int* entityB = static_cast<int*>(bodyUserDataB); std::string entityB_name = real_world.name_vec[*entityB].name; b2Vec2 zero(0, 0); // if(entityA_name == "elavator_platform" && entityB_name == "circle") { // real_world.physics_body_vec[*entityB].body->SetLinearVelocity(zero); // real_world.physics_body_vec[*entityB].body->SetAngularVelocity(0); // }else if(entityB_name == "elavator_platform" && entityA_name == "circle") { // real_world.physics_body_vec[*entityA].body->SetLinearVelocity(zero); // real_world.physics_body_vec[*entityB].body->SetAngularVelocity(0); // } // if (entityA_name == "elevator") { // b2Vec2 vel = contact->GetFixtureA()->GetBody()->GetLinearVelocity(); // float ang_vel = contact->GetFixtureA()->GetBody()->GetAngularVelocity(); // cout<<"velX = "<<vel.x<<"velY = "<<vel.y<<endl; // cout<<"ang vel = "<<ang_vel<<endl; // vel.x = vel.x * -1; // vel.y = vel.y * -1; // contact->GetFixtureA()->GetBody()->SetLinearVelocity(zero); // contact->GetFixtureA()->GetBody()->SetAngularVelocity(0); // } // if (entityB_name == "elevator") { // b2Vec2 vel = contact->GetFixtureB()->GetBody()->GetLinearVelocity(); // float ang_vel = contact->GetFixtureB()->GetBody()->GetAngularVelocity(); // vel.x = vel.x * -1; // vel.y = vel.y * -1; // contact->GetFixtureB()->GetBody()->SetLinearVelocity(zero); // contact->GetFixtureB()->GetBody()->SetAngularVelocity(0); // cout<<"velX = "<<vel.x<<"velY = "<<vel.y<<endl; // cout<<"ang vel = "<<ang_vel<<endl; // } // b2Vec2 normal = contact->GetManifold()->localNormal; // cout<<"normalX = "<<normal.x<<"normalY = "<<normal.y<<endl; // cout<<"impulses1 = "<<oldManifold->points[1].normalImpulse = 0.f; } void MyContactListener::PostSolve (b2Contact *contact, const b2ContactImpulse *impulse) { void* bodyUserDataA = contact->GetFixtureA()->GetBody()->GetUserData(); int* entityA = static_cast<int*>(bodyUserDataA); std::string entityA_name = real_world.name_vec[*entityA].name; void* bodyUserDataB = contact->GetFixtureB()->GetBody()->GetUserData(); int* entityB = static_cast<int*>(bodyUserDataB); std::string entityB_name = real_world.name_vec[*entityB].name; b2Vec2 zero(0, 0); // if(entityA_name == "elavator_platform" && entityB_name == "circle") { // real_world.physics_body[*entityB].body->SetLinearVelocity(zero); // }else if(entityB_name == "elavator_platform" && entityA_name == "circle") { // real_world.physics_body[*entityA].body->SetLinearVelocity(zero); // } // // b2Vec2 zero(0, 0); // if (entityA_name == "elavator") { // b2Vec2 vel = contact->GetFixtureA()->GetBody()->GetLinearVelocity(); // float ang_vel = contact->GetFixtureA()->GetBody()->GetAngularVelocity(); // cout<<"velX = "<<vel.x<<"velY = "<<vel.y<<endl; // cout<<"ang vel = "<<ang_vel<<endl; // vel.x = vel.x * -1; // vel.y = vel.y * -1; // contact->GetFixtureA()->GetBody()->SetLinearVelocity(zero); // contact->GetFixtureA()->GetBody()->SetAngularVelocity(0); // } // if (entityB_name == "elavator") { // b2Vec2 vel = contact->GetFixtureB()->GetBody()->GetLinearVelocity(); // float ang_vel = contact->GetFixtureB()->GetBody()->GetAngularVelocity(); // vel.x = vel.x * -1; // vel.y = vel.y * -1; // contact->GetFixtureB()->GetBody()->SetLinearVelocity(zero); // contact->GetFixtureB()->GetBody()->SetAngularVelocity(0); // cout<<"velX = "<<vel.x<<"velY = "<<vel.y<<endl; // cout<<"ang vel = "<<ang_vel<<endl; // } } void MyContactListener::change_moving_platform_direction(int entity) { float mul = -1; b2Vec2 vel; vel.x = real_world.velocity_vec[entity].x * mul; vel.y = real_world.velocity_vec[entity].y * mul; real_world.velocity_vec[entity] = vel; b2JointEdge* j = real_world.physics_body_vec[entity].body->GetJointList(); if(j)j->joint->GetBodyB()->SetLinearVelocity(vel);//if the core body is deleted prevents from null } void MyContactListener::activate_spring_motor(int entity) { b2JointEdge* j = real_world.physics_body_vec[entity].body->GetJointList(); b2PrismaticJoint* pj = (b2PrismaticJoint*)j->joint; pj->SetMotorSpeed (-5); } void MyContactListener::teleport_objectA(int entityA, int entityB, int contact_id, b2Contact* contact) { if(!teleportA_flag){ b2JointEdge* j = real_world.physics_body_vec[entityA].body->GetJointList(); b2Vec2 pos = j->other->GetPosition(); float teleportB_angle = j->other->GetAngle(); b2Vec2 ball_vel; float angle; if(contact_id == 0) { ball_vel = contact->GetFixtureB()->GetBody()->GetLinearVelocity(); angle = contact->GetFixtureB()->GetBody()->GetAngle(); }else{ ball_vel = contact->GetFixtureA()->GetBody()->GetLinearVelocity(); angle = contact->GetFixtureA()->GetBody()->GetAngle(); } b2Vec2 vel; float multiplier = 0; if(abs(ball_vel.x) >= abs(ball_vel.y)) { multiplier = abs(ball_vel.x); }else { multiplier = abs(ball_vel.y); } vel.x = multiplier * cos(teleportB_angle); vel.y = multiplier * sin(teleportB_angle); qDebug() << "teleport angle: " << angle; real_world.teleportation_vec[entityB].is_teleporting = true; real_world.teleportation_vec[entityB].coordinates = pos; real_world.teleportation_vec[entityB].angle = angle; real_world.teleportation_vec[entityB].velocity = vel; teleportB_flag = true; teleportA_flag = false; }else{ teleportA_flag = false; } } void MyContactListener::teleport_objectB(int entityA, int entityB, int contact_id, b2Contact *contact) { if(!teleportB_flag){ b2JointEdge* j = real_world.physics_body_vec[entityA].body->GetJointList(); b2Vec2 pos = j->other->GetPosition(); float teleportA_angle = j->other->GetAngle(); b2Vec2 ball_vel; float angle; if(contact_id == 0) { ball_vel = contact->GetFixtureB()->GetBody()->GetLinearVelocity(); angle = contact->GetFixtureB()->GetBody()->GetAngle(); }else{ ball_vel = contact->GetFixtureA()->GetBody()->GetLinearVelocity(); angle = contact->GetFixtureA()->GetBody()->GetAngle(); } b2Vec2 vel; float multilyer = 0; if(abs(ball_vel.x) >= abs(ball_vel.y)) { multilyer = abs(ball_vel.x); }else { multilyer = abs(ball_vel.y); } vel.x = multilyer * cos(teleportA_angle); vel.y = multilyer * sin(teleportA_angle); real_world.teleportation_vec[entityB].is_teleporting = true; real_world.teleportation_vec[entityB].coordinates = pos; real_world.teleportation_vec[entityB].angle = angle; real_world.teleportation_vec[entityB].velocity = vel; teleportA_flag = true; teleportB_flag = false; }else { teleportB_flag = false; } }
3ccd023ca90a28bcb3997c3563767c66954d88e9
8e679f1c3edde15bb4051dba8723690cbb6b1ecd
/src/Hooks.cpp
a5da7d9db43fa18f9c32d7ca0c0d8b3b8d8ec77d
[ "MIT" ]
permissive
sharebright/task
11b6e57c481a7b61aad092d37e10b7b4b2677967
00204e01912aeb9e39b94ac7ba16562fdd5b5f2c
refs/heads/master
2021-05-27T06:17:12.822049
2014-01-15T23:23:16
2014-01-15T23:23:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,941
cpp
Hooks.cpp
//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <algorithm> #include <Context.h> #include <Hooks.h> #include <Timer.h> #include <text.h> #include <i18n.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hook::Hook () : _event ("") , _file ("") , _function ("") { } //////////////////////////////////////////////////////////////////////////////// Hook::Hook (const std::string& e, const std::string& f, const std::string& fn) : _event (e) , _file (f) , _function (fn) { } //////////////////////////////////////////////////////////////////////////////// Hook::Hook (const Hook& other) { _event = other._event; _file = other._file; _function = other._function; } //////////////////////////////////////////////////////////////////////////////// Hook& Hook::operator= (const Hook& other) { if (this != &other) { _event = other._event; _file = other._file; _function = other._function; } return *this; } //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () { // New 2.x hooks. _validTaskEvents.push_back ("on-task-add"); // Unimplemented _validTaskEvents.push_back ("on-task-modify"); // Unimplemented _validTaskEvents.push_back ("on-task-complete"); // Unimplemented _validTaskEvents.push_back ("on-task-delete"); // Unimplemented _validProgramEvents.push_back ("on-launch"); _validProgramEvents.push_back ("on-exit"); _validProgramEvents.push_back ("on-file-read"); // Unimplemented _validProgramEvents.push_back ("on-file-write"); // Unimplemented _validProgramEvents.push_back ("on-synch"); // Unimplemented _validProgramEvents.push_back ("on-merge"); // Unimplemented _validProgramEvents.push_back ("on-gc"); // Unimplemented } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// // Enumerate all hooks, and tell API about the script files it must load in // order to call them. Note that API will perform a deferred read, which means // that if it isn't called, a script will not be loaded. void Hooks::initialize () { // Allow a master switch to turn the whole thing off. bool big_red_switch = context.config.getBoolean ("extensions"); if (big_red_switch) { Config::const_iterator it; for (it = context.config.begin (); it != context.config.end (); ++it) { std::string type; std::string name; std::string value; // "<type>.<name>" Nibbler n (it->first); if (n.getUntil ('.', type) && type == "hook" && n.skip ('.') && n.getUntilEOS (name)) { Nibbler n (it->second); // <path>:<function> [, ...] while (!n.depleted ()) { std::string file; std::string function; if (n.getUntil (':', file) && n.skip (':') && n.getUntil (',', function)) { context.debug (std::string ("Event '") + name + "' hooked by " + file + ", function " + function); Hook h (name, Path::expand (file), function); _all.push_back (h); (void) n.skip (','); } else ; // Was: throw std::string (format ("Malformed hook definition '{1}'.", it->first)); } } } } else context.debug ("Hooks::initialize --> off"); } //////////////////////////////////////////////////////////////////////////////// // Program hooks. bool Hooks::trigger (const std::string& event) { return false; } //////////////////////////////////////////////////////////////////////////////// // Task hooks. bool Hooks::trigger (const std::string& event, Task& task) { return false; } //////////////////////////////////////////////////////////////////////////////// bool Hooks::validProgramEvent (const std::string& event) { if (std::find (_validProgramEvents.begin (), _validProgramEvents.end (), event) != _validProgramEvents.end ()) return true; return false; } //////////////////////////////////////////////////////////////////////////////// bool Hooks::validTaskEvent (const std::string& event) { if (std::find (_validTaskEvents.begin (), _validTaskEvents.end (), event) != _validTaskEvents.end ()) return true; return false; } ////////////////////////////////////////////////////////////////////////////////
2eae80aa346337cb5a24cb12f304e8a9538f64f1
2fdfba54bbeca28ebe1d9e39c39bbb5053e7da72
/splitMergeRGB.hpp
79fd607d35f9c7eb6e136cf38c0f42c78362fd5a
[]
no_license
GawainGao/cattleImageProcessing
c9db6dd4fdd5150502bd4bf876d7a711817d718c
04a7207ddabf6142a884ac36b3658f2bf2945239
refs/heads/master
2020-04-19T17:18:20.400595
2019-01-30T11:24:36
2019-01-30T11:24:36
168,330,918
0
0
null
null
null
null
UTF-8
C++
false
false
524
hpp
splitMergeRGB.hpp
// // splitMergeRGB.hpp // New_cattle // // Created by 高源 on 2018/11/27. // Copyright © 2018 Gao Yuan. All rights reserved. // #ifndef splitMergeRGB_hpp #define splitMergeRGB_hpp #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace cv; using namespace std; Mat splitMergeRGB(Mat srcImage, int r_start, int r_end, int g_start, int g_end, int b_start, int b_end); #endif /* splitMergeRGB_hpp */
d6aa80ab50d812ca4b189d388de2589a6dd4bae3
077b52d6bf4438d2e0172531ba6acb27b1aaf8dd
/Inheritance/11/waterconsumer.hpp
93631b9a2afffd7fb48409dcbe93456ead1e5512
[]
no_license
bmvskii/OOP
a41ccf5a9862f6f112e8a82a25462bac4c605a64
810ad97eb418024cfac7beb66a8fff76cae73b90
refs/heads/master
2020-03-25T02:03:42.824530
2019-08-01T13:31:00
2019-08-01T13:31:00
143,271,973
0
0
null
null
null
null
UTF-8
C++
false
false
1,798
hpp
waterconsumer.hpp
// (C) 2013-2016, Sergei Zaychenko, KNURE, Kharkiv, Ukraine #ifndef _WATERCONSUMER_HPP_ #define _WATERCONSUMER_HPP_ /*****************************************************************************/ #include <string> class WaterConsumer { /*-----------------------------------------------------------------*/ public: WaterConsumer( int _consumerID, std::string const & _fullOwnerName, std::string const & _address ); virtual ~WaterConsumer() = default; virtual void payment(double _amount) = 0; virtual void usingWater(double _amount) = 0; virtual double getDebt(double _cost) = 0; void pay(double _amount); int getConsumerID() const; double getPaymentSummary() const; std::string const & getConsumerFullName() const; std::string const & getConsumerAddress() const; private: int m_consumerID; double m_paymentSummary; std::string m_consumerFullName; std::string m_consumerAddress; /*-----------------------------------------------------------------*/ }; inline void WaterConsumer::pay(double _amount) { m_paymentSummary += _amount; } inline int WaterConsumer::getConsumerID() const { return m_consumerID; } /*****************************************************************************/ inline double WaterConsumer::getPaymentSummary() const { return m_paymentSummary; } /*****************************************************************************/ inline std::string const & WaterConsumer::getConsumerFullName() const { return m_consumerFullName; } /*****************************************************************************/ inline std::string const & WaterConsumer::getConsumerAddress() const { return m_consumerAddress; } /*****************************************************************************/ #endif // _WATERCONSUMER_HPP_
b9ceb5d764531f36592375172aa12beebb69d155
b9f6fec7dfa6eb01f2701bcf4bd9bff1e8c53e22
/Dia da semana.cpp
8b245c30ebed5ea4c3de5782ed64383ee1e0e0bb
[]
no_license
lrgsouza/SoftwareEngUniversityP1
eb0651fc39451b40a7e4acc7e4336f0476ce5237
d9ddf6e3fc54b9423f17fb6f35cbf98f9846ce65
refs/heads/main
2023-03-27T17:06:44.350017
2021-03-18T02:35:35
2021-03-18T02:35:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
Dia da semana.cpp
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { int D,M,A,DELTA,GX,FX,N,DS; double F,G; // GX = int(365.25*g) // FY = int(30.6*f) // ENTRADAS cin >> D >> M >> A; //FORMULAS 1 (DEFINE G e F) if (M <= 2){ G = A -1; F = M + 13; } else{ G = A; F = M+1; } //FORMULAS 2 GX = 365.25 * G; FX = 30.6 * F; N = GX + FX - 621049 + D; //DELTA if (N < 36523) DELTA = 2; if (N < 73048 && N >= 36523) DELTA = 1; if (N >= 73048) DELTA = 0; DS = (N % 7) + DELTA + 1; switch (DS) { case (1): cout << "domingo" << endl; break; case (2): cout << "segunda-feira" << endl; break; case (3): cout << "terca-feira" << endl; break; case (4): cout << "quarta-feira" << endl; break; case (5): cout << "quinta-feira" << endl; break; case (6): cout << "sexta-feita" << endl; break; case (7): cout << "sabado" << endl; break; } return 0; }
9fbe35e71e045d33978ed6380945f8bac7b8bddf
c44e52880af2528055441630fe3850bea2cb4c37
/C++/uva11942.cpp
633ff8933f25eb48aa0d7963dfcf4d86928c23c6
[ "MIT" ]
permissive
MrinmoiHossain/Uva-Solution
f89df917eb608243e621f43f3e8e9ec9b6c69c76
85602085b7c8e1d4711e679b8f5636678459b2c5
refs/heads/master
2021-01-19T19:39:40.880868
2018-12-28T17:26:15
2018-12-28T17:26:15
88,434,419
1
2
null
null
null
null
UTF-8
C++
false
false
741
cpp
uva11942.cpp
//Accepted #include <bits/stdc++.h> using namespace std; int main(void) { int N; cin >> N; vector<int>a(10); vector<bool>c(N); for(int i = 0; i < N; i++){ for(int j = 0; j < 10; j++){ cin >> a[j]; } int pcon = 0, ncon = 0; for(int j = 1; j < 10; j++){ if(a[j] - a[j - 1] >= 0) pcon++; if(a[j] - a[j - 1] < 0) ncon++; } if(pcon == 9 || ncon == 9) c[i] = 1; else c[i] = 0; } cout << "Lumberjacks:" << endl; for(int i = 0; i < N; i++) if(c[i]) cout << "Ordered" << endl; else cout << "Unordered" << endl; return 0; }
acb9582096cf3aa8166ab7820590d4312fb00174
c47089ceb4e1edfe000a7e70d6063b940b492798
/fifo/Worker.cpp
e6fb3ad32737705a11e5cdd8e8b7942bdb3cf5a9
[]
no_license
kukhterin/first
1ae8d2df084c22c2d811029e6989f485e793f8bf
64fa0b3a20fd91f90764c090c4b2c58b97e40bac
refs/heads/master
2020-12-02T06:38:24.621125
2017-11-08T09:44:07
2017-11-08T09:44:07
96,868,693
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
Worker.cpp
#include <iostream> #include <cstdio> #include <string.h> #include "Worker.hpp" Worker::Worker(NamedPipe &p) : pipe_(p) { run(); } void Worker::run() { std::string stop = "stop"; std::string empty = ""; while(true) { std::string result = (pipe_.answer()); if(result == stop) break; if(result == empty) continue; else { std::cout << result << std::endl; continue; } } return; }
2ae8a7c3fbc033290ad4726333b78c9086b0abf0
eee894fbc325926cdd66538ee65eb889203387a7
/A little work/HuffCodeNode.h
c60da3c7c7e6d3b4a202bbb5747660378f830dc6
[]
no_license
deadpool10086/love-C
e94bb3cc078cd75ea065f01c9ab6bd81a12ca34c
22e804120c4786bd745e2cdd9b023601830d96c8
refs/heads/master
2020-01-23T21:48:39.953420
2017-01-04T10:40:33
2017-01-04T10:40:33
74,674,585
0
0
null
2016-11-25T09:03:51
2016-11-24T13:13:17
null
UTF-8
C++
false
false
782
h
HuffCodeNode.h
class HuffCodeNode { private: unsigned int *data_; int size_; public: HuffCodeNode() { data_ = 0; size_ = 0; } HuffCodeNode(unsigned int *data, int size) { size_ = size; data_ = new unsigned int[size / 32 + 1]; for(int i=0; i<size/32+1; i++) { data_[i] = data[i]; } } void writ(fstream & writ,int & forWrit, int &bitSize) { while(bitSize + size_ >= 32) { if(bitSize + size_ >32) { forWrit = forWrit|(data_[0]>>(bitSize)); size_ = size_ + bitSize - 32; for(int i=0;i<size_/32;i++) { data_[i] = data_[i]<<(32-bitSize)|data_[i+1]>>(bitSize); } bitSize = 32; } if(bitSize == 32) { writ.write(reinterpret_cast<char *>(&forWrote), 4); bitSize=0; } } } };
cd6e397be50094c4ef7bf312ac3f3f3137e66b71
ed50f4016f02cb71341a30466127b85a7956dbd4
/PlayerManager.h
dd53ddd88935f488773b05d439bf0c6a11c7d867
[]
no_license
wakeup5/Sword-Is-Desert
b4fc456791cc88aa31db9f5c1dfa094ffcffcdcf
97f2a6144c84411d68668431fd474518ad521dd9
refs/heads/master
2021-01-22T05:32:38.696110
2017-05-26T05:09:30
2017-05-26T05:09:30
92,474,362
0
0
null
null
null
null
UHC
C++
false
false
882
h
PlayerManager.h
#pragma once #include "Singleton.h" class Player; class Inventory; class Equipment; class Mercenary; class Pet; class Around_Dust; class Dust; class PlayerManager : public Singleton < PlayerManager > { private: Player* _player; Inventory* _inven; Equipment* _equip; cXMesh_Static* _bowMesh; Mercenary* _mercenary; Pet* _pet; //플레이어 이펙트 Around_Dust* _adEffect; Dust* _dEffect; public: PlayerManager(); ~PlayerManager(); HRESULT Setup(); void Release(); void Update(float timeDelta); void Render(); Player* GetPlayer() { return _player; } Inventory* GetInventory() { return _inven; } Equipment* GetEquipment() { return _equip; } Mercenary* GetMercenary() { return _mercenary; } Pet* GetPet() { return _pet; } bool MonsterCollision(Monster* monster); CharacterInfo GetPlayerTotalStatus(); }; #define PLAYER_MGR PlayerManager::GetInstance()
baf4aae2dc74d7d1a1dda30113b761e90c587152
5becf25573322e1e5d3a24364727ed34fe315850
/contrib/bootserv/src/handler.hpp
7327e900c711d5049d7ea5323cd1288a88ec74cc
[ "CC0-1.0", "Zlib", "GPL-3.0-only" ]
permissive
despair86/loki-network
c6eec559121aa8dfdbf0af143f03ea0bae79ea34
45c556ca598d2b2df94e620fe1b33a65046217c8
refs/heads/master
2021-06-21T04:07:49.616979
2020-04-21T22:50:23
2020-05-01T22:37:06
142,740,572
0
0
Zlib
2018-07-29T07:35:41
2018-07-29T07:35:41
null
UTF-8
C++
false
false
845
hpp
handler.hpp
#ifndef LOKINET_BOOTSERV_HANDLER_HPP #define LOKINET_BOOTSERV_HANDLER_HPP #include <iostream> #include "lokinet-config.hpp" namespace lokinet { namespace bootserv { struct Handler { Handler(std::ostream& o) : out(o){}; virtual ~Handler(){}; /// handle command /// return exit code virtual int Exec(const Config& conf) = 0; /// report an error to system however that is done /// return exit code virtual int ReportError(const char* err) = 0; protected: std::ostream& out; }; using Handler_ptr = std::unique_ptr< Handler >; /// create cgi handler Handler_ptr NewCGIHandler(std::ostream& out); /// create cron handler Handler_ptr NewCronHandler(std::ostream& out); } // namespace bootserv } // namespace lokinet #endif
1015ff676d824b9b64df3738a22c95f170ef926f
ebc866b438ee6281d9f9f66b10d47059a561247d
/src/data_source.h
aa5943e4a02646c2037b71b3c3e8cab4d337d38e
[]
no_license
AliMehrpour/SelfDrivingCar-Term2-P1-ExtendedKalmanFilter
60ed716442c6590feddc6246329d486517a6d473
402752f9a4c4e2cc2268351831fb9d407e10111d
refs/heads/master
2021-01-19T19:08:55.468679
2017-04-17T16:00:45
2017-04-17T16:00:45
88,400,663
1
0
null
null
null
null
UTF-8
C++
false
false
699
h
data_source.h
/* * data_source.h * * Created on: Apr 9, 2017 * Author: Ali Mehrpour */ #ifndef DATA_SOURCE_H_ #define DATA_SOURCE_H_ #include <vector> #include <iostream> #include "data.h" using namespace std; using std::vector; /** * Load measurement and ground truth data */ class DataSource { public: vector<Data> measurements_; // Measurement list vector<Data> truths_; // Ground truth list DataSource(); ~DataSource(); /** * Load data from given file name */ void Load(string file_name, bool process_laser_measurement, bool process_radar_measurement); /** * return string representation of current object */ string ToString(); }; #endif /* DATA_SOURCE_H_ */
2b891550af9f0312179ef7597f30a1c562251e9a
24c3b6ee3e2b06288bed587e34751969b4a73e31
/Codeforces/ProblemSet/1333/F.cpp
d7ea8ba4b1c2b0bf1d2eb3eb22f8dca1510c9092
[]
no_license
KatsuyaKikuchi/ProgrammingContest
89afbda50d1cf59fc58d8a9e25e6660334f18a2a
d9254202eec56f96d8c5b508556464a3f87a0a4f
refs/heads/master
2023-06-05T20:07:36.334182
2021-06-13T13:55:06
2021-06-13T13:55:06
318,641,671
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
F.cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<ll, ll> pll; #define FOR(i, n, m) for(ll (i)=(m);(i)<(n);++(i)) #define REP(i, n) FOR(i,n,0) #define OF64 std::setprecision(10) const ll MOD = 1000000007; const ll INF = (ll) 1e15; ll P[500005]; int main() { cin.tie(0); ios::sync_with_stdio(false); ll N; cin >> N; memset(P, 0, sizeof(P)); for (ll i = 2; i <= N; ++i) { if (P[i] > 0) continue; for (ll j = i; j <= N; j += i) { if (P[j] == 0) P[j] = i; } } priority_queue<ll, vector<ll>, greater<ll>> q; for (ll i = 2; i <= N; ++i) { q.push(i / P[i]); } while (!q.empty()) { ll t = q.top(); q.pop(); cout << t << " "; } cout << endl; return 0; }
149129492f6999d30b6338446dc7a04031d5246b
421d70efa4bd31b613fb8ce467ef20507860e4e7
/Project3Part2Submission2/Actor.h
5048578699694482baa722f894b456f56c37c394
[]
no_license
mntxca/CS-32-Projects
847ab69073beaf4b6baaeb1a913293eddca539d4
21b9b81e05eb6c5001080177863dae8b7adfab0d
refs/heads/main
2023-07-13T21:47:47.225059
2021-08-29T00:44:11
2021-08-29T00:44:11
400,919,310
0
0
null
null
null
null
UTF-8
C++
false
false
17,602
h
Actor.h
#ifndef ACTOR_H_ #define ACTOR_H_ #include "GraphObject.h" // Students: Add code to this file, Actor.cpp, StudentWorld.h, and StudentWorld.cpp //#1 of part 1 #include "StudentWorld.h" class GhostRacer; class StudentWorld; class Actor : public GraphObject //#1 p2: derived from GraphObject class { public: Actor(int imageID, double startX, double startY, int dir, double size, unsigned int depth, bool startAlive, bool collisionAvoid, StudentWorld* StudentWorld1, double verticalSpeed1, double horizontalSpeed1, GhostRacer* GhostRacer1, bool affectedByProjectile1 = false) :GraphObject(imageID, startX, startY, dir, size, depth), alive(startAlive), collisionAvoidance(collisionAvoid), world(StudentWorld1), verticalSpeed(verticalSpeed1), horizontalSpeed(horizontalSpeed1), racer(GhostRacer1), affectedByProjectile(affectedByProjectile1) //takes in inputs to initialize base class and member variables { } //what should this initialize and take input for? virtual void doSomething() = 0; //this is the doSomething() function which makes the object do whatever it needs to each tick, but this depends on what the type of the object is, so this must be virtual void doSomethingBasic(); //this is the default moving algorithm for nearly all derived classes, this is used in only some (most) derived classes, so I just call it when its needed as part of doSomething() so no need to be virtual, I don't call it in classes that use a different moving method bool isAlive() { return alive; } //this just checks if something is alive or not, this is the same for every single class so doesn't need to be virtual void nowDead() { alive = false; } //makes the object dead, same for all derived classes so no need for virtual bool isCollisionAvoidanceWorthy() { return collisionAvoidance; } // returns if the object isCollisionAvoidanceWorthy, which is the same for all derived classes so no need for virtual StudentWorld* getWorld() { return world; } // returns the base world, which again is the same for all derived classes so no need for virtual void play(const int sound); //this is just easier syntax for the playSound(int input), which is the same for all classes so no need for virtual double getVerticalSpeed() { return verticalSpeed; } //returns the vertical speed, which again is the same for all derived classes so no need for virtual double setVerticalSpeed(double newSpeed) { verticalSpeed = newSpeed; return verticalSpeed; } //changes then returns the vertical speed, which again is the same for all derived classes so no need for virtual double getHorizontalSpeed() { return horizontalSpeed; } //returns the horizontal speed, which again is the same for all derived classes so no need for virtual double setHorizontalSpeed(double newSpeed) { horizontalSpeed = newSpeed; return horizontalSpeed; } //changes then returns the horizontal speed, which again is the same for all derived classes so no need for virtual GhostRacer* getRacer() { return racer; } //returns the Ghostracer pointer, which again is the same for all derived classes so no need for virtual bool isAffectedByProjectile() { return affectedByProjectile; } ////returns the vertical speed, which again is the same for all derived classes so no need for virtual virtual void holyWaterHit(){ }// the default is that this does absolutely nothing (as many derived classes are completely unaffected), but some derived classes are affected, so this depends on the class, so this is virtual private: bool collisionAvoidance; bool alive; StudentWorld* world; double verticalSpeed; double horizontalSpeed; GhostRacer* racer; bool affectedByProjectile; }; class BorderLine : public Actor {//Actor(int imageID, double startX, double startY, int dir, double size, unsigned int depth, bool startAlive, bool collisionAvoid, StudentWorld* StudentWorld1) public: BorderLine(int imageID, double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Actor(imageID, startX, startY, 0, 2.0, 2, true, false, StudentWorld1, -4, 0, GhostRacer1, false) //takes in inputs to initialize base class, constant inputs are the ones that the spec says that this type of object always has {} virtual void doSomething() { doSomethingBasic(); } //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual private: }; class OilSlick : public Actor {//Actor(int imageID, double startX, double startY, int dir, double size, unsigned int depth, bool startAlive, bool collisionAvoid, StudentWorld* StudentWorld1) public: OilSlick(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Actor(IID_OIL_SLICK, startX, startY, 0, randInt(2,5), 1, true, false, StudentWorld1, -4, 0, GhostRacer1, false)//takes in inputs to initialize base class and member variables {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual private: }; class MovingActor : public Actor {// Actor(int imageID, double startX, double startY, int dir, double size, unsigned int depth, bool startAlive, bool collisionAvoid, StudentWorld* StudentWorld1, int verticalSpeed1, int horizontalSpeed1, GhostRacer* GhostRacer1) public: MovingActor(int imageID, double startX, double startY, int dir, double size, bool collisionAvoid, int hitpoints, StudentWorld* StudentWorld1, int verticalSpeed1, int horizontalSpeed1, GhostRacer* GhostRacer1, bool affectedByProjectile) :Actor(imageID, startX, startY, dir, size, 0, true, collisionAvoid, StudentWorld1, verticalSpeed1, horizontalSpeed1, GhostRacer1, affectedByProjectile), hp(hitpoints), movementPlanDistance(0) //all Movingactors have depth 0, all actors start alive, movementPlandistance starts at 0 {} void takeDamage(int damage); //all MovingActors are able to take damage (which is why this function is in the MovingActor class), so this function is not virtual because this just decrements the HP by the inputted amount, and then calls nowDead() if the HP is 0 or less. This process is the same for all derived classes, so no need for virtual int getHP() { return hp; } //returns HP, which is something that all MovingActors have (which is why this function is in the MovingActor class), so this function is not virtual because this process of getting the variable is the same for all derived classes int setHP(int newVal) { hp = newVal; return newVal;} //sets and returns HP, which is something that all MovingActors have (which is why this function is in the MovingActor class), so this function is not virtual because this process of setting the variable is the same for all derived classes //These three following functions are like peas in a pod. They all deal with getting, decrementing, and setting new movementPlanDist, which is used in all the derived classes of MovingActor (which is why these functions are in the MovingActor class) //The process that these three work with are the same no matter what derived class it is, which is why none of these three are virtual int getMovementPlanDist() { return movementPlanDistance; } int decMovementPlanDist() { movementPlanDistance--; return movementPlanDistance; } void setMovementPlanDist(int newPlan) { movementPlanDistance = newPlan; } //This below is used for multiple derived classes of MovingActor(which is why this function is in the MovingActor class), so this function is not virtual because this function is just not called in derived classes that do things differently void newMovementPlan(); private: int hp; int movementPlanDistance; }; class GhostRacer : public MovingActor { public: GhostRacer(StudentWorld* StudentWorld1) :MovingActor(IID_GHOST_RACER, 128, 32, up, 4.0, true, 100, StudentWorld1, 0, 0, this, false), holyWaterCount(10) //takes in inputs to initialize base class and member variables, including speed components, position, up direction, 100 hitpoints, CAW and a few others {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual void spin(); //this function spins the direction of the GhostRacer when driving over an oilslick, and this is part of the GhostRacer class because this function changes the direction of the GhostRacer object. This is not virtual because there is no equivalent spinning of any other class type //These next three functions go hand in hand. The three functions return the holyWaterCount, which measures the amount of sprays left, or add the number of picked up holyWater sprays, or decrement the holyWaterCount when a spraying projectile is released //Only the GhostRacer can shoot and pick up holy water, which is why these three functions are in this class. These are not virtual because there is only one class that can actually use the holy water int getHolyWaterValue() { return holyWaterCount; } int holyWaterPickup(int num) { holyWaterCount += num; return holyWaterCount; } void holyWaterDecrement() { if (holyWaterCount > 0) holyWaterCount--; } //This function heals the GhostRacer by the healed amount, but to no more than 100 HP. Only the GhostRacer can heal, which is why this is in the GhostRacer class, and it is also not virtual for this reason (no need to be virtual if there are no more implementations of same function) void heal(int amount) { if (getHP() + amount > 100) setHP(100); else setHP(getHP() + amount); } private: int holyWaterCount; }; class Goodie : public Actor { public: Goodie(int imageID, double startX, double startY, int dir, double size, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1, bool affectedByProjectile) :Actor(imageID, startX, startY, dir, size, 2, true, false, StudentWorld1, -4, 0, GhostRacer1, affectedByProjectile)//takes in inputs to initialize base class and member variables, including depth of 2 and speed components {} private: }; class HealingGoodie : public Goodie { public: HealingGoodie(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Goodie(IID_HEAL_GOODIE, startX, startY, 0, 1.0, StudentWorld1, GhostRacer1, true) //takes in inputs to initialize base class and member variables, like direction of 0 and size of 1.0, and affectedByProjectile of true {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual virtual void holyWaterHit() { nowDead(); } //the virtual holyWaterHit() function is overrided in some classes I wrote because some classes must respond to holy water hitting them differently, while some do absolutely nothing, which is the default function in the Actor class so this must be virtual private: }; class HolyWaterGoodie : public Goodie { public: HolyWaterGoodie(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Goodie(IID_HOLY_WATER_GOODIE, startX, startY, 90, 2.0, StudentWorld1, GhostRacer1, true) {} virtual void doSomething();//the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual virtual void holyWaterHit() { nowDead(); } //the virtual holyWaterHit() function is overrided in some classes I wrote because some classes must respond to holy water hitting them differently, while some do absolutely nothing, which is the default function in the Actor class so this must be virtual private: }; class SoulGoodie : public Goodie { public: SoulGoodie(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Goodie(IID_SOUL_GOODIE, startX, startY, 0, 4.0, StudentWorld1, GhostRacer1, false) {} virtual void doSomething();//the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual private: }; class Pedestrian : public MovingActor {//MovingActor(int imageID, double startX, double startY, int dir, double size, bool collisionAvoid, int hitpoints, StudentWorld* StudentWorld1, int verticalSpeed1, int horizontalSpeed1, GhostRacer* GhostRacer1) public: Pedestrian(int imageID, double startX, double startY, double size, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :MovingActor(imageID, startX, startY, 0, size, true, 2, StudentWorld1, -4 , 0, GhostRacer1, true), movementPlanDistance(0) {} private: int movementPlanDistance; }; class ZomPed : public Pedestrian {//Pedestrian(int imageID, double startX, double startY, double size, StudentWorld* StudentWorld1) public: ZomPed(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Pedestrian(IID_ZOMBIE_PED, startX, startY, 3.0, StudentWorld1, GhostRacer1), ticksUntilNextGrunt(0) {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual //These next three functions go hand in hand. The three functions return the holyWaterCount, which measures the amount of sprays left, or add the number of picked up holyWater sprays, or decrement the holyWaterCount when a spraying projectile is released //Only the GhostRacer can shoot and pick up holy water, which is why these three functions are in this class. These are not virtual because there is only one class that can actually use the holy water int decTicksUntilNextGrunt() { if (ticksUntilNextGrunt > 0) ticksUntilNextGrunt--; else return -1; return ticksUntilNextGrunt; } int getTicksUntilNextGrunt() { return ticksUntilNextGrunt; } int setTicksUntilNextGrunt(int newTicks) { ticksUntilNextGrunt = newTicks; return newTicks; } virtual void holyWaterHit() { gotHurt(); } //the virtual holyWaterHit() function is overrided in some classes I wrote because some classes must respond to holy water hitting them differently, while some do absolutely nothing, which is the default function in the Actor class so this must be virtual private: void gotHurt(); int ticksUntilNextGrunt; }; class HumPed : public Pedestrian { public: HumPed(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :Pedestrian(IID_HUMAN_PED, startX, startY, 2.0, StudentWorld1, GhostRacer1) {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual virtual void holyWaterHit(); //the virtual holyWaterHit() function is overrided in some classes I wrote because some classes must respond to holy water hitting them differently, while some do absolutely nothing, which is the default function in the Actor class so this must be virtual private: }; class ZomCab : public MovingActor {//int imageID, double startX, double startY, int dir, double size, bool collisionAvoid, int hitpoints, StudentWorld* StudentWorld1, int verticalSpeed1, int horizontalSpeed1, GhostRacer* GhostRacer1 public: ZomCab(double startX, double startY, double verticalSpeed1, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1) :MovingActor(IID_ZOMBIE_CAB, startX, startY, 90, 4.0, true, 3, StudentWorld1, verticalSpeed1, 0, GhostRacer1, true), hasDamagedGhostRacer(false) {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual virtual void holyWaterHit(); //the virtual holyWaterHit() function is overrided in some classes I wrote because some classes must respond to holy water hitting them differently, while some do absolutely nothing, which is the default function in the Actor class so this must be virtual private: bool hasDamagedGhostRacer; }; class Projectile : public Actor {//Actor(int imageID, double startX, double startY, int dir, double size, unsigned int depth, bool startAlive, bool collisionAvoid, StudentWorld* StudentWorld1, int verticalSpeed1, int horizontalSpeed1, GhostRacer* GhostRacer1) public: Projectile(double startX, double startY, StudentWorld* StudentWorld1, GhostRacer* GhostRacer1, int direction) :Actor(IID_HOLY_WATER_PROJECTILE, startX, startY, direction, 1.0, 1, true, false, StudentWorld1, 0, 0, GhostRacer1, false), travelDistLeft(160) {} virtual void doSomething(); //the virtual doSomething() function is in every single class that I wrote because each class must doSomething() each tick, and each class must doSomething() different, so this must be virtual void tickMoved() {travelDistLeft -= SPRITE_HEIGHT; if (travelDistLeft <= 0) { nowDead(); }} //decrement by the sprite's height every tick, and once the travelDist is completed (when it is 0), then kill the sprite (to range limit it by 160 px). This is in the Projectile class because only projectiles have a range limit out of all classes, and for the same reason, there is no need for this to be virtual because there are no other implementations of this. private: int travelDistLeft; }; #endif // ACTOR_H_
42d0a975438e6722e4a9df696303432937139a58
6c40b92de13b247e682fe703899293b5e1e2d7a6
/MyProjects/CODE_LAB/src/flash.cpp
71fd39b147756b216d275dd22c96257f68ef92d6
[]
no_license
ismdeep/ICPC
8154e03c20d55f562acf95ace5a37126752bad2b
2b661fdf5dc5899b2751de7d67fb26ccb6e24fc1
refs/heads/master
2020-04-16T17:44:24.296597
2016-07-08T02:59:01
2016-07-08T02:59:01
9,766,019
1
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
flash.cpp
#include <iostream> #include <windows.h> #include <time.h> using namespace std; string colorInstruction = "color 80"; void iChangeColor(int background, int colorValue) { if (background == 1 || background == 2) { colorInstruction[6] = ('8' + background); } else { colorInstruction[6] = ('A' + background - 3); } colorInstruction[7] = ('0' + colorValue); system(&colorInstruction[0]); } int main() { int background = rand() % 2; while (1) { if (rand() % 2 == 0) { background = rand() % 8; } iChangeColor(background , rand() % 8); Sleep(rand() % 50); } return 0; } // end // iCoding@CodeLab // //
00948181f5f3cdec4857994477c8dff5fb39ee71
3eafea92a3b829aa6dd01674477f2b1d9fd1aadf
/examples/ExtFonts/ExtFonts.ino
1154440e37c3722d49e756b95a0f1bd2bf7caf33
[]
no_license
hwreverse/easyT6963
27d2d2ca512ae6c72941f6c5bcd7c96c913ce5eb
97313d744f5a8fd64d6325f0b482c029db8f3595
refs/heads/master
2020-05-04T16:34:37.106483
2015-03-07T22:34:02
2015-03-07T22:34:02
179,281,202
0
0
null
null
null
null
UTF-8
C++
false
false
1,877
ino
ExtFonts.ino
#include <SPI.h> #include <mcp23s17.h> // needed! #include <T6963_SPI.h> #include "fonts/Dubsteptrix__12.h" #include "fonts/Imagine_FontFixed__6.h" /* monoMMM_Fixed__6 Square_HeadCon_Fixed__9 M39_SQUAREFUTURE_Fixed__5 Indieutka_PixelFixed__12 Imagine_FontFixed__15 Imagine_FontFixed__6 genown_one_fixed__5 DubsteptrixFixed__8 Dubsteptrix__12 BeatboxFixed__8 Beatbox__9 Identification_Mono__8 Square_Pixel7__14 SnareDrum_One_NBP__12 Redensek__9 Pixel_Millennium__12b Pixel_Millennium__12 Megaton__12 Megaton__9 Imagine_Font__12b Imagine_Font__12 Imagine_Font__9 Homespun_TT_BRK__9 */ #if (defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__)) //--- Arduino Mega --- T6963_SPI lcd(53,0x20,1);//53,0x20 #else T6963_SPI lcd(10,0x20,1);//10,0x20 #endif void printIt(uint8_t x,uint8_t y,char* txt,boolean color){ lcd.gPrint(x,y,txt,&Dubsteptrix__12,color); } void printIt2(uint8_t x,uint8_t y,char* txt,boolean color){ lcd.gPrint(x,y,txt,&Imagine_FontFixed__6,color); } boolean _fastmode; uint8_t _line1; uint8_t _line2; void setup() { //Serial.begin(115200); randomSeed(analogRead(0)); lcd.begin(240,128,T6963_6x8DOTS,32);//240,128,T6963_6x8DOTS,32 lcd.setBacklight(1); lcd.setMode(NORMAL);//Switch to Normal Mode } void loop() { _fastmode = random(0,2); lcd.fastMode(_fastmode); _line1 = random(0,2); _line2 = random(0,2); if (_fastmode){ lcd.setCursor(0,10); lcd.print("Fast Mode Enabled..."); } else { lcd.setCursor(0,10); lcd.print("Slow secure mode ..."); } if (_line1 == 0){ printIt(3, 3, "T6963C LCD", 0); } else { printIt2(3, 3, "T6963C LCD", 0); } if (_line2 == 0){ printIt(3, 25, "ext. Fonts", 0); } else { printIt2(3, 25, "ext. Fonts", 0); } delay(2000); lcd.clearGraphic(); }
d86cb56afffa5dcbf61386397bab24de04448095
80a555214e269fcba94854fac351399f4a3d6e66
/pybindings/src/cv_uncc_module.hpp
a0a61a309cd94217f90ae1b8c94ac6c2c758aedd
[]
no_license
uncc-visionlab/ros_rgbd_surface_tracker
3ef8fa9681891fc36730a5a82532c2094c9e7971
0eb66f2cce8b726d7fa5b0564f8e4631a329b9c1
refs/heads/master
2023-06-08T19:18:32.300132
2021-05-17T03:10:51
2021-05-17T03:10:51
325,326,522
1
0
null
null
null
null
UTF-8
C++
false
false
382
hpp
cv_uncc_module.hpp
#ifndef BVMODULE_H #define BVMODULE_H // header file contents go here... #include <opencv2/opencv.hpp> using namespace std; using namespace cv; namespace cv_uncc { namespace rgbd { CV_EXPORTS_W void fillHoles(Mat &mat); class CV_EXPORTS_W Filters { public: CV_WRAP Filters(); CV_WRAP void edge(InputArray im, OutputArray imedge); }; } } #endif // BVMODULE_H
d8be765dab0ca659d4e8609041e82a4eea809210
53bdf5b903694564d03521ef3105c1b03dfd1ca9
/heap-sort.cpp
a5596f50fe2b68a672711ffea9c127f061668601
[]
no_license
kapildeshpande/DSA
d02a83ce30bf95597d98e347975d3f1127817acf
9c029628d17bd1d69c921d4a3f3bbd87b8ab8568
refs/heads/master
2021-12-27T19:06:14.975379
2021-08-02T07:17:49
2021-08-02T07:17:49
92,045,830
6
1
null
null
null
null
UTF-8
C++
false
false
940
cpp
heap-sort.cpp
#include<iostream> using namespace std; int a[50], temp,n; void build_heap (); void heapify (int i, int m); void heapsort () { build_heap(); int m=n; while (m>=2) { temp=a[1]; a[1]=a[m]; a[m]=temp; cout<<a[1]<<" "<<a[m]<<"\n"; m=m-1; heapify (1,m); } } void build_heap () { for ( int i=n/2; i>=1; i--) { cout<<i<<"\n"; heapify (i,n); } } void heapify (int i, int m) { int l=2*i; int r=(2*i)+1; int max=i; if (l<=m && a[l]>a[max] ) max=l; if (r<=m && a[r]>a[max] ) max=r; if (max!=i){ temp=a[i]; a[i]=a[max]; a[max]=temp; cout<<a[i]<<" "<<a[max]<<"\n"; heapify (max,m); } } int main() { cout<<"Enter the number of elements you want in array: "; cin>>n; cout<<"Enter the elements:\n"; for ( int i=1; i<=n; i++ ) cin>>a[i]; heapsort(); cout<<"After sorting(Heap sort):- "; for (int i=1; i<=n; i++) cout<<a[i] <<" "; return 0; }
a0a924d66d2a8227511c6774b19a0870783d49b4
3dff775734ba488f4badaae1e0b68abb53a8b0c2
/adspc++2code/QueueLi.cpp
0f31cd59240827f9151e23beb82df9e43675b494
[]
no_license
barrygu/dsaa
22211497c127f28658f74c256d1fefe416257e19
432f5c764c0b8531f5063e1839445fbeb496dc73
refs/heads/master
2016-08-05T16:35:47.312632
2014-07-14T03:14:21
2014-07-14T03:14:21
21,804,296
0
1
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
QueueLi.cpp
#include "QueueLi.h" // Construct the queue. template <class Object> Queue<Object>::Queue( ) { front = back = NULL; } // Copy constructor. template <class Object> Queue<Object>::Queue( const Queue<Object> & rhs ) { front = back = NULL; *this = rhs; } // Destructor. template <class Object> Queue<Object>::~Queue( ) { makeEmpty( ); } // Test if the queue is logically empty. // Return true if empty, false, otherwise. template <class Object> bool Queue<Object>::isEmpty( ) const { return front == NULL; } // Make the queue logically empty. template <class Object> void Queue<Object>::makeEmpty( ) { while( !isEmpty( ) ) dequeue( ); } // Return the least recently inserted item in the queue // or throw UnderflowException if empty. template <class Object> const Object & Queue<Object>::getFront( ) const { if( isEmpty( ) ) throw UnderflowException( ); return front->element; } // Return and remove the least recently inserted item from // the queue. Throw UnderflowException if empty. template <class Object> Object Queue<Object>::dequeue( ) { Object frontItem = getFront( ); ListNode *old = front; front = front->next; delete old; return frontItem; } // Insert x into the queue. template <class Object> void Queue<Object>::enqueue( const Object & x ) { if( isEmpty( ) ) back = front = new ListNode( x ); else back = back->next = new ListNode( x ); } // Deep copy. template <class Object> const Queue<Object> & Queue<Object>::operator=( const Queue<Object> & rhs ) { if( this != &rhs ) { makeEmpty( ); ListNode *rptr; for( rptr = rhs.front; rptr != NULL; rptr = rptr->next ) enqueue( rptr->element ); } return *this; }
97f6e3a5f722ed438939640f7a26d5dddbeb8778
2b11ce1b85044457479bbb3a810de8a91750eb2e
/dft.hxx
00b4a6846aefd5cd4a35262ebcdd61cfa4aa69d3
[]
no_license
Drako/fft_test
7e577c305452589b44c9e999361c968e441ca218
1c507777962fdb2dca030734348939eccc4100df
refs/heads/master
2021-01-18T19:24:35.201222
2015-02-17T16:19:10
2015-02-17T16:19:10
30,925,401
0
0
null
null
null
null
UTF-8
C++
false
false
542
hxx
dft.hxx
#ifndef DFT_HXX #define DFT_HXX #include <complex> #include <vector> static std::size_t const DFT_ALL = 0; std::vector<std::complex<double>> dft(std::vector<double> const & source_signal, std::size_t count = DFT_ALL); std::vector<std::complex<double>> dft(std::vector<std::complex<double>> const & source_signal, std::size_t count = DFT_ALL); std::vector<std::complex<double>> fft(std::vector<double> const & source_signal); std::vector<std::complex<double>> fft(std::vector<std::complex<double>> const & source_signal); #endif // DFT_HXX
9e8bcfc397c6da4fbf988c0146f6064384f814ff
cbfc6c986d72c07e962dec587ce3ec5ca7f2b019
/third_party/upb/upb/io/zero_copy_stream_test.cc
6cdb4f2eae6b53cc0954929216ef2952876d8925
[ "Apache-2.0", "BSD-3-Clause", "MPL-2.0" ]
permissive
ctiller/grpc
f6e26b7033f184fa44c33ccc452ffb86cfb88346
e49cfd494cbe0da619dad1ea649d6fc788a8cb9f
refs/heads/master
2023-09-01T05:47:19.040152
2023-04-14T23:42:47
2023-04-14T23:42:47
31,379,631
6
1
Apache-2.0
2023-09-14T05:03:03
2015-02-26T17:36:22
C++
UTF-8
C++
false
false
10,340
cc
zero_copy_stream_test.cc
/* * Copyright (c) 2009-2022, Google LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Google LLC nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Testing strategy: For each type of I/O (array, string, file, etc.) we // create an output stream and write some data to it, then create a // corresponding input stream to read the same data back and expect it to // match. When the data is written, it is written in several small chunks // of varying sizes, with a BackUp() after each chunk. It is read back // similarly, but with chunks separated at different points. The whole // process is run with a variety of block sizes for both the input and // the output. #include "gtest/gtest.h" #include "upb/io/chunked_input_stream.h" #include "upb/io/chunked_output_stream.h" #include "upb/upb.hpp" namespace upb { namespace { class IoTest : public testing::Test { protected: // Test helpers. // Helper to write an array of data to an output stream. bool WriteToOutput(upb_ZeroCopyOutputStream* output, const void* data, int size); // Helper to read a fixed-length array of data from an input stream. int ReadFromInput(upb_ZeroCopyInputStream* input, void* data, int size); // Write a string to the output stream. void WriteString(upb_ZeroCopyOutputStream* output, const std::string& str); // Read a number of bytes equal to the size of the given string and checks // that it matches the string. void ReadString(upb_ZeroCopyInputStream* input, const std::string& str); // Writes some text to the output stream in a particular order. Returns // the number of bytes written, in case the caller needs that to set up an // input stream. int WriteStuff(upb_ZeroCopyOutputStream* output); // Reads text from an input stream and expects it to match what // WriteStuff() writes. void ReadStuff(upb_ZeroCopyInputStream* input, bool read_eof = true); // Similar to WriteStuff, but performs more sophisticated testing. int WriteStuffLarge(upb_ZeroCopyOutputStream* output); // Reads and tests a stream that should have been written to // via WriteStuffLarge(). void ReadStuffLarge(upb_ZeroCopyInputStream* input); static const int kBlockSizes[]; static const int kBlockSizeCount; }; const int IoTest::kBlockSizes[] = {1, 2, 5, 7, 10, 23, 64}; const int IoTest::kBlockSizeCount = sizeof(IoTest::kBlockSizes) / sizeof(int); bool IoTest::WriteToOutput(upb_ZeroCopyOutputStream* output, const void* data, int size) { const uint8_t* in = reinterpret_cast<const uint8_t*>(data); size_t in_size = size; size_t out_size; while (true) { upb::Status status; void* out = upb_ZeroCopyOutputStream_Next(output, &out_size, status.ptr()); if (out_size == 0) return false; if (in_size <= out_size) { memcpy(out, in, in_size); upb_ZeroCopyOutputStream_BackUp(output, out_size - in_size); return true; } memcpy(out, in, out_size); in += out_size; in_size -= out_size; } } int IoTest::ReadFromInput(upb_ZeroCopyInputStream* input, void* data, int size) { uint8_t* out = reinterpret_cast<uint8_t*>(data); size_t out_size = size; const void* in; size_t in_size = 0; while (true) { upb::Status status; in = upb_ZeroCopyInputStream_Next(input, &in_size, status.ptr()); if (in_size == 0) { return size - out_size; } if (out_size <= in_size) { memcpy(out, in, out_size); if (in_size > out_size) { upb_ZeroCopyInputStream_BackUp(input, in_size - out_size); } return size; // Copied all of it. } memcpy(out, in, in_size); out += in_size; out_size -= in_size; } } void IoTest::WriteString(upb_ZeroCopyOutputStream* output, const std::string& str) { EXPECT_TRUE(WriteToOutput(output, str.c_str(), str.size())); } void IoTest::ReadString(upb_ZeroCopyInputStream* input, const std::string& str) { std::unique_ptr<char[]> buffer(new char[str.size() + 1]); buffer[str.size()] = '\0'; EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size()); EXPECT_STREQ(str.c_str(), buffer.get()); } int IoTest::WriteStuff(upb_ZeroCopyOutputStream* output) { WriteString(output, "Hello world!\n"); WriteString(output, "Some te"); WriteString(output, "xt. Blah blah."); WriteString(output, "abcdefg"); WriteString(output, "01234567890123456789"); WriteString(output, "foobar"); const int result = upb_ZeroCopyOutputStream_ByteCount(output); EXPECT_EQ(result, 68); return result; } // Reads text from an input stream and expects it to match what WriteStuff() // writes. void IoTest::ReadStuff(upb_ZeroCopyInputStream* input, bool read_eof) { ReadString(input, "Hello world!\n"); ReadString(input, "Some text. "); ReadString(input, "Blah "); ReadString(input, "blah."); ReadString(input, "abcdefg"); EXPECT_TRUE(upb_ZeroCopyInputStream_Skip(input, 20)); ReadString(input, "foo"); ReadString(input, "bar"); EXPECT_EQ(upb_ZeroCopyInputStream_ByteCount(input), 68); if (read_eof) { uint8_t byte; EXPECT_EQ(ReadFromInput(input, &byte, 1), 0); } } int IoTest::WriteStuffLarge(upb_ZeroCopyOutputStream* output) { WriteString(output, "Hello world!\n"); WriteString(output, "Some te"); WriteString(output, "xt. Blah blah."); WriteString(output, std::string(100000, 'x')); // A very long string WriteString(output, std::string(100000, 'y')); // A very long string WriteString(output, "01234567890123456789"); const int result = upb_ZeroCopyOutputStream_ByteCount(output); EXPECT_EQ(result, 200055); return result; } // Reads text from an input stream and expects it to match what WriteStuff() // writes. void IoTest::ReadStuffLarge(upb_ZeroCopyInputStream* input) { ReadString(input, "Hello world!\nSome text. "); EXPECT_TRUE(upb_ZeroCopyInputStream_Skip(input, 5)); ReadString(input, "blah."); EXPECT_TRUE(upb_ZeroCopyInputStream_Skip(input, 100000 - 10)); ReadString(input, std::string(10, 'x') + std::string(100000 - 20000, 'y')); EXPECT_TRUE(upb_ZeroCopyInputStream_Skip(input, 20000 - 10)); ReadString(input, "yyyyyyyyyy01234567890123456789"); EXPECT_EQ(upb_ZeroCopyInputStream_ByteCount(input), 200055); uint8_t byte; EXPECT_EQ(ReadFromInput(input, &byte, 1), 0); } // =================================================================== TEST_F(IoTest, ArrayIo) { const int kBufferSize = 256; uint8_t buffer[kBufferSize]; upb::Arena arena; for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { auto output = upb_ChunkedOutputStream_New(buffer, kBufferSize, kBlockSizes[j], arena.ptr()); int size = WriteStuff(output); auto input = upb_ChunkedInputStream_New(buffer, size, kBlockSizes[j], arena.ptr()); ReadStuff(input); } } } TEST(ChunkedStream, SingleInput) { const int kBufferSize = 256; uint8_t buffer[kBufferSize]; upb::Arena arena; auto input = upb_ChunkedInputStream_New(buffer, kBufferSize, kBufferSize, arena.ptr()); const void* data; size_t size; upb::Status status; data = upb_ZeroCopyInputStream_Next(input, &size, status.ptr()); EXPECT_EQ(size, kBufferSize); data = upb_ZeroCopyInputStream_Next(input, &size, status.ptr()); EXPECT_EQ(data, nullptr); EXPECT_EQ(size, 0); EXPECT_TRUE(upb_Status_IsOk(status.ptr())); } TEST(ChunkedStream, SingleOutput) { const int kBufferSize = 256; uint8_t buffer[kBufferSize]; upb::Arena arena; auto output = upb_ChunkedOutputStream_New(buffer, kBufferSize, kBufferSize, arena.ptr()); size_t size; upb::Status status; void* data = upb_ZeroCopyOutputStream_Next(output, &size, status.ptr()); EXPECT_EQ(size, kBufferSize); data = upb_ZeroCopyOutputStream_Next(output, &size, status.ptr()); EXPECT_EQ(data, nullptr); EXPECT_EQ(size, 0); EXPECT_TRUE(upb_Status_IsOk(status.ptr())); } // Check that a zero-size input array doesn't confuse the code. TEST(ChunkedStream, InputEOF) { upb::Arena arena; char buf; auto input = upb_ChunkedInputStream_New(&buf, 0, 1, arena.ptr()); size_t size; upb::Status status; const void* data = upb_ZeroCopyInputStream_Next(input, &size, status.ptr()); EXPECT_EQ(data, nullptr); EXPECT_EQ(size, 0); EXPECT_TRUE(upb_Status_IsOk(status.ptr())); } // Check that a zero-size output array doesn't confuse the code. TEST(ChunkedStream, OutputEOF) { upb::Arena arena; char buf; auto output = upb_ChunkedOutputStream_New(&buf, 0, 1, arena.ptr()); size_t size; upb::Status status; void* data = upb_ZeroCopyOutputStream_Next(output, &size, status.ptr()); EXPECT_EQ(data, nullptr); EXPECT_EQ(size, 0); EXPECT_TRUE(upb_Status_IsOk(status.ptr())); } } // namespace } // namespace upb
3db7eafe719553166b64ab8ee2e495952b8c1ab2
fac846c24bbcc7aa84ca235ac32333ef95333ce7
/src/sprite.cpp
46dfc9e3866d27edfc2c585cfbc086fd923c77cd
[]
no_license
johnernaut/braincraft
c150bcc506a58c8c4ba3b4f602d84403fae8f869
5224f4c164be6a9804f692c3c9845db8bd94f07b
refs/heads/master
2020-04-05T23:41:41.945582
2015-02-17T13:40:39
2015-02-17T13:40:39
30,838,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
sprite.cpp
#include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "Sprite.h" Sprite::Sprite(SDL_Renderer *ren, std::string imagePath, int x, int y, int w, int h) { sRenderer = ren; SDL_Surface *img = IMG_Load(imagePath.c_str()); pSprite = SDL_CreateTextureFromSurface(sRenderer, img); SDL_FreeSurface(img); if (pSprite == nullptr) { SDL_Log("Failed to create sprite error: %s", SDL_GetError()); } // Set cropping properties sCrop.x = x; sCrop.y = y; sCrop.w = w; sCrop.h = h; // Set image size properties SDL_QueryTexture(pSprite, NULL, NULL, &sRect.w, &sRect.h); } Sprite::~Sprite() { SDL_DestroyTexture(pSprite); } void Sprite::Draw() { SDL_RenderCopy(sRenderer, pSprite, &sCrop, &sRect); } int Sprite::GetX() { return sRect.x; } int Sprite::GetY() { return sRect.y; } void Sprite::SetX(int x) { sRect.x = x; } void Sprite::SetY(int y) { sRect.y = y; } void Sprite::SetOrigin(int x, int y) { sRect.x = x; sRect.y = y; }
0edc76e28dc186a544ed3e4639b7de6d082efac9
f9f03edf48617e2dc512a812c030a4f3a07c03d2
/22_dfs.cpp
6fd5c4806dcb3ab989b15dad666e8b2d412889cd
[]
no_license
gitchaofang/leetcode
8d2769383e563788486dfa85a21d2df0c1c568d6
86907b9df994280e376e8c9f136fa8c37807ba2a
refs/heads/master
2021-08-08T17:46:50.384188
2020-12-16T06:30:59
2020-12-16T06:30:59
232,033,250
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
22_dfs.cpp
class Solution { public: void dfs(std::string str, const int& cnt, const int& n, std::vector<std::string>& res){ int len = str.size(); if(len == 2 * n){ if(cnt == n) res.push_back(str); return; } if(cnt < n) dfs(str + '(', cnt + 1, n, res); if(len - cnt < cnt) dfs(str + ')', cnt, n, res); return; } vector<string> generateParenthesis(int n) { std::vector<std::string> res; dfs("",0,n,res); return res; } };
d65f9b352cb4dc679d3369873b57607ebc818fcf
7a2918c7c5579e8e7ed8c8cd2412ba22adc27881
/Squar.cpp
8d4e995f6526d3909d0877358a4be5ea34a5072e
[]
no_license
mace707/Engine
056b0c84e4b71b697a0fb5b5de909b6ac8a57f8a
5b54c2a7a708c2b5e3d472d7a243e35717c4cb3f
refs/heads/master
2016-09-06T17:06:54.771856
2015-07-17T12:18:50
2015-07-17T12:18:50
35,770,562
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
Squar.cpp
#include "stdafx.h" #include "Squar.h" #include <OpenGl\glut.h> Squar::Squar ( ) { } Squar::~Squar ( ) { } void Squar::Draw ( int x1, int y1, int x2, int y2, Color col, bool token ) { glPushMatrix ( ); glBegin ( GL_QUADS ); glColor3f(col.R, col.G, col.B); if ( token ) { double x1f = x1 + 0.25; double x2f = x2 - 0.25; double y1f = y1 + 0.25; double y2f = y2 - 0.25; glVertex2f ( x1f, y1f ); glVertex2f ( x1f, y2f ); glVertex2f ( x2f, y2f ); glVertex2f ( x2f, y1f ); } else { glVertex2f ( x1, y1 ); glVertex2f ( x1, y2 ); glVertex2f ( x2, y2 ); glVertex2f ( x2, y1 ); } glEnd ( ); glPopMatrix ( ); }
1dc8d7120c6c51bf5a6a2e47d4e0830fea5b2ad4
76aab74b58991e2cf8076d6b4ed6f4deba1c57bd
/luogu/1025.cpp
6b0192edde07e5cb9e82212b06f4c8ec523ebb25
[]
no_license
StudyingFather/my-code
9c109660c16b18f9974d37a2a1d809db4d6ce50a
8d02be445ac7affad58c2d71f3ef602f3d2801f6
refs/heads/master
2023-08-16T23:17:10.817659
2023-08-04T11:31:40
2023-08-04T11:31:40
149,898,152
6
2
null
null
null
null
UTF-8
C++
false
false
223
cpp
1025.cpp
#include <stdio.h> int f[505][505]; int main() { int n,k; scanf("%d%d",&n,&k); f[0][0]=1; for(int i=1;i<=n;i++) for(int j=1;j<=k;j++) if(i>=j) f[i][j]=f[i-j][j]+f[i-1][j-1]; printf("%d",f[n][k]); return 0; }
e77128ccbe23627b37836ce66b179ea0db916e2b
e1c57f7e3f53bf0dede920f6cb7dddb6da6b1178
/Lab 1/src/wxGUI.cpp
d2f4ba6eddcca80516b85bb8e4c52ae3c7746103
[]
no_license
r-englund/SciVisLabs
7ffde3eb31e0947982328a6ba04e2bd7c8a54804
15ac5bf4998d6c3063b8cec7d5061d420524b208
refs/heads/master
2016-09-11T10:24:10.879240
2012-11-07T15:48:43
2012-11-07T15:48:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,052
cpp
wxGUI.cpp
#include "wxGUI.hh" #include "wxVTKRenderWindowInteractor.hh" #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkConeSource.h> #include <vtkCamera.h> #include <vtkProperty.h> enum { Menu_Quit = 1, Menu_About, Ctrl_Slider1, Ctrl_Slider2, Ctrl_Slider3, Ctrl_Slider4, Ctrl_Slider5, Ctrl_Slider6 }; #define MY_FRAME 101 #define MY_VTK_WINDOW 102 BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(Menu_Quit, MyFrame::OnQuit) EVT_MENU(Menu_About, MyFrame::OnAbout) EVT_COMMAND_SCROLL(Ctrl_Slider1, MyFrame::OnSlider1) EVT_COMMAND_SCROLL(Ctrl_Slider2, MyFrame::OnSlider2) EVT_COMMAND_SCROLL(Ctrl_Slider3, MyFrame::OnSlider3) EVT_COMMAND_SCROLL(Ctrl_Slider4, MyFrame::OnSlider4) EVT_COMMAND_SCROLL(Ctrl_Slider5, MyFrame::OnSlider5) EVT_COMMAND_SCROLL(Ctrl_Slider6, MyFrame::OnSlider6) // Connect events from new widgets here END_EVENT_TABLE() IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { MyFrame *frame = new MyFrame(_T("wxWindows-VTK App"), wxPoint(50, 50), wxSize(450, 340)); frame->Show(TRUE); SetTopWindow(frame); return TRUE; } MyFrame::MyFrame( const wxString& title, const wxPoint& pos, const wxSize& size ) : wxFrame( (wxFrame *)NULL, -1, title, pos, size ){ #ifdef __WXMAC__ wxApp::s_macAboutMenuItemId = Menu_About; #endif wxMenu *menuFile = new wxMenu(_T(""), wxMENU_TEAROFF); wxMenu *helpMenu = new wxMenu; helpMenu->Append( Menu_About, _T("&About...\tCtrl-A"), _T("Show about dialog") ); menuFile->Append( Menu_Quit, _T("E&xit\tAlt-X"), _T("Quit this program") ); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, _T("&File")); menuBar->Append(helpMenu, _T("&Help")); SetMenuBar(menuBar); CreateStatusBar(2); SetStatusText(_T("Drag the mouse in the frame above")); SetStatusText(_T("VTK/wx example"),1); // Widgets --- wxFlexGridSizer *m_sizer = new wxFlexGridSizer(1); SetSizer(m_sizer); m_pVTKWindow = new wxVTKRenderWindowInteractor(this, MY_VTK_WINDOW); m_pVTKWindow->UseCaptureMouseOn(); //m_pVTKWindow->DebugOn(); m_sizer->Add( m_pVTKWindow, 0, wxEXPAND ); wxSlider *m_slider1 = new wxSlider( this,Ctrl_Slider1, 50, 0, 100 ); m_sizer->Add( m_slider1, 0, wxEXPAND ); wxSlider *m_slider2 = new wxSlider( this,Ctrl_Slider2, 100, 0, 100 ); m_sizer->Add( m_slider2, 0, wxEXPAND ); wxSlider *m_slider3 = new wxSlider( this,Ctrl_Slider3, 8, 0, 64 ); m_sizer->Add( m_slider3, 0, wxEXPAND ); wxSlider *m_slider4 = new wxSlider( this,Ctrl_Slider4, 255, 0, 255 ); m_sizer->Add( m_slider4, 0, wxEXPAND ); wxSlider *m_slider5 = new wxSlider( this,Ctrl_Slider5, 255, 0, 255 ); m_sizer->Add( m_slider5, 0, wxEXPAND ); wxSlider *m_slider6 = new wxSlider( this,Ctrl_Slider6, 255, 0, 255 ); m_sizer->Add( m_slider6, 0, wxEXPAND ); // Add or remove widgets here // Connect their events to the event table above m_sizer->AddGrowableCol( 0, 1 ); m_sizer->AddGrowableRow( 0, 1 ); // Construct VTK --- ConstructVTK(); } MyFrame::~MyFrame() { if(m_pVTKWindow) m_pVTKWindow->Delete(); DestroyVTK(); } void MyFrame::ConstructVTK() { pRenderer = vtkRenderer::New(); pConeMapper = vtkPolyDataMapper::New(); pConeActor = vtkActor::New(); pConeSource = vtkConeSource::New(); // connect the render window and wxVTK window pRenderWindow = m_pVTKWindow->GetRenderWindow(); // connect renderer and render window and configure render window pRenderWindow->AddRenderer(pRenderer); // initialize cone pConeSource->SetResolution(8); // connect pipeline pConeMapper->SetInput(pConeSource->GetOutput()); pConeActor->SetMapper(pConeMapper); pRenderer->AddActor(pConeActor); // configure renderer pRenderer->SetBackground(0,0,0); pRenderer->GetActiveCamera()->Elevation(30.0); pRenderer->GetActiveCamera()->Azimuth(30.0); pRenderer->GetActiveCamera()->Zoom(1.0); pRenderer->GetActiveCamera()->SetClippingRange(1,1000); } void MyFrame::DestroyVTK() { if (pRenderer != 0) pRenderer->Delete(); if (pConeMapper != 0) pConeMapper->Delete(); if (pConeActor != 0) pConeActor->Delete(); if (pConeSource != 0) pConeSource->Delete(); } // event handlers void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { Close(TRUE); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxString msg; msg.Printf( _T("This is the about dialog of wx-vtk sample.\n") ); wxMessageBox( msg, _T("About wx-vtk"), wxOK | wxICON_INFORMATION, this ); } void MyFrame::OnSlider1(wxScrollEvent& event){ pConeSource->SetRadius( event.GetPosition() / 100.0 ); m_pVTKWindow->Render(); SetStatusText(_T("Updated cone radius.")); } void MyFrame::OnSlider2(wxScrollEvent& event){ pConeSource->SetHeight( event.GetPosition() / 100.0 ); m_pVTKWindow->Render(); SetStatusText(_T("Updated cone height.")); } void MyFrame::OnSlider3(wxScrollEvent& event){ pConeSource->SetResolution( event.GetPosition() ); m_pVTKWindow->Render(); SetStatusText(_T("Updated cone resolution.")); } void MyFrame::OnSlider4(wxScrollEvent& event){ double c[3]; pConeActor->GetProperty()->GetColor(c); c[0] = event.GetPosition() / 255.0; pConeActor->GetProperty()->SetColor(c); m_pVTKWindow->Render(); SetStatusText(_T("Updated red color.")); } void MyFrame::OnSlider5(wxScrollEvent& event){ double c[3]; pConeActor->GetProperty()->GetColor(c); c[1] = event.GetPosition() / 255.0; pConeActor->GetProperty()->SetColor(c); m_pVTKWindow->Render(); SetStatusText(_T("Updated green color.")); } void MyFrame::OnSlider6(wxScrollEvent& event){ double c[3]; pConeActor->GetProperty()->GetColor(c); c[2] = event.GetPosition() / 255.0; pConeActor->GetProperty()->SetColor(c); m_pVTKWindow->Render(); SetStatusText(_T("Updated blue color.")); }
766f9f13e146d354d12f7bb9d9f8c616fc7e763d
5d6e55bfebdbf398536aefbc9405094c5f2c223a
/lab2/task2/run_queue.h
d5d728bbe0cd7a16afd61c6ff0170529601e78de
[]
no_license
ilyakrasnou/labsAVS
1f6230b49259cfcb82d381a20ec1308945e61af7
ddf9ab1fe58f8268a69af03218b740e266ff9d57
refs/heads/master
2020-08-04T22:35:42.627775
2019-12-20T18:47:18
2019-12-20T18:47:18
212,300,021
0
1
null
null
null
null
UTF-8
C++
false
false
3,541
h
run_queue.h
#ifndef LAB2_RUN_QUEUE_H #define LAB2_RUN_QUEUE_H #include <iostream> #include <thread> #include <vector> #include <atomic> #include "dynamic_queue.h" #include "fixed_atomic_queue.h" #include "fixed_mutex_queue.h" #include "lock_free_queue.h" const std::vector<int> producer_num = {1, 2, 4}; const std::vector<int> consumer_num = {1, 2, 4}; const std::vector<size_t> queue_size = {1, 4, 16}; const int NUM_TASK = 1 << 20; template <typename T> void test_queue(IQueue<T> &queue, int producer_n, int consumer_n) { int task_num = NUM_TASK; std::atomic_int sum(0); std::vector<std::thread> producers(producer_n); std::vector<std::thread> consumers(consumer_n); auto start = std::chrono::high_resolution_clock::now(); for (auto& thread: producers) thread = std::thread([&task_num, &queue]() { for (int i = 0; i < task_num; ++i) queue.push(1); }); for (auto& thread: consumers) thread = std::thread([&sum, &queue, task_num, producer_n]() { T v; while (sum.load() < producer_n * task_num) { sum += queue.pop(v); } }); for (auto& thread: producers) { if (thread.joinable()) thread.join(); } for (auto& thread: consumers) { if (thread.joinable()) thread.join(); } auto end = std::chrono::high_resolution_clock::now(); std::cout <<" " << sum.load() << ", time: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1e-9 << " sec" << std::endl << std::endl; } template <typename T> void run_dynamic_queue() { for (int producer_n : producer_num) for (int consumer_n : consumer_num) { std::cout << "Result for producer_num: " << producer_n << ", consumer_num: " << consumer_n << std::endl; DynamicQueue<T> q; test_queue<T>( q, producer_n, consumer_n); } } template <typename T> void run_fixed_mutex_queue() { for (auto size : queue_size) for (int producer_n : producer_num) for (int consumer_n : consumer_num) { std::cout << "Result for producer_num: " << producer_n << ", consumer_num: " << consumer_n << ", size: " << size << std::endl; FixedMutexQueue<T> q(size); test_queue<T>(q, producer_n, consumer_n); } } template <typename T> void run_fixed_atomic_queue() { for (auto size : queue_size) for (int producer_n : producer_num) for (int consumer_n : consumer_num) { std::cout << "Result for producer_num: " << producer_n << ", consumer_num: " << consumer_n << ", size: " << size << std::endl; // std::cout << "what? " << std::endl; FixedAtomicQueue<T> q(size); test_queue<T>(q, producer_n, consumer_n); } } template <typename T> void run_lock_free_queue() { for (auto size : queue_size) for (int producer_n : producer_num) for (int consumer_n : consumer_num) { std::cout << "Result for producer_num: " << producer_n << ", consumer_num: " << consumer_n << ", size: " << size << std::endl; LockFreeQueue<T> q; test_queue<T>(q, producer_n, consumer_n); } } #endif //LAB2_RUN_QUEUE_H
12c0901a0ee06c2d2beab88609a50996059dc0d9
20c52c1f902902f5bbd0993958407acb3df3b8ef
/src/medianOfArrays.h
6bbd00816c1c8cfe03a802c9bef3ebff95615de0
[]
no_license
CoreyUWK/ByteByByte-Cplus
f246baa2ccd0b06d004c218fce1f0ff7369e83e2
175de547c2672dad4ce96fe8515517568d5246fb
refs/heads/master
2023-02-19T05:17:13.195841
2023-02-07T21:51:34
2023-02-07T21:51:34
217,896,589
0
0
null
null
null
null
UTF-8
C++
false
false
590
h
medianOfArrays.h
/* * medianOfArrays.h * * Created on: 2019-09-06 * Author: ckirsch */ #ifndef MEDIANOFARRAYS_H_ #define MEDIANOFARRAYS_H_ #include <vector> using namespace std; class SubArray { int *arr; int start; int size; public: SubArray(int arr[], int size); void updateRange(int start, int end); double getMedian(int &medianIndex1, int &medianIndex2); int *getArray() { return arr; } int getSize() { return size; } int getStart() { return start; } int getEnd() { return start + size - 1; } }; void medianOfArraysMain(); #endif /* MEDIANOFARRAYS_H_ */
7aa911ad7f041df04988bbc55a4bdf96edd20a00
29b81bdc013d76b057a2ba12e912d6d4c5b033ef
/boost/include/boost/gil/extension/dynamic_image/any_image.hpp
3dc45d8d196ded062ed6ff6deee334deefaf8ea1
[]
no_license
GSIL-Monitor/third_dependences
864d2ad73955ffe0ce4912966a4f0d1c60ebd960
888ebf538db072a92d444a9e5aaa5e18b0f11083
refs/heads/master
2020-04-17T07:32:49.546337
2019-01-18T08:47:28
2019-01-18T08:47:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
any_image.hpp
version https://git-lfs.github.com/spec/v1 oid sha256:08838f2d922925a2dceec1621982ebe1412d24f35fd0a7a43f7b64c87835e811 size 6295
d87d9d3863a9bb68074071e348da95c58825253a
34fec248091fbd431bd6631363644b611b0411c8
/Cells.h
f4ae58399adf80a13d65b7ecfd15c89d246ccb1b
[]
no_license
ph-altiv/ConsoleSapeur
74979bb1129e74d97fe86c1ded93bf878e4d2179
679c45901151a23f699a572c9629acc7873bd316
refs/heads/master
2021-01-10T05:36:17.723871
2016-03-24T17:22:31
2016-03-24T17:22:31
54,543,275
0
0
null
null
null
null
UTF-8
C++
false
false
621
h
Cells.h
#pragma once namespace cells { constexpr int CELLTYPENAME_QUANTITY = 12; enum CellTypeName { ZERO_CELL = 0, ONE_CELL = 1, TWO_CELL = 2, THREE_CELL = 3, FOUR_CELL = 4, FIVE_CELL = 5, SIX_CELL = 6, SEVEN_CELL = 7, EIGHT_CELL = 8, HIDDEN_CELL = 9, MARKED_CELL = 10, MINED_CELL = 11 }; struct CellParameters { unsigned short color; char symbol; }; class GetCellParameters { public: GetCellParameters(); CellParameters operator() (const CellTypeName type) const; CellParameters operator() (const int type) const; } #ifndef CELLS_CPP static const GetCellParameters #endif ; }
36ca0d22d021cae2b38dfea474f254aead192e6c
6f05f7d5a67b6bb87956a22b988067ec772ba966
/data/test/cpp/86cc905cb6cfcc275204460194fdb36cd021004eCanvas.h
86cc905cb6cfcc275204460194fdb36cd021004e
[ "MIT" ]
permissive
harshp8l/deep-learning-lang-detection
93b6d24a38081597c610ecf9b1f3b92c7d669be5
2a54293181c1c2b1a2b840ddee4d4d80177efb33
refs/heads/master
2020-04-07T18:07:00.697994
2018-11-29T23:21:23
2018-11-29T23:21:23
158,597,498
0
0
MIT
2018-11-21T19:36:42
2018-11-21T19:36:41
null
UTF-8
C++
false
false
677
h
86cc905cb6cfcc275204460194fdb36cd021004eCanvas.h
#include "Sample.h" class Canvas { public: static Sample currSample; float width; float height; Canvas() { } Canvas(float width, float height) : width(width), height(height) { } static Sample getCurrSample(); bool getSample(Sample* sample); }; Sample Canvas::getCurrSample() { return Sample(currSample.x, currSample.y); } bool Canvas::getSample(Sample* sample) { if (sample->x == (width - 1) && sample->y == (height - 1)) { return false; } if (sample->x == (width - 1)) { currSample.x = 0; currSample.y++; return true; } currSample.x++; return true; } Sample Canvas::currSample = Sample(0,0);
81f416c7a591c1dd95afc92e800c54f46202a82b
07be39b45a4c8a6f2812117f34b5fe9874702f9b
/2028.cpp
9dfcc0a08e1db70cc9ec946336fe8184df37837b
[]
no_license
FilipeMazzon/uri-problem-solutions
f2d9222d5506cf273901b984ca1d1f64545414da
5eb4328ff1c9d1d48672a422d9ae4358a90e3739
refs/heads/master
2021-05-16T00:44:40.471326
2017-10-15T02:52:06
2017-10-15T02:52:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
484
cpp
2028.cpp
#include<bits/stdc++.h> using namespace std; int main() { int y,u=0; while(cin>>y){ int num=1; u++; num += ((y*(y + 1)) / 2); if(y == 0) printf("Caso %d: %d numero\n", u, num); else printf("Caso %d: %d numeros\n", u, num); printf("0"); for(int i=1; i<=y; i++) { for(int j=1; j<=i; j++) printf(" %d", i); } cout<<endl<<endl; } }
e0d3db5dcc42881e8f80fbcb951290d0d400d478
b3f41792c04cd973c747d8d5488512ed9ae08c03
/longest_Str_Withoutrepeat/LSWR_C++.cpp
b6e522f73d4cb44a1c706e5e2e1bd65ae08e36bd
[]
no_license
hf532304/Leetcode
21ca7c25b11ed8355ebcd3a1cedba1baa761e226
1b20272b8dae5f18e4a5b114e664be9171c6b2bf
refs/heads/master
2020-03-28T17:56:51.887564
2018-09-19T02:33:52
2018-09-19T02:33:52
148,838,475
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
LSWR_C++.cpp
class Solution { public: int lengthOfLongestSubstring(string s) { int res = 0; int maxlen = 0; int start = 0; unordered_map<char,int> Hashmap; int len = 0; int j = 0; unordered_map<char,int>::iterator repeat; while(j < s.length()){ repeat = Hashmap.find(s[j]); if(repeat != Hashmap.end()){ start = max(start,Hashmap.at(s[j]) + 1); } Hashmap[s[j]] = j; maxlen = max(maxlen,j - start + 1); j++; } return maxlen; } };
30279b7c3cd5c07b5c22613a91873112804cd3a1
cae8beb7de70e4361a5071e33b023b3cd4f3031e
/BomberMan/monster3.cpp
069719afda74eea94a95e48ee8a056331e4aad60
[]
no_license
AmazingPangWei/BomberMan
78cfd471223a83e47a4978a71e267d82d8c0f24b
31ff4b6a6a25b57c42c4492d7a5efca06546185d
refs/heads/master
2020-04-25T08:40:57.312247
2019-02-26T07:57:47
2019-02-26T07:57:47
172,655,153
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
monster3.cpp
#include "monster3.h" Monster3::Monster3(QWidget *parent):Monster(parent) { movie = new QMovie(); speed = 15; pix.load(":/new/prefix1/素材/第一关怪物(左).png"); this->setPixmap(pix); } void Monster3::RightMove() { pix.load(":/new/prefix1/素材/第一关怪物(右).png"); this->setPixmap(pix); this->move(this->x()+speed,this->y()); } void Monster3::LeftMove() { pix.load(":/new/prefix1/素材/第一关怪物(左).png"); this->setPixmap(pix); this->move(this->x()-speed,this->y()); } void Monster3::UpMove() { this->move(this->x(),this->y()-speed); } void Monster3::DownMove() { this->move(this->x(),this->y()+speed); } void Monster3::Dead() { movie->setFileName(":/new/prefix1/素材/死亡.gif"); setMovie(movie); movie->start(); }
6e2d5c472fa93eea77c5b6ac80a88012f2b7f969
170dd12bfcb597333ec8fb0a73c997896e6afb42
/cpg/cpgsyntax/Composite.hpp
ab57cc81fea1bf4d154ae9529f01a797b2c524f1
[]
no_license
slaakko/cminor
ffce61c4a8d202dadc80f85e2653b313a2d346bb
efea239afc9ebfc5d9ace566dce1113daa88c89f
refs/heads/master
2020-05-31T06:01:03.343170
2017-06-29T13:34:37
2017-06-29T13:34:37
69,146,774
2
0
null
null
null
null
UTF-8
C++
false
false
957
hpp
Composite.hpp
#ifndef Composite_hpp_5596 #define Composite_hpp_5596 #include <cminor/pl/Grammar.hpp> #include <cminor/pl/Keyword.hpp> #include <cminor/pl/Scope.hpp> #include <cminor/pl/Parser.hpp> namespace cpg { namespace syntax { class CompositeGrammar : public cminor::parsing::Grammar { public: static CompositeGrammar* Create(); static CompositeGrammar* Create(cminor::parsing::ParsingDomain* parsingDomain); cminor::parsing::Parser* Parse(const char* start, const char* end, int fileIndex, const std::string& fileName, cminor::parsing::Scope* enclosingScope); private: CompositeGrammar(cminor::parsing::ParsingDomain* parsingDomain_); virtual void CreateRules(); virtual void GetReferencedGrammars(); class AlternativeRule; class SequenceRule; class DifferenceRule; class ExclusiveOrRule; class IntersectionRule; class ListRule; class PostfixRule; }; } } // namespace cpg.syntax #endif // Composite_hpp_5596
cf9b6c0e4c0970a877359212633fdba0839b7eac
93949503792cc85b4d85436500f67853f79ffe0c
/includes/ui/Button.hpp
20647237811544e24aab066955e66fdb0b825141
[]
no_license
simtr/tptpp
3b654405258c0f8ea7667daee29143a79c804346
a6608027d8283c4648b5f06e26d793f3a72d4b5c
refs/heads/master
2021-01-22T05:54:56.294123
2011-10-24T00:09:51
2011-10-24T00:09:51
2,038,729
3
0
null
null
null
null
UTF-8
C++
false
false
918
hpp
Button.hpp
#ifndef UI_BUTTON_HPP #define UI_BUTTON_HPP #include <SFML/Graphics.hpp> #include "Component.hpp" #include <string> namespace ui { class Button : public Component { public: Button(int x, int y, int width, int height, const std::string& buttonText); bool Toggleable; std::string ButtonText; virtual void OnMouseClick(int x, int y, unsigned int button); virtual void OnMouseUnclick(int x, int y, unsigned int button); virtual void OnMouseUp(int x, int y, unsigned int button); virtual void OnMouseEnter(int x, int y, int dx, int dy); virtual void OnMouseLeave(int x, int y, int dx, int dy); virtual void Draw(void* userdata); inline bool GetState() { return state; } virtual void DoAction(); //action of button what ever it may be protected: bool isButtonDown, state, isMouseInside; }; } #endif
88419b6d23948be962d0687cf8d09b62d8d8fdfb
ed6cc29968179d13bb30c73dbf2be2fb6469d495
/11. des/PallaUpdate 11.12.2017/PP Backup/006 Type & Topping/UI/UserInputUI.h
34b4ca80e37d7b5cf73759380e1354451c933319
[]
no_license
sindri69/pizza420
e0880eea7eb0dbdeabae3dc675dba732a1778d90
a0f78b59b5830ff67e9b5456a6e6d229869628f5
refs/heads/master
2021-08-28T14:59:32.423484
2017-12-12T14:19:05
2017-12-12T14:19:05
112,332,570
0
0
null
null
null
null
UTF-8
C++
false
false
2,005
h
UserInputUI.h
#ifndef USERINPUTUI_H #define USERINPUTUI_H #include <string> #include <iostream> #include <sstream> /// for StringStream in the convert functions using namespace std; class UserInputUI /// This class's job is getting user input, keeps cout & cin in other classes to a minimum :] { public: UserInputUI(); /// Here we take a string and change all characters to lowercase or uppercase string convert_StringToLowerCase(string s); string convert_StringToUpperCase(string s); /// Here we convert strings to numbers or numbers to strings (note: http://www.cplusplus.com/forum/articles/9645/) string convert_DoubleToString(double d); string convert_IntegerToString(int i); double convert_StringToDouble(string s); int convert_StringToInteger(string s); /// Here we ask the user a question, and return the answer as a number int getAnswer_Integer(string question); double getAnswer_Double(string question); /// Here we are checking if the answer is an integer bool answerIsInteger(string answer); /// Here the user is asked the question repeatedly until he replies with yes or no bool getAnswer_Yes_Or_No(string question); /// Here we ask a question and return the answer as a string string getAnswer(string question); /// Here we ask the user the question repeatedly until he gives a valid answer, we then return the answer, can have up to 6 valid answers string getAnswer(string question, string validAnswer); string getAnswer(string q, string a1, string a2); string getAnswer(string q, string a1, string a2, string a3); string getAnswer(string q, string a1, string a2, string a3, string a4); string getAnswer(string q, string a1, string a2, string a3, string a4, string a5); string getAnswer(string q, string a1, string a2, string a3, string a4, string a5, string a6); }; #endif // USERINPUTUI_H
19109306b9f65b5e247cca5a7ede881fabb691a4
b91e35135c06667bd5d3b2352568ac8b6e184cef
/src/example_lib/example_lib.h
9abf1a23fe8d6d3783a8136ce860bb9684649692
[ "MIT" ]
permissive
ryanmcdermott/bazel-cpp-template
4826d374118fb6c7aa6dda69c684ef3e6d3a9367
3349608c140afe63ff92ee2cc218855af9da9ec3
refs/heads/master
2022-11-18T01:40:31.596353
2020-07-07T01:33:30
2020-07-07T01:33:30
270,453,396
1
0
null
null
null
null
UTF-8
C++
false
false
144
h
example_lib.h
#ifndef SRC_EXAMPLE_LIB_EXAMPLE_LIB_H #define SRC_EXAMPLE_LIB_EXAMPLE_LIB_H #include <vector> std::vector<int> foobar(unsigned int n); #endif
1d18e969b258e5623a0f749d8c6a1eceb9e5b066
a3d0f92c3fd95c9d0d844405ac80a246ceb86c03
/src/database/vtk/generated/SoVtkDataSetMapper.h
fc7bcf77cc5ab5404705a82a02ec37fbba2fc2ce
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JoonVan/xip-libraries
79cc97e84ea45e30e0dc61fd8a98503a36fe9194
9f0fef66038b20ff0c81c089d7dd0038e3126e40
refs/heads/master
2020-12-20T18:49:48.942407
2013-06-25T20:57:19
2013-06-25T20:57:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,136
h
SoVtkDataSetMapper.h
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * \brief * \author Sylvain Jaume, Francois Huguet */ # ifndef SO_VTK_DATASETMAPPER_H_ # define SO_VTK_DATASETMAPPER_H_ # include <Inventor/engines/SoSubEngine.h> # include "xip/inventor/vtk/SoSFVtkAlgorithmOutput.h" # include "xip/inventor/vtk/SoSFVtkObject.h" # include "vtkDataSetMapper.h" # include "Inventor/fields/SoSFVec2f.h" # include "Inventor/fields/SoSFInt32.h" # include "Inventor/fields/SoSFFloat.h" class SoVtkDataSetMapper : public SoEngine { SO_ENGINE_HEADER( SoVtkDataSetMapper ); public: /// Constructor SoVtkDataSetMapper(); /// Class Initialization static void initClass(); // Inputs /// ScalarRange SoSFVec2f ScalarRange; /// ResolveCoincidentTopology SoSFInt32 ResolveCoincidentTopology; /// ImmediateModeRendering SoSFInt32 ImmediateModeRendering; /// ScalarMode SoSFInt32 ScalarMode; /// GlobalImmediateModeRendering SoSFInt32 GlobalImmediateModeRendering; /// ClippingPlanes of type vtkPlaneCollection SoSFVtkObject ClippingPlanes; /// ResolveCoincidentTopologyZShift SoSFFloat ResolveCoincidentTopologyZShift; /// Input data of type vtkDataSet SoSFVtkObject Input; /// Input connection SoSFVtkAlgorithmOutput InputConnection; /// UseLookupTableScalarRange SoSFInt32 UseLookupTableScalarRange; /// ScalarMaterialMode SoSFInt32 ScalarMaterialMode; /// LookupTable of type vtkScalarsToColors SoSFVtkObject LookupTable; /// ScalarVisibility SoSFInt32 ScalarVisibility; /// InterpolateScalarsBeforeMapping SoSFInt32 InterpolateScalarsBeforeMapping; /// Static SoSFInt32 Static; /// RenderTime SoSFFloat RenderTime; /// ColorMode SoSFInt32 ColorMode; // Outputs /// SoSFVtkObject of type vtkPlaneCollection SoEngineOutput oClippingPlanes; /// SoSFVtkAlgorithmOutput SoEngineOutput OutputPort; /// SoSFVtkObject of type vtkScalarsToColors SoEngineOutput oLookupTable; /// SoSFVtkObject of type DataSetMapper SoEngineOutput Output; protected: /// Destructor ~SoVtkDataSetMapper(); /// Evaluate Function virtual void evaluate(); /// inputChanged Function virtual void inputChanged(SoField *); /// reset Function virtual void reset(); /// vtkPlaneCollection SoVtkObject *mClippingPlanes; /// vtkAlgorithm SoVtkAlgorithmOutput *mOutputPort; /// vtkScalarsToColors SoVtkObject *mLookupTable; /// vtkDataSetMapper SoVtkObject *mOutput; private: vtkDataSetMapper* mObject; /// addCalled checks if the Add*() method has been called bool addCalled; }; #endif // SO_VTK_DATASETMAPPER_H_
668bd40e1908cf7681d6caddc207a645f8fe0449
1f902e98de99596e36ba017ce3907828b99a3c1f
/libs/androidfw/tests/Config_test.cpp
698c36f0930139732cf2ee8500e081a01de2d26c
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
aosp-mirror/platform_frameworks_base
c98112233373c83586fb1bf4d7ac256e5521b11d
942d47b019852409865ee53a189b09cc0743dff1
refs/heads/main
2023-08-29T10:34:14.756209
2023-08-29T07:02:44
2023-08-29T07:02:44
65,885
4,479
2,590
NOASSERTION
2023-08-08T07:25:50
2008-10-21T18:20:37
Java
UTF-8
C++
false
false
7,063
cpp
Config_test.cpp
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "androidfw/ResourceTypes.h" #include "utils/Log.h" #include "utils/String8.h" #include "utils/Vector.h" #include "TestHelpers.h" #include "gtest/gtest.h" namespace android { static ResTable_config selectBest(const ResTable_config& target, const Vector<ResTable_config>& configs) { ResTable_config bestConfig; memset(&bestConfig, 0, sizeof(bestConfig)); const size_t configCount = configs.size(); for (size_t i = 0; i < configCount; i++) { const ResTable_config& thisConfig = configs[i]; if (!thisConfig.match(target)) { continue; } if (thisConfig.isBetterThan(bestConfig, &target)) { bestConfig = thisConfig; } } return bestConfig; } static ResTable_config buildDensityConfig(int density) { ResTable_config config; memset(&config, 0, sizeof(config)); config.density = uint16_t(density); config.sdkVersion = 4; return config; } TEST(ConfigTest, shouldSelectBestDensity) { ResTable_config deviceConfig; memset(&deviceConfig, 0, sizeof(deviceConfig)); deviceConfig.density = ResTable_config::DENSITY_XHIGH; deviceConfig.sdkVersion = 21; Vector<ResTable_config> configs; ResTable_config expectedBest = buildDensityConfig(ResTable_config::DENSITY_HIGH); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); expectedBest = buildDensityConfig(ResTable_config::DENSITY_XXHIGH); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); expectedBest = buildDensityConfig(int(ResTable_config::DENSITY_XXHIGH) - 20); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); configs.add(buildDensityConfig(int(ResTable_config::DENSITY_HIGH) + 20)); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); configs.add(buildDensityConfig(int(ResTable_config::DENSITY_XHIGH) - 1)); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); expectedBest = buildDensityConfig(ResTable_config::DENSITY_XHIGH); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); expectedBest = buildDensityConfig(ResTable_config::DENSITY_ANY); expectedBest.sdkVersion = 21; configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); } TEST(ConfigTest, shouldSelectBestDensityWhenNoneSpecified) { ResTable_config deviceConfig; memset(&deviceConfig, 0, sizeof(deviceConfig)); deviceConfig.sdkVersion = 21; Vector<ResTable_config> configs; configs.add(buildDensityConfig(ResTable_config::DENSITY_HIGH)); ResTable_config expectedBest = buildDensityConfig(ResTable_config::DENSITY_MEDIUM); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); expectedBest = buildDensityConfig(ResTable_config::DENSITY_ANY); configs.add(expectedBest); ASSERT_EQ(expectedBest, selectBest(deviceConfig, configs)); } TEST(ConfigTest, shouldMatchRoundQualifier) { ResTable_config deviceConfig; memset(&deviceConfig, 0, sizeof(deviceConfig)); ResTable_config roundConfig; memset(&roundConfig, 0, sizeof(roundConfig)); roundConfig.screenLayout2 = ResTable_config::SCREENROUND_YES; EXPECT_FALSE(roundConfig.match(deviceConfig)); deviceConfig.screenLayout2 = ResTable_config::SCREENROUND_YES; EXPECT_TRUE(roundConfig.match(deviceConfig)); deviceConfig.screenLayout2 = ResTable_config::SCREENROUND_NO; EXPECT_FALSE(roundConfig.match(deviceConfig)); ResTable_config notRoundConfig; memset(&notRoundConfig, 0, sizeof(notRoundConfig)); notRoundConfig.screenLayout2 = ResTable_config::SCREENROUND_NO; EXPECT_TRUE(notRoundConfig.match(deviceConfig)); } TEST(ConfigTest, RoundQualifierShouldHaveStableSortOrder) { ResTable_config defaultConfig; memset(&defaultConfig, 0, sizeof(defaultConfig)); ResTable_config longConfig = defaultConfig; longConfig.screenLayout = ResTable_config::SCREENLONG_YES; ResTable_config longRoundConfig = longConfig; longRoundConfig.screenLayout2 = ResTable_config::SCREENROUND_YES; ResTable_config longRoundPortConfig = longConfig; longRoundPortConfig.orientation = ResTable_config::ORIENTATION_PORT; EXPECT_TRUE(longConfig.compare(longRoundConfig) < 0); EXPECT_TRUE(longConfig.compareLogical(longRoundConfig) < 0); EXPECT_TRUE(longRoundConfig.compare(longConfig) > 0); EXPECT_TRUE(longRoundConfig.compareLogical(longConfig) > 0); EXPECT_TRUE(longRoundConfig.compare(longRoundPortConfig) < 0); EXPECT_TRUE(longRoundConfig.compareLogical(longRoundPortConfig) < 0); EXPECT_TRUE(longRoundPortConfig.compare(longRoundConfig) > 0); EXPECT_TRUE(longRoundPortConfig.compareLogical(longRoundConfig) > 0); } TEST(ConfigTest, ScreenShapeHasCorrectDiff) { ResTable_config defaultConfig; memset(&defaultConfig, 0, sizeof(defaultConfig)); ResTable_config roundConfig = defaultConfig; roundConfig.screenLayout2 = ResTable_config::SCREENROUND_YES; EXPECT_EQ(defaultConfig.diff(roundConfig), ResTable_config::CONFIG_SCREEN_ROUND); } TEST(ConfigTest, RoundIsMoreSpecific) { ResTable_config deviceConfig; memset(&deviceConfig, 0, sizeof(deviceConfig)); deviceConfig.screenLayout2 = ResTable_config::SCREENROUND_YES; deviceConfig.screenLayout = ResTable_config::SCREENLONG_YES; ResTable_config targetConfigA; memset(&targetConfigA, 0, sizeof(targetConfigA)); ResTable_config targetConfigB = targetConfigA; targetConfigB.screenLayout = ResTable_config::SCREENLONG_YES; ResTable_config targetConfigC = targetConfigB; targetConfigC.screenLayout2 = ResTable_config::SCREENROUND_YES; EXPECT_TRUE(targetConfigB.isBetterThan(targetConfigA, &deviceConfig)); EXPECT_TRUE(targetConfigC.isBetterThan(targetConfigB, &deviceConfig)); } TEST(ConfigTest, ScreenIsWideGamut) { ResTable_config defaultConfig; memset(&defaultConfig, 0, sizeof(defaultConfig)); ResTable_config wideGamutConfig = defaultConfig; wideGamutConfig.colorMode = ResTable_config::WIDE_COLOR_GAMUT_YES; EXPECT_EQ(defaultConfig.diff(wideGamutConfig), ResTable_config::CONFIG_COLOR_MODE); } TEST(ConfigTest, ScreenIsHdr) { ResTable_config defaultConfig; memset(&defaultConfig, 0, sizeof(defaultConfig)); ResTable_config hdrConfig = defaultConfig; hdrConfig.colorMode = ResTable_config::HDR_YES; EXPECT_EQ(defaultConfig.diff(hdrConfig), ResTable_config::CONFIG_COLOR_MODE); } } // namespace android.
87ca554e92bfed146799b129d532b76b2c8d050f
ed649693468835126ae0bc56a9a9745cbbe02750
/win8_apps/cpp/Basic/Basic_Service/BasicService/AllJoynObjects.h
d02f62c21da128afd0c2f72e88238dcd62918413
[]
no_license
tkellogg/alljoyn-core
982304d78da73f07f888c7cbd56731342585d9a5
931ed98b3f5e5dbd40ffb529a78825f28cc59037
refs/heads/master
2020-12-25T18:22:32.166135
2014-07-17T13:56:18
2014-07-17T13:58:56
21,984,205
2
1
null
null
null
null
UTF-8
C++
false
false
4,923
h
AllJoynObjects.h
//----------------------------------------------------------------------- // <copyright file="AllJoynObjects.h" company="AllSeen Alliance."> // Copyright (c) 2012, AllSeen Alliance. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // </copyright> //----------------------------------------------------------------------- #pragma once #include "MainPage.xaml.h" using namespace BasicService; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Interop; using namespace AllJoyn; namespace AllJoynObjects { // Encapsulation object for dispatcher to use when printing message to UI [Windows::Foundation::Metadata::WebHostHiddenAttribute] public ref class ArgumentObject sealed { public: ArgumentObject(Platform::String ^ msg, TextBox ^ tb); void OnDispactched(); private: Platform::String ^ text; TextBox ^ textBox; }; // Bus Object which implements the 'cat' interface and handles its method calls from clients public ref class BasicSampleObject sealed { public: BasicSampleObject::BasicSampleObject(BusAttachment ^ busAtt, Platform::String ^ path); // Concatenate the two input strings and reply to caller with the result. void BasicSampleObject::Cat(InterfaceMember ^ member, Message ^ msg); property BusObject ^ GetBusObject { BusObject ^ get(); } private: BusObject ^ busObject; //Primary bus object implementing interface over the bus }; // Bus Listener which handles all bus events of interest public ref class MyBusListener sealed { public: MyBusListener(BusAttachment ^ busAtt); // Called by the bus when an external bus is discovered that is advertising a well-known // name that this attachment has registered interest in via a DBus call to // org.alljoyn.Bus.FindAdvertisedName void FoundAdvertisedName(Platform::String ^ wellKnownName, TransportMaskType transport, Platform::String ^ namePrefix); // Called by the bus when an advertisement previously reported through FoundName has become // unavailable. void LostAdvertisedName(Platform::String ^ wellKnownName, TransportMaskType transport, Platform::String ^ namePrefix); // Called when the owner of a well-known name changes void NameOwnerChanged(Platform::String ^ busName, Platform::String ^ previousOwner, Platform::String ^ newOwner); // Called when there's been a join session request from the client bool AcceptSessionJoiner(unsigned short sessionPort, Platform::String ^ joiner, SessionOpts ^ sessionOpts); // Called when a session has been joined by client void SessionJoined(unsigned short sessionPort, unsigned int sessId, Platform::String ^ joiner); // Called when bus attachment has been disconnected from the D-Bus void BusDisconnected(); // Called when bus attachment is stopping void BusStopping(); // Called by the bus when an existing session becomes disconnected. void SessionLost(unsigned int sessId); // Called by the bus when a member of a multipoint session is added. void SessionMemberAdded(unsigned int sessionId, Platform::String ^ uniqueName); // Called by the bus when a member of a multipoint session is removed. void SessionMemberRemoved(unsigned int sessionId, Platform::String ^ uniqueName); // Called by bus attachment when the bus listener is registered void ListenerRegistered(BusAttachment ^ busAtt); // Called by bus attachment when the bus listener is unregistered void ListenerUnregistered(); property BusListener ^ GetBusListener { BusListener ^ get(); } property SessionListener ^ GetSessionListener { SessionListener ^ get(); } property SessionPortListener ^ GetSessionPortListener { SessionPortListener ^ get(); } private: BusListener ^ busListener; //primary listener which handles events occurring over the bus SessionListener ^ sessionListener; //primary listener which handles events occurring in the session SessionPortListener ^ sessionPortListener; //primary listener handling events over the established session port }; }
afa6a0e665eec937d33ff26a2d326f26b9fcbc1b
ad934eeba2ac2a3c1d49b02af864790ece137034
/vijosp/VIJOSP1037.cpp
7f7a364bd9fea98b5406e4608e4b03c97d251608
[]
no_license
xiang578/acm-icpc
19b3d8c7771b935293749f5ccad0591cde8fc896
6f2fdfc62bd689842c80b1caee2d4caf8162d72f
refs/heads/master
2022-01-12T12:28:43.381927
2022-01-12T04:20:44
2022-01-12T04:20:44
39,777,634
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
VIJOSP1037.cpp
#include<bits/stdc++.h> using namespace std; int sum,n,h[1000],dp[2][5000]; int main() { while(~scanf("%d",&n)) { sum=0; memset(dp,0xff,sizeof(dp)); for(int i=1;i<=n;i++) { scanf("%d",&h[i]); sum+=h[i]; } int now=0; dp[0][0]=0; for(int i=1;i<=n;i++) { now=now^1; for(int j=0;j<=sum;j++) { dp[now][j]=dp[now^1][j]; } for(int j=0;j<=sum;j++) { if(dp[now^1][j]!=-1) dp[now][j+h[i]]=max(dp[now][j+h[i]],dp[now^1][j]+h[i]); if(j<=h[i]&&dp[now^1][j]!=-1) dp[now][h[i]-j]=max(dp[now][h[i]-j],dp[now^1][j]-j+h[i]); if(j>h[i]&&dp[now^1][j]!=-1) dp[now][j-h[i]]=max(dp[now][j-h[i]],dp[now^1][j]); } //for(int j=0;j<=sum;j++) printf("%d ",dp[now][j]);printf("\n"); } if(dp[now][0]<=0) puts("Impossible"); else printf("%d\n",dp[now][0]); } return 0; }
b24dd42c4e15de41734d82e72d96941f7c30afb6
1f2a602f0807a81ab6eade3f6f8eb76d0f49670b
/app/old/musictablemodel.h
66473d5e60d95e22552cdedd55f786eaf3130462
[ "MIT" ]
permissive
N-911/CPP-Uamp
c2e3bcbb52130a312efe5556f6fb0064349ec4c8
221dc7894861fc9f1aa648e26db16649a4164625
refs/heads/main
2023-01-20T22:01:38.039095
2020-11-16T13:22:43
2020-11-16T13:22:43
312,043,288
0
0
null
2020-11-11T17:34:51
2020-11-11T17:34:51
null
UTF-8
C++
false
false
2,406
h
musictablemodel.h
#ifndef MUSICTABLEMODEL_H #define MUSICTABLEMODEL_H #include <QMainWindow> #include <QAbstractItemModel> #include <QVector> #include "music.h" #include "medialibrary.h" class MusicTableModel : public QAbstractTableModel { Q_OBJECT public: explicit MusicTableModel(MediaLibrary& _m_library, QWidget *parent = nullptr); int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; Qt::ItemFlags flags(const QModelIndex &index) const override; bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; // // bool insertColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override; // bool removeColumns(int column, int count, const QModelIndex &parent = QModelIndex()) override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; signals: void editCompleted(const QString &); public slots: void saveTags(const QModelIndex &index, const Music& new_tags); private: QWidget *m_parent; QVector<QString> listHeaders = {"Title", "Time", "Artist", "Rating", "Genre", "Album", "Year", "Track", "Comment", "Name","Path"}; MediaLibrary& m_class_library; }; #endif // MUSICTABLEMODEL_H /// for sql // QVector<Music>& m_media_library; //MediaLibrary& m_class_library; /* void showTable() { connOpen(); QSqlQueryModel * myModel=new QSqlQueryModel(ui->tableView); QSqlQuery select; if (!select.exec("select * from tab")) { QMessageBox::critical(this, tr("Error"), select.lastError().text()); } else { myModel->setQuery(select); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(myModel); // create proxy proxyModel->setSourceModel(myModel); ui->tableView->setSortingEnabled(true); // enable sortingEnabled ui->tableView->setModel(proxyModel); } connClose(); } */
94fe29be57e5353182a3b212728136a96383663f
41c6bb0ed7c7373b2ec171eedbaf33e0fb5027c7
/transaction.cpp
f2eb9609089f4f08db9160721bef40feca83f691
[]
no_license
haanhduclinh/blockchain
5e5e837917e75cc2e397820558f33ae7a7cde45b
d3762cfaa24931307a07792685fe966ce395b55e
refs/heads/master
2020-03-18T13:58:08.045574
2018-05-25T07:44:52
2018-05-25T07:44:52
134,821,055
0
0
null
null
null
null
UTF-8
C++
false
false
703
cpp
transaction.cpp
#include <iostream> #include <string> #include <vector> class Transaction{ public: Transaction(); string sender; string recipient: float amount; vector<Transaction> currentTransaction(); void addTransaction(Transaction tNew); private: vector<Transaction> _vTransaction; } Transaction::Transaction(){ vector<Transaction> _vTransaction; } vector<Transaction> Transaction::currentTransaction(){ return _vTransaction; } void Transaction::addTransaction(Transaction tNew)(){ if((!tNew.sender) || (!tNew.recipient) || (amount < 0)){ cout << "Invalid transaction" << endl; }else{ _vTransaction.push_back(tNew) cout << "New Transaction" << endl; } }
c3c43c016e6654977c0d751f71d78f65ae126095
72ed63c92ff6b2c66eb26f9bb8fe42f9c30b6dcc
/C/283 算法_链表的操作.cpp
c8e745b874fc1e0a1ccadaba0dd71baa167530e5
[]
no_license
wangjunjie1107/CodeTesting
ceee7adbf73d357cb3b93e751682e05b83b54328
2e614831877f30db109e5b669a1d77bb17208a5a
refs/heads/master
2020-07-15T04:59:36.138974
2019-10-30T00:39:29
2019-10-30T00:39:29
205,484,180
0
0
null
null
null
null
GB18030
C++
false
false
3,200
cpp
283 算法_链表的操作.cpp
#include<string.h> //添加结点到链表尾部 ChainListType *ChainListAddEnd(ChainListType *head, DATA data) { ChainListType *node, *h; if(!(node = (ChainListType *)malloc(sizeof(ChainListType)))) { printf("为保存结点数据申请内存失败!\n"); return NULL; //分配内存失败 } node->data = data; //保存数据 node->next = NULL; //设置结点指针为空,即为表尾 if(head == NULL) //链表头结点指向空 { head = node; //让头结点指向插入的结点 return head; //返回头结点 } h = head;//定义一个指针,指向头结点,让它从头结点开始往下查找,直到找到尾节点 while(h->next != NULL) //查找链表的末尾 { h = h->next; } h->next = node; return head; } //添加结点到链表头部 ChainListType *ChainListAddFirst(ChainListType *head, DATA data) { ChainListType *node, *h; if(!(node = (ChainListType *)malloc(sizeof(ChainListType)))) { printf("为保存结点数据申请内存失败!\n"); return NULL; //分配内存失败 } node->data = data; //保存数据 //挂链操作 node->next = head; //指向头指针所指结点 head = node; //头指针指向新增结点 return head; } //将结点插入到链表当中 ChainListType *ChainListInsert(ChainListType *head, char *findkey, DATA data) { ChainListType *node, *node1; //为新节点分配内存空间,准备装入数据 if(!(node = (ChainListType *)malloc(sizeof(ChainListType)))) { printf("为保存结点数据申请内存失败!\n"); return NULL; //分配内存失败 } node->data = data; //保存结点中的数据 node1 = ChainListFind(head, findkey); if(node1) //若找到要插入的位置,也就是在哪个结点之后插入 { //挂链操作 node->next = node1->next; node1->next = node; } else{ free(node); //释放内存 printf("未找到插入位置!\n"); } return head; //返回头指针 } //按关键字在链表中查找 ChainListType *ChainListFind(ChainListType *head, char *key) { ChainListType *h; h = head; //保存链表头指针 while(h) //若结点有效,则进行查找 { //若关键字与传入关键字相同 if(strcmp(h->data.key, key) == 0) return h; //返回该结点指针 h = h->next; //继续查找下一结点 } return NULL; //返回空指针,表示未找到 } //删除指定关键字的结点 int ChainListDelete(ChainListType *head, char *key) { ChainListType *node, *h;//node保存删除结点的前一个结点 node = h = head; while(h) //当 h != NULL 时 { if(strcmp(h->data.key, key) == 0)//找到要删除的结点 { node->next = h->next;//使前一结点指向当前结点的下一个结点 free(h);//释放内存 return 1; } else { node = h; //指向当前结点 h = h->next; //指向下一结点 } } return 0;//未找到要删除的结点 } //获取链表长度 int ChainListLength(ChainListType *head) { ChainListType *h; int i = 0; //计数 h = head; while(h) //遍历整个链表 { i++; //累加结点数量 h = h->next; //处理下一结点 } return i; //返回结点数量 }
7d73d099bf6121eb30d3237709e125355d6a5ce6
6622db78382cfb9d30d8ab63856fc1852f199920
/vfd_gl.ino
00597112b5460a14bbe7230c61a069eb7d2c506e
[]
no_license
Bankst/GU800_VFD_GL
15c831295e4243f1194f4efed480087c9069613f
79583b4c4edf18a95d722e1a48457d4f53ba8292
refs/heads/master
2023-08-06T21:41:51.397498
2021-09-06T18:24:02
2021-09-06T18:24:02
401,539,340
0
0
null
null
null
null
UTF-8
C++
false
false
4,403
ino
vfd_gl.ino
#include <math.h> #include <SPI.h> #include "src/arduinogl/ArduinoGL.h" // #include "src/GU800/GU800_GFX.h" #include "src/GU800/GU800_Canvas.h" // #include "pikachu.h" #define css 10 // #define css 53 #define cd 9 #define reset 8 GU800_Canvas display(css, cd, reset); uint8_t state = 1; void setup() { Serial.begin(9600); pinMode(css, OUTPUT); digitalWrite(css, LOW); pinMode(LED_BUILTIN, OUTPUT); delay(5); digitalWrite(LED_BUILTIN, HIGH); // SPI.setSCK(14); delay(2500); display.begin(); display.clearDisplay(); // setup text display.setTextColor(WHITE); display.setTextSize(1); display.setCursor(0, 0); // display.println("Fuck You!"); printInit(); display.display(); } void initGL() { /* Pass the canvas to the OpenGL environment */ glUseCanvas(&display); glClear(GL_COLOR_BUFFER_BIT); glPointSize(4); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // square // gluOrtho2D(-5.0, 5.0, -5.0, 5.0); // cube gluPerspective(30.0, display.width()/display.height(), 0.1f, 9999.f); glMatrixMode(GL_MODELVIEW); } void printInit() { display.setCursor(26, 18); display.println("INITIALIZING"); display.setCursor(38, 26); display.println("ARDUINOGL"); display.setCursor(44, 34); display.print("ENGINE"); } float _angle = 0.0f; // static float scale = 3.0, scaleInc = 0.4; // const float maxScale = 8.0, minScale = 2.0; void prep3dShapeDraw(float angle, float scale) { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); gluLookAt(10, 8, -10, 0, 0, 0, 0, 1, 0); glRotatef(angle, 0.f, 1.f, 0.f); glScalef(scale, scale, scale); } void runSquare(float angle, float scale) { // square glLoadIdentity(); glRotatef(angle, 0.f, 0.f, 1.f); glScalef(scale, scale, 0.f); glTranslatef(-0.5f, -0.5f, 0.f); // square glBegin(GL_POLYGON); glVertex3f(0.f, 1.f, 0.f); glVertex3f(0.f, 0.f, 0.f); glVertex3f(1.f, 0.f, 0.f); glVertex3f(1.f, 1.f, 0.f); glEnd(); } void drawCube() { glBegin(GL_POLYGON); glVertex3f(-1, -1, -1); glVertex3f(1, -1, -1); glVertex3f(1, 1, -1); glVertex3f(-1, 1, -1); glEnd(); glBegin(GL_POLYGON); glVertex3f(1, -1, -1); glVertex3f(1, -1, 1); glVertex3f(1, 1, 1); glVertex3f(1, 1, -1); glEnd(); glBegin(GL_POLYGON); glVertex3f(1, -1, 1); glVertex3f(-1, -1, 1); glVertex3f(-1, 1, 1); glVertex3f(1, 1, 1); glEnd(); glBegin(GL_POLYGON); glVertex3f(-1, -1, 1); glVertex3f(-1, -1, -1); glVertex3f(-1, 1, -1); glVertex3f(-1, 1, 1); glEnd(); glBegin(GL_POLYGON); glVertex3f(-1, -1, 1); glVertex3f(1, -1, 1); glVertex3f(1, -1, -1); glVertex3f(-1, -1, -1); glEnd(); glBegin(GL_POLYGON); glVertex3f(-1, 1, -1); glVertex3f(1, 1, -1); glVertex3f(1, 1, 1); glVertex3f(-1, 1, 1); glEnd(); } void drawPyramid() { glBegin(GL_TRIANGLE_STRIP); glVertex3f(-1, -1, -1); glVertex3f(1, -1, -1); glVertex3f(0, 1, 0); glVertex3f(1, -1, 1); glVertex3f(-1, -1, 1); glEnd(); glBegin(GL_POLYGON); glVertex3f(-1, -1, 1); glVertex3f(1, -1, 1); glVertex3f(1, -1, -1); glVertex3f(-1, -1, -1); glEnd(); } void runGL() { _angle += 5.0f; _angle = fmod(_angle, 360.0f); const float _scale = 2.5f; runSquare(_angle, _scale); //prep3dShapeDraw(_angle, _scale); //drawCube(); // drawPyramid(); // runPikachu(_angle); /* Ask the display to print our frame buffer */ display.display(); } uint8_t dotCount = 0; uint8_t loadCounts = 0; void printLoading() { display.clearDisplay(); printInit(); for (uint8_t i = 0; i < dotCount; i++) { display.print("."); } display.display(); delay(75); dotCount++; if (dotCount >= 4) { dotCount = 0; loadCounts++; } } void loop() { if (state == 0) { Serial.print(loadCounts); Serial.println(" load"); printLoading(); if (loadCounts > 4) { state++; Serial.println("END STATE 0"); } } if (state == 1) { display.clearDisplay(); display.setCursor(24, 26); display.println("LOAD COMPLETE!"); display.display(); delay(250); Serial.println("END STATE 1"); state++; } if (state == 2) { display.clearDisplay(); display.display(); state++; Serial.println("cleared, running GL!"); } if (state == 3) { runSquare(1, 2); } }
8984c0149dfa71b2689b6fa7409664228d8c8531
54a9b1d648e4fb2d43a953b19ee7fa572114de96
/EntityComponents/EC_ChatBubble/EC_ChatBubble.h
382db4d95427909cb87001c6e29a085659825e5c
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jesterKing/naali
02f834c4ccf37cc7f1fb2a0a74774addb9561a21
98baf592637d0edc684f21ab6488783a8b008c81
refs/heads/master
2021-01-18T08:02:25.655961
2010-04-27T10:26:53
2010-04-27T10:28:08
746,307
0
1
null
null
null
null
UTF-8
C++
false
false
2,731
h
EC_ChatBubble.h
/** * For conditions of distribution and use, see copyright notice in license.txt * * @file EC_ChatBubble.h * @brief EC_ChatBubble Chat bubble component wich shows billboard with chat bubble and text on entity. * @note The entity must have EC_OgrePlaceable component available in advance. */ #ifndef incl_EC_ChatBubble_EC_ChatBubble_h #define incl_EC_ChatBubble_EC_ChatBubble_h #include "ComponentInterface.h" #include "Declare_EC.h" #include "Vector3D.h" #include <QStringList> #include <QFont> #include <QColor> namespace OgreRenderer { class Renderer; } namespace Ogre { class SceneNode; class BillboardSet; class Billboard; } class EC_ChatBubble : public Foundation::ComponentInterface { Q_OBJECT DECLARE_EC(EC_ChatBubble); private: /// Constuctor. /// @param module Owner module. explicit EC_ChatBubble(Foundation::ModuleInterface *module); public: /// Destructor. ~EC_ChatBubble(); /// Sets postion for the chat bubble. /// @param position Position. /// @note The position is relative to the entity to which the chat bubble is attached. void SetPosition(const Vector3df &position); /// Sets the font used for the chat bubble text. /// @param font Font. void SetFont(const QFont &font) { font_ = font; } /// Sets the color of the chat bubble text. /// @param color Color. void SetTextColor(const QColor &color) { textColor_ = color; } /// Sets the color of the chat bubble. /// @param color Color. void SetBubbleColor(const QColor &color) { bubbleColor_ = color; } public slots: /// Adds new message to be shown on the chat bubble. /// @param msg Message to be shown. /// @note The time the message is shown is calculated from the message length. void ShowMessage(const QString &msg); private slots: /// Removes the last message. void RemoveLastMessage(); /// Removes all the messages. void RemoveAllMessages(); /// Redraws the chat bubble with current messages. void Refresh(); private: /// Returns pixmap with chat bubble and current messages renderer to it. QPixmap GetChatBubblePixmap(); /// Renderer pointer. boost::weak_ptr<OgreRenderer::Renderer> renderer_; /// Ogre billboard set. Ogre::BillboardSet *billboardSet_; /// Ogre billboard. Ogre::Billboard *billboard_; /// Name of the material used for the billboard set. std::string materialName_; /// For used for the chat bubble text. QFont font_; /// Color of the chat bubble text. QColor textColor_; /// Color of the chat bubble. QColor bubbleColor_; /// List of visible chat messages. QStringList messages_; }; #endif
dfa7f8dd634eadba9878e4a9bc422c0dd250ef23
20423565855b1acc23e8ecaf91b10f5bb3ac68ec
/src/CVTask.cpp
bd9c22427824b27745c8f0a0ea3002819af50ec2
[]
no_license
crocdialer/Qt_CV_Box
907548f71ab1d449c43f138803714f0f0ff0c00a
6a21924ee67c6fea9a635fe7bd691a9d1c78814c
refs/heads/master
2021-01-13T02:26:15.721960
2012-04-26T14:20:46
2012-04-26T14:21:06
3,109,432
1
0
null
null
null
null
UTF-8
C++
false
false
1,942
cpp
CVTask.cpp
#include "CVTask.h" using namespace std; using namespace cv; Mat CVTask::colorOutput(const Mat& confMap,const Colormap &cm, const Size& s) { if(confMap.empty()) return cm.apply(Mat(s,CV_8UC1,0.0)); Size outSize = s; if(outSize==Size()) outSize = confMap.size(); Mat tmp = confMap; //cv::normalize(confMap,tmp,0,255,CV_MINMAX); if(confMap.type() & CV_32F ) { tmp = confMap * 255; } tmp.convertTo(tmp,CV_8UC1); Mat resized; resize (tmp, resized,outSize); // generate colormap-output tmp=cm.apply(resized); return tmp; } TaskXRay::TaskXRay():CVTask() { m_colorMap = Colormap(Colormap::BONE); }; Mat TaskXRay::doProcessing(const Mat &inFrame) { Mat grayImg,out; cvtColor(inFrame, grayImg, CV_BGR2GRAY); bitwise_not(grayImg, grayImg); //out = m_colorMap.apply(grayImg); out = colorOutput(grayImg,m_colorMap); return out; }; TaskThermal::TaskThermal():CVTask() { m_colorMap = Colormap(Colormap::JET); } Mat TaskThermal::doProcessing(const Mat &inFrame) { Mat grayImg,outMat; if(inFrame.channels() == 3) cvtColor(inFrame, grayImg, CV_BGR2GRAY); else grayImg = inFrame; outMat = m_colorMap.apply(grayImg); return outMat; } TaskSalience::TaskSalience():CVTask() { m_colorMap = Colormap(Colormap::BONE); } cv::Mat TaskSalience::doProcessing(const cv::Mat &inFrame) { cv::Mat downSized,outMat; double ratio = 320 * 1. / inFrame.cols; resize(inFrame, downSized, cv::Size(0,0), ratio, ratio, INTER_NEAREST); m_salienceDetect.updateSalience(downSized); m_salienceDetect.getSalImage(m_salImg); //resize(salImg,salImg,inFrame.size(),CV_INTER_LINEAR); outMat = colorOutput(m_salImg, m_colorMap) ; resize(outMat,outMat,inFrame.size(),CV_INTER_LINEAR); return outMat; };
9aad0d33bbe0aa5b8c558077bc3c007f2a44ca40
070775dcf7b91efdc84e3f7c12fad4708cccf441
/07 深拷贝与浅拷贝/test.cpp
c73cddde8fe4f1ecaec6d85316328837cd02fd7f
[]
no_license
514467952/c-about
9df501480ddbf734ea4146bd47333ec39d44091f
7af295b7882b2d7c91bf5565df3accb70d67929b
refs/heads/master
2020-06-15T07:43:44.323190
2020-01-21T01:57:35
2020-01-21T01:57:35
195,238,626
1
0
null
null
null
null
GB18030
C++
false
false
799
cpp
test.cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; class Person { public: Person() { } //初始化属性 Person(char *name, int age) { m_Name = (char *)malloc(strlen(name) + 1); strcpy(m_Name, name); } //拷贝构造 系统会提供默认 //自己提供拷贝构造,原因简单的浅拷贝会释放堆空间两次 Person(const Person&p) { m_age = p.m_age; m_Name = (char *)malloc(strlen(p.m_Name)+1); strcpy(m_Name, p.m_Name); } ~Person() { cout << "析构函数的调用" << endl; if (m_Name != NULL) { free(m_Name); m_Name = NULL; } } //姓名 char * m_Name; //年龄 int m_age; }; void test01() { Person p1("敌法", 10); Person p2(p1);//调用拷贝构造 } int main() { test01(); system("pause"); return 0; }
5104fbc45c0e4009c688360c30eacfd61246976d
91c426b7c58c2ee0c06a8df300188134e364ba62
/main.cpp
53191b245c2dce250c3d724d4ec6f2bcde7abab0
[]
no_license
lingadnicholas/data_structs_prac_cpp
3da3f0bc98cd8f8fbc666a3bfad428444143b932
e378044833cf87ac588080b056937a8fcac32a1e
refs/heads/master
2022-04-11T14:53:50.942831
2020-04-01T22:30:58
2020-04-01T22:30:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,021
cpp
main.cpp
#include "provided.h" #include "ExpandableHashMap.h" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <cassert> using namespace std; void test5() { StreetMap sm; sm.load("E:\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt"); PointToPointRouter p(&sm); GeoCoord start("34.0625329", "-118.4470263"); //GeoCoord end("34.0636533", "-118.4470480"); GeoCoord end("34.0636344", "-118.4482275"); //GeoCoord end("34.0593696","-118.4455875"); list <StreetSegment> seg; vector <StreetSegment> segs; double dist; p.generatePointToPointRoute(start, end, seg, dist); //testing deliveries GeoCoord depot = start; vector<DeliveryRequest> deliveries; deliveries.push_back(DeliveryRequest("popcorn", GeoCoord("34.0712323", "-118.4505969"))); deliveries.push_back(DeliveryRequest("cake", GeoCoord("34.0687443", "-118.4449195"))); deliveries.push_back(DeliveryRequest("coffee", GeoCoord("34.0685657", "-118.4489289"))); deliveries.push_back(DeliveryRequest("pizza", GeoCoord("34.0718238", "-118.4525699"))); deliveries.push_back(DeliveryRequest("coffee", GeoCoord("34.0666168", "-118.4395786"))); deliveries.push_back(DeliveryRequest("pies", GeoCoord("34.0711774", "-118.4495120"))); deliveries.push_back(DeliveryRequest("soup", GeoCoord("34.0656797", "-118.4505131"))); deliveries.push_back(DeliveryRequest("pasta", GeoCoord("34.0616291", "-118.4416199"))); deliveries.push_back(DeliveryRequest("pastries", GeoCoord("34.0636860", "-118.4453568"))); deliveries.push_back(DeliveryRequest("potatoes", GeoCoord("34.0683189", "-118.4536522"))); DeliveryPlanner dp(&sm); vector<DeliveryCommand> dcs; double totalMiles; for (int i = 0; i < 100; i++) dp.generateDeliveryPlan(depot, deliveries, dcs, totalMiles); } void test4() { StreetMap sm; sm.load("C:\\Users\\linga\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt"); PointToPointRouter p(&sm); GeoCoord start("34.0625329", "-118.4470263"); //GeoCoord end("34.0636533", "-118.4470480"); GeoCoord end("34.0636344", "-118.4482275"); //GeoCoord end("34.0593696","-118.4455875"); list <StreetSegment> seg; vector <StreetSegment> segs; double dist; //testing deliveries GeoCoord depot = start; vector<DeliveryRequest> deliveries; deliveries.push_back(DeliveryRequest("popcorn", GeoCoord("34.0712323", "-118.4505969"))); deliveries.push_back(DeliveryRequest("cake", GeoCoord("34.0687443", "-118.4449195"))); deliveries.push_back(DeliveryRequest("coffee", GeoCoord("34.0685657", "-118.4489289"))); deliveries.push_back(DeliveryRequest("pizza", GeoCoord("34.0718238", "-118.4525699"))); deliveries.push_back(DeliveryRequest("coffee", GeoCoord("34.0666168", "-118.4395786"))); DeliveryPlanner dp(&sm); vector<DeliveryCommand> dcs; double totalMiles; dp.generateDeliveryPlan(depot, deliveries, dcs, totalMiles); cout << totalMiles; } void test3() { StreetMap sm; sm.load("C:\\Users\\linga\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt"); PointToPointRouter p(&sm); GeoCoord start("34.0625329", "-118.4470263"); GeoCoord end("34.0636533", "-118.4470480"); //GeoCoord end("34.0636344", "-118.4482275"); list <StreetSegment> seg; vector <StreetSegment> segs; double dist; sm.getSegmentsThatStartWith(start, segs); p.generatePointToPointRoute(start, end, seg, dist); //testing deliveries GeoCoord depot = end; vector<DeliveryRequest> deliveries; deliveries.push_back(DeliveryRequest("popcorn", GeoCoord("34.0636344", "-118.4482275"))); deliveries.push_back(DeliveryRequest("cake", GeoCoord("34.0608001", "-118.4457307"))); deliveries.push_back(DeliveryRequest("coffee", GeoCoord("34.0438832", "-118.4950204"))); deliveries.push_back(DeliveryRequest("soda", GeoCoord("34.0666168", "-118.4395786"))); DeliveryPlanner dp(&sm); vector<DeliveryCommand> dcs; double totalMiles; dp.generateDeliveryPlan(depot, deliveries, dcs, totalMiles); cout << totalMiles; } void test2() { StreetMap sm; sm.load("C:\\Users\\linga\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt"); PointToPointRouter p(&sm); GeoCoord start("34.0625329", "-118.4470263"); GeoCoord end("34.0636533", "-118.4470480"); list <StreetSegment> seg; vector <StreetSegment> segs; double dist; sm.getSegmentsThatStartWith(start, segs); p.generatePointToPointRoute(start, end, seg, dist); cout << "Done" << endl; } void test1() { GeoCoord first; GeoCoord second("34.0555267", "118.4796954"); GeoCoord third("34.0555267", "118.4796954"); GeoCoord fourth("4.0555267", "18.4796954"); GeoCoord fifth("324.0555267", "11.479694"); GeoCoord sixth("134.0555267", "8.479654"); GeoCoord seventh("374.0555267", "18.47954"); GeoCoord eighth("384.0555267", "1.4796954"); GeoCoord ninth("394.0555267", "8.479654"); GeoCoord tenth("3224.0555267", "18.479654"); GeoCoord eleventh("314.0555267", "1128.479954"); ExpandableHashMap<GeoCoord, double> hashing; hashing.associate(first, 30); hashing.associate(second, 50); assert(hashing.size() == 2); hashing.associate(second, 60); assert(hashing.size() == 2); hashing.reset(); cout << hashing.size() << endl; assert(hashing.size() == 0); hashing.associate(second, 70); assert(hashing.size() == 1); //Looks like there is an error in expanding the table. hashing.associate(third, 10); hashing.associate(fourth, 10); hashing.associate(fifth, 10); hashing.associate(sixth, 10); hashing.associate(seventh, 10); hashing.associate(eighth, 10); hashing.associate(ninth, 10); //Throws an exception when trying to copy this one hashing.associate(tenth, 10); hashing.associate(eleventh, 10); cout << "All tests passed" << endl; } bool loadDeliveryRequests(string deliveriesFile, GeoCoord& depot, vector<DeliveryRequest>& v); bool parseDelivery(string line, string& lat, string& lon, string& item); int main() { StreetMap sm; //"C:\\Users\\linga\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt" //"E:\\OneDrive - UCLA IT Services\\Project4\\mapdata.txt" if (!sm.load("mapdata.txt")) { std::cout << "Unable to load map data file " << endl; return 1; } GeoCoord depot; vector<DeliveryRequest> deliveries; //"C:\\Users\\linga\\OneDrive - UCLA IT Services\\Project4\\deliveries.txt" //"E:\\OneDrive - UCLA IT Services\\Project4\\deliveries.txt" if (!loadDeliveryRequests("deliveries.txt", depot, deliveries)) { std::cout << "Unable to load delivery request file " << endl; return 1; } std::cout << "Generating route...\n\n"; DeliveryPlanner dp(&sm); vector<DeliveryCommand> dcs; double totalMiles; DeliveryResult result = dp.generateDeliveryPlan(depot, deliveries, dcs, totalMiles); if (result == BAD_COORD) { std::cout << "One or more depot or delivery coordinates are invalid." << endl; return 1; } if (result == NO_ROUTE) { std::cout << "No route can be found to deliver all items." << endl; return 1; } std::cout << "Starting at the depot...\n"; for (const auto& dc : dcs) std::cout << dc.description() << endl; std::cout << "You are back at the depot and your deliveries are done!\n"; std::cout.setf(ios::fixed); std::cout.precision(2); std::cout << totalMiles << " miles travelled for all deliveries." << endl; } bool loadDeliveryRequests(string deliveriesFile, GeoCoord& depot, vector<DeliveryRequest>& v) { ifstream inf(deliveriesFile); if (!inf) return false; string lat; string lon; inf >> lat >> lon; inf.ignore(10000, '\n'); depot = GeoCoord(lat, lon); string line; while (getline(inf, line)) { string item; if (parseDelivery(line, lat, lon, item)) v.push_back(DeliveryRequest(item, GeoCoord(lat, lon))); } return true; } bool parseDelivery(string line, string& lat, string& lon, string& item) { const size_t colon = line.find(':'); if (colon == string::npos) { cout << "Missing colon in deliveries file line: " << line << endl; return false; } istringstream iss(line.substr(0, colon)); if (!(iss >> lat >> lon)) { cout << "Bad format in deliveries file line: " << line << endl; return false; } item = line.substr(colon + 1); if (item.empty()) { cout << "Missing item in deliveries file line: " << line << endl; return false; } return true; }
01e51f66ffa7ecb7c0af9c32ea6d9c8b5ff7f2eb
0e0a39875ad5089ca1d49d1e1c68d6ef337941ff
/src/Core/Handle.cpp
3ba722978556fe43bc30f544cbdd404236fa782a
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
FloodProject/flood
aeb30ba9eb969ec2470bd34be8260423cd83ab9f
466ad3f4d8758989b883f089f67fbc24dcb29abd
refs/heads/master
2020-05-18T01:56:45.619407
2016-02-14T17:00:53
2016-02-14T17:18:40
4,555,061
6
2
null
2014-06-21T18:08:53
2012-06-05T02:49:39
C#
WINDOWS-1252
C++
false
false
1,948
cpp
Handle.cpp
/************************************************************************ * * Flood Project © (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #include "Core/API.h" #include "Core/Handle.h" #include "Core/Log.h" NAMESPACE_CORE_BEGIN //-----------------------------------// HandleManager* HandleCreateManager( Allocator* alloc ) { HandleManager* man = Allocate(alloc, HandleManager); man->nextHandle = 0; return man; } //-----------------------------------// void HandleDestroyManager( HandleManager* man ) { if( !man ) return; const HandleMap& handles = man->handles; if( handles.Size() > 0 ) { //LogAssert("Handle manager should not have any handles"); goto out; } out: Deallocate(man); } //-----------------------------------// HandleId HandleCreate(HandleManager* man, ReferenceCounted* ref) { if( !man ) return HandleInvalid; HandleMap& handles = man->handles; HandleId id = man->nextHandle.increment(); handles[id] = ref; return id; } //-----------------------------------// void HandleDestroy(HandleManager* man, HandleId id) { if( !man ) return; HandleMap& handles = man->handles; HandleMap::Iterator it = handles.Find(id); if( it == handles.End() ) return; handles.Erase(it); } //-----------------------------------// void HandleGarbageCollect(HandleManager* man) { } //-----------------------------------// ReferenceCounted* HandleFind(HandleManager* man, HandleId id) { HandleMap& handles = man->handles; HandleMap::Iterator it = handles.Find(id); if (it == handles.End()) return nullptr; return handles[id]; } //-----------------------------------// NAMESPACE_CORE_END
dc2c2e808d388fde08b1985864caeb2dd26da29a
cd05c5245c9df3b427e10424ccb8ed93a30b773b
/Raytrace/Framework/DX/DescriptorTable.h
9db2c2e2939765d8d70e36e7321a714a59081fc4
[]
no_license
matsumoto0112/raytracing
aa451c0a91b9a85705285185443e9b4d05300564
ea524069397eb5f6c06e9b9068a0fb814b6ba2ac
refs/heads/master
2020-08-23T23:48:23.375308
2019-11-01T09:25:35
2019-11-01T09:25:35
216,726,521
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,314
h
DescriptorTable.h
#pragma once #include <d3d12.h> #include "Utility/Typedef.h" namespace Framework::DX { namespace HeapType { enum Enum { CBV_SRV_UAV = 0, Sampler, RTV, DSV, }; } //HeapType namespace HeapFlag { enum Enum { None = 0, ShaderVisible, }; } //HeapFlag /** * @class DescriptorTable * @brief discription */ class DescriptorTable { public: /** * @brief コンストラクタ */ DescriptorTable(ID3D12Device* device, HeapType::Enum heapType, HeapFlag::Enum heapFlag, UINT descriptorNum); /** * @brief デストラクタ */ ~DescriptorTable(); void create(ID3D12Device* device, HeapType::Enum heapType, HeapFlag::Enum heapFlag, UINT descriptorNum); void reset(); ID3D12DescriptorHeap* getHeap() const { return mHeap.Get(); } UINT allocate(D3D12_CPU_DESCRIPTOR_HANDLE* handle); UINT allocateWithGPU(D3D12_CPU_DESCRIPTOR_HANDLE* cpuHandle, D3D12_GPU_DESCRIPTOR_HANDLE* gpuHandle); private: ComPtr<ID3D12DescriptorHeap> mHeap; UINT mDescriptorSize; UINT mAllocatedNum; }; } //Framework::DX
070219f7876fedac41eb8089fea77d618dda1ca2
eb50a330cb3d2402d17bee9a5f91f2b372c1e1c1
/SPOJ/help_the_team.cpp
f792d3b0ef837702396d1b05e9d78f17408301c9
[]
no_license
MaxSally/Competitive_Programming
2190552a8c8a97d13f33d5fdbeb94c5d92fa9038
8c57924224ec0d1bbc5f17078505ef8864f4caa3
refs/heads/master
2023-04-27T22:28:19.276998
2023-04-12T22:47:10
2023-04-12T22:47:10
270,885,835
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
help_the_team.cpp
//http://www.spoj.com/problems/CAM5/ #include<vector> #include<iostream> #include<stdio.h> #include<queue> using namespace std; bool visited[100000]; void DFS(int start,vector< vector<int> > &relationship){ int l=relationship[start].size(); visited[start]=1; for(int i=0;i<l;i++){ if(visited[relationship[start][i]]==0){ DFS(relationship[start][i],relationship); } } } int main(){ //freopen("help_the_team.txt","r",stdin); ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; for(int ii=0;ii<t;ii++){ int n,e,cnt; cnt=0; cin >> n >> e; vector< vector<int> > relationship; for(int i=0;i<n;i++){ visited[i]=0; } relationship.resize(n); for(int i=0;i<e;i++){ int temp, temp1; cin >> temp >> temp1; relationship[temp].push_back(temp1); relationship[temp1].push_back(temp); } for(int i=0;i<n;i++){ if(visited[i]==0){ cnt++; DFS(i,relationship); } } cout << cnt << endl; } return 0; }
7e95e975fd1f31ed0c6385b05368b479a382ec22
4352b5c9e6719d762e6a80e7a7799630d819bca3
/tutorials/eulerVortex.twitch/eulerVortex.cyclic.twitch.test.test/processor3/1.32/p
31ae0e4f7c92667fc0a2e4419d6e84f5ea43c17a
[]
no_license
dashqua/epicProject
d6214b57c545110d08ad053e68bc095f1d4dc725
54afca50a61c20c541ef43e3d96408ef72f0bcbc
refs/heads/master
2022-02-28T17:20:20.291864
2019-10-28T13:33:16
2019-10-28T13:33:16
184,294,390
1
0
null
null
null
null
UTF-8
C++
false
false
30,418
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1.32"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 5625 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 1 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999998 0.999998 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999998 0.999998 0.999998 0.999998 0.999998 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.999996 0.999996 0.999997 0.999997 0.999998 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999995 0.999995 0.999995 0.999996 0.999997 0.999997 0.999998 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999993 0.999993 0.999993 0.999994 0.999995 0.999996 0.999997 0.999998 1 1 1 1 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999991 0.999991 0.999991 0.999992 0.999993 0.999994 0.999996 0.999998 1 1 1 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999988 0.999988 0.999988 0.999989 0.99999 0.999992 0.999995 0.999997 1 1 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999983 0.999983 0.999984 0.999985 0.999987 0.99999 0.999993 0.999996 1 1 1.00001 1.00001 1.00001 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999977 0.999977 0.999978 0.99998 0.999983 0.999987 0.999991 0.999996 1 1.00001 1.00001 1.00001 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00002 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.99997 0.999971 0.999972 0.999975 0.999978 0.999983 0.999989 0.999995 1 1.00001 1.00001 1.00002 1.00002 1.00003 1.00003 1.00003 1.00003 1.00003 1.00003 1.00003 1.00002 1.00002 1.00002 1.00001 1.00001 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999962 0.999962 0.999964 0.999968 0.999973 0.999979 0.999987 0.999995 1 1.00001 1.00002 1.00003 1.00003 1.00004 1.00004 1.00004 1.00004 1.00004 1.00004 1.00004 1.00003 1.00003 1.00002 1.00002 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999952 0.999953 0.999956 0.999961 0.999967 0.999976 0.999986 0.999997 1.00001 1.00002 1.00003 1.00004 1.00005 1.00005 1.00006 1.00006 1.00006 1.00005 1.00005 1.00005 1.00004 1.00004 1.00003 1.00002 1.00002 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999941 0.999943 0.999947 0.999953 0.999962 0.999974 0.999987 1 1.00002 1.00003 1.00004 1.00005 1.00006 1.00007 1.00007 1.00008 1.00007 1.00007 1.00007 1.00006 1.00005 1.00005 1.00004 1.00003 1.00003 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999929 0.999932 0.999938 0.999948 0.99996 0.999975 0.999992 1.00001 1.00003 1.00005 1.00006 1.00008 1.00009 1.00009 1.0001 1.0001 1.0001 1.00009 1.00009 1.00008 1.00007 1.00006 1.00005 1.00004 1.00003 1.00003 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999919 0.999923 0.999933 0.999946 0.999962 0.999982 1 1.00003 1.00005 1.00007 1.00009 1.00011 1.00012 1.00013 1.00013 1.00013 1.00013 1.00012 1.00011 1.0001 1.00009 1.00008 1.00006 1.00005 1.00004 1.00003 1.00002 1.00002 1.00001 1.00001 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.99991 0.999918 0.999932 0.99995 0.999973 0.999999 1.00003 1.00006 1.00009 1.00011 1.00014 1.00016 1.00017 1.00018 1.00018 1.00018 1.00017 1.00016 1.00015 1.00013 1.00011 1.0001 1.00008 1.00006 1.00005 1.00004 1.00003 1.00002 1.00001 1.00001 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999908 0.999922 0.999942 0.999968 0.999999 1.00003 1.00007 1.00011 1.00015 1.00018 1.00021 1.00023 1.00024 1.00025 1.00025 1.00024 1.00023 1.00021 1.00019 1.00017 1.00015 1.00012 1.0001 1.00008 1.00006 1.00005 1.00003 1.00002 1.00002 1.00001 1 1 1 0.999999 0.999998 0.999998 0.999998 0.999998 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999918 0.99994 0.999971 1.00001 1.00005 1.0001 1.00015 1.0002 1.00024 1.00028 1.00031 1.00033 1.00035 1.00035 1.00034 1.00033 1.00031 1.00028 1.00025 1.00022 1.00019 1.00016 1.00013 1.0001 1.00008 1.00006 1.00004 1.00003 1.00002 1.00001 1 1 0.999998 0.999997 0.999997 0.999997 0.999997 0.999998 0.999998 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999947 0.999983 1.00003 1.00008 1.00014 1.00021 1.00027 1.00033 1.00039 1.00043 1.00047 1.00049 1.0005 1.00049 1.00048 1.00045 1.00042 1.00038 1.00033 1.00029 1.00024 1.0002 1.00016 1.00013 1.00009 1.00007 1.00005 1.00003 1.00002 1.00001 1 0.999999 0.999997 0.999996 0.999995 0.999995 0.999996 0.999996 0.999997 0.999998 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00001 1.00007 1.00013 1.00021 1.00029 1.00038 1.00046 1.00054 1.00061 1.00066 1.0007 1.00072 1.00072 1.0007 1.00067 1.00062 1.00057 1.00051 1.00044 1.00038 1.00032 1.00026 1.0002 1.00016 1.00012 1.00008 1.00006 1.00004 1.00002 1.00001 1 0.999998 0.999994 0.999993 0.999993 0.999994 0.999994 0.999995 0.999996 0.999997 0.999998 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00012 1.00021 1.0003 1.00042 1.00053 1.00065 1.00076 1.00086 1.00094 1.001 1.00104 1.00105 1.00104 1.001 1.00094 1.00087 1.00078 1.00069 1.00059 1.0005 1.00041 1.00033 1.00026 1.0002 1.00015 1.0001 1.00007 1.00004 1.00002 1.00001 1 0.999995 0.999992 0.99999 0.999991 0.999991 0.999992 0.999993 0.999995 0.999996 0.999997 0.999998 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.0003 1.00043 1.00058 1.00073 1.00089 1.00105 1.0012 1.00132 1.00142 1.00149 1.00153 1.00152 1.00149 1.00142 1.00132 1.00121 1.00107 1.00094 1.0008 1.00067 1.00055 1.00043 1.00034 1.00025 1.00018 1.00013 1.00008 1.00005 1.00003 1.00001 0.999997 0.999991 0.999987 0.999986 0.999987 0.999988 0.99999 0.999991 0.999993 0.999995 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00058 1.00077 1.00098 1.0012 1.00142 1.00164 1.00183 1.00199 1.00211 1.00219 1.00221 1.00219 1.00212 1.002 1.00185 1.00167 1.00148 1.00128 1.00109 1.0009 1.00073 1.00057 1.00044 1.00033 1.00023 1.00016 1.0001 1.00006 1.00003 1.00001 0.999994 0.999986 0.999982 0.999981 0.999982 0.999984 0.999986 0.999989 0.999991 0.999993 0.999995 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.001 1.00128 1.00157 1.00188 1.00218 1.00246 1.00271 1.00292 1.00307 1.00315 1.00316 1.00311 1.00298 1.0028 1.00258 1.00232 1.00204 1.00176 1.00148 1.00121 1.00097 1.00076 1.00058 1.00042 1.0003 1.0002 1.00013 1.00007 1.00003 1.00001 0.99999 0.99998 0.999976 0.999975 0.999976 0.999979 0.999982 0.999985 0.999988 0.999991 0.999993 0.999995 0.999997 0.999998 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.0016 1.00199 1.0024 1.00282 1.00322 1.0036 1.00392 1.00418 1.00436 1.00445 1.00444 1.00434 1.00415 1.00389 1.00356 1.00319 1.0028 1.0024 1.002 1.00164 1.0013 1.00101 1.00076 1.00056 1.00039 1.00026 1.00016 1.00009 1.00004 1.00001 0.999985 0.999973 0.999968 0.999967 0.999969 0.999973 0.999977 0.999981 0.999985 0.999989 0.999992 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00244 1.00297 1.00353 1.00409 1.00462 1.00511 1.00552 1.00584 1.00606 1.00615 1.00612 1.00597 1.00569 1.00532 1.00487 1.00435 1.0038 1.00325 1.00271 1.00221 1.00175 1.00135 1.00101 1.00074 1.00051 1.00034 1.00021 1.00012 1.00005 1.00001 0.999979 0.999964 0.999959 0.999958 0.999961 0.999966 0.999971 0.999977 0.999982 0.999986 0.99999 0.999992 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00357 1.00429 1.00503 1.00576 1.00644 1.00706 1.00758 1.00797 1.00823 1.00833 1.00827 1.00805 1.00767 1.00717 1.00655 1.00586 1.00512 1.00437 1.00364 1.00296 1.00234 1.00181 1.00135 1.00098 1.00068 1.00045 1.00028 1.00015 1.00007 1.00001 0.999975 0.999956 0.999948 0.999948 0.999951 0.999957 0.999964 0.999971 0.999977 0.999983 0.999987 0.999991 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00504 1.00599 1.00694 1.00787 1.00873 1.00949 1.01012 1.0106 1.0109 1.01101 1.01091 1.01062 1.01014 1.00948 1.00868 1.00777 1.0068 1.00581 1.00485 1.00394 1.00312 1.0024 1.0018 1.0013 1.0009 1.0006 1.00037 1.0002 1.00009 1.00002 0.999972 0.999947 0.999937 0.999935 0.99994 0.999947 0.999956 0.999964 0.999972 0.999978 0.999984 0.999988 0.999992 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00692 1.00812 1.00931 1.01045 1.0115 1.0124 1.01315 1.0137 1.01404 1.01416 1.01404 1.01368 1.01309 1.01228 1.01128 1.01014 1.0089 1.00763 1.00638 1.0052 1.00412 1.00318 1.00238 1.00172 1.0012 1.00079 1.00049 1.00028 1.00013 1.00003 0.999971 0.999938 0.999924 0.999923 0.999928 0.999936 0.999946 0.999957 0.999966 0.999974 0.99998 0.999986 0.99999 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.00922 1.0107 1.01213 1.01348 1.01468 1.01571 1.01654 1.01716 1.01754 1.01768 1.01755 1.01715 1.01647 1.01552 1.01434 1.01295 1.01144 1.00985 1.00828 1.00677 1.00539 1.00417 1.00313 1.00227 1.00158 1.00105 1.00066 1.00038 1.00018 1.00005 0.999975 0.999933 0.999913 0.999909 0.999914 0.999924 0.999936 0.999949 0.99996 0.999969 0.999977 0.999983 0.999988 0.999992 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.01194 1.01368 1.01533 1.01682 1.01813 1.01922 1.02008 1.02072 1.02112 1.02128 1.02118 1.02079 1.0201 1.01908 1.01776 1.01618 1.01439 1.01249 1.01056 1.00869 1.00695 1.0054 1.00407 1.00296 1.00208 1.00139 1.00088 1.00051 1.00026 1.00009 0.999987 0.99993 0.999903 0.999895 0.9999 0.999911 0.999925 0.999939 0.999952 0.999964 0.999973 0.99998 0.999986 0.99999 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.01502 1.01697 1.01873 1.02026 1.02153 1.02255 1.02334 1.02393 1.02432 1.02452 1.0245 1.02422 1.02363 1.02268 1.02135 1.01967 1.01768 1.0155 1.01322 1.01096 1.00883 1.00691 1.00523 1.00383 1.00271 1.00183 1.00117 1.00069 1.00036 1.00015 1.00001 0.999932 0.999894 0.999882 0.999885 0.999898 0.999913 0.999929 0.999944 0.999957 0.999968 0.999977 0.999983 0.999989 0.999992 0.999995 0.999996 0.999998 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.01832 1.02032 1.02202 1.02337 1.02439 1.02514 1.02567 1.02607 1.0264 1.02665 1.02681 1.0268 1.02651 1.02585 1.02474 1.02315 1.02113 1.01877 1.0162 1.01357 1.01104 1.0087 1.00664 1.0049 1.00348 1.00237 1.00154 1.00093 1.0005 1.00022 1.00004 0.999941 0.99989 0.999871 0.999871 0.999883 0.9999 0.999919 0.999935 0.99995 0.999963 0.999973 0.999981 0.999987 0.999991 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.02158 1.0234 1.02473 1.02557 1.02599 1.02614 1.02615 1.02618 1.02633 1.02666 1.02713 1.02761 1.02793 1.02791 1.02736 1.0262 1.02441 1.02208 1.01937 1.01645 1.01353 1.01078 1.0083 1.00617 1.00443 1.00305 1.002 1.00123 1.00069 1.00033 1.0001 0.999961 0.999891 0.999862 0.999859 0.999869 0.999887 0.999908 0.999926 0.999943 0.999958 0.999969 0.999978 0.999984 0.999989 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.02443 1.02568 1.02619 1.02603 1.02537 1.02445 1.02356 1.02295 1.02282 1.02324 1.02418 1.02546 1.02681 1.02791 1.02845 1.0282 1.02708 1.02513 1.02251 1.01947 1.01625 1.0131 1.0102 1.00766 1.00555 1.00386 1.00256 1.0016 1.00092 1.00046 1.00017 0.999994 0.999899 0.999857 0.999848 0.999857 0.999876 0.999897 0.999917 0.999936 0.999952 0.999965 0.999975 0.999983 0.999988 0.999992 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.02636 1.02648 1.02554 1.02372 1.02133 1.01877 1.01649 1.0149 1.01431 1.01484 1.01646 1.01893 1.02184 1.0247 1.02701 1.02836 1.02851 1.02745 1.02532 1.02242 1.01907 1.01562 1.01232 1.00936 1.00685 1.00481 1.00323 1.00205 1.00121 1.00064 1.00027 1.00004 0.999917 0.999858 0.99984 0.999846 0.999864 0.999886 0.999909 0.99993 0.999947 0.999961 0.999972 0.999981 0.999987 0.999991 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.0267 1.02497 1.02179 1.01748 1.01256 1.00765 1.00342 1.00046 0.999205 0.999872 1.00241 1.00651 1.01161 1.01699 1.02191 1.02571 1.02795 1.02847 1.02738 1.02502 1.02182 1.01821 1.01459 1.01124 1.00832 1.00591 1.00401 1.00259 1.00156 1.00086 1.00039 1.00011 0.999947 0.999866 0.999837 0.999837 0.999854 0.999876 0.999901 0.999923 0.999942 0.999957 0.999969 0.999978 0.999985 0.99999 0.999993 0.999996 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.02473 1.02025 1.01386 1.00611 0.997763 0.989734 0.982941 0.978188 0.976071 0.976885 0.980587 0.986777 0.994733 1.00349 1.01199 1.01925 1.02455 1.02753 1.02821 1.02694 1.02426 1.02075 1.01694 1.01324 1.00993 1.00714 1.00491 1.00322 1.00198 1.00112 1.00055 1.0002 0.99999 0.999882 0.999838 0.999832 0.999846 0.999868 0.999893 0.999916 0.999936 0.999954 0.999967 0.999977 0.999984 0.999989 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.01967 1.01141 1.00075 0.988534 0.975849 0.963935 0.953997 0.947066 0.943896 0.944867 0.949951 0.958669 0.970133 0.983113 0.9962 1.00802 1.01748 1.02393 1.02725 1.02777 1.02612 1.02304 1.01925 1.01532 1.01166 1.0085 1.00592 1.00393 1.00246 1.00143 1.00074 1.00031 1.00005 0.999909 0.999847 0.999831 0.99984 0.999861 0.999887 0.999911 0.999932 0.99995 0.999964 0.999975 0.999983 0.999988 0.999992 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.01082 0.997688 0.981688 0.964017 0.946161 0.929705 0.916143 0.906724 0.902351 0.903482 0.91011 0.9217 0.937218 0.955174 0.973791 0.991255 1.00602 1.01705 1.024 1.02712 1.0271 1.02489 1.02139 1.01739 1.01346 1.00994 1.00702 1.00472 1.00301 1.00179 1.00097 1.00044 1.00012 0.999947 0.999863 0.999835 0.999838 0.999857 0.999882 0.999907 0.999928 0.999947 0.999962 0.999973 0.999981 0.999987 0.999992 0.999995 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.997662 0.978593 0.956271 0.932322 0.908654 0.887193 0.869711 0.857626 0.851956 0.853233 0.861479 0.876137 0.896066 0.919557 0.944474 0.968537 0.989679 1.0064 1.01801 1.02461 1.02694 1.02609 1.02322 1.01935 1.01526 1.01145 1.00819 1.00559 1.00362 1.0022 1.00123 1.0006 1.00021 0.999995 0.999886 0.999844 0.99984 0.999855 0.999878 0.999903 0.999926 0.999945 0.99996 0.999972 0.999981 0.999987 0.999991 0.999995 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.979946 0.954027 0.924619 0.893827 0.863987 0.837342 0.815862 0.80109 0.794105 0.795498 0.805328 0.823061 0.847508 0.876808 0.90852 0.9399 0.968323 0.991734 1.00899 1.01997 1.02538 1.02645 1.0246 1.02111 1.01701 1.01297 1.00942 1.00651 1.00428 1.00265 1.00152 1.00078 1.00032 1.00006 0.999918 0.999859 0.999846 0.999856 0.999877 0.999901 0.999923 0.999943 0.999959 0.999971 0.99998 0.999986 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.957792 0.924354 0.8874 0.849543 0.813515 0.781808 0.756504 0.739191 0.730955 0.732419 0.743689 0.764301 0.793094 0.828142 0.866787 0.90587 0.942197 0.973091 0.996871 1.01306 1.02227 1.02584 1.02542 1.02259 1.01863 1.01447 1.01066 1.00747 1.00497 1.00313 1.00185 1.00099 1.00045 1.00013 0.999959 0.99988 0.999856 0.99986 0.999878 0.999901 0.999923 0.999942 0.999958 0.99997 0.999979 0.999986 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.931705 0.890396 0.8458 0.801027 0.759141 0.722789 0.694063 0.67451 0.665167 0.666658 0.679137 0.70225 0.734941 0.775336 0.820666 0.867447 0.91195 0.950838 0.981799 1.00391 1.01757 1.02417 1.02559 1.0237 1.02008 1.0159 1.01189 1.00844 1.0057 1.00365 1.00219 1.00121 1.00059 1.00022 1.00001 0.999909 0.999872 0.999869 0.999882 0.999903 0.999924 0.999943 0.999958 0.99997 0.999979 0.999986 0.99999 0.999994 0.999996 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.902547 0.853367 0.801398 0.750204 0.703089 0.66275 0.631184 0.609817 0.599585 0.601068 0.614472 0.639572 0.675498 0.720536 0.771943 0.826026 0.878592 0.925642 0.964176 0.992708 1.01135 1.02146 1.02509 1.02441 1.02131 1.01722 1.01308 1.00941 1.00643 1.00417 1.00255 1.00145 1.00074 1.00031 1.00007 0.999944 0.999892 0.999881 0.99989 0.999908 0.999926 0.999944 0.999959 0.999971 0.99998 0.999986 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.871456 0.814747 0.755992 0.699144 0.647644 0.604128 0.570416 0.547736 0.536877 0.538337 0.55236 0.578868 0.617235 0.666009 0.722601 0.783249 0.843395 0.898426 0.944615 0.979843 1.00382 1.01779 1.02394 1.02471 1.02229 1.01841 1.0142 1.01035 1.00716 1.00471 1.00293 1.0017 1.00091 1.00042 1.00013 0.999985 0.999917 0.999896 0.999899 0.999914 0.99993 0.999947 0.999961 0.999972 0.99998 0.999987 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.839735 0.776123 0.711405 0.64984 0.594902 0.549073 0.513933 0.490456 0.479238 0.480676 0.495028 0.522367 0.562354 0.613871 0.6746 0.740838 0.807783 0.870287 0.923905 0.965831 0.995288 1.01333 1.02222 1.02461 1.02302 1.01944 1.01524 1.01125 1.00787 1.00523 1.0033 1.00196 1.00108 1.00053 1.00021 1.00003 0.999947 0.999916 0.999912 0.999922 0.999935 0.99995 0.999963 0.999974 0.999982 0.999987 0.999992 0.999994 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.808734 0.739051 0.669325 0.604035 0.5466 0.499275 0.463365 0.439551 0.42822 0.429639 0.444064 0.471726 0.512577 0.565884 0.629677 0.70042 0.773191 0.842398 0.902938 0.951305 0.986175 1.00834 1.02006 1.02419 1.02352 1.02031 1.01617 1.01208 1.00854 1.00574 1.00367 1.00222 1.00125 1.00065 1.00028 1.00008 0.999981 0.999938 0.999927 0.999932 0.999943 0.999955 0.999967 0.999976 0.999983 0.999988 0.999992 0.999995 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.779738 0.70493 0.631185 0.563112 0.50402 0.455898 0.419744 0.395959 0.384696 0.386093 0.400397 0.427975 0.469074 0.52335 0.589224 0.663403 0.740941 0.815918 0.882647 0.936954 0.976953 1.00311 1.01762 1.02351 1.02381 1.02103 1.01699 1.01283 1.00917 1.00622 1.00402 1.00247 1.00143 1.00076 1.00036 1.00014 1.00002 0.999963 0.999944 0.999944 0.999951 0.999961 0.999971 0.999979 0.999985 0.99999 0.999993 0.999996 0.999997 0.999998 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.753885 0.674935 0.598107 0.528072 0.468001 0.419603 0.383578 0.360056 0.348971 0.35034 0.36439 0.391612 0.432515 0.487127 0.55426 0.630907 0.712176 0.791909 0.863936 0.923483 0.968121 0.997965 1.01512 1.0227 1.02394 1.0216 1.01769 1.0135 1.00973 1.00666 1.00435 1.0027 1.00159 1.00088 1.00044 1.00019 1.00006 0.999991 0.999964 0.999958 0.999961 0.999968 0.999975 0.999982 0.999987 0.999991 0.999994 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.732115 0.649979 0.570905 0.499572 0.439002 0.390662 0.354975 0.331824 0.320963 0.322293 0.336029 0.362756 0.403199 0.457714 0.52548 0.603781 0.687817 0.77128 0.847621 0.911558 0.960172 0.993243 1.01274 1.02185 1.02396 1.02204 1.01827 1.01407 1.01021 1.00705 1.00464 1.00292 1.00175 1.00099 1.00052 1.00025 1.0001 1.00002 0.999985 0.999973 0.999972 0.999976 0.999981 0.999986 0.99999 0.999993 0.999995 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.715151 0.63073 0.550116 0.477984 0.417219 0.369091 0.3338 0.311029 0.300383 0.301674 0.315104 0.341316 0.3812 0.435375 0.503335 0.582627 0.668574 0.754774 0.834399 0.901769 0.953561 0.989258 1.0107 1.02108 1.02394 1.02239 1.01874 1.01453 1.01062 1.00737 1.00489 1.00311 1.00189 1.00109 1.0006 1.00031 1.00014 1.00005 1.00001 0.99999 0.999984 0.999984 0.999987 0.99999 0.999993 0.999995 0.999996 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.703491 0.617624 0.536064 0.463487 0.402679 0.354777 0.319826 0.297365 0.286893 0.28816 0.301348 0.327126 0.366488 0.420237 0.488108 0.567871 0.654967 0.742954 0.824819 0.894597 0.948669 0.986282 1.00916 1.0205 1.02392 1.02264 1.0191 1.01489 1.01093 1.00764 1.0051 1.00327 1.00201 1.00119 1.00067 1.00036 1.00018 1.00008 1.00003 1.00001 0.999995 0.999993 0.999993 0.999994 0.999996 0.999997 0.999998 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.697424 0.610894 0.528906 0.456134 0.395332 0.347577 0.312833 0.290564 0.28021 0.281481 0.294533 0.320033 0.359007 0.41236 0.479982 0.559803 0.64736 0.73622 0.819274 0.890396 0.945781 0.984523 1.00826 1.02018 1.02394 1.02283 1.01934 1.01514 1.01116 1.00782 1.00526 1.0034 1.00211 1.00127 1.00073 1.00041 1.00022 1.00011 1.00005 1.00002 1.00001 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.697048 0.610602 0.528661 0.455907 0.395115 0.347384 0.31268 0.290466 0.280162 0.281474 0.294523 0.319935 0.358713 0.411774 0.479062 0.55859 0.64597 0.734811 0.818003 0.889376 0.945067 0.984107 1.00808 1.02017 1.02402 1.02295 1.01948 1.01527 1.01128 1.00794 1.00536 1.00348 1.00219 1.00133 1.00079 1.00046 1.00026 1.00014 1.00008 1.00004 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.702285 0.616655 0.535242 0.462724 0.401963 0.354142 0.319323 0.29703 0.286724 0.288114 0.301291 0.326814 0.3656 0.418489 0.48538 0.564286 0.650868 0.738803 0.821076 0.891604 0.946581 0.98507 1.00865 1.02047 1.02417 1.02301 1.0195 1.01529 1.0113 1.00797 1.0054 1.00353 1.00224 1.00138 1.00083 1.00049 1.00029 1.00017 1.0001 1.00006 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.712902 0.628828 0.548459 0.476456 0.415805 0.367848 0.332809 0.310342 0.299995 0.301508 0.31493 0.34073 0.379689 0.432489 0.498888 0.576819 0.661955 0.748094 0.828397 0.89699 0.950252 0.987357 1.00992 1.02107 1.02436 1.023 1.01941 1.01518 1.01122 1.00792 1.00538 1.00354 1.00226 1.00142 1.00087 1.00053 1.00032 1.00019 1.00012 1.00007 1.00005 1.00003 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.728546 0.646768 0.568016 0.49691 0.436553 0.388511 0.353233 0.330561 0.320175 0.321856 0.335614 0.361798 0.401009 0.453709 0.519431 0.59596 0.678961 0.762388 0.839678 0.905287 0.95588 0.990822 1.0118 1.0219 1.02457 1.0229 1.01919 1.01496 1.01104 1.00779 1.00531 1.00351 1.00226 1.00143 1.00089 1.00055 1.00034 1.00021 1.00013 1.00009 1.00006 1.00004 1.00002 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.748752 0.670032 0.593524 0.523797 0.46406 0.416124 0.3807 0.357879 0.347501 0.349399 0.363535 0.390122 0.429549 0.481998 0.546724 0.621317 0.701424 0.781202 0.854463 0.916092 0.963146 0.995236 1.01413 1.02286 1.02474 1.02267 1.01883 1.0146 1.01075 1.00759 1.00518 1.00343 1.00223 1.00142 1.0009 1.00057 1.00036 1.00023 1.00015 1.0001 1.00007 1.00004 1.00003 1.00002 1.00001 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.77292 0.698055 0.624497 0.556734 0.498081 0.450586 0.415255 0.392438 0.382159 0.384313 0.398809 0.425707 0.465162 0.517048 0.580298 0.652286 0.728669 0.803857 0.872122 0.928876 0.971634 1.0003 1.01672 1.02384 1.02481 1.02231 1.01833 1.01412 1.01036 1.00731 1.00499 1.00333 1.00217 1.0014 1.0009 1.00058 1.00037 1.00024 1.00016 1.00011 1.00007 1.00005 1.00003 1.00002 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; boundaryField { emptyPatches_empt { type empty; } top_cyc { type cyclic; } bottom_cyc { type cyclic; } inlet_cyc { type cyclic; } outlet_cyc { type cyclic; } procBoundary3to1 { type processor; value nonuniform List<scalar> 75 ( 0.800318 0.730123 0.660304 0.595207 0.538236 0.491657 0.456777 0.434218 0.424176 0.426605 0.441358 0.468348 0.50748 0.558309 0.619434 0.688028 0.759795 0.829477 0.891875 0.942994 0.980856 1.00567 1.01935 1.02472 1.02471 1.02177 1.01768 1.01352 1.00988 1.00696 1.00476 1.00318 1.00209 1.00136 1.00089 1.00058 1.00038 1.00025 1.00017 1.00012 1.00008 1.00006 1.00004 1.00003 1.00002 1.00001 1.00001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; } procBoundary3to1throughtop_cyc { type processorCyclic; value nonuniform List<scalar> 75 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; } procBoundary3to2 { type processor; value nonuniform List<scalar> 75 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999998 0.999998 0.999997 0.999995 0.999993 0.999991 0.999988 0.999983 0.999978 0.999971 0.999963 0.999953 0.999942 0.99993 0.999917 0.999907 0.999901 0.999904 0.999922 0.999967 1.00005 1.00019 1.00042 1.00076 1.00125 1.00194 1.00289 1.00414 1.00575 1.00775 1.01017 1.01298 1.01609 1.01935 1.0225 1.02517 1.02688 1.02706 1.02508 1.02035 1.01236 1.00079 0.985598 0.967028 0.945632 0.922226 0.897807 0.873471 0.850314 0.829353 0.81147 0.79737 0.787565 0.782369 0.781905 0.786124 0.794833 0.807706 0.824281 0.843979 ) ; } procBoundary3to2throughoutlet_cyc { type processorCyclic; value nonuniform List<scalar> 75 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; } } // ************************************************************************* //
d7b7c972124f6d26a279951dbe28bc3113dde766
ecde4736e27b275b37bf1ccd7f375e31c1faf733
/2006old/ServerMonitor/ServerSummary.cpp
20faf3f92f2d78b18561d3e68a4b1b86eebfd9ff
[]
no_license
bahamut8348/xkcode
1d85ef9b806c13af7193c9fd2281c99f174357a3
41665e5601d6d555ae2633ac0aa8cc1108a6b6bf
refs/heads/master
2016-09-10T17:29:15.351377
2013-05-17T02:37:30
2013-05-17T02:37:30
34,992,677
1
1
null
null
null
null
UTF-8
C++
false
false
6,714
cpp
ServerSummary.cpp
#include "StdAfx.h" #include "ServerStatus.h" #include "ServerSummary.h" #include "resource.h" #define CPUAGESTR L"%2.06f" BOOL CServerSummary::PreTranslateMessage( MSG* pMsg ) { if (CFrameWindowImpl<CServerSummary>::PreTranslateMessage(pMsg)) return TRUE; return FALSE; } BOOL CServerSummary::OnIdle() { return FALSE; } LRESULT CServerSummary::OnCreate( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ ) { CImageList il; il.Create(16,16, ILC_COLOR32, 5,5); il.AddIcon(::AtlLoadIcon(IDI_RUNAPP)); il.AddIcon(::AtlLoadIcon(IDI_UP)); il.AddIcon(::AtlLoadIcon(IDI_DOWN)); m_ServerList.Create(m_hWnd, rcDefault, NULL,WS_HSCROLL| WS_VISIBLE | WS_CHILDWINDOW | LVS_REPORT |LVS_SINGLESEL |WS_CLIPCHILDREN|LVS_SHOWSELALWAYS ); m_hWndClient = m_ServerList; m_ServerList.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT | LVS_EX_SUBITEMIMAGES ); m_ServerList.SetImageList(il.m_hImageList, LVSIL_SMALL); struct ColumnHeader { LPTSTR name; DWORD width; DWORD pos; } headers[] = { L"Name",150,LVCFMT_LEFT, L"PID", 80, LVCFMT_RIGHT, L"CPU", 80, LVCFMT_RIGHT, L"Memory", 100, LVCFMT_RIGHT, L"Virtual Memory", 100, LVCFMT_RIGHT, L"Version", 100, LVCFMT_LEFT, L"Command Line", 300, LVCFMT_LEFT }; for(DWORD a=0; a<(sizeof(headers)/sizeof(headers[0])); a++) { m_ServerList.InsertColumn(a, headers[a].name, headers[a].pos, headers[a].width); } SetTimer(1,500,NULL); return 0; } void CServerSummary::AddServer( const CServerStatus *pServer ) { LV_ITEM item; ZeroMemory(&item, sizeof(item)); item.mask = LVIF_PARAM | LVIF_TEXT | LVIF_IMAGE|LVIF_IMAGE; item.lParam = (LPARAM)pServer; item.iImage = I_IMAGECALLBACK; item.pszText= LPSTR_TEXTCALLBACK; item.cchTextMax = MAX_PATH; m_ServerList.InsertItem(&item); //int n=m_ServerList.InsertItem(0,L"sdfdf",0); //m_ServerList.SetItemData(n, (LPARAM)pServer); } LRESULT CServerSummary::OnLVGetDispInfo( int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/ ) { NMLVDISPINFO *pdi = (NMLVDISPINFO*)pnmh; LVITEM & item = pdi->item; static CString s; static CServerStatus *pServer; pServer = (CServerStatus *)item.lParam; static TCHAR tstr[24]; if(pdi->hdr.hwndFrom == m_ServerList.m_hWnd) { switch (item.iSubItem) { case 0: { //item.mask = LVIF_TEXT | LVIF_IMAGE; item.iImage = 0; wcsncpy_s(item.pszText,item.cchTextMax, pServer->m_ProcInfo.Name ,item.cchTextMax); break; } case 1: { _itow_s(pServer->m_ProcInfo.PID, item.pszText, item.cchTextMax, 10); break; } case 2: { // CPU Usage break; } case 3: { // Memory Usage break; } case 4: { // virtual usage _itow_s(pServer->m_VMemUsage, item.pszText, item.cchTextMax, 10); break; } case 5: { wcsncpy_s(item.pszText,item.cchTextMax, pServer->m_ProcInfo.FileVersion ,item.cchTextMax); break; } case 6: { item.pszText =(LPTSTR) (LPCTSTR)pServer->m_CmdLine; //wcsncpy_s(item.pszText,item.cchTextMax, pServer->m_CmdLine ,item.cchTextMax); break; } } } return 1; } void CServerSummary::DelServer( const CServerStatus *pServer ) { static LVFINDINFO fi; ZeroMemory(&fi,sizeof fi); fi.flags = LVFI_PARAM | LVFI_PARTIAL; fi.lParam = (LPARAM) pServer; int n= m_ServerList.FindItem( &fi ,-1 ); m_ServerList.DeleteItem(n); } LRESULT CServerSummary::OnTimer( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/ ) { for(int a=0; a<m_ServerList.GetItemCount(); a++) { CServerStatus *pServer = (CServerStatus *) m_ServerList.GetItemData(a); static TCHAR memstr[24]; static TCHAR tstr[24]; bool need = false; int UseImage = -1; LVITEM litem={0}; litem.mask = LVIF_IMAGE; litem.iSubItem =3; litem.iItem = a; m_ServerList.GetItem(&litem); m_ServerList.GetItemText(a, litem.iSubItem, memstr,24); int memusage = _wtoi(memstr); int cha = pServer->m_MemUsage - memusage; litem.mask = 0; // = 0 if( cha != 0 ) { need = true; _itow_s(pServer->m_MemUsage, memstr, 24, 10); litem.mask |= LVIF_TEXT; litem.cchTextMax = 24; litem.pszText = memstr; if(cha > 0) { UseImage = 1; } else { UseImage = 2; } } if(litem.iImage != UseImage) { litem.iImage = UseImage; litem.mask |= LVIF_IMAGE; need = TRUE; } if(need) { m_ServerList.SetItem(&litem); } static TCHAR cpustr[24]; m_ServerList.GetItemText(a, 2, cpustr, 24); swprintf_s(tstr, 24, CPUAGESTR, pServer->m_CPUUsage); if( _tcscmp(tstr, cpustr ) != 0) { m_ServerList.SetItemText(a,2, tstr); need = true; } } return 0; } LRESULT CServerSummary::OnDbClick( int idCtrl, LPNMHDR pnmh, BOOL& /*bHandled*/ ) { if(pnmh->hwndFrom == m_ServerList.m_hWnd) { int idx = m_ServerList.GetSelectedIndex(); if(idx>-1) { ViewType *pView = (ViewType *) (CServerStatus *)m_ServerList.GetItemData(idx); SendMessage(GetParent().GetParent(), WM_TOFRAME, WF_SETACTIVEPAGE,(LPARAM)pView); } } return 1; } LRESULT CServerSummary::OnContextMenu( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/ ) { int idx = m_ServerList.GetSelectedIndex(); if(idx == -1) return 1; DWORD xPos = GET_X_LPARAM(lParam); DWORD yPos = GET_Y_LPARAM(lParam); CServerStatus *pServer = (CServerStatus *)m_ServerList.GetItemData(idx); CMenu m; m.LoadMenu(IDR_MENU1); int ret = m.GetSubMenu(0).TrackPopupMenu(TPM_NONOTIFY | TPM_RETURNCMD ,xPos, yPos, m_hWnd ); if(ret == ID_FORSERVERITEM_ACTIVE) { ::ShowWindow(pServer->m_hwndProc, SW_SHOW); ::SetForegroundWindow(pServer->m_hwndProc); ::SetActiveWindow(pServer->m_hwndProc); } else if(ret == ID_FORSERVERITEM_HIDE) { ::ShowWindow(pServer->m_hwndProc, SW_HIDE); } else if(ret == ID_FORSERVERITEM_SHOW) { ::ShowWindow(pServer->m_hwndProc, SW_SHOW); } else if(ret == ID_FORSERVERITEM_HIDEALL) { for(int a =0; a < m_ServerList.GetItemCount(); a++) { ::ShowWindow(((CServerStatus *)m_ServerList.GetItemData(a))->m_hwndProc, SW_HIDE); } }else if(ret == ID_FORSERVERITEM_STOP ) { Utils::KillProcess(pServer->m_ProcInfo.PID); } else if(ret == ID_FORSERVERITEM_RESTART) { Utils::KillProcess(pServer->m_ProcInfo.PID); if(pServer->m_ServiceName.IsEmpty()) { Utils::StartProcess(pServer->m_CmdLine,pServer->m_Title); } else { Utils::StartService(pServer->m_ServiceName); } } return 0; }
3a3324347e6c6878a0795c9a3c768935f898eefe
97e642461856458e1912627510619fe2cd3f27be
/code/utils/lipschitz.cpp
83a742b3332e1eb97b1f4647b67cf5980e06d90f
[ "Apache-2.0" ]
permissive
eth-sri/deepg
390d3da1a04af7fc46564dc13518aff0df17b0c6
f7e553028eaffd99eb59a1594c9e58ef830a80b1
refs/heads/master
2023-04-06T20:26:25.654823
2021-07-15T13:38:19
2021-07-15T13:38:19
218,042,975
16
6
Apache-2.0
2023-03-24T23:25:37
2019-10-28T12:35:53
Python
UTF-8
C++
false
false
13,291
cpp
lipschitz.cpp
#include "utils/lipschitz.h" #include "utils/constants.h" #include <queue> #include <random> std::ostream& operator << (std::ostream& os, const PointD& pt) { os << "("; for (size_t i = 0; i < pt.x.size(); ++i) { if (i != 0) { os << ","; } os << pt.x[i]; } os << ")"; return os; } PointD PointD::operator + (const PointD& other) const { assert(x.size() == other.x.size()); vector<double> retX = this->x; for (size_t i = 0; i < other.x.size(); ++i) { retX[i] += other.x[i]; } return PointD(retX); } std::ostream& operator << (std::ostream& os, const HyperBox& box) { os << "("; for (size_t i = 0; i < box.it.size(); ++i) { if (i != 0) { os << ","; } os << box.it[i]; } os << ")"; return os; } vector<PointD> HyperBox::sample(int k, std::default_random_engine generator) const { vector<std::uniform_real_distribution<double>> diss; for (auto itv : it) { diss.emplace_back(itv.inf, itv.sup); } vector<PointD> ret; for (int i = 0; i < k; ++i) { PointD samplePoint; for (auto d : diss) { samplePoint.x.push_back(d(generator)); } ret.push_back(samplePoint); } return ret; } bool HyperBox::inside(PointD p) const { assert(dim == p.x.size()); for (size_t i = 0; i < dim; ++i) { if (p.x[i] < it[i].inf - Constants::EPS) { return false; } if (p.x[i] > it[i].sup + Constants::EPS) { return false; } } return true; } PointD HyperBox::center() const { std::vector<double> ret; for (auto itv : it) { ret.push_back(0.5 * (itv.inf + itv.sup)); } return PointD(ret); } void HyperBox::split(size_t dim1, HyperBox &hbox1, HyperBox &hbox2) const { assert(dim1 <= dim); hbox1.it.insert(hbox1.it.begin(), it.begin(), it.begin() + dim1); hbox2.it.insert(hbox2.it.begin(), it.begin() + dim1, it.end()); hbox1.dim = hbox1.it.size(); hbox2.dim = hbox2.it.size(); } HyperBox HyperBox::concatenate(const HyperBox &hbox1, const HyperBox &hbox2) { HyperBox hbox; hbox.it.insert(hbox.it.end(), hbox1.it.begin(), hbox1.it.end()); hbox.it.insert(hbox.it.end(), hbox2.it.begin(), hbox2.it.end()); hbox.dim = hbox1.dim + hbox2.dim; return hbox; } vector<HyperBox> HyperBox::split(int k, vector<vector<double>>& splitPoints) const { if (!splitPoints.empty()) { assert(splitPoints.size() == dim); for (int i = 0; i < dim; ++i) { for (double& x : splitPoints[i]) { x = it[i].inf + x * (it[i].sup - it[i].inf); } } } else { splitPoints.resize(dim); for (int i = 0; i < dim; ++i) { double delta = it[i].length() / k; for (int j = 1; j <= k - 1; ++j) { splitPoints[i].push_back(it[i].inf + j * delta); } } } vector<vector<Interval>> chunks(dim); for (int i = 0; i < dim; ++i) { double prev = it[i].inf; for (double x : splitPoints[i]) { chunks[i].emplace_back(prev, x); prev = x; } chunks[i].emplace_back(prev, it[i].sup); } vector<HyperBox> ret; for (size_t i = 0; i < dim; ++i) { vector<HyperBox> tmp = ret; ret.clear(); for (const Interval& chunk : chunks[i]) { if (i == 0) { ret.push_back(HyperBox({chunk})); } else { for (HyperBox hbox : tmp) { HyperBox newBox = hbox; ++newBox.dim; newBox.it.push_back(chunk); ret.push_back(newBox); } } } } return ret; } int HyperBox::getIndexToCut(pair<bool, vector<Interval>> grad) const { vector<double> ret; if (Constants::SPLIT_MODE == "standard") { for (auto itv : it) { ret.push_back(itv.sup - itv.inf); } } else if (Constants::SPLIT_MODE == "gradient") { for (int k = 0; k < it.size(); ++k) { ret.push_back( (it.at(k).sup - it.at(k).inf) * (grad.second.at(k).sup - grad.second.at(k).inf)); } } else if (Constants::SPLIT_MODE == "gradientSign") { for (int k = 0; k < it.size(); ++k) { if (grad.second.at(k).inf < 0 && 0 < grad.second.at(k).sup ) { ret.push_back( (it.at(k).sup - it.at(k).inf) * (grad.second.at(k).sup - grad.second.at(k).inf)); } else { ret.push_back( 0 ); } } } else { assert(false); } return (int)(max_element(ret.begin(), ret.end()) - ret.begin()); } double HyperBox::diameter() const { double sum = 0; for (auto itv : it) { sum += pow(itv.sup - itv.inf, 2.0); } return sqrt(sum); } Interval& HyperBox::operator[](int i) { return it[i]; } vector<HyperBox> branching(HyperBox& box, int p, pair<bool, vector<Interval>> grad) { int t = box.getIndexToCut(grad); double delta = (box[t].sup - box[t].inf) / p; vector<HyperBox> ret; for (int q = 0; q < p; ++q) { HyperBox tmp = box; tmp[t] = {tmp[t].inf + delta*q, tmp[t].inf + delta*(q+1)}; ret.push_back(tmp); } return ret; } // LipschitzFunction operator * (const double x, const LipschitzFunction& f) { // auto fgrad = f.gradF; // auto ff = f.f; // std::function<double(vector<double>)> mulF = [x, ff](vector<double> xp) { // return x * ff(xp); // }; // function<pair<bool, vector<Interval>>(const HyperBox& hbox)> mulGrad = [x, fgrad](const HyperBox& hbox) { // auto ret = fgrad(hbox); // for (size_t i = 0; i < ret.second.size(); ++i) { // ret.second[i] = ret.second[i] * x; // } // return ret; // }; // return LipschitzFunction(mulF, f.domain, f.image * x, mulGrad); // } // LipschitzFunction LipschitzFunction::operator * (const LipschitzFunction &other) { // assert(domain.it.size() == other.domain.it.size()); // assert(false); // auto tmp1 = f, tmp2 = other.f; // std::function<double(vector<double>)> mulF = [tmp1, tmp2](vector<double> x) { // return tmp1(x) * tmp2(x); // }; // return LipschitzFunction(mulF, domain, image * other.image); // } LipschitzFunction LipschitzFunction::operator + (const LipschitzFunction& other) { assert(domain.it.size() == other.domain.it.size()); auto tmp1 = f, tmp2 = other.f; std::function<double(vector<double>)> sumF = [tmp1, tmp2](vector<double> x) { return tmp1(x) + tmp2(x); }; auto tmpGrad1_i = gradF_interval, tmpGrad2_i = other.gradF_interval; function<pair<bool, vector<Interval>>(const HyperBox& hbox)> addGrad_i = [tmpGrad1_i, tmpGrad2_i](const HyperBox& hbox) { auto p1 = tmpGrad1_i(hbox), p2 = tmpGrad2_i(hbox); vector<Interval> ret; for (size_t i = 0; i < p1.second.size(); ++i) { ret.push_back(p1.second[i] + p2.second[i]); } return make_pair(true, ret); }; return LipschitzFunction(sumF, domain, addGrad_i); } LipschitzFunction LipschitzFunction::operator - (const LipschitzFunction& other) { return *this + (-other); } LipschitzFunction LipschitzFunction::operator - () const { auto tmpF = f; auto tmpGradF_i = gradF_interval; std::function<double(vector<double>)> negativeF = [tmpF](vector<double> x) { return -tmpF(x); }; function<pair<bool, vector<Interval>>(const HyperBox& hbox)> negativeGradF_i = [tmpGradF_i](const HyperBox& hbox) { auto ret = tmpGradF_i(hbox); for (size_t i = 0; i < ret.second.size(); ++i) { ret.second[i] = -ret.second[i]; } return ret; }; auto ret = LipschitzFunction(negativeF, domain, negativeGradF_i); return ret; } double LipschitzFunction::getUpperBoundCauchySchwarz(const HyperBox& subdomain, PointD x, pair<bool, vector<Interval>> grad) const { double lipConst = 0; for (const Interval& pd : grad.second) { lipConst += max(pd.sup * pd.sup, pd.inf * pd.inf); } lipConst = sqrt(lipConst); return f(x) + 0.5 * lipConst * subdomain.diameter(); } double LipschitzFunction::getUpperBoundTriangle(const HyperBox& subdomain, PointD x, pair<bool, vector<Interval>> grad) const { double ret = f(x); for (int k = 0; k < subdomain.dim; ++k) { ret += 0.5 * max(abs(grad.second[k].inf), abs(grad.second[k].sup)) * (subdomain.it[k].sup - subdomain.it[k].inf); } return ret; } double LipschitzFunction::getUpperBound(const HyperBox& subdomain, PointD x) const { pair<bool, vector<Interval>> grad = gradF_interval(subdomain); if (Constants::UB_ESTIMATE == "Triangle") { return getUpperBoundTriangle(subdomain, x, grad); } else if (Constants::UB_ESTIMATE == "CauchySchwarz") { return getUpperBoundCauchySchwarz(subdomain, x, grad); } else { assert(false); } } double LipschitzFunction::maximize(double epsilon, int p, Statistics& counter, int maxIter) const { PointD x_opt = domain.center(); double f_opt = f(x_opt); if ((getUpperBound(domain, x_opt) - f_opt) <= epsilon) { return getUpperBound(domain, x_opt); } auto cmp = [](pair<HyperBox, double> left, pair<HyperBox, double> right) { return left.second > right.second; }; priority_queue<pair<HyperBox, double>, std::vector<pair<HyperBox, double>>, decltype(cmp)> pq(cmp); pq.push({domain, getUpperBound(domain, x_opt)}); for (int it = 0; it < maxIter && !pq.empty(); ++it) { pair<HyperBox, double> top = pq.top(); pq.pop(); HyperBox hbox = top.first; double bound = top.second; if (bound < f_opt) { continue; } pair<bool, vector<Interval>> grad = gradF_interval(hbox); /* * If function is differentiable on the entire hyperbox, make use of the gradients. * For every dimension j such that partial derivative of the function w.r.t variable x_j is * negative/positive on the entire hyperbox, set the value to left or right border of hyperbox immediately. */ bool modifiedBox = false; HyperBox newBox = hbox; for (size_t i = 0; i < hbox.dim; ++i) { if (hbox.it[i].sup > hbox.it[i].inf) { if (grad.second[i].inf >= 0) { modifiedBox = true; newBox.it[i] = {hbox.it[i].sup, hbox.it[i].sup}; } else if (grad.second[i].sup <= 0) { modifiedBox = true; newBox.it[i] = {hbox.it[i].inf, hbox.it[i].inf}; } } } if (modifiedBox) { auto new_x = newBox.center(); if (f(new_x) > f_opt) { f_opt = f(new_x); } double newBound = getUpperBound(newBox, new_x); if (newBound - f_opt > epsilon) { pq.push({newBox, newBound}); } continue; } vector<HyperBox> newBoxes = branching(hbox, p, grad); // Evaluation of sub-problems for (HyperBox chunkBox : newBoxes) { vector<double> x = chunkBox.center(); double f_x = f(x); if (f_x > f_opt) { f_opt = f_x; } double chunkBound = getUpperBound(chunkBox, x); if (chunkBound - f_opt > epsilon) { pq.push({chunkBox, chunkBound}); } } } double ret = f_opt + epsilon; while (!pq.empty()) { pair<HyperBox, double> top = pq.top(); pq.pop(); ret = max(ret, top.second); } return ret; } double LipschitzFunction::minimize(double epsilon, int p, Statistics& counter, int maxIter) const { LipschitzFunction selfNegative = -(*this); return -selfNegative.maximize(epsilon, p, counter, maxIter); } LipschitzFunction LipschitzFunction::getLinear(HyperBox domain, vector<double> weights, double bias, int degree) { assert(domain.dim * degree == weights.size()); std::function<double(vector<double>)> f = [domain, weights, bias, degree](vector<double> params) { assert(params.size() == domain.dim); double ret = bias; for (size_t i = 0; i < domain.dim; ++i) { for (int j = 0; j < degree; ++j) { ret += weights[i * degree + j] * pow(params[i], j + 1); } } return ret; }; std::function<pair<bool, vector<Interval>>(HyperBox)> gradF_interval = [domain, weights, degree](HyperBox hbox) { vector<Interval> ret; for (size_t i = 0; i < domain.dim; ++i) { Interval d(0, 0); for (int j = 0; j < degree; ++j) { d = d + (j + 1) * weights[i * degree + j] * hbox.it[i].pow(j); } ret.push_back(d); } return make_pair(true, ret); }; vector<double> linWeights; for (size_t i = 0; i < domain.dim; ++i) { linWeights.push_back(weights[i * degree]); } return LipschitzFunction(f, domain, gradF_interval); }
9ee80184db8a891593914d324fddb38733ef094a
86f1ea7058b2e107b1b9d6768d1c30ca3b0e3629
/HW_05/main.cpp
23135148e778b72e677bc06fa5187c05b009682d
[]
no_license
DT6A/HSE_OS
c497dfddfa77d70e2c59e6449e081864f0633222
b4402d4fd2d6b6e089df9a2b83bc82c702e2b0e8
refs/heads/main
2023-06-01T16:15:10.191809
2021-06-12T13:41:57
2021-06-12T13:41:57
332,246,010
1
0
null
null
null
null
UTF-8
C++
false
false
5,896
cpp
main.cpp
/* * Author: @kkarnauk */ #include <algorithm> #include <iostream> #include <cassert> #include <cstring> #include <vector> #include <set> #include <string> #include <random> #include "slab_allocator.hpp" #include "page_allocator.hpp" using namespace hse::arch_os; enum class Color { Blue, Green }; template<Color T> class colorText; std::string getPrefix(const colorText<Color::Green> &) { return "\033[1;32m"; } std::string getPrefix(const colorText<Color::Blue> &) { return "\033[1;34m"; } template<Color T> class colorText { public: explicit colorText(const std::string &text_) : text{text_} {} friend std::ostream &operator<<(std::ostream &out, const colorText &color) { out << getPrefix(color) << color.text << "\033[0m"; return out; } private: const std::string &text; }; std::mt19937 rnd(228); std::vector<std::size_t> randomPermutation(std::size_t len) { std::vector<std::size_t> perm(len); for (std::size_t i = 0; i < len; i++) { perm[i] = i; } std::shuffle(perm.begin(), perm.end(), rnd); return perm; } char *tocharp(void *memory) { return reinterpret_cast<char *>(memory); } std::vector<std::uint8_t> corruptMemory(void *memory, std::size_t len) { char *memoryChar = tocharp(memory); for (std::size_t i = 0; i < len; i++) { memoryChar[i] = rnd() & 255; } std::vector<std::uint8_t> bytes(len); std::memcpy(bytes.data(), memoryChar, len); return bytes; } void testNotCorruptedMemory(void *memory, const std::vector<uint8_t> &values) { assert(std::memcmp(memory, values.data(), values.size()) == 0); } void testAllocDealloc(std::size_t totalSize, std::size_t minObjectSize, std::size_t maxObjectSize) { for (std::size_t i = minObjectSize; i <= maxObjectSize; i++) { const std::size_t count = totalSize / i; { SlabAllocator alloc(i); for (std::size_t j = 0; j < count; j++) { assert(alloc.allocate() != nullptr); } } { SlabAllocator alloc(i); std::vector<void *> mems(count); for (std::size_t j = 0; j < count; j++) { mems[j] = alloc.allocate(); assert(mems[j] != nullptr); } for (std::size_t j : randomPermutation(count)) { alloc.deallocate(mems[j]); } } } } void testMemory(std::size_t totalSize, std::size_t minObjectSize, std::size_t maxObjectSize) { for (std::size_t i = minObjectSize; i <= maxObjectSize; i++) { const std::size_t count = totalSize / i; { SlabAllocator alloc(i); std::vector<void *> mems(count); std::vector<std::vector<std::uint8_t>> memValues(count); for (std::size_t j = 0; j < count; j++) { mems[j] = alloc.allocate(); memValues[j] = corruptMemory(mems[j], i); } for (std::size_t j = 0; j < count; j++) { testNotCorruptedMemory(mems[j], memValues[j]); } for (std::size_t j : randomPermutation(count)) { testNotCorruptedMemory(mems[j], memValues[j]); alloc.deallocate(mems[j]); } } } } void stressTest(std::size_t objectSize, std::size_t iterations) { constexpr std::size_t RANDOM_CHECKS_COUNT = 10; { SlabAllocator alloc(objectSize); std::vector<void *> mems; std::vector<std::vector<uint8_t>> memValues; std::set<std::size_t> indices; auto getRandomIndex = [&]() { return *indices.lower_bound(abs(int(rnd())) % (*indices.rbegin() + 1)); }; for (std::size_t iter = 0; iter < iterations; iter++) { int command = rnd(); if (command % 3 != 0) { // allocation mems.push_back(alloc.allocate()); memValues.push_back(corruptMemory(mems.back(), objectSize)); indices.insert(mems.size() - 1); } else { if (indices.empty()) { iterations++; continue; } std::size_t index = getRandomIndex(); indices.erase(index); testNotCorruptedMemory(mems[index], memValues[index]); alloc.deallocate(mems[index]); } if (indices.empty()) { continue; } for (std::size_t i = 0; i < RANDOM_CHECKS_COUNT; i++) { std::size_t index = getRandomIndex(); testNotCorruptedMemory(mems[index], memValues[index]); } } } std::cout << "Stress test. Object size = " << colorText<Color::Blue>(std::to_string(objectSize)) << ". " << colorText<Color::Green>("Completed.") << std::endl; } void testSmallAllocDealloc() { testAllocDealloc(SlabAllocator::BIG_SIZE << 7, 1, SlabAllocator::BIG_SIZE - 1); std::cout << "Test: small sizes. What: allocate/deallocate. " << colorText<Color::Green>("Completed.") << std::endl; } void testSmallMemory() { testMemory(SlabAllocator::BIG_SIZE << 6, 1, SlabAllocator::BIG_SIZE - 1); std::cout << "Test: small sizes. What: memory not corrupted. " << colorText<Color::Green>("Completed.") << std::endl; } void testSmallSizes() { testSmallAllocDealloc(); testSmallMemory(); for (std::size_t i = 1; i < SlabAllocator::BIG_SIZE; i *= (i < 10 ? 2 : 1.1)) { stressTest(i, 5000); } } constexpr std::size_t MAX_OBJECT_SIZE = PAGE_SIZE * 2; void testBigAllocDealloc() { testAllocDealloc(SlabAllocator::BIG_SIZE << 8, SlabAllocator::BIG_SIZE, MAX_OBJECT_SIZE); std::cout << "Test: big sizes. What: allocate/deallocate. " << colorText<Color::Green>("Completed.") << std::endl; } void testBigMemory() { testMemory(SlabAllocator::BIG_SIZE << 7, SlabAllocator::BIG_SIZE, MAX_OBJECT_SIZE); std::cout << "Test: big sizes. What: memory not corrupted. " << colorText<Color::Green>("Completed.") << std::endl; } void testBigSizes() { testBigAllocDealloc(); testBigMemory(); for (std::size_t i = SlabAllocator::BIG_SIZE; i <= MAX_OBJECT_SIZE; i *= 1.07) { stressTest(i, 5000); } } int main() { testSmallSizes(); testBigSizes(); }
5fb9219db62d49149fb4b33157696922398d0499
cacb08f4bc09e9fc0d74f828414ca8609619978c
/YEAR 3 - EGC/HW 1 - Bow and Arrow/Object2D.cpp
b60e714262c2aa9d40d13c7a9eb36bc7da8d8ec8
[]
no_license
ghiculescualexandru/Coursework
5e298b73aaedc32c1146af1a8f33c4724347832f
f06faeadb1d32c687aa0e6ddf8a338814204743a
refs/heads/master
2021-09-19T01:11:19.857376
2021-09-05T11:48:04
2021-09-05T11:48:04
202,554,704
0
0
null
null
null
null
UTF-8
C++
false
false
13,107
cpp
Object2D.cpp
#include "Object2D.h" #include <math.h> #include <Core/Engine.h> Mesh* Object2D::CreateSquare(std::string name, glm::vec3 leftBottomCorner, float length, glm::vec3 color, bool fill) { glm::vec3 corner = leftBottomCorner; std::vector<VertexFormat> vertices = { VertexFormat(corner, color), VertexFormat(corner + glm::vec3(length, 0, 0), color), VertexFormat(corner + glm::vec3(length, length, 0), color), VertexFormat(corner + glm::vec3(0, length, 0), color) }; std::vector<unsigned short> indices = { 0, 1, 2, 3, 0, 2 }; Mesh* item = new Mesh(name); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateBalloonLine(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { glm::vec3 corner = leftBottomCorner; std::vector<VertexFormat> vertices = { VertexFormat(corner, color), VertexFormat(corner + glm::vec3(0, -scale - scale / 10, 0), color), VertexFormat(corner + glm::vec3(-scale / 4, -scale * 1.25, 0), color), VertexFormat(corner + glm::vec3(scale / 4, -scale * 1.5, 0), color), VertexFormat(corner + glm::vec3(-scale / 4, -scale * 1.75, 0), color), VertexFormat(corner + glm::vec3(scale / 4, -scale * 2.00, 0), color), }; std::vector<unsigned short> indices = { 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }; Mesh* item = new Mesh(name); item->SetDrawMode(GL_LINES); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateTriangle(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { glm::vec3 corner = leftBottomCorner; std::vector<VertexFormat> vertices = { VertexFormat(corner + glm::vec3(0, -scale + scale/10, 0), color), VertexFormat(corner + glm::vec3(-scale * 0.10, -scale*1.1, 0), color), VertexFormat(corner + glm::vec3(scale * 0.10, -scale*1.1, 0), color), }; std::vector<unsigned short> indices = { 0, 1, 2, }; Mesh* item = new Mesh(name); item->SetDrawMode(GL_TRIANGLES); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateBow(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { // x = (cos 2pi / nr varfuri) * i // y = (sin 2pi / nr varfuri) * i std::vector<double> xCoordinates; std::vector<double> xxCoordinates; std::vector<double> yCoordinates; std::vector<double> yyCoordinates; int maxStep = 250; int steps = 0; double scaleFactor = 10; double xMin = 1.79769e+308; for (int i = 0; i < maxStep + 2; i++) { double x = cos(2 * M_PI / maxStep * i) * scale; double xx = cos(2 * M_PI / maxStep * i) * (scale - scale / scaleFactor); double y = sin(2 * M_PI / maxStep * i) * scale; double yy = sin(2 * M_PI / maxStep * i) * (scale - scale / scaleFactor); if (x > 0) { if (x < xMin) { xMin = x; } steps++; xCoordinates.push_back(x); xxCoordinates.push_back(xx); yCoordinates.push_back(y); yyCoordinates.push_back(yy); } } glm::vec3 corner = leftBottomCorner; std::vector<VertexFormat> vertices = { }; for (int i = 0; i < steps; i++) { double x = xCoordinates.at(i); double xx = xxCoordinates.at(i); double y = yCoordinates.at(i); double yy = yyCoordinates.at(i); if (x == xMin) { vertices.push_back(VertexFormat(glm::vec3(x - (scale / scaleFactor), y + scale * 2, 0), color)); vertices.push_back(VertexFormat(glm::vec3(x, 0, 0), color)); vertices.push_back(VertexFormat(glm::vec3(x - (scale / scaleFactor), 0, 0), color)); vertices.push_back(VertexFormat(glm::vec3(x, y, 0), color)); vertices.push_back(VertexFormat(glm::vec3(x - (scale / scaleFactor), y, 0), color)); } vertices.push_back(VertexFormat(glm::vec3(x, y, 0), color)); vertices.push_back(VertexFormat(glm::vec3(xx, yy, 0), color)); } std::vector<unsigned short> indices; for (int i = 0; i < steps * 2 + 5; i++) { indices.push_back(i); } Mesh* item = new Mesh(name); item->SetDrawMode(GL_TRIANGLE_STRIP); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateArrow(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { std::vector<VertexFormat> vertices = { VertexFormat(glm::vec3(0, -scale/15, 0), color), // 0 VertexFormat(glm::vec3(3 * scale, -scale/15, 0), color), // 1 VertexFormat(glm::vec3(3 * scale, scale/15, 0), color), // 2 VertexFormat(glm::vec3(0, scale/15, 0), color), // 3 VertexFormat(glm::vec3(3 * scale, 0, 0), color), // 4 VertexFormat(glm::vec3(4 * scale, 0, 0), color), // 5 VertexFormat(glm::vec3(3 * scale, 1 * scale, 0), color), // 6 VertexFormat(glm::vec3(3 * scale, -1 * scale, 0), color), // 7 }; std::vector<unsigned short> indices = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 5, 7, }; Mesh* item = new Mesh(name); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateBalloon(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { std::vector<double> xCoordinates; std::vector<double> yCoordinates; float xMin = 1.79769e+308, yMin = 1.79769e+308; int maxStep = 100; for (int i = 0; i < maxStep; i++) { double x = cos(2 * M_PI / maxStep * i) * scale / 2; double y = sin(2 * M_PI / maxStep * i) * scale; if (x < xMin) { xMin = x; } if (y < yMin) { yMin = y; } xCoordinates.push_back(x); yCoordinates.push_back(y); } glm::vec3 corner = leftBottomCorner; std::vector<VertexFormat> vertices = { VertexFormat(corner, color), }; for (int i = 1; i < maxStep; i++) { double x = xCoordinates.at(i); double y = yCoordinates.at(i); vertices.push_back(VertexFormat(glm::vec3(x, y, 0), color)); } std::vector<unsigned short> indices; for (int i = 1; i < maxStep; i++) { indices.push_back(i); } indices.push_back(1); Mesh* item = new Mesh(name); item->SetDrawMode(GL_TRIANGLE_FAN); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateStar(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { double scaleFactor = scale / 3; float c1 = scale; float c2 = scale; std::vector<VertexFormat> vertices = { VertexFormat(glm::vec3(0, -0, 0), color), // 0 VertexFormat(glm::vec3(0, c1, 0), color), // 1 VertexFormat(glm::vec3(-c2, c1, 0), color), // 2 VertexFormat(glm::vec3(-0, 0, 0), color), // 3 VertexFormat(glm::vec3(c1, 0, 0), color), // 4 VertexFormat(glm::vec3(c1, c2, 0), color), // 5 VertexFormat(glm::vec3(0, 0, 0), color), // 6 VertexFormat(glm::vec3(0, -c1, 0), color), // 7 VertexFormat(glm::vec3(c2, -c1, 0), color), // 8 VertexFormat(glm::vec3(0, 0, 0), color), // 9 VertexFormat(glm::vec3(-c1, 0, 0), color), // 10 VertexFormat(glm::vec3(-c1, -c2, 0), color), // 11 }; std::vector<unsigned short> indices = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11, }; Mesh* item = new Mesh(name); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateHeart(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { glm::vec3 corner = leftBottomCorner; std::vector<double> xCoordinates; std::vector<double> yCoordinates; int maxStep = 100; for (int i = 0; i < maxStep; i++) { double x = 16 * sin(2 * M_PI / maxStep * i) * sin(2 * M_PI / maxStep * i) * sin(2 * M_PI / maxStep * i) * scale; double y = 13 * cos(2 * M_PI / maxStep * i) * scale - 5 * cos(2 * 2 * M_PI / maxStep * i) * scale - 2 * cos(3 * 2 * M_PI / maxStep * i) * scale - cos(4 * 2 * M_PI / maxStep * i) * scale; xCoordinates.push_back(x); yCoordinates.push_back(y); } std::vector<VertexFormat> vertices = { VertexFormat(corner, color), }; for (int i = 1; i < maxStep; i++) { double x = xCoordinates.at(i); double y = yCoordinates.at(i); vertices.push_back(VertexFormat(glm::vec3(x, y, 0), color)); } std::vector<unsigned short> indices; for (int i = 1; i < maxStep; i++) { indices.push_back(i); } indices.push_back(1); Mesh* item = new Mesh(name); item->SetDrawMode(GL_TRIANGLE_FAN); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateCharacter(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { float s = scale; std::vector<VertexFormat> vertices = { VertexFormat(glm::vec3(-s, -s, 0), color), // 0 VertexFormat(glm::vec3(s, -s, 0), color), // 1 VertexFormat(glm::vec3(-s, 2 * s, 0), color), // 2 VertexFormat(glm::vec3(s, 2 * s, 0), color), // 3 VertexFormat(glm::vec3(-s / 2, -s, 0), color), // 4 VertexFormat(glm::vec3(0, -s, 0), color), // 5 VertexFormat(glm::vec3(-s, -2 * s, 0), color), // 6 VertexFormat(glm::vec3(-s / 2, - 2 * s, 0), color), // 7 VertexFormat(glm::vec3(s / 2, -s, 0), color), // 8 VertexFormat(glm::vec3(0, -s, 0), color), // 9 VertexFormat(glm::vec3(s, -2 * s, 0), color), // 10 VertexFormat(glm::vec3(s / 2, -2 * s, 0), color), // 11 VertexFormat(glm::vec3(s, 1.5 * s, 0), color), // 12 VertexFormat(glm::vec3(s, s, 0), color), // 13 VertexFormat(glm::vec3(1.5 * s, 2 * s, 0), color), // 14 VertexFormat(glm::vec3(2* s, 1.5 * s, 0), color), // 15 VertexFormat(glm::vec3(s, s / 1.2, 0), color), // 16 VertexFormat(glm::vec3(s, s / 1.8, 0), color), // 17 VertexFormat(glm::vec3(s * 2.2, s / 1.2, 0), color), // 18 VertexFormat(glm::vec3(s * 2.2, s / 1.8, 0), color), // 19 VertexFormat(glm::vec3(-s / 4, 2 * s, 0), color), // 20 VertexFormat(glm::vec3(s / 4, 2 * s, 0), color), // 21 VertexFormat(glm::vec3(-s / 4, 2.7 * s, 0), color), // 22 VertexFormat(glm::vec3(s / 4, 2.7 * s, 0), color), // 23 VertexFormat(glm::vec3(-s / 1.5, 2.7 * s, 0), color), // 24 VertexFormat(glm::vec3(s / 1.5, 2.7 * s, 0), color), // 25 VertexFormat(glm::vec3(-s / 1.5, 3.7 * s, 0), color), // 26 VertexFormat(glm::vec3(s / 1.5, 3.7 * s, 0), color), // 27 }; std::vector<unsigned short> indices = { 0, 1, 2, 1, 2, 3, 4, 5, 6, 5, 6, 7, 8, 9, 10, 9, 10,11, 12,13,14, 13,14,15, 16,17,18, 17,18,19, 20,21,22, 21,22,23, 24,25,26, 25,26,27 }; Mesh* item = new Mesh(name); item->InitFromData(vertices, indices); return item; } Mesh* Object2D::CreateGameOver(std::string name, glm::vec3 leftBottomCorner, float scale, glm::vec3 color, bool fill) { glm::vec3 corner = leftBottomCorner; float s = scale; std::vector<VertexFormat> vertices = { // letter G. VertexFormat(glm::vec3(-7.0 * s, +s, 0), color), VertexFormat(glm::vec3(-8.0 * s, +s, 0), color), VertexFormat(glm::vec3(-8.0 * s, -s, 0), color), VertexFormat(glm::vec3(-7.0 * s, -s, 0), color), VertexFormat(glm::vec3(-7.0 * s, +0, 0), color), VertexFormat(glm::vec3(-7.5 * s, +0, 0), color), // letter A. VertexFormat(glm::vec3(-6.0 * s, -s, 0), color), VertexFormat(glm::vec3(-5.5 * s, +s, 0), color), VertexFormat(glm::vec3(-5.0 * s, -s, 0), color), VertexFormat(glm::vec3(-5.0 * s, +0, 0), color), VertexFormat(glm::vec3(-6.0 * s, +0, 0), color), // letter M. VertexFormat(glm::vec3(-4.0 * s, -s, 0), color), //11 VertexFormat(glm::vec3(-4.0 * s, +s, 0), color), //12 VertexFormat(glm::vec3(-3.5 * s, +0, 0), color), //13 VertexFormat(glm::vec3(-3.0 * s, +s, 0), color), //14 VertexFormat(glm::vec3(-3.0 * s, -s, 0), color), //15 // letter E. VertexFormat(glm::vec3(-2.0 * s, +s, 0), color), //16 VertexFormat(glm::vec3(-2.0 * s, -s, 0), color), //17 VertexFormat(glm::vec3(-1.0 * s, +s, 0), color), //18 VertexFormat(glm::vec3(-1.0 * s, +0, 0), color), //19 VertexFormat(glm::vec3(-2.0 * s, +0, 0), color), //20 VertexFormat(glm::vec3(-1.0 * s, -s, 0), color), //21 // letter O. VertexFormat(glm::vec3(+1.0 * s, +s, 0), color), //22 VertexFormat(glm::vec3(+1.0 * s, -s, 0), color), //23 VertexFormat(glm::vec3(+2.0 * s, +s, 0), color), //24 VertexFormat(glm::vec3(+2.0 * s, -s, 0), color), //25 // letter V. VertexFormat(glm::vec3(+3.0 * s, +s, 0), color), //26 VertexFormat(glm::vec3(+3.5 * s, -s, 0), color), //27 VertexFormat(glm::vec3(+4.0 * s, +s, 0), color), //28 // letter E. VertexFormat(glm::vec3(+5.0 * s, +s, 0), color), //29 VertexFormat(glm::vec3(+5.0 * s, -s, 0), color), //30 VertexFormat(glm::vec3(+6.0 * s, +s, 0), color), //31 VertexFormat(glm::vec3(+6.0 * s, -s, 0), color), //32 VertexFormat(glm::vec3(+5.0 * s, +0, 0), color), //33 VertexFormat(glm::vec3(+6.0 * s, +0, 0), color), //34 // letter R. VertexFormat(glm::vec3(+7.0 * s, +s, 0), color), //35 VertexFormat(glm::vec3(+7.0 * s, -s, 0), color), //36 VertexFormat(glm::vec3(+8.0 * s, +s, 0), color), //37 VertexFormat(glm::vec3(+8.0 * s, +0, 0), color), //38 VertexFormat(glm::vec3(+7.0 * s, +0, 0), color), //39 VertexFormat(glm::vec3(+8.0 * s, -s, 0), color), //40 }; std::vector<unsigned short> indices = { 0,1, 1,2, 2,3, 3,4, 4,5, 6,7, 7,8, 9,10, 11,12, 12,13, 13,14, 14,15, 16,17, 16,18, 17,21, 19,20, 22,23, 23,25, 25,24, 22,24, 26,27, 27,28, 29,30, 29,31, 30,32, 33,34, 35,36, 35,37, 37,38, 38,39, 39,40 }; Mesh* item = new Mesh(name); item->SetDrawMode(GL_LINES); item->InitFromData(vertices, indices); return item; }
35d544d135d931c55acdcea3fb49c5592dc99b8a
bf032a886be90735d5d57797c1f43cfa0615407d
/src/gateway/cache.tpp
fbba5f1c75921fedc4eda6d25eb9a93b55b91993
[]
no_license
rucoder/modbusd
ef56d4dc5d4a3f8494df78052f46a8ff944b9b93
9b1371dc7afe574945fa75a91967803d2af4481b
refs/heads/master
2021-01-10T19:10:08.085045
2013-11-14T13:28:33
2013-11-14T13:28:33
10,158,479
0
2
null
null
null
null
UTF-8
C++
false
false
1,769
tpp
cache.tpp
// cache.tpp // /** @file @brief Cache template implementation. */ #ifndef _CACHE_TPP_ #define _CACHE_TPP_ #include "cache.hpp" namespace stek { namespace oasis { namespace ic { namespace dbgateway { template< typename item_t > _cache_t< item_t >::_cache_t( string_t const & name ) : object_t( name + " cache" ) { }; // ctor template< typename item_t > string_t _cache_t< item_t >::name( ) const { return _name; }; template< typename item_t > typename _cache_t< item_t >::items_t _cache_t< item_t >::get( keys_t const & keys ) const { mutex_t::locker_t locker( _mutex ); items_t items; for ( size_t i = 0; i < keys.size(); ++ i ) { const_iterator_t it = _bulk.find( keys[ i ] ); if ( it != _bulk.end() ) { items.push_back( it->second ); }; }; return items; }; // get template< typename item_t > void _cache_t< item_t >::update( items_t const & items ) { if ( items.empty() ) { DLOG( "nothing to do" ); } else { DLOG( items.size() << " item(s) received" ); size_t updated = 0; { mutex_t::locker_t locker( _mutex ); for ( size_t i = 0; i < items.size(); ++ i ) { item_t const & item = items[ i ]; iterator_t it = _bulk.find( item.key() ); if ( it == _bulk.end() || item.date > it->second.date ) { _bulk[ item.key() ] = item; ++ updated; }; // if }; // for i } DLOG( updated << " item(s) updated" ); }; // if }; // update }; // namespace dbgateway }; // namespace ic }; // namespace oasis }; // namespace stek #endif // _CACHE_TPP_ // end of file //
fb39c77895b290b0ef502a519401db9dac24b679
6d427c7b04cb92cee6cc8d37df07cf8b129fdada
/11000 - 11999/11292.cpp
812b367b0dbcbde285812ae74d9dc1fa6fb66102
[]
no_license
FForhad/Online-Judge-Ex.-Uva-Solutions
3c5851d72614274cafac644bcdbc9e065fd5d8d8
b7fdf62d274a80333dec260f5a420f9d6efdbdaf
refs/heads/master
2023-03-20T23:47:30.116053
2021-03-10T02:07:49
2021-03-10T02:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
11292.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,m,a; while ( scanf("%d%d",&n,&m) == 2 && ( n || m ) ) { deque < int > dq,dq2; for ( int i = 0; i != n; i++ ) { scanf("%d",&a); dq2.push_back ( a ); } for ( int i = 0; i != m; i++ ) { scanf("%d",&a); dq.push_back ( a ); } if ( n > m ) { printf("Loowater is doomed!\n"); continue; } sort(dq.begin(),dq.end()); sort(dq2.begin(),dq2.end()); long long int ans = 0; for ( int i = 0; i != n; i++ ) { int a = dq2 [ i ]; while ( dq.size() && dq.front() < a ){dq.pop_front();} if( dq.empty()) { ans = -1; break; } ans+= dq.front(); dq.pop_front(); } if(ans >= 0 )printf("%lld\n",ans); else printf("Loowater is doomed!\n"); } return 0; }
a3999b2b3462b62246ec7fdea485d6727fa34898
5800e14e1b95c2ef397b30b2c58f777d35ed26cc
/code.cpp
be2cac58a7c2cd8e6a7207a9c5255515a506116c
[ "MIT" ]
permissive
KorvusAcademy/sockext
298631fbdadb1931146ef2045609aee801f1be9b
c972b3aed7d82df7872db4f1527079904a963954
refs/heads/master
2020-03-15T05:08:15.462321
2018-05-03T10:56:58
2018-05-03T10:56:58
131,982,394
0
0
null
null
null
null
UTF-8
C++
false
false
3,765
cpp
code.cpp
// Source of information: https://msdn.microsoft.com // Developed by Korvux Neb #include "stdafx.h" #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <iostream> #include <string.h> #pragma comment(lib, "Ws2_32.lib") int main(int argc, char *argv[]) { // Variables used to send data to the server. WSADATA wsaData; // The WSADATA structure contains information about the Windows Sockets implementation. int iResult; // Variable used to checks error in functions. SOCKADDR_IN SockAddr; // Struct used by Winsocket to specify an local endpoint address or remote socket connection. std::string url = "httpbin.org"; // Target URL std::string request = "GET /user-agent HTTP/1.1\r\nHost: " + url + "\r\nUser-Agent: C++ Elite\r\n\r\n"; // Request that will be sended to Target URL struct hostent *host; // hostent structure is used by functions to store information about a given host, such as host name, IPv4 address, and so forth. std::cout << "### SOCKET PROGRAMMING ###" << std::endl; // Initialize Winsock // Variable that will contain the result of WSAStartup, used to check if it has been successfully executed.s iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); // The WSAStartup function initiates use of the Winsock DLL by a process. if (iResult != 0) { // If successful, the WSAStartup function returns zero. printf("WSAStartup failed: %d\n", iResult); return 1; } SOCKET Socket; // In Winsock applications, a socket descriptor IS NOT a file descriptor and must be used with the Winsock functions. Socket = socket(AF_INET, SOCK_STREAM, 0); // The socket function creates a socket that is bound to a specific transport service provider. if (Socket == INVALID_SOCKET) { // If the socket call fails, it returns INVALID_SOCKET. std::cout << "Socket creation failed." << std::endl; } // The addrinfo structure is used by the getaddrinfo function to hold host address information. struct addrinfo *result = NULL, *ptr = NULL, hints; SecureZeroMemory(&hints, sizeof(hints)); // Fills a block of memory with zeros. hints.ai_family = AF_INET; // IPV4. hints.ai_socktype = SOCK_STREAM; // Supports reliable connection-oriented byte stream communication. hints.ai_protocol = IPPROTO_TCP; // Transmission control protocol aka TCP. // The getaddrinfo function provides protocol-independent translation from an ANSI host name to an address. #define DEFAULT_PORT "80" iResult = getaddrinfo(url.c_str(), DEFAULT_PORT, &hints, &result); // Success returns zero. Failure returns a nonzero Windows Sockets error code if (iResult != 0) { printf("getaddrinfo failed: %d\n", iResult); WSACleanup(); // The WSACleanup function terminates use of the Winsock 2 DLL(Ws2_32.dll). return 1; } SockAddr.sin_port = htons(80); // The htons function converts a u_short from host to TCP/IP network byte order (which is big-endian). SockAddr.sin_family = AF_INET; // sin_addr is the IP address in the socket | is a union, so it can be accessed as s_addr(one 4 - bytes integer). SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr); if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) { std::cout << "Could not connect"; system("pause"); //return 1; } // send GET / HTTP send(Socket, request.c_str(), strlen(request.c_str()), 0); int nDataLength; char buffer[10000]; std::string response; // recieve html while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) { int i = 0; while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') { response += buffer[i]; i += 1; } } closesocket(Socket); WSACleanup(); // Display HTML source std::cout << response.c_str() << std::endl; char input{ ' ' }; std::cin >> input; return 0; }
692ab734b0161e443faecff1505546640ce60c95
b8f0c109aa1c4b659501cb822ab5831e5da7c448
/CA/Particles/ui_mainwindow.h
95e7ee946d42de4b941e8300443cfd7ce482eaa2
[]
no_license
EmelineGOT/FIB
8b02f7e2b2db736c06430ff18168420819515296
e3da143c9a26181286494a595b32b50dc97ce5a5
refs/heads/master
2021-06-28T06:19:18.656566
2019-01-14T21:51:10
2019-01-14T21:51:10
134,577,481
0
1
null
null
null
null
UTF-8
C++
false
false
9,263
h
ui_mainwindow.h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.10.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDockWidget> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QRadioButton> #include <QtWidgets/QSlider> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> #include "glwidget.h" QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QAction *action_Quit; QAction *action_Open; QWidget *centralWidget; QHBoxLayout *horizontalLayout; GLWidget *openGLWidget; QMenuBar *menuBar; QMenu *menu_File; QDockWidget *dockWidget; QWidget *dockWidgetContents; QVBoxLayout *verticalLayout_3; QGroupBox *groupBox; QVBoxLayout *verticalLayout_2; QSlider *horizontalSlider; QGroupBox *groupBox_2; QVBoxLayout *verticalLayout; QRadioButton *EulerOrig; QRadioButton *EulerSemi; QRadioButton *Verlet; QSpacerItem *verticalSpacer; QGroupBox *horizontalGroupBox; QHBoxLayout *horizontalLayout_2; QPushButton *resetButton; QPushButton *quitButton; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(800, 600); MainWindow->setDocumentMode(false); action_Quit = new QAction(MainWindow); action_Quit->setObjectName(QStringLiteral("action_Quit")); action_Open = new QAction(MainWindow); action_Open->setObjectName(QStringLiteral("action_Open")); action_Open->setEnabled(false); action_Open->setVisible(false); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); horizontalLayout = new QHBoxLayout(centralWidget); horizontalLayout->setSpacing(6); horizontalLayout->setContentsMargins(11, 11, 11, 11); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); openGLWidget = new GLWidget(centralWidget); openGLWidget->setObjectName(QStringLiteral("openGLWidget")); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(openGLWidget->sizePolicy().hasHeightForWidth()); openGLWidget->setSizePolicy(sizePolicy); horizontalLayout->addWidget(openGLWidget); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 800, 22)); menu_File = new QMenu(menuBar); menu_File->setObjectName(QStringLiteral("menu_File")); MainWindow->setMenuBar(menuBar); dockWidget = new QDockWidget(MainWindow); dockWidget->setObjectName(QStringLiteral("dockWidget")); dockWidget->setMinimumSize(QSize(192, 329)); dockWidgetContents = new QWidget(); dockWidgetContents->setObjectName(QStringLiteral("dockWidgetContents")); verticalLayout_3 = new QVBoxLayout(dockWidgetContents); verticalLayout_3->setSpacing(6); verticalLayout_3->setContentsMargins(11, 11, 11, 11); verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3")); groupBox = new QGroupBox(dockWidgetContents); groupBox->setObjectName(QStringLiteral("groupBox")); verticalLayout_2 = new QVBoxLayout(groupBox); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); horizontalSlider = new QSlider(groupBox); horizontalSlider->setObjectName(QStringLiteral("horizontalSlider")); horizontalSlider->setMinimum(5); horizontalSlider->setMaximum(100); horizontalSlider->setSingleStep(10); horizontalSlider->setValue(50); horizontalSlider->setOrientation(Qt::Horizontal); verticalLayout_2->addWidget(horizontalSlider); verticalLayout_3->addWidget(groupBox); groupBox_2 = new QGroupBox(dockWidgetContents); groupBox_2->setObjectName(QStringLiteral("groupBox_2")); verticalLayout = new QVBoxLayout(groupBox_2); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); EulerOrig = new QRadioButton(groupBox_2); EulerOrig->setObjectName(QStringLiteral("EulerOrig")); EulerOrig->setChecked(true); verticalLayout->addWidget(EulerOrig); EulerSemi = new QRadioButton(groupBox_2); EulerSemi->setObjectName(QStringLiteral("EulerSemi")); verticalLayout->addWidget(EulerSemi); Verlet = new QRadioButton(groupBox_2); Verlet->setObjectName(QStringLiteral("Verlet")); verticalLayout->addWidget(Verlet); verticalLayout_3->addWidget(groupBox_2); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout_3->addItem(verticalSpacer); horizontalGroupBox = new QGroupBox(dockWidgetContents); horizontalGroupBox->setObjectName(QStringLiteral("horizontalGroupBox")); horizontalLayout_2 = new QHBoxLayout(horizontalGroupBox); horizontalLayout_2->setSpacing(6); horizontalLayout_2->setContentsMargins(11, 11, 11, 11); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); resetButton = new QPushButton(horizontalGroupBox); resetButton->setObjectName(QStringLiteral("resetButton")); QPalette palette; QBrush brush(QColor(51, 52, 53, 255)); brush.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); QBrush brush1(QColor(164, 166, 168, 96)); brush1.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush1); resetButton->setPalette(palette); horizontalLayout_2->addWidget(resetButton); quitButton = new QPushButton(horizontalGroupBox); quitButton->setObjectName(QStringLiteral("quitButton")); QPalette palette1; QBrush brush2(QColor(59, 60, 60, 255)); brush2.setStyle(Qt::SolidPattern); palette1.setBrush(QPalette::Active, QPalette::ButtonText, brush2); palette1.setBrush(QPalette::Inactive, QPalette::ButtonText, brush2); palette1.setBrush(QPalette::Disabled, QPalette::ButtonText, brush1); quitButton->setPalette(palette1); quitButton->setAutoFillBackground(false); quitButton->setAutoDefault(true); quitButton->setFlat(false); horizontalLayout_2->addWidget(quitButton); verticalLayout_3->addWidget(horizontalGroupBox); dockWidget->setWidget(dockWidgetContents); MainWindow->addDockWidget(static_cast<Qt::DockWidgetArea>(2), dockWidget); menuBar->addAction(menu_File->menuAction()); menu_File->addAction(action_Open); menu_File->addAction(action_Quit); retranslateUi(MainWindow); quitButton->setDefault(false); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr)); action_Quit->setText(QApplication::translate("MainWindow", "&Quit", nullptr)); action_Open->setText(QApplication::translate("MainWindow", "&Open", nullptr)); menu_File->setTitle(QApplication::translate("MainWindow", "File", nullptr)); groupBox->setTitle(QApplication::translate("MainWindow", "Size of particles:", nullptr)); groupBox_2->setTitle(QApplication::translate("MainWindow", "Methods:", nullptr)); EulerOrig->setText(QApplication::translate("MainWindow", "Euler Orig", nullptr)); EulerSemi->setText(QApplication::translate("MainWindow", "Euler Semi", nullptr)); Verlet->setText(QApplication::translate("MainWindow", "Verlet", nullptr)); resetButton->setText(QApplication::translate("MainWindow", "Reset", nullptr)); quitButton->setText(QApplication::translate("MainWindow", "Quit", nullptr)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
fc69cf16be635c3a3ee69ac5b879a3f348bfa970
583607df178ed1389df59f63011da5b35387c811
/src/libime/dynamictriedictionary.h
cce2b91e2f07313a61b102df456bb4afac2d28b3
[]
no_license
liuzhiping/libime
d83746190a7a735e839e443c4ac4bcb890557992
53d74880a5d93bddbe41ec6af94aa4bf2c665e67
refs/heads/master
2020-12-11T06:01:36.852547
2014-09-19T12:37:10
2014-09-19T12:37:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
860
h
dynamictriedictionary.h
#ifndef LIBIME_DYNAMICTRIEDICTIONARY_H #define LIBIME_DYNAMICTRIEDICTIONARY_H #include <istream> #include <ostream> #include <memory> #include "dictionary.h" namespace libime { class StringEncoder; class DynamicTrieDictionary : Dictionary { public: DynamicTrieDictionary(char delim=' ', char linedelim='\n'); virtual void lookup(const std::string& input, std::vector<std::string>& output) override; void read(std::istream& in); void write(std::ostream& out); void setStringEncoder(const std::shared_ptr<StringEncoder>& encoder); void insert(const std::string& input, const std::string& output); void remove(const std::string& input, const std::string& output); private: class Private; std::unique_ptr<Private> d; }; } #endif // LIBIME_DYNAMICTRIEDICTIONARY_H
f780cfa7531c041d9a00247a0e3c10d596991852
a64b74c2522570ff8e5a2e982fc60ef9af95dbc6
/src/5.1.cpp
d5499f51cebdb12172c7a5673756cb16ee04a08f
[]
no_license
sawfly/straustrup
444cda204d133dea12d6f86542d3e2d179cc9a57
4701e5f5e431772bc5ac13076f911b3b060ae4dd
refs/heads/master
2020-04-05T03:34:57.817497
2018-11-16T17:00:35
2018-11-16T17:00:35
156,520,031
0
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
5.1.cpp
#include <iostream> int main() { char c = 'r'; char *p = &c; int a[10] = {1,2,3,4}; int &pa = *a; std::string as[] = {"pzdc", "dcp"}; std::string *pas = as; char **sym = &p; const int dcp = 228; const int *pdcp = &dcp; int pzdc = 228; int *const ipdcp = &pzdc; return 0; }
153e137c759d64638e35d44a2434185071f504f7
b6450bcc107521c0f5056475e383bcd3147a0a5e
/Common/Include/Logger.h
604287ef4cdffb43668feded91dee0a59008dfab
[]
no_license
nickluo/camaro-sdk
d75b012469fbdd8eb0b4473fd1572fce123fd9a1
7362a3dbf5a54d659a15343e405cfb6d4fef6a36
refs/heads/master
2020-05-21T13:35:47.840366
2017-01-10T09:13:17
2017-01-10T09:13:17
45,231,885
1
3
null
null
null
null
UTF-8
C++
false
false
1,215
h
Logger.h
#pragma once #include "spdlog/spdlog.h" #include "spdlog/sinks/dist_sink.h" #include "spdlog/sinks/syslog_sink.h" #include <string> namespace TopGear { class Logger { public: static void Initialize() { if (instance == nullptr) instance = std::unique_ptr<Logger>(new Logger); } //static std::shared_ptr<spdlog::logger> &Instance() //{ // return instance->logger; //} static void Write(spdlog::level::level_enum level, const std::string &text); static bool SwitchStdout(bool enable); static bool SwitchDaily(bool enable); #ifdef __linux__ static bool SwitchSyslog(bool enable); #endif ~Logger() {} private: Logger(); std::shared_ptr<spdlog::sinks::dist_sink_mt> dist_sink; std::shared_ptr<spdlog::sinks::stdout_sink_mt> std_sink; std::shared_ptr<spdlog::sinks::daily_file_sink_mt> daily_sink; std::shared_ptr<spdlog::logger> logger; bool std_sink_en = false; bool daily_sink_en = false; #ifdef __linux__ std::shared_ptr<spdlog::sinks::syslog_sink> sys_sink; bool sys_sink_en = false; #endif bool ConfigSink(bool enable, spdlog::sink_ptr &sink, bool &original) const; static std::unique_ptr<Logger> instance; static const std::string LoggerName; }; }
3c89ff4d4448f5e48fe1e85c3b3bf1c7546c29c3
af7b319aa7b7a3158f2f9fd8678e2888aa786605
/helper.h
65c9f6063be84a3e61a587563695e3817873f498
[]
no_license
zoness32/BrickBreak
95a32a77de7a2718a5b6bda1655c76551572149f
a261913028bb9db5bf8929f60ca078b3000d115b
refs/heads/master
2016-09-06T10:25:18.358836
2013-11-06T13:35:52
2013-11-06T13:35:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
helper.h
#ifndef HELPER_H #define HELPER_H #include <QBrush> #include <QFont> #include <QPen> #include <QRect> class QPainter; class QPaintEvent; class Helper { public: Helper(); public: void paint(QPainter *painter, QPaintEvent *event, QString*); void setGeometry(QRect geom); void setColor(QColor colors); private: QBrush background; QBrush circleBrush; QFont textFont; QPen circlePen; QPen textPen; QRect geometry; }; #endif
ea015d6900e7d0cc9fd2d2d8eb1cbdedd316f444
4c095941095ebfefbbef24b610cbc89c27c88880
/src/conn/ConnectionAdapter.cpp
7356533509532e0535bb6d5d4cef42b2c1688255
[]
no_license
wusopp/network-probe
3679284d42cabc04f1fe4b8420bd642a6f3b4ab7
8c5769c4047a01d84341dfe267aff08ac12a732b
refs/heads/master
2023-02-18T09:04:50.943285
2021-01-10T13:10:04
2021-01-10T13:10:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
ConnectionAdapter.cpp
/* * ConnectionAdapter.cpp * * Created on: 2015. 4. 18. * Author: sound79 */ #include <stdio.h> #include "../util/Debug.h" #include "ConnectionAdapter.h" //ConnectionAdapter::ConnectionAdapter() //{ // mConnector = new PosixSocketLib(); //} // //ConnectionAdapter::~ConnectionAdapter() //{ int ConnectionAdapter::OnSend() { return 0; } int ConnectionAdapter::OnReceive(unsigned char* buffer, int length) { if(mProto) { mProto->ParseData(buffer, length); } return 0; } int ConnectionAdapter::TryCreate(Connection &conn) { return ICreate(conn); } int ConnectionAdapter::TryConnect(Connection &conn) { return IConnect(conn); } int ConnectionAdapter::TryDisconnect() { return IDisconnect(); } int ConnectionAdapter::TryBind(Connection &conn) { return IBind(conn); } int ConnectionAdapter::TrySend(TConnBuffer &buffer) { return ISend(buffer); } int ConnectionAdapter::TryReceive(TConnBuffer &buffer) { return IReceive(buffer); } int ConnectionAdapter::TrySetEvent() { return ISetEvent(); } int ConnectionAdapter::TrySetSocketOption(unsigned int type, int value) { return ISetSocketOption(type, value); }
407f954f79adefa4fee59ca53122262c7abd3c4c
fe02a586e2a010017dd52617a4733138c2923fd3
/Windows/Windows.cpp
7e78633143ed52d224b812ac2ac59fe8b48da0d5
[]
no_license
KonH/CppProc
fdda609db4c0572860b3f704a1f92e67bf56dae9
96badd8376a972fd6e5ca00948eb221e4a7efc8b
refs/heads/master
2020-03-25T18:25:10.401869
2018-08-31T15:46:52
2018-08-31T15:46:52
144,029,860
1
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
Windows.cpp
#include "stdafx.h" #include "ProcFrontend.h" int main(int argc, char* argv[]) { return ProcFrontend::start(argc, argv); }
e0cf11867c4f9432ac65a452fb03cd43449994ee
52dae991a8e363e66533f2acf8c90428afec91c3
/windows_ex/netDemo/clientDemo/clientDemo.cpp
159283b4d8a8c850d191735d3a06edd9d1f5808d
[]
no_license
y0n0622/vc6.0code
1c8100816c2e2d5d05ef72cebd665baa3a42b491
8a657e8b90534e5cd63e438509f2d9c63f15940b
refs/heads/master
2020-03-29T01:34:15.589075
2018-09-19T05:37:19
2018-09-19T05:37:19
149,395,360
1
0
null
null
null
null
GB18030
C++
false
false
1,196
cpp
clientDemo.cpp
// clientDemo.cpp : Defines the entry point for the console application. //一个简单的客户端,向服务端发送字符串 #include "stdafx.h" #include "Winsock2.h" #pragma comment(lib, "Ws2_32.lib") #define BUF_SIZE 256 int main(int argc, char* argv[]) { WSADATA wsd; SOCKET sHost; SOCKADDR_IN servAddr; char buf[BUF_SIZE]; int retVal; if(WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { printf("WSAStarup failed!\n"); return -1; } sHost = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(INVALID_SOCKET == sHost) { printf("socket failed!\n"); WSACleanup(); return -1; } servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); servAddr.sin_port = htons((short)4999); int nServAddlen = sizeof(servAddr); retVal = connect(sHost, (LPSOCKADDR)&servAddr, sizeof(servAddr)); if(SOCKET_ERROR == retVal) { printf("connect failed!\n"); closesocket(sHost); return -1; } // buf[256] = {"0"}; strcpy(buf, "mytcp"); retVal = send(sHost, buf, strlen(buf), 0); if(SOCKET_ERROR == retVal) { printf("send failed!\n"); closesocket(sHost); WSACleanup(); return -1; } closesocket(sHost); WSACleanup(); getchar(); return 0; }
9cc2343cb5ee2fab7a5093d9527b39e6634b9ed2
fae474903666e7ca007c4c9c5c4d60772b2da250
/src/ofxKinectMemory.cpp
3ab063f035cc14ec155a0067a4d4ba0c246f227f
[ "MIT" ]
permissive
AssociationAlReves/ofAlReves
502d4a574aae55a2d58dfba53401b049210aa09e
70491f0b57cd45b7d486eb751067b64e2ce524e4
refs/heads/master
2023-04-03T21:48:21.407646
2023-03-18T17:38:11
2023-03-18T17:38:16
37,789,591
1
0
MIT
2023-03-11T12:59:54
2015-06-20T23:25:05
C++
UTF-8
C++
false
false
15,814
cpp
ofxKinectMemory.cpp
#include "ofxKinectMemory.h" #include "ofApp.h" using namespace ofxCv; using namespace cv; const string GUI_SETTINGS = "kinectmemory_settings.xml"; //-------------------------------------------------------------- void ofxKinectMemory::setup() { ofSetVerticalSync(true); ofBackground(0); ofEnableArbTex(); //ofApp *app = (ofApp *)ofxGetAppPtr(); forceWarpOff = false; bDrawJoinedActors = false; // enable depth->video image calibration kinect.setRegistration(true); kinect.init(); kinect.open(); // opens first available kinect // print the intrinsic IR sensor values if (kinect.isConnected()) { ofLogNotice() << "sensor-emitter dist: " << kinect.getSensorEmitterDistance() << "cm"; ofLogNotice() << "sensor-camera dist: " << kinect.getSensorCameraDistance() << "cm"; ofLogNotice() << "zero plane pixel size: " << kinect.getZeroPlanePixelSize() << "mm"; ofLogNotice() << "zero plane dist: " << kinect.getZeroPlaneDistance() << "mm"; } bShowHelp = false; bKinectFrameReady = false; grayImage.allocate(kinect.width, kinect.height, ofImageType::OF_IMAGE_GRAYSCALE); grayImage.clear(); //----------------------------------------- // FBOs fboWhite.allocate(ofGetScreenWidth(), ofGetScreenHeight(), GL_RGBA32F_ARB); fboBlack.allocate(ofGetScreenWidth(), ofGetScreenHeight(), GL_RGBA32F_ARB); /* fboWhite.allocate(kinect.width*2, kinect.height*2, GL_RGBA32F_ARB); fboBlack.allocate(kinect.width*2, kinect.height*2, GL_RGBA32F_ARB);*/ fboWhite.begin(); ofClear(255, 255, 255, 0); fboWhite.end(); fboBlack.begin(); ofClear(255, 255, 255, 0); fboBlack.end(); //----------------------------------------- //----------------------------------- // contour finder contourFinder.setMinAreaRadius(1); contourFinder.setMaxAreaRadius(800); contourFinder.setThreshold(15); // wait for half a frame before forgetting something contourFinder.getTracker().setPersistence(15); // an object can move up to 32 pixels per frame contourFinder.getTracker().setMaximumDistance(32); // ----------------------- // GUI gui.setup("Memory", Globals::hostName + GUI_SETTINGS); cvGroup.setName("OpenCV"); cvGroup.add(nearThreshold.set("nearThreshold", 255, 0, 255)); cvGroup.add(farThreshold.set("farThreshold", 213, 0, 255)); cvGroup.add(thresholdParam.set("threshold", 13, 0, 255)); cvGroup.add(contourMinArea.set("contourMinArea", 1, 0, 640)); cvGroup.add(contourMaxArea.set("contourMaxArea", 800, 0, 640)); cvGroup.add(blurSize.set("blurSize", 10, 0, 50)); cvGroup.add(maximumDistance.set("maximumDistance", 32, 0, 300)); cvGroup.add(persistence.set("persistence", 15, 0, 100)); gui.add(cvGroup); appGroup.setName("App"); appGroup.add(numFramesDelay.set("numFramesDelay", 35, 1, 200)); appGroup.add(angle.set("kinect angle", 13, -30, 30)); appGroup.add(bStartMemory.set("StartMemory", false)); appGroup.add(fadeAmnt.set("fade amount", 10, 0, 50)); appGroup.add(blackScreen.set("blackScreen", true)); appGroup.add(antiAlias.set("antiAlias", true)); appGroup.add(lineWidth.set("lineWidth", 1, 0, 10)); // appGroup.add(camOrientation.set("camOrientation", app->cam.getOrientationEuler(), ofVec3f(-180, -180, -180), ofVec3f(180, 180, 180))); // appGroup.add(camPosition.set("camPosition", app->cam.getPosition(), ofVec3f(-180, -180, -180), ofVec3f(180, 180, 180))); //appGroup.add(lineColor.set("lineColor", ofColor(0), ofColor(0), ofColor(255))); gui.add(appGroup); debugGroup.setName("debug"); debugGroup.add(bShowLabels.set("ShowLabels", true)); debugGroup.add(bShowImages.set("ShowImages", true)); gui.add(debugGroup); // //if (!forceWarpOff) { // // WARP // int w = ofGetWidth(); // int h = ofGetHeight(); // int x = (ofGetWidth() - w) * 0.5; // center on screen. // int y = (ofGetHeight() - h) * 0.5; // center on screen. // bool invertWarp = false; // if (invertWarp) { // warper.setSourceRect(ofRectangle(0, 0, w, h)); // this is the source rectangle which is the size of the image and located at ( 0, 0 ) // warper.setBottomLeftCornerPosition(ofPoint(x, y)); // this is position of the quad warp corners, centering the image on the screen. // warper.setBottomRightCornerPosition(ofPoint(x + w, y)); // this is position of the quad warp corners, centering the image on the screen. // warper.setTopLeftCornerPosition(ofPoint(x, y + h)); // this is position of the quad warp corners, centering the image on the screen. // warper.setTopRightCornerPosition(ofPoint(x + w, y + h)); // this is position of the quad warp corners, centering the image on the screen. // } else { // warper.setSourceRect(ofRectangle(0, 0, w, h)); // this is the source rectangle which is the size of the image and located at ( 0, 0 ) // warper.setTopLeftCornerPosition(ofPoint(x, y)); // this is position of the quad warp corners, centering the image on the screen. // warper.setTopRightCornerPosition(ofPoint(x + w, y)); // this is position of the quad warp corners, centering the image on the screen. // warper.setBottomLeftCornerPosition(ofPoint(x, y + h)); // this is position of the quad warp corners, centering the image on the screen. // warper.setBottomRightCornerPosition(ofPoint(x + w, y + h)); // this is position of the quad warp corners, centering the image on the screen. // } // // warper.setup(); // warper.load(); // reload last saved changes. // warper.toggleShow(); //} //app->cam.reset(); gui.loadFromFile(Globals::hostName + GUI_SETTINGS); //app->cam.setPosition(camPosition); //app->cam.setOrientation(camOrientation); } //-------------------------------------------------------------- void ofxKinectMemory::update() { if (kinect.isConnected()) { contourFinder.setMinAreaRadius(contourMinArea); contourFinder.setMaxAreaRadius(contourMaxArea); contourFinder.setThreshold(thresholdParam); contourFinder.getTracker().setPersistence(persistence); contourFinder.getTracker().setMaximumDistance(maximumDistance); kinect.update(); // there is a new frame and we are connected if (kinect.isFrameNew()) { bKinectFrameReady = true; // load grayscale depth image and color image from the kinect source //grayImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height); grayImage.setFromPixels(kinect.getDepthPixels()); //grayImage.update(); copyGray(grayImage, grayImageNear); copyGray(grayImage, grayImageFar); imitate(grayImageFiltered, grayImage); threshold(grayImageNear, (float)nearThreshold, true); threshold(grayImageFar, (float)farThreshold, false); bitwise_and(grayImageNear, grayImageFar, grayImageFiltered); grayImageFiltered.update(); blur(grayImageFiltered, blurSize); grayImageFiltered.update(); contourFinder.findContours(grayImageFiltered); } } } //-------------------------------------------------------------- void ofxKinectMemory::draw() { //cam.begin(); //ofClear(0); ofSetColor(255); if (bKinectFrameReady) { RectTracker& tracker = contourFinder.getTracker(); // delete dead actors for (auto & label : tracker.getDeadLabels()) { //cout << "Dead actor: " << label << endl; actors.erase(label); actorsHullUnion.erase(label); } // delete new actors for (auto & label : tracker.getNewLabels()) { //cout << "New actor: " << label << endl; actors[label] = list<vector<cv::Point> >(); } // union of all points vector<cv::Point> mergedHullsTotal; vector<cv::Point> HullTotal; // for each blob for (int i = 0; i < contourFinder.size(); i++) { int label = contourFinder.getLabel(i); vector<cv::Point> hullPoints = contourFinder.getConvexHull(i); if (bStartMemory) { list<vector<cv::Point> >& actor = actors[label]; // add polyline if (actor.size() == 0) { actor.assign(numFramesDelay, hullPoints); } else { actor.push_back(hullPoints); } // union of all points vector<cv::Point> mergedHulls; for (auto & curHull : actor) { mergedHulls.insert(mergedHulls.end(), curHull.begin(), curHull.end()); mergedHullsTotal.insert(mergedHullsTotal.end(), curHull.begin(), curHull.end()); } // remove oldest hull for current actor actor.pop_front(); vector<cv::Point> hull; convexHull(mergedHulls, hull); ofPolyline polyline; polyline.resize(hull.size()); for (int hullIndex = 0; hullIndex < (int)hull.size(); hullIndex++) { polyline[hullIndex].x = hull[hullIndex].x; polyline[hullIndex].y = hull[hullIndex].y; } polyline.close(); actorsHullUnion[label] = polyline; /* ofSetColor(ofColor::blue); polyline.draw(); ofSetColor(255);*/ } else { ofPolyline polyline; polyline.resize(hullPoints.size()); for (int hullIndex = 0; hullIndex < (int)hullPoints.size(); hullIndex++) { polyline[hullIndex].x = hullPoints[hullIndex].x; polyline[hullIndex].y = hullPoints[hullIndex].y; } polyline.close(); polyline.draw(); if (bShowLabels) { ofPoint center = toOf(contourFinder.getCenter(i)); ofPushMatrix(); ofTranslate(center.x, center.y); string msg = ofToString(label) + ":" + ofToString(tracker.getAge(label)); ofDrawBitmapStringHighlight(msg, 0, 0, ofColor::white, ofColor::red); ofVec2f velocity = toOf(contourFinder.getVelocity(i)); ofScale(5, 5); ofDrawLine(0, 0, velocity.x, velocity.y); ofPopMatrix(); } } //if (bStartMemory) } // for each blob if (bStartMemory && mergedHullsTotal.size() > 0) { convexHull(mergedHullsTotal, HullTotal); bigHull2Actors.resize(HullTotal.size()); for (int hullIndex = 0; hullIndex < (int)HullTotal.size(); hullIndex++) { bigHull2Actors[hullIndex].x = HullTotal[hullIndex].x; bigHull2Actors[hullIndex].y = HullTotal[hullIndex].y; } bigHull2Actors.close(); } } // END if KINECT //if (bGotImage) //cam.end(); if (kinect.isConnected()) { if (bShowImages && !bStartMemory) { grayImageFiltered.draw(10, 10); grayImage.draw(800, 0); } //ofDrawAxis(50); } drawMemoryTrails(); if (bShowHelp) { gui.draw(); } } //-------------------------------------------------------------- void ofxKinectMemory::drawMemoryTrails() { if (kinect.isConnected()) { if (bStartMemory) { ofEnableAlphaBlending(); if (antiAlias) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); } ofSetLineWidth(lineWidth); if (blackScreen) { // BLACK //-------------------------------------------------------------- ofBackground(0); fboBlack.begin(); ofPushMatrix(); ofPushMatrix(); float ratioW = ofGetScreenWidth() / kinect.width; float ratioH = ofGetScreenHeight() / kinect.height; ofScale(ratioW, ratioH); ofSetColor(0, 0, 0, fadeAmnt); ofFill(); ofDrawRectangle(0, 0, 0, fboBlack.getWidth(), fboBlack.getHeight()); ofNoFill(); ofSetColor(255); if (bDrawJoinedActors) { bigHull2Actors.draw(); } else { for (auto & actor : actorsHullUnion) { actor.second.draw(); } } ofPopMatrix(); fboBlack.end(); ofDisableAlphaBlending(); ofPushMatrix(); ofTranslate(fboWhite.getWidth() / 2, fboWhite.getHeight() / 2); ofScale(1, -1, 1); ofTranslate(-fboWhite.getWidth() / 2, -fboWhite.getHeight() / 2); //ofDisableAlphaBlending(); fboBlack.draw(0, 0); ofPopMatrix(); } else { // WHITE //ofBackground(255); ofBackground(255, 255, 255, 0); if (ofGetKeyPressed('c')) { ofClear(255, 255, 255, 0); } fboWhite.begin(); if (ofGetKeyPressed('c')) { ofClear(255, 255, 255, 0); } ofPushMatrix(); float ratioW = ofGetScreenWidth() / kinect.width; float ratioH = ofGetScreenHeight() / kinect.height; ofScale(ratioW, ratioH); ofSetColor(255, 255, 255, fadeAmnt); ofFill(); ofDrawRectangle(0, 0, 0, fboWhite.getWidth(), fboWhite.getHeight()); ofNoFill(); //ofSetColor(lineColor); ofSetColor(0); if (bDrawJoinedActors) { bigHull2Actors.draw(); } else { for (auto & actor : actorsHullUnion) { actor.second.draw(); } } ofPopMatrix(); fboWhite.end(); ofPushMatrix(); ofTranslate(fboWhite.getWidth() / 2, fboWhite.getHeight() / 2); ofScale(1, -1, 1); ofTranslate(-fboWhite.getWidth() / 2, -fboWhite.getHeight() / 2); //ofDisableAlphaBlending(); fboWhite.draw(0, 0); ofPopMatrix(); } } } else { ofEnableAlphaBlending(); // NO KINECT ofBackground(255, 255, 255, 0); fboWhite.begin(); ofPushMatrix(); float ratioW = ofGetScreenWidth() / kinect.width; float ratioH = ofGetScreenHeight() / kinect.height; ofScale(ratioW, ratioH); ofSetColor(255, 255, 255, fadeAmnt); ofFill(); ofDrawRectangle(0, 0, 0, fboWhite.getWidth(), fboWhite.getHeight()); ofNoFill(); //ofSetColor(lineColor); ofSetColor(0); ofDrawRectangle(0, 0, 640, 480); ofDrawCircle(0, 0, 0, 50); ofDrawCircle(640, 0, 0, 50); ofDrawCircle(640, 480, 0, 50); ofDrawCircle(0, 480, 0, 50); ofPopMatrix(); fboWhite.end(); ofPushMatrix(); ofTranslate(fboWhite.getWidth() / 2, fboWhite.getHeight() / 2); ofScale(1, -1, 1); ofTranslate(-fboWhite.getWidth() / 2, -fboWhite.getHeight() / 2); //ofDisableAlphaBlending(); fboWhite.draw(0, 0); ofPopMatrix(); ofDisableAlphaBlending(); } } //-------------------------------------------------------------- void ofxKinectMemory::keyPressed(int key) { ofApp *app = (ofApp *)ofxGetAppPtr(); switch (key) { case 'h': bShowHelp = !bShowHelp; break; case'l': { gui.loadFromFile(Globals::hostName + GUI_SETTINGS); // app->cam.setPosition(camPosition); // app->cam.setOrientation(camOrientation); //kinect.setCameraTiltAngle(angle); } break; case's': gui.saveToFile(Globals::hostName + GUI_SETTINGS); break; case 'a': kinect.setCameraTiltAngle(angle); break; case OF_KEY_UP: angle++; if (angle > 30) angle = 30; kinect.setCameraTiltAngle(angle); break; case OF_KEY_DOWN: angle--; if (angle < -30) angle = -30; kinect.setCameraTiltAngle(angle); break; case 'b': blackScreen = !blackScreen; break; case ' ': bStartMemory = !bStartMemory; break; case 'j': bDrawJoinedActors = false; break; case 'J': bDrawJoinedActors = true; case 'C': kinect.setCameraTiltAngle(0); // zero the tilt on exit kinect.close(); break; case 'O': kinect.open(); kinect.setCameraTiltAngle(angle); break; case '>' : farThreshold += 0.5; break; case '<': farThreshold -= 0.5; break; } if (key == 'W') { forceWarpOff = false; } if (key == 'w') { forceWarpOff = true; } if (!forceWarpOff) { // WARPs // if (key == 'H') { // warper.toggleShow(); // } // if (key == 'L') { // warper.load(); // } // if (key == 'S') { //// camOrientation = app->cam.getOrientationEuler(); //// camPosition = app -> cam.getPosition(); // gui.saveToFile(Globals::hostName + GUI_SETTINGS); // // warper.save(); // } } } //-------------------------------------------------------------- void ofxKinectMemory::updateExit() { closeKinect(); finishedExiting(); } //-------------------------------------------------------------- void ofxKinectMemory::exit() { closeKinect(); } //-------------------------------------------------------------- void ofxKinectMemory::closeKinect() { kinect.setCameraTiltAngle(0); // zero the tilt on exit kinect.close(); }
65ee3a9566e75641f39411ab7d87a2a9ff43ec7f
c9d3176099bd20da79f28239a77b71324c6109b8
/day03/ex03/NinjaTrap.cpp
5adfd77ce03aaf6f0cb916010c376afba32d4aa9
[]
no_license
Ashypilo/Piscine-CPP
9db9e08e3f3853e9a198d256d42d8cca9090cb75
2ff24ffedae35c6bdb627f9a080513b2c2f63373
refs/heads/master
2020-08-13T15:37:28.047031
2019-10-14T09:12:36
2019-10-14T09:12:36
214,993,845
0
0
null
null
null
null
UTF-8
C++
false
false
2,928
cpp
NinjaTrap.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* NinjaTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ashypilo <ashypilo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/03 17:36:27 by ashypilo #+# #+# */ /* Updated: 2019/10/04 19:59:16 by ashypilo ### ########.fr */ /* */ /* ************************************************************************** */ #include "NinjaTrap.hpp" NinjaTrap::NinjaTrap() { std::cout << "I am Ninja is born in the NinjaTrap" << std::endl; this->name = "Ninja"; this->level = 0; this->armor_damage_reduction = 0; this->energy_points = 0; this->max_energy_points = 0; this->hit_points = 0; this->max_hit_points = 0; this->melee_attack_damage = 0; this->ranged_attack_damage = 0; return ; } NinjaTrap::NinjaTrap(std::string name) { std::cout << "I am " << name << " is born in the NinjaTrap" << std::endl; this->name = name; this->level = 1; this->armor_damage_reduction = 0; this->energy_points = 120; this->max_energy_points = 120; this->hit_points = 60; this->max_hit_points = 60; this->melee_attack_damage = 60; this->ranged_attack_damage = 5; return ; } NinjaTrap::NinjaTrap(const NinjaTrap& copy) { std::cout << "Copy call" << std::endl; *this = copy; return ; } NinjaTrap::~NinjaTrap() { std::cout << "I am " << name << " is finish in the NinjaTrap" << std::endl; return ; } NinjaTrap& NinjaTrap::operator=(const NinjaTrap& over) { name = over.name; level = over.level; armor_damage_reduction = over.armor_damage_reduction; energy_points = over.energy_points; max_energy_points = over.max_energy_points; hit_points = over.hit_points; max_hit_points = over.max_hit_points; melee_attack_damage = over.melee_attack_damage; ranged_attack_damage = over.ranged_attack_damage; return (*this); } void NinjaTrap::ninjaShoebox(ClapTrap& clap) { std::cout << "I " + clap.getName() + " used ClapTrap class" << std::endl; } void NinjaTrap::ninjaShoebox(FragTrap& frag) { std::cout << "I " + frag.getName() + " used FragTrap class" << std::endl; } void NinjaTrap::ninjaShoebox(ScavTrap& scav) { std::cout << "I " + scav.getName() + " used ScavTrap class" << std::endl; } void NinjaTrap::ninjaShoebox(NinjaTrap& nini) { std::cout << "I " + nini.getName() + " used NinjaTrap class" << std::endl; }
a5a60eee6ec402e20b7d69d43ba6d94a94fc03e3
b112ff7af0f4cd97cdcbbcb50126745aa5248304
/examples/0044.sha/hello_hmac_sha256.cc
db7a426b19c3f0c53a077d6e98c78c1e21e924be
[ "MIT" ]
permissive
FrancoisSestier/fast_io
d5f42caf563e61d9ac0b9c4cb53123c9420bf7bf
30ed67bfecdd9d05102c34bf121cff9d31773565
refs/heads/master
2022-12-15T11:27:58.623652
2020-09-08T01:54:17
2020-09-08T01:54:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
305
cc
hello_hmac_sha256.cc
#include"../../include/fast_io.h" #include"../../include/fast_io_device.h" #include"../../include/fast_io_crypto.h" int main(int argc,char** argv) { fast_io::hmac_sha256 sha("Hello"); fast_io::hash_processor processor(sha); print(processor,"Hello hmac sha256"); processor.do_final(); println(sha); }
c076609f513df681951090d85cc62288377882a9
168faa6ff6cc5918336affdb155682d958c1a048
/toolkits/collaborative_filtering/util.hpp
395a0562b5d1bd103beace20b06ba79cbda63a3a
[ "Apache-2.0" ]
permissive
michael-hahn/frap
6bed6c069a580e892a8dcea79bcca13bd0a01e4e
d214d243345c6c62f6fd916bc01b682d65fae5fe
refs/heads/master
2021-06-18T21:04:06.173367
2017-06-16T20:45:29
2017-06-16T20:45:29
82,714,093
5
3
null
null
null
null
UTF-8
C++
false
false
2,174
hpp
util.hpp
#ifndef __CF_UTILS__ #define __CF_UTILS__ #include <omp.h> #include <stdio.h> #include <iostream> int number_of_omp_threads(){ int num_threads = 0; int id; #pragma omp parallel private(id) { id = omp_get_thread_num(); if (id == 0) num_threads = omp_get_num_threads(); } return num_threads; } struct in_file{ FILE * outf; in_file(std::string fname) { outf = fopen(fname.c_str(), "r"); if (outf == NULL){ std::cerr<<"Failed to open file: " << fname << std::endl; exit(1); } } ~in_file() { if (outf != NULL) fclose(outf); } }; struct out_file{ FILE * outf; out_file(const std::string fname){ outf = fopen(fname.c_str(), "w"); } ~out_file(){ if (outf != NULL) fclose(outf); } }; /* template<typename T1> void load_map_from_txt_file(T1 & map, const std::string filename, bool gzip, int fields){ logstream(LOG_INFO)<<"loading map from txt file: " << filename << std::endl; gzip_in_file fin(filename, gzip); char linebuf[1024]; char saveptr[1024]; bool mm_header = false; int line = 0; char * pch2 = NULL; while (!fin.get_sp().eof() && fin.get_sp().good()){ fin.get_sp().getline(linebuf, 10000); if (fin.get_sp().eof()) break; if (linebuf[0] == '%'){ logstream(LOG_INFO)<<"Detected matrix market header: " << linebuf << " skipping" << std::endl; mm_header = true; continue; } if (mm_header){ mm_header = false; continue; } char *pch = strtok_r(linebuf," \r\n\t",(char**)&saveptr); if (!pch){ logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl; } if (fields == 2){ pch2 = strtok_r(NULL,"\n",(char**)&saveptr); if (!pch2) logstream(LOG_FATAL) << "Error when parsing file: " << filename << ":" << line <<std::endl; } if (fields == 1) map[boost::lexical_cast<std::string>(line)] = pch; else map[pch] = pch2; line++; } logstream(LOG_INFO)<<"Map size is: " << map.size() << std::endl; }*/ #endif
870c1a4970c08a027e421a8282b035537776cc57
c2726850594308c9a4d1a64388d8fa7b10dd806a
/codebase/rbf/adt.h
93083a07b6cd3008192a04b64071c0a3bd3c6cbe
[]
no_license
yangjiao2/cs222
559a686d3b0d87dbb26a4b8524a32152c1745938
6c215e64cf484298d7a5b59588fdb526aa75d630
refs/heads/master
2020-05-26T00:38:07.503128
2014-04-19T07:28:23
2014-04-19T07:28:23
43,621,567
1
0
null
2015-10-04T01:52:05
2015-10-04T01:52:05
null
UTF-8
C++
false
false
2,765
h
adt.h
// // adt.h // // Created by bluesea on 14-1-18. // Copyright (c) 2014年 bluesea. All rights reserved. // #ifndef _adt_h_ #define _adt_h_ #include <iostream> #include "rbfm.h" #define ACCESS_FIELD_METHODS(fieldName) \ int get_##fieldName(void);\ int set_##fieldName(int v); #define ACCESS_ENTRY_METHODS(entryName) \ int get_##entryName(int index);\ int set_##entryName(int index, int val); //class themselves do not store data, it just refers to outside buffer class RecordPage; class RecordHeader; class PageDirectory{ public: char *data; //bad naming styles, easy to conflict with local variable with same name int in_the_page; PageDirectory(char *dt = NULL): data(dt), in_the_page(0){} ACCESS_FIELD_METHODS(pgnum) ACCESS_FIELD_METHODS(next) ACCESS_ENTRY_METHODS(pgid) ACCESS_ENTRY_METHODS(pgfreelen) int moveToNext(FileHandle &fh); int firstPageWithFreelen(FileHandle &fh, int len); //return matching pgnum int allocRecordPage(FileHandle &fh); //return allocated pgnum static int MaximunEntryNum(void); int nextRecordPageID(FileHandle &fh, int pageid); int nextRecord(FileHandle &fh, RID &rid); int locateRecordPage(FileHandle &fh, int pageid); //return entry's index }; class RecordPage{ public: char *data; //points to beginning of page RecordPage(char *dt = NULL): data(dt) {} ACCESS_FIELD_METHODS(rcdnum) ACCESS_FIELD_METHODS(freeptr) //offset of freeSpace starting from beginning of page ACCESS_ENTRY_METHODS(offset) //rcdlen = 0 means it was empty, rcdlen < 0, means it's a timbstone. //then forwarding addr (pageid, slotid) = (-rcdlen, offset) ACCESS_ENTRY_METHODS(rcdlen) int getFreelen(void); RecordHeader getRecordHeaderAt(int index); //setting returning rh's data RecordHeader allocRecordHeader(int len, int& slotID); //alloc recordHeader by len int nextRecord(int start_from_slot); void removeSlot(int index); bool isEmptyAt(int index); bool isTombStone(int index); }; class RecordHeader{ public: char *data; //points to beginning of header RecordHeader(char *dt = NULL): data(dt) {} ACCESS_FIELD_METHODS(fieldnum) ACCESS_ENTRY_METHODS(fieldOffset) int writeRecord(vector<Attribute> recordDescriptor, char *bytes); char *getContentPointer(void); char *getAttributePointer(int index); //record's length, including header static int getRecordLength(vector<Attribute> descriptor, char *data); static int getRecordContentLength(vector<Attribute> descriptor, char *data); //TODO: add get/set field method, not required in project1 }; extern int writeInt(char *data, int val); extern int readInt(char *data); #endif /* defined(__cs222__adt__) */
8be468957cab7993833c0d3b8e820241fa6c0e4d
d6eb6c4f340d343ea368507b1c7e7671d45a5767
/src/lib/v8/src/.svn/text-base/utils.cc.svn-base
08a6ec9f5d6e0778b7fdbb0d4d0104395d9af7b9
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
brn/mocha
8242888c18081cb844a2c2bd0c222162cd46e4cf
9ff68d6e2c753acf6ce57cdb3188f162549d2045
refs/heads/master
2021-06-06T06:43:06.230281
2021-05-07T16:04:12
2021-05-07T16:04:12
2,707,603
19
0
null
null
null
null
UTF-8
C++
false
false
3,264
utils.cc.svn-base
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <stdarg.h> #include "../include/v8stdint.h" #include "checks.h" #include "utils.h" namespace v8 { namespace internal { SimpleStringBuilder::SimpleStringBuilder(int size) { buffer_ = Vector<char>::New(size); position_ = 0; } void SimpleStringBuilder::AddString(const char* s) { AddSubstring(s, StrLength(s)); } void SimpleStringBuilder::AddSubstring(const char* s, int n) { ASSERT(!is_finalized() && position_ + n < buffer_.length()); ASSERT(static_cast<size_t>(n) <= strlen(s)); memcpy(&buffer_[position_], s, n * kCharSize); position_ += n; } void SimpleStringBuilder::AddPadding(char c, int count) { for (int i = 0; i < count; i++) { AddCharacter(c); } } void SimpleStringBuilder::AddDecimalInteger(int32_t value) { uint32_t number = static_cast<uint32_t>(value); if (value < 0) { AddCharacter('-'); number = static_cast<uint32_t>(-value); } int digits = 1; for (uint32_t factor = 10; digits < 10; digits++, factor *= 10) { if (factor > number) break; } position_ += digits; for (int i = 1; i <= digits; i++) { buffer_[position_ - i] = '0' + static_cast<char>(number % 10); number /= 10; } } char* SimpleStringBuilder::Finalize() { ASSERT(!is_finalized() && position_ < buffer_.length()); buffer_[position_] = '\0'; // Make sure nobody managed to add a 0-character to the // buffer while building the string. ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_)); position_ = -1; ASSERT(is_finalized()); return buffer_.start(); } } } // namespace v8::internal
f9a462f9eb857e0b0d466f29d8e8a2a0f1765b1b
d9e483192b0a334cd8447a4dddd5c50bb4f5e444
/Sources/ncreport/include/ncreportimageitem.h
ef5b45333893f369be777e089eb2b181a94c34e7
[ "MIT" ]
permissive
baudoliver7/industria-elec
4fb90d18bf7196b56cd7e3ab50ca036698a54e3b
31850b177122ce09dd5de94d93a757352b8dd317
refs/heads/master
2022-12-06T10:35:46.937675
2020-09-01T01:04:13
2020-09-01T01:04:13
291,858,760
0
0
null
null
null
null
UTF-8
C++
false
false
4,660
h
ncreportimageitem.h
/**************************************************************************** * * Copyright (C) 2002-2008 Helta Kft. / NociSoft Software Solutions * All rights reserved. * Author: Norbert Szabo * E-mail: nszabo@helta.hu, info@nocisoft.com * Web: www.nocisoft.com * * This file is part of the NCReport reporting software * * Licensees holding a valid NCReport License Agreement may use this * file in accordance with the rights, responsibilities, and obligations * contained therein. Please consult your licensing agreement or contact * nszabo@helta.hu if any conditions of this licensing are not clear * to you. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * ****************************************************************************/ #ifndef NCREPORTIMAGEITEM_H #define NCREPORTIMAGEITEM_H #include "ncreportitem.h" /*! Image item's data class */ class NCReportImageData : public NCReportItemData { public: NCReportImageData() : aspRatMode(Qt::KeepAspectRatio), transformMode(Qt::FastTransformation), scaling(true), format(0), alignment(Qt::AlignLeft | Qt::AlignTop) {} Qt::AspectRatioMode aspRatMode; Qt::TransformationMode transformMode; bool scaling; uint format; //short htmlAlign; Qt::Alignment alignment; QByteArray htmlWidth, htmlHeight; QByteArray svgXml; #ifdef USE_QIMAGE_INSTEAD_OF_QPIXMAP QImage image; #else QPixmap image; #endif }; /*! Image item class */ class NCReportImageItem : public NCReportItem { public: NCReportImageItem( NCReportDef* rdef, QGraphicsItem* parent =0); ~NCReportImageItem(); enum ImageFormat { Binary=0, Base64Encoded, Svg }; //QRectF boundingRect() const; int type() const; inline Qt::AspectRatioMode aspectRatioMode() const { return ((NCReportImageData*)d)->aspRatMode; } void setAspectRatioMode( Qt::AspectRatioMode am ); inline bool isScaling() const { return ((NCReportImageData*)d)->scaling; } inline void setScaling( bool set ) const { ((NCReportImageData*)d)->scaling = set; } inline Qt::TransformationMode transformMode() const { return ((NCReportImageData*)d)->transformMode; } inline void setTransformMode( Qt::TransformationMode tm ) { ((NCReportImageData*)d)->transformMode = tm; } //inline QString fileName() const //{ return ((NCReportImageData*)d)->filename; } //inline void setFileName( const QString& fname ) //{ ((NCReportImageData*)d)->filename = fname; } inline ImageFormat imageFormat() const { return (ImageFormat)((NCReportImageData*)d)->format; } inline void setImageFormat( ImageFormat f ) { ((NCReportImageData*)d)->format = f; } #ifdef USE_QIMAGE_INSTEAD_OF_QPIXMAP inline QImage image() const #else inline QPixmap image() const #endif { return ((NCReportImageData*)d)->image; } #ifdef USE_QIMAGE_INSTEAD_OF_QPIXMAP inline void setImage( const QImage& image ) #else inline void setImage( const QPixmap& image ) #endif { ((NCReportImageData*)d)->image = image; } inline QByteArray svg() const { return ((NCReportImageData*)d)->svgXml; } inline void setSvg( const QByteArray& svg ) { ((NCReportImageData*)d)->svgXml = svg; } inline QByteArray htmlWidth() const { return ((NCReportImageData*)d)->htmlWidth; } inline void setHtmlWidth( const QByteArray& width ) { ((NCReportImageData*)d)->htmlWidth = width; } inline QByteArray htmlHeight() const { return ((NCReportImageData*)d)->htmlHeight; } inline void setHtmlHeight( const QByteArray& height ) { ((NCReportImageData*)d)->htmlHeight = height; } // inline short htmlAlign() const // { return ((NCReportImageData*)d)->htmlAlign; } // inline void setHtmlAlign( short align ) // { ((NCReportImageData*)d)->htmlAlign = align; } inline Qt::Alignment alignment() const { return ((NCReportImageData*)d)->alignment; } inline void setAlignment( Qt::Alignment al ) { ((NCReportImageData*)d)->alignment = al; } void adjustSize(); bool read( NCReportXMLReader* ); bool write( NCReportXMLWriter* ); void setDefaultForEditor(); void paint( NCReportOutput* output, const QPointF& mPos); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void updateValue(NCReportEvaluator *); void updateContent(); bool load(); QByteArray toBase64() const; QByteArray toHtml() const; private: QPointF imageTargetPoint( const QRectF& itemRect, const QSizeF &imageSize ) const; }; #endif
332bd4dab63eab6fb91c131f3c8da4972763e3cc
24d3fb528330b3343edd28bcd40264e5cc680c26
/proxygen/lib/http/codec/compress/HPACKDecodeBuffer.h
237c515b083de99ebd117ab51fbe745a63abbfb4
[ "BSD-3-Clause" ]
permissive
Yeolar/coral-proxygen
5c56386b7971be2509ba0beba5ea34ac1758b841
345b69711852698326634c295266c1823a9c668b
refs/heads/master
2021-01-18T20:21:27.765578
2015-09-10T11:05:36
2015-09-10T11:05:36
41,807,696
8
0
null
null
null
null
UTF-8
C++
false
false
2,182
h
HPACKDecodeBuffer.h
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <folly/Conv.h> #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include <proxygen/lib/http/codec/compress/HPACKConstants.h> #include <proxygen/lib/http/codec/compress/Huffman.h> namespace proxygen { class HPACKDecodeBuffer { public: explicit HPACKDecodeBuffer(const huffman::HuffTree& huffmanTree, folly::io::Cursor& cursorVal, uint32_t totalBytes) : huffmanTree_(huffmanTree), cursor_(cursorVal), totalBytes_(totalBytes), remainingBytes_(totalBytes) {} ~HPACKDecodeBuffer() {} void reset(folly::io::Cursor& cursorVal) { reset(cursorVal, folly::to<uint32_t>(cursorVal.totalLength())); } void reset(folly::io::Cursor& cursorVal, uint32_t totalBytes) { cursor_ = cursorVal; totalBytes_ = totalBytes; remainingBytes_ = totalBytes; } uint32_t consumedBytes() const { return totalBytes_ - remainingBytes_; } const folly::io::Cursor& cursor() const { return cursor_; } /** * @returns true if there are no more bytes to decode. Calling this method * might move the cursor from the current IOBuf to the next one */ bool empty(); /** * extracts one byte from the buffer and advances the cursor */ uint8_t next(); /** * just peeks at the next available byte without moving the cursor */ uint8_t peek(); /** * decode an integer from the current position, given a nbit prefix * that basically needs to be ignored */ HPACK::DecodeError decodeInteger(uint8_t nbit, uint32_t& integer); /** * decode a literal starting from the current position */ HPACK::DecodeError decodeLiteral(std::string& literal); private: const huffman::HuffTree& huffmanTree_; folly::io::Cursor& cursor_; uint32_t totalBytes_; uint32_t remainingBytes_; }; }
785813bf6fb31f06e1727209d16d8817f6046a41
8d222ca0b4c45656afed23a504b3465184b8ff0a
/C++/calculator.cpp
ef586947830018ef35369bf370ebcbd541924d24
[]
no_license
lifujie/Misc
678df62eccb6e1bdac777b7d0b4aeb3fe8460ee6
1ac9984d37848e5b80d0dea6a7876c48d1246f1f
refs/heads/master
2021-01-25T11:27:16.711497
2012-11-13T06:09:36
2012-11-13T06:09:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,074
cpp
calculator.cpp
/**************************************** * A normal console calculator program. * * Use recursion downward design(LL1). * *--------------------------------------* * E ---> TE * * E ---> +TE | -TE | 0 * * T ---> FT * * T ---> *FT | /FT | 0 * * F ---> (E) | NUM * * *************************************/ #include <stdio.h> #include <string.h> #define N 30 /* Allocation space for express */ #define PLUS 0 #define SUBT 1 #define MULT 2 #define DIVI 3 #define NUM 4 #define LBRK 5 #define RBRK 6 #define END 7 #define OTHER 8 int err; int pCur; int TOKEN; char Get str[N]; /* save express */ double T value; int parser(void); /* A function for syntax analysis */ void Match(void); /* read token */ double E(void); /* figure plus and sub */ double E_(void); /* sub faction of E */ double T(void); /* figure mult and divi */ double T_(void); /* sub faction of T */ double F(void); /* read value and analyse resursion */ int main(int argc, char *argv[]) /* contain command mode */ { if (argc == 2) { strcpy(Get str, argv[1]); Match(); /* initialize value */ printf("The result is: %lf\n\n", E()); } else { printf("Enter a express:\n"); whilE_(!err) { /* iterate condition */ scanf("%s", Get str); Match(); /* initialize value */ printf("%s%lf%s\n", "The result is: ", E(), "\n Input express continue, " "and input any letter Exit.\n"); T value = pCur = 0; /* initialisation */ } printf("ERROR: Contain undefinition charactor - bye!\n\n"); } getchar(); return 0; } //Read a token void Match(void) { TOKEN = parser(); } //analyse express int parser(void) { int cnt = 0; char Tmp[N]; whilE_(Get str[pCur] == ' ') pCur++; whilE_(Get str[pCur] >= '0' && Get str[pCur] <= '9' || Get str[pCur] == '.') Tmp[cnt++] = Get str[pCur++]; if (cnt) { sscanf(Tmp, "%lf", &T value); return NUM; } switch (Get str[pCur++]) { case '+' : return PLUS; case '-' : return SUBT; case '*' : return MULT; case '/' : return DIVI; case '(' : return LBRK; case ')' : return RBRK; case '\0' : return END; default : return OTHER; } } //E-->TE' double E(void) { switch (TOKEN) { case LBRK : case NUM : return T() + E_(); case END : return F(); default : err = 1; return -1; } } //E-->+TE' | -TE' | empty double E_(void) { switch(TOKEN) { case PLUS : Match(); return T() + E_(); case SUBT : Match(); return -(T() - E_()); case RBRK : case END : return 0; default : err = 1; return -1; } } //T-->TE' double T(void) { switch(TOKEN) { case LBRK : case NUM : return F() * T_(); default : err = 1; return -1; } } //T'-->*FT' | /FT' | empty double T_(void) { switch(TOKEN) { case MULT : Match(); return F() * T_(); case DIVI : Match(); return 1 / (F() / T_()); case PLUS : case SUBT : case RBRK : case END: return 1; default : err = 1; return -1; } } //E-->E | value double F(void) { double Tmp; switch(TOKEN) { case LBRK : Match(); Tmp = E(); Match(); return Tmp; case NUM : Tmp = T value; Match(); return Tmp; default : err = 1; return -1; } }
d3fac16f2f921e3227dd650660173d2f7c9b8d7d
09bbbbca189b65d85fd6e189dad5541c73d37143
/lib/algebra/arithmetic.hpp
a7b4126b5fe7fc2cd7cb911c26bbe2e829701468
[]
no_license
hyperpower/carpios
44bdfba95776be17ee6b4c19cf0e8d86d88440d1
07369bea131ab72b7bc85ee7aa259aa77358b3f1
refs/heads/master
2020-09-09T09:42:16.461489
2017-11-01T09:41:25
2017-11-01T09:41:25
94,442,716
0
0
null
null
null
null
UTF-8
C++
false
false
11,910
hpp
arithmetic.hpp
/************************ // \file Arithmetic.h // \brief // // \author czhou // \date 12 févr. 2014 ***********************/ #ifndef ARITHMETIC_H_ #define ARITHMETIC_H_ #include "../type_define.hpp" #include "array_list.hpp" #include <math.h> #include <iostream> namespace carpio { const Float PI = 3.14159265358979323846; const Float EXP = 2.71828182845904523536; template<typename TYPE> inline int StepFun(TYPE x) { return (x <= 0) ? 0 : 1; } inline int Sign(Float x) { if (x < 0.0) { return -1; } else if (x > 0.0) { return 1; } else { return 0; } } enum Range { _oo_, _oc_, _co_, _cc_, }; template<typename TYPE> inline bool IsInRange(const TYPE &down, const TYPE &value, const TYPE &up, const Range &range) { switch (range) { case _oo_: return (down < value && value < up); case _oc_: return (down < value && value <= up); case _co_: return (down <= value && value < up); case _cc_: return (down <= value && value <= up); } return false; } template<class ST> class IdxRange { protected: ArrayListV<ST> _arr; public: typedef typename ArrayListV<ST>::iterator iterator; typedef typename ArrayListV<ST>::const_iterator const_iterator; IdxRange(const ST& down, const ST& up) { ASSERT(down < up); _arr.reconstruct(up - down); _arr.assign_forward(down, 1); } //iterater iterator begin() { return _arr.begin(); } const_iterator begin() const { return _arr.begin(); } iterator end() { return _arr.end(); } const_iterator end() const { return _arr.end(); } }; // round to n digit of a // roundto(3.145,1)=3.1 roundto(3.145,2)=3.15 inline Float RoundTo(Float a, int n) { return round(a * pow(10, n)) / pow(10, n); } // this function return a^2+b^2 inline Float SqareSum(Float &a, Float &b) { return a * a + b * b; } // this function return (a+b)*(a+b) inline Float SumSqare(Float &a, Float &b) { return (a + b) * (a + b); } inline int CountSignificanceDigit(Float a) { for (int i = 0; i < 30; i++) { if (RoundTo(a, i) == a) { return i; } } return -1; } inline Float VolumeOfCircularTruncatedCone(Float R, Float r, Float h) { return PI * h * (R * R + r * r + R * r) / 3; } template<class TYPE> inline TYPE Max(TYPE a, TYPE b, bool (*Comp_ge)(const TYPE &, const TYPE &)) { return Comp_ge(a, b) ? a : b; } template<class TYPE> inline TYPE Max(TYPE a, TYPE b, TYPE c, bool (*Comp_ge)(const TYPE &, const TYPE &)) { TYPE tmp = Comp_ge(a, b) ? a : b; return Comp_ge(tmp, c) ? tmp : c; } template<class TYPE> inline TYPE Min(TYPE a, TYPE b, bool (*Comp_le)(const TYPE &, const TYPE &)) { return Comp_le(a, b) ? a : b; } template<class TYPE> inline TYPE Min(TYPE a, TYPE b, TYPE c, bool (*Comp_le)(const TYPE &, const TYPE &)) { TYPE tmp = Comp_le(a, b) ? a : b; return Comp_le(tmp, c) ? tmp : c; } template<class TYPE> inline TYPE Mid(TYPE a, TYPE b, TYPE c, bool (*Comp_ge)(const TYPE &, const TYPE &)) { int idx = Comp_ge(a, b) ? 1 : 2; if (idx == 1) idx = Comp_ge(a, c) ? 1 : 3; else idx = Comp_ge(b, c) ? 2 : 3; if (idx == 1) return Comp_ge(b, c) ? b : c; else if (idx == 2) return Comp_ge(a, c) ? a : c; else return Comp_ge(a, b) ? a : b; } template<class TYPE> inline void Sort(const TYPE &a, const TYPE &b, const TYPE &c, // bool (*Comp)(const TYPE &, const TYPE &), // TYPE &big, TYPE &mid, TYPE &small) { int idx = Comp(a, b) ? 1 : 2; if (idx == 1) idx = Comp(a, c) ? 1 : 3; else idx = Comp(b, c) ? 2 : 3; if (idx == 1) { big = a; if (Comp(b, c)) { mid = b; small = c; } else { mid = c; small = b; } return; } if (idx == 2) { big = b; if (Comp(a, c)) { mid = a; small = c; } else { mid = c; small = a; } return; } big = c; if (Comp(a, b)) { mid = a; small = b; } else { mid = b; small = a; } } template<class TYPE> bool CompGreat(const TYPE &a, const TYPE &b) { return a > b; } template<class TYPE> bool CompLess(const TYPE &a, const TYPE &b) { return a < b; } template<class TYPE> inline void Sort(const TYPE &a, const TYPE &b, const TYPE &c, // bool (*Comp)(const TYPE &, const TYPE &), // int &big, int &mid, int &small) { int idx = Comp(a, b) ? 0 : 1; if (idx == 0) idx = Comp(a, c) ? 0 : 2; else idx = Comp(b, c) ? 1 : 2; if (idx == 0) { big = 0; if (Comp(b, c)) { mid = 1; small = 2; } else { mid = 2; small = 1; } return; } if (idx == 1) { big = 1; if (Comp(a, c)) { mid = 0; small = 2; } else { mid = 2; small = 0; } return; } big = 2; if (Comp(a, b)) { mid = 0; small = 1; } else { mid = 1; small = 0; } } template<class TYPE> inline void Swap(TYPE &a, TYPE &b) // { TYPE tmp = a; a = b; b = tmp; } template<class TYPE> inline void SortIncrease(TYPE &a, TYPE &b, TYPE &c) // { if (b < a) { swap(a, b); } if (c < a) { swap(a, c); } if (c < b) { swap(b, c); } } template<class TYPE> int SolveQuadraticEquation(const TYPE &a, const TYPE &b, const TYPE &c, Float &x1, Float &x2) { Float discri = 0; int numroot; discri = b * b - 4.0 * a * c; if (discri == 0) { numroot = 1; } else if (discri > 0) { numroot = 2; } else { numroot = 0; } if (numroot == 2) { x1 = (-b - sqrt(discri)) / 2 / a; x2 = (-b + sqrt(discri)) / 2 / a; return 2; } else if (numroot == 1) { x1 = -b / 2 / a; x2 = x1; return 1; } else { return 0; } } template<class TYPE> int SolveCubicEquation(const TYPE &a, const TYPE &b, const TYPE &c, const TYPE &d, Float &x1, Float &x2, Float &x3) { ASSERT(a != 0); Float A = b * b - 3.0 * a * c; Float B = b * c - 9.0 * a * d; Float C = c * c - 3.0 * b * d; Float discri = B * B - 4.0 * A * C; //case 1 has three equal real roots if (A == 0 && B == 0) { x1 = -b / 3.0 / a; x2 = x1; x3 = x1; return 1; } if (discri > 0) { Float Y1 = A * b + 1.5 * a * (-B + sqrt(discri)); Float Y2 = A * b + 1.5 * a * (-B - sqrt(discri)); Float cuberY1 = Y1 < 0 ? -pow(-Y1, 1.0 / 3.0) : pow(Y1, 1.0 / 3.0); Float cuberY2 = Y2 < 0 ? -pow(-Y2, 1.0 / 3.0) : pow(Y2, 1.0 / 3.0); x1 = (-b - cuberY1 - cuberY2) / 3.0 / a; //ignore complex roots x2 = x1; x3 = x1; return 2; } if (discri == 0) { Float K = B / A; x1 = -b / a + K; x2 = K / 2.0; x3 = x2; SortIncrease(x1, x2, x3); return 3; } if (discri < 0) { Float T = (2.0 * A * b - 3.0 * a * B) / (2.0 * pow(A, 1.5)); Float sita3 = acos(T) / 3.0; x1 = (-b - 2.0 * sqrt(A) * cos(sita3)) / (3.0 * a); x2 = (-b + sqrt(A) * (cos(sita3) + sqrt(3.0) * sin(sita3))) / (3.0 * a); x3 = (-b + sqrt(A) * (cos(sita3) - sqrt(3.0) * sin(sita3))) / (3.0 * a); SortIncrease(x1, x2, x3); return 4; } return -1; } inline Float Rand(Float r1, Float r2) { ASSERT(r1 != r2); Float rnum1 = rand() % 100; Float rmax = std::max(r1, r2); Float rmin = std::min(r1, r2); return rmin + (rmax - rmin) / 100 * rnum1; } template<class TYPE> inline TYPE Max(const TYPE& a, const TYPE& b) { return a >= b ? a : b; } template<class TYPE> inline TYPE Max(const TYPE& a, const TYPE& b, const TYPE& c) { return Max(Max(a, b), c); } template<class TYPE> inline TYPE Max(const TYPE a[], St len) { TYPE max = a[0]; for (St i = 1; i < len; ++i) { if (max < a[i]) { max = a[i]; } } return max; } template<class TYPE> inline TYPE Min(const TYPE& a, const TYPE& b) { return a <= b ? a : b; } template<class TYPE> inline TYPE Abs(const TYPE& s) { return s < 0 ? -s : s; } template<class TYPE> inline bool IsEqual(const TYPE& a, const TYPE& b) { return Abs(a - b) < SMALL; } template<class TYPE> inline bool IsZero(const TYPE& a) { return Abs(a - 0.0) < SMALL; } // Greater, equal or less template<class TYPE> inline int GEL(const TYPE& a, const TYPE& v) { //greater equal or less if (v < a) { return -1; } else if (v == a) { return 0; } else { return 1; } } template<class CVT, class VT> struct Interp_ { /// template<class DIM, class POI, class ARR> static VT Linear_all(const DIM& dim, const POI& p, const POI& p1, const POI& p2, const ARR& av) { if (dim == 1) { return Linear(p[0], p1[0], p2[0], av[0], av[1]); } if (dim == 2) { return Bilinear( p[0], p[1], p1[0], p1[1], // p2[0], p2[1], // av[0], av[1], av[2], av[3]); } if (dim == 3) { return Trilinear( // p[0], p[1], p[2], // p1[0], p1[1], p1[2], // p2[0], p2[1], p2[2], // av[0], av[1], av[2], av[3], av[4], av[5], av[6], av[7]); } } /// Linear interpolate. /// Linear reference /// u is a normalized u static VT Linear_r(CVT u, const VT& a, const VT& b) { return ((a * (1.0 - u)) + (b * u)); } static VT Linear(CVT x, CVT x1, CVT x2, const VT& a, const VT& b) { CVT u = (x - x1) / (x2 - x1); return Linear_r(u, a, b); } /// Bilinear interpolate. /* Corners are: * 1b -----2c * ^ | | * | | | * v | | * 0a -----3d * u-> */ static VT Bilinear_r(CVT u, CVT v, const VT& a, const VT& b, const VT& c, const VT& d) { return ((a * (1 - u) * (1 - v)) + (d * (1 - u) * v) + (b * u * (1 - v)) + (c * u * v)); } static VT Bilinear( // CVT x, CVT y, // CVT x1, CVT y1, // CVT x2, CVT y2, // const VT& a, const VT& b, const VT& c, const VT& d) { CVT u = (x - x1) / (x2 - x1); CVT v = (y - y1) / (y2 - y1); return Bilinear_r(u, v, a, b, c, d); } /// Trilinear interpolate. static VT Trilinear_r(CVT u, CVT v, CVT w, const VT& a, const VT& b, const VT& c, const VT& d, const VT& e, const VT& f, const VT& g, const VT& h) { VT t0(Bilinear_r(u, v, a, b, c, d)); VT t1(Bilinear_r(u, v, e, f, g, h)); return (((1 - w) * t0) + (w * t1)); } static VT Trilinear( // CVT x, CVT y, CVT z, // CVT x1, CVT y1, CVT z1, // CVT x2, CVT y2, CVT z2, // const VT& a, const VT& b, const VT& c, const VT& d, const VT& e, const VT& f, const VT& g, const VT& h) { CVT u = (x - x1) / (x2 - x1); CVT v = (y - y1) / (y2 - y1); CVT w = (z - z1) / (z2 - z1); return Trilinear_r(u, v, w, a, b, c, d, e, f, g, h); } }; } //namespace Larus #endif /* ARITHMETIC_H_ */
93605b55a1ef07fd83552ab60b7c8f5b7bd05ecf
90f9301da33fc1e5401ca5430a346610a9423877
/300+/547_Friend_Circles.h
b872a013afc4aa7003d8ade8506226d594e1fa15
[]
no_license
RiceReallyGood/Leetcode
ff19d101ca7555d0fa79ef746f41da2e5803e6f5
dbc432aeeb7bbd4af30d4afa84acbf6b9f5a16b5
refs/heads/master
2021-01-25T22:58:56.601117
2020-04-10T06:27:31
2020-04-10T06:27:31
243,217,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
h
547_Friend_Circles.h
#include <vector> using namespace std; class Solution { public: int findCircleNum(vector<vector<int>>& M) { int N = M.size(); UF uf(N); for(int i = 0; i < N; i++){ for(int j = i + 1; j < N; j++) if(M[i][j] == 1) uf.Union(i, j); } return uf.size(); } private: class UF{ public: UF(int n) : parent(n), rank(n){ sz = n; for(int i = 0; i < n; i++) parent[i] = i; } void Union(int v1, int v2){ int root1 = root(v1); int root2 = root(v2); if(root1 == root2) return; if(rank[root1] > rank[root2]) parent[root2] = root1; else if(rank[root1] < rank[root2]) parent[root1] = root2; else{ parent[root2] = root1; rank[root1]++; } sz--; } int size() {return sz;} private: int root(int v){ if(parent[v] != v) parent[v] = root(parent[v]); return parent[v]; } vector<int> parent; vector<int> rank; int sz; }; };
e7b9019ec94807487f90387e1e4fff080e3daee5
820b6af9fd43b270749224bb278e5f714f655ac9
/Rendering/VR/vtkVRInteractorStyle.cxx
fc653b8d42026f026b97b18a21c5bb3425422074
[ "BSD-3-Clause" ]
permissive
Kitware/VTK
49dee7d4f83401efce8826f1759cd5d9caa281d1
dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271
refs/heads/master
2023-09-01T10:21:57.496189
2023-09-01T08:20:15
2023-09-01T08:21:05
631,615
2,253
1,243
NOASSERTION
2023-09-14T07:53:03
2010-04-27T15:12:58
C++
UTF-8
C++
false
false
46,039
cxx
vtkVRInteractorStyle.cxx
// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen // SPDX-License-Identifier: BSD-3-Clause #include "vtkVRInteractorStyle.h" #include "vtkAssemblyPath.h" #include "vtkCallbackCommand.h" #include "vtkCamera.h" #include "vtkCellPicker.h" #include "vtkInformation.h" #include "vtkMatrix3x3.h" #include "vtkPlane.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkQuaternion.h" #include "vtkRenderer.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSphereSource.h" #include "vtkTextActor3D.h" #include "vtkTextProperty.h" #include "vtkTimerLog.h" #include "vtkTransform.h" #include "vtkVRControlsHelper.h" #include "vtkVRHardwarePicker.h" #include "vtkVRMenuRepresentation.h" #include "vtkVRMenuWidget.h" #include "vtkVRModel.h" #include "vtkVRRenderWindow.h" #include "vtkVRRenderWindowInteractor.h" //------------------------------------------------------------------------------ VTK_ABI_NAMESPACE_BEGIN vtkVRInteractorStyle::vtkVRInteractorStyle() { this->InteractionProps.resize(vtkEventDataNumberOfDevices); this->ClippingPlanes.resize(vtkEventDataNumberOfDevices); for (int d = 0; d < vtkEventDataNumberOfDevices; ++d) { this->InteractionState[d] = VTKIS_NONE; for (int i = 0; i < vtkEventDataNumberOfInputs; i++) { this->ControlsHelpers[d][i] = nullptr; } } // Create default inputs mapping this->MapInputToAction(vtkCommand::Select3DEvent, VTKIS_POSITION_PROP); this->MenuCommand->SetClientData(this); this->MenuCommand->SetCallback(vtkVRInteractorStyle::MenuCallback); this->Menu->SetRepresentation(this->MenuRepresentation); this->Menu->PushFrontMenuItem("exit", "Exit", this->MenuCommand); this->Menu->PushFrontMenuItem("clipmode", "Clipping Mode", this->MenuCommand); this->Menu->PushFrontMenuItem("probemode", "Probe Mode", this->MenuCommand); this->Menu->PushFrontMenuItem("grabmode", "Grab Mode", this->MenuCommand); vtkNew<vtkPolyDataMapper> pdm; this->PickActor->SetMapper(pdm); this->PickActor->GetProperty()->SetLineWidth(4); this->PickActor->GetProperty()->RenderLinesAsTubesOn(); this->PickActor->GetProperty()->SetRepresentationToWireframe(); this->PickActor->DragableOff(); vtkNew<vtkCellPicker> exactPicker; this->SetInteractionPicker(exactPicker); } //------------------------------------------------------------------------------ vtkVRInteractorStyle::~vtkVRInteractorStyle() { for (int d = 0; d < vtkEventDataNumberOfDevices; ++d) { for (int i = 0; i < vtkEventDataNumberOfInputs; i++) { if (this->ControlsHelpers[d][i]) { this->ControlsHelpers[d][i]->Delete(); } } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "HoverPick: " << this->HoverPick << endl; os << indent << "GrabWithRay: " << this->GrabWithRay << endl; } //------------------------------------------------------------------------------ // Generic events binding //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnSelect3D(vtkEventData* edata) { vtkEventDataDevice3D* bd = edata->GetAsEventDataDevice3D(); if (!bd) { return; } int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; this->FindPokedRenderer(x, y); decltype(this->InputMap)::key_type key(vtkCommand::Select3DEvent, bd->GetAction()); auto it = this->InputMap.find(key); if (it == this->InputMap.end()) { return; } int state = it->second; // if grab mode then convert event data into where the ray is intersecting geometry switch (bd->GetAction()) { case vtkEventDataAction::Press: case vtkEventDataAction::Touch: this->StartAction(state, bd); break; case vtkEventDataAction::Release: case vtkEventDataAction::Untouch: this->EndAction(state, bd); break; default: break; } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnNextPose3D(vtkEventData* edata) { vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (!edd) { return; } if (edd->GetAction() == vtkEventDataAction::Press) { this->LoadNextCameraPose(); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::Movement3D(int interactionState, vtkEventData* edata) { vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (!edd) { return; } // Retrieve device type int idev = static_cast<int>(edd->GetDevice()); // Update current state int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; this->FindPokedRenderer(x, y); // Set current state and interaction prop this->InteractionProp = this->InteractionProps[idev]; double const* pos = edd->GetTrackPadPosition(); if (edd->GetAction() == vtkEventDataAction::Press) { this->StartAction(interactionState, edd); this->LastTrackPadPosition[0] = 0.0; this->LastTrackPadPosition[1] = 0.0; this->LastGroundMovementTrackPadPosition[0] = 0.0; this->LastGroundMovementTrackPadPosition[1] = 0.0; this->LastElevationTrackPadPosition[0] = 0.0; this->LastElevationTrackPadPosition[1] = 0.0; return; } if (edd->GetAction() == vtkEventDataAction::Release) { this->EndAction(interactionState, edd); return; } // If the input event is from a joystick and is away from the center then // call start. When the joystick returns to the center, call end. if ((edd->GetInput() == vtkEventDataDeviceInput::Joystick || edd->GetInput() == vtkEventDataDeviceInput::TrackPad) && this->InteractionState[idev] != interactionState && fabs(pos[1]) > 0.1) { this->StartAction(interactionState, edd); this->LastTrackPadPosition[0] = 0.0; this->LastTrackPadPosition[1] = 0.0; this->LastGroundMovementTrackPadPosition[0] = 0.0; this->LastGroundMovementTrackPadPosition[1] = 0.0; this->LastElevationTrackPadPosition[0] = 0.0; this->LastElevationTrackPadPosition[1] = 0.0; return; } if (this->InteractionState[idev] == interactionState) { // Stop when returning to the center on the joystick if ((edd->GetInput() == vtkEventDataDeviceInput::Joystick || edd->GetInput() == vtkEventDataDeviceInput::TrackPad) && fabs(pos[1]) < 0.1) { this->EndAction(interactionState, edd); return; } // Do the 3D movement corresponding to the interaction state switch (interactionState) { case VTKIS_DOLLY: this->Dolly3D(edd); break; case VTKIS_GROUNDMOVEMENT: this->GroundMovement3D(edd); break; case VTKIS_ELEVATION: this->Elevation3D(edd); break; default: break; } this->InvokeEvent(vtkCommand::InteractionEvent, nullptr); return; } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnViewerMovement3D(vtkEventData* edata) { if (this->Style == vtkVRInteractorStyle::FLY_STYLE) { this->Movement3D(VTKIS_DOLLY, edata); } else if (this->Style == vtkVRInteractorStyle::GROUNDED_STYLE) { this->Movement3D(VTKIS_GROUNDMOVEMENT, edata); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnElevation3D(vtkEventData* edata) { if (this->Style == vtkVRInteractorStyle::GROUNDED_STYLE) { this->Movement3D(VTKIS_ELEVATION, edata); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnMove3D(vtkEventData* edata) { vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (!edd) { return; } // Retrieve device type int idev = static_cast<int>(edd->GetDevice()); if (edd->GetDevice() == vtkEventDataDevice::HeadMountedDisplay) { edd->GetWorldDirection(this->HeadsetDir); } // Update current state int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; // Set current state and interaction prop this->InteractionProp = this->InteractionProps[idev]; auto interactionState = this->InteractionState[idev]; switch (interactionState) { case VTKIS_POSITION_PROP: this->FindPokedRenderer(x, y); this->PositionProp(edd); this->InvokeEvent(vtkCommand::InteractionEvent, nullptr); break; case VTKIS_DOLLY: case VTKIS_GROUNDMOVEMENT: case VTKIS_ELEVATION: this->FindPokedRenderer(x, y); this->Movement3D(interactionState, edd); this->InvokeEvent(vtkCommand::InteractionEvent, nullptr); break; case VTKIS_CLIP: this->FindPokedRenderer(x, y); this->Clip(edd); this->InvokeEvent(vtkCommand::InteractionEvent, nullptr); break; default: vtkDebugMacro(<< "OnMove3D: unknown interaction state " << idev << ": " << this->InteractionState[idev]); break; } // Update rays this->UpdateRay(edd->GetDevice()); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnMenu3D(vtkEventData* edata) { vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (!edd) { return; } int x = this->Interactor->GetEventPosition()[0]; int y = this->Interactor->GetEventPosition()[1]; this->FindPokedRenderer(x, y); if (edd->GetAction() == vtkEventDataAction::Press) { this->StartAction(VTKIS_MENU, edd); return; } if (edd->GetAction() == vtkEventDataAction::Release) { this->EndAction(VTKIS_MENU, edd); return; } } //------------------------------------------------------------------------------ // Interaction entry points //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartPick(vtkEventDataDevice3D* edata) { this->HideBillboard(); this->HidePickActor(); this->InteractionState[static_cast<int>(edata->GetDevice())] = VTKIS_PICK; // update ray this->UpdateRay(edata->GetDevice()); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndPick(vtkEventDataDevice3D* edata) { // perform probe this->ProbeData(edata->GetDevice()); this->InteractionState[static_cast<int>(edata->GetDevice())] = VTKIS_NONE; // Update ray this->UpdateRay(edata->GetDevice()); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartLoadCamPose(vtkEventDataDevice3D* edata) { int iDevice = static_cast<int>(edata->GetDevice()); this->InteractionState[iDevice] = VTKIS_LOAD_CAMERA_POSE; } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndLoadCamPose(vtkEventDataDevice3D* edata) { this->LoadNextCameraPose(); int iDevice = static_cast<int>(edata->GetDevice()); this->InteractionState[iDevice] = VTKIS_NONE; } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartPositionProp(vtkEventDataDevice3D* edata) { if (this->GrabWithRay) { if (!this->HardwareSelect(edata->GetDevice(), true)) { return; } vtkSelection* selection = this->HardwarePicker->GetSelection(); if (!selection || selection->GetNumberOfNodes() == 0) { return; } vtkSelectionNode* node = selection->GetNode(0); this->InteractionProp = vtkProp3D::SafeDownCast(node->GetProperties()->Get(vtkSelectionNode::PROP())); } else { double pos[3]; edata->GetWorldPosition(pos); this->FindPickedActor(pos, nullptr); } if (this->InteractionProp == nullptr) { return; } this->InteractionState[static_cast<int>(edata->GetDevice())] = VTKIS_POSITION_PROP; this->InteractionProps[static_cast<int>(edata->GetDevice())] = this->InteractionProp; // Don't start action if a controller is already positioning the prop int rc = static_cast<int>(vtkEventDataDevice::RightController); int lc = static_cast<int>(vtkEventDataDevice::LeftController); if (this->InteractionProps[rc] == this->InteractionProps[lc]) { this->EndPositionProp(edata); return; } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndPositionProp(vtkEventDataDevice3D* edata) { vtkEventDataDevice dev = edata->GetDevice(); this->InteractionState[static_cast<int>(dev)] = VTKIS_NONE; this->InteractionProps[static_cast<int>(dev)] = nullptr; } namespace { // Calls `func` for each prop in `renderer` that is not part of a widget representation template <typename Func> void ForEachNonWidgetProp(vtkRenderer* renderer, Func&& func) { vtkCollectionSimpleIterator cookie; vtkPropCollection* props = renderer->GetViewProps(); props->InitTraversal(cookie); for (vtkProp* prop = props->GetNextProp(cookie); prop; prop = props->GetNextProp(cookie)) { if (!prop->IsA("vtkWidgetRepresentation")) { auto* actor = vtkActor::SafeDownCast(prop); if (actor) { actor->InitPathTraversal(); for (vtkAssemblyPath* path = actor->GetNextPath(); path; path = actor->GetNextPath()) { func(path->GetLastNode()->GetViewProp()); } } } } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartClip(vtkEventDataDevice3D* ed) { if (this->CurrentRenderer == nullptr) { return; } vtkEventDataDevice dev = ed->GetDevice(); this->InteractionState[static_cast<int>(dev)] = VTKIS_CLIP; if (!this->ClippingPlanes[static_cast<int>(dev)]) { this->ClippingPlanes[static_cast<int>(dev)] = vtkSmartPointer<vtkPlane>::New(); } if (this->CurrentRenderer != nullptr) { ForEachNonWidgetProp(this->CurrentRenderer, [this, dev](vtkProp* prop) { auto* actor = vtkActor::SafeDownCast(prop); if (actor) { auto* mapper = actor->GetMapper(); if (mapper) { mapper->AddClippingPlane(this->ClippingPlanes[static_cast<int>(dev)]); } } }); } else { vtkWarningMacro(<< "no current renderer on the interactor style."); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndClip(vtkEventDataDevice3D* ed) { vtkEventDataDevice dev = ed->GetDevice(); this->InteractionState[static_cast<int>(dev)] = VTKIS_NONE; if (this->CurrentRenderer != nullptr) { ForEachNonWidgetProp(this->CurrentRenderer, [this, dev](vtkProp* prop) { auto* actor = vtkActor::SafeDownCast(prop); if (actor) { auto* mapper = actor->GetMapper(); if (mapper) { mapper->RemoveClippingPlane(this->ClippingPlanes[static_cast<int>(dev)]); } } }); } else { vtkWarningMacro(<< "no current renderer on the interactor style."); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartMovement3D(int interactionState, vtkEventDataDevice3D* ed) { if (this->CurrentRenderer == nullptr) { return; } vtkEventDataDevice dev = ed->GetDevice(); this->InteractionState[static_cast<int>(dev)] = interactionState; } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndMovement3D(vtkEventDataDevice3D* ed) { vtkEventDataDevice dev = ed->GetDevice(); this->InteractionState[static_cast<int>(dev)] = VTKIS_NONE; } //------------------------------------------------------------------------------ // Complex gesture interaction methods //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnPan() { int rc = static_cast<int>(vtkEventDataDevice::RightController); int lc = static_cast<int>(vtkEventDataDevice::LeftController); if (!this->InteractionProps[rc] && !this->InteractionProps[lc]) { this->InteractionState[rc] = VTKIS_PAN; this->InteractionState[lc] = VTKIS_PAN; int pointer = this->Interactor->GetPointerIndex(); this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], this->Interactor->GetEventPositions(pointer)[1]); if (this->CurrentRenderer == nullptr) { return; } vtkCamera* camera = this->CurrentRenderer->GetActiveCamera(); vtkRenderWindowInteractor3D* rwi = static_cast<vtkRenderWindowInteractor3D*>(this->Interactor); double t[3] = { rwi->GetTranslation3D()[0] - rwi->GetLastTranslation3D()[0], rwi->GetTranslation3D()[1] - rwi->GetLastTranslation3D()[1], rwi->GetTranslation3D()[2] - rwi->GetLastTranslation3D()[2] }; double* ptrans = rwi->GetPhysicalTranslation(camera); rwi->SetPhysicalTranslation(camera, ptrans[0] + t[0], ptrans[1] + t[1], ptrans[2] + t[2]); // clean up if (this->Interactor->GetLightFollowCamera()) { this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnPinch() { int rc = static_cast<int>(vtkEventDataDevice::RightController); int lc = static_cast<int>(vtkEventDataDevice::LeftController); if (!this->InteractionProps[rc] && !this->InteractionProps[lc]) { this->InteractionState[rc] = VTKIS_ZOOM; this->InteractionState[lc] = VTKIS_ZOOM; int pointer = this->Interactor->GetPointerIndex(); this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], this->Interactor->GetEventPositions(pointer)[1]); if (this->CurrentRenderer == nullptr) { return; } double dyf = this->Interactor->GetScale() / this->Interactor->GetLastScale(); vtkCamera* camera = this->CurrentRenderer->GetActiveCamera(); vtkRenderWindowInteractor3D* rwi = static_cast<vtkRenderWindowInteractor3D*>(this->Interactor); double physicalScale = rwi->GetPhysicalScale(); this->SetScale(camera, physicalScale / dyf); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::OnRotate() { int rc = static_cast<int>(vtkEventDataDevice::RightController); int lc = static_cast<int>(vtkEventDataDevice::LeftController); // Rotate only when one controller is not interacting if (!this->InteractionProps[rc] && !this->InteractionProps[lc]) { this->InteractionState[rc] = VTKIS_ROTATE; this->InteractionState[lc] = VTKIS_ROTATE; double angle = this->Interactor->GetRotation() - this->Interactor->GetLastRotation(); // rotate the world, aka rotate the physicalViewDirection about the physicalViewUp vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); if (!renWin) { return; } double* vup = renWin->GetPhysicalViewUp(); double* dop = renWin->GetPhysicalViewDirection(); double newDOP[3]; double wxyz[4]; wxyz[0] = vtkMath::RadiansFromDegrees(angle); wxyz[1] = vup[0]; wxyz[2] = vup[1]; wxyz[3] = vup[2]; vtkMath::RotateVectorByWXYZ(dop, wxyz, newDOP); renWin->SetPhysicalViewDirection(newDOP); } } //------------------------------------------------------------------------------ // Interaction methods //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ProbeData(vtkEventDataDevice controller) { // Invoke start pick method if defined this->InvokeEvent(vtkCommand::StartPickEvent, nullptr); if (!this->HardwareSelect(controller, false)) { return; } // Invoke end pick method if defined if (this->HandleObservers && this->HasObserver(vtkCommand::EndPickEvent)) { this->InvokeEvent(vtkCommand::EndPickEvent, this->HardwarePicker->GetSelection()); } else { this->EndPickCallback(this->HardwarePicker->GetSelection()); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::PositionProp(vtkEventData* ed, double* lwpos, double* lwori) { if (this->InteractionProp == nullptr || !this->InteractionProp->GetDragable()) { return; } this->Superclass::PositionProp(ed, lwpos, lwori); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::Clip(vtkEventDataDevice3D* ed) { if (this->CurrentRenderer == nullptr) { return; } const double* wpos = ed->GetWorldPosition(); const double* wori = ed->GetWorldOrientation(); double ori[4]; ori[0] = vtkMath::RadiansFromDegrees(wori[0]); ori[1] = wori[1]; ori[2] = wori[2]; ori[3] = wori[3]; // we have a position and a normal, that defines our plane double r[3]; double up[3]; up[0] = 0; up[1] = -1; up[2] = 0; vtkMath::RotateVectorByWXYZ(up, ori, r); vtkEventDataDevice dev = ed->GetDevice(); int idev = static_cast<int>(dev); this->ClippingPlanes[idev]->SetNormal(r); this->ClippingPlanes[idev]->SetOrigin(wpos[0], wpos[1], wpos[2]); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::GroundMovement3D(vtkEventDataDevice3D* edd) { if (this->CurrentRenderer == nullptr) { return; } vtkVRRenderWindowInteractor* rwi = vtkVRRenderWindowInteractor::SafeDownCast(this->Interactor); // Get joystick position if (edd->GetType() == vtkCommand::ViewerMovement3DEvent) { edd->GetTrackPadPosition(this->LastGroundMovementTrackPadPosition); } // Get current translation of the scene double* sceneTrans = rwi->GetPhysicalTranslation(this->CurrentRenderer->GetActiveCamera()); // Get the physical view up vector (in world coordinates) double* physicalViewUp = rwi->GetPhysicalViewUp(); vtkMath::Normalize(physicalViewUp); this->LastGroundMovement3DEventTime->StopTimer(); // Compute travelled distance during elapsed time double physicalScale = rwi->GetPhysicalScale(); double distanceTravelledWorld = this->DollyPhysicalSpeed * /* m/sec */ physicalScale * /* world/physical */ this->LastGroundMovement3DEventTime->GetElapsedTime(); /* sec */ this->LastGroundMovement3DEventTime->StartTimer(); // Get the translation according to the headset view direction vector // projected on the "XY" (ground) plan. double viewTrans[3] = { physicalViewUp[0], physicalViewUp[1], physicalViewUp[2] }; vtkMath::MultiplyScalar(viewTrans, vtkMath::Dot(this->HeadsetDir, physicalViewUp)); vtkMath::Subtract(this->HeadsetDir, viewTrans, viewTrans); vtkMath::Normalize(viewTrans); // Get the translation according to the headset "right" direction vector // projected on the "XY" (ground) plan. double rightTrans[3] = { 0.0, 0.0, 0.0 }; vtkMath::Cross(viewTrans, physicalViewUp, rightTrans); vtkMath::Normalize(rightTrans); // Scale the view direction translation according to the up / down thumbstick position. double scaledDistanceViewDir = this->LastGroundMovementTrackPadPosition[1] * distanceTravelledWorld; vtkMath::MultiplyScalar(viewTrans, scaledDistanceViewDir); // Scale the right direction translation according to the left / right thumbstick position. double scaledDistanceRightDir = this->LastGroundMovementTrackPadPosition[0] * distanceTravelledWorld; vtkMath::MultiplyScalar(rightTrans, scaledDistanceRightDir); // Compute and set new translation of the scene double newSceneTrans[3] = { 0.0, 0.0, 0.0 }; vtkMath::Add(viewTrans, rightTrans, newSceneTrans); vtkMath::Subtract(sceneTrans, newSceneTrans, newSceneTrans); rwi->SetPhysicalTranslation( this->CurrentRenderer->GetActiveCamera(), newSceneTrans[0], newSceneTrans[1], newSceneTrans[2]); if (this->AutoAdjustCameraClippingRange) { this->CurrentRenderer->ResetCameraClippingRange(); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::Elevation3D(vtkEventDataDevice3D* edd) { if (this->CurrentRenderer == nullptr) { return; } vtkVRRenderWindowInteractor* rwi = vtkVRRenderWindowInteractor::SafeDownCast(this->Interactor); // Get joystick position if (edd->GetType() == vtkCommand::Elevation3DEvent) { edd->GetTrackPadPosition(this->LastElevationTrackPadPosition); } // Get current translation of the scene double* sceneTrans = rwi->GetPhysicalTranslation(this->CurrentRenderer->GetActiveCamera()); // Get the physical view up vector (in world coordinates) double* physicalViewUp = rwi->GetPhysicalViewUp(); vtkMath::Normalize(physicalViewUp); this->LastElevation3DEventTime->StopTimer(); // Compute travelled distance during elapsed time double physicalScale = rwi->GetPhysicalScale(); double distanceTravelledWorld = this->DollyPhysicalSpeed * /* m/sec */ physicalScale * /* world/physical */ this->LastElevation3DEventTime->GetElapsedTime(); /* sec */ this->LastElevation3DEventTime->StartTimer(); // Get the translation according to the "Z" (up) world coordinates axis, // scaled according to the up / down thumbstick position. double scaledDistance = this->LastElevationTrackPadPosition[1] * distanceTravelledWorld; double upTrans[3] = { physicalViewUp[0], physicalViewUp[1], physicalViewUp[2] }; vtkMath::MultiplyScalar(upTrans, scaledDistance); // Compute and set new translation of the scene double newSceneTrans[3] = { 0.0, 0.0, 0.0 }; vtkMath::Subtract(sceneTrans, upTrans, newSceneTrans); rwi->SetPhysicalTranslation( this->CurrentRenderer->GetActiveCamera(), newSceneTrans[0], newSceneTrans[1], newSceneTrans[2]); if (this->AutoAdjustCameraClippingRange) { this->CurrentRenderer->ResetCameraClippingRange(); } } //------------------------------------------------------------------------------ // Utility routines //------------------------------------------------------------------------------ void vtkVRInteractorStyle::MapInputToAction( vtkCommand::EventIds eid, vtkEventDataAction action, int state) { if (state < VTKIS_NONE) { return; } decltype(this->InputMap)::key_type key(eid, action); auto it = this->InputMap.find(key); if (it != this->InputMap.end()) { if (it->second == state) { return; } } this->InputMap[key] = state; this->Modified(); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::MapInputToAction(vtkCommand::EventIds eid, int state) { this->MapInputToAction(eid, vtkEventDataAction::Press, state); this->MapInputToAction(eid, vtkEventDataAction::Release, state); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::StartAction(int state, vtkEventDataDevice3D* edata) { switch (state) { case VTKIS_POSITION_PROP: this->StartPositionProp(edata); break; case VTKIS_DOLLY: this->StartMovement3D(state, edata); this->LastDolly3DEventTime->StartTimer(); break; case VTKIS_GROUNDMOVEMENT: this->StartMovement3D(state, edata); this->LastGroundMovement3DEventTime->StartTimer(); break; case VTKIS_ELEVATION: this->StartMovement3D(state, edata); this->LastElevation3DEventTime->StartTimer(); break; case VTKIS_CLIP: this->StartClip(edata); break; case VTKIS_PICK: this->StartPick(edata); break; case VTKIS_LOAD_CAMERA_POSE: this->StartLoadCamPose(edata); break; case VTKIS_MENU: // Menu is only displayed upon action end (e.g. button release) break; default: vtkDebugMacro(<< "StartAction: unknown state " << state); break; } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndAction(int state, vtkEventDataDevice3D* edata) { switch (state) { case VTKIS_POSITION_PROP: this->EndPositionProp(edata); break; case VTKIS_DOLLY: this->EndMovement3D(edata); this->LastDolly3DEventTime->StopTimer(); break; case VTKIS_GROUNDMOVEMENT: this->EndMovement3D(edata); this->LastGroundMovement3DEventTime->StopTimer(); break; case VTKIS_ELEVATION: this->EndMovement3D(edata); this->LastElevation3DEventTime->StopTimer(); break; case VTKIS_CLIP: this->EndClip(edata); break; case VTKIS_PICK: this->EndPick(edata); break; case VTKIS_MENU: this->Menu->SetInteractor(this->Interactor); this->Menu->Show(edata); break; case VTKIS_LOAD_CAMERA_POSE: this->EndLoadCamPose(edata); break; case VTKIS_TOGGLE_DRAW_CONTROLS: this->ToggleDrawControls(); break; case VTKIS_EXIT: if (this->Interactor) { this->Interactor->ExitCallback(); } break; default: vtkDebugMacro(<< "EndAction: unknown state " << state); break; } // Reset complex gesture state because a button has been released for (int d = 0; d < vtkEventDataNumberOfDevices; ++d) { switch (this->InteractionState[d]) { case VTKIS_PAN: case VTKIS_ZOOM: case VTKIS_ROTATE: this->InteractionState[d] = VTKIS_NONE; break; default: vtkDebugMacro(<< "EndAction: unknown interaction state " << d << ": " << this->InteractionState[d]); break; } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::AddTooltipForInput( vtkEventDataDevice device, vtkEventDataDeviceInput input, const std::string& text) { int iInput = static_cast<int>(input); int iDevice = static_cast<int>(device); std::string controlName; std::string controlText; int drawSide = -1; int buttonSide = -1; // Setup default text and layout switch (input) { case vtkEventDataDeviceInput::Trigger: controlName = "trigger"; drawSide = vtkVRControlsHelper::Left; buttonSide = vtkVRControlsHelper::Back; controlText = "Trigger :\n"; break; case vtkEventDataDeviceInput::TrackPad: controlName = "trackpad"; drawSide = vtkVRControlsHelper::Right; buttonSide = vtkVRControlsHelper::Front; controlText = "Trackpad :\n"; break; case vtkEventDataDeviceInput::Grip: controlName = "lgrip"; drawSide = vtkVRControlsHelper::Right; buttonSide = vtkVRControlsHelper::Back; controlText = "Grip :\n"; break; case vtkEventDataDeviceInput::ApplicationMenu: controlName = "button"; drawSide = vtkVRControlsHelper::Left; buttonSide = vtkVRControlsHelper::Front; controlText = "Application Menu :\n"; break; default: vtkWarningMacro(<< "AddTooltipForInput: unknown input type " << static_cast<int>(input)); break; } controlText += text; // Clean already existing helpers if (this->ControlsHelpers[iDevice][iInput] != nullptr) { if (this->CurrentRenderer) { this->CurrentRenderer->RemoveViewProp(this->ControlsHelpers[iDevice][iInput]); } this->ControlsHelpers[iDevice][iInput]->Delete(); this->ControlsHelpers[iDevice][iInput] = nullptr; } // Create an input helper and add it to the renderer vtkVRControlsHelper* inputHelper = this->MakeControlsHelper(); inputHelper->SetTooltipInfo(controlName.c_str(), buttonSide, drawSide, controlText.c_str()); this->ControlsHelpers[iDevice][iInput] = inputHelper; this->ControlsHelpers[iDevice][iInput]->SetDevice(device); if (this->CurrentRenderer) { this->ControlsHelpers[iDevice][iInput]->SetRenderer(this->CurrentRenderer); this->ControlsHelpers[iDevice][iInput]->BuildRepresentation(); this->CurrentRenderer->AddViewProp(this->ControlsHelpers[iDevice][iInput]); } } //------------------------------------------------------------------------------ // Handle Ray drawing and update //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ShowRay(vtkEventDataDevice controller) { vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); if (!renWin || (controller != vtkEventDataDevice::LeftController && controller != vtkEventDataDevice::RightController)) { return; } vtkVRModel* cmodel = renWin->GetModelForDevice(controller); if (cmodel) { cmodel->SetShowRay(true); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::HideRay(vtkEventDataDevice controller) { vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); if (!renWin || (controller != vtkEventDataDevice::LeftController && controller != vtkEventDataDevice::RightController)) { return; } vtkVRModel* cmodel = renWin->GetModelForDevice(controller); if (cmodel) { cmodel->SetShowRay(false); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::UpdateRay(vtkEventDataDevice controller) { if (!this->Interactor) { return; } vtkRenderer* ren = this->CurrentRenderer; vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); vtkVRRenderWindowInteractor* iren = vtkVRRenderWindowInteractor::SafeDownCast(this->Interactor); if (!ren || !renWin || !iren) { return; } vtkVRModel* mod = renWin->GetModelForDevice(controller); if (!mod) { return; } int idev = static_cast<int>(controller); // Keep the same ray if a controller is interacting with a prop if (this->InteractionProps[idev] != nullptr) { return; } // Check if interacting with a widget vtkPropCollection* props = ren->GetViewProps(); vtkIdType nbProps = props->GetNumberOfItems(); for (vtkIdType i = 0; i < nbProps; i++) { vtkWidgetRepresentation* rep = vtkWidgetRepresentation::SafeDownCast(props->GetItemAsObject(i)); if (rep && rep->IsA("vtkQWidgetRepresentation") && rep->GetInteractionState() != 0) { mod->SetShowRay(true); mod->SetRayLength(ren->GetActiveCamera()->GetClippingRange()[1]); mod->SetRayColor(0.0, 0.0, 1.0); return; } } if (this->GetGrabWithRay() || this->InteractionState[idev] == VTKIS_PICK) { mod->SetShowRay(true); } else { mod->SetShowRay(false); return; } // Set length to its max if interactive picking is off if (!this->HoverPick) { mod->SetRayColor(1.0, 0.0, 0.0); mod->SetRayLength(ren->GetActiveCamera()->GetClippingRange()[1]); return; } // Compute controller position and world orientation double p0[3]; // Ray start point double wxyz[4]; // Controller orientation double dummy_ppos[3]; double wdir[3]; vtkMatrix4x4* devicePose = renWin->GetDeviceToPhysicalMatrixForDevice(controller); if (!devicePose) { return; } iren->ConvertPoseToWorldCoordinates(devicePose, p0, wxyz, dummy_ppos, wdir); // Compute ray length. this->InteractionPicker->Pick3DRay(p0, wxyz, ren); // If something is picked, set the length accordingly vtkProp3D* prop = this->InteractionPicker->GetProp3D(); if (prop) { double p1[3]; this->InteractionPicker->GetPickPosition(p1); mod->SetRayLength(sqrt(vtkMath::Distance2BetweenPoints(p0, p1))); mod->SetRayColor(0.0, 1.0, 0.0); } // Otherwise set the length to its max else { mod->SetRayLength(ren->GetActiveCamera()->GetClippingRange()[1]); mod->SetRayColor(1.0, 0.0, 0.0); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ShowBillboard(const std::string& text) { vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); vtkRenderer* ren = this->CurrentRenderer; if (!renWin || !ren) { return; } renWin->UpdateHMDMatrixPose(); double dop[3]; ren->GetActiveCamera()->GetDirectionOfProjection(dop); double vr[3]; double* vup = renWin->GetPhysicalViewUp(); double dtmp[3]; double vupdot = vtkMath::Dot(dop, vup); if (fabs(vupdot) < 0.999) { dtmp[0] = dop[0] - vup[0] * vupdot; dtmp[1] = dop[1] - vup[1] * vupdot; dtmp[2] = dop[2] - vup[2] * vupdot; vtkMath::Normalize(dtmp); } else { renWin->GetPhysicalViewDirection(dtmp); } vtkMath::Cross(dtmp, vup, vr); vtkNew<vtkMatrix4x4> rot; for (int i = 0; i < 3; ++i) { rot->SetElement(0, i, vr[i]); rot->SetElement(1, i, vup[i]); rot->SetElement(2, i, -dtmp[i]); } rot->Transpose(); double orient[3]; vtkTransform::GetOrientation(orient, rot); vtkTextProperty* prop = this->TextActor3D->GetTextProperty(); this->TextActor3D->SetOrientation(orient); this->TextActor3D->RotateX(-30.0); double tpos[3]; double scale = renWin->GetPhysicalScale(); ren->GetActiveCamera()->GetPosition(tpos); tpos[0] += (0.7 * scale * dop[0] - 0.1 * scale * vr[0] - 0.4 * scale * vup[0]); tpos[1] += (0.7 * scale * dop[1] - 0.1 * scale * vr[1] - 0.4 * scale * vup[1]); tpos[2] += (0.7 * scale * dop[2] - 0.1 * scale * vr[2] - 0.4 * scale * vup[2]); this->TextActor3D->SetPosition(tpos); // scale should cover 10% of FOV double fov = ren->GetActiveCamera()->GetViewAngle(); double tsize = 0.1 * 2.0 * atan(fov * 0.5); // 10% of fov tsize /= 200.0; // about 200 pixel texture map scale *= tsize; this->TextActor3D->SetScale(scale, scale, scale); this->TextActor3D->SetInput(text.c_str()); this->CurrentRenderer->AddActor(this->TextActor3D); prop->SetFrame(1); prop->SetFrameColor(1.0, 1.0, 1.0); prop->SetBackgroundOpacity(1.0); prop->SetBackgroundColor(0.0, 0.0, 0.0); prop->SetFontSize(14); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::HideBillboard() { this->CurrentRenderer->RemoveActor(this->TextActor3D); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ShowPickSphere(double* pos, double radius, vtkProp3D* prop) { this->PickActor->GetProperty()->SetColor(this->PickColor); this->Sphere->SetCenter(pos); this->Sphere->SetRadius(radius); this->PickActor->GetMapper()->SetInputConnection(this->Sphere->GetOutputPort()); if (prop) { this->PickActor->SetPosition(prop->GetPosition()); this->PickActor->SetScale(prop->GetScale()); } else { this->PickActor->SetPosition(0.0, 0.0, 0.0); this->PickActor->SetScale(1.0, 1.0, 1.0); } this->CurrentRenderer->AddActor(this->PickActor); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ShowPickCell(vtkCell* cell, vtkProp3D* prop) { vtkNew<vtkPolyData> pd; vtkNew<vtkPoints> pdpts; pdpts->SetDataTypeToDouble(); vtkNew<vtkCellArray> lines; this->PickActor->GetProperty()->SetColor(this->PickColor); int nedges = cell->GetNumberOfEdges(); if (nedges) { for (int edgenum = 0; edgenum < nedges; ++edgenum) { vtkCell* edge = cell->GetEdge(edgenum); vtkPoints* pts = edge->GetPoints(); int npts = edge->GetNumberOfPoints(); lines->InsertNextCell(npts); for (int ep = 0; ep < npts; ++ep) { vtkIdType newpt = pdpts->InsertNextPoint(pts->GetPoint(ep)); lines->InsertCellPoint(newpt); } } } else if (cell->GetCellType() == VTK_LINE || cell->GetCellType() == VTK_POLY_LINE) { vtkPoints* pts = cell->GetPoints(); int npts = cell->GetNumberOfPoints(); lines->InsertNextCell(npts); for (int ep = 0; ep < npts; ++ep) { vtkIdType newpt = pdpts->InsertNextPoint(pts->GetPoint(ep)); lines->InsertCellPoint(newpt); } } else { return; } pd->SetPoints(pdpts.Get()); pd->SetLines(lines.Get()); if (prop) { this->PickActor->SetPosition(prop->GetPosition()); this->PickActor->SetScale(prop->GetScale()); this->PickActor->SetUserMatrix(prop->GetUserMatrix()); } else { this->PickActor->SetPosition(0.0, 0.0, 0.0); this->PickActor->SetScale(1.0, 1.0, 1.0); } this->PickActor->SetOrientation(prop->GetOrientation()); static_cast<vtkPolyDataMapper*>(this->PickActor->GetMapper())->SetInputData(pd); this->CurrentRenderer->AddActor(this->PickActor); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::HidePickActor() { if (this->CurrentRenderer) { this->CurrentRenderer->RemoveActor(this->PickActor); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::ToggleDrawControls() { if (this->CurrentRenderer == nullptr) { return; } // Enable helpers for (int d = 0; d < vtkEventDataNumberOfDevices; ++d) { // No helper for HMD if (static_cast<vtkEventDataDevice>(d) == vtkEventDataDevice::HeadMountedDisplay) { continue; } for (int i = 0; i < vtkEventDataNumberOfInputs; i++) { if (this->ControlsHelpers[d][i]) { if (this->ControlsHelpers[d][i]->GetRenderer() != this->CurrentRenderer) { vtkRenderer* ren = this->ControlsHelpers[d][i]->GetRenderer(); if (ren) { ren->RemoveViewProp(this->ControlsHelpers[d][i]); } this->ControlsHelpers[d][i]->SetRenderer(this->CurrentRenderer); this->ControlsHelpers[d][i]->BuildRepresentation(); this->CurrentRenderer->AddViewProp(this->ControlsHelpers[d][i]); } this->ControlsHelpers[d][i]->SetEnabled(!this->ControlsHelpers[d][i]->GetEnabled()); } } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::SetDrawControls(bool val) { if (this->CurrentRenderer == nullptr) { return; } // Enable helpers for (int d = 0; d < vtkEventDataNumberOfDevices; ++d) { // No helper for HMD if (static_cast<vtkEventDataDevice>(d) == vtkEventDataDevice::HeadMountedDisplay) { continue; } for (int i = 0; i < vtkEventDataNumberOfInputs; i++) { if (this->ControlsHelpers[d][i]) { if (this->ControlsHelpers[d][i]->GetRenderer() != this->CurrentRenderer) { vtkRenderer* ren = this->ControlsHelpers[d][i]->GetRenderer(); if (ren) { ren->RemoveViewProp(this->ControlsHelpers[d][i]); } this->ControlsHelpers[d][i]->SetRenderer(this->CurrentRenderer); this->ControlsHelpers[d][i]->BuildRepresentation(); this->CurrentRenderer->AddViewProp(this->ControlsHelpers[d][i]); } this->ControlsHelpers[d][i]->SetEnabled(val); } } } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::SetInteractor(vtkRenderWindowInteractor* iren) { this->Superclass::SetInteractor(iren); if (iren) { this->SetupActions(iren); } } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::EndPickCallback(vtkSelection* sel) { if (!sel) { return; } vtkSelectionNode* node = sel->GetNode(0); if (!node || !node->GetProperties()->Has(vtkSelectionNode::PROP())) { return; } vtkProp3D* prop = vtkProp3D::SafeDownCast(node->GetProperties()->Get(vtkSelectionNode::PROP())); if (!prop) { return; } this->ShowPickSphere(prop->GetCenter(), prop->GetLength() / 2.0, nullptr); } //------------------------------------------------------------------------------ void vtkVRInteractorStyle::MenuCallback( vtkObject* vtkNotUsed(object), unsigned long, void* clientdata, void* calldata) { std::string name = static_cast<const char*>(calldata); vtkVRInteractorStyle* self = static_cast<vtkVRInteractorStyle*>(clientdata); if (name == "exit") { if (self->Interactor) { self->Interactor->ExitCallback(); } } if (name == "togglelabel") { self->ToggleDrawControls(); } if (name == "clipmode") { self->MapInputToAction(vtkCommand::Select3DEvent, VTKIS_CLIP); } if (name == "grabmode") { self->MapInputToAction(vtkCommand::Select3DEvent, VTKIS_POSITION_PROP); } if (name == "probemode") { self->MapInputToAction(vtkCommand::Select3DEvent, VTKIS_PICK); } } //------------------------------------------------------------------------------ bool vtkVRInteractorStyle::HardwareSelect(vtkEventDataDevice controller, bool actorPassOnly) { vtkRenderer* ren = this->CurrentRenderer; vtkVRRenderWindow* renWin = vtkVRRenderWindow::SafeDownCast(this->Interactor->GetRenderWindow()); vtkVRRenderWindowInteractor* iren = static_cast<vtkVRRenderWindowInteractor*>(this->Interactor); if (!ren || !renWin || !iren) { return false; } vtkVRModel* cmodel = renWin->GetModelForDevice(controller); if (!cmodel) { return false; } cmodel->SetVisibility(false); // Compute controller position and world orientation double p0[3]; // Ray start point double wxyz[4]; // Controller orientation double dummy_ppos[3]; double wdir[3]; vtkMatrix4x4* devicePose = renWin->GetDeviceToPhysicalMatrixForDevice(controller); if (!devicePose) { return false; } iren->ConvertPoseToWorldCoordinates(devicePose, p0, wxyz, dummy_ppos, wdir); this->HardwarePicker->PickProp(p0, wxyz, ren, ren->GetViewProps(), actorPassOnly); cmodel->SetVisibility(true); return true; } VTK_ABI_NAMESPACE_END
d2420c030b765d2ab4e3e61451d32d4bddb21731
c21c8cba94f4f73aa23de98e555ef77bcab494f0
/GeeksforGeeks/Random-problems/gold mine problem.cpp
91bdab55bb98d67206dfa8471475ffe134d23aa4
[]
no_license
hoatd/Ds-Algos-
fc3ed0c8c1b285fb558f53eeeaea2632e0ed03ae
1e74995433685f32ce75a036cd82460605024c49
refs/heads/master
2023-03-19T05:48:42.595330
2019-04-29T06:20:43
2019-04-29T06:20:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,422
cpp
gold mine problem.cpp
// AUTHOR: SHIV ANAND // LANGUAGE: CPP /** Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially the miner is at first column but can be at any row. He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. Find out maximum amount of gold he can collect. **/ /** Input : mat[][] = {{1, 3, 3}, {2, 1, 4}, {0, 6, 4}}; Output : 12 {(1,0)->(2,1)->(2,2)} **/ #include<bits/stdc++.h> #define si(x) scanf("%d",&x) #define slli(x) scanf("%lld",&x) #define sli(x) scanf("%ld",&x) #define ff first #define ss second #define pb push_back #define mp make_pair #define LL long long #define mod 1000000007 #define pfi(x) printf("%d\n",x) #define pfli(x) printf("%ld\n",x) #define pflli(x) printf("%lld\n",x) #define lli long long int #define ull unsigned long long int using namespace std; const int maxn = 1e2+2; int gold[maxn][maxn]; int dp_maximum_gold(int n,int m) { int dp_gold[n][m]; memset(dp_gold, 0, sizeof(dp_gold)); for(int col=m-1; col>=0; col--) { for(int row =0; row < n; row++) { // collects right if it is not the last column int right_collect = (col == m-1) ? 0 : dp_gold[row][col+1]; // collect right up if it is not the first row or last column int right_up_collect = (col == m-1 || row == 0) ? 0 : dp_gold[row-1][col+1]; //collect right down if it is not the last row or last column int right_down_collect = (col == m-1 || row == n-1) ? 0 : dp_gold[row+1][col+1]; // now get the max of all the three movements dp_gold[row][col] = gold[row][col] + max(right_collect, max(right_down_collect, right_up_collect)); } } int max_ = dp_gold[0][0]; // returns the maximum collection from the first column because initially miner is at any row in the first column for(int row=1; row<n; row++) { max_ = max(max_ , dp_gold[row][0]); } return max_; } int main() { int n,m; si(n); si(m); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { si(gold[i][j]); } } int ans = dp_maximum_gold(n,m); cout<<ans<<endl; return 0; }
e98fee5eafd770e6c8a586ea4f385d85dfe49f0a
74a9456b605da15cbce5eefcfc22b2c049925d24
/mimosa/rpc/http-call.cc
f942bc8980b29b2de53c70916f92f0a64f4c274e
[ "MIT" ]
permissive
abique/mimosa
195ae693e2270fbfe9129b95b981946fab780d4e
87fff4dfce5f5a792bd7b93db3f3337e477aae76
refs/heads/master
2022-06-30T16:32:55.355008
2022-06-07T11:38:47
2022-06-07T11:38:47
2,087,313
27
8
MIT
2018-01-16T07:20:04
2011-07-22T05:40:03
C++
UTF-8
C++
false
false
1,029
cc
http-call.cc
#include "../stream/string-stream.hh" #include "../stream/copy.hh" #include "../http/client-channel.hh" #include "http-call.hh" #include "json.hh" namespace mimosa { namespace rpc { bool httpCall(const std::string &url, const google::protobuf::Message &request, google::protobuf::Message *response) { http::ClientChannel cc; http::RequestWriter::Ptr rw = new http::RequestWriter(cc); /* request body (JSON) */ stream::StringStream::Ptr data = new stream::StringStream; jsonEncode(data.get(), request); /* request header */ rw->setUrl(url); rw->setMethod(http::kMethodPost); rw->setProto(1, 1); rw->setContentType("application/json"); rw->setContentLength(data->str().size()); if (!rw->sendRequest()) return false; stream::copy(*data, *rw); /* decode response */ auto rr = rw->response(); if (!rr) return false; if (response) jsonDecode(rr.get(), response); return true; } } }
c4889dd1f52cd51d8c5f18e74082796088536c9c
a34aa19f8e550aca3a2babcb32c703b3ae914aff
/Efficiency/ESD/AliAnalysisTaskEfficiencyd.h
d4f0bc562b71c8358c42e9cf513e6b36fc15c01c
[ "MIT" ]
permissive
mpuccio/AnalysisDeuteronFlow
bbfff54fa1c80c28fac9398aa55c7b8ebcaa69f8
fed8fa5eaf1e30726c2d1df1d8fb068543bc0c47
refs/heads/master
2020-05-19T19:16:56.978026
2015-03-25T14:07:21
2015-03-25T14:07:21
24,088,516
2
0
null
null
null
null
UTF-8
C++
false
false
1,463
h
AliAnalysisTaskEfficiencyd.h
// // AliAnalysisTaskEfficiencyd.h // // Created by Maximiliano Puccio on 28/10/14. // Copyright (c) 2014 ALICE. All rights reserved. // #ifndef __AliAnalysisTaskEfficiencyd__ #define __AliAnalysisTaskEfficiencyd__ class TTree; class AliPIDResponse; #include "AliAnalysisTaskSE.h" class AliAnalysisTaskEfficiencyd : public AliAnalysisTaskSE { public: AliAnalysisTaskEfficiencyd(); virtual ~AliAnalysisTaskEfficiencyd(); virtual void UserCreateOutputObjects(); virtual void UserExec(Option_t *); virtual void Terminate(Option_t *); private: AliAnalysisTaskEfficiencyd(const AliAnalysisTaskEfficiencyd &source); AliAnalysisTaskEfficiencyd &operator=(const AliAnalysisTaskEfficiencyd &source); AliPIDResponse *fPIDResponse; TTree *fTree; Float_t fTpMC; Float_t fTpTMC; Float_t fTetaMC; Float_t fTyMC; Float_t fTphiMC; Float_t fTp; Float_t fTpT; Float_t fTeta; Float_t fTphi; Float_t fTbeta; Float_t fTDCAxy; Float_t fTDCAz; Float_t fTchi2; Float_t fTcentrality; UShort_t fTTPCnClusters; UShort_t fTTPCnSignal; Char_t fTITSnClusters; Char_t fTITSnSignal; Bool_t fTIsPrimary; Bool_t fTIsSecondaryFromMaterial; ClassDef(AliAnalysisTaskEfficiencyd, 1); }; #endif /* defined(__AliAnalysisTaskEfficiencyd__) */
2529e6406aaaf5446eab3408b65a45584649c561
0f50401b5d862ed1077d51898414e921cf3f4b22
/src/executor/CephExecutor.hpp
3833ed07b4d99db903c535a296b9e774d038484f
[ "Apache-2.0" ]
permissive
vivint-smarthome/ceph-mesos
912131e58c94c4938cff6b2aedaa9b12c7e58a94
914f50c55aff4d8bbc9c00149e775ebaa3674a33
refs/heads/master
2021-01-15T20:33:35.191767
2017-02-28T10:52:47
2017-02-28T10:52:47
62,018,945
1
0
Apache-2.0
2019-09-18T15:48:50
2016-06-27T02:12:56
C++
UTF-8
C++
false
false
3,053
hpp
CephExecutor.hpp
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _CEPHMESOS_EXECUTOR_CEPHEXECUTOR_HPP_ #define _CEPHMESOS_EXECUTOR_CEPHEXECUTOR_HPP_ #include <mesos/executor.hpp> using std::string; using namespace mesos; class CephExecutor : public Executor { public: CephExecutor(){} ~CephExecutor(){} void registered( ExecutorDriver* driver, const ExecutorInfo& executorInfo, const FrameworkInfo& frameworkInfo, const SlaveInfo& slaveInfo); void reregistered(ExecutorDriver* driver, const SlaveInfo& slaveInfo); void disconnected(ExecutorDriver* driver); void launchTask(ExecutorDriver* driver, const TaskInfo& task); void killTask(ExecutorDriver* driver, const TaskID& taskId); void frameworkMessage(ExecutorDriver* driver, const string& data); void shutdown(ExecutorDriver* driver); void error(ExecutorDriver* driver, const string& message); private: string runShellCommand(string cmd); void deleteConfigDir(string localSharedConfigDir); bool existsConfigFiles(string localSharedConfigDir); bool createLocalSharedConfigDir(string localSharedConfigDir); bool copySharedConfigFiles(); string getContainerName(string taskId); string constructMonCommand( string localMountDir, string _containerName); string registerOSD(); string constructOSDCommand( string localMountDir, string osdId, string _containerName); string constructRADOSGWCommand( string localMountDir, string _containerName); bool block_until_started(string _containerName, string timeout); void startLongRunning(string binaryName, string cmd); bool downloadDockerImage(string imageName); bool parseHostConfig(TaskInfo taskinfo); bool prepareDisks(); bool mountDisk(string diskname, string dir, string flags); string getPublicNetworkIP(string ips, string CIDR); string containerName; TaskID myTaskId; string myHostname; pid_t myPID; string localSharedConfigDirRoot; string localConfigDirName = "ceph_config_root"; string sandboxAbsolutePath; string localMountOSDDir = ""; string localMountJNLDir = ""; //host hardware info string mgmtNIC; string dataNIC; string osddisk; string jnldisk; string mountFLAGS = " -o inode64,noatime,logbsize=256k"; }; #endif
160326bf69d4c1f62d12f3684533b98744f82922
b34b2a4bd56122a619507a453543e0f0ae56d6dd
/PolynomialDemo.cpp
07d9396606d42ed2bd6c0ca3ff7f404223d56c24
[]
no_license
bryanstamey/PolynomialEval
1b03639598a429232d67caa2f24e8e9fcbb0c4e7
50134ddd48454678b142ebaa9f3675fe76ad9e21
refs/heads/master
2021-01-11T16:11:29.755935
2017-02-05T00:12:41
2017-02-05T00:12:41
80,031,047
0
0
null
null
null
null
UTF-8
C++
false
false
3,189
cpp
PolynomialDemo.cpp
/** * Provides input to naive and horner eval functions * and outputs the evaluation of polynomials. * @author Bryan T Stamey * @since 1/23/17 * @see Polynomial.h, Polynomial.cpp */ #include <cstdlib> #include "Polynomial.h" #include <iostream> #include <chrono> #include <random> using namespace std; int main(int argc, char** argv) { typedef std::chrono::high_resolution_clock::time_point TimeVar; //calculate polynomial f double f[] = {4, 5, 0, 2, 3, 5, -1}; Polynomial polyf(f,6); //pass polynomial f cout << "f: [" << polyf.str() << "]\n"; cout << "deg f(x) := " << polyf.degree() << endl; cout << "Using Horner’s method, f(3) = " << polyf.hornerEval(3) << endl; cout << "Using naive method, f(3) = " << polyf.naiveEval(3) << endl << endl; //calculate polynomial g double g[] = {12.5, 0, 0, -1, 7.2, -9.5}; Polynomial polyg(g,5); //pass polynomial g cout << "g: [" << polyg.str() << "] \n"; cout << "deg g(x) := " << polyg.degree() << endl; cout << "Using Horner’s method, g(-7.25) = " << polyg.hornerEval(-7.25) << endl; cout << "Using naive method, g(-7.25) = " << polyg.naiveEval(-7.25) << endl; cout << endl << endl; cout << "Empirical Analysis of Naive vs Horner's Methods \non 10 Polynomials with Random Coefficients\n"; cout << "================================================\n"; cout << "Degree Naive Time (ns) Horner's Time (ns)\n"; cout << "------------------------------------------------\n"; for(int i = 1000; i <= 10000; i = i + 1000) { //1000, 2000, ..., 10000 double *c = new double[i + 1]; for(int j = 0; j <= i; j++) { //loop over exponents srand(time(NULL)); //seeds generator to time c[j] = rand() % 6; //rand nums [0,5] } Polynomial polyc(c,i); //pass polynomial c random_device rd; default_random_engine generator(rd()); uniform_real_distribution<double> distribution(0.5,1.2); double x = distribution(generator); //rand eval num [0.5,1.2] cout << i << " "; //print degree //Naive eval & time chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now(); polyc.naiveEval(x); chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::nanoseconds>( t2 - t1 ).count(); cout << duration << " "; //naive time //Horner eval & time chrono::high_resolution_clock::time_point t3 = chrono::high_resolution_clock::now(); polyc.hornerEval(x); chrono::high_resolution_clock::time_point t4 = chrono::high_resolution_clock::now(); auto duration1 = chrono::duration_cast<chrono::nanoseconds>( t4 - t3 ).count(); cout << duration1 << " \n"; //horner time } cout << "------------------------------------------------\n"; return 0; }
25ded347c9b84827601247912428b379f2db4bc3
aa19b8a46aa4f02b3c20ab10765cc202a559383c
/src/proxy/directproxy.cpp
c928f18606f63a496600b86d0f561c2416efe144
[]
no_license
shizeeg/gluxi-hacks
28a7cbb7249c2d18ef7ecaae643e78511dd6e412
0ad00e3e64dd23db4b400b1f906cfc07f2e95c68
refs/heads/master
2021-01-01T18:29:12.920063
2011-05-10T16:35:39
2011-05-10T16:35:39
1,530,177
1
0
null
null
null
null
UTF-8
C++
false
false
8,383
cpp
directproxy.cpp
#include "directproxy.h" //#define MY_DEBUG #include "socketw/src/SocketW.h" #include <QtGlobal> #include <errno.h> #ifdef MY_DEBUG static int lastFileID=0; #endif DirectProxy::DirectProxy(int id, int typ, QString nfo) : BaseProxy(id, typ, nfo) { qWarning() << "DirectProxy"; // lastURL=""; } DirectProxy::~DirectProxy() {} QByteArray DirectProxy::httpRequest(const QString& prot, const QString&host, const QString&url, QStringList* cookies, QStringList* custHeader, QString& lastURL) { redirectTo.clear(); QByteArray arr; int length; if (!custHeader && !wascustom) { arr.append(QString("GET %1 HTTP/1.0\r\n").arg(url)); } else { arr.append(QString("POST %1 HTTP/1.0\r\n").arg(url)); } if (lastURL!="") arr.append(QString("Referer: %1\r\n").arg(lastURL)); lastURL=QString("%1%2%3").arg(prot,host,url); arr.append(QString("Host: %1\r\n").arg(host)); arr.append(QString("Accept: %1\r\n").arg(contentTypes.join(","))); arr.append(QString("User-Agent: %1\r\n").arg(userAgent)); arr.append("Connection: close\r\n"); if (cookies->count()) { arr.append("Cookie: "); for (int i=0; i<cookies->count(); i++) { arr.append(QString("%1").arg(cookies->value(i))); if (i!=cookies->count()-1) arr.append("; "); } arr.append("\r\n"); } if (custHeader) { length=0; for (int i=0; i<custHeader->count(); i++) length+=custHeader->value(i).length(); arr.append("Content-Type: application/x-www-form-urlencoded\r\n"); arr.append(QString("Content-Length: %1\r\n\r\n").arg(length)); for (int i=0; i<custHeader->count(); i++) arr.append(QString("%1\r\n").arg(custHeader->value(i))); } if (wascustom) { arr.append(QString("Content-Length: %1\r\n").arg(postSize)); arr.append(postData); } else arr.append("\r\n"); #ifdef Q_WS_WIN arr.replace("\r\n","\n"); #endif qWarning() << "---------------------------------->>>>>>>>>>>>" << endl << arr << "----------------------------------"; return arr; } int DirectProxy::parseResponseLine(QString& line, QStringList*cookies, QString&redirect) { qWarning() << "Response | "<<line; headers.append(line); if (line.startsWith("HTTP/")) { errorString=line.section(" ",1); QString code=line.section(" ",1,1); // qDebug() << "CODE:" << code; if (code[0]=='2') return 0; if (code[0]=='4') return -1; if (code[0]=='3') return 0; return 0; } //"Set-Cookie: PHPSESSID=0a59981fcf687e75a80f243eb691f23f; path=/; domain=lafox.net" if (line.toUpper().startsWith("SET-COOKIE: ")) { QString cookie=line.section(" ",1,100); cookie=cookie.section(";",0,0); if (cookie.endsWith(";")) cookie.remove(cookie.length()-1,1); QString cookieName=cookie.section("=",0,0); QString cookieValue=cookie.section("=",1,100).trimmed(); QRegExp exp(QString("%1.*").arg(cookieName)); int idd=cookies->indexOf(exp); while (idd>=0) { cookies->removeAt(idd); idd=cookies->indexOf(exp); } if (cookieValue!="" && cookieValue!="deleted") cookies->append(QString("%1").arg(cookie)); } if (line.toUpper().startsWith("CONTENT-TYPE:")) { line=line.section(": ",1); contentType=line.section(';',0,0).trimmed(); // get Content-type // Find Charset= QRegExp exp("CHARSET=([A-Za-z0-9\\-_]+)"); exp.setMinimal(false); exp.setCaseSensitivity(Qt::CaseInsensitive); if (exp.indexIn(line)>=0) charset=exp.capturedTexts()[1]; if (!contentTypes.isEmpty() && contentTypes.indexOf(contentType)<0) { errorString=QString("Content-type \"%1\" is not allowed").arg(contentType); return -1; } return 0; } if (line.toUpper().startsWith("CONTENT-LENGTH:")) { contentLength=line.section(" ",1,1).toInt(); if (contentLength>maxSize) { errorString=QString("Content-length limit: %1").arg(contentLength); return -1; } return contentLength; } if (line.toUpper().startsWith("LOCATION:")) { redirect=line.section(":",1,1000).trimmed(); redirectTo=redirect; errorString=QString("Redirect to: %1").arg(redirect); } return 0; } int DirectProxy::readResponse(SWInetSocket* socket, MyBuf *buf, QStringList* cookies, QString&redirect) { SWBaseSocket::SWBaseError error; char ch; QString s; int wasn=0; s=""; int res; int ret; ret =0; redirect=""; while (1) { if (buf->pos>=buf->count) { buf->count=socket->recv(buf->data,MYBUFSIZE,&error); if (buf->count<=0) return -1; buf->pos=0; } ch=buf->data[buf->pos++]; if (ch==0x0d) continue; if (ch=='\n') { if (wasn) return ret; res=parseResponseLine(s,cookies,redirect); if (res<0) return res; if (res>0) ret=res; s=""; wasn=1; } else { wasn=0; s+=ch; } } return ret; } QString DirectProxy::fetchPage(const QString&host, const QString&url, QString&referer, QStringList *cookies, QStringList*custHeader, int custom) { headers.clear(); charset.clear(); contentLength=0; SWBaseSocket::SWBaseError error; QString redirect; SWInetSocket socket; // socket.set_timeout(Preferences::connectionTimeout, Preferences::connectionTimeout*1000*1000); wascustom=custom; if (!socket.connect(80,host.toLatin1().data(),&error)) { errorString=QString::fromStdString(socket.get_error()); return 0; } QByteArray arr=httpRequest("http://",host,url, cookies, custHeader, referer); if (!socket.send(arr.data(),arr.size(),&error)) return 0; struct MyBuf buf; buf.count=socket.recv(buf.data,MYBUFSIZE,&error); buf.pos=0; if (buf.count<=0) return 0; int respResult = readResponse(&socket,&buf,cookies,redirect); if (respResult<0) return 0; if (redirect!="") { qWarning("Redirect"); arr.clear(); arr.append(redirect); return QTextStream(arr).readAll(); } if (headersOnly) return 0; arr.clear(); int total=0; if (buf.pos<buf.count) { arr.append(QByteArray(buf.data+buf.pos,buf.count-buf.pos)); total+=arr.count(); buf.count=0; } while (respResult==0 || (total<respResult)) { buf.count=socket.recv(buf.data,MYBUFSIZE,&error); if (buf.count) { arr.append(QByteArray(buf.data,buf.count)); total+=buf.count; } // qDebug() << total << " of " << respResult; if (error == SWBaseSocket::ok) continue; if (error == SWBaseSocket::notConnected || error==SWBaseSocket::terminated || error==SWBaseSocket::timeout) break; return 0; } #ifdef MY_DEBUG lastFileID++; QFile fp("files/"+QString::number(lastFileID).rightJustified(2,QChar('0'))+".html"); fp.open(QIODevice::WriteOnly); fp.write(arr.data(),arr.count()); fp.close(); #endif lastData=arr; return QTextStream(arr).readAll(); } QString DirectProxy::fetchPageSSL(const QString&host, const QString&url, QString&referer, QStringList *cookies, QStringList*custHeader, int custom) { headers.clear(); charset.clear(); contentLength=0; QString redirect; SWBaseSocket::SWBaseError error; SWSSLSocket socket; lastData.clear(); wascustom=custom; // socket.set_timeout(Preferences::connectionTimeout, Preferences::connectionTimeout*1000*1000); // Preferences::addHost(host); if (!socket.connect(443,host.toLatin1().data(),&error)) { errorString=QString::fromStdString(socket.get_error()); return 0; } QByteArray arr=httpRequest("https://",host,url, cookies, custHeader, referer); if (!socket.send(arr.data(),arr.size(),&error)) return 0; struct MyBuf buf; buf.count=socket.recv(buf.data,MYBUFSIZE,&error); buf.pos=0; if (buf.count<=0) return 0; int respResult = readResponse(&socket,&buf,cookies, redirect); if (respResult<0) return 0; if (redirect!="") { // qDebug("Redirect"); arr.clear(); arr.append(redirect); return QTextStream(arr).readAll(); } arr.clear(); int total=0; if (buf.pos<buf.count) { arr.append(QByteArray(buf.data+buf.pos,buf.count-buf.pos)); total+=arr.count(); buf.count=0; } while (respResult==0 || (total<respResult)) { buf.count=socket.recv(buf.data,MYBUFSIZE,&error); if (buf.count) { arr.append(QByteArray(buf.data,buf.count)); total+=buf.count; } // qDebug() << total << " of " << respResult; if (error == SWBaseSocket::ok) continue; if (error == SWBaseSocket::notConnected || error==SWBaseSocket::terminated ||error==SWBaseSocket::timeout) break; return 0; } lastData=arr; #ifdef MY_DEBUG lastFileID++; QFile fp("files/"+QString::number(lastFileID).rightJustified(2,QChar('0'))+".html"); fp.open(QIODevice::WriteOnly); fp.write(arr.data(),arr.count()); fp.close(); #endif return QTextStream(arr).readAll(); }
0d1ad7c86c02618309b718626b64b1acdccee6fe
715c4f02e9d19656e84dc8b2eff7450eb3e33463
/LastVersion/DataBase/DataBase.cpp
96a4b3db7a8397456574077142afd7e6433fc0aa
[]
no_license
amirrezatav/SqliteInCpp
b841c257621f100f890ee0ee2e765edcbd0689ed
de0ffe2139b9f622749b5099093f87a086398d54
refs/heads/main
2023-06-02T20:31:54.715990
2021-06-14T08:42:06
2021-06-14T08:42:06
372,417,201
0
1
null
null
null
null
UTF-8
C++
false
false
8,955
cpp
DataBase.cpp
#include "DataBase.h" DataBase::DataBase() { } DataBase::~DataBase() { Close(); } bool DataBase::Open(string path, bool ThrowExc) { int res = sqlite3_open(path.c_str(),&db); if (res != SQLITE_OK && ThrowExc) { ThrowError(SQLITE_OK); } return true; } void DataBase::Close(bool ThrowExc ) { int res = sqlite3_close(db); if (res != SQLITE_OK && ThrowExc) ThrowError(db); } #pragma region Insertion void DataBase::InsertCustomer(int username, int listid, bool ThrowExc ) { Lock(); const char* sql = "INSERT INTO Customer (Username,ListId)VALUES(?, ?);"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt ,1, username); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 2, listid); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); sqlite3_finalize(stmt); UnLock(); if (res != SQLITE_DONE && ThrowExc) ThrowError(db); } void DataBase::InsertList(int productid, int listid, bool ThrowExc ) { Lock(); const char* sql = "INSERT INTO List (ProductId,ListId,DateTime)VALUES(?, ?, datetime('now', 'localtime'));"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 1, productid); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 2, listid); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); sqlite3_finalize(stmt); UnLock(); if (res != SQLITE_DONE && ThrowExc) ThrowError(db); } void DataBase::InsertProduct(int id, string name, int filesize, string filename, bool ThrowExc) { Lock(); const char* sql = "INSERT INTO Product (Id,Name,File,FileName)VALUES(?, ?, ? ,?);"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 1, id); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_text(stmt, 2, name.c_str(), name.size() , nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_zeroblob(stmt, 3, filesize); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_text(stmt, 4, filename.c_str() , filename.size(),nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); sqlite3_finalize(stmt); UnLock(); if (res != SQLITE_DONE && ThrowExc) ThrowError(db); } int DataBase::GetProductRowId(int id, bool ThrowExc) { const char* sql = "Select rowid from product where id == ?"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 1, id); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); return sqlite3_column_int(stmt, 0); } string DataBase::GetProductFileName(int id, bool ThrowExc) { const char* sql = "Select filename from product where id == ?"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 1, id); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); return string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))); } sqlite3_blob* DataBase::OpenProductFile(int rowid,bool readonly , bool ThrowExc ) { sqlite3_blob* file = nullptr; int res = sqlite3_blob_open(db, "main", "Product", "File", rowid, readonly ? 0 : 1, &file); if (res != SQLITE_OK && ThrowExc) { ThrowError(SQLITE_OK); } return file; } void DataBase::WriteProductFile(sqlite3_blob* file, char* Buffer, long long Size, long long index, bool ThrowExc ) { Lock(); int res = sqlite3_blob_write(file , Buffer , Size, index); UnLock(); if (res != SQLITE_OK && ThrowExc) { CloseProductFile(file); throw exception("Error"); } } void DataBase::GetProductFile(int id, string path) { int rowid = GetProductRowId(id); sqlite3_blob* file = OpenProductFile(rowid, 1); long long size = sqlite3_blob_bytes(file); long long index = 0; const int buffersize = 20 * 1024; char Buffer[buffersize]; string Path = path + "\\" + GetProductFileName(id); ofstream ofs (Path,ios::binary); if (ofs.good()) { while (index < size) { int read = size - index < buffersize ? size - index : buffersize; sqlite3_blob_read(file, Buffer, read, index); ofs.write(Buffer, read); index += read; } } ofs.close(); CloseProductFile(file); } void DataBase::CloseProductFile(sqlite3_blob* file, bool ThrowExc ) { Lock(); int res = sqlite3_blob_close(file); UnLock(); if (res != SQLITE_OK && ThrowExc) { UnLock(); ThrowError(db); } } //#pragma endregion //#pragma region Delete //void DataBase::DeleteCustomer(int username = 0, int listid = 0, bool ThrowExc = true) //{ // //} //void DataBase::DeleteCustomer(int product = 0, int listid = 0, bool ThrowExc = true) //{ // //} //void DataBase::DeleteProduct(int id = 0, string name = "", string filename = "", bool ThrowExc = true) //{ // //} //#pragma endregion //#pragma region Update void DataBase::UpdateCustomerUsername(int usernamelast, int usernameNew, bool ThrowExc) { Lock(); const char* sql = "UPDATE Customer set username = ? where username = ?;"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 1, usernameNew); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_int(stmt, 2, usernamelast); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); sqlite3_finalize(stmt); UnLock(); if (res != SQLITE_DONE && ThrowExc) ThrowError(db); } //void database::updatecustomerlistid(int username, int listidnew, bool throwexc = true) //{ // //} //#pragma endregion #ifndef Other int DataBase::GetCount(string tablename) { string sql = "Select count(*) from " + tablename; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr); if (res != SQLITE_OK) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); if (res != SQLITE_OK ) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } return sqlite3_column_int(stmt, 0); } Book* DataBase::SearchBook(string bookname, int& BookCount, bool ThrowExc) { Lock(); bookname = "%" + bookname + "%"; const char* sql = "Select count(*) from product where name like ?;"; sqlite3_stmt* stmt; int res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_text(stmt, 1, bookname.c_str(), bookname.size(), nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_step(stmt); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } BookCount = sqlite3_column_int(stmt, 0); sql = "Select id,name,filename form product where name like ? ;"; res = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } res = sqlite3_bind_text(stmt, 1, bookname.c_str(), bookname.size(), nullptr); if (res != SQLITE_OK && ThrowExc) { UnLock(); sqlite3_finalize(stmt); ThrowError(db); } Book* books = new Book[BookCount]; /*while (sqlite3_step(stmt) != SQLITE_DONE) { }*/ /*while (sqlite3_step(stmt) == SQLITE_ROW) { }*/ for (int i = 0; i < BookCount; i++) { sqlite3_step(stmt); Book book; book.BookId = sqlite3_column_int(stmt, 0); book.BookName = string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1))); book.filename = string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2))); books[i] = book; } sqlite3_finalize(stmt); UnLock(); return books; } void DataBase::Lock() { sqlite3_mutex_enter(sqlite3_db_mutex(db)); } void DataBase::UnLock() { sqlite3_mutex_leave(sqlite3_db_mutex(db)); } #endif // !Other
e26289a9ab4af94082e1be41beee9cd4b19945f3
5fa2f4655f52421448d7a8a1121287dbd0495c4d
/experiment/main.cc
1a23cb14268ada367bc097ff7270105608d223af
[]
no_license
nipun510/lab
4df69a349f5a30e1a89ac3727d8e4ea7b3c018d5
28a13dabbefc8fc061f3716a270160c72d34a7f2
refs/heads/master
2023-02-10T23:06:02.839371
2023-01-29T10:50:27
2023-01-29T10:50:27
206,139,811
0
0
null
null
null
null
UTF-8
C++
false
false
67
cc
main.cc
#include "example.h" int main() { person<int> p; p.fun(); }
f37e002264a70f6cbfe7601ac677a6e9dd03281d
a4727da298b6ccfc8441acf025749dfd8b38465a
/include/deal.II-translator/A-headers/instantiations.h
bf7476a055d1a13ec72dc32146e2323db537acd8
[]
no_license
jiaqiwang969/dealii-transltor
6e16295a67118214142de31d0df3979c19a93785
e3019fbaf625aa1c56cac08a3d61af4d6d3b4b3d
refs/heads/master
2023-05-09T20:27:50.493383
2021-06-09T06:45:09
2021-06-09T06:45:09
374,146,574
0
0
null
null
null
null
UTF-8
C++
false
false
5,462
h
instantiations.h
// --------------------------------------------------------------------- // // Copyright (C) 2005 - 2020 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE.md at // the top level directory of deal.II. // // --------------------------------------------------------------------- /** * @page Instantiations Template instantiations * Instantiation of complex class and function templates is expensive both in * terms of compile time and disk space. Therefore, we try to separate * declaration and implementation of templates as far as possible, and make * sure that implementations are read by the compiler only when necessary. * Template classes in <tt>deal.II</tt> can be grouped into three categories, * depending on the number of probable different instantiations. These three * groups are discussed in the following. * * * * @section Inst1 Known and fixed number of instantiations These are the * classes having template parameters with very predictable values. The * typical prototype is * * @code * template <int dim> class Function; * @endcode * * Here, we have a small number of instantiations ( <code>dim = 1,2,3</code> * ) known at the time of design of the library. Therefore, member functions * of this class are defined in a <tt>.cc</tt> file in the source directory * and we instantiate the template for these known values explicitly in the * source file. From an application viewpoint, all you actually get to see * then is the declaration of the template. Actual instantiations of member * functions happens inside the library and is done when you compile the * library, not when you compile your application code. For these classes, * adding instantiations for new parameters involves changing the library. * However, this is rarely needed, of course, unless you are not content with * computing only in 1d, 2d, or 3d. * * * * @subsection Inst1a Available instances If the template parameter is * <tt>dim</tt>, the available instances are for <tt>dim=1,2,3</tt>, if there * is no other information. There are other cases of classes (not depending on * the spatial dimension) for which only a certain, small number of template * arguments is supported and explicit instantiations are provided in the * library. In particular, this includes all the linear algebra classes that * are templatized on the type of the scalar underlying stored values: we only * support <code>double</code>, <code>float</code> , and in some cases * <code>std::complex@<double@></code> and * <code>std::complex@<float@></code> . * * * * @section Inst2 A few instantiations, most of which are known These are * class templates usually having a small number of instantiations, but * additional instantiations may be necessary. Therefore, a set of * instantiations for the most likely parameters is provided precompiled in * the libraries, but the implementation of the templates are provided in a * special header file so that it is accessible in case someone wants to * instantiate it for an unforeseen argument. Typical examples for this would * be some of the linear algebra classes that take a vector type as template * argument. They would be instantiated within the library for * <code>Vector&lt;double&gt;</code> , <code>Vector&lt;float&gt;</code>, * <code>BlockVector&lt;double&gt;</code> , and * <code>BlockVector&lt;float&gt;</code> , for example. However, they may * also be used with other vector types, such as <code>long double</code> * and <code>std::complex@<long double@></code> , as long as they satisfy * certain interfaces, including vector types that are not part of the library * but possibly defined in an application program. In such a case, * applications can instantiate these templates by hand as described in the * next section. * * * * @subsection Inst2c Creating new instances Choose one of your source files * to provide the required instantiations. Say that you want the class * template <tt>XXXX</tt>, defined in the header file <tt>xxxx.h</tt>, * instantiated with the template parameter <tt>long double</tt>. Then, your * file should contain the lines * * @code * // Include class template declaration * #include <xxxx.h> * // Include member definitions * #include <xxxx.templates.h> * * ... * * template class XXXX<long double>; * @endcode * * * * * @subsection Inst2p Provided instances * Like with * the classes in section @ref Inst1 , the instances provided in the * library are often listed in the documentation of that class in a form * similar to this: * * @verbatim * Template Instantiations: some (<p1>a,b,c<p2>) * @endverbatim * * * * * @section Inst3 Many unknown instantiations These are the classes, where * no reasonable predetermined set of instances exists. Therefore, all member * definitions are included in the header file and are instantiated wherever * needed. An example would be the SmartPointer class template that can be * used with virtually any template argument. * * */
f5546ef4d43bb2373fae61dc572d4bdcacfcfe6f
c4b87875cde64eb40a35416686c7add860d9d6b7
/source/json/parseJSON.cpp
118e6729ce9582f612bdc4c30daeb59f8634826c
[]
no_license
felipegb94/simEngine
27428bd13973b8c775083073458fbab7b42aefec
e9d735165586c0964efc64d41c0b24c54564c675
refs/heads/master
2020-04-06T03:41:56.030260
2014-06-12T05:30:14
2014-06-12T05:30:14
13,427,227
1
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
parseJSON.cpp
/* * parseJSON.cpp * * Created on: Sep 23, 2013 * Author: pipe */ //#include "Symbolic/headers/symbolic/symbolicc++.h" #include "../includes/rapidjson/document.h" #include "jsonParser.h" using namespace std; /** * The following function makes use of the rapidjson library to parse a json string that is * read from a file. It returns a Document object, which is defined in the rapidjson library. * Note: A document object is very similar to an associative array. * */ rapidjson::Document parseJSON(string filename){ string line; string json; ifstream myfile (filename.c_str()); //file to read. if (myfile.is_open()){ while (getline (myfile,line) ){ json += line; } myfile.close(); } else cout << "Unable to open file"; rapidjson::Document d; d.Parse<0>(json.c_str()); return d; }
84d17661497aab160e632ec900643f0659275d43
b92d1eb369e57f16f38543273afdfe1acfaddcbc
/ui/paintwidget.h
9057e78122569c799021b34d28c02d693caa3501
[]
no_license
testlaidong/CG2018
04f63edc5a5222658c6cc48b29927136ed307ce5
696d530bc2cca5749612c8303e8d640b12f2492f
refs/heads/master
2022-05-24T19:27:52.962487
2018-12-31T11:28:16
2018-12-31T11:28:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
paintwidget.h
#ifndef PAINTWIDGET_H #define PAINTWIDGET_H #include <GL/gl.h> #include <GL/glu.h> #include <QOpenGLWidget> #include <map> #include <vector> #include "QOpenGLFunctions" #include "common/common.h" #include "drawer/drawer.h" #include "common/box.h" #include "editor/editor.h" using namespace std; class PaintWidget: public QOpenGLWidget, protected QOpenGLFunctions { Q_OBJECT public: PaintWidget(QWidget *parent = nullptr); void resetSelector(); void saveTo(string filename); protected: void initializeGL(); void paintGL(); void resizeGL(int w, int h); void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent * event); private: vector<IShape *>shapes; BoundingBox box; map<Mode, FigureGenerator *>drawers; map<Mode, Editor *>editors; }; #endif // PAINTWIDGET_H
3a806e1c1456f315ae84701af1cdbee825537f86
fb1f00551e6f5f2aa2762124f803dae4acc2e2ba
/controller.h
d0983a2bf438a22b0ff5b0c1d9d3b099b0c1d766
[]
no_license
yakupbeyoglu/ImageSliderQt-QML
a29fdde5e52221e733c59e281a6e19f2c91e6a31
ea5f34c747af8110ce4209d4dcaafebb9d34faac
refs/heads/main
2023-01-05T05:19:22.072954
2020-11-04T00:19:52
2020-11-04T00:19:52
309,837,378
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
controller.h
#ifndef CONTROLLER_H #define CONTROLLER_H #include <QObject> #include <QtDebug> #include "images.h" class Controller: public QObject { Q_OBJECT public: Q_PROPERTY(QString tpath READ getPath NOTIFY pathsended); explicit Controller(QObject *parent = 0); QString getPath(); public slots: // 1 is next 0 is previous void keypress(const int key); signals : void pathsended(); private: Images imagePaths; QString currentPath; }; #endif // CONTROLLER_H
6dc0b6ffc49a6a1e62a20387a12745f222f11542
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h
e22cb9f8f8eb014eeb3915a31c1a8d683d096996
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
5,617
h
nearby_share_contact_manager_impl.h
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_NEARBY_SHARING_CONTACTS_NEARBY_SHARE_CONTACT_MANAGER_IMPL_H_ #define CHROME_BROWSER_NEARBY_SHARING_CONTACTS_NEARBY_SHARE_CONTACT_MANAGER_IMPL_H_ #include <memory> #include <string> #include "base/functional/callback.h" #include "base/memory/raw_ptr.h" #include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager.h" #include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" class NearbyShareClientFactory; class NearbyShareContactDownloader; class NearbyShareLocalDeviceDataManager; class NearbyShareProfileInfoProvider; class PrefService; namespace ash::nearby { class NearbyScheduler; } // namespace ash::nearby // Implementation of NearbyShareContactManager that persists the set of allowed // contact IDs--for selected-contacts visiblity mode--in prefs. All other // contact data is downloaded from People API, via the NearbyShare server, as // needed. // // The Nearby Share server must be explicitly informed of all contacts this // device is aware of--needed for all-contacts visibility mode--as well as what // contacts are allowed for selected-contacts visibility mode. These uploaded // contact lists are used by the server to distribute the device's public // certificates accordingly. This implementation persists a hash of the last // uploaded contact data, and after every contacts download, a subsequent upload // request is made if we detect that the contact list or allowlist has changed // since the last successful upload. We also schedule periodic contact uploads // just in case the server removed the record. // // In addition to supporting on-demand contact downloads, this implementation // periodically checks in with the Nearby Share server to see if the user's // contact list has changed since the last upload. class NearbyShareContactManagerImpl : public NearbyShareContactManager { public: class Factory { public: static std::unique_ptr<NearbyShareContactManager> Create( PrefService* pref_service, NearbyShareClientFactory* http_client_factory, NearbyShareLocalDeviceDataManager* local_device_data_manager, NearbyShareProfileInfoProvider* profile_info_provider); static void SetFactoryForTesting(Factory* test_factory); protected: virtual ~Factory(); virtual std::unique_ptr<NearbyShareContactManager> CreateInstance( PrefService* pref_service, NearbyShareClientFactory* http_client_factory, NearbyShareLocalDeviceDataManager* local_device_data_manager, NearbyShareProfileInfoProvider* profile_info_provider) = 0; private: static Factory* test_factory_; }; ~NearbyShareContactManagerImpl() override; private: NearbyShareContactManagerImpl( PrefService* pref_service, NearbyShareClientFactory* http_client_factory, NearbyShareLocalDeviceDataManager* local_device_data_manager, NearbyShareProfileInfoProvider* profile_info_provider); // NearbyShareContactsManager: void DownloadContacts() override; void SetAllowedContacts( const std::set<std::string>& allowed_contact_ids) override; void OnStart() override; void OnStop() override; void Bind(mojo::PendingReceiver<nearby_share::mojom::ContactManager> receiver) override; // nearby_share::mojom::ContactsManager: void AddDownloadContactsObserver( ::mojo::PendingRemote<nearby_share::mojom::DownloadContactsObserver> observer) override; std::set<std::string> GetAllowedContacts() const; void OnPeriodicContactsUploadRequested(); void OnContactsDownloadRequested(); void OnContactsDownloadSuccess( std::vector<nearbyshare::proto::ContactRecord> contacts, uint32_t num_unreachable_contacts_filtered_out); void OnContactsDownloadFailure(); void OnContactsUploadFinished(bool did_contacts_change_since_last_upload, const std::string& contact_upload_hash, bool success); bool SetAllowlist(const std::set<std::string>& new_allowlist); // Notify the base-class and mojo observers that contacts were downloaded. void NotifyAllObserversContactsDownloaded( const std::set<std::string>& allowed_contact_ids, const std::vector<nearbyshare::proto::ContactRecord>& contacts, uint32_t num_unreachable_contacts_filtered_out); raw_ptr<PrefService, ExperimentalAsh> pref_service_ = nullptr; raw_ptr<NearbyShareClientFactory, ExperimentalAsh> http_client_factory_ = nullptr; raw_ptr<NearbyShareLocalDeviceDataManager, ExperimentalAsh> local_device_data_manager_ = nullptr; raw_ptr<NearbyShareProfileInfoProvider, ExperimentalAsh> profile_info_provider_ = nullptr; std::unique_ptr<ash::nearby::NearbyScheduler> periodic_contact_upload_scheduler_; std::unique_ptr<ash::nearby::NearbyScheduler> contact_download_and_upload_scheduler_; std::unique_ptr<NearbyShareContactDownloader> contact_downloader_; mojo::RemoteSet<nearby_share::mojom::DownloadContactsObserver> observers_set_; mojo::ReceiverSet<nearby_share::mojom::ContactManager> receiver_set_; base::WeakPtrFactory<NearbyShareContactManagerImpl> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_NEARBY_SHARING_CONTACTS_NEARBY_SHARE_CONTACT_MANAGER_IMPL_H_
35c0514e3ecbe0a9e1d3440db62dc9e8527f7e16
d68b8f9313198b751264cb9c7dc3171f47f39552
/rtlab_exp_tk/comedi_device.h
35cfa1eaee6fa9ada849eb9687ade2d662b410ad
[]
no_license
cculianu/calinsrc
e97fc02f1141132b718623d3c94cf1775a877e0d
338d7d083854366f7a4162d53d95a2116fda6f0e
refs/heads/master
2021-01-16T18:39:44.697710
2003-01-29T17:19:23
2003-01-29T17:19:23
32,130,393
0
0
null
null
null
null
UTF-8
C++
false
false
6,111
h
comedi_device.h
/* * This file is part of the RT-Linux Multichannel Data Acquisition System * * Copyright (c) 2001 Calin Culianu * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program (see COPYRIGHT file); if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA, or go to their website at * http://www.gnu.org. */ #ifndef _COMEDI_DEVICE_H #define _COMEDI_DEVICE_H #include <qstring.h> #include <vector> #include <comedi.h> #include <comedilib.h> #include "shared_stuff.h" #include "common.h" namespace ComediChannel { enum AnalogRef { Ground = AREF_GROUND, Common = AREF_COMMON, Differential = AREF_DIFF, Other = AREF_OTHER, Undefined, }; /* helper functions */ int ar2int(AnalogRef r); AnalogRef int2ar(int r); }; namespace ComediRange { class Unit { public: Unit(int i = UNIT_volt); Unit & operator=(int i); bool operator== (const Unit &); operator int() const; operator QString() const; private: int u; }; /* parses 'string' for range settings and puts the results inside rangeMin, rangeMax, and units */ extern bool parseString(const QString &string, double & rangeMin, double & rangeMax, Unit & units); extern QString buildString(double min, double max, Unit); extern const Unit Volts, MilliVolts; }; class ComediSubDevice { friend class ComediDevice; public: enum SubdevType { subdevtype_low = 0, AnalogInput, AnalogOutput, Other, Undefined, subdevtype_high }; ComediSubDevice(int id = -1, bool used_by_rt_process = false, bool can_be_locked = true) : id(id), n_channels(-1), used_by_rt_process(used_by_rt_process), can_be_locked(can_be_locked), type(Undefined), is_null(false) {}; bool isNull() const { return is_null; }; vector<comedi_range> & ranges() { return _ranges; } const vector<comedi_range> & ranges() const {return _ranges;} /* Generates a string for the given range index returns a null QString if range_id is invalid... */ QString generateRangeString(uint range_id) const; lsampl_t maxData() const { return maxdata; } lsampl_t & maxData() { return maxdata; } /*double sampleToUnits(const SampleStruct & sample, uint *unit = 0) const; lsampl_t unitsToSample(SampleStruct & s, double unitdata) const;*/ /* convert a SubdevType to a native comedi int */ static int sd2int(SubdevType t); /* convert a native comedi int back to a SubdevType */ static SubdevType int2sd(int i); /* note that above two methods aren't perfectly symmetric.. namely everything other than COMEDI_SUBD_(AI|AO) get flattened to SubdevType 'Other', which, when converted back, becomes COMEDI_SUBD_UNUSED */ int id, n_channels; bool used_by_rt_process, can_be_locked; SubdevType type; /* from comedi.h */ private: ComediSubDevice(float *dummy) /* dummy constructor for a null dev */ : is_null(true) { dummy++; }; bool is_null; vector<comedi_range> _ranges; lsampl_t maxdata; }; class ComediDevice { public: ComediDevice(const QString & filename = "") : filename(filename) {}; /* returns a null (isNull() == true) ComediSubDevice if not found */ const ComediSubDevice & find(ComediSubDevice::SubdevType type = ComediSubDevice::AnalogInput, int id_start = 0) const; QString filename; QString devicename, drivername; int minor; /* from comedi */ vector<ComediSubDevice> subdevices; bool isNull() const { return subdevices.size() <= 0; }; }; #define _cd_undefinedval (COMEDI_SUBD_UNUSED-1) inline int ComediSubDevice::sd2int(SubdevType t) { register int ret; switch (t) { case AnalogInput: ret = COMEDI_SUBD_AI; break; case AnalogOutput: ret = COMEDI_SUBD_AO; break; case Undefined: ret = _cd_undefinedval; break; default: ret = COMEDI_SUBD_UNUSED; break; } return ret; } inline ComediSubDevice::SubdevType ComediSubDevice::int2sd(int i) { register SubdevType ret; switch (i) { case COMEDI_SUBD_AI: ret = AnalogInput; break; case COMEDI_SUBD_AO: ret = AnalogOutput; break; case _cd_undefinedval: ret = Undefined; break; default: ret = Other; break; } return ret; } #undef _cd_undefinedval #define _ar_undefinedval (static_cast<int>(ComediChannel::Undefined)) inline int ComediChannel::ar2int(AnalogRef r) { switch (r) { case Ground: return AREF_GROUND; case Common: return AREF_COMMON; case Differential: return AREF_DIFF; case Other: return AREF_OTHER; default: return _ar_undefinedval; } return _ar_undefinedval; /* not reached */ } inline ComediChannel::AnalogRef ComediChannel::int2ar(int i) { switch (i) { case AREF_GROUND: return Ground; case AREF_COMMON: return Common; case AREF_DIFF: return Differential; case AREF_OTHER: return Other; default: return Undefined; } return Undefined; /* not reached */ } #undef _ar_undefinedval /* pass optional int * to save the unit type in the param this is no longer needed? inline double ComediSubDevice:: sampleToUnits(const SampleStruct &s, uint *unit = 0) const { if (unit) { *unit = _ranges[s.range].unit; } return (_ranges[s.range].max - _ranges[s.range].min) * s.data/(double)maxdata + _ranges[s.range].min; } */ #endif