blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
4370de3bfcdc63995690dda85b8b4e74b1109305
8840469d03c5451f589c0e26b72193156c4ee56e
/examples/qntzr/qntzr.ino
a7657b285dfbff1c4c37f03719d2bfaef3567cea
[ "BSD-3-Clause" ]
permissive
saluber/du-ino
f175c8d3b6f8e7820cbf8410ef6c475e55187372
36163e917da9ace7a5b4b131b1fd6086cf7a672d
refs/heads/master
2020-03-26T16:26:47.892257
2018-08-16T22:10:54
2018-08-16T22:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,109
ino
/* * #### #### * #### #### * #### #### ## * #### #### #### * #### ############ ############ #### ########## #### #### * #### #### #### #### #### #### #### ######## * #### #### #### #### #### #### #### ######## * #### #### #### #### #### #### #### #### #### * #### #### #### #### #### #### #### #### #### * #### ############ ############ #### ########## #### #### * #### #### * ################################ #### * __ __ __ __ __ #### * | | | | [__) |_/ (__ |__| | | [__) #### * |/\| |__| | \ | \ .__) | | |__| | ## * * * DU-INO Quantizer Function * Aaron Mavrinac <aaron@logick.ca> */ #include <du-ino_function.h> #include <du-ino_widgets.h> #include <du-ino_scales.h> #include <avr/pgmspace.h> static const unsigned char icons[] PROGMEM = { 0x60, 0x78, 0x78, 0x78, 0x78, 0x78, 0x60, // trigger mode off 0x60, 0x63, 0x0f, 0x0f, 0x0f, 0x63, 0x60 // trigger mode on }; volatile bool triggered; void trig_isr(); void trigger_mode_scroll_callback(int delta); void key_scroll_callback(int delta); void scale_scroll_callback(int delta); void notes_click_callback(uint8_t selected); class DU_Quantizer_Function : public DUINO_Function { public: DU_Quantizer_Function() : DUINO_Function(0b00001100) { } virtual void setup() { // build widget hierarchy container_outer_ = new DUINO_WidgetContainer<2>(DUINO_Widget::DoubleClick); container_top_ = new DUINO_WidgetContainer<3>(DUINO_Widget::Click, 2); container_outer_->attach_child(container_top_, 0); widget_trigger_mode_ = new DUINO_DisplayWidget(76, 0, 9, 9, DUINO_Widget::Full); widget_trigger_mode_->attach_scroll_callback(trigger_mode_scroll_callback); container_top_->attach_child(widget_trigger_mode_, 0); widget_key_ = new DUINO_DisplayWidget(90, 0, 13, 9, DUINO_Widget::Full); widget_key_->attach_scroll_callback(key_scroll_callback); container_top_->attach_child(widget_key_, 1); widget_scale_ = new DUINO_DisplayWidget(108, 0, 19, 9, DUINO_Widget::Full); widget_scale_->attach_scroll_callback(scale_scroll_callback); container_top_->attach_child(widget_scale_, 2); container_notes_ = new DUINO_WidgetContainer<12>(DUINO_Widget::Scroll); container_outer_->attach_child(container_notes_, 1); widgets_notes_[0] = new DUINO_DisplayWidget(6, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[1] = new DUINO_DisplayWidget(15, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[2] = new DUINO_DisplayWidget(24, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[3] = new DUINO_DisplayWidget(33, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[4] = new DUINO_DisplayWidget(42, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[5] = new DUINO_DisplayWidget(60, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[6] = new DUINO_DisplayWidget(69, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[7] = new DUINO_DisplayWidget(78, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[8] = new DUINO_DisplayWidget(87, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[9] = new DUINO_DisplayWidget(96, 54, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[10] = new DUINO_DisplayWidget(105, 29, 7, 7, DUINO_Widget::DottedBox); widgets_notes_[11] = new DUINO_DisplayWidget(114, 54, 7, 7, DUINO_Widget::DottedBox); for(uint8_t i = 0; i < 12; ++i) { container_notes_->attach_child(widgets_notes_[i], i); } container_notes_->attach_click_callback_array(notes_click_callback); trigger_mode = false; key = 0; scale_id = 0; scale = get_scale_by_id(scale_id); output_octave = 0; output_note = 0; current_displayed_note = 0; gt_attach_interrupt(GT3, trig_isr, FALLING); // draw top line Display.draw_du_logo_sm(0, 0, DUINO_SH1106::White); Display.draw_text(16, 0, "QNTZR", DUINO_SH1106::White); // draw kays draw_left_key(1, 11); // C draw_black_key(13, 11); // Db draw_center_key(19, 11); // D draw_black_key(31, 11); // Eb draw_right_key(37, 11); // E draw_left_key(55, 11); // F draw_black_key(67, 11); // Gb draw_center_key(73, 11); // G draw_black_key(85, 11); // Ab draw_center_key(91, 11); // A draw_black_key(103, 11); // Bb draw_right_key(109, 11); // B invert_note(current_displayed_note); widget_setup(container_outer_); Display.display_all(); display_trigger_mode(); display_key(); display_scale(); } virtual void loop() { if(!trigger_mode || triggered) { if(scale == 0) { cv_out(CO1, 0.0); output_octave = 0; output_note = 0; } else { // read input float input = cv_read(CI1); // find a lower bound int below_octave = (int)input - 1; uint8_t below_note = 0; while(!(scale & (1 << below_note))) { below_note++; } // find closest lower and upper values int above_octave = below_octave, octave = below_octave; uint8_t above_note = below_note, note = below_note; while(note_cv(above_octave, key, above_note) < input) { note++; if(note > 11) { note = 0; octave++; } if(scale & (1 << note)) { below_octave = above_octave; below_note = above_note; above_octave = octave; above_note = note; } } // output the nearer of the two values float below = note_cv(below_octave, key, below_note); float above = note_cv(above_octave, key, above_note); if(input - below < above - input) { cv_out(CO1, below); octave = below_octave; note = below_note; } else { cv_out(CO1, above); octave = above_octave; note = above_note; } // send trigger and update display note if note has changed if(octave != output_octave || note != output_note) { gt_out(GT1, true, true); output_octave = octave; output_note = note; } } // reset trigger triggered = false; } widget_loop(); // display current note if(output_note != current_displayed_note) { invert_note(current_displayed_note); invert_note(output_note); current_displayed_note = output_note; } } void widget_trigger_mode_scroll_callback(int delta) { trigger_mode = delta > 0; display_trigger_mode(); } void widget_key_scroll_callback(int delta) { key += delta; key %= 12; if(key < 0) { key += 12; } display_key(); triggered = true; } void widget_scale_scroll_callback(int delta) { scale_id += delta; if(scale_id < -1) { scale_id = -1; } else if(scale_id >= N_SCALES) { scale_id = N_SCALES - 1; } scale = get_scale_by_id(scale_id); display_scale(); triggered = true; } void widgets_notes_click_callback(uint8_t selected) { scale ^= (1 << selected); scale_id = get_id_from_scale(scale); display_scale(); triggered = true; } private: float note_cv(int octave, uint8_t key, uint8_t note) { return (float)octave + (float)key / 12.0 + (float)note / 12.0; } void draw_left_key(int16_t x, int16_t y) { Display.draw_vline(x, y, 52, DUINO_SH1106::White); Display.draw_hline(x + 1, y, 9, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 11, y + 28, 5, DUINO_SH1106::White); Display.draw_vline(x + 16, y + 28, 24, DUINO_SH1106::White); } void draw_center_key(int16_t x, int16_t y) { Display.draw_vline(x, y + 28, 24, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 28, 5, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 6, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 7, y, 3, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 11, y + 28, 5, DUINO_SH1106::White); Display.draw_vline(x + 16, y + 28, 24, DUINO_SH1106::White); } void draw_right_key(int16_t x, int16_t y) { Display.draw_vline(x, y + 28, 24, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 28, 5, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 51, 15, DUINO_SH1106::White); Display.draw_vline(x + 6, y, 29, DUINO_SH1106::White); Display.draw_hline(x + 7, y, 9, DUINO_SH1106::White); Display.draw_vline(x + 16, y, 52, DUINO_SH1106::White); } void draw_black_key(int16_t x, int16_t y) { Display.draw_vline(x, y, 27, DUINO_SH1106::White); Display.draw_hline(x + 1, y, 9, DUINO_SH1106::White); Display.draw_hline(x + 1, y + 26, 9, DUINO_SH1106::White); Display.draw_vline(x + 10, y, 27, DUINO_SH1106::White); } void display_trigger_mode() { Display.fill_rect(widget_trigger_mode_->x() + 1, widget_trigger_mode_->y() + 1, 7, 7, widget_trigger_mode_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); Display.draw_bitmap_7(widget_trigger_mode_->x() + 1, widget_trigger_mode_->y() + 1, icons, trigger_mode, widget_trigger_mode_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); widget_trigger_mode_->display(); } void display_key() { Display.fill_rect(widget_key_->x() + 1, widget_key_->y() + 1, 11, 7, widget_key_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); bool sharp = false; unsigned char letter; switch(key) { case 1: // C# sharp = true; case 0: // C letter = 'C'; break; case 3: // D# sharp = true; case 2: // D letter = 'D'; break; case 4: // E letter = 'E'; break; case 6: // F# sharp = true; case 5: // F letter = 'F'; break; case 8: // G# sharp = true; case 7: // G letter = 'G'; break; case 10: // A# sharp = true; case 9: // A letter = 'A'; break; case 11: // B letter = 'B'; break; } Display.draw_char(widget_key_->x() + 1, widget_key_->y() + 1, letter, widget_key_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); if(sharp) { Display.draw_char(widget_key_->x() + 7, widget_key_->y() + 1, '#', widget_key_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); } widget_key_->display(); } void display_scale() { Display.fill_rect(widget_scale_->x() + 1, widget_scale_->y() + 1, 17, 7, widget_scale_->inverted() ? DUINO_SH1106::White : DUINO_SH1106::Black); if(scale_id > -1) { for(uint8_t i = 0; i < 3; ++i) { Display.draw_char(widget_scale_->x() + 1 + i * 6, widget_scale_->y() + 1, pgm_read_byte(&scales[scale_id * 5 + 2 + i]), widget_scale_->inverted() ? DUINO_SH1106::Black : DUINO_SH1106::White); } } for(uint8_t note = 0; note < 12; ++note) { bool white = scale & (1 << note); if(note == current_displayed_note) { white = !white; } Display.fill_rect(widgets_notes_[note]->x() + 1, widgets_notes_[note]->y() + 1, 5, 5, white ? DUINO_SH1106::White : DUINO_SH1106::Black); } Display.display_all(); } void invert_note(uint8_t note) { bool refresh_lower = false; switch(note) { case 0: Display.fill_rect(2, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(11, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 1: Display.fill_rect(14, 12, 9, 25, DUINO_SH1106::Inverse); break; case 2: Display.fill_rect(26, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(20, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 3: Display.fill_rect(32, 12, 9, 25, DUINO_SH1106::Inverse); break; case 4: Display.fill_rect(44, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(38, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 5: Display.fill_rect(56, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(65, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 6: Display.fill_rect(68, 12, 9, 25, DUINO_SH1106::Inverse); break; case 7: Display.fill_rect(80, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(74, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 8: Display.fill_rect(86, 12, 9, 25, DUINO_SH1106::Inverse); break; case 9: Display.fill_rect(98, 12, 3, 28, DUINO_SH1106::Inverse); Display.fill_rect(92, 40, 15, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; case 10: Display.fill_rect(104, 12, 9, 25, DUINO_SH1106::Inverse); break; case 11: Display.fill_rect(116, 12, 9, 50, DUINO_SH1106::Inverse); Display.fill_rect(110, 40, 6, 22, DUINO_SH1106::Inverse); refresh_lower = true; break; } Display.display(2, 124, 1, refresh_lower ? 7 : 4); } DUINO_WidgetContainer<2> * container_outer_; DUINO_WidgetContainer<3> * container_top_; DUINO_WidgetContainer<12> * container_notes_; DUINO_DisplayWidget * widget_trigger_mode_; DUINO_DisplayWidget * widget_key_; DUINO_DisplayWidget * widget_scale_; DUINO_DisplayWidget * widgets_notes_[12]; bool trigger_mode; int8_t key; int scale_id; uint16_t scale; uint8_t output_note; int output_octave; uint8_t current_displayed_note; }; DU_Quantizer_Function * function; void trig_isr() { triggered = true; } void trigger_mode_scroll_callback(int delta) { function->widget_trigger_mode_scroll_callback(delta); } void key_scroll_callback(int delta) { function->widget_key_scroll_callback(delta); } void scale_scroll_callback(int delta) { function->widget_scale_scroll_callback(delta); } void notes_click_callback(uint8_t selected) { function->widgets_notes_click_callback(selected); } void setup() { function = new DU_Quantizer_Function(); triggered = false; function->begin(); } void loop() { function->loop(); }
[ "mavrinac@gmail.com" ]
mavrinac@gmail.com
ce418e0b0839d701f9cdb2b443b48c8223c868c1
08d1ed39609beac9ca2604ece44aa10741330e37
/server/main/utils/MD5Util.hpp
ead16a77c5815c9066838114b7bee4d4f567bf50
[]
no_license
wenyiyi/user
e1a310c47b9e526722c0f469054f20a10d12323e
860a1cda51b1024ad21b6f4271f7d613c849b1c6
refs/heads/master
2022-11-10T22:04:34.923705
2020-07-01T05:17:48
2020-07-01T05:17:48
276,225,400
0
0
null
null
null
null
UTF-8
C++
false
false
210
hpp
// // MD5Util.hpp // user // // Created by Vincent on 2020/6/26. // Copyright © 2020 Vincent. All rights reserved. // #ifndef MD5Util_hpp #define MD5Util_hpp #include <stdio.h> #endif /* MD5Util_hpp */
[ "1217047025@qq.com" ]
1217047025@qq.com
005b56d107a73510760afe9e5140a6be2ba31dee
0a570a49cac8a807d8feceb78663355212b080cb
/Arduino/jarvis/SerialController.hpp
856acc795267d33675151fc3597a9217e64db72b
[ "MIT" ]
permissive
davide-dv/IoTProject
7405c21f2ca611eaf21ea0d691a4e5fdd90795e4
eba3fe2e9bb103f1db971d35a3dd9dc4cd8c5255
refs/heads/master
2021-01-19T00:31:48.384386
2017-05-04T15:10:22
2017-05-04T15:10:22
76,870,978
0
0
null
null
null
null
UTF-8
C++
false
false
538
hpp
#ifndef __SERIALCONTROLLER_HPP__ #define __SERIALCONTROLLER_HPP__ #include "Task.hpp" #include "JarvisHW.hpp" #include "MessageService.hpp" #include <SoftwareSerial.h> #include "PinConfig.hpp" class SerialController : public Task { public: SerialController(JarvisHW* js); ~SerialController(); void init(int period); void tick(); private: int bt[2] = PIN_BT; SoftwareSerial* _bluetooth; MessageService* _btMsg; JarvisHW* _js; long _start; float _temp; enum InternalState {A_WAIT, BT_ADV} _internalState; }; #endif
[ "antoniotagliente@aol.com" ]
antoniotagliente@aol.com
6c57c994f37499bf6b67238436e589da7aed452d
20aab3ff4cdf44f9976686a2f161b3a76038e782
/lua/ProjectST/龍神録/project/22章/mydat/source/char.cpp
be176c7a8125a1666f0da320d2a3b1938c34daab
[ "MIT" ]
permissive
amenoyoya/old-project
6eee1e3e27ea402c267fc505b80f31fa89a2116e
640ec696af5d18267d86629098f41451857f8103
refs/heads/master
2020-06-12T20:06:25.828454
2019-07-12T04:09:30
2019-07-12T04:09:30
194,408,956
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,571
cpp
#include "../include/GV.h" void calc_ch(){ if(ch.cnt==0 && ch.flag==2){//今の瞬間死んだら ch.x=FIELD_MAX_X/2;//座標セット ch.y=FIELD_MAX_Y+30; ch.mutekicnt++;//無敵状態へ } if(ch.flag==2){//死んで浮上中なら unsigned int push=CheckStatePad(configpad.left)+CheckStatePad(configpad.right) +CheckStatePad(configpad.up)+CheckStatePad(configpad.down); ch.y-=1.5;//キャラを上に上げる //1秒以上か、キャラがある程度上にいて、何かおされたら if(ch.cnt>60 || (ch.y<FIELD_MAX_Y-20 && push)){ ch.cnt=0; ch.flag=0;//キャラステータスを元に戻す } } if(ch.mutekicnt>0){//無敵カウントが0じゃなければ ch.mutekicnt++; if(ch.mutekicnt>150)//150以上たったら ch.mutekicnt=0;//戻す } ch.cnt++;//キャラクタカウントアップ ch.img=(ch.cnt%24)/6;//現在の画像決定 } void ch_move(){ int i,sayu_flag=0,joge_flag=0; double x,y,mx,my,naname=1; double move_x[4]={-4.0,4.0,0,0},move_y[4]={0,0,4.0,-4.0}; int inputpad[4]; inputpad[0]=CheckStatePad(configpad.left); inputpad[1]=CheckStatePad(configpad.right); inputpad[2]=CheckStatePad(configpad.down); inputpad[3]=CheckStatePad(configpad.up); if(CheckStatePad(configpad.left)>0)//左キーが押されていたら ch.img+=4*2;//画像を左向きに else if(CheckStatePad(configpad.right)>0)//右キーが押されていたら ch.img+=4*1;//画像を右向きに for(i=0;i<2;i++)//左右分 if(inputpad[i]>0)//左右どちらかの入力があれば sayu_flag=1;//左右入力フラグを立てる for(i=2;i<4;i++)//上下分 if(inputpad[i]>0)//上下どちらかの入力があれば joge_flag=1;//上下入力フラグを立てる if(sayu_flag==1 && joge_flag==1)//左右、上下両方の入力があれば斜めだと言う事 naname=sqrt(2.0);//移動スピードを1/ルート2に for(int i=0;i<4;i++){//4方向分ループ if(inputpad[i]>0){//i方向のキーボード、パッドどちらかの入力があれば x=ch.x , y=ch.y;//今の座標をとりあえずx,yに格納 mx=move_x[i]; my=move_y[i];//移動分をmx,myに代入 if(CheckStatePad(configpad.slow)>0){//低速移動なら mx=move_x[i]/3; my=move_y[i]/3;//移動スピードを1/3に } x+=mx/naname , y+=my/naname;//今の座標と移動分を足す if(!(x<10 || x>FIELD_MAX_X || y<5 || y>FIELD_MAX_Y-5)){//計算結果移動可能範囲内なら ch.x=x , ch.y=y;//実際に移動させる } } } }
[ "mtyswe3@gmail.com" ]
mtyswe3@gmail.com
b58111b00f0b94eab61982eba3290cadad01b3d9
b85aad75aa5984fb6f276feaad21d9e07040b380
/source/main.cpp
09cd58ebda1efe2671ef6a370d379bbaadbb7ed8
[]
no_license
jason0597/Seedminer-CPP
9e4397d85f47735185f7c6d667adbbe71bab0588
728e02d7e6620ef4132fb4a261ec079f848a4b66
refs/heads/master
2020-03-07T06:47:49.294984
2018-04-04T23:28:18
2018-04-04T23:28:18
127,331,793
1
0
null
null
null
null
UTF-8
C++
false
false
3,081
cpp
#include <iostream> #include <string> #include "common.hpp" #include "data_nodes.hpp" #include "file_handling.hpp" #include "launcher.hpp" int32_t getMsed3Error(uint32_t num, std::vector<std::vector<int32_t>> nodes) { std::vector<int32_t> LFCSes = nodes[0]; std::vector<int32_t> msed3s = nodes[1]; int distance = std::abs((int)(LFCSes[0] - num)); int idx = 0; for (int i = 0; i < LFCSes.size(); i++) { int cdistance = std::abs((int)(LFCSes[i] - num)); if (cdistance < distance) { idx = i; distance = cdistance; } } return msed3s[idx]; } bool stringIsHex(std::string str) { return (str.find_first_not_of("0123456789abcdefABCDEF") == std::string::npos); } int main (int argc, char **argv) { if (argc == 1) { try { movable_part1 mp1; file_handling::readMP1(&mp1); std::vector<std::vector<int32_t>> nodes = data_nodes::readNodes(mp1.isNew3DS); uint32_t lfcs_num = mp1.LFCS[0] | (mp1.LFCS[1] << 8) | (mp1.LFCS[2] << 16) | (mp1.LFCS[3] << 24); std::cout << "lfcs_num: " << std::hex << lfcs_num << std::endl; if (lfcs_num == 0) { throw std::invalid_argument("The LFCS has been left blank!"); } int32_t msed3error = getMsed3Error(lfcs_num >> 12, nodes); std::cout << "msed3error: " << std::dec << msed3error << std::endl; mp1.msed3estimate = ((lfcs_num / 5) + (-1) * msed3error); std::cout << "msed3estimate: " << std::hex << mp1.msed3estimate << std::endl; launcher::doMining(mp1); } catch (std::exception e) { std::cout << "An exception occurred!" << std::endl; std::cout << e.what() << std::endl; system("pause"); return -1; } } else if (argc > 1 && (strcmp(argv[1], "id0") == 0)) { try { if (argc < 3) throw std::invalid_argument("id0 argument specified, but no id0 was provided!"); if (strlen(argv[2]) != 32) throw std::invalid_argument("The provided id0 is not 32 characters!"); if (!stringIsHex(std::string(argv[2]))) throw std::invalid_argument("The provided id0 is not a valid hexadecimal string!"); std::vector<uint8_t> id0(32); memcpy(&id0[0], argv[2], 32); file_handling::writeBytes("movable_part1.sed", 16, id0); std::cout << "Inserted the id0 in the movable_part1.sed" << std::endl; } catch (std::exception e) { std::cout << "An exception occurred!" << std::endl; std::cout << e.what() << std::endl; system("pause"); return -1; } } else { std::cout << "Incorrect usage!" << std::endl; std::cout << "Correct usage:" << std::endl << " - Seedminer" << std::endl << " - Seedminer id0 abcdef012345EXAMPLEdef0123456789" << std::endl; system("pause"); } system("pause"); return 0; }
[ "jason099080@hotmail.com" ]
jason099080@hotmail.com
17fd91a123850b2707faf2bcf468493856e81bed
034de645cc99598e357862fe8f379173edca7021
/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBuffer.h
135d3c2b38744fb65bc31cdb4b6ce2e57cfb9abb
[ "MIT" ]
permissive
leggedrobotics/ogre
1c0efe89a6fe55fe2e505ce55abdcf18603153a1
fe47104b65ffbbf3f4166cc2b11a93109c799537
refs/heads/raisimOgre
2021-07-08T18:46:32.251172
2020-10-05T13:21:09
2020-10-05T13:21:09
195,427,004
2
9
MIT
2020-10-05T13:21:10
2019-07-05T14:56:13
C++
UTF-8
C++
false
false
2,506
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #ifndef __GL3PlusHARDWAREBUFFER_H__ #define __GL3PlusHARDWAREBUFFER_H__ #include "OgreGL3PlusPrerequisites.h" #include "OgreHardwareBuffer.h" namespace Ogre { class GL3PlusHardwareBuffer { private: GLenum mTarget; size_t mSizeInBytes; uint32 mUsage; GLuint mBufferId; GL3PlusRenderSystem* mRenderSystem; /// Utility function to get the correct GL usage based on HBU's static GLenum getGLUsage(uint32 usage); public: void* lockImpl(size_t offset, size_t length, HardwareBuffer::LockOptions options); void unlockImpl(); GL3PlusHardwareBuffer(GLenum target, size_t sizeInBytes, uint32 usage); ~GL3PlusHardwareBuffer(); void readData(size_t offset, size_t length, void* pDest); void writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer); void copyData(GLuint srcBufferId, size_t srcOffset, size_t dstOffset, size_t length, bool discardWholeBuffer); GLuint getGLBufferId(void) const { return mBufferId; } }; } #endif // __GL3PlusHARDWAREBUFFER_H__
[ "rojtberg@gmail.com" ]
rojtberg@gmail.com
06763a0115d93a36ce9babca4e2112d6e44ff34b
1b0dffdec77c9d28ee304f93a39c63fe85fe0fe3
/BlockClockProject/BC_test/BC_test.ino
bc8bb327b489cfd649603fb0eaae901abb453934
[]
no_license
srosy/BlockClock
6bdda34881c4a52ac4b28717f5ac91d2b97e855e
1e570e4d0bb64b0d8c0563c1a5c5b57fa5daf7c1
refs/heads/master
2020-03-30T11:34:26.259081
2018-10-02T00:47:58
2018-10-02T00:47:58
151,180,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,881
ino
/* BLock Clock Test Program March 31, 2018 */ int potpin = 0; // analog pin used to connect the potentiometer int val; // variable to read the value from the analog pin #include "BC.h" int Xdelay = 500; int Ydelay = 500; bool X = true; // bool FWD = true; #include <SPI.h> #include <SparkFunDS3234RTC.h> //#include <Servo.h> //Servo myservo; // create servo object to control a servo void setup() { Serial.begin(9600); Serial << "Block Clock Tester\n"; Serial.setTimeout(1000000L); pinMode(nCOIL_SS, OUTPUT); digitalWrite(nCOIL_SS, HIGH); rtc.begin(nCLK_SS); rtc.update(); printTime(); // pinMode(CLAW_MTR, OUTPUT); // digitalWrite(CLAW_MTR, LOW); // pinMode(CLAW_UP, INPUT_PULLUP); // pinMode(CLAW_DOWN, INPUT_PULLUP); // myservo.attach(6); printHelp(); } void loop() { char c = Serial.read(); switch (c) { case 'D' : set_time(); break; case 'H' : set_HMS(); break; case 'T' : rtc.update(); printTime(); break; case 'F' : FWD = true; break; case 'R' : FWD = false; break; case 'u' : SLCC_hand_up(); break; case 'd' : SLCC_hand_down(); break; case 'B' : SLCC_hand_grasp(); break; case 'b' : SLCC_hand_release(); break; case 'X' : X = true; break; case 'Y' : X = false; break; case 'S' : stepto(); break; case 'G' : goto_step(); break; default: if (c != -1) printHelp(); } } void printHelp() { Serial << "Enter one of the following:\n" << " D - to set the time\n" << " H - to set HMS\n" << " T - view time\n" << " F - step direction forward\n" << " R - step direction reverse\n" << " u - hand up\n" << " d - hand down\n" << " B - grasp block\n" << " b - release block\n" << " X - step axis X\n" << " Y - step axis Y\n"; }
[ "noreply@github.com" ]
srosy.noreply@github.com
1cbc670dece0f67dbe4908d846cb54bac703d13c
a14bce89ac64eb13ddb80c670624fbc6b0768d8b
/Kaltag/citypath.cpp
24015bb1f952975768ffb2f6d34d783d09d5a199
[]
no_license
tylercchase/cs202
e15ac38d1cdc096d9ba11954af3e42f8402d1d15
ce6d3fe71d52114b3bc4728d009646d933f0a2da
refs/heads/master
2020-12-11T17:48:21.305867
2020-05-01T01:43:03
2020-05-01T01:43:03
233,916,293
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
#include "cityPath.hpp" #include <math.h> void CityPath::addCity(CityNode &city){ connections.push_back(city); } int CityPath::totalDistance(){ int total = 0; for(int i = 0; i < connections.size() - 1; i++){ total += sqrt(pow((connections[i+1].getLatitude() - connections[i].getLatitude() ),2) + pow(connections[i+1].getLongitude() - connections[i].getLongitude() ,2)); } return total; }
[ "tylercchase@gmail.com" ]
tylercchase@gmail.com
d7f035e71582d668881cb61dc4cf243cb15a37f3
75d5e91750db9da92b76b1cf133f1321e5408555
/GRA/Draw.h
2e72dd2a82518cf4c0f65772237da9e62f92f9dd
[]
no_license
piotr4321/grafika
33337eeebe74602caf57bbe3af26116d4d95734d
7cddda25552bec1efa6c4c2061f7c49cd8f2035e
refs/heads/master
2021-01-10T05:34:34.080673
2016-01-22T17:50:25
2016-01-22T17:50:25
50,146,695
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
#pragma once #include <cstdlib> #include "quickcg.h" //klasa reprezentujaca operacje rysowania class Draw { public: //funkcja inicjalizująca okno gry static void initScreen(int width, int height, bool fullscreen, const std::string& text); //funkcja rysująca nową klatkę static void updateScreen(); //funkcja czyszcząca ekran static void clearScreenToBlack(); //funkcja rysująca ściane static void drawVerticalLine(int x, int y1, int y2, const QuickCG::ColorRGB& color); //wybór kolory ściany static QuickCG::ColorRGB setWallColor(int n); };
[ "wefwfwae@gmail.com" ]
wefwfwae@gmail.com
f50c7aecf63e55745f352c46306b0a19098e4874
fe91ffa11707887e4cdddde8f386a8c8e724aa58
/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc
945fdcb6ee22706a15da7a82f4ddc77f5ee525c8
[ "BSD-3-Clause" ]
permissive
akshaymarch7/chromium
78baac2b45526031846ccbaeca96c639d1d60ace
d273c844a313b1e527dec0d59ce70c95fd2bd458
refs/heads/master
2023-02-26T23:48:03.686055
2020-04-15T01:20:07
2020-04-15T01:20:07
255,778,651
2
1
BSD-3-Clause
2020-04-15T02:04:56
2020-04-15T02:04:55
null
UTF-8
C++
false
false
22,393
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include <limits> #include <set> #include "base/bind_helpers.h" #include "base/debug/leak_annotations.h" #include "base/hash/hash.h" #include "base/memory/ptr_util.h" #include "base/no_destructor.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "base/profiler/sampling_profiler_thread_token.h" #include "base/profiler/stack_sampling_profiler.h" #include "base/strings/strcat.h" #include "base/task/thread_pool/thread_pool_instance.h" #include "base/threading/sequence_local_storage_slot.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" #include "services/tracing/public/cpp/perfetto/producer_client.h" #include "third_party/perfetto/protos/perfetto/trace/interned_data/interned_data.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/profiling/profile_common.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/profiling/profile_packet.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/track_event/process_descriptor.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/track_event/thread_descriptor.pbzero.h" #if defined(OS_ANDROID) #include "base/android/reached_code_profiler.h" #endif #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) #include <dlfcn.h> #include "base/trace_event/cfi_backtrace_android.h" #include "services/tracing/public/cpp/stack_sampling/stack_sampler_android.h" #endif using StreamingProfilePacketHandle = protozero::MessageHandle<perfetto::protos::pbzero::StreamingProfilePacket>; namespace tracing { namespace { class TracingSamplerProfilerDataSource : public PerfettoTracedProcess::DataSourceBase { public: static TracingSamplerProfilerDataSource* Get() { static base::NoDestructor<TracingSamplerProfilerDataSource> instance; return instance.get(); } TracingSamplerProfilerDataSource() : DataSourceBase(mojom::kSamplerProfilerSourceName) {} ~TracingSamplerProfilerDataSource() override { NOTREACHED(); } void RegisterProfiler(TracingSamplerProfiler* profiler) { base::AutoLock lock(lock_); if (!profilers_.insert(profiler).second) { return; } if (is_started_) { profiler->StartTracing( producer_->CreateTraceWriter(data_source_config_.target_buffer()), data_source_config_.chrome_config().privacy_filtering_enabled()); } else if (is_startup_tracing_) { profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } } void UnregisterProfiler(TracingSamplerProfiler* profiler) { base::AutoLock lock(lock_); if (!profilers_.erase(profiler) || !(is_started_ || is_startup_tracing_)) { return; } profiler->StopTracing(); } // PerfettoTracedProcess::DataSourceBase implementation, called by // ProducerClient. void StartTracing( PerfettoProducer* producer, const perfetto::DataSourceConfig& data_source_config) override { base::AutoLock lock(lock_); DCHECK(!is_started_); is_started_ = true; is_startup_tracing_ = false; data_source_config_ = data_source_config; bool should_enable_filtering = data_source_config.chrome_config().privacy_filtering_enabled(); for (auto* profiler : profilers_) { profiler->StartTracing( producer->CreateTraceWriter(data_source_config.target_buffer()), should_enable_filtering); } } void StopTracing(base::OnceClosure stop_complete_callback) override { base::AutoLock lock(lock_); DCHECK(is_started_); is_started_ = false; is_startup_tracing_ = false; producer_ = nullptr; for (auto* profiler : profilers_) { profiler->StopTracing(); } std::move(stop_complete_callback).Run(); } void Flush(base::RepeatingClosure flush_complete_callback) override { flush_complete_callback.Run(); } void SetupStartupTracing(PerfettoProducer* producer, const base::trace_event::TraceConfig& trace_config, bool privacy_filtering_enabled) override { bool enable_sampler_profiler = trace_config.IsCategoryGroupEnabled( TRACE_DISABLED_BY_DEFAULT("cpu_profiler")); if (!enable_sampler_profiler) return; base::AutoLock lock(lock_); if (is_started_) { return; } is_startup_tracing_ = true; for (auto* profiler : profilers_) { // Enable filtering for startup tracing always to be safe. profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } } void AbortStartupTracing() override { base::AutoLock lock(lock_); if (!is_startup_tracing_) { return; } for (auto* profiler : profilers_) { // Enable filtering for startup tracing always to be safe. profiler->StartTracing(nullptr, /*should_enable_filtering=*/true); } is_startup_tracing_ = false; } void ClearIncrementalState() override { incremental_state_reset_id_.fetch_add(1u, std::memory_order_relaxed); } static uint32_t GetIncrementalStateResetID() { return incremental_state_reset_id_.load(std::memory_order_relaxed); } private: base::Lock lock_; // Protects subsequent members. std::set<TracingSamplerProfiler*> profilers_; bool is_startup_tracing_ = false; bool is_started_ = false; perfetto::DataSourceConfig data_source_config_; static std::atomic<uint32_t> incremental_state_reset_id_; }; // static std::atomic<uint32_t> TracingSamplerProfilerDataSource::incremental_state_reset_id_{0}; base::SequenceLocalStorageSlot<TracingSamplerProfiler>& GetSequenceLocalStorageProfilerSlot() { static base::NoDestructor< base::SequenceLocalStorageSlot<TracingSamplerProfiler>> storage; return *storage; } } // namespace TracingSamplerProfiler::TracingProfileBuilder::BufferedSample::BufferedSample( base::TimeTicks ts, std::vector<base::Frame>&& s) : timestamp(ts), sample(std::move(s)) {} TracingSamplerProfiler::TracingProfileBuilder::BufferedSample:: ~BufferedSample() = default; TracingSamplerProfiler::TracingProfileBuilder::BufferedSample::BufferedSample( TracingSamplerProfiler::TracingProfileBuilder::BufferedSample&& other) : BufferedSample(other.timestamp, std::move(other.sample)) {} TracingSamplerProfiler::TracingProfileBuilder::TracingProfileBuilder( base::PlatformThreadId sampled_thread_id, std::unique_ptr<perfetto::TraceWriter> trace_writer, bool should_enable_filtering, const base::RepeatingClosure& sample_callback_for_testing) : sampled_thread_id_(sampled_thread_id), trace_writer_(std::move(trace_writer)), should_enable_filtering_(should_enable_filtering), sample_callback_for_testing_(sample_callback_for_testing) {} TracingSamplerProfiler::TracingProfileBuilder::~TracingProfileBuilder() { // Deleting a TraceWriter can end up triggering a Mojo call which calls // TaskRunnerHandle::Get() and isn't safe on thread shutdown, which is when // TracingProfileBuilder gets destructed, so we make sure this happens on // a different sequence. if (base::ThreadPoolInstance::Get()) { PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner()->DeleteSoon( FROM_HERE, std::move(trace_writer_)); } else { // Intentionally leak; we have no way of safely destroying this at this // point. ANNOTATE_LEAKING_OBJECT_PTR(trace_writer_.get()); trace_writer_.release(); } } base::ModuleCache* TracingSamplerProfiler::TracingProfileBuilder::GetModuleCache() { return &module_cache_; } void TracingSamplerProfiler::TracingProfileBuilder::OnSampleCompleted( std::vector<base::Frame> frames, base::TimeTicks sample_timestamp) { base::AutoLock l(trace_writer_lock_); if (!trace_writer_) { if (buffered_samples_.size() < kMaxBufferedSamples) { buffered_samples_.emplace_back( BufferedSample(sample_timestamp, std::move(frames))); } return; } if (!buffered_samples_.empty()) { for (const auto& sample : buffered_samples_) { WriteSampleToTrace(sample); } buffered_samples_.clear(); } WriteSampleToTrace(BufferedSample(sample_timestamp, std::move(frames))); if (sample_callback_for_testing_) { sample_callback_for_testing_.Run(); } } void TracingSamplerProfiler::TracingProfileBuilder::WriteSampleToTrace( const TracingSamplerProfiler::TracingProfileBuilder::BufferedSample& sample) { const auto& frames = sample.sample; auto reset_id = TracingSamplerProfilerDataSource::GetIncrementalStateResetID(); if (reset_id != last_incremental_state_reset_id_) { reset_incremental_state_ = true; last_incremental_state_reset_id_ = reset_id; } if (reset_incremental_state_) { interned_callstacks_.ResetEmittedState(); interned_frames_.ResetEmittedState(); interned_frame_names_.ResetEmittedState(); interned_module_names_.ResetEmittedState(); interned_module_ids_.ResetEmittedState(); interned_modules_.ResetEmittedState(); auto trace_packet = trace_writer_->NewTracePacket(); trace_packet->set_sequence_flags( perfetto::protos::pbzero::TracePacket::SEQ_INCREMENTAL_STATE_CLEARED); // Note: Make sure ThreadDescriptors we emit here won't cause // metadata events to be emitted from the JSON exporter which conflict // with the metadata events emitted by the regular TrackEventDataSource. auto* thread_descriptor = trace_packet->set_thread_descriptor(); thread_descriptor->set_pid(base::GetCurrentProcId()); thread_descriptor->set_tid(sampled_thread_id_); last_timestamp_ = sample.timestamp; thread_descriptor->set_reference_timestamp_us( last_timestamp_.since_origin().InMicroseconds()); reset_incremental_state_ = false; } int32_t current_process_priority = base::Process::Current().GetPriority(); if (current_process_priority != last_emitted_process_priority_) { last_emitted_process_priority_ = current_process_priority; auto trace_packet = trace_writer_->NewTracePacket(); auto* process_descriptor = trace_packet->set_process_descriptor(); process_descriptor->set_pid(base::GetCurrentProcId()); process_descriptor->set_process_priority(current_process_priority); } auto trace_packet = trace_writer_->NewTracePacket(); // Delta encoded timestamps and interned data require incremental state. trace_packet->set_sequence_flags( perfetto::protos::pbzero::TracePacket::SEQ_NEEDS_INCREMENTAL_STATE); auto callstack_id = GetCallstackIDAndMaybeEmit(frames, &trace_packet); auto* streaming_profile_packet = trace_packet->set_streaming_profile_packet(); streaming_profile_packet->add_callstack_iid(callstack_id); streaming_profile_packet->add_timestamp_delta_us( (sample.timestamp - last_timestamp_).InMicroseconds()); last_timestamp_ = sample.timestamp; } void TracingSamplerProfiler::TracingProfileBuilder::SetTraceWriter( std::unique_ptr<perfetto::TraceWriter> writer) { base::AutoLock l(trace_writer_lock_); trace_writer_ = std::move(writer); } InterningID TracingSamplerProfiler::TracingProfileBuilder::GetCallstackIDAndMaybeEmit( const std::vector<base::Frame>& frames, perfetto::TraceWriter::TracePacketHandle* trace_packet) { size_t ip_hash = 0; for (const auto& frame : frames) { ip_hash = base::HashInts(ip_hash, frame.instruction_pointer); } InterningIndexEntry interned_callstack = interned_callstacks_.LookupOrAdd(ip_hash); if (interned_callstack.was_emitted) return interned_callstack.id; auto* interned_data = (*trace_packet)->set_interned_data(); std::vector<InterningID> frame_ids; for (const auto& frame : frames) { std::string frame_name; std::string module_name; std::string module_id; uintptr_t rel_pc = 0; #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) Dl_info info = {}; // For chrome address we do not have symbols on the binary. So, just write // the offset address. For addresses on framework libraries, symbolize // and write the function name. if (frame.instruction_pointer == 0) { frame_name = "Scanned"; } else if (base::trace_event::CFIBacktraceAndroid::is_chrome_address( frame.instruction_pointer)) { rel_pc = frame.instruction_pointer - base::trace_event::CFIBacktraceAndroid::executable_start_addr(); } else if (dladdr(reinterpret_cast<void*>(frame.instruction_pointer), &info) != 0) { // TODO(ssid): Add offset and module debug id if symbol was not resolved // in case this might be useful to send report to vendors. if (info.dli_sname) frame_name = info.dli_sname; if (info.dli_fname) module_name = info.dli_fname; } if (frame.module) { module_id = frame.module->GetId(); if (module_name.empty()) module_name = frame.module->GetDebugBasename().MaybeAsASCII(); } // If no module is available, then name it unknown. Adding PC would be // useless anyway. if (module_name.empty()) { DCHECK(!base::trace_event::CFIBacktraceAndroid::is_chrome_address( frame.instruction_pointer)); frame_name = "Unknown"; rel_pc = 0; } #else if (frame.module) { module_name = frame.module->GetDebugBasename().MaybeAsASCII(); module_id = frame.module->GetId(); rel_pc = frame.instruction_pointer - frame.module->GetBaseAddress(); } else { module_name = module_id = ""; frame_name = "Unknown"; } #endif MangleModuleIDIfNeeded(&module_id); // We never emit frame names in privacy filtered mode. bool should_emit_frame_names = !frame_name.empty() && !should_enable_filtering_; if (should_enable_filtering_ && !rel_pc && frame.module) { rel_pc = frame.instruction_pointer - frame.module->GetBaseAddress(); } InterningIndexEntry interned_frame; if (should_emit_frame_names) { interned_frame = interned_frames_.LookupOrAdd(std::make_pair(frame_name, module_id)); } else { interned_frame = interned_frames_.LookupOrAdd(std::make_pair(rel_pc, module_id)); } if (!interned_frame.was_emitted) { InterningIndexEntry interned_frame_name; if (should_emit_frame_names) { interned_frame_name = interned_frame_names_.LookupOrAdd(frame_name); if (!interned_frame_name.was_emitted) { auto* frame_name_entry = interned_data->add_function_names(); frame_name_entry->set_iid(interned_frame_name.id); frame_name_entry->set_str( reinterpret_cast<const uint8_t*>(frame_name.data()), frame_name.length()); } } InterningIndexEntry interned_module; if (frame.module) { interned_module = interned_modules_.LookupOrAdd(frame.module->GetBaseAddress()); if (!interned_module.was_emitted) { InterningIndexEntry interned_module_id = interned_module_ids_.LookupOrAdd(module_id); if (!interned_module_id.was_emitted) { auto* module_id_entry = interned_data->add_build_ids(); module_id_entry->set_iid(interned_module_id.id); module_id_entry->set_str( reinterpret_cast<const uint8_t*>(module_id.data()), module_id.length()); } InterningIndexEntry interned_module_name = interned_module_names_.LookupOrAdd(module_name); if (!interned_module_name.was_emitted) { auto* module_name_entry = interned_data->add_mapping_paths(); module_name_entry->set_iid(interned_module_name.id); module_name_entry->set_str( reinterpret_cast<const uint8_t*>(module_name.data()), module_name.length()); } auto* module_entry = interned_data->add_mappings(); module_entry->set_iid(interned_module.id); module_entry->set_build_id(interned_module_id.id); module_entry->add_path_string_ids(interned_module_name.id); } } auto* frame_entry = interned_data->add_frames(); frame_entry->set_iid(interned_frame.id); if (should_emit_frame_names) { frame_entry->set_function_name_id(interned_frame_name.id); } else { frame_entry->set_rel_pc(rel_pc); } if (frame.module) { frame_entry->set_mapping_id(interned_module.id); } } frame_ids.push_back(interned_frame.id); } auto* callstack_entry = interned_data->add_callstacks(); callstack_entry->set_iid(interned_callstack.id); for (auto& frame_id : frame_ids) callstack_entry->add_frame_ids(frame_id); return interned_callstack.id; } // static void TracingSamplerProfiler::MangleModuleIDIfNeeded(std::string* module_id) { #if defined(OS_ANDROID) || defined(OS_LINUX) // Linux ELF module IDs are 160bit integers, which we need to mangle // down to 128bit integers to match the id that Breakpad outputs. // Example on version '66.0.3359.170' x64: // Build-ID: "7f0715c2 86f8 b16c 10e4ad349cda3b9b 56c7a773 // Debug-ID "C215077F F886 6CB1 10E4AD349CDA3B9B 0" if (module_id->size() >= 32) { *module_id = base::StrCat({module_id->substr(6, 2), module_id->substr(4, 2), module_id->substr(2, 2), module_id->substr(0, 2), module_id->substr(10, 2), module_id->substr(8, 2), module_id->substr(14, 2), module_id->substr(12, 2), module_id->substr(16, 16), "0"}); } #endif } // static std::unique_ptr<TracingSamplerProfiler> TracingSamplerProfiler::CreateOnMainThread() { return std::make_unique<TracingSamplerProfiler>( base::GetSamplingProfilerCurrentThreadToken()); } // static void TracingSamplerProfiler::CreateOnChildThread() { base::SequenceLocalStorageSlot<TracingSamplerProfiler>& slot = GetSequenceLocalStorageProfilerSlot(); if (slot) return; slot.emplace(base::GetSamplingProfilerCurrentThreadToken()); } // static void TracingSamplerProfiler::DeleteOnChildThreadForTesting() { GetSequenceLocalStorageProfilerSlot().reset(); } // static void TracingSamplerProfiler::RegisterDataSource() { PerfettoTracedProcess::Get()->AddDataSource( TracingSamplerProfilerDataSource::Get()); } // static void TracingSamplerProfiler::StartTracingForTesting( PerfettoProducer* producer) { TracingSamplerProfilerDataSource::Get()->StartTracingWithID( 1, producer, perfetto::DataSourceConfig()); } // static void TracingSamplerProfiler::SetupStartupTracingForTesting() { base::trace_event::TraceConfig config( TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), base::trace_event::TraceRecordMode::RECORD_UNTIL_FULL); TracingSamplerProfilerDataSource::Get()->SetupStartupTracing( /*producer=*/nullptr, config, /*privacy_filtering_enabled=*/false); } // static void TracingSamplerProfiler::StopTracingForTesting() { TracingSamplerProfilerDataSource::Get()->StopTracing(base::DoNothing()); } TracingSamplerProfiler::TracingSamplerProfiler( base::SamplingProfilerThreadToken sampled_thread_token) : sampled_thread_token_(sampled_thread_token) { DCHECK_NE(sampled_thread_token_.id, base::kInvalidThreadId); TracingSamplerProfilerDataSource::Get()->RegisterProfiler(this); } TracingSamplerProfiler::~TracingSamplerProfiler() { TracingSamplerProfilerDataSource::Get()->UnregisterProfiler(this); } void TracingSamplerProfiler::SetSampleCallbackForTesting( const base::RepeatingClosure& sample_callback_for_testing) { base::AutoLock lock(lock_); sample_callback_for_testing_ = sample_callback_for_testing; } void TracingSamplerProfiler::StartTracing( std::unique_ptr<perfetto::TraceWriter> trace_writer, bool should_enable_filtering) { base::AutoLock lock(lock_); if (profiler_) { if (trace_writer) { profile_builder_->SetTraceWriter(std::move(trace_writer)); } return; } #if defined(OS_ANDROID) // The sampler profiler would conflict with the reached code profiler if they // run at the same time because they use the same signal to suspend threads. if (base::android::IsReachedCodeProfilerEnabled()) return; #endif base::StackSamplingProfiler::SamplingParams params; params.samples_per_profile = std::numeric_limits<int>::max(); params.sampling_interval = base::TimeDelta::FromMilliseconds(50); // If the sampled thread is stopped for too long for sampling then it is ok to // get next sample at a later point of time. We do not want very accurate // metrics when looking at traces. params.keep_consistent_sampling_interval = false; auto profile_builder = std::make_unique<TracingProfileBuilder>( sampled_thread_token_.id, std::move(trace_writer), should_enable_filtering, sample_callback_for_testing_); profile_builder_ = profile_builder.get(); // Create and start the stack sampling profiler. #if defined(OS_ANDROID) #if BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && defined(OFFICIAL_BUILD) auto* module_cache = profile_builder->GetModuleCache(); profiler_ = std::make_unique<base::StackSamplingProfiler>( params, std::move(profile_builder), std::make_unique<StackSamplerAndroid>(sampled_thread_token_, module_cache)); profiler_->Start(); #endif // BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && defined(OFFICIAL_BUILD) #else // defined(OS_ANDROID) profiler_ = std::make_unique<base::StackSamplingProfiler>( sampled_thread_token_, params, std::move(profile_builder)); profiler_->Start(); #endif // defined(OS_ANDROID) } void TracingSamplerProfiler::StopTracing() { base::AutoLock lock(lock_); if (!profiler_) { return; } // Stop and release the stack sampling profiler. profiler_->Stop(); profile_builder_ = nullptr; profiler_.reset(); } } // namespace tracing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
24fd8e4ae252079b83a771d1fdf742b566e2fb66
c6881dbb2cb0aea8ac39c809aa5d339c9e15ac09
/Blockchain/txdb.cpp
7beceb3bd01ebb780c277a8af9aa5a2d2c3b2ce9
[]
no_license
HungMingWu/blockchain-demo
d62afbe6caf41f07b7896f312fd9a2a7e27280c7
ebe6e079606fe2fe7bf03783d66300df7a94d5be
refs/heads/master
2020-03-21T22:33:38.664567
2018-10-01T10:12:40
2018-10-01T10:12:40
139,134,108
0
0
null
null
null
null
UTF-8
C++
false
false
12,523
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "chain.h" #include "chainparams.h" #include "hash.h" #include "main.h" #include "pow.h" #include "uint256.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; static const char DB_COINS = 'c'; static const char DB_BLOCK_FILES = 'f'; static const char DB_TXINDEX = 't'; static const char DB_ADDRESSINDEX = 'a'; static const char DB_ADDRESSUNSPENTINDEX = 'u'; static const char DB_TIMESTAMPINDEX = 's'; static const char DB_SPENTINDEX = 'p'; static const char DB_BLOCK_INDEX = 'b'; static const char DB_BEST_BLOCK = 'B'; static const char DB_FLAG = 'F'; static const char DB_REINDEX_FLAG = 'R'; static const char DB_LAST_BLOCK = 'l'; CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) { } bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const { return db.Read(make_pair(DB_COINS, txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256 &txid) const { return db.Exists(make_pair(DB_COINS, txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read(DB_BEST_BLOCK, hashBestChain)) return uint256(); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { CDBBatch batch(&db.GetObfuscateKey()); size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { if (it->second.coins.IsPruned()) batch.Erase(make_pair(DB_COINS, it->first)); else batch.Write(make_pair(DB_COINS, it->first), it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (!hashBlock.IsNull()) batch.Write(DB_BEST_BLOCK, hashBlock); LOG_INFO("Committing {} changed transactions (out of {}) to coin database...", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) { return Read(make_pair(DB_BLOCK_FILES, nFile), info); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write(DB_REINDEX_FLAG, '1'); else return Erase(DB_REINDEX_FLAG); } bool CBlockTreeDB::ReadReindexing(bool &fReindexing) { fReindexing = Exists(DB_REINDEX_FLAG); return true; } bool CBlockTreeDB::ReadLastBlockFile(int &nFile) { return Read(DB_LAST_BLOCK, nFile); } bool CCoinsViewDB::GetStats(CCoinsStats &stats) const { /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ std::unique_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator()); pcursor->Seek(DB_COINS); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; CCoins coins; if (pcursor->GetKey(key) && key.first == DB_COINS) { if (pcursor->GetValue(coins)) { stats.nTransactions++; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + pcursor->GetValueSize(); ss << VARINT(0); } else { LOG_ERROR("CCoinsViewDB::GetStats() : unable to read value"); return false; } } else { break; } pcursor->Next(); } { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : fileInfo) batch.Write(make_pair(DB_BLOCK_FILES, pairs.first), *pairs.second); batch.Write(DB_LAST_BLOCK, nLastFile); for (const auto &info : blockinfo) batch.Write(make_pair(DB_BLOCK_INDEX, info->GetBlockHash()), CDiskBlockIndex(info)); return WriteBatch(batch, true); } bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) { return Read(make_pair(DB_TXINDEX, txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Write(make_pair(DB_TXINDEX, pairs.first), pairs.second); return WriteBatch(batch); } bool CBlockTreeDB::ReadSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value) { return Read(make_pair(DB_SPENTINDEX, key), value); } bool CBlockTreeDB::UpdateSpentIndex(const std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) { if (pairs.second.IsNull()) { batch.Erase(make_pair(DB_SPENTINDEX, pairs.first)); } else { batch.Write(make_pair(DB_SPENTINDEX, pairs.first), pairs.second); } } return WriteBatch(batch); } bool CBlockTreeDB::UpdateAddressUnspentIndex(const std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) { if (pairs.second.IsNull()) { batch.Erase(make_pair(DB_ADDRESSUNSPENTINDEX, pairs.first)); } else { batch.Write(make_pair(DB_ADDRESSUNSPENTINDEX, pairs.first), pairs.second); } } return WriteBatch(batch); } bool CBlockTreeDB::ReadAddressUnspentIndex(uint160 addressHash, int type, std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_ADDRESSUNSPENTINDEX, CAddressIndexIteratorKey(type, addressHash))); while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char,CAddressUnspentKey> key; if (pcursor->GetKey(key) && key.first == DB_ADDRESSUNSPENTINDEX && key.second.hashBytes == addressHash) { CAddressUnspentValue nValue; if (pcursor->GetValue(nValue)) { unspentOutputs.push_back(make_pair(key.second, nValue)); pcursor->Next(); } else { LOG_ERROR("failed to get address unspent value"); return false; } } else { break; } } return true; } bool CBlockTreeDB::WriteAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Write(make_pair(DB_ADDRESSINDEX, pairs.first), pairs.second); return WriteBatch(batch); } bool CBlockTreeDB::EraseAddressIndex(const std::vector<std::pair<CAddressIndexKey, CAmount > >&vect) { CDBBatch batch(&GetObfuscateKey()); for (const auto &pairs : vect) batch.Erase(make_pair(DB_ADDRESSINDEX, pairs.first)); return WriteBatch(batch); } bool CBlockTreeDB::ReadAddressIndex(uint160 addressHash, int type, std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex, int start, int end) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); if (start > 0 && end > 0) { pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorHeightKey(type, addressHash, start))); } else { pcursor->Seek(make_pair(DB_ADDRESSINDEX, CAddressIndexIteratorKey(type, addressHash))); } while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char,CAddressIndexKey> key; if (pcursor->GetKey(key) && key.first == DB_ADDRESSINDEX && key.second.hashBytes == addressHash) { if (end > 0 && key.second.blockHeight > end) { break; } CAmount nValue; if (pcursor->GetValue(nValue)) { addressIndex.push_back(make_pair(key.second, nValue)); pcursor->Next(); } else { LOG_ERROR("failed to get address index value"); return false; } } else { break; } } return true; } bool CBlockTreeDB::WriteTimestampIndex(const CTimestampIndexKey &timestampIndex) { CDBBatch batch(&GetObfuscateKey()); batch.Write(make_pair(DB_TIMESTAMPINDEX, timestampIndex), 0); return WriteBatch(batch); } bool CBlockTreeDB::ReadTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector<uint256> &hashes) { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_TIMESTAMPINDEX, CTimestampIndexIteratorKey(low))); while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, CTimestampIndexKey> key; if (pcursor->GetKey(key) && key.first == DB_TIMESTAMPINDEX && key.second.timestamp <= high) { hashes.push_back(key.second.blockHash); pcursor->Next(); } else { break; } } return true; } bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) { return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) { char ch; if (!Read(std::make_pair(DB_FLAG, name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::LoadBlockIndexGuts() { std::unique_ptr<CDBIterator> pcursor(NewIterator()); pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256())); // Load mapBlockIndex while (pcursor->Valid()) { boost::this_thread::interruption_point(); std::pair<char, uint256> key; if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) { CDiskBlockIndex diskindex; if (pcursor->GetValue(diskindex)) { // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev.reset(InsertBlockIndex(diskindex.hashPrev)); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->hashClaimTrie = diskindex.hashClaimTrie; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; #if 0 if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); #endif pcursor->Next(); } else { LOG_ERROR("LoadBlockIndex() : failed to read value"); return false; } } else { break; } } return true; }
[ "u9089000@gmail.com" ]
u9089000@gmail.com
f8a2f9878b920864f2f7959eca45175e2601c073
69b650b9d8a72975d0347941977be30e251624d4
/SouraEngine/Platform/Windows/WindowsWindow.h
3ac063e1f12c5b1e2059e5051e05f4af61873cd2
[]
no_license
mohammadkamal/SouraEngine
829b3ec535fc52775523f6c8145fa7389da56fb3
da207e63e66ce004ae44bb61cc896fc472917553
refs/heads/master
2023-06-04T14:04:43.730150
2021-06-29T12:48:31
2021-06-29T12:48:31
271,069,273
1
0
null
null
null
null
UTF-8
C++
false
false
828
h
#pragma once #include "Core/Window.h" #include <memory> #include <glad/glad.h> #include <GLFW/glfw3.h> namespace SouraEngine { class WindowsWindow :public Window { public: WindowsWindow(const WindowProperties& props); virtual ~WindowsWindow(); virtual void OnUpdate() override; virtual uint32_t GetWidth() const override { return m_Data.Width; } virtual uint32_t GetHeight() const override { return m_Data.Height; } //Event Callback Method //VSync virtual void* GetNativeWindow() const { return m_Window; } private: virtual void Init(const WindowProperties& props); virtual void Shutdown(); GLFWwindow* m_Window; std::unique_ptr<GraphicsContext> m_Context; struct WindowData { std::string Title; uint32_t Width, Height; //VSync //Event Callback }; WindowData m_Data; }; }
[ "mohammadkamalshady@gmail.com" ]
mohammadkamalshady@gmail.com
b1c6ab4e38fe64bd221c5fc95d236d3617a29ffd
bd697660a48a179aab653ecbc21fdbf4a1c29c80
/BattleTank/Source/BattleTank/TankPlayerController.cpp
1a25fcd5d367289b3360f60af1c3c852718f486c
[]
no_license
celioreyes/UC_Section04_BattleTank
c4c9c99565358420bc1ad7106193a39afa7c9a81
e0640a04db374c597987916c3878384ed9f704cd
refs/heads/master
2020-04-14T19:28:00.377665
2019-02-17T20:59:50
2019-02-17T20:59:50
164,058,590
0
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TankPlayerController.h" #include "BattleTank.h" ATank* ATankPlayerController::GetControlledTank() const { return Cast<ATank>(GetPawn()); }
[ "celioreyesrr@gmail.com" ]
celioreyesrr@gmail.com
af73160f7a8b2e8f75da9a7c40a059bed1a5158a
515d4cea84eb2dd70b67b1b1bfc64de14fdd0d3d
/arduino/arduino_onboard/arduino.ino
b91f66ad7a6fdcf9ab03d6d79434547ab0d48a3d
[]
no_license
Pigaco/hosts
cc618566dcedca9442850ce0aeb18286d2b5decb
64a872aeeb179ce38513d553a015c7165956b73e
refs/heads/master
2021-01-22T03:13:58.418832
2016-11-14T12:41:57
2016-11-14T12:41:57
38,927,975
1
0
null
null
null
null
UTF-8
C++
false
false
1,614
ino
#include "serial_connector.h" #include "button.h" #include "led.h" //If you change the baud rate here, you also have //to change it in the makefile. SerialConnector serialConnector(9600); //Workaround for an arduino compiler bug void* __dso_handle; void* __cxa_atexit; //LEDs LED *leds[6]; //Buttons Button *buttons[11]; void setup(void) { //Status-LED pinMode(13, OUTPUT); digitalWrite(13, HIGH); serialConnector.setup(); Button::serialConnector = &serialConnector; //Create LEDs and buttons. //Be cautious with the IDs and pins! // //!!!!!!!!!!! //CHANGE THIS //!!!!!!!!!!! //LEDs use the analog pins. leds[0] = new LED(A0); leds[1] = new LED(A1); leds[2] = new LED(A2); leds[3] = new LED(A3); leds[4] = new LED(A4); leds[5] = new LED(A5); //Buttons use the digital pins. buttons[0] = new Button(10, BUTTON_UP); buttons[1] = new Button(11, BUTTON_DOWN); buttons[2] = new Button(12, BUTTON_LEFT); buttons[3] = new Button(2, BUTTON_RIGHT); buttons[4] = new Button(9, BUTTON_ACTION); buttons[5] = new Button(3, BUTTON_BUTTON1); buttons[6] = new Button(4, BUTTON_BUTTON2); buttons[7] = new Button(5, BUTTON_BUTTON3); buttons[8] = new Button(6, BUTTON_BUTTON4); buttons[9] = new Button(7, BUTTON_BUTTON5); buttons[10] = new Button(8, BUTTON_BUTTON6); serialConnector.leds = leds; } void loop(void) { int i; serialConnector.loop(); for(i = 0; i < 6; ++i) { leds[i]->loop(); } for(i = 0; i < 11; ++i) { buttons[i]->loop(); } }
[ "mail@maximaximal.com" ]
mail@maximaximal.com
d22164f929db37287d624e1b729aa15747ab4323
b496aaf23fef3507808aad224103f1bc43e638ef
/sesion3_1/src/Texture.cpp
4baad551f6ca074d439a7a455f37a8faab53b5f8
[]
no_license
hnjm/PracticaFinalIG
f7672c925a5286e1af9b25b32592a7393e1bf055
8e0140d69dc7974d9bf62b9514c4c4808b47835c
refs/heads/master
2020-07-27T21:42:55.145834
2019-01-08T13:32:57
2019-01-08T13:32:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
#include "Texture.h" //------------------------ // Constructor dela clase //------------------------ Texture::Texture(GLuint idTexture, const char* pathTexture) { // Texture unit this->idTexture = idTexture; // Creamos la textura a configurar glGenTextures(1,&texture); glBindTexture(GL_TEXTURE_2D, texture); // Cargamos la imagen (SOIL) int textureW, textureH; unsigned char* imgTexture = SOIL_load_image(pathTexture, &textureW, &textureH, 0, SOIL_LOAD_RGB); // Creamos la textura glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textureW, textureH, 0, GL_RGB, GL_UNSIGNED_BYTE, imgTexture); glGenerateMipmap(GL_TEXTURE_2D); // Liberamos memoria (SOIL) SOIL_free_image_data(imgTexture); // Configuramos la textura glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } //------------------------------------------------------------------------------------------ // Activa una "unidad de textura" para que esta sea accesible desde el shader de fragmentos //------------------------------------------------------------------------------------------ void Texture::Activate() { glActiveTexture(GL_TEXTURE0 + idTexture); glBindTexture(GL_TEXTURE_2D,texture); } //----------------------------------------- // Devuelve el identificador de la textura //----------------------------------------- GLuint Texture::getIdTexture() { return idTexture; } //----------------------- // Destructor dela clase //----------------------- Texture::~Texture() { glDeleteTextures(1,&texture); }
[ "noreply@github.com" ]
hnjm.noreply@github.com
befbc79acc3a9c1f491c77672618342456efeebe
a714d23380e2f75a100c3c98b71e9a878a7c9465
/comp_prog/ioi_archive/2011/ricehub/grader.cpp
00f754fdf17f0f0441dc12f1f0a5f901d456a21d
[]
no_license
harta01/kaizen
61ba6f5b461d2124d6366561c78d535756a1da75
235662e12497ee1eb58bf4f2e37c99746de1f415
refs/heads/master
2020-04-12T22:38:25.934735
2016-10-03T03:04:43
2016-10-03T03:04:43
68,275,745
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
#include "grader.h" #include <stdio.h> #include <stdlib.h> #define MAX_R 1000000 static int R, L; static long long B; static int X[MAX_R]; static int solution; inline void my_assert(int e) {if (!e) abort();} static void read_input() { int i; my_assert(3==scanf("%d %d %lld",&R,&L,&B)); for(i=0; i<R; i++) my_assert(1==scanf("%d",&X[i])); my_assert(1==scanf("%d",&solution)); } int main() { int ans; read_input(); ans = besthub(R,L,X,B); if(ans==solution) printf("Correct.\n"); else printf("Incorrect. Returned %d instead of %d.\n",ans,solution); return 0; }
[ "wijayaha@garena.com" ]
wijayaha@garena.com
129b28ea2e4c5cf8f36aaac73632c2560d45192b
785df77400157c058a934069298568e47950e40b
/TnbMesh/TnbLib/SizeMapControl/3d/Mesh3d_SizeMapControlFwd.hxx
1969f93adb96a6c04dcbef044688aefd24d1edbd
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
343
hxx
#pragma once #ifndef _Mesh3d_SizeMapControlFwd_Header #define _Mesh3d_SizeMapControlFwd_Header namespace tnbLib { // Forward Declarations [6/22/2022 Amir] class Cad_TModel; template<class GeomType> class Mesh_SizeMapControl; typedef Mesh_SizeMapControl<Cad_TModel> Mesh3d_SizeMapControl; } #endif // !_Mesh3d_SizeMapControlFwd_Header
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
744c48380fbc321db608409ae435136b82cc90b6
4d7ae3ca4674267c72385fa1ba67496e3abd55ff
/libRayTracing/RayTracing/aabb.h
f52df8b074fa8ed181af90015358b6fd35c6187c
[ "MIT" ]
permissive
tanganke/RayTracing
1e5c1e066b74f26ef215f1075e43cd8db8eb7259
876180439cbc2a6241735d18de6e0eb9e2f11e96
refs/heads/master
2023-08-25T02:56:58.126412
2021-10-13T11:52:07
2021-10-13T11:52:07
404,777,544
0
0
null
null
null
null
UTF-8
C++
false
false
2,421
h
#pragma once #include "ray.h" #include "float.h" #include <iostream> namespace ray_tracing { class aabb { public: vec3 lower_bound, higher_bound; public: aabb() : lower_bound{FLT_MAX, FLT_MAX, FLT_MAX}, higher_bound{FLT_MIN, FLT_MIN, FLT_MIN} {}; aabb(const vec3 &lower_bound_, const vec3 &higher_bound_) : lower_bound{lower_bound_}, higher_bound{higher_bound_} {} aabb(const aabb &a, const aabb &b) { vec3 lower{std::min(a.lower_bound[0], b.lower_bound[0]), std::min(a.lower_bound[1], b.lower_bound[1]), std::min(a.lower_bound[2], b.lower_bound[2])}; vec3 higher{std::max(a.higher_bound[0], b.higher_bound[0]), std::max(a.higher_bound[1], b.higher_bound[1]), std::max(a.higher_bound[2], b.higher_bound[2])}; lower_bound = lower; higher_bound = higher; } inline vec3 &min() { return lower_bound; } inline vec3 &max() { return higher_bound; } inline const vec3 &min() const { return lower_bound; } inline const vec3 &max() const { return higher_bound; } aabb &push_back(const vec3 &p) { for (int i = 0; i < 3; ++i) { lower_bound[i] = std::min(lower_bound[i], p[i]); higher_bound[i] = std::max(higher_bound[i], p[i]); } return *this; } bool hit(const ray &r, float t_min, float t_max) const { for (int i = 0; i < 3; ++i) { float t[2] = {(lower_bound[i] - r.start_point[i]) / r.direction[i], (higher_bound[i] - r.start_point[i]) / r.direction[i]}; float interval[2] = {std::min(t[0], t[1]), std::max(t[0], t[1])}; t_min = std::max(interval[0], t_min); t_max = std::min(interval[1], t_max); if (t_max <= t_min) return false; } return true; } inline void translate(const vec3 &displacement) { lower_bound += displacement; higher_bound += displacement; } inline void clear() { *this = aabb(); } }; inline std::ostream &operator<<(std::ostream &os, const aabb &bbox) { os << "aabb(" << bbox.lower_bound << ',' << bbox.higher_bound << ')'; return os; } }
[ "tang.anke@foxmail.com" ]
tang.anke@foxmail.com
c9720145685fd4b975aa66f0483e660dc5a01bb5
67354b590965aef0cfccaf524951e8d799c5dbbf
/gui/ImageStackView.h
f01c35e2bdabbc8c25fecd4c0e79d9204cc191c1
[]
no_license
unidesigner/imageprocessing
31643dcc46ed82f57c1398dc25c74a384dfa35a1
2878a56fff5d59930fe73a8f99200b1ea8fc0607
refs/heads/master
2021-01-15T21:48:56.122674
2013-02-27T11:26:42
2013-02-27T11:26:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
h
#ifndef IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__ #define IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__ #include <pipeline/all.h> #include <imageprocessing/ImageStack.h> #include <gui/Keys.h> #include <gui/Signals.h> #include "ImageStackPainter.h" class ImageStackView : public pipeline::SimpleProcessNode<> { public: ImageStackView(unsigned int numImages = 1); private: void updateOutputs(); void onKeyDown(gui::KeyDown& signal); pipeline::Input<ImageStack> _stack; pipeline::Output<ImageStackPainter> _painter; pipeline::Output<Image> _currentImage; signals::Slot<gui::SizeChanged> _sizeChanged; signals::Slot<gui::ContentChanged> _contentChanged; // the section to show int _section; // copy of the currently visible image vigra::MultiArray<2, float> _currentImageData; }; #endif // IMAGEPROCESSING_GUI_IMAGE_STACK_VIEW_H__
[ "funke@ini.ch" ]
funke@ini.ch
bb1e5e0ad7d3c14a859e3e886aa34e15d40558d9
ea727ced064f305a844d54343ee0534e00571e24
/Graph/PrintAdjList/PrintAdjList.h
05f9ff9e0eb826bd1c71b90005e4c30ab2a321fb
[]
no_license
iukjgo/practice_easy
dce60754329dd63f15dfdf9ee7a77fea7229fee0
dfd19e7c28b8f967d4079f6d6870492723cdfefa
refs/heads/master
2020-04-06T08:03:09.227027
2018-11-21T03:11:54
2018-11-21T03:11:54
157,293,395
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef PrintAdjList_h #define PrintAdjList_h #include <iostream> #include <vector> class Graph { public: Graph(int vertices, int edges) : mVertices(vertices), mEdges(edges), mAdj(vertices) { }; void addEdge(int u, int v); const std::vector<int>* getAdjList(int u) const; const int getVerticesCount() const { return mVertices; } private: std::vector<std::vector<int>> mAdj; int mVertices; int mEdges; }; class PrintAdjList { public: PrintAdjList() {}; static void print(const Graph& g); private: }; #endif /* PrintAdjList_h */
[ "iukjgo@gmail.com" ]
iukjgo@gmail.com
56df4e03d1a5923c15de1988c8431d446c6468ff
5bbeacb6613fdaa184a5bda4bdb54b16dc8654e1
/zMuSource/GameServer/MonsterBag.cpp
09f253ca68ce783ea490345dc4864c6cdf122ae9
[]
no_license
yiyilookduy/IGCN-SS12
0e4b6c655c2f15e561ad150e1dd0f047a72ef23b
6a3f8592f4fa9260e56c1d5fee7a62277dc3691d
refs/heads/master
2020-04-04T09:03:13.134134
2018-11-02T03:02:29
2018-11-02T03:02:29
155,804,847
0
4
null
null
null
null
UTF-8
C++
false
false
3,415
cpp
//////////////////////////////////////////////////////////////////////////////// // MonsterBag.cpp #include "stdafx.h" #include "MonsterBag.h" #include "TLog.h" #include "user.h" #include "LuaBag.h" #include "MapClass.h" #include "GameMain.h" CMonsterBag::CMonsterBag() { } CMonsterBag::~CMonsterBag() { } void CMonsterBag::SetBagInfo(int iParam1, int MonsterClass) { this->m_BagMonsterClass = MonsterClass; } bool CMonsterBag::CheckCondition(int aIndex, int MonsterClass, int iParam2) { if (rand() % 10000 >= this->m_BagData.dwBagUseRate) { return false; } if (this->m_BagMonsterClass == MonsterClass) { return true; } return false; } bool CMonsterBag::IsBag(int aIndex, int MonsterClass, int iParam2) { if (this->m_BagMonsterClass == MonsterClass) { return true; } return false; } bool CMonsterBag::UseBag(int aIndex, int iMonsterIndex) { if (gObj[aIndex].Type != OBJ_USER) { return false; } LPOBJ lpObj = &gObj[aIndex]; LPOBJ lpMonsterObj = &gObj[iMonsterIndex]; if (rand() % 10000 >= this->m_BagData.dwItemDropRate) { MapC[gObj[aIndex].MapNumber].MoneyItemDrop(this->m_BagData.dwDropMoney, lpObj->X, lpObj->Y); return true; } if (rand() % 10000 < this->m_BagData.dwGainRuudRate) { int iRuudValue = this->GetValueMinMax(this->m_BagData.dwMinGainRuud, this->m_BagData.dwMaxGainRuud); lpObj->m_PlayerData->Ruud += iRuudValue; GSProtocol.GCSendRuud(aIndex, lpObj->m_PlayerData->Ruud, iRuudValue, true); return true; } BAG_ITEM m_Item; BAG_SECTION_ITEMS m_ItemSection; BAG_SECTION_DROP m_DropSection; int iResult = this->GetDropSection(aIndex, m_DropSection); if (iResult == FALSE) { return false; } iResult = this->GetItemsSection(m_DropSection, m_ItemSection); if (iResult == FALSE) { return false; } if (m_ItemSection.btItemDropCount <= 0) { return false; } if (m_ItemSection.btItemDropCount == 1) { if (rand()%10000 < this->m_BagData.dwRandomSetItemDropRate) { MakeRewardSetItem(aIndex, lpMonsterObj->X, lpMonsterObj->Y, 1, lpObj->MapNumber); return true; } if (this->GetItem(m_ItemSection, m_Item) == FALSE) { return false; } bool bResult = gLuaBag.DropCommonBag(aIndex, lpMonsterObj->MapNumber, lpMonsterObj->X, lpMonsterObj->Y, &m_Item); if (bResult == false) { return false; } return true; } for (int i = 0; i < m_ItemSection.btItemDropCount; i++) { BYTE cDropX = lpMonsterObj->X; BYTE cDropY = lpMonsterObj->Y; if (!gObjGetRandomItemDropLocation(lpMonsterObj->MapNumber, cDropX, cDropY, 4, 4, 10)) { cDropX = lpMonsterObj->X; cDropY = lpMonsterObj->Y; } if (rand()%10000 < this->m_BagData.dwRandomSetItemDropRate) { MakeRewardSetItem(aIndex, cDropX, cDropY, 1, lpObj->MapNumber); continue; } if (this->GetItem(m_ItemSection, m_Item) == FALSE) { return false; } bool bResult = gLuaBag.DropMonsterBag(aIndex, iMonsterIndex, lpMonsterObj->MapNumber, cDropX, cDropY, &m_Item); if (bResult == false) { return false; } } return true; } bool CMonsterBag::UseBag_GremoryCase(int aIndex, int iMonsterIndex, BYTE btStorageType, BYTE btRewardSource, int iExpireDays) { return false; } //////////////////////////////////////////////////////////////////////////////// // vnDev.Games - MuServer S12EP2 IGC v12.0.1.0 - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "duypnse63523@fpt.edu.vn" ]
duypnse63523@fpt.edu.vn
3f7bba1662824a937b68e636515ca0c606b2d437
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/multimedia/audio/DuckingCaptureSample/WasapiChat.Cpp
93e269d3755c1808ec1fd55f0ac995ecda52908e
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
9,810
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // // A very simple "Chat" client - reads samples from the default console device and discards the output. // #include "StdAfx.h" #include "WasapiChat.h" CWasapiChat::CWasapiChat(HWND AppWindow) : CChatTransport(AppWindow), _ChatEndpoint(NULL), _AudioClient(NULL), _RenderClient(NULL), _CaptureClient(NULL), _Flow(eRender), _ChatThread(NULL), _ShutdownEvent(NULL), _AudioSamplesReadyEvent(NULL) { } CWasapiChat::~CWasapiChat(void) { SafeRelease(&_ChatEndpoint); SafeRelease(&_AudioClient); SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); if (_ChatThread) { CloseHandle(_ChatThread); } if (_ShutdownEvent) { CloseHandle(_ShutdownEvent); } if (_AudioSamplesReadyEvent) { CloseHandle(_AudioSamplesReadyEvent); } } // // We can "Chat" if there's more than one capture device. // bool CWasapiChat::Initialize(bool UseInputDevice) { IMMDeviceEnumerator *deviceEnumerator; HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&deviceEnumerator)); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to instantiate device enumerator", L"WASAPI Transport Initialize Failure", MB_OK); return false; } if (UseInputDevice) { _Flow = eCapture; } else { _Flow = eRender; } hr = deviceEnumerator->GetDefaultAudioEndpoint(_Flow, eCommunications, &_ChatEndpoint); deviceEnumerator->Release(); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to retrieve default endpoint", L"WASAPI Transport Initialize Failure", MB_OK); return false; } // // Create our shutdown event - we want an auto reset event that starts in the not-signaled state. // _ShutdownEvent = CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); if (_ShutdownEvent == NULL) { MessageBox(_AppWindow, L"Unable to create shutdown event.", L"WASAPI Transport Initialize Failure", MB_OK); return false; } _AudioSamplesReadyEvent = CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); if (_ShutdownEvent == NULL) { MessageBox(_AppWindow, L"Unable to create samples ready event.", L"WASAPI Transport Initialize Failure", MB_OK); return false; } return true; } // // Shut down the chat code and free all the resources. // void CWasapiChat::Shutdown() { if (_ChatThread) { SetEvent(_ShutdownEvent); WaitForSingleObject(_ChatThread, INFINITE); CloseHandle(_ChatThread); _ChatThread = NULL; } if (_ShutdownEvent) { CloseHandle(_ShutdownEvent); _ShutdownEvent = NULL; } if (_AudioSamplesReadyEvent) { CloseHandle(_AudioSamplesReadyEvent); _AudioSamplesReadyEvent = NULL; } SafeRelease(&_ChatEndpoint); SafeRelease(&_AudioClient); SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); } // // Start the "Chat" - open the capture device, start capturing. // bool CWasapiChat::StartChat(bool HideFromVolumeMixer) { WAVEFORMATEX *mixFormat = NULL; HRESULT hr = _ChatEndpoint->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, reinterpret_cast<void **>(&_AudioClient)); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to activate audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->GetMixFormat(&mixFormat); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to get mix format on audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // Initialize the chat transport - Initialize WASAPI in event driven mode, associate the audio client with // our samples ready event handle, retrieve a capture/render client for the transport, create the chat thread // and start the audio engine. // GUID chatGuid; hr = CoCreateGuid(&chatGuid); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to create GUID.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, (HideFromVolumeMixer ? AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE : 0) | AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST, 500000, 0, mixFormat, &chatGuid); CoTaskMemFree(mixFormat); mixFormat = NULL; if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to initialize audio client.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _AudioClient->SetEventHandle(_AudioSamplesReadyEvent); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to set ready event.", L"WASAPI Transport Start Failure", MB_OK); return false; } if (_Flow == eRender) { hr = _AudioClient->GetService(IID_PPV_ARGS(&_RenderClient)); } else { hr = _AudioClient->GetService(IID_PPV_ARGS(&_CaptureClient)); } if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to get Capture/Render client.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // Now create the thread which is going to drive the "Chat". // _ChatThread = CreateThread(NULL, 0, WasapiChatThread, this, 0, NULL); if (_ChatThread == NULL) { MessageBox(_AppWindow, L"Unable to create transport thread.", L"WASAPI Transport Start Failure", MB_OK); return false; } // // For render, we want to pre-roll a frames worth of silence into the pipeline. That way the audio engine won't glitch on startup. // if (_Flow == eRender) { BYTE *pData; UINT32 framesAvailable; hr = _AudioClient->GetBufferSize(&framesAvailable); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to get client buffer size.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _RenderClient->GetBuffer(framesAvailable, &pData); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to get buffer.", L"WASAPI Transport Start Failure", MB_OK); return false; } hr = _RenderClient->ReleaseBuffer(framesAvailable, AUDCLNT_BUFFERFLAGS_SILENT); if (FAILED(hr)) { MessageBox(_AppWindow, L"Failed to release buffer.", L"WASAPI Transport Start Failure", MB_OK); return false; } } // // We're ready to go, start the chat! // hr = _AudioClient->Start(); if (FAILED(hr)) { MessageBox(_AppWindow, L"Unable to start chat client.", L"WASAPI Transport Start Failure", MB_OK); return false; } return true; } // // Stop the "Chat" - Stop the capture thread and release the buffers. // void CWasapiChat::StopChat() { // // Tell the chat thread to shut down, wait for the thread to complete then clean up all the stuff we // allocated in StartChat(). // if (_ShutdownEvent) { SetEvent(_ShutdownEvent); } if (_ChatThread) { WaitForSingleObject(_ChatThread, INFINITE); CloseHandle(_ChatThread); _ChatThread = NULL; } SafeRelease(&_RenderClient); SafeRelease(&_CaptureClient); SafeRelease(&_AudioClient); } DWORD CWasapiChat::WasapiChatThread(LPVOID Context) { bool stillPlaying = true; CWasapiChat *chat = static_cast<CWasapiChat *>(Context); HANDLE waitArray[2] = {chat->_ShutdownEvent, chat->_AudioSamplesReadyEvent}; while (stillPlaying) { HRESULT hr; DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, INFINITE); switch (waitResult) { case WAIT_OBJECT_0 + 0: stillPlaying = false; // We're done, exit the loop. break; case WAIT_OBJECT_0 + 1: // // Either stream silence to the audio client or ignore the audio samples. // // Note that we don't check for errors here. This is because // (a) there's no way of reporting the failure // (b) once the streaming engine has started there's really no way for it to fail. // if (chat->_Flow == eRender) { BYTE *pData; UINT32 framesAvailable; hr = chat->_AudioClient->GetCurrentPadding(&framesAvailable); hr = chat->_RenderClient->GetBuffer(framesAvailable, &pData); hr = chat->_RenderClient->ReleaseBuffer(framesAvailable, AUDCLNT_BUFFERFLAGS_SILENT); } else { BYTE *pData; UINT32 framesAvailable; DWORD flags; hr = chat->_AudioClient->GetCurrentPadding(&framesAvailable); hr = chat->_CaptureClient->GetBuffer(&pData, &framesAvailable, &flags, NULL, NULL); hr = chat->_CaptureClient->ReleaseBuffer(framesAvailable); } } } return 0; } // // Returns "true" for the window messages we handle in our transport. // bool CWasapiChat::HandlesMessage(HWND /*hWnd*/, UINT /*message*/) { return false; } // // Don't process Wave messages. // INT_PTR CWasapiChat::MessageHandler(HWND /*hWnd*/, UINT /*message*/, WPARAM /*wParam*/, LPARAM /*lParam*/) { return FALSE; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
d3efa762dbb898e39d13bd12646aca5d867154d3
ae0dbf9739042461b1b55dd79aad3beff25ba3b0
/bfs2.cpp
68a8f66dea2ec611bfe9e4a6df431a2b77f96d38
[]
no_license
saquib77/Code
b058d587438c5e029a1b422b2facb80924c69f91
006faa69f35d3cbfd9aca261ed696cab78ff7fb0
refs/heads/main
2023-07-14T01:05:22.466452
2021-08-20T06:55:13
2021-08-20T06:55:13
341,225,695
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include<bits/stdc++.h> using namespace std; queue<int>q; bool visited[7]; int dist[7]; vector<pair<int,int>>gp[7]; void bfs(int n){ visited[n]=true; dist[n]=0; q.push(n); while(!q.empty()){ int s=q.front(); q.pop(); cout<<s<<" "; for(auto v:gp[s]){ if(visited[v.first]) continue; visited[v.first]=true; dist[v.first]=dist[s]+1; q.push(v.first); } } } int main(){ gp[1].push_back(make_pair(5,1)); gp[2].push_back(make_pair(3,2)); gp[2].push_back(make_pair(1,5)); gp[3].push_back(make_pair(4,7)); gp[3].push_back(make_pair(2,2)); gp[4].push_back(make_pair(1,3)); gp[5].push_back(make_pair(4,2)); //bfs(1); bfs(2); cout<<"\n"; return 0; }
[ "chand567khan@gmail.com" ]
chand567khan@gmail.com
31e6f12a2149c21297c193403f899b0ad7472938
e56923b83be1f888f1a36877c904efc5e92341d6
/BreathDetectionSystem/src/forandroid/CommBase/jni/include/TCPConnector.h
c1acc506618e636e40c05d11344d8f6522c398fc
[]
no_license
IFrestart/Breath
12671279452d2c69298b5f8682013424b5a6f9ae
d93701f1caf228fe39a1c53651ee59705390736f
refs/heads/master
2020-06-19T23:36:43.916392
2019-07-16T02:01:17
2019-07-16T02:01:17
196,914,017
0
0
null
null
null
null
GB18030
C++
false
false
5,962
h
/** * Copyright (c) 2004, HangZhou Webcon Corporation. * 被动TCP类,提供被动TCP的建立,关闭,发送数据等操作 * @file TCPConnector.h * @short 被动TCP类 * @author zhoujj <zhoujj@webcon.com.cn> * @class CTCPConnector * @short 被动TCP类 **/ #ifndef __TCPCONNECTOR_H__ #define __TCPCONNECTOR_H__ #include "Timer.h" #include "BaseACObject.h" #include "ACCommMainObject.h" //#include "HighCommCon.h" class IACMainObject; //class CACPackHead; class CSockHeader; // 包装MyAcDll中UDP和TCP连接套接字 class CTCPConnector { public: /** 构造函数 */ CTCPConnector(ISockEventCallBack* pCallBack=0); /** 析构函数 */ ~CTCPConnector(void); /** * 创建一个TCP socket * @param ipstr socket要连接到的IP,字符串 * @param port socket要连接到的端口号 * @param pSockEventCallBack 处理TCP事件的回调接口 * @return 成功则返回0 */ int create(const char* ipstr, unsigned short port, ISockEventCallBack* pSockEventCallBack= 0); /** * 创建一个TCP socket * @param ip socket要连接到的IP * @param port socket要连接到的端口号 * @param pSockEventCallBack 处理TCP事件的回调接口 * @return 成功则返回0 */ int create(unsigned long ip, unsigned short port, ISockEventCallBack* pSockEventCallBack= 0); /** * 关闭TCP socket * @return 成功则返回0 */ int close(); /** * 通过TCP socket发送数据 * @param pdutype socket要发送数据的PDU类型 * @param data socket要发送的数据 * @param len socket要发送数据的长度 * @return 成功则返回0 */ int sendPacket(unsigned short pdutype, const void* data, unsigned long len); /** * 返回TCP socket底层的FD * @return 不成功则返回-1 */ ACE_HANDLE getSock() const; #if 0 /** 启动通信对象(不使用代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param bUseHttp 是否使用HTTP协议(当用HTTP代理或HTTP协议登陆后, 建立点对点连接时,如双方在同一局域网,则为FALSE,其它情况为TRUE) * @param bMulPoint 是否组播 * @return 0-成功, <0失败 */ int Start(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, BOOL bUseHttp,BOOL bMulPoint=FALSE); /** 启动通信对象(使用SOCK5代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param lpProxyAddr 代理服务器IP * @param nProxyPort 代理服务器端口 * @param lpProxyUserName 代理用户名 * @param lpProxyPassword 代理密码 * @return 0-成功, <0失败 */ int StartSock5(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, LPCTSTR lpProxyAddr, USHORT nProxyPort, LPCTSTR lpProxyUserName, LPCTSTR lpProxyPassword); /** 启动通信对象(使用HTTP代理) * @param wProtoType 通信对象类型(SOCK_STREAM-TCP, SOCK_DGRAM-UDP) * @param lpLocalHost 本机IP * @param nLocalPort 本机端口 * @param lpszSvrAddr 服务器IP * @param nSvrPort 服务器端口 * @param lpProxyAddr 代理服务器IP * @param nProxyPort 代理服务器端口 * @param lpProxyUserName 代理用户名 * @param lpProxyPassword 代理密码 * @return 0-成功, <0失败 */ int StartHttp(WORD wProtoType, LPCTSTR lpLocalHost, USHORT nLocalPort, LPCTSTR lpszSvrAddr, USHORT nSvrPort, LPCTSTR lpProxyAddr, USHORT nProxyPort, LPCTSTR lpProxyUserName, LPCTSTR lpProxyPassword); /** UDP通信对象发送数据 * @param wPduType 数据包的PDU类别 * @param lpData 要发送的数据 * @param dwSize 数据长度 * @param bSync 是否同步发送(目前只支持同步发送) * @param lpRemoteHost 接收方的IP * @param nRemotePort 接收方的端口 * @param wExtParam 扩展参数(用于程序调试) * @param bSock5Flag 如果用SOCK5登陆到服务器,点对点连接间发送数据是否加 SOCK5头(当双方在同一局域网时,应为FALSE) */ int SendCommUDPData(WORD wPduType, const BYTE* lpData, DWORD dwSize, BOOL bSync, LPCTSTR lpRemoteHost, USHORT nRemotePort, WORD wExtParam, BOOL bSock5Flag); /** TCP通信对象发送数据 * @param wPduType 数据包的PDU类别 * @param lpData 要发送的数据 * @param dwSize 数据长度 * @param bSync 是否同步发送(目前只支持同步发送) * @param hSocket 本参数不使用 */ int SendCommTCPData(WORD wPduType, const BYTE* lpData, DWORD dwSize, BOOL bSync, SOCKET hSocket= INVALID_SOCKET); #endif /** 停止通信对象 */ void Stop(int nType=0); ///** 获取本机IP //*/ //LPCTSTR GetLocalHost(void) const; ///** 获取本机子网掩码 //*/ //LPCTSTR GetLocalMask(void) const; ///** 获取本地端口 //*/ //USHORT GetLocalPort(void); ///** 获取通信对象的套接字句柄 //*/ //SOCKET GetSocket(void); /*关闭Socket * */ // void CloseConnect(); //void CloseConnect(SOCKET hSocket); void setHeadFlag(bool flag) {m_bHeadFlag = flag;}//add 2012-10-18 int GetExitType(); private: /** 删除通信对象(不用线程删除) */ void FreeObject(void); /** 停止通信对象实现线程 */ #ifdef _WIN32 static DWORD WINAPI StopThreadHelper(LPVOID lpParam); static DWORD WINAPI StopMyselfThreadHelper(LPVOID lpParam); #else static void* StopThreadHelper(LPVOID lpParam); static void* StopMyselfThreadHelper(LPVOID lpParam); #endif IACMainObject* m_pAcCommObj; ///< MyAcDll通信对象接口 ISockEventCallBack* m_pCallBack; ///< 数据回调接口实现对象 //CACPackHead* m_pHeadInfo; ///< 数据包头处理对象 CSockHeader* m_pHeadInfo; ///< 数据包头处理对象 int m_nExitType; bool m_bHeadFlag; //add 2012-10-18 }; #endif /*__TCPCONNECTOR_H__*/
[ "782117205@qq.com" ]
782117205@qq.com
4854448793f4dbf22a51e067b83293ffee1db3d0
fef58dcd0c1434724a0a0a82e4c84ae906200289
/usages/0x7033EEFD9B28088E.cpp
7437a3e5ec31d297b26c583585689f28aff74211
[]
no_license
DottieDot/gta5-additional-nativedb-data
a8945d29a60c04dc202f180e947cbdb3e0842ace
aea92b8b66833f063f391cb86cbcf4d58e1d7da3
refs/heads/main
2023-06-14T08:09:24.230253
2021-07-11T20:43:48
2021-07-11T20:43:48
380,364,689
1
0
null
null
null
null
UTF-8
C++
false
false
879
cpp
// freemode.ysc @ L146260 void func_1667(int iParam0, bool bParam1) { struct<14> Var0; struct<13> Var1; if (NETWORK::NETWORK_IS_GAME_IN_PROGRESS()) { if (!func_1669()) { if (iParam0 != -1) { if (NETWORK::NETWORK_IS_PLAYER_ACTIVE(iParam0)) { NETWORK::_0xA7C511FA1C5BDA38(iParam0, 1); func_101(&(Global_1676406[iParam0 /*5*/].f_2), 0, 0); if (bParam1) { func_1619("GRIEF_TICK_VIC", iParam0, 0, 0, 0, 1, 1, 0); } Var0.f_10 = PLAYER::PLAYER_ID(); Var0.f_2 = -1256884122; func_1668(Var0, func_17850(iParam0)); if (MISC::IS_BIT_SET(Global_1573899, 3)) { MISC::SET_BIT(&Global_1573899, 7); } Var1 = { func_38(iParam0) }; STATS::_0x7033EEFD9B28088E(&Var1); } } } } }
[ "tvangroenigen@outlook.com" ]
tvangroenigen@outlook.com
4dd2afb655477a13465ae64633910ff36eafefaf
7a93937f9faa2ef6175d430770d156bbb72cbe66
/source_code.cpp
d1a3bdfd571a566fa573a355c3e775036683a54a
[]
no_license
ramsai-5A1/library_managemet_system
6f6b2d962104a705bee88525bb968c236af04c08
bfbba13652376a2a7cd924762eeb767d7d63ef45
refs/heads/main
2023-08-25T15:15:33.993095
2021-09-19T06:06:21
2021-09-19T06:06:21
408,046,246
0
0
null
null
null
null
UTF-8
C++
false
false
16,392
cpp
************************** //HEADER FILES// #include<iostream.h> #include<fstream.h> #include<process.h> #include<stdio.h> #include<dos.h> #include<conio.h> ************************** struct date1 { int day; int mon; int year; }; class STUDENT { int NOB, std; int fine; char sname[30]; date1 d1,d2; protected: int enrollno; public: STUDENT() { NOB=0; fine=0; d1.day=0; d1.mon=0; d1.year=0; d2.day=0; d2.mon=0; d2.year=0; } void CREATE() { cout<<"\nenter student name:";gets(sname); cout<<"\nenter student rollno:";cin>>enrollno; cout<<"\nenter class:";cin>>std; } //************************************************// //DISPLAY FUNCTION// //************************************************// void DISPLAY() { cout<<"\n***************************\n"; cout<<"\n student name:";puts(sname); cout<<"\n student rollno:";cout<<enrollno; cout<<"\n class:";cout<<std; cout<<"\n no of books issued:";cout<<NOB; cout<<"\n date of issue:";cout<<d1.day<<"-"<<d1.mon<<"-"<<d1.year; cout<<"\n date of return:";cout<<d2.day<<"-"<<d2.mon<<"-"<<d2.year; cout<<"\n fine to be paid:";cout<<fine; } //************************************************// void f_fine() { cout<<"\n fine to be paid:";cout<<fine; } void DOI() { struct date D; getdate(&D); d1.year=D.da_year; d1.mon=D.da_mon; d1.day=D.da_day; } void DOR() { struct date C; getdate(&C); d2.year=C.da_year; d2.mon=C.da_mon; d2.day=C.da_day; } void get_nob() { NOB=NOB+1; } void set_nob() { NOB=NOB-1; } int ret_roll() { return enrollno; } //************************************************// // FINE CALCULATION FUNCTION// //************************************************// void calc_fine() { int val=d1.day,M,N,val1=d2.day,F; if(d1.mon==1) { M=val; } else if(d1.mon==2) { M=31+val; } else if(d1.mon==3) { M=28+31+val; } else if(d1.mon==4) { M=31+28+31+val; } else if(d1.mon==5) { M=30+31+28+31+val; } else if(d1.mon==6) { M=31+30+31+28+31+val; } else if(d1.mon==7) { M=30+31+30+31+28+31+val; } else if(d1.mon==8) { M=31+30+31+30+31+28+31+val; } else if(d1.mon==9) { M=31+31+30+31+30+31+28+31+val; } else if(d1.mon==10) { M=30+31+31+30+31+30+31+28+31+val; } else if(d1.mon==11) { M=31+30+31+31+30+31+30+31+28+31+val; } else if(d1.mon==12) { M=30+31+30+31+31+30+31+30+31+28+31+val; } if(d2.mon==1) { N=val1; } else if(d2.mon==2) { N=31+val1; } else if(d2.mon==3) { N=28+31+val1; } else if(d2.mon==4) { N=31+28+31+val1; } else if(d2.mon==5) { N=30+31+28+31+val1; } else if(d2.mon==6) { N=31+30+31+28+31+val1; } else if(d2.mon==7) { N=30+31+30+31+28+31+val1; } else if(d2.mon==8) { N=31+30+31+30+31+28+31+val1; } else if(d2.mon==9) { N=31+31+30+31+30+31+28+31+val1; } else if(d2.mon==10) { N=30+31+31+30+31+30+31+28+31+val1; } else if(d2.mon==11) { N=31+30+31+31+30+31+30+31+28+31+val1; } else if(d2.mon==12) { N=30+31+30+31+31+30+31+30+31+28+31+val1; } F=N-M; if(F>10) { fine=(F-1)*5; } } }; class BOOK { int qty,total_books; char bname[30],author[30]; float price; protected: int bno; public: BOOK() { qty=0; bno=0; total_books=0; } void get_qty() { qty=qty+1; } void set_qty() { qty=qty-1; } void BCREATE() { cout<<"\nenter book name:";gets(bname); cout<<"\nenter bookno:";cin>>bno; cout<<"\nenter book price:";cin>>price; cout<<"\nenter author name :";gets(author); cout<<"\nenter number of books :";cin>>qty; calc_tot(qty); } //************************************************// //BOOK DISPLAY FUNCTION// //************************************************// void BDISPLAY() { cout<<"\n***************************\n"; cout<<"\n book name:";puts(bname); cout<<" bookno:";cout<<bno; cout<<"\n author name:";puts(author); cout<<"\book Quantity:";cout<<qty; cout<<"\n book price:";cout<<price; } //************************************************// void calc_tot(int x) { total_books+=x; } void tot_book() { cout<<"\n available book in the library:"<<total_books; } int ret_bno() { return bno; } void set_price(int x) { price=x; } }; //************************************************// //STUDENT RECORDS// //************************************************// //SEARCH FUNCTION// //************************************************// void SEARCH() { STUDENT S; int R; cout<<"\n enter student enroll";cin>>R; fstream f2; f2.open("d:/swathi/STUDENT.dat",ios::binary|ios::in); f2.seekg(0,ios::beg); int h=0; while(!f2.eof()) { f2.read((char*)&S,sizeof(S)); if(R==S.ret_roll()) { S.DISPLAY(); h=1; break; } } if(h==0) { cout<<"\nSTUDENT RECORD IS NOT FOUND"; } f2.close(); } //************************************************// //MODIFY FUNCTION// //************************************************// void MODIFY() { STUDENT S; int c; cout<<"\nenter enroll no whose record is to be modified:"; cin>>c; fstream f3; f3.open("d:/swathi/STUDENT.dat",ios::in|ios::out|ios::binary); while(!f3.eof()) { f3.read((char*)&S,sizeof(S)); if(S.ret_roll()==c) { long x=f3.tellg(); f3.seekg(x-sizeof(S)); cout<<"\nNew record to modify:"; S.CREATE(); f3.write((char*)&S,sizeof(S)); break; } } cout<<"\nrecord modified!"; f3.close(); } //************************************************// //DELETE FUNCTION// //************************************************// void DELETE() { STUDENT S; int j; cout<<"\nenter enroll no whose record is to be deleted:";cin>>j; ifstream f4; f4.open("d:/swathi/STUDENT.dat",ios::in|ios::binary); ofstream f5; f5.open("d:/swathi/STUDENT1.dat",ios::out|ios::binary); while(!f4.eof()) { f4.read((char*)&S,sizeof(S)); if(S.ret_roll()!=j) { f5.write((char*)&S,sizeof(S)); } } f4.close(); f5.close(); remove("d:/swathi/STUDENT.dat"); rename("d:/swathi/STUDENT1.dat","d:/swathi/STUDENT.dat"); } //************************************************// //ADD FUNCTION// //************************************************// void ADD() { STUDENT S; fstream f7; f7.open("d:/swathi/STUDENT.dat",ios::in|ios::out|ios::app|ios::binary); S.CREATE(); f7.write((char*)&S,sizeof(S)); f7.close(); cout<<"\nStudent record added."; } //************************************************// //STUDENT DISPLAY FUNCTION// //************************************************// void STUDENTDISPLAY() { STUDENT S; fstream f; f.open("d:/swathi/STUDENT.dat",ios::binary|ios::in); cout<<"\n ALL STUDENTS RECORDS"; f.seekg(0,ios::beg); while(!f.eof()) { f.read((char*)&S,sizeof(S)); S.DISPLAY(); getch(); } f.close(); } //************************************************// //STUDENT CREATE FUNCTION// //************************************************// void STUD_CREATE() { STUDENT S; ofstream f1; char A='Y'; f1.open("d:/swathi/STUDENT.dat",ios::binary|ios::in|ios::out); while(A=='Y') { S.CREATE(); f1.write((char*)&S,sizeof(S)); cout<<"\ndo u want to enter another record(Y\N):";cin>>A; } } //************************************************// //BOOK RECORD// //************************************************// //BOOK SEARCH FUNCTION// //************************************************// void BSEARCH() { BOOK B; int T,j=0; cout<<"\n enter book no";cin>>T; fstream Q2; Q2.open("d:/swathi/BOOK.dat",ios::in|ios::binary); Q2.seekg(0,ios::beg); while(!Q2.eof()) { Q2.read((char*)&B,sizeof(B)); if(T==B.ret_bno()) { B.BDISPLAY(); j=1; break; } } if(j==0) { cout<<"\nBOOK IS NOT FOUND"; } Q2.close(); } //************************************************// //BOOK MODIFY FUNCTION// //************************************************// void BMODIFY() { BOOK B; int p,ch,ch1; cout<<"\nenter book no whose record is to be modified:"; cin>>p; fstream Q3; Q3.open("d:/swathi/BOOK.dat",ios::in|ios::out|ios::binary); while(!Q3.eof()) { Q3.read((char*)&B,sizeof(B)); if(B.ret_bno()==p) { long o=Q3.tellg(); Q3.seekg(o-sizeof(B),ios::beg); cout<<"\nNew record to modify:"; cout<<"\nprice modification:"; cin>>ch; cout<<"\nenter new price:";cin>>ch1; B.set_price(ch1); Q3.write((char*)&B,sizeof(B)); break; } } Q3.close(); cout<<"\nRECORD IS MODIFIED!"; } //************************************************// //BOOK DELETE FUNCTION// //************************************************// void BDELETE() { BOOK B; int d; cout<<"\nenter book no whose record is to be deleted:";cin>>d; ifstream Q4; Q4.open("d:/swathi/BOOK.dat",ios::in|ios::binary); ofstream Q5; Q5.open("d:/swathi/BOOK1.dat",ios::out|ios::binary); while(!Q4.eof()) { Q4.read((char*)&B,sizeof(B)); if(B.ret_bno()!=d) { Q5.write((char*)&B,sizeof(B)); } } Q4.close(); Q5.close(); remove("d:/swathi/BOOK.dat"); rename("d:/swathi/BOOK1.dat","d:/swathi/BOOK.dat"); cout<<"\nRECORD IS DELETED!"; } //************************************************// //BOOK ADD FUNCTION// //************************************************// void BADD() { BOOK B; fstream Q6; Q6.open("d:/swathi/BOOK.dat",ios::in|ios::out|ios::app|ios::binary); B.BCREATE(); Q6.write((char*)&B,sizeof(B)); Q6.close(); cout<<"\nBOOK record added."; } //************************************************// //BOOK DISPLAY FUNCTION// //************************************************// void BOOKDISPLAY() { fstream Q; BOOK B; Q.open("BOOK.dat",ios::binary|ios::in); Q.seekg(0,ios::beg); while(!Q.eof()) { Q.read((char*)&B,sizeof(B)); B.BDISPLAY(); getch(); } Q.close(); } //************************************************// //BOOK CREATE FUNCTION// //************************************************// void BOOK_CREATE() { BOOK B; char Z='W'; ofstream Q1; Q1.open("d:/swathi/BOOK.dat",ios::binary|ios::out); while(Z=='W') { B.BCREATE(); Q1.write((char*)&B,sizeof(B)); cout<<"\ndo u want to enter another record(W\N):";cin>>Z; } } //************************************************// //BOOK ISSSUE// //************************************************// //BOOK SEARCH FUNCTION// //************************************************// void BBSEARCH() { BOOK B; int T1; cout<<"\n enter book no";cin>>T1; fstream I3; I3.open("d:/swathi/BOOK.dat",ios::in|ios::binary|ios::out); I3.seekg(0,ios::beg); while(!I3.eof()) { I3.read((char*)&B,sizeof(B)); if(T1==B.ret_bno()) { B.set_qty(); B.BDISPLAY(); I3.seekp(I3.tellp()-sizeof(B),ios::beg); I3.write((char*)&B,sizeof(B)); //B.tot_book(); break; } } I3.close(); } //************************************************// void set() { int SNO, flag=0; STUDENT S; cout<<"\nenter STUDENT NO:";cin>>SNO; fstream I; I.open("d:/swathi/STUDENT.dat",ios::binary|ios::in|ios::out); I.seekg(0,ios::beg); while(!I.eof()) { I.read((char*)&S,sizeof(S)); if(SNO==S.ret_roll()) { //BBSEARCH(); flag=1; S.DOI(); I.seekp(I.tellp()-sizeof(S),ios::beg); I.write((char*)&S,sizeof(S)); break; } } if(flag==1) { BBSEARCH(); S.get_nob(); I.seekp(I.tellp()-sizeof(S),ios::beg); I.write((char*)&S,sizeof(S)); I.close(); } else { cout<<"\nStudent not found"; I.close(); } } //************************************************// //BOOK DEPOSIT// //************************************************// //DEPOSIT SEARCH FUNCTION// //************************************************// void DSEARCH() { BOOK B; int T2; cout<<"\n enter book no";cin>>T2; fstream Z3; Z3.open("d:/swathi/BOOK.dat",ios::in|ios::binary|ios::out); Z3.seekg(0,ios::beg); while(!Z3.eof()) { Z3.read((char*)&B,sizeof(B)); if(T2==B.ret_bno()) { B.get_qty(); B.BDISPLAY(); Z3.seekp(Z3.tellp()-sizeof(B),ios::beg); Z3.write((char*)&B,sizeof(B)); //B.tot_book(); break; } } Z3.close(); } //************************************************// void get() { int stno,flag1=0; cout<<"\nenter student no";cin>>stno; STUDENT S; BOOK B; fstream Z; Z.open("d:/swathi/STUDENT.dat",ios::binary|ios::in|ios::out); Z.seekg(0,ios::beg); while(!Z.eof()) { Z.read((char*)&S,sizeof(S)); if(stno==S.ret_roll()) { flag1=1; S.DOR(); Z.seekp(Z.tellp()-sizeof(S),ios::beg); Z.write((char*)&S,sizeof(S)); S.calc_fine(); break; } } if(flag1==1) { DSEARCH(); S.set_nob(); Z.seekp(Z.tellp()-sizeof(S),ios::beg); Z.write((char*)&S,sizeof(S)); S.f_fine(); Z.close(); } else { cout<<"\nStudent not found"; Z.close(); } } void main() { int x,N; char ans='y', ANS='s'; fstream f1; STUDENT S; BOOK B; cout<<"\n MAIN MENU"; while(ans=='y') { MAINMENU: cout<<"\n1.BOOK ISSUE"; cout<<"\n2.BOOK DEPOSIT"; cout<<"\n3.ADMINISTRATOR MENU"; cout<<"\n4.EXIT"; cin>>x; clrscr(); switch(x) { case 1: cout<<"BOOK ISSUE"; set(); cout<<"\nBOOK IS ISSUED"; cout<<"\nNOTE:book must be returned within ten days."; cout<<"\nfine-5 rupee per day"; break; case 2: cout<<"BOOK DEPOSIT"; get(); break; case 3: clrscr(); while(ANS=='s') { cout<<"\n1.CREATE STUDENT RECORD"; cout<<"\n2.DISPLAY ALL STUDENT RECORDS"; cout<<"\n3.DISPLAY SPECIFIC STUDENT RECORD"; cout<<"\n4.MODIFY STUDENT RECORD"; cout<<"\n5.DELETE STUDENT RECORD"; cout<<"\n6.ADD STUDENT RECORD"; cout<<"\n7.CREATE BOOK RECORD"; cout<<"\n8.DISPLAY ALL BOOKS RECORD"; cout<<"\n9.DISPLAY SPECIFIC BOOK RECORD"; cout<<"\n10.MODIFY BOOK RECORD"; cout<<"\n11.DELETE BOOK RECORD"; cout<<"\n12.ADD BOOK RECORD"; cout<<"\n13.BACK TO MAIN MENU"; cin>>N; clrscr(); switch(N) { case 1: cout<<"\nSTUDENT RECORDS"; STUD_CREATE(); break; case 2: STUDENTDISPLAY(); break; case 3: SEARCH(); break; case 4: MODIFY(); break; case 5: DELETE(); break; case 6: ADD(); break; case 7: cout<<"\nBOOK RECORDS"; BOOK_CREATE(); break; case 8: cout<<"\n ALL BOOK RECORDS"; BOOKDISPLAY(); break; case 9: BSEARCH(); break; case 10: BMODIFY(); break; case 11: BDELETE(); break; case 12: BADD(); break; case 13: goto MAINMENU; deafult: cout<<"\nwrong choice."; } cout<<"\nmore operation(s/t)";cin>>ANS; clrscr(); } case 4: exit(0); } cout<<"\nmore operations?(y/n):";cin>>ans; } }
[ "noreply@github.com" ]
ramsai-5A1.noreply@github.com
ed209b6ba2b8017b034ca404332d76bf15b51ce4
d12dde7654b12f40ecd125343d3374672efcc2af
/src/b.LSH/headers/common.hpp
54909d39d6cec6a87633a8dc904b5d8a65073256
[]
no_license
Stefanosdl/Neural_Networks_and_clustering_of_images
30a300289f4bf7fe488ff849548f33f6bd29bb38
7e0c9f66f3ea2d093a9ee03d9a43933fa52dc7f7
refs/heads/main
2023-02-18T20:33:47.761556
2021-01-09T14:36:53
2021-01-09T14:36:53
321,059,013
0
1
null
null
null
null
UTF-8
C++
false
false
194
hpp
// define default values #define INPUT_FILE 0 #define QUERY_FILE 1 #define SUCCESS 0 #define ERROR 1 #define inf 4294967295 extern unsigned int w; extern unsigned int M; extern unsigned int m;
[ "noreply@github.com" ]
Stefanosdl.noreply@github.com
bddec873c29a08479271504dab4d0c1b692050ae
e46b909cdf0361f6c336f532507573c2f592cdf4
/contrib/libs/protobuf/util/internal/protostream_objectsource.h
66ea5bc4884533a8c3176e3cbc75bdf2fa084cf9
[ "Apache-2.0" ]
permissive
exprmntr/test
d25b50881089640e8d94bc6817e9194fda452e85
170138c9ab62756f75882d59fb87447fc8b0f524
refs/heads/master
2022-11-01T16:47:25.276943
2018-03-31T20:56:25
2018-03-31T20:56:25
95,452,782
0
3
Apache-2.0
2022-10-30T22:45:27
2017-06-26T14:04:21
C++
UTF-8
C++
false
false
13,643
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. #ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__ #define GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__ #include <functional> #include "stubs/hash.h" #include "stubs/common.h" #include "type.pb.h" #include "util/internal/object_source.h" #include "util/internal/object_writer.h" #include "util/internal/type_info.h" #include "util/type_resolver.h" #include <contrib/libs/protobuf/stubs/stringpiece.h> #include "stubs/status.h" #include "stubs/statusor.h" namespace google { namespace protobuf { class Field; class Type; } // namespace protobuf namespace protobuf { namespace util { namespace converter { class TypeInfo; // An ObjectSource that can parse a stream of bytes as a protocol buffer. // Its WriteTo() method can be given an ObjectWriter. // This implementation uses a google.protobuf.Type for tag and name lookup. // The field names are converted into lower camel-case when writing to the // ObjectWriter. // // Sample usage: (suppose input is: string proto) // ArrayInputStream arr_stream(proto.data(), proto.size()); // CodedInputStream in_stream(&arr_stream); // ProtoStreamObjectSource os(&in_stream, /*ServiceTypeInfo*/ typeinfo, // <your message google::protobuf::Type>); // // Status status = os.WriteTo(<some ObjectWriter>); class /* LIBPROTOBUF_EXPORT */ ProtoStreamObjectSource : public ObjectSource { public: ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream, TypeResolver* type_resolver, const google::protobuf::Type& type); virtual ~ProtoStreamObjectSource(); virtual util::Status NamedWriteTo(StringPiece name, ObjectWriter* ow) const; // Sets whether or not to use lowerCamelCase casing for enum values. If set to // false, enum values are output without any case conversions. // // For example, if we have an enum: // enum Type { // ACTION_AND_ADVENTURE = 1; // } // Type type = 20; // // And this option is set to true. Then the rendered "type" field will have // the string "actionAndAdventure". // { // ... // "type": "actionAndAdventure", // ... // } // // If set to false, the rendered "type" field will have the string // "ACTION_AND_ADVENTURE". // { // ... // "type": "ACTION_AND_ADVENTURE", // ... // } void set_use_lower_camel_for_enums(bool value) { use_lower_camel_for_enums_ = value; } // Sets the max recursion depth of proto message to be deserialized. Proto // messages over this depth will fail to be deserialized. // Default value is 64. void set_max_recursion_depth(int max_depth) { max_recursion_depth_ = max_depth; } protected: // Writes a proto2 Message to the ObjectWriter. When the given end_tag is // found this method will complete, allowing it to be used for parsing both // nested messages (end with 0) and nested groups (end with group end tag). // The include_start_and_end parameter allows this method to be called when // already inside of an object, and skip calling StartObject and EndObject. virtual util::Status WriteMessage(const google::protobuf::Type& descriptor, StringPiece name, const uint32 end_tag, bool include_start_and_end, ObjectWriter* ow) const; private: ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream, const TypeInfo* typeinfo, const google::protobuf::Type& type); // Function that renders a well known type with a modified behavior. typedef util::Status (*TypeRenderer)(const ProtoStreamObjectSource*, const google::protobuf::Type&, StringPiece, ObjectWriter*); // Looks up a field and verify its consistency with wire type in tag. const google::protobuf::Field* FindAndVerifyField( const google::protobuf::Type& type, uint32 tag) const; // TODO(skarvaje): Mark these methods as non-const as they modify internal // state (stream_). // // Renders a repeating field (packed or unpacked). // Returns the next tag after reading all sequential repeating elements. The // caller should use this tag before reading more tags from the stream. util::StatusOr<uint32> RenderList(const google::protobuf::Field* field, StringPiece name, uint32 list_tag, ObjectWriter* ow) const; // Renders a NWP map. // Returns the next tag after reading all map entries. The caller should use // this tag before reading more tags from the stream. util::StatusOr<uint32> RenderMap(const google::protobuf::Field* field, StringPiece name, uint32 list_tag, ObjectWriter* ow) const; // Renders a packed repeating field. A packed field is stored as: // {tag length item1 item2 item3} instead of the less efficient // {tag item1 tag item2 tag item3}. util::Status RenderPacked(const google::protobuf::Field* field, ObjectWriter* ow) const; // Renders a google.protobuf.Timestamp value to ObjectWriter static util::Status RenderTimestamp(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Renders a google.protobuf.Duration value to ObjectWriter static util::Status RenderDuration(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Following RenderTYPE functions render well known types in // google/protobuf/wrappers.proto corresponding to TYPE. static util::Status RenderDouble(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderFloat(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderInt64(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderUInt64(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderInt32(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderUInt32(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderBool(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderString(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static util::Status RenderBytes(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Renders a google.protobuf.Struct to ObjectWriter. static util::Status RenderStruct(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Helper to render google.protobuf.Struct's Value fields to ObjectWriter. static util::Status RenderStructValue(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Helper to render google.protobuf.Struct's ListValue fields to ObjectWriter. static util::Status RenderStructListValue( const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Render the "Any" type. static util::Status RenderAny(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); // Render the "FieldMask" type. static util::Status RenderFieldMask(const ProtoStreamObjectSource* os, const google::protobuf::Type& type, StringPiece name, ObjectWriter* ow); static hash_map<string, TypeRenderer>* renderers_; static void InitRendererMap(); static void DeleteRendererMap(); static TypeRenderer* FindTypeRenderer(const string& type_url); // Renders a field value to the ObjectWriter. util::Status RenderField(const google::protobuf::Field* field, StringPiece field_name, ObjectWriter* ow) const; // Same as above but renders all non-message field types. Callers don't call // this function directly. They just use RenderField. util::Status RenderNonMessageField(const google::protobuf::Field* field, StringPiece field_name, ObjectWriter* ow) const; // Reads field value according to Field spec in 'field' and returns the read // value as string. This only works for primitive datatypes (no message // types). const string ReadFieldValueAsString( const google::protobuf::Field& field) const; // Utility function to detect proto maps. The 'field' MUST be repeated. bool IsMap(const google::protobuf::Field& field) const; // Utility to read int64 and int32 values from a message type in stream_. // Used for reading google.protobuf.Timestamp and Duration messages. std::pair<int64, int32> ReadSecondsAndNanos( const google::protobuf::Type& type) const; // Helper function to check recursion depth and increment it. It will return // Status::OK if the current depth is allowed. Otherwise an error is returned. // type_name and field_name are used for error reporting. util::Status IncrementRecursionDepth(StringPiece type_name, StringPiece field_name) const; // Input stream to read from. Ownership rests with the caller. google::protobuf::io::CodedInputStream* stream_; // Type information for all the types used in the descriptor. Used to find // google::protobuf::Type of nested messages/enums. const TypeInfo* typeinfo_; // Whether this class owns the typeinfo_ object. If true the typeinfo_ object // should be deleted in the destructor. bool own_typeinfo_; // google::protobuf::Type of the message source. const google::protobuf::Type& type_; // Whether to render enums using lowerCamelCase. Defaults to false. bool use_lower_camel_for_enums_; // Tracks current recursion depth. mutable int recursion_depth_; // Maximum allowed recursion depth. int max_recursion_depth_; // Whether to render unknown fields. bool render_unknown_fields_; GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(ProtoStreamObjectSource); }; } // namespace converter } // namespace util } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_PROTOSTREAM_OBJECTSOURCE_H__
[ "exprmntr@yandex-team.ru" ]
exprmntr@yandex-team.ru
109c6cf5b2f8d28dd9b9255d055de409901993b4
fb72a39f5da510ba346db3073d33c6387760fb93
/ficha.h
ecb6eead10ccdf8555e8b80c3c80000089c9cd76
[ "MIT" ]
permissive
jion/tetrabrick
bcd724e572c907f7fc8c4fb7219ea4decc7e88c7
0946c2528a1e8b13ad7c1835b93934138404c025
refs/heads/master
2021-01-17T12:15:42.512451
2020-03-10T14:35:29
2020-03-10T14:35:29
33,821,988
1
0
null
null
null
null
UTF-8
C++
false
false
706
h
#ifndef ficha_h #define ficha_h #include <SDL/SDL.h> #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; class Ficha { public: int valor; int posicion; bool data[4][4][4]; Ficha( class Galeria *galeria ); ~Ficha(); void imprimir (SDL_Surface *dst, int x = 0, int y = 0); void nueva_ficha(int ficha = 0); void rotar(int lado); // 0 + // 1 - private: class Image *bloques; SDL_Surface *pieza; void actualizar(void); void carga_valores(void); typedef Uint8 data_[4][4]; typedef data_ pieza_[4]; pieza_ fichas[7]; }; #endif
[ "el.manu@gmail.com" ]
el.manu@gmail.com
4461b5f1ac1074311ee33a16e2d870117977669c
9b9b0fd49be3d29b1367e7882c4b69ca4e3118ed
/Source/System/Math/Primitive/Others/Ray.cpp
e622ba288e2fec28980a8f2e64def04fb7612c70
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
arian153/Physics-Project
01e949bc4edf2a5ea3436fe2e85c20c566eae923
4571eab70d0a079358905db8c33230545ffb66b9
refs/heads/main
2023-04-22T13:13:12.557697
2021-04-30T11:48:39
2021-04-30T11:48:39
320,809,601
1
0
null
null
null
null
UTF-8
C++
false
false
13,285
cpp
#include "Ray.hpp" #include "../../Utility/Utility.hpp" #include "Line.hpp" namespace PhysicsProject { Ray::Ray(const Vector3& position, const Vector3& direction) : position(position), direction(direction) { } Ray::Ray(const Ray& rhs) : position(rhs.position), direction(rhs.direction) { } Ray::~Ray() { } Vector3 Ray::ParamToPoint(Real t) const { if (t < 0.0f) { return position; } return position + direction * t; } Real Ray::PointToParam(const Vector3& point_on_ray) const { Vector3 t_dir = point_on_ray - position; Vector3 inv_dir = direction; inv_dir.SetInverse(); Vector3 t_vector = t_dir.HadamardProduct(inv_dir); if (Math::IsValid(t_vector.x) == true) { return t_vector.x; } if (Math::IsValid(t_vector.y) == true) { return t_vector.y; } if (Math::IsValid(t_vector.z) == true) { return t_vector.z; } return 0.0f; } Ray Ray::GetReflectedRay(const Vector3& normal, const Vector3& new_position) const { Vector3 n = normal.Normalize(); Vector3 reflect_direction = -2.0f * DotProduct(direction, n) * n + direction; return Ray(new_position, reflect_direction.Normalize()); } Vector3 Ray::SymmetricPoint(const Vector3& point) const { Vector3 closest = ClosestPoint(point); return closest + closest - point; } Vector3 Ray::ClosestPoint(const Vector3& point) const { Vector3 w = point - position; Real proj = w.DotProduct(direction); // endpoint 0 is closest point if (proj <= 0.0f) { return position; } // somewhere else in ray Real ddd = direction.DotProduct(direction); return position + (proj / ddd) * direction; } Real Ray::Distance(const Vector3& point, Real& t) const { return sqrtf(DistanceSquared(point, t)); } Real Ray::DistanceSquared(const Vector3& point, Real& t) const { Vector3 w = point - position; Real proj = w.DotProduct(direction); // origin is closest point if (proj <= 0) { t = 0.0f; return w.DotProduct(w); } // else use normal line check Real ddd = direction.DotProduct(direction); t = proj / ddd; return w.DotProduct(w) - t * proj; } Vector3Pair Ray::ClosestPoint(const Ray& ray) const { Vector3 w0 = position - ray.position; Real r0d_dot_r0d = direction.DotProduct(direction); Real r0d_dot_r1d = direction.DotProduct(ray.direction); Real r1d_dot_r1d = ray.direction.DotProduct(ray.direction); Real r0d_dot_w = direction.DotProduct(w0); Real r1d_dot_w = ray.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; // parameters to compute s_c, t_c Real s_c, t_c; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // start by clamping s_c sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s_c = 0.0f; } else { s_c = -r0d_dot_w / r0d_dot_r0d; } } else { t_c = tn / td; s_c = sn / sd; } // compute closest points return Vector3Pair(position + s_c * direction, ray.position + t_c * ray.direction); } Ray& Ray::operator=(const Ray& rhs) { if (this != &rhs) { position = rhs.position; direction = rhs.direction; direction.SetNormalize(); } return *this; } bool Ray::operator==(const Ray& rhs) const { return rhs.position == position && rhs.direction == direction; } bool Ray::operator!=(const Ray& rhs) const { return rhs.position != position || rhs.direction != direction; } Real Distance(const Ray& ray0, const Ray& ray1, Real& s, Real& t) { return sqrtf(DistanceSquared(ray0, ray1, s, t)); } Real Distance(const Ray& ray, const Vector3& point, Real& t) { return sqrtf(DistanceSquared(ray, point, t)); } Real Distance(const Ray& ray, const Line& line, Real& s, Real& t) { return sqrtf(DistanceSquared(ray, line, s, t)); } Real Distance(const Line& line, const Ray& ray, Real& s, Real& t) { return sqrtf(DistanceSquared(line, ray, s, t)); } Real DistanceSquared(const Ray& ray0, const Ray& ray1, Real& s, Real& t) { Vector3 w0 = ray0.position - ray1.position; Real r0d_dot_r0d = ray0.direction.DotProduct(ray0.direction); Real r0d_dot_r1d = ray0.direction.DotProduct(ray1.direction); Real r1d_dot_r1d = ray1.direction.DotProduct(ray1.direction); Real r0d_dot_w = ray0.direction.DotProduct(w0); Real r1d_dot_w = ray1.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator) == true) { // clamp s_c to 0 sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // clamp s_c within [0,+inf] sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t within [0,+inf] // clamp t to 0 if (tn < 0.0f) { t = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s = 0.0f; } else { s = -r0d_dot_w / r0d_dot_r0d; } } else { t = tn / td; s = sn / sd; } // compute difference vector and distance squared Vector3 wc = w0 + (ray0.direction * s) - (ray1.direction * t); return wc.DotProduct(wc); } Real DistanceSquared(const Ray& ray, const Vector3& point, Real& t) { Vector3 w = point - ray.position; Real proj = w.DotProduct(ray.direction); // origin is closest point if (proj <= 0) { t = 0.0f; return w.DotProduct(w); } // else use normal line check Real vsq = ray.direction.DotProduct(ray.direction); t = proj / vsq; return w.DotProduct(w) - (proj * t); } Real DistanceSquared(const Ray& ray, const Line& line, Real& s, Real& t) { Vector3 w0 = ray.position - line.position; Real rd_dot_rd = ray.direction.DotProduct(ray.direction); Real rd_dot_ld = ray.direction.DotProduct(line.direction); Real ld_dot_ld = line.direction.DotProduct(line.direction); Real rd_dot_w = ray.direction.DotProduct(w0); Real ld_dot_w = line.direction.DotProduct(w0); Real denominator = rd_dot_rd * ld_dot_ld - rd_dot_ld * rd_dot_ld; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { s = 0.0f; t = ld_dot_w / ld_dot_ld; // compute difference vector and distance squared Vector3 wc = w0 - t * line.direction; return wc.DotProduct(wc); } // clamp s_c within [0,1] Real sn = rd_dot_ld * ld_dot_w - ld_dot_ld * rd_dot_w; // clamp s_c to 0 if (sn < 0.0f) { s = 0.0f; t = ld_dot_w / ld_dot_ld; } // clamp s_c to 1 else if (sn > denominator) { s = 1.0f; t = (ld_dot_w + rd_dot_ld) / ld_dot_ld; } else { s = sn / denominator; t = (rd_dot_rd * ld_dot_w - rd_dot_ld * rd_dot_w) / denominator; } // compute difference vector and distance squared Vector3 wc = w0 + s * ray.direction - t * line.direction; return wc.DotProduct(wc); } Real DistanceSquared(const Line& line, const Ray& ray, Real& s, Real& t) { return DistanceSquared(ray, line, s, t); } Vector3Pair ClosestPoint(const Ray& ray0, const Ray& ray1) { Vector3 w0 = ray0.position - ray1.position; Real r0d_dot_r0d = ray0.direction.DotProduct(ray0.direction); Real r0d_dot_r1d = ray0.direction.DotProduct(ray1.direction); Real r1d_dot_r1d = ray1.direction.DotProduct(ray1.direction); Real r0d_dot_w = ray0.direction.DotProduct(w0); Real r1d_dot_w = ray1.direction.DotProduct(w0); Real denominator = r0d_dot_r0d * r1d_dot_r1d - r0d_dot_r1d * r0d_dot_r1d; // parameters to compute s_c, t_c Real s_c, t_c; Real sn, sd, tn, td; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { sd = td = r1d_dot_r1d; sn = 0.0f; tn = r1d_dot_w; } else { // start by clamping s_c sd = td = denominator; sn = r0d_dot_r1d * r1d_dot_w - r1d_dot_r1d * r0d_dot_w; tn = r0d_dot_r0d * r1d_dot_w - r0d_dot_r1d * r0d_dot_w; // clamp s_c to 0 if (sn < 0.0f) { sn = 0.0f; tn = r1d_dot_w; td = r1d_dot_r1d; } } // clamp t_c within [0,+inf] // clamp t_c to 0 if (tn < 0.0f) { t_c = 0.0f; // clamp s_c to 0 if (-r0d_dot_w < 0.0f) { s_c = 0.0f; } else { s_c = -r0d_dot_w / r0d_dot_r0d; } } else { t_c = tn / td; s_c = sn / sd; } // compute closest points return Vector3Pair(ray0.position + s_c * ray0.direction, ray1.position + t_c * ray1.direction); } Vector3Pair ClosestPoint(const Ray& ray, const Line& line) { // compute intermediate parameters Vector3Pair result; Vector3 w0 = ray.position - line.position; Real rd_dot_rd = ray.direction.DotProduct(ray.direction); Real rd_dot_ld = ray.direction.DotProduct(line.direction); Real ld_dot_ld = line.direction.DotProduct(line.direction); Real rd_dot_w = ray.direction.DotProduct(w0); Real ld_dot_w = line.direction.DotProduct(w0); Real denominator = rd_dot_rd * ld_dot_ld - rd_dot_ld * rd_dot_ld; // if denominator is zero, try finding closest point on ray1 to origin0 if (Math::IsZero(denominator)) { // compute closest points result.a = ray.position; result.b = line.position + (ld_dot_w / ld_dot_ld) * line.direction; } else { // parameters to compute s_c, t_c Real s_c, t_c; // clamp s_c within [0,1] Real sn = rd_dot_ld * ld_dot_w - ld_dot_ld * rd_dot_w; // clamp s_c to 0 if (sn < 0.0f) { s_c = 0.0f; t_c = ld_dot_w / ld_dot_ld; } // clamp s_c to 1 else if (sn > denominator) { s_c = 1.0f; t_c = (ld_dot_w + rd_dot_ld) / ld_dot_ld; } else { s_c = sn / denominator; t_c = (rd_dot_rd * ld_dot_w - rd_dot_ld * rd_dot_w) / denominator; } // compute closest points result.a = ray.position + s_c * ray.direction; result.b = line.position + t_c * line.direction; } return result; } }
[ "p084111@gmail.com" ]
p084111@gmail.com
9cabf73d8871360ef6c37907db51de4cf25b055d
1e257f46d039238e5d13817c218afc7e24a91cc9
/655267/2 刮刮樂.cpp
2ef7637644aa9b153e66a3f6bf59f5fe16ff49bd
[]
no_license
firedragon0314/20200528-toi
24bbd0d7efe593d53e94bcd5a7c5200057abc089
6852c598b4d68bc2c4281cdc0761dc83584c4ee5
refs/heads/master
2022-09-20T01:45:05.661881
2020-06-03T16:30:58
2020-06-03T16:30:58
269,138,649
0
0
null
2020-06-03T16:26:11
2020-06-03T16:26:10
null
UTF-8
C++
false
false
701
cpp
#include <iostream> using namespace std; int main() { int a[3],b[2][5],total = 0; bool check = false; for(int i = 0; i < 3; i++){ cin >> a[i]; } for(int i = 0; i < 2; i++){ for(int y = 0; y < 5; y++){ cin >> b[i][y]; } } for(int i = 0; i < 3; i++){ for(int y = 0; y < 5; y++){ if((i == 0 || i == 1) && a[i] == b[0][y]){ total += b[1][y]; }else if(i == 2 && a[i] == b [0][y]){ check = true; total -= b[1][y]; } } } if(check == false){ total *= 2; }else if(total < 0){ total = 0; } cout << total; }
[ "noreply@github.com" ]
firedragon0314.noreply@github.com
e06aa2ce7e88d706576ff9d6ff2ee2585f29a3b9
9ef5662fa65ca9793577d5151fcf4a7b82ef300f
/P5/SDLProject/Entity.h
d3861a3eaa62f8d6920c4ab2a0703d7f5f2a1539
[]
no_license
lsemenuk/CS3113
ab9a5261b7f2f261350b170fa0d8b576d65d2de8
ef46502117638622bb96957ccf9994a4010f70ba
refs/heads/master
2022-12-02T23:15:14.105027
2020-08-14T21:31:37
2020-08-14T21:31:37
267,184,503
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
h
#pragma once #define GL_SILENCE_DEPRECATION #ifdef _WINDOWS #include <GL/glew.h> #endif #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_opengl.h> #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "ShaderProgram.h" #include "Map.h" enum EntityType { PLAYER, PLATFORM, ENEMY }; enum AIType { STAGE1, STAGE2, STAGE3 }; enum AIState { IDLE, WALKING, ATTACKING, CHARGING, }; class Entity { public: EntityType entityType; AIType aiType; AIState aiState; Entity *lastCollided = NULL; glm::vec3 position; glm::vec3 movement; glm::vec3 acceleration; glm::vec3 velocity; float width = .8; float height = .8; bool jump = false; float jumpPower = 0; float speed; GLuint textureID; glm::mat4 modelMatrix; int *animRight = NULL; int *animLeft = NULL; int *animUp = NULL; int *animDown = NULL; int *animIndices = NULL; int animFrames = 0; int animIndex = 0; float animTime = 0; int animCols = 0; int animRows = 0; bool isActive = true; bool collidedTop = false; bool collidedBottom = false; bool collidedLeft = false; bool collidedRight = false; bool collidedEnemyBottom = false; bool lostLife = false; bool gameOver = false; bool gameWin = false; Entity(); bool CheckCollision(Entity *other); void CheckCollisionsY(Entity *objects, int objectCount); void CheckCollisionsX(Entity *objects, int objectCount); void CheckCollisionsX(Map *map); void CheckCollisionsY(Map *map); void Update(float deltaTime, Entity *player, Entity *objects, int objectCount, Map *map, int *lives); void Render(ShaderProgram *program); void DrawSpriteFromTextureAtlas(ShaderProgram *program, GLuint textureID, int index); void AI(Entity *player); void AIWalker(); void AIWaitAndCharge(Entity *player); void AIJumpAndFollow(Entity *player); void AIPatrol(Entity *player); void AIPatrolLevel3(Entity *player); };
[ "ls4508@nyu.edu" ]
ls4508@nyu.edu
ee2cb507c1b5f24ffcd6d71f493443fbdabb4e34
923e7df48e06716797ba0010e07c6d49c87754cc
/internal/core/unittest/test_bf.cpp
8863cf1473f19e829171444ebdde94868895c14b
[ "Apache-2.0" ]
permissive
xiaocai2333/milvus
b22269545f7b9f3f52a59a5f35422018c08fe8ff
82edb4d2df25b289fb5b5fe364e693f50f9a170f
refs/heads/master
2023-08-28T12:43:43.095519
2023-01-05T07:33:39
2023-01-05T07:33:39
219,463,625
1
0
Apache-2.0
2019-11-04T09:28:29
2019-11-04T09:28:28
null
UTF-8
C++
false
false
4,593
cpp
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License #include <gtest/gtest.h> #include <random> #include "common/Utils.h" #include "knowhere/index/vector_index/helpers/IndexParameter.h" #include "query/SearchBruteForce.h" #include "test_utils/Distance.h" #include "test_utils/DataGen.h" using namespace milvus; using namespace milvus::segcore; using namespace milvus::query; namespace { auto GenFloatVecs(int dim, int n, const knowhere::MetricType& metric, int seed = 42) { auto schema = std::make_shared<Schema>(); auto fvec = schema->AddDebugField("fvec", DataType::VECTOR_FLOAT, dim, metric); auto dataset = DataGen(schema, n, seed); return dataset.get_col<float>(fvec); } // (offset, distance) std::vector<std::tuple<int, float>> Distances(const float* base, const float* query, // one query. int nb, int dim, const knowhere::MetricType& metric) { if (milvus::IsMetricType(metric, knowhere::metric::L2)) { std::vector<std::tuple<int, float>> res; for (int i = 0; i < nb; i++) { res.emplace_back(i, L2(base + i * dim, query, dim)); } return res; } else if (milvus::IsMetricType(metric, knowhere::metric::IP)) { std::vector<std::tuple<int, float>> res; for (int i = 0; i < nb; i++) { res.emplace_back(i, IP(base + i * dim, query, dim)); } return res; } else { PanicInfo("invalid metric type"); } } std::vector<int> GetOffsets(const std::vector<std::tuple<int, float>>& tuples, int k) { std::vector<int> offsets; for (int i = 0; i < k; i++) { auto [offset, distance] = tuples[i]; offsets.push_back(offset); } return offsets; } // offsets std::vector<int> Ref(const float* base, const float* query, // one query. int nb, int dim, int topk, const knowhere::MetricType& metric) { auto res = Distances(base, query, nb, dim, metric); std::sort(res.begin(), res.end()); if (milvus::IsMetricType(metric, knowhere::metric::L2)) { // do nothing } else if (milvus::IsMetricType(metric, knowhere::metric::IP)) { std::reverse(res.begin(), res.end()); } else { PanicInfo("invalid metric type"); } return GetOffsets(res, topk); } bool AssertMatch(const std::vector<int>& ref, const int64_t* ans) { for (int i = 0; i < ref.size(); i++) { if (ref[i] != ans[i]) { return false; } } return true; } bool is_supported_float_metric(const std::string& metric) { return milvus::IsMetricType(metric, knowhere::metric::L2) || milvus::IsMetricType(metric, knowhere::metric::IP); } } // namespace class TestFloatSearchBruteForce : public ::testing::Test { public: void Run(int nb, int nq, int topk, int dim, const knowhere::MetricType& metric_type) { auto bitset = std::make_shared<BitsetType>(); bitset->resize(nb); auto bitset_view = BitsetView(*bitset); auto base = GenFloatVecs(dim, nb, metric_type); auto query = GenFloatVecs(dim, nq, metric_type); dataset::SearchDataset dataset{metric_type, nq, topk, -1, dim, query.data()}; if (!is_supported_float_metric(metric_type)) { // Memory leak in knowhere. // ASSERT_ANY_THROW(BruteForceSearch(dataset, base.data(), nb, bitset_view)); return; } auto result = BruteForceSearch(dataset, base.data(), nb, bitset_view); for (int i = 0; i < nq; i++) { auto ref = Ref(base.data(), query.data() + i * dim, nb, dim, topk, metric_type); auto ans = result.get_seg_offsets() + i * topk; AssertMatch(ref, ans); } } }; TEST_F(TestFloatSearchBruteForce, L2) { Run(100, 10, 5, 128, "L2"); Run(100, 10, 5, 128, "l2"); } TEST_F(TestFloatSearchBruteForce, IP) { Run(100, 10, 5, 128, "IP"); Run(100, 10, 5, 128, "ip"); } TEST_F(TestFloatSearchBruteForce, NotSupported) { Run(100, 10, 5, 128, "aaaaaaaaaaaa"); }
[ "noreply@github.com" ]
xiaocai2333.noreply@github.com
24ff7f5b273714ec781324349f641ea696872520
19531eb1f498ad7273bcec961b34e9de79fd9381
/cservan/MWERalign-master/src/Evaluator_unsegmentedWER.hh
2e7b79bf6dee8e6248cca65a64a9aa8a2b76367a
[]
no_license
Trialp/Ressources_GETALP
106e8616cef17510037bfd8af5a15511779842f7
e728f4ece5ac344ad57c1cc7eddc8bf9cfa4bcd2
refs/heads/master
2020-03-07T05:16:01.590588
2018-04-04T14:18:47
2018-04-04T14:18:47
127,291,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,124
hh
/*-------------------------------------------------------------- Copyright 2006 (c) by RWTH Aachen - Lehrstuhl fuer Informatik 6 Richard Zens, Evgeny Matusov, Gregor Leusch --------------------------------------------------------------- This header file is part of the MwerAlign C++ Library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef EVALUATOR_UNSEGMENTEDWER_HH_ #define EVALUATOR_UNSEGMENTEDWER_HH_ #include "Evaluator.hh" #include <map> #include <set> using namespace std; class Evaluator_unsegmentedWER : public Evaluator { public: typedef Evaluator::hyptype hyptype; typedef Evaluator::HypContainer HypContainer; typedef struct DP_ { unsigned int cost; unsigned int bp; } DP; typedef std::vector<std::vector<DP> > Matrix; Evaluator_unsegmentedWER(); Evaluator_unsegmentedWER(const std::string& refFile); ~Evaluator_unsegmentedWER() {} double _evaluate2(const HypContainer& hyps, std::ostream& out) const; double _evaluate2(const HypContainer& hyps, const HypContainer& hypsBi, std::ostream& out) const; double _evaluate(const HypContainer& hyps) const { return _evaluate2(hyps, std::cout); } double _evaluate_abs(const HypContainer&) const { return 0.0; }; std::string name() const; void setInsertionCosts(double x) {ins_=x;} void setDeletionCosts(double x) {del_=x;} virtual bool initrefs() { return true; } void setOptions(const double maxER, const bool human) { maxER_ = maxER; human_ = human; } protected: double computeSpecialWER(const std::vector<std::vector<unsigned int> >& A, const std::vector<unsigned int>& B, unsigned int nSegments) const; unsigned int getVocIndex(const std::string& word) const; unsigned int getSubstitutionCosts(const uint a, const uint b) const; unsigned int getInsertionCosts(const uint w) const; unsigned int additionalInsertionCosts(const uint w, const uint w2=0) const; unsigned int getDeletionCosts(const uint w) const; double ins_,del_; void fillPunctuationSet(); private: unsigned int segmentationWord; double maxER_; bool human_; mutable unsigned int refLength_; mutable unsigned int vocCounter_; mutable std::map<std::string,unsigned int> vocMap_; mutable std::set<unsigned int> punctuationSet_; mutable std::vector<unsigned int> boundary; mutable std::vector<unsigned int> sentCosts; }; #endif
[ "initial@athena5.imag.fr" ]
initial@athena5.imag.fr
61aa9de08c5ecf8ca4bb8c8e2806be2d1f89a0f1
888ff1ff4f76c61e0a2cff281f3fae2c9a4dcb7b
/C/C200/C230/C236/1.cpp
5fd04a813965d37db35728ca035a9cee196df843
[]
no_license
sanjusss/leetcode-cpp
59e243fa41cd5a1e59fc1f0c6ec13161fae9a85b
8bdf45a26f343b221caaf5be9d052c9819f29258
refs/heads/master
2023-08-18T01:02:47.798498
2023-08-15T00:30:51
2023-08-15T00:30:51
179,413,256
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
/* * @Author: sanjusss * @Date: 2021-04-11 10:31:51 * @LastEditors: sanjusss * @LastEditTime: 2021-04-11 10:33:19 * @FilePath: \C\C200\C230\C236\1.cpp */ #include "leetcode.h" class Solution { public: int arraySign(vector<int>& nums) { int sign = 1; for (int i : nums) { if (i == 0) { return 0; } else if (i < 0) { sign *= -1; } } return sign; } };
[ "sanjusss@qq.com" ]
sanjusss@qq.com
39a5c59db82d2e73c7893bcc582794792e2fa6c0
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/cdc/include/tencentcloud/cdc/v20201214/model/ModifyDedicatedClusterInfoResponse.h
e5f1ce5239fd2e4ed8cde99b4cdd799f2b453acf
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
1,686
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_ #define TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cdc { namespace V20201214 { namespace Model { /** * ModifyDedicatedClusterInfo返回参数结构体 */ class ModifyDedicatedClusterInfoResponse : public AbstractModel { public: ModifyDedicatedClusterInfoResponse(); ~ModifyDedicatedClusterInfoResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; private: }; } } } } #endif // !TENCENTCLOUD_CDC_V20201214_MODEL_MODIFYDEDICATEDCLUSTERINFORESPONSE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
7b659d4b8492dfd26232988ddfd5359a133d6c45
77a091c62781f6aefeebdfd6efd4bab9caa51465
/Done/main/mon.cpp
abd7c73ba2761e597109d329fe43eff048d1ec2a
[]
no_license
breno-helf/Maratona
55ab11264f115592e1bcfd6056779a3cf27e44dc
c6970bc554621746cdb9ce53815b8276a4571bb3
refs/heads/master
2021-01-23T21:31:05.267974
2020-05-05T23:25:23
2020-05-05T23:25:23
57,412,343
1
2
null
2017-01-25T14:58:46
2016-04-29T20:54:08
C++
UTF-8
C++
false
false
702
cpp
#include <bits/stdc++.h> using namespace std; #define debug(args...) fprintf(stderr,args) #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const int MAX = 1e6 + 2; const int INF = 0x3f3f3f3f; const ll MOD = 1000000007; int n, k; char s[MAX]; map<ll, int> M; int main () { scanf("%d%d", &n, &k); scanf(" %s", s); ll sum = 0; int resp = 0; for (int i = 0; i < n; i++) { if (s[i] == 'O') sum++; else sum -= k; if (!sum) resp = i + 1; else if (M.find(sum) != M.end()) { resp = (i - M[sum] > resp) ? i - M[sum] : resp; } else { M[sum] = i; } } printf("%d\n", resp); return 0; }
[ "breno.moura@hotmail.com" ]
breno.moura@hotmail.com
094d0f0a877564aeac36fa8e32505a80f4934f43
b6790e0d113b82bf0064220d0b469cfe77d21d78
/Source/tasks/VideoUpdate.cpp
85fb6afbb45068532025ed169d3ba71835f765bd
[]
no_license
spykedood/Oh-My-Buddha
e2c2a4d0ae5a39958cca8e3f0de2b31438b5c2e7
20c632c55afda0482267c7d4528f88c387c2098d
refs/heads/master
2021-01-17T12:19:23.311953
2012-10-17T20:16:14
2012-10-17T20:16:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,610
cpp
#include <SDL.h> #include <SDL_ttf.h> #include <GL/glew.h> #include "VideoUpdate.h" #include "../game.h" #include "../utilities/VarManager.h" #include "../utilities/xml.h" #include "../utilities/types.h" int VideoUpdate::scrWidth; int VideoUpdate::scrHeight; int VideoUpdate::scrBPP; int VideoUpdate::fullScrn; bool VideoUpdate::scrResized; VideoUpdate::VideoUpdate() { } VideoUpdate::~VideoUpdate() { } bool VideoUpdate::Start() { SINGLETON_GET(VarManager, var) XMLFile file; GET_PATH("\\Data\\", path) if (file.load(path + "Settings\\omb.cfg")) { file.setElement("graphics"); scrWidth = file.readInt("graphics", "width"); scrHeight = file.readInt("graphics", "height"); scrBPP = file.readInt("graphics", "bpp"); fullScrn = (file.readString("graphics", "fullscreen") == "true") ? true : false; } else { const SDL_VideoInfo* video = SDL_GetVideoInfo(); scrWidth = 800; scrHeight = 600; scrBPP = 32;// video->vfmt->BitsPerPixel; fullScrn = false; } screenWidth = scrWidth; var.set("win_width", scrWidth); screenHeight=scrHeight; var.set("win_height", scrHeight); screenBPP=scrBPP; fullScreen=fullScrn; var.set("win_fullScreen", fullScrn); scrResized = false; if(-1==SDL_InitSubSystem(SDL_INIT_VIDEO)) { printf("Error: %c", SDL_GetError()); return false; } SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // Set title to build stamp and set icon SDL_WM_SetCaption("Oh My Buddha!", "OMB"); std::string myIcon = path + "OMG.ico"; SDL_Surface* Icon = SDL_LoadBMP(myIcon.c_str()); SDL_WM_SetIcon(Icon, NULL); if(fullScrn != true){ flags = SDL_OPENGL | SDL_RESIZABLE | SDL_ASYNCBLIT | SDL_HWSURFACE; SDL_putenv("SDL_VIDEO_CENTERED=center"); //Center the game Window }else{ flags = SDL_OPENGL | SDL_ANYFORMAT | SDL_FULLSCREEN | SDL_HWSURFACE; } if( ( SDL_SetVideoMode(scrWidth, scrHeight, scrBPP, flags) ) == false ) { printf("Error: SDL_SetVideoMode(%i, %i, %i) : %s", scrWidth, scrHeight, scrBPP, SDL_GetError()); return false; } // Hide the mouse cursor SDL_ShowCursor(var.getb("mouseEnabled")); // Enable fonts if (TTF_Init() == -1) printf("ERROR: TTF_Init() : %s", TTF_GetError()); // Enable GLEW for Shaders GLenum err = glewInit(); if (GLEW_OK != err) printf("ERROR: TTF_Init() : %s", glewGetErrorString(err)); return true; } void VideoUpdate::Update() { SINGLETON_GET(VarManager, var) // Check for window events SDL_Event test_event; while(SDL_PollEvent(&test_event)) { switch (test_event.type) { case SDL_ACTIVEEVENT: if( ( test_event.active.state & SDL_APPACTIVE ) || ( test_event.active.state & SDL_APPINPUTFOCUS ) ) // ICONIFIED or restored { if( test_event.active.gain == 0 ) { var.set("hasFocus", false); var.set("mouseEnabled", true); } else { var.set("hasFocus", true); var.set("mouseEnabled", false); } } break; case SDL_VIDEORESIZE: // Adjusted screen size. scrWidth = test_event.resize.w; var.set("win_width", scrWidth); scrHeight = test_event.resize.h; var.set("win_height", scrHeight); scrResized = true; break; case SDL_QUIT: // Pressed 'x'. exit(0); break; } } // Show or hide mouse SDL_ShowCursor(var.getb("mouseEnabled")); SDL_GL_SwapBuffers(); } void VideoUpdate::Stop() { SDL_QuitSubSystem(SDL_INIT_VIDEO); //TODO: FIX ON EXIT ERROR TTF_Quit(); }
[ "msleith@cngames.co.uk" ]
msleith@cngames.co.uk
ffeb1e40bda9195a71b9e93f296a6f8ade9c312a
d6b742de2c20c67e2afcb36fa8f4b0b5deb78c77
/plotscript.cpp
07d8365e01863697400e3164ecc3803d802bfa1b
[]
no_license
hqt286/Plot-Script
a58e4a97261d903bddbdd6577599111c24b75200
cb8babc0f644bb1b3e17163e5cd14fd1991918de
refs/heads/master
2020-04-12T04:48:54.427447
2018-12-18T16:22:22
2018-12-18T16:22:22
162,306,552
1
0
null
null
null
null
UTF-8
C++
false
false
4,251
cpp
#include <string> #include <sstream> #include <iostream> #include <fstream> #include <thread> #include "startup_config.hpp" #include "interpreter.hpp" #include "semantic_error.hpp" #include "cntlc_tracer.hpp" typedef message_queue<std::string> MessageQueueStr; void repl(Interpreter interp); void prompt() { std::cout << "\nplotscript> "; } std::string readline() { std::string line; std::getline(std::cin, line); return line; } void error(const std::string & err_str) { std::cerr << "Error: " << err_str << std::endl; } void info(const std::string & err_str) { std::cout << "Info: " << err_str << std::endl; } int eval_from_stream(std::istream & stream, std::string filename) { Interpreter interp; if (!interp.parseStream(stream)) { error("Invalid Program. Could not parse."); return EXIT_FAILURE; } else { try { Expression exp = interp.evaluate(); std::cout << exp << std::endl; } catch (const SemanticError & ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } } if (filename == STARTUP_FILE) repl(interp); return EXIT_SUCCESS; } int eval_from_file(std::string filename) { std::ifstream ifs(filename); if (!ifs) { error("Could not open file for reading."); return EXIT_FAILURE; } return eval_from_stream(ifs, filename); } int eval_from_command(std::string argexp) { std::istringstream expression(argexp); return eval_from_stream(expression, "no_file"); } void ProcessData(MessageQueueStr * msgIn, MessageQueueStr * msgOut, Interpreter * interp) { while (1) { std::string popMessage; msgIn->wait_and_pop(popMessage); if (popMessage == "%stop") break; std::istringstream expMsg(popMessage); std::ostringstream textOutput; if (!interp->parseStream(expMsg)) { msgOut->push("Invalid Expression. Could not parse."); } else { try { Expression exp = interp->evaluate(); textOutput << exp; msgOut->push(textOutput.str()); } catch (const SemanticError & ex) { textOutput << ex.what(); msgOut->push(textOutput.str()); } } } } // A REPL is a repeated read-eval-print loop void repl(Interpreter interp) { bool reset = false; install_handler(); while (1) { global_status_flag = 0; Interpreter InscopeInterp(interp); MessageQueueStr * msgIn = new MessageQueueStr(); MessageQueueStr * msgOut = new MessageQueueStr(); bool KernalRunning = true; std::thread * worker; worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); std::string textOutput; while (!std::cin.eof()) { if (reset) { reset = false; break; } prompt(); std::string line = readline(); if (line.empty()) continue; if (line == "%exit") { msgIn->push("%stop"); worker->join(); return; } if (line == "%stop" && KernalRunning == true) { msgIn->push(line); worker->join(); KernalRunning = false; } else if (line == "%start" && KernalRunning == false) { worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); KernalRunning = true; } else if (line == "%reset") { if (KernalRunning == true) { msgIn->push("%stop"); worker->join(); } reset = true; } else if (KernalRunning == false) { std::cout << "Error: interpreter kernel not running"; continue; } else { msgIn->push(line); while (!msgOut->try_pop(textOutput)) { if (global_status_flag > 0) { global_status_flag = 0; std::cout << "Error: interpreter kernel interrupted"; msgIn->push("%stop"); worker->detach(); worker->~thread(); msgIn = new MessageQueueStr(); msgOut = new MessageQueueStr(); InscopeInterp = interp; worker = new std::thread(ProcessData, msgIn, msgOut, &InscopeInterp); break; } if (msgOut->try_pop(textOutput)) break; } std::cout << textOutput; } } } } int main(int argc, char *argv[]) { if (argc == 2) { return eval_from_file(argv[1]); } else if (argc == 3) { if (std::string(argv[1]) == "-e") { return eval_from_command(argv[2]); } else { error("Incorrect number of command line arguments."); } } else { eval_from_file(STARTUP_FILE); } return EXIT_SUCCESS; }
[ "hqt286@vt.edu" ]
hqt286@vt.edu
71ab6c9395fd926ab847a0d3c2f50e7518ed573f
6dedc5c204ac18abee11159ffe0bcc300be61c5a
/signalAndSlot/student.cpp
75264368d46f11cb6d0083d9eff7e58b8321e503
[]
no_license
MrDalili/qtStudy
ad364cd8b91212a8bb7f3916b1abf7653888d5c0
febd2cfbbb04f0b99038ccac78a48c4247ea5451
refs/heads/master
2020-08-04T04:32:13.014803
2019-11-17T04:09:15
2019-11-17T04:09:15
212,006,597
0
0
null
null
null
null
UTF-8
C++
false
false
255
cpp
#include "student.h" #include <QDebug> Student::Student(QObject *parent) : QObject(parent) { } void Student::treat(){ qDebug() << "请老师吃饭"; } void Student::treat(QString food){ qDebug() << "请老师吃饭" << food.toUtf8().data(); }
[ "275482839@qq.com" ]
275482839@qq.com
2509fdbb377a57a44bcac8d0922f53bd8b612f32
96730d79a4f1e874944869458cf76c38d5926bbf
/src/qt/miningpage.cpp
c1d9c02b0689134dff80d0594f9c50098df3cf9f
[ "MIT" ]
permissive
HorseCoinProject/Horsecoin
ae40225796570af2211da20d4af07adab101f46f
057bdf236c1d71d5986be469e1f197f345d3bc0c
refs/heads/master
2016-08-06T16:58:33.284292
2014-03-08T14:57:55
2014-03-08T14:57:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,679
cpp
#include "miningpage.h" #include "ui_miningpage.h" MiningPage::MiningPage(QWidget *parent) : QWidget(parent), ui(new Ui::MiningPage) { ui->setupUi(this); setFixedSize(400, 420); minerActive = false; minerProcess = new QProcess(this); minerProcess->setProcessChannelMode(QProcess::MergedChannels); readTimer = new QTimer(this); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; initThreads = 0; connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput())); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed())); connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int))); connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool))); connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted())); connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError))); connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished())); connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput())); } MiningPage::~MiningPage() { minerProcess->kill(); delete ui; } void MiningPage::setModel(ClientModel *model) { this->model = model; loadSettings(); bool pool = model->getMiningType() == ClientModel::PoolMining; ui->threadsBox->setValue(model->getMiningThreads()); ui->typeBox->setCurrentIndex(pool ? 1 : 0); // if (model->getMiningStarted()) // startPressed(); } void MiningPage::startPressed() { initThreads = ui->threadsBox->value(); if (minerActive == false) { saveSettings(); if (getMiningType() == ClientModel::SoloMining) minerStarted(); else startPoolMining(); } else { if (getMiningType() == ClientModel::SoloMining) minerFinished(); else stopPoolMining(); } } void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); if (!url.contains("http://")) url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text()); args << "--algo" << "scrypt"; args << "--scantime" << ui->scantimeBox->text().toAscii(); args << "--url" << urlLine.toAscii(); args << "--userpass" << userpassLine.toAscii(); args << "--threads" << ui->threadsBox->text().toAscii(); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is needed for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. QString program = QDir::current().filePath("minerd"); if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) ui->list->addItem(args.join(" ").prepend(" ").prepend(program)); ui->mineSpeedLabel->setText("Speed: N/A"); ui->shareCount->setText("Accepted: 0 - Rejected: 0"); minerProcess->start(program,args); minerProcess->waitForStarted(-1); readTimer->start(500); } void MiningPage::stopPoolMining() { ui->mineSpeedLabel->setText(""); minerProcess->kill(); readTimer->stop(); } void MiningPage::saveSettings() { model->setMiningDebug(ui->debugCheckBox->isChecked()); model->setMiningScanTime(ui->scantimeBox->value()); model->setMiningServer(ui->serverLine->text()); model->setMiningPort(ui->portLine->text()); model->setMiningUsername(ui->usernameLine->text()); model->setMiningPassword(ui->passwordLine->text()); } void MiningPage::loadSettings() { ui->debugCheckBox->setChecked(model->getMiningDebug()); ui->scantimeBox->setValue(model->getMiningScanTime()); ui->serverLine->setText(model->getMiningServer()); ui->portLine->setText(model->getMiningPort()); ui->usernameLine->setText(model->getMiningUsername()); ui->passwordLine->setText(model->getMiningPassword()); } void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("(yay!!!)")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("(booooo)")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/s")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(8); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } } void MiningPage::minerError(QProcess::ProcessError error) { if (error == QProcess::FailedToStart) { reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as HorseCoin-Qt.", ERROR, NULL); } } void MiningPage::minerFinished() { if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining stopped.", ERROR, NULL); else reportToList("Miner exited.", ERROR, NULL); ui->list->addItem(""); minerActive = false; resetMiningButton(); model->setMining(getMiningType(), false, initThreads, 0); } void MiningPage::minerStarted() { if (!minerActive) if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining started.", ERROR, NULL); else reportToList("Miner started. You might not see any output for a few minutes.", STARTED, NULL); minerActive = true; resetMiningButton(); model->setMining(getMiningType(), true, initThreads, 0); } void MiningPage::updateSpeed() { double totalSpeed=0; int totalThreads=0; QMapIterator<int, double> iter(threadSpeed); while(iter.hasNext()) { iter.next(); totalSpeed += iter.value(); totalThreads++; } // If all threads haven't reported the hash speed yet, make an assumption if (totalThreads != initThreads) { totalSpeed = (totalSpeed/totalThreads)*initThreads; } QString speedString = QString("%1").arg(totalSpeed); QString threadsString = QString("%1").arg(initThreads); QString acceptedString = QString("%1").arg(acceptedShares); QString rejectedString = QString("%1").arg(rejectedShares); QString roundAcceptedString = QString("%1").arg(roundAcceptedShares); QString roundRejectedString = QString("%1").arg(roundRejectedShares); if (totalThreads == initThreads) ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); else ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString)); model->setMining(getMiningType(), true, initThreads, totalSpeed*1000); } void MiningPage::reportToList(QString msg, int type, QString time) { QString message; if (time == NULL) message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg); else message = QString("[%1] - %2").arg(time, msg); switch(type) { case SHARE_SUCCESS: acceptedShares++; roundAcceptedShares++; updateSpeed(); break; case SHARE_FAIL: rejectedShares++; roundRejectedShares++; updateSpeed(); break; case LONGPOLL: roundAcceptedShares = 0; roundRejectedShares = 0; break; default: break; } ui->list->addItem(message); ui->list->scrollToBottom(); } // Function for fetching the time QString MiningPage::getTime(QString time) { if (time.contains("[")) { time.resize(21); time.remove("["); time.remove("]"); time.remove(0,11); return time; } else return NULL; } void MiningPage::enableMiningControls(bool enable) { ui->typeBox->setEnabled(enable); ui->threadsBox->setEnabled(enable); ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } void MiningPage::enablePoolMiningControls(bool enable) { ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } ClientModel::MiningType MiningPage::getMiningType() { if (ui->typeBox->currentIndex() == 0) // Solo Mining { return ClientModel::SoloMining; } else if (ui->typeBox->currentIndex() == 1) // Pool Mining { return ClientModel::PoolMining; } return ClientModel::SoloMining; } void MiningPage::typeChanged(int index) { if (index == 0) // Solo Mining { enablePoolMiningControls(false); } else if (index == 1) // Pool Mining { enablePoolMiningControls(true); } } void MiningPage::debugToggled(bool checked) { model->setMiningDebug(checked); } void MiningPage::resetMiningButton() { ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining"); enableMiningControls(!minerActive); }
[ "jack@jack-desktop.(none)" ]
jack@jack-desktop.(none)
89df47c8a1ee872b4f921051dc543be6aece782d
08278b638a0c44e7a3951f2a5f5d72d33f610682
/MummyDiner/state/LevelScreen.h
aa03e238494085e8311f86f3b5a5cd9d6aa99ca6
[]
no_license
muhdmirzamz/MummyDiner
f486446c74290c959fd3bae8dbaeed96f0a475df
ce55023acc138638dc1cb3fc8360e4fad9b7bc18
refs/heads/master
2021-01-01T16:00:25.059462
2015-12-15T12:04:07
2015-12-15T12:04:07
31,579,910
1
0
null
2015-04-25T12:05:44
2015-03-03T04:48:03
C++
UTF-8
C++
false
false
1,405
h
// // LevelScreen.h // MummyDiner // // Created by Muhd Mirza on 5/1/15. // Copyright (c) 2015 Muhd Mirza. All rights reserved. // #ifndef __MummyDiner__LevelScreen__ #define __MummyDiner__LevelScreen__ #include "GameState.h" #include "GameOverScreen.h" class LevelScreen: public GameState { public: static bool normalMode; LevelScreen(); void handleEvent(); void spawnCustomer(); void moveCharacter(); void checkCollision(); void update(); void render(); void cleanupLevelScreen(int state); private: SpriteClass *_waitress; Waitress _waitressObj; SpriteClass *_customer; Customer _customerObj; SpriteClass *_topWalkingCustomer; Customer _topWalkingCustomerObj; SpriteClass *_bottomWalkingCustomer; Customer _bottomWalkingCustomerObj; SpriteClass *_chef; Chef _chefObj; SpriteClass _topLeftTable; SpriteClass _topRightTable; SpriteClass _bottomLeftTable; SpriteClass _bottomRightTable; SpriteClass _counter; SpriteClass _stove; BackgroundClass _backgroundArr[5]; BackgroundClass _topLeftBackground; BackgroundClass _topRightBackground; BackgroundClass _bottomLeftBackground; BackgroundClass _bottomRightBackground; BackgroundClass _foodPickupBackground; ButtonClass _lsBackToMenuButton; MenuSystem _menuSystem; int _mouseClickX; int _mouseClickY; }; #endif /* defined(__MummyDiner__LevelScreen__) */
[ "muhdmirzamz@gmail.com" ]
muhdmirzamz@gmail.com
935b7906fa0d013ab04fbad50b0109663462b879
3dca688178c70e5f1469763682f344d2aa2a3a89
/HihoCoder/1014.cpp
cad32503b43cb85f0a5b058e50560b20037c5d78
[]
no_license
Jokeren/OnlineJudge
cbfa422dd62c18f29c7f240c7936891a5ba8c8de
6759791b2cff3872b8dbefc064d543ed18df8296
refs/heads/master
2020-05-20T13:48:45.245018
2015-04-19T05:44:34
2015-04-19T05:44:34
32,642,030
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
cpp
#define _USE_MATH_DEFINES #ifdef ONLINE_JUDGE #define FINPUT(file) 0 #define FOUTPUT(file) 0 #else #define FINPUT(file) freopen(file,"r",stdin) #define FOUTPUT(file) freopen(file,"w",stdout) #endif #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> #include <set> #include <stack> #include <string> #include <map> #include <vector> #include <queue> #include <algorithm> #include <functional> #include <bitset> typedef long long ll; typedef long double ld; static const int N = 1000100; static const int M = 19; static const int LEN = 50; static const int MAX = 0x7fffffff; static const int GMAX = 0x3f3f3f3f; static const ll LGMAX = 0x3f3f3f3f3f3f3f3f; static const int MIN = ~MAX; static const double EPS = 1e-9; static const ll BASE = 1000000007; static const int CH = 27; struct Trie { //N代表节点个数,通常为字符串长度*字符串个数 //数据量太大时要用new int ch[N][CH]; int value[N][CH]; int sz; Trie():sz(1) { memset(ch[0], 0, sizeof(ch[0])); memset(value[0], 0, sizeof(value[0])); } void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); memset(value[0], 0, sizeof(value[0])); } void insert(char *s, int v) { int u = 0, n = strlen(s); for (int i = 0; i < n; i++) { int c = s[i] - 'a' + 1; if (!ch[u][c]) { //大量节省时间 memset(ch[sz], 0, sizeof(ch[sz])); memset(value[sz], 0, sizeof(value[sz])); ch[u][c] = sz++; } ++value[u][c]; u = ch[u][c]; } } int search(char *s) { int u = 0, n = strlen(s); int ret; int c; for (int i = 0; i < n; i++) { c = s[i] - 'a' + 1; if (ch[u][c] != 0) { ret = value[u][c]; u = ch[u][c]; } else { return 0; } } return ret; } }; int main() { FINPUT("in.txt"); FOUTPUT("out.txt"); int n, m; //数据量太大时要用new struct Trie *trie = new Trie(); while (scanf("%d", &n) != EOF) { char str[12]; for (int i = 0; i < n; ++i) { scanf("%s", str); trie->insert(str, i); } scanf("%d", &m); for (int i = 0; i < m; ++i) { scanf("%s", str); printf("%d\n", trie->search(str)); } trie->init(); } return 0; }
[ "KerenZhou@outlook.com" ]
KerenZhou@outlook.com
7770d97190d004aab3d589728c5316574fafe963
dc4e28a8f33435c15271211049dff3cbcf65a4e3
/RA6963/RA6963.ino
fc920659177ea16e396da00ed83d0971b35ddb1a
[]
no_license
Hrastovc/RA6963-LCD-driver
3d466d4f8bed007882d6a1ef066da0a98cac19fc
cadc5db6c35e638516baa707e5f92232c6607f23
refs/heads/master
2022-06-27T06:35:16.026490
2020-05-09T18:18:17
2020-05-09T18:18:17
262,631,849
2
0
null
null
null
null
UTF-8
C++
false
false
13,417
ino
#include "pinsDef.h" #include "RA6963defines.h" #define FALSE (0) #define TRUE (1) #define DATA (0) #define AUTO (0) #define CMD (1) #define STATUS (1) #define READ (0) #define WRITE (1) #define FILL (0) #define BITMAP (1) void setup() { /* set output pins */ WR_DDR |= (1 << WR); RD_DDR |= (1 << RD); CE_DDR |= (1 << CE); CD_DDR |= (1 << CD); RST_DDR |= (1 << RST); FS1_DDR |= (1 << FS1); /* set pins to HIGH */ RD_PORT |= (1 << RD); WR_PORT |= (1 << WR); CE_PORT |= (1 << CE); CD_PORT |= (1 << CD); /* set pins to LOW */ FS1_PORT &= ~(1 << FS1); /* Reset LCD IC */ RST_PORT &= ~(1 << RST); delay(50); RST_PORT |= (1 << RST); delay(50); /* LCD init */ R6963(WRITE, CMD, 0x00, 0x00, SetControlWord | GraphicHomeAddress, 2); R6963(WRITE, CMD, 0x1E, 0x00, SetControlWord | GraphicArea, 2); R6963(WRITE, CMD, 0x00, 0x00, ModeSet, 0); R6963(WRITE, CMD, 0x00, 0x00, DisplayMode | GraphicOn, 0); R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); R6963(WRITE, DATA, FILL, 0x00, DataAutoReadWrite, 3840); } void loop() { R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); for(uint16_t i = 0; i < 3840; i++) { R6963(WRITE, CMD, 0x00, (0x01 << (7-((i/30)%8))), DataReadWrite | WriteIncrementADP, 1); } delay(1000); R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); for(uint16_t i = 0; i < 3840; i++) { R6963(WRITE, CMD, 0x00, (0x80 << (7-((i/30)%8))), DataReadWrite | WriteIncrementADP, 1); } delay(1000); //R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); //R6963(WRITE, DATA, FILL, 0xFF, DataAutoReadWrite, 3840); //R6963(WRITE, CMD, 0x00, 0x00, RegistersSetting | AddressPointer, 2); //R6963(WRITE, DATA, FILL, 0x00, DataAutoReadWrite, 3840); } /************************************************************************************//** ** \brief R6963 ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param cmdData Indicates data or command operatiom. ** \param data0 First data byte. ** \param data1 Second data byte. ** \param cmd Command to send. ** \param dataCount Number of bytes to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963(uint8_t rdWr, uint8_t cmdData, uint8_t data0, uint16_t data1, uint8_t cmd, uint16_t dataCount) { uint8_t command[3]; /* Write command to RA6963. */ if(rdWr == WRITE & cmdData == CMD) { /* Fill array with first data byte */ command[0] = data0; /* In case only one data byte is to be writen put it in the command[0]. */ if(dataCount) command[dataCount - 1] = data1; /* Fill array with command */ command[dataCount] = cmd; /* Call R6963sendCmd and return status */ return R6963sendCmd(command, dataCount); } /* Write data to RA6963 */ else if(cmdData == DATA) { /* Call R6963auto and return status */ return R6963auto(rdWr, data0, (uint8_t *)data1, dataCount); } /* Parameters invalid */ return FALSE; } /*** end of R6963 ***/ /************************************************************************************//** ** \brief R6963auto ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param p Indicates if data parameter is pointer or not. ** \param data Pointer to the start of bitmap. ** \param byteCount Number ob bytes to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963auto(uint8_t rdWr, uint8_t p, uint8_t *data, uint16_t byteCount) { uint8_t cmd; /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write data */ if(rdWr == WRITE) { /* write command */ cmd = DataAutoReadWrite | DataAutoWrite; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* wait for status */ if(!R6963waitStatus(STA3, 1000)) return FALSE; } /* read data */ else if(rdWr == READ) { /* write command */ cmd = DataAutoReadWrite | DataAutoRead; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* wait for status */ if(!R6963waitStatus(STA2, 1000)) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* counter */ uint16_t i = 0; /* write/read all the data bytes */ do { /* write data */ if(rdWr == WRITE) { if(p == FILL) { /* write data */ uint8_t color = (uint16_t)data; if(!R6963rdWrData(WRITE, DATA, &color)) return FALSE; i++; } else if(p == BITMAP) { /* write data */ if(!R6963rdWrData(WRITE, DATA, (data + (i++)))) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* wait for status */ if(!R6963waitStatus(STA3, 1000)) return FALSE; } /* read data */ else if(rdWr == READ) { /* read data */ if(!R6963rdWrData(READ, DATA, (data + (i++)))) return FALSE; /* wait for status */ if(!R6963waitStatus(STA2, 1000)) return FALSE; } else { /* Mode not supported. */ return FALSE; } } while(i < byteCount); /* write command */ cmd = DataAutoReadWrite | AutoReset; if(!R6963rdWrData(WRITE, CMD, &cmd)) return FALSE; /* return true */ return TRUE; } /*** end of R6963auto ***/ /************************************************************************************//** ** \brief R6963sendCmd ** \param data Pointer to the variable with data to send. ** \param byteCount Number of byte to send. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963sendCmd(uint8_t *data, uint8_t byteCount) { /* constrain byteCount */ if(byteCount > 2) return FALSE; /* write all the data bytes */ for(uint8_t i = 0; i < byteCount; i++) { /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write data */ if(!R6963rdWrData(WRITE, DATA, (data + i))) return FALSE; } /* wait for status */ if(!R6963waitStatus(STA1 | STA0, 1000)) return FALSE; /* write command */ if(!R6963rdWrData(WRITE, CMD, (data + byteCount))) return FALSE; /* return true */ return TRUE; } /*** end of R6963sendCmd ***/ /************************************************************************************//** ** \brief R6963waitStatus ** \param mask Status register mask. ** \param timeout Time to wait for status in ms. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963waitStatus(uint8_t mask, uint16_t timeout) { uint8_t statReg; /* convert time to count */ //TODO /* poll status */ do { /* read status register */ if(!R6963rdWrData(READ, STATUS, &statReg)) return FALSE; /* wait a bit */ //TODO } while(!((statReg & mask) == mask)); /* return status */ if(!((statReg & mask) == mask)) return FALSE; /* return TRUE */ return TRUE; } /*** end of R6963waitStatus ***/ /************************************************************************************//** ** \brief R6963rdWrData ** \param rdWr Indicates reading or writing, WRITE or READ. ** \param cdState State of a CD pin. ** \param data Pointer to the data variable to read or write. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963rdWrData(uint8_t rdWr, uint8_t cdState, uint8_t *data) { /* write data */ if(rdWr == WRITE) { /* Data bus direction */ if(!R6963dataBusDir(OUTPUT)) return FALSE; /* set data bus */ if(!R6963setDataBus(*data)) return FALSE; } /* read data */ else if(rdWr == READ) { /* Data bus direction */ if(!R6963dataBusDir(INPUT)) return FALSE; } else { /* Mode not supported. */ return FALSE; } /* Register select; Command/Data write */ if(!R6963cd(cdState)) return FALSE; /* WR or RD take low */ if(!R6963wr(~rdWr)) return FALSE; if(!R6963rd( rdWr)) return FALSE; /* CE pulsed low for greater than 150ns */ if(!R6963ce(LOW)) return FALSE; /* wait a least 150ns */ //asm("nop"); //asm("nop"); //asm("nop"); if(rdWr == READ) { /* read data bus */ if(!R6963readDataBus(data)) return FALSE; } /* CE take high */ if(!R6963ce(HIGH)) return FALSE; /* return TRUE */ return TRUE; } /*** end of R6963rdWrData ***/ /************************************************************************************//** ** \brief R6963cd ** \param state State of the CD pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963cd(uint8_t state) { /* set pin to the state. */ CD_PORT = (CD_PORT & ~(1 << CD)) | ((state & 0x01) << CD); /* return TRUE */ return TRUE; } /*** end of R6963cd ***/ /************************************************************************************//** ** \brief R6963wr ** \param state State of the WR pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963wr(uint8_t state) { /* set pin to the state. */ WR_PORT = (WR_PORT & ~(1 << WR)) | ((state & 0x01) << WR); /* return TRUE */ return TRUE; } /*** end of R6963wr ***/ /************************************************************************************//** ** \brief R6963rd ** \param state State of the RD pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963rd(uint8_t state) { /* set pin to the state. */ RD_PORT = (RD_PORT & ~(1 << RD)) | ((state & 0x01) << RD); /* return TRUE */ return TRUE; } /*** end of R6963rd ***/ /************************************************************************************//** ** \brief R6963ce ** \param state State of the CE pin, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963ce(uint8_t state) { /* set pin to the state. */ CE_PORT = (CE_PORT & ~(1 << CE)) | ((state & 0x01) << CE); /* return TRUE */ return TRUE; } /*** end of R6963ce ***/ /************************************************************************************//** ** \brief R6963setDataBus ** \param data Data to set the bus to ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963setDataBus(uint8_t data) { /* set data bus */ D0_PORT = (D0_PORT & ~(1 << D0)) | (((data >> 0) & 0x01) << D0); D1_PORT = (D1_PORT & ~(1 << D1)) | (((data >> 1) & 0x01) << D1); D2_PORT = (D2_PORT & ~(1 << D2)) | (((data >> 2) & 0x01) << D2); D3_PORT = (D3_PORT & ~(1 << D3)) | (((data >> 3) & 0x01) << D3); D4_PORT = (D4_PORT & ~(1 << D4)) | (((data >> 4) & 0x01) << D4); D5_PORT = (D5_PORT & ~(1 << D5)) | (((data >> 5) & 0x01) << D5); D6_PORT = (D6_PORT & ~(1 << D6)) | (((data >> 6) & 0x01) << D6); D7_PORT = (D7_PORT & ~(1 << D7)) | (((data >> 7) & 0x01) << D7); /* return TRUE */ return TRUE; } /*** end of R6963setDataBus ***/ /************************************************************************************//** ** \brief R6963readDataBus ** \param data Pointer to the bus variable ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963readDataBus(uint8_t *data) { *data = 0; /* read data bus */ *data |= (((D0_PIN >> D0) & 0x01) << 0); *data |= (((D1_PIN >> D1) & 0x01) << 1); *data |= (((D2_PIN >> D2) & 0x01) << 2); *data |= (((D3_PIN >> D3) & 0x01) << 3); *data |= (((D4_PIN >> D4) & 0x01) << 4); *data |= (((D5_PIN >> D5) & 0x01) << 5); *data |= (((D6_PIN >> D6) & 0x01) << 6); *data |= (((D7_PIN >> D7) & 0x01) << 7); /* return TRUE */ return TRUE; } /*** end of R6963readDataBus ***/ /************************************************************************************//** ** \brief R6963dataBusDir ** \param dir Data bus direction, 0 or 1. ** \return True if successful, false otherwise. ** ****************************************************************************************/ uint8_t R6963dataBusDir(uint8_t dir) { /* set pins direction */ D0_DDR = (D0_DDR & ~(1 << D0)) | ((dir & 0x01) << D0); D1_DDR = (D1_DDR & ~(1 << D1)) | ((dir & 0x01) << D1); D2_DDR = (D2_DDR & ~(1 << D2)) | ((dir & 0x01) << D2); D3_DDR = (D3_DDR & ~(1 << D3)) | ((dir & 0x01) << D3); D4_DDR = (D4_DDR & ~(1 << D4)) | ((dir & 0x01) << D4); D5_DDR = (D5_DDR & ~(1 << D5)) | ((dir & 0x01) << D5); D6_DDR = (D6_DDR & ~(1 << D6)) | ((dir & 0x01) << D6); D7_DDR = (D7_DDR & ~(1 << D7)) | ((dir & 0x01) << D7); /* return TRUE */ return TRUE; } /*** end of R6963dataBusDir ***/
[ "luka.hrastovec@gmail.com" ]
luka.hrastovec@gmail.com
19fe69fae6ecd207e5804b903b11d656270b8135
4ed0e03a070b86faa1b031ff88ad488f032dd91e
/dart_microtask_queue.h
bcb0427af8d37ef34d0679f9d059c237e8069734
[ "BSD-3-Clause" ]
permissive
canluhuang/tonic
a83df0666225e66b01501e454b6db8d65a32c821
7bdb116b60aebc4200823147d6986037faab43f0
refs/heads/main
2023-03-16T16:53:04.455969
2021-03-03T13:03:46
2021-03-03T13:03:46
344,128,393
0
0
null
null
null
null
UTF-8
C++
false
false
992
h
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_TONIC_DART_MICROTASK_QUEUE_H_ #define LIB_TONIC_DART_MICROTASK_QUEUE_H_ #include <vector> #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/dart_persistent_value.h" #include "tonic/logging/dart_error.h" namespace tonic { class DartMicrotaskQueue { public: DartMicrotaskQueue(); ~DartMicrotaskQueue(); static void StartForCurrentThread(); static DartMicrotaskQueue* GetForCurrentThread(); void ScheduleMicrotask(Dart_Handle callback); void RunMicrotasks(); void Destroy(); bool HasMicrotasks() const { return !queue_.empty(); } DartErrorHandleType GetLastError(); private: typedef std::vector<DartPersistentValue> MicrotaskQueue; DartErrorHandleType last_error_; MicrotaskQueue queue_; }; } // namespace tonic #endif // LIB_TONIC_DART_MICROTASK_QUEUE_H_
[ "lukehuang@tencent.com" ]
lukehuang@tencent.com
458deacd30242136f570046f24a40c96a781eec5
5e3d71944ea698f673276eb9ccd5cf099f3d422c
/src/libIterativeRobot/abstractBaseClasses/PositionTracker.cpp
2a67d5ec06d69b25e2ba30127ba6c09163470cce
[]
no_license
1138programming/2018-2019-VEX-1138C-Redemption
7e1533d1f5fb0cf394d734d6e8b3f0f0f551a0e8
bea4f343786092472031a79ffc03b784eef7fc2a
refs/heads/master
2020-04-06T21:11:45.215021
2019-02-24T18:50:58
2019-02-24T18:50:58
157,795,757
1
0
null
null
null
null
UTF-8
C++
false
false
3,009
cpp
#include "abstractBaseClasses/PositionTracker.h" PositionTracker::PositionTracker(Motor* leftMotor, Motor* rightMotor, pros::ADIEncoder* backEncoder, float leftDist, float rightDist, float backDist, float wheelRadius, int ticksPerRev) { this->leftMotor = leftMotor; this->rightMotor = rightMotor; this->backEncoder = backEncoder; this->leftDist = leftDist; this->rightDist = rightDist; this->backDist = backDist; this->wheelRadius = wheelRadius; this->ticksPerRev = ticksPerRev; currentLeftEncoderValue = 0; currentRightEncoderValue = 0; currentBackEncoderValue = 0; previousLeftEncoderValue = 0; previousRightEncoderValue = 0; previousBackEncoderValue = 0; deltaLeftEncoderValue = 0; deltaRightEncoderValue = 0; deltaBackEncoderValue = 0; initialAngle = 0; absoluteAngle = 0; previousAngle = 0; deltaAngle = 0; averageAngle = 0; localXOffset = 0; localYOffset = 0; globalXOffset = 0; globalYOffset = 0; previousXOffset = 0; previousYOffset = 0; currentX = 0; currentY = 0; } float PositionTracker::ticksToInches(int ticks) { float c = M_PI * wheelRadius * wheelRadius; return c * (ticks / ticksPerRev); } void PositionTracker::update() { currentLeftEncoderValue = leftMotor->getEncoderValue(); currentRightEncoderValue = rightMotor->getEncoderValue(); currentBackEncoderValue = backEncoder->get_value(); deltaLeftEncoderValue = currentLeftEncoderValue - previousLeftEncoderValue; deltaRightEncoderValue = currentLeftEncoderValue - previousRightEncoderValue; deltaBackEncoderValue = currentBackEncoderValue - previousBackEncoderValue; previousLeftEncoderValue = currentLeftEncoderValue; previousRightEncoderValue = currentRightEncoderValue; previousBackEncoderValue = currentBackEncoderValue; absoluteAngle = initialAngle + (ticksToInches(deltaLeftEncoderValue) - ticksToInches(deltaRightEncoderValue)) / (leftDist + rightDist); deltaAngle = absoluteAngle - previousAngle; previousAngle = absoluteAngle; if (deltaAngle == 0) { localXOffset = deltaBackEncoderValue; localYOffset = deltaRightEncoderValue; } else { localXOffset = 2 * sin(deltaAngle / 2) * ((deltaBackEncoderValue / deltaAngle) + backDist); localYOffset = 2 * sin(deltaAngle / 2) * ((deltaRightEncoderValue / deltaAngle) + rightDist); } averageAngle = absoluteAngle + deltaAngle / 2; float radius = sqrt((localXOffset * localXOffset) + (localYOffset * localYOffset)); float angle = atan(localYOffset / localXOffset); float newAngle = angle - averageAngle; globalXOffset = radius * cos(newAngle); globalYOffset = radius * sin(newAngle); currentX = globalXOffset + previousXOffset; currentY = globalYOffset + previousYOffset; previousXOffset = globalXOffset; previousYOffset = globalYOffset; } float PositionTracker::getCurrentXPosition() { return currentX; } float PositionTracker::getCurrentYPosition() { return currentY; } float PositionTracker::getCurrentAngle() { return absoluteAngle; }
[ "CDCheek22@chaminet.org" ]
CDCheek22@chaminet.org
239d1e454cf30f5a03d73cc40ff71e8dc4c85353
2dfbb17960cc1ad86163abdba8ab380554ca635a
/src/utiltime.h
eded248c4af480eb228d19dcccabe9d4c7f28f00
[ "MIT" ]
permissive
liray-unendlich/ZENZO-Core
1bdba73696f63ccec16d04bf4189f55b07c9de78
b6d449447a675e1307f0c02e36daaf5c1afb67ae
refs/heads/master
2020-04-13T16:08:23.460161
2018-10-13T19:25:07
2018-10-13T19:25:07
163,313,550
0
0
MIT
2018-12-27T16:08:07
2018-12-27T16:08:07
null
UTF-8
C++
false
false
705
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The PIVX developers // Copyright (c) 2017 The Zenzo developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTILTIME_H #define BITCOIN_UTILTIME_H #include <stdint.h> #include <string> int64_t GetTime(); int64_t GetTimeMillis(); int64_t GetTimeMicros(); void SetMockTime(int64_t nMockTimeIn); void MilliSleep(int64_t n); std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); std::string DurationToDHMS(int64_t nDurationTime); #endif // BITCOIN_UTILTIME_H
[ "info@zenzo.io" ]
info@zenzo.io
b1dc38d0e606b4c9bdd5d24af987982ff86e1862
aa4b90e539ab43c64b54b9f2516a3446c9380a01
/main.cpp
dcc32d9c3a57150ee91fa8d3759ef8f4aa26755c
[]
no_license
eggplanty/CPPAlgorithmLearning
27197a0fbf7bdb124b77d443d34326ae875bf4fd
1870fef242631f26d1bb0922084fb49f66439e76
refs/heads/master
2022-12-06T00:36:18.244126
2020-08-28T03:07:33
2020-08-28T03:07:33
272,315,654
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
#include <iostream> #include <vector> #include <cstring> using namespace std; class Solution { public: string reverseLeftWords(string s, int n) { auto reverse = [] (string &str, int i , int j) { while(i < j) swap(str[i++], str[j--]); }; reverse(s, 0, n-1); reverse(s, n, s.size() - 1); reverse(s, 0, s.size()); return s; } }; int main() { Solution().reverseLeftWords("123456", 3); }
[ "794261358@qq.com" ]
794261358@qq.com
bb28095d121679dfb7b353d73366532c2bfb4099
6e60700b3732a3c0e5d54cf7950d62fbbbec4d95
/HW 1/source.cpp
2be4f3b69667a191af8a00a022114c3c99998f35
[]
no_license
mathpop09/ECS-178
735ca6370578d52523c41930b41fc08791a7e1f0
722f5b0629de814eec5cafb08ee8003d8d75c435
refs/heads/master
2020-05-15T09:19:53.997424
2019-06-06T20:24:19
2019-06-06T20:24:19
182,174,730
0
0
null
null
null
null
UTF-8
C++
false
false
8,934
cpp
#include <GL/glut.h> #include <iostream> #include <vector> #include <algorithm> #include "algo.h" #include <chrono> using namespace std; vector<vector<dim>> curves; vector<dim> coordinates; //Store the Castlejau Curves and its t Values vector<vector<dim>> CasteljauCurves; vector<double> tValues; //Store the Bernstein Curves vector<vector<dim>> BernsteinCurves; //Curve-Curve Intersection Curves. Always will be Bernstein, but stored separately //[0] and [1] will be tested for intersection, [2] and [3], [4] and [5], etc etc vector<vector<dim>> IntersectionCurves; int pointsNum = 0; int res = 0; bool theSwitch = false; algo ag; //1. Get control point data from desired curve //2. Delete curve data from CasteljauCurves (and the t value) and from BezierCurves //3. Get the two sets of new control points and push it back to either CasteljauCurve or BezierCurves //Note: castel == true, then casteljau subdivison. castel == false, then bernstein subdivision void subDivision(int index, double t, bool castel) { vector<dim> subCurve1; vector<dim> subCurve2; vector<dim> curve; vector<dim> smallCurve; double casT; if (castel == true) { //save curve index curve = CasteljauCurves[index]; casT = tValues[index]; //save curve t-value //erase that curve from existence CasteljauCurves.erase(CasteljauCurves.begin() + index); tValues.erase(tValues.begin() + index); } else { //save curve index curve = BernsteinCurves[index]; //erase that curve from existence BernsteinCurves.erase(BernsteinCurves.begin() + index); } //calculate the first curve for(int i = 0; i < curve.size(); i++) { if (i == 0) { subCurve1.push_back(curve[0]); } else { for(int j = 0; j <= i; j++) { cout << curve[j].x << " " << curve[j].y << endl; smallCurve.push_back(curve[j]); } subCurve1.push_back(ag.singleT(smallCurve, t)); smallCurve.clear(); } } //calculate the second curve for(int i = curve.size() - 1; i >= 0; i--) { if (i == curve.size() - 1) { subCurve2.push_back(curve[curve.size()-1]); } else { for(int j = curve.size() - 1; j >= i; j--) { smallCurve.push_back(curve[j]); } subCurve2.push_back(ag.singleT(smallCurve, 1-t)); smallCurve.clear(); } } //add curves back to the curve collection if (castel == true) { CasteljauCurves.push_back(subCurve1); reverse(subCurve2.begin(), subCurve2.end()); CasteljauCurves.push_back(subCurve2); tValues.push_back(casT); tValues.push_back(casT); } else { BernsteinCurves.push_back(subCurve1); BernsteinCurves.push_back(subCurve2); } } //after initial prompt void recycle(int res) { cout << "Here are the collection of coordinates: " << endl; cout << "Here are the collection of Casteljau Curves: " << endl; for(int i = 0; i < CasteljauCurves.size(); i++) { cout << "Curve #: " << i << endl; for (int j = 0; j < CasteljauCurves[i].size(); j++) { cout << " Index: " << j << " " << CasteljauCurves[i][j].x << ", " << CasteljauCurves[i][j].y << endl; } } cout << "Here are the collection of Bernstein Curves: " << endl; for(int i = 0; i < BernsteinCurves.size(); i++) { cout << "Curve #: " << i << endl; for (int j = 0; j < BernsteinCurves[i].size(); j++) { cout << " Index: " << j << " " << BernsteinCurves[i][j].x << ", " << BernsteinCurves[i][j].y << endl; } } cout << "Please send me the curve you want to modify and the proper modifications [(C)asteljau/(B)ernstein] [Curve Number] [Index Number] [(I)nsert/(D)elete]" << endl; string CB; cin >> CB; int cNum; cin >> cNum; int iNum; cin >> iNum; string insDel; cin >> insDel; if (insDel == "I") { cout << "What are the coordinates?" << endl; double xcoor; double ycoor; cin >> xcoor; cin >> ycoor; if (CB == "B") { BernsteinCurves[cNum].insert(BernsteinCurves[cNum].begin() + iNum, {xcoor, ycoor}); } else { CasteljauCurves[cNum].insert(CasteljauCurves[cNum].begin() + iNum, {xcoor, ycoor}); tValues.insert(tValues.begin() + cNum, 0.5); } } else { if (CB == "B") { BernsteinCurves[cNum].erase(BernsteinCurves[cNum].begin() + iNum); } else { CasteljauCurves[cNum].erase(CasteljauCurves[cNum].begin() + iNum); tValues.erase(tValues.begin() + cNum); } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); for (int k = 0; k < BernsteinCurves.size(); k++) { ag.Bernstein(BernsteinCurves[k], res); } for (int k = 0; k < CasteljauCurves.size(); k++) { ag.deCasteljau(CasteljauCurves[k], tValues[k], res); } recycle(res); } void promptUser(void) { string CI; bool intersection; //Two modes, regular curve drawing or intersection cout << "Hello! Would you like to perform an intersection or would you just like to draw some curves? C for Curve Drawing/I for Intersection" << endl; cin >> CI; if (CI == "C") { intersection = false; theSwitch = true; } else { intersection = true; } cout << "What resolution would you like your curves to be?" << endl; cin >> res; if (intersection == false) { cout << "Please tell me how many curves would you like" << endl; int curveCount = 0; cin >> curveCount; //Separate the Bernstein-Casteljau Drawing Window and the Curve-Curve Intersection Window //Bezier Curve Prompt for (int j = 0; j < curveCount; j++) { string methodBC; cout << "Bernstein method or Casteljau method for drawing curves? [B]ernstein/[C]asteljau: " << endl; cin >> methodBC; cout << "Hello! How many coordinates are on your control polygon?" << endl; cin >> pointsNum; cout << "Please enter your " << pointsNum << " control points. Format: x y" << endl; //loop over the number of control points for (int i = 0; i < pointsNum; i++) { double coorX = 0; double coorY = 0; cout << "Control Point " << (i + 1) << ": " << endl; cin >> coorX >> coorY; cout << "Coordinate X: " << coorX << " Coordinate Y: " << coorY << endl; coordinates.push_back({coorX, coorY}); } if (methodBC == "B") { BernsteinCurves.push_back(coordinates); coordinates.clear(); } else if (methodBC == "C") { cout << "Please enter your parameter for t: " << endl; double t; cin >> t; tValues.push_back(t); CasteljauCurves.push_back(coordinates); coordinates.clear(); } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); for (int k = 0; k < BernsteinCurves.size(); k++) { auto start = std::chrono::high_resolution_clock::now(); ag.Bernstein(BernsteinCurves[k], res); auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; std::cout << "Elapsed time: " << elapsed.count() << " s\n"; } for (int k = 0; k < CasteljauCurves.size(); k++) { auto start = std::chrono::high_resolution_clock::now(); ag.deCasteljau(CasteljauCurves[k], tValues[k], res); auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; std::cout << "Elapsed time: " << elapsed.count() << " s\n"; } } else { cout << "Please enter the tolerance that you desire (0.01 or lower recommended)" << endl; double tolerance; cin >> tolerance; cout << "Please enter the two curves that you desire" << endl; for (int k = 0; k < 2; k++) { cout << "Hello! How many coordinates are on your control polygon?" << endl; cin >> pointsNum; cout << "Please enter your " << pointsNum << " control points. Format: x y" << endl; for (int i = 0; i < pointsNum; i++) { double coorX = 0; double coorY = 0; cout << "Control Point " << (i + 1) << ": " << endl; cin >> coorX >> coorY; cout << "Coordinate X: " << coorX << " Coordinate Y: " << coorY << endl; coordinates.push_back({coorX, coorY}); } BernsteinCurves.push_back(coordinates); coordinates.clear(); } ag.Bernstein(BernsteinCurves[0], res); ag.Bernstein(BernsteinCurves[1], res); ag.IntersectionCheck(BernsteinCurves[0], BernsteinCurves[1], tolerance); } } void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT); promptUser(); glutSwapBuffers(); if (theSwitch == true) { glClear(GL_COLOR_BUFFER_BIT); recycle(res); /* coor = {-0.75,-0.5}; coordinates.push_back(coor); coor = {0.5,0.0}; coordinates.push_back(coor); coor = {0.0,0.5}; coordinates.push_back(coor); ag.deCastlejau(coordinates); coordinates.clear(); */ glutSwapBuffers(); } } int main(int argc, char **argv) { // init GLUT and create Window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(400,200); glutInitWindowSize(800,800); glutCreateWindow("Homework 1"); // register callbacks glutDisplayFunc(renderScene); cout << "The dimensions of the window is 800 by 800, the bottom left is (0, 0)" << endl; glutMainLoop(); // enter GLUT event processing cycle return 1; }
[ "noreply@github.com" ]
mathpop09.noreply@github.com
f83556b84f13c6a8e889a825d49e472a39d8b749
987fa85ca5b7db9806e698f6947714de6be9f7a6
/Personal/backup4/gameBackup/src/ShaderProgram.cpp
6f5e84b0823843534b5f4b148fa5a79442fb22be
[]
no_license
mynameisjohn/code
89a711c554766a354f7268d714ddbda183e9dd6c
14f0fd704e13939e71d2bdd17862573eff32ef9d
refs/heads/master
2021-01-15T12:19:10.912281
2014-09-02T23:10:55
2014-09-02T23:10:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,395
cpp
//also ripped off of lazy foo #include "ShaderProgram.h" ShaderProgram::ShaderProgram(){ mProgramID = (GLuint)NULL; } ShaderProgram::~ShaderProgram(){ freeProgram(); } void ShaderProgram::freeProgram(){ glDeleteProgram(mProgramID); } bool ShaderProgram::bind(){ glUseProgram(mProgramID); GLenum err = glGetError(); if (err != GL_NO_ERROR){ printf( "Error binding shader! %s\n", gluErrorString(err)); printProgramLog(mProgramID); return false; } return true; } void ShaderProgram::unbind(){ glUseProgram((GLuint)NULL); } GLuint ShaderProgram::getProgramID(){ return mProgramID; } void ShaderProgram::printProgramLog(GLuint program){ if (glIsProgram(program)){ int infoLogLength=0, maxLength=0; char * infoLog; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); infoLog = new char[maxLength]; glGetProgramInfoLog(program,maxLength,&infoLogLength,infoLog); if (infoLogLength>0) printf("%s\n", infoLog); delete[] infoLog; } else printf("%d did not reference a program. \n",program); return; } void ShaderProgram::printShaderLog(GLuint shader){ if (glIsShader(shader)){ int infoLogLength=0, maxLength=0; char * infoLog; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); infoLog = new char[maxLength]; glGetShaderInfoLog(shader,maxLength,&infoLogLength,infoLog); if (infoLogLength>0) printf("%s\n", infoLog); delete[] infoLog; } else printf("%d did not reference a shader. \n",shader); return; } GLuint ShaderProgram::loadShaderFromFile(std::string path, GLenum shaderType){ GLuint shaderID=0; std::string shaderString; std::ifstream sourceFile(path.c_str()); if (sourceFile){ shaderString.assign((std::istreambuf_iterator<char>(sourceFile)), std::istreambuf_iterator<char>()); shaderID = glCreateShader(shaderType); const GLchar * shaderSource = shaderString.c_str(); glShaderSource(shaderID, 1, (const GLchar**)&shaderSource, NULL); glCompileShader(shaderID); GLint shaderCompiled = GL_FALSE; glGetShaderiv(shaderID, GL_COMPILE_STATUS, &shaderCompiled); if (shaderCompiled != GL_TRUE){ printf("Unable to compile shader %d!\n\nSource:\n%s\n", shaderID, shaderSource); printShaderLog(shaderID); glDeleteShader(shaderID); shaderID = 0; } } else printf( "Unable to open file %s\n", path.c_str() ); return shaderID; }
[ "mynameisjohnj@gmail.com" ]
mynameisjohnj@gmail.com
511df78768ddfc0863ff29e00ad0c5763f02fc74
942e6d29b3e6193c8541b31140ea9aef5554379b
/Sources/Inputs/ButtonMouse.cpp
ad84f4e0b33bf9bda0750a06d9f7db20f00de37e
[ "MIT" ]
permissive
hhYanGG/Acid
e7da2457bdd5820f7cba38b1602762f426dbd849
f5543e9290aee5e25c6ecdafe8a3051054b203c0
refs/heads/master
2020-03-27T13:11:56.488574
2018-08-28T17:47:35
2018-08-28T18:10:46
146,595,670
1
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include "ButtonMouse.hpp" namespace acid { ButtonMouse::ButtonMouse(const std::vector<MouseButton> &buttons) : IButton(), m_buttons(buttons), m_wasDown(false) { } ButtonMouse::~ButtonMouse() { } bool ButtonMouse::IsDown() const { if (Mouse::Get() == nullptr) { return false; } for (auto &button : m_buttons) { if (Mouse::Get()->GetButton(button)) { return true; } } return false; } bool ButtonMouse::WasDown() { bool stillDown = m_wasDown && IsDown(); m_wasDown = IsDown(); return m_wasDown == !stillDown; } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
2cf42f2729cbc21d310cfcd6ee5ee3444c4b946b
e276303d11773362c146c4a6adbdc92d6dee9b3f
/Classes/Native/mscorlib_System_Collections_Generic_GenericEqualit1636656366.h
c6a4f79bb3713f3072861a65887c4f0f8f3b077f
[ "Apache-2.0" ]
permissive
AkishinoShiame/Virtual-Elderly-Chatbot-IOS-Project-IOS-12
45d1358bfc7c8b5c5b107b9d50a90b3357dedfe1
a834966bdb705a2e71db67f9d6db55e7e60065aa
refs/heads/master
2020-06-14T02:22:06.622907
2019-07-02T13:45:08
2019-07-02T13:45:08
194,865,711
0
0
null
null
null
null
UTF-8
C++
false
false
642
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Collections_Generic_EqualityCompar1226409501.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.GenericEqualityComparer`1<UnityEngine.UI.ColorBlock> struct GenericEqualityComparer_1_t1636656366 : public EqualityComparer_1_t1226409501 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "akishinoshiame@icloud.com" ]
akishinoshiame@icloud.com
97585d88601930cd6102b5085f3d50c721b9def5
57d123a5f68b1e8095d5239eb7c3af28784e0799
/OJ——work/work_three/一元多项式相加.cpp
df415b93e16c492ba3cc22d768b2d525f6f52eba
[]
no_license
Floweryu/DataStructuresAlgorithms
dda159afe3b8327deecfa3a8f72a62cf16d1d538
e61a424dcca1913c0e5ef4fae15b5945dbd04d9b
refs/heads/master
2022-03-26T04:22:07.849883
2019-12-18T07:52:11
2019-12-18T07:52:11
null
0
0
null
null
null
null
GB18030
C++
false
false
2,926
cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct term{ int cof; int inx; struct term *next; }term,*LinkList; typedef LinkList polynomial; //初始化链表 int InitList(LinkList &L) { L=(LinkList)malloc(sizeof(term)); if(!L) return 0; L->next=NULL; return 1; } //判断链表是否为空;空就返回1 int Empty_L(term *L) { /*当只有一个头结点的时候,该链表就为空*/ if((L->next)==NULL) //头结点与NULL相连 return 1; else return 0; } //打印多项式链表 void printfPolynomial(polynomial &P) { LinkList q=P->next; while(q) { printf("%d %d ",q->cof,q->inx); q=q->next; } printf("\n"); } //创建输入多项式 int CreatePoly(polynomial &L) { LinkList p,q; L=(LinkList)malloc(sizeof(term)); q=L; int c,e; while(scanf("%d %d",&c,&e)!=EOF&&e>=0) { p=(LinkList)malloc(sizeof(term)); p->cof=c; p->inx=e; q->next=p; q=q->next; } q->next=NULL; } //多项式加法 int addPolyn(polynomial pa,polynomial pb) { LinkList qa=pa->next; LinkList qb=pb->next; LinkList L,qc,s,pc; L=pc=(LinkList)malloc(sizeof(term)); L->next=NULL; while(qa!=NULL&&qb!=NULL) { qc=(LinkList)malloc(sizeof(term)); //测试点printf("%d %d\n",qa->inx,qb->inx); if(qa->inx < qb->inx) //pa中的指数大于pb { qc->cof=qb->cof; //将小的一项赋给qc qc->inx=qb->inx; qb=qb->next; //指向下一个 } else if(qa->inx > qb->inx) { qc->cof=qa->cof; //将小的一项赋给qc qc->inx=qa->inx; qa=qa->next; } else //如果相等 { qc->cof=qa->cof+qb->cof; //系数相加保存到qc qc->inx=qa->inx; //指数不变 qa=qa->next; qb=qb->next; } if((qc->cof)!=0) //如果该项系数不为0 { qc->next=pc->next; //将qc插入到新链表 pc中 pc->next=qc; pc=qc; //新申请指针向下移 } else free(qc); } while(qa!=NULL) { qc=(LinkList)malloc(sizeof(term)); qc->cof=qa->cof; qc->inx=qa->inx; qa=qa->next; qc->next=pc->next; pc->next=qc; pc=qc; } while(qb!=NULL) { qc=(LinkList)malloc(sizeof(term)); qc->cof=qb->cof; qc->inx=qb->inx; qb=qb->next; qc->next=pc->next; pc->next=qc; pc=qc; } if(Empty_L(L)) printf("0\n"); printfPolynomial(L); } int main() { LinkList pa,pb; CreatePoly(pa); //测试点printfPolynomial(pa); CreatePoly(pb); //测试点printfPolynomial(pb); addPolyn(pa,pb); }
[ "869830837@qq.com" ]
869830837@qq.com
c7f7d149ec86bbd6623b4d4dedc8ba476590d403
9c98ce485432ed36171800011fcdce2b5ca8a04d
/employee.h
c3e2e76e81c293910c6f20eb5fca4b2d613d3839
[ "Apache-2.0" ]
permissive
MasterMaxLi/EmployeeManager
621560baadf333d3d985c5550177962543933998
a6121a53012086691de393f939853a0119e509db
refs/heads/main
2023-04-06T10:24:46.027062
2021-04-16T13:11:30
2021-04-16T13:11:30
357,537,511
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
238
h
#pragma once #include<iostream> #include"worker.h" using namespace std; class Employee :public Worker { public: //¹¹Ô캯Êý Employee(int id, string name, int dId); virtual void showInfo(); virtual string getDeptName(); };
[ "riwinkids@gmail.com" ]
riwinkids@gmail.com
c00565dd227c6261c032f7218e7ebc2856af1143
1da7dac0da7bbfab25ffd47b6ef898e42365af25
/src/fpLineSpectrum.h
669fd58e58b6361b41a82fe98411f13a5d7b82fc
[ "Apache-2.0" ]
permissive
pixlise/piquant
a32e9a6dab8115bc6a601bac4b6efa4bebe2395a
a534d67ee84734fff746e6bdce0df8a1c3f72926
refs/heads/main
2023-04-13T21:21:07.518073
2023-03-24T11:02:43
2023-03-24T11:02:43
520,582,671
3
0
Apache-2.0
2023-03-24T11:02:45
2022-08-02T17:04:14
C
UTF-8
C++
false
false
2,647
h
// Copyright (c) 2018-2022 California Institute of Technology (“Caltech”) and // University of Washington. U.S. Government sponsorship acknowledged. // 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 Caltech nor its operating division, the Jet Propulsion // Laboratory, 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. #ifndef fpLineSpectrum_h #define fpLineSpectrum_h #include <vector> #include "XrayLines.h" #include "XraySpectrum.h" #include "XrayDetector.h" // Info for consolidated emission lines, used for tails, shelf, and pileup effects struct LineGroup { float energy = 0; float intensity = 0; int number = 0; float tail_sum = 0; string symbol; }; // Generates calculated spectrum from Xray Lines object that has been loaded with intensity factor // Calculation is Gaussian with fwhm as input, integral matches line intensity // Calculated spectrum is counts in each channel // Added check for zero or negative energy at low channels Dec. 12, 2011 void fpLineSpectrum( const XrayLines &lines_in, const XrayDetector detector, const float threshold_in, const XrayEnergyCal &cal_in, const float eMin, std::vector <LineGroup> &pileup_list, SpectrumComponent &component_out ); #endif
[ "tom@spicule.co.uk" ]
tom@spicule.co.uk
48e85d3fcc55a6709568cd82a8079d00b1441f80
503a8aac2364361325a9adcdbb7d27c2982c8624
/Drinks/Wine.cpp
a9cb92ecfd59b6f0ad23ef6110a72e91df2a74a6
[]
no_license
GuyOded/Driniking_Bar
19a4769c82fc1a5447b48d9501bfb24a13f6f0b4
8c778156c90126691c03c8cb25f47633c76d58e0
refs/heads/master
2021-01-10T17:44:15.265995
2016-03-01T18:19:02
2016-03-01T18:19:02
52,898,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
/* * Wine.cpp * * Created on: Feb 12, 2016 * Author: guy */ #include "Wine.h" #include <sstream> /** * * @param name-the name of the wine * @param temp-the temperature * @param year-the year the wine was made in(or aged since I think) */ Wine::Wine(std::string name, int temp, int year) :Drink(name), m_temp(temp), m_year(year) { //basically converts to string std::string temp_string; std::stringstream ss; ss << temp; ss >> temp_string; m_preparation = "Keep it in " + temp_string + " degrees celsius and serve"; } /** * copy constructor * @param other */ Wine::Wine(const Wine& other) :Drink(other.m_name, other.m_preparation), m_temp(other.m_temp), m_year(other.m_year) {} Wine::~Wine() { } /** * * @return the name plus the year in brackets */ std::string Wine::getName() { std::string year; std::stringstream ss; ss << m_year; ss >> year; return m_name + " (year " + year + ")"; } std::string Wine::prepare() { return m_preparation; } Wine* Wine::clone() const { return new Wine(*this); }
[ "itayoded1@gmail.com" ]
itayoded1@gmail.com
fdeadfd0a2b861f2b996166eefc29efb6adf203e
6a6e8dbc2b200b730cbafbee4b075384a9fb5a11
/source/test/intltest/textfile.cpp
4bb6965ab58a9f0eaae1e23922c59511525525c2
[ "BSD-3-Clause", "ICU", "LicenseRef-scancode-unicode", "NAIST-2003", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
njlr/icu4c-2
74fc360be3c75663e6e0e2dc1fc5ddbd13d0efe2
caef63a217fd526bdcf221de949374b4c1b275cc
refs/heads/master
2021-01-20T11:09:30.606859
2017-03-30T17:26:53
2017-03-30T17:26:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,231
cpp
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ********************************************************************** * Copyright (c) 2004,2011 International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: March 19 2004 * Since: ICU 3.0 ********************************************************************** */ #include "textfile.h" #include "cmemory.h" #include "cstring.h" #include "intltest.h" #include "util.h" // If the symbol CCP is defined, then the 'name' and 'encoding' // constructor parameters are copied. Otherwise they are aliased. // #define CCP TextFile::TextFile(const char* _name, const char* _encoding, UErrorCode& ec) : file(0), name(0), encoding(0), buffer(0), capacity(0), lineNo(0) { if (U_FAILURE(ec) || _name == 0 || _encoding == 0) { if (U_SUCCESS(ec)) { ec = U_ILLEGAL_ARGUMENT_ERROR; } return; } #ifdef CCP name = uprv_malloc(uprv_strlen(_name) + 1); encoding = uprv_malloc(uprv_strlen(_encoding) + 1); if (name == 0 || encoding == 0) { ec = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(name, _name); uprv_strcpy(encoding, _encoding); #else name = (char*) _name; encoding = (char*) _encoding; #endif const char* testDir = IntlTest::getSourceTestData(ec); if (U_FAILURE(ec)) { return; } if (!ensureCapacity((int32_t)(uprv_strlen(testDir) + uprv_strlen(name) + 1))) { ec = U_MEMORY_ALLOCATION_ERROR; return; } uprv_strcpy(buffer, testDir); uprv_strcat(buffer, name); file = T_FileStream_open(buffer, "rb"); if (file == 0) { ec = U_ILLEGAL_ARGUMENT_ERROR; return; } } TextFile::~TextFile() { if (file != 0) T_FileStream_close(file); if (buffer != 0) uprv_free(buffer); #ifdef CCP uprv_free(name); uprv_free(encoding); #endif } UBool TextFile::readLine(UnicodeString& line, UErrorCode& ec) { if (T_FileStream_eof(file)) { return FALSE; } // Note: 'buffer' may change after ensureCapacity() is called, // so don't use // p=buffer; *p++=c; // but rather // i=; buffer[i++]=c; int32_t n = 0; for (;;) { int c = T_FileStream_getc(file); // sic: int, not int32_t if (c < 0 || c == 0xD || c == 0xA) { // consume 0xA following 0xD if (c == 0xD) { c = T_FileStream_getc(file); if (c != 0xA && c >= 0) { T_FileStream_ungetc(c, file); } } break; } if (!setBuffer(n++, c, ec)) return FALSE; } if (!setBuffer(n++, 0, ec)) return FALSE; UnicodeString str(buffer, encoding); // Remove BOM in first line, if present if (lineNo == 0 && str[0] == 0xFEFF) { str.remove(0, 1); } ++lineNo; line = str.unescape(); return TRUE; } UBool TextFile::readLineSkippingComments(UnicodeString& line, UErrorCode& ec, UBool trim) { for (;;) { if (!readLine(line, ec)) return FALSE; // Skip over white space int32_t pos = 0; ICU_Utility::skipWhitespace(line, pos, TRUE); // Ignore blank lines and comment lines if (pos == line.length() || line.charAt(pos) == 0x23/*'#'*/) { continue; } // Process line if (trim) line.remove(0, pos); return TRUE; } } /** * Set buffer[index] to c, growing buffer if necessary. Return TRUE if * successful. */ UBool TextFile::setBuffer(int32_t index, char c, UErrorCode& ec) { if (capacity <= index) { if (!ensureCapacity(index+1)) { ec = U_MEMORY_ALLOCATION_ERROR; return FALSE; } } buffer[index] = c; return TRUE; } /** * Make sure that 'buffer' has at least 'mincapacity' bytes. * Return TRUE upon success. Upon return, 'buffer' may change * value. In any case, previous contents are preserved. */ #define LOWEST_MIN_CAPACITY 64 UBool TextFile::ensureCapacity(int32_t mincapacity) { if (capacity >= mincapacity) { return TRUE; } // Grow by factor of 2 to prevent frequent allocation // Note: 'capacity' may be 0 int32_t i = (capacity < LOWEST_MIN_CAPACITY)? LOWEST_MIN_CAPACITY: capacity; while (i < mincapacity) { i <<= 1; if (i < 0) { i = 0x7FFFFFFF; break; } } mincapacity = i; // Simple realloc() no good; contents not preserved // Note: 'buffer' may be 0 char* newbuffer = (char*) uprv_malloc(mincapacity); if (newbuffer == 0) { return FALSE; } if (buffer != 0) { uprv_strncpy(newbuffer, buffer, capacity); uprv_free(buffer); } buffer = newbuffer; capacity = mincapacity; return TRUE; }
[ "njlr@users.noreply.github.com" ]
njlr@users.noreply.github.com
e945f13a1afce69eeb7b9a12bbb573c0ebb22739
df3e1338171befbad80267a24c6866e97bd5f378
/Dfslab.cpp
bb12b231b0cc6ab5f4e41f810e15b381fd6a9f90
[]
no_license
Shaykat/Algorithms
1e6cf3ab7421478d7c293c340438917fa6064eb9
66960a9cc1aab35cf703ea220f9b0706e9e32afb
refs/heads/master
2021-08-20T01:02:53.538420
2017-11-27T21:54:29
2017-11-27T21:54:29
107,311,887
0
0
null
null
null
null
UTF-8
C++
false
false
1,576
cpp
#include<iostream> #include<cstdlib> #include<vector> #include<cstring> using namespace std; int matrix[100][100]; vector<int>graph[100]; int time[2][100],color[100]; int node,edge; int t=0; void dfs(int u) { color[u] = 1; time[0][u] = ++t; for(int i=0;i<node;i++) { if(matrix[u][i] == 1 && color[i] == 0) { dfs(i); } } color[u] = 2; time[1][u] = ++t; } int main() { int x,y,v; cin >> node >> edge; memset(color,0,sizeof(color)); for(int i=0;i<edge;i++) { cin >> x >> y; graph[x].push_back(y); graph[y].push_back(x); matrix[x][y] = 1; matrix[y][x] = 1; } /*for(int i=0;i<node;i++) { cout << i << " : "; for(int j=0;j<graph[i].size();j++) { cout << matrix[i][j] << " "; } cout << endl; }*/ // adjecensi matrix; /*for(int i=0;i<node;i++) { for(int j=0;j<node;j++) { if(matrix[i][j]== 1) { cout << matrix[i][j] << " " ; } cout << endl; } }*/ int component = 0; int ft,tm,n; for(int i =0;i<node;i++) { tm = t; if(color[i] == 0) { dfs(i); component ++; } ft = t - tm; cout << "number of node in component " << component << ": " << ft/2 << endl; } cout << "component :" << component << endl; //getch(); return 0; } /* 10 11 0 6 0 9 6 1 6 7 7 3 0 1 1 9 1 3 9 4 3 4 8 2 */
[ "shaykat2057@gmail.com" ]
shaykat2057@gmail.com
5603a11b546db76f172f6d86aae3f835e9f8f62d
584ca4da32b0e70a2702b5b16222d3d9475cd63a
/src/test/bswap_tests.cpp
5d903859a8146c8d16e92fcb9fd60c2c7d9ac045
[ "MIT" ]
permissive
IluminumProject/iluminum
d87e14cbeb0873fc7b1e42968cb039ecf2b4e03d
9685edf64161c66205c89ee72d711b0144733735
refs/heads/master
2020-03-10T08:55:36.095447
2018-04-21T15:56:18
2018-04-21T15:56:18
128,815,453
0
0
MIT
2018-04-12T07:00:53
2018-04-09T18:19:59
C++
UTF-8
C++
false
false
737
cpp
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compat/byteswap.h" #include "test/test_iluminum.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(bswap_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(bswap_tests) { // Sibling in bitcoin/src/qt/test/compattests.cpp uint16_t u1 = 0x1234; uint32_t u2 = 0x56789abc; uint64_t u3 = 0xdef0123456789abc; uint16_t e1 = 0x3412; uint32_t e2 = 0xbc9a7856; uint64_t e3 = 0xbc9a78563412f0de; BOOST_CHECK(bswap_16(u1) == e1); BOOST_CHECK(bswap_32(u2) == e2); BOOST_CHECK(bswap_64(u3) == e3); } BOOST_AUTO_TEST_SUITE_END()
[ "4mindsmine@gmail.com" ]
4mindsmine@gmail.com
0805501118c68483fbfa623d65fd2e17251747c3
32ede53a77c76deb095cf4609f3a301550a2bf35
/PrintDrawer.cpp
f5b8751fc6c2615f590c3fcef31e0d7aaf490e4b
[]
no_license
justtookoff/FlyingDuckChart
9492fa2e1083139102f592ea887c78fa074370a7
8b551285e97b14cb6c959473c89ab6c2ab82ff50
refs/heads/master
2021-07-03T03:25:18.942558
2017-09-23T09:13:15
2017-09-23T09:13:15
104,552,351
0
0
null
null
null
null
UHC
C++
false
false
9,871
cpp
//PrintDrawer.cpp #include "PrintDrawer.h" #include "NSChartForm.h" #include <iostream> #include "Sequence.h" #include "Selection.h" #include "Iteration.h" #include "Case.h" #include "String.h" #pragma warning(disable:4996) PrintDrawer::PrintDrawer(){ } PrintDrawer::PrintDrawer(const PrintDrawer& source){ } PrintDrawer::~PrintDrawer(){ } void PrintDrawer::VisitSequencePrint(Sequence* sequence, CDC *pDC){ CPoint pt[4]; Long j = 0; Long i = 0; Long k = 0; Long length; char cha[64000]; char chaInput[64000]; Long printX = sequence->GetX() * 4; Long printY = sequence->GetY() * 4; Long printWidth = sequence->GetWidth() * 4; Long printHeight = sequence->GetHeight() * 4; pt[0].x = printX; pt[0].y = printY; pt[1].x = printX + printWidth; pt[1].y = printY; pt[2].x = printX + printWidth; pt[2].y = printY + printHeight; pt[3].x = printX; pt[3].y = printY + printHeight; pDC->Polygon(pt, 4); //contents를 배열에 복사한다. strcpy(cha, sequence->GetContents().c_str()); //길이를 구한다 length = strlen(cha); //문자열을 출력한다 while (i < length + 1) { //chaInput에 배열에있는 것을 하나씩 넣어준다. chaInput[j] = cha[i]; //cha가 만약 리턴캐리지이면 if (cha[i] == '\r' || cha[i] == '\0') { //chaInput에 넣었던 리턴캐리지를 널문자로 바꿔준다. chaInput[j] = '\0'; //차곡차곡 넣어주었던 chaInput을 텍스트아웃으로 출력시켜준다. pDC->TextOut(printX + 25, printY + (printHeight / 4) + k, chaInput); //chaInput을 초기화시켜준다. j = -1; i++; k = k + 105; } j++; i++; } } void PrintDrawer::VisitSelectionPrint(Selection* selection, CDC *pDC){ Long x; Long y; Long i = 0; Long j = 0; Long k = 0; Long length; char cha[64000]; char chaInput[64000]; Structure *structure; Visitor *visitor; visitor = new PrintDrawer; CPoint pt[4]; Long printX = selection->GetX() * 4; Long printY = selection->GetY() * 4; Long printWidth = selection->GetWidth() * 4; Long printHeight = selection->GetHeight() * 4; Long printMidX = selection->GetMidX() * 4; Long printMidY = selection->GetMidY() * 4; pt[0].x = printX; pt[0].y = printY; pt[1].x = printX + printWidth; pt[1].y = printY; pt[2].x = printX + printWidth; pt[2].y = printY + printHeight; pt[3].x = printX; pt[3].y = printY + printHeight; pDC->Polygon(pt, 4); pDC->MoveTo(CPoint(printX, printY)); pDC->LineTo(CPoint(printMidX, printMidY)); pDC->MoveTo(CPoint(printX + printWidth, printY)); pDC->LineTo(CPoint(printMidX, printMidY)); x = printMidX - (printWidth / 30); y = printMidY - (printMidY - printY) * 2 / 3; //contents를 배열에 복사한다. strcpy(cha, selection->GetContents().c_str()); //길이를 구한다 length = strlen(cha); //문자열을 출력한다 while (i < length + 1) { //chaInput에 배열에있는 것을 하나씩 넣어준다. chaInput[j] = cha[i]; //cha가 만약 리턴캐리지이면 if (cha[i] == '\r' || cha[i] == '\0') { //chaInput에 넣었던 리턴캐리지를 널문자로 바꿔준다. chaInput[j] = '\0'; //차곡차곡 넣어주었던 chaInput을 텍스트아웃으로 출력시켜준다. pDC->TextOut(x - 55, y + k, chaInput); //chaInput을 초기화시켜준다. j = -1; i++; k = k + 15; } j++; i++; } pDC->TextOut(printX + (printWidth / 10), printY + (printMidY - printY) * 1 / 2, "TRUE"); pDC->TextOut(printX + (printWidth * 4 / 5), printY + (printMidY - printY) * 1 / 2, "FALSE"); pDC->LineTo(CPoint(printMidX, printY + printHeight)); pDC->MoveTo(CPoint(printX, printMidY)); pDC->LineTo(CPoint(printX + printWidth, printMidY)); i = 0; while (i < selection->GetLength()) { structure = selection->GetChild(i); structure->AcceptPrint(visitor, pDC); i++; } if (visitor != 0) { delete visitor; } } void PrintDrawer::VisitIterationPrint(Iteration *iteration, CDC *pDC){ Long i = 0; Long j = 0; Long k = 0; Long length; char cha[64000]; char chaInput[64000]; Structure *structure; Visitor *visitor; visitor = new PrintDrawer; CPoint pt[6]; Long printX = iteration->GetX() * 4; Long printY = iteration->GetY() * 4; Long printWidth = iteration->GetWidth() * 4; Long printHeight = iteration->GetHeight() * 4; Long printMidX = iteration->GetMidX() * 4; Long printMidY = iteration->GetMidY() * 4; pt[0].x = printX; pt[0].y = printY; pt[1].x = printX + printWidth; pt[1].y = printY; pt[2].x = printX + printWidth; pt[2].y = printMidY; pt[3].x = printMidX; pt[3].y = printMidY; pt[4].x = printMidX; pt[4].y = printY + printHeight; pt[5].x = printX; pt[5].y = printY + printHeight; pDC->Polygon(pt, 6); //contents를 배열에 복사한다. strcpy(cha, iteration->GetContents().c_str()); //길이를 구한다 length = strlen(cha); //문자열을 출력한다 while (i < length + 1) { //chaInput에 배열에있는 것을 하나씩 넣어준다. chaInput[j] = cha[i]; //cha가 만약 리턴캐리지이면 if (cha[i] == '\r' || cha[i] == '\0') { //chaInput에 넣었던 리턴캐리지를 널문자로 바꿔준다. chaInput[j] = '\0'; //차곡차곡 넣어주었던 chaInput을 텍스트아웃으로 출력시켜준다. pDC->TextOut(printMidX - (printMidX - printX) / 2, printMidY - (printMidY - printY) * 2 / 3 + k, chaInput); //chaInput을 초기화시켜준다. j = -1; i++; k = k + 15; } j++; i++; } i = 0; while (i < iteration->GetLength()) { structure = iteration->GetChild(i); structure->AcceptPrint(visitor, pDC); i++; } if (visitor != 0) { delete visitor; } } void PrintDrawer::VisitCasePrint(Case *sCase, CDC *pDC){ Long i = 0; Long k = 0; Long v = 0; Long length; char cha[64000]; char chaInput[64000]; Structure *structure; Visitor *visitor; visitor = new PrintDrawer; //Case 구조 Long j = 0; Long x; //전체 사각형을 그린다 CPoint pt[4]; Long printX = sCase->GetX() * 4; Long printY = sCase->GetY() * 4; Long printWidth = sCase->GetWidth() * 4; Long printHeight = sCase->GetHeight() * 4; Long printMidX = sCase->GetMidX() * 4; Long printMidY = sCase->GetMidY() * 4; pt[0].x = printX; pt[0].y = printY; pt[1].x = printX + printWidth; pt[1].y = printY; pt[2].x = printX + printWidth; pt[2].y = printY + printHeight; pt[3].x = printX; pt[3].y = printY + printHeight; pDC->Polygon(pt, 4); //왼쪽 대각선을 그린다 pDC->MoveTo(CPoint(printX, printY)); pDC->LineTo(CPoint(printMidX, printMidY)); //오른쪽 대각선을 그린다. pDC->MoveTo(CPoint(printX + printWidth, printY)); pDC->LineTo(CPoint(printMidX, printMidY)); //전체 사각형을 둘로 나눈다 pDC->MoveTo(CPoint(printX, printMidY)); pDC->LineTo(CPoint(printX + printWidth, printMidY)); //TRUE, FALSE 구간을 나눈다 pDC->MoveTo(CPoint(printMidX, printMidY)); pDC->LineTo(CPoint(printMidX, printY + printHeight)); //조건문, TRUE, FALSE 글씨를 적는다 //contents를 배열에 복사한다. strcpy(cha, sCase->GetContents().c_str()); //길이를 구한다 length = strlen(cha); //문자열을 출력한다 while (i < length + 1) { //chaInput에 배열에있는 것을 하나씩 넣어준다. chaInput[j] = cha[i]; //cha가 만약 리턴캐리지이면 if (cha[i] == '\r' || cha[i] == '\0') { //chaInput에 넣었던 리턴캐리지를 널문자로 바꿔준다. chaInput[j] = '\0'; //차곡차곡 넣어주었던 chaInput을 텍스트아웃으로 출력시켜준다. pDC->TextOut(printX + (printWidth / 2), (printY + (printMidY - printY) / 5) + k, chaInput); //chaInput을 초기화시켜준다. j = -1; i++; k = k + 15; } j++; i++; } pDC->TextOut(printX + (printWidth / 10), printY + (printMidY - printY) * 1 / 2, "TRUE"); pDC->TextOut(printMidX + (((printX + printWidth) - printMidX) / 2), printY + ((printMidY - printY) * 1 / 2), "FALSE"); //midY2를 구한다 Long midY2 = printMidY + 100; pDC->MoveTo(CPoint(printX, midY2)); pDC->LineTo(CPoint(printMidX, midY2)); Long standardWidth = printMidX - printX; Long divideWidth = standardWidth / (sCase->GetCount() + 1); //반복해서 케이스문을 그린다. x = printX; j = 0; while (j <= sCase->GetCount()) { pDC->MoveTo(CPoint(x, printMidY)); pDC->LineTo(CPoint(x, printY + printHeight)); //contents를 배열에 복사한다. strcpy(cha, sCase->GetCaseString(j).c_str()); //길이를 구한다 length = strlen(cha); i = 0; v = 0; k = 0; //문자열을 출력한다 while (i < length + 1) { //chaInput에 배열에있는 것을 하나씩 넣어준다. chaInput[v] = cha[i]; //cha가 만약 리턴캐리지이면 if (cha[i] == '\r' || cha[i] == '\0') { //chaInput에 넣었던 리턴캐리지를 널문자로 바꿔준다. chaInput[v] = '\0'; //차곡차곡 넣어주었던 chaInput을 텍스트아웃으로 출력시켜준다. pDC->TextOut(x + (divideWidth / 2), printMidY + ((midY2 - printMidY) / 3) + k, chaInput); //chaInput을 초기화시켜준다. v = -1; i++; k = k + 15; } v++; i++; } x += divideWidth; j++; } pDC->TextOut((x - divideWidth) + (divideWidth / 6), printMidY + ((midY2 - printMidY) / 3), "default"); i = 0; while (i < sCase->GetLength()) { structure = sCase->GetChild(i); structure->AcceptPrint(visitor, pDC); i++; } if (visitor != 0) { delete visitor; } } PrintDrawer& PrintDrawer::operator=(const PrintDrawer& source){ return *this; }
[ "noreply@github.com" ]
justtookoff.noreply@github.com
586642535890a4705ad4cd65de24dd23fe6a281f
db04ecf258aef8a187823b8e47f4a1ae908e5897
/Cplus/FlattenBinaryTreetoLinkedList.cpp
812f1e994941e6615964e6dd3fe4f4f7a055f2b7
[ "MIT" ]
permissive
JumHorn/leetcode
9612a26e531ceae7f25e2a749600632da6882075
abf145686dcfac860b0f6b26a04e3edd133b238c
refs/heads/master
2023-08-03T21:12:13.945602
2023-07-30T07:00:50
2023-07-30T07:00:50
74,735,489
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
//Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: void flatten(TreeNode *root) { TreeNode dummy, *d = &dummy; preorder(root, d); } void preorder(TreeNode *root, TreeNode *&pre) { if (root == nullptr) return; TreeNode *left = root->left, *right = root->right; root->left = nullptr; pre->right = root; pre = root; preorder(left, pre); preorder(right, pre); } };
[ "JumHorn@gmail.com" ]
JumHorn@gmail.com
cb985a48458f063a4d6edc8fd94768ae1155d1af
fcffc4a91dcc4c2ec3ed814f6a949e9d7e8a83fa
/SDL_OpenGL_app.cpp
1a65e950683effc77cda4868336911840b8bd1f5
[]
no_license
IAmCorbin/SDL_OpenGL_app
721394445563083d0559eb3848f82c8d8729416e
7b289b7695fb0df1604e402e0ca0c3587ea401e9
refs/heads/master
2020-05-19T09:05:38.145314
2010-02-23T09:26:44
2010-02-23T09:26:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,234
cpp
// SDL_OpenGL_app.cpp // Class for creating a new SDL and OpenGL Application #include "SDL_OpenGL_app.h" //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::// //:::::::::::::SDL_OpenGL_app CLASS METHODS::::::::::::::::::// SDL_OpenGL_app::SDL_OpenGL_app() : fov(45.0f), zNear(0.1f), zFar(500.0f), incAngle(0.1f), incZoom(0.01f), xMove(0.0f), yMove(0.0f), zoom(-30.0f), angleX(-45.0f), angleY(0.0f), angleZ(15.0f), mousemove(false), gameover(false) { } void SDL_OpenGL_app::init(const char* titleTxt, const char* iconTxt, int width=800, int height=600, bool full=false) { fullscreen = full; //START SDL and error check if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)==-1) { //error initializing SDL fprintf(stderr,"Could not initialize SDL!\n"); exit(1); } else { //SDL initialized fprintf(stdout,"SDL initialized!\n"); atexit(SDL_Quit); } //Initialize Joystick if present if(SDL_NumJoysticks()>0) { //grab the first joystick joystick =SDL_JoystickOpen(0); //get the number of buttons joystickButtons = SDL_JoystickNumButtons(joystick); //enable joystick events SDL_JoystickEventState(SDL_ENABLE); } //Set Window Title SDL_WM_SetCaption(titleTxt,iconTxt); //initialize OpenGL SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 ); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 ); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glShadeModel(GL_SMOOTH); resize(width,height); } void SDL_OpenGL_app::run() { //SDL Event Structure SDL_Event event; while(!this->isGameover()) { //draw the current frame this->drawFrame(); //swap OpenGL Buffers SDL_GL_SwapBuffers(); //EVENTS if(SDL_PollEvent(&event)) { this->handleEvents(event); } else { this->handleKeys(); } } } void SDL_OpenGL_app::resize(int width, int height) { //Resize WIDTH = width; HEIGHT = height; //load window and error check if(fullscreen) MainWindow = SDL_SetVideoMode(WIDTH,HEIGHT,32,SDL_OPENGL | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN); else MainWindow = SDL_SetVideoMode(WIDTH,HEIGHT,0,SDL_OPENGL | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE); if(!MainWindow) { fprintf(stderr,"Error with SDL_SetVideoMove!\n"); exit(1); }else { fprintf(stderr,"SDL_SetVideoMode Successfull!\n"); } glViewport(0, 0, WIDTH, HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (height <= 0) height = 1; int aspectratio = WIDTH / HEIGHT; gluPerspective(fov, aspectratio, zNear, zFar); glMatrixMode(GL_MODELVIEW); //enable culling for performance and proper display glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); //enable depth testing for proper display glEnable(GL_DEPTH_TEST); glLoadIdentity(); } Uint8* SDL_OpenGL_app::getKeystate() { keystate = SDL_GetKeyState(NULL); return keystate; } //Mouse, Quit and Resize events void SDL_OpenGL_app::handleEvents(SDL_Event event) { switch(event.type) { //hangle resize //handle mouse movements case SDL_MOUSEBUTTONDOWN: if(event.button.button == SDL_BUTTON_LEFT) { if(!mousemove) mousemove = true; } else if(event.button.button == SDL_BUTTON_WHEELUP ) { if(abs(zoom)>zNear) zoom += 1.0f; } else if(event.button.button == SDL_BUTTON_WHEELDOWN ) { if(abs(zoom)<zFar) zoom -= 1.0f; } break; case SDL_MOUSEBUTTONUP: if(event.button.button == SDL_BUTTON_LEFT) if(mousemove) mousemove = false; break; case SDL_MOUSEMOTION: if(mousemove) { if(event.motion.xrel > 0 ) angleY += 1.0f; if(event.motion.xrel < 0 ) angleY -= 1.0f; if(event.motion.yrel > 0 ) angleX += 1.0f; if(event.motion.yrel < 0 ) angleX -= 1.0f; } break; case SDL_VIDEORESIZE: resize(event.resize.w, event.resize.h); break; //handle quit case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: gameover = true; break; default: break; } break; case SDL_QUIT: gameover = true; break; default: break; } } void SDL_OpenGL_app::handleKeys() { //grab keyboard state SDL_OpenGL_app::getKeystate(); //process key data //TRANSLATE //zoom in if (keystate[SDLK_i] ) { if(abs(zoom)>zNear) { zoom += incZoom; } }//zoom out if (keystate[SDLK_o] ) { if(abs(zoom)<zFar) { zoom -= incZoom; } }//translate world camera X if (keystate[SDLK_LEFT] ) { xMove += .01; } if (keystate[SDLK_RIGHT] ) { xMove -= .01; } //translate world camera Y if (keystate[SDLK_DOWN] ) { yMove += .01; } if (keystate[SDLK_UP] ) { yMove -= .01; } //ROTATE //rotate world around X if (keystate[SDLK_KP8] ) { angleX += incAngle; } if (keystate[SDLK_KP2] ) { angleX -= incAngle; } //rotate world around Y if (keystate[SDLK_KP4] ) { angleY += incAngle; if(angleY == 360) angleY = 0; } if (keystate[SDLK_KP6] ) { angleY -= incAngle; if(angleY == 0) angleY = 360; } //rotate world around Z if (keystate[SDLK_KP1] ) { angleZ += incAngle; } if (keystate[SDLK_KP3] ) { angleZ -= incAngle; } } void SDL_OpenGL_app::drawFrame() { SDL_OpenGL_app::drawFrame_Open(); } void SDL_OpenGL_app::drawFrame_Open() { //CLEAR glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //DRAW glLoadIdentity(); //apply camera location and zoom glTranslatef(xMove,yMove,zoom); //apply X Rotation glRotatef(angleX, 1.0f, 0.0f, 0.0f); //apply Y Rotation glRotatef(angleY, 0.0f, 1.0f, 0.0f); //apply Z Rotation glRotatef(angleZ, 0.0f, 0.0f, 1.0f); //Let OpenGL know about Vertex and Color array glEnableClientState(GL_VERTEX_ARRAY); //We want a vertex array glEnableClientState(GL_COLOR_ARRAY); //and a color array } void SDL_OpenGL_app::drawFrame_Close() { glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } //gluPerspective //fovy // Specifies the field of view angle, in degrees, in the y direction. //aspect // Specifies the aspect ratio that determines // the field of view in the x direction. // The aspect ratio is the ratio of x (width) to y (height). //zNear // Specifies the distance from the viewer to the near clipping plane (always positive). //zFar // Specifies the distance from the viewer to the far clipping plane (always positive). void SDL_OpenGL_app::gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * M_PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); } void SDL_OpenGL_app::setGameover() { gameover = true; } bool SDL_OpenGL_app::isGameover() { return gameover; } //:::::::::::::SDL_OpenGL_app CLASS METHODS::::::::::::::::::// //:::::END:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::END::::::://
[ "Corbin@IAmCorbin.net" ]
Corbin@IAmCorbin.net
5f8413f6dee2c381bdb9f9b2410d359d34a28fa2
ff3f093552bd4bd4a1ce172afc18c5e473844b02
/xwa_hook_d3dinfos_textures/hook_d3dinfos_textures/d3dinfos.cpp
5377f4b1317b6c80fcb69e0ba9080a036919f4d6
[]
no_license
hixio-mh/xwa_hooks
d31172d2249c60bf12aaff60301d8814fe9f3ec7
c97e4634c0e084665d007f7bc053b69ca7370522
refs/heads/master
2022-11-18T19:28:56.170099
2020-07-23T16:20:50
2020-07-23T16:20:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,295
cpp
#include "targetver.h" #include "d3dinfos.h" #include "config.h" #pragma pack(push, 1) struct XwaD3DInfo { char m00[0x53]; XwaD3DInfo* pNext; XwaD3DInfo* pPrevious; }; static_assert(sizeof(XwaD3DInfo) == 91, "size of XwaD3DInfo must be 91"); #pragma pack(pop) class D3DInfoArray { public: D3DInfoArray() { auto lines = GetFileLines("hooks.ini", "hook_d3dinfos_textures"); if (lines.empty()) { lines = GetFileLines("hook_d3dinfos_textures.cfg"); } int count = abs(GetFileKeyValueInt(lines, "Size")); if (count == 0) { count = 10000; } this->_d3dinfos.reserve(count); } int Size() { return this->_d3dinfos.capacity(); } XwaD3DInfo* Data() { return this->_d3dinfos.data(); } private: std::vector<XwaD3DInfo> _d3dinfos; }; D3DInfoArray g_XwaD3DInfos; int InitD3DInfosHook(int* params) { auto& XwaD3DInfosFirstEmpty = *(XwaD3DInfo**)0x00686B24; auto& XwaD3DInfosFirstUsed = *(XwaD3DInfo**)0x00686B28; auto& XwaD3DInfosCount = *(int*)0x00686B2C; int size = g_XwaD3DInfos.Size(); XwaD3DInfo* data = g_XwaD3DInfos.Data(); for (int i = 0; i < size - 1; i++) { data[i] = {}; data[i].pNext = &data[i + 1]; } data[size - 1] = {}; XwaD3DInfosFirstEmpty = &data[0]; XwaD3DInfosFirstUsed = nullptr; XwaD3DInfosCount = 0; return 0; }
[ "JeremyAnsel@users.noreply.github.com" ]
JeremyAnsel@users.noreply.github.com
1bda00844dd3dc2c4af66df38867da60c7e71481
89db00ac521f82738df606dff95403ae0cf9a52f
/SDL_Demo/Source files/GameWindow.cpp
d98d55d8cf4614cde6f3e274a6dccef6ae07950e
[]
no_license
n1yazbek/Helicopter-Game-final-project-
6f6cc85fb3d3704414085df32f775abb31145833
dc578b99b1e5a226bf0eea7ee5674aadde122aec
refs/heads/master
2023-04-29T08:08:22.033610
2021-05-12T22:22:40
2021-05-12T22:22:40
353,833,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,934
cpp
#include "GameWindow.h" GameWindow::GameWindow(const char* title) :window(NULL), renderer(NULL){ window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, GetWidth(), GetHeight(), SDL_WINDOW_SHOWN); if (window == NULL) { cerr << "There was an error while creating the window" << endl << SDL_GetError() << endl; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); } SDL_Texture* GameWindow::loadTexture(const char* filename) { SDL_Texture* texture = NULL; texture = IMG_LoadTexture(renderer, filename); if (texture == NULL) cout << "Failed to load texture: " << SDL_GetError() << endl; return texture; } void GameWindow::clear() { SDL_RenderClear(renderer); } void GameWindow::render(const Sprite& sprite) { SDL_Rect src; if (sprite.getRows() != 1 || sprite.getCols()!=1) { int cls = 1; int frameW = sprite.getFrameW(), frameH = sprite.getFrameH(); SDL_QueryTexture(sprite.GetTex(), NULL, NULL, &frameW, &frameH); int time_r = (SDL_GetTicks() / sprite.getAnimSpeed()) % (sprite.getRows() ); int time_c = (SDL_GetTicks() / sprite.getAnimSpeed()) % (sprite.getCols()); src.y = sprite.getFrameH() * time_r; src.x = sprite.getFrameW() * time_c; src.w = sprite.getRect().w; src.h = sprite.getRect().h; } else{ src.x = sprite.getRect().x; src.y = sprite.getRect().y; src.w = sprite.getRect().w; src.h = sprite.getRect().h; } SDL_Rect dst; dst.x = sprite.GetX(); dst.y = sprite.GetY(); dst.w = sprite.getRect().w; dst.h = sprite.getRect().h; SDL_Texture* txt = sprite.GetTex(); SDL_RenderCopy(renderer, txt, &src, &dst); } void GameWindow::renderScore( Helicopter& helic) { SDL_QueryTexture(helic.scoreText, NULL, NULL, &helic.texW, &helic.texH); SDL_RenderCopy(renderer, helic.scoreText, NULL, &helic.scoreRect); } void GameWindow::textCreator(TTF_Font* font, SDL_Color color, const char* text, Helicopter&helic) { SDL_Surface* textSurface = TTF_RenderText_Solid(font, text, color); helic.scoreText = SDL_CreateTextureFromSurface(renderer, textSurface); } void GameWindow::render_BestScore(Helicopter& helic) { SDL_QueryTexture(helic.BestScoreText, NULL, NULL, &helic.BestTexW, &helic.BestTexH); SDL_RenderCopy(renderer, helic.BestScoreText, NULL, &helic.BestScoreRect); } void GameWindow::BestScore_Creator(TTF_Font* font, SDL_Color color, const char* text, Helicopter& helic) { SDL_Surface* textSurface = TTF_RenderText_Solid(font, text, color); helic.BestScoreText = SDL_CreateTextureFromSurface(renderer, textSurface); } void GameWindow::display() { SDL_RenderPresent(renderer); } int GameWindow::GetWidth()const{ return width; } int GameWindow::GetHeight() const{ return height; } SDL_Renderer* GameWindow::getRenderer() const { return this->renderer; } GameWindow::~GameWindow() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); }
[ "niiazbek.mamasaliev@edu.bme.hu" ]
niiazbek.mamasaliev@edu.bme.hu
673715f129f87fad8ffe4db256a34fedfb7bd541
a5909aaec6e4aab8a779ca8bacc4af8f6c1295f3
/samples/12_InitFrameBuffers/12_InitFrameBuffers.cpp
2340e042797046893db3ed9fb3599b9b5d06dbd4
[ "Apache-2.0" ]
permissive
cdotstout/Vulkan-Hpp
538e97e209d18fee139f7482093095ed90644797
eaf09ee61e6cb964cf72e0023cd30777f8e3f9fe
refs/heads/master
2020-07-02T00:00:41.267108
2019-07-25T12:26:03
2019-07-25T12:26:03
201,353,822
0
1
Apache-2.0
2020-01-11T00:44:33
2019-08-08T23:44:48
C++
UTF-8
C++
false
false
3,434
cpp
// Copyright(c) 2019, NVIDIA 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. // // VulkanHpp Samples : 12_InitFrameBuffers // Initialize framebuffers #include "../utils/utils.hpp" #include "vulkan/vulkan.hpp" #include <iostream> static char const* AppName = "12_InitFrameBuffers"; static char const* EngineName = "Vulkan.hpp"; int main(int /*argc*/, char ** /*argv*/) { try { vk::UniqueInstance instance = vk::su::createInstance(AppName, EngineName, {}, vk::su::getInstanceExtensions()); #if !defined(NDEBUG) vk::UniqueDebugReportCallbackEXT debugReportCallback = vk::su::createDebugReportCallback(instance); #endif vk::PhysicalDevice physicalDevice = instance->enumeratePhysicalDevices().front(); vk::su::SurfaceData surfaceData(instance, AppName, AppName, vk::Extent2D(64, 64)); std::pair<uint32_t, uint32_t> graphicsAndPresentQueueFamilyIndex = vk::su::findGraphicsAndPresentQueueFamilyIndex(physicalDevice, *surfaceData.surface); vk::UniqueDevice device = vk::su::createDevice(physicalDevice, graphicsAndPresentQueueFamilyIndex.first, vk::su::getDeviceExtensions()); vk::su::SwapChainData swapChainData(physicalDevice, device, *surfaceData.surface, surfaceData.extent, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, vk::UniqueSwapchainKHR(), graphicsAndPresentQueueFamilyIndex.first, graphicsAndPresentQueueFamilyIndex.second); vk::su::DepthBufferData depthBufferData(physicalDevice, device, vk::Format::eD16Unorm, surfaceData.extent); vk::UniqueRenderPass renderPass = vk::su::createRenderPass(device, swapChainData.colorFormat, depthBufferData.format); /* VULKAN_KEY_START */ vk::ImageView attachments[2]; attachments[1] = depthBufferData.imageView.get(); std::vector<vk::UniqueFramebuffer> framebuffers; framebuffers.reserve(swapChainData.imageViews.size()); for (auto const& view : swapChainData.imageViews) { attachments[0] = view.get(); framebuffers.push_back(device->createFramebufferUnique(vk::FramebufferCreateInfo(vk::FramebufferCreateFlags(), renderPass.get(), 2, attachments, surfaceData.extent.width, surfaceData.extent.height, 1))); } // Note: No need to explicitly destroy the Framebuffers, as the destroy functions are called by the destructor of the UniqueFramebuffer on leaving this scope. /* VULKAN_KEY_END */ #if defined(VK_USE_PLATFORM_WIN32_KHR) DestroyWindow(surfaceData.window); #else #pragma error "unhandled platform" #endif } catch (vk::SystemError err) { std::cout << "vk::SystemError: " << err.what() << std::endl; exit(-1); } catch (std::runtime_error err) { std::cout << "std::runtime_error: " << err.what() << std::endl; exit(-1); } catch (...) { std::cout << "unknown error\n"; exit(-1); } return 0; }
[ "mtavenrath@users.noreply.github.com" ]
mtavenrath@users.noreply.github.com
e69f41719effeae0e6a8e6ffbc59dfc75ebd7662
bad4cb7ec18961d4cedcf827f687198886bd744e
/500-599/547-friend-circles.cpp
c4330a566b41da04dec8a20eeeec44c35b54bf30
[]
no_license
lamborghini1993/LeetCode
505fb3fef734deb9a04e342058f4cedc6ffdc8d2
818833ca87e8dbf964c0743d8381408964d37c71
refs/heads/master
2021-12-26T19:54:09.451175
2021-08-15T15:27:20
2021-08-15T15:27:20
160,816,839
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
#include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <string> #include <queue> #include <climits> #include <algorithm> #include <unordered_map> using namespace std; class Solution { public: int row, col; int findCircleNum(vector<vector<int>> &M) { row = M.size(); if (row < 1) return 0; col = M[0].size(); vector<bool> vis(row); int result = 0; for (int i = 0; i < row; i++) { if (vis[i]) continue; vis[i] = true; DFS(vis, M, i); result++; } return result; } void DFS(vector<bool> &vis, vector<vector<int>> &grid, int x) { for (int i = 0; i < col; i++) { if (x == i || vis[i] || grid[x][i] == 0) continue; vis[i] = true; DFS(vis, grid, i); } } };
[ "1323242382@qq.com" ]
1323242382@qq.com
22c41bf05ed2bbad30e2e0d479443c56a31a6266
cac6b164b1946be1f64fe47f50239dd4e61392ae
/src/qt/optionsdialog.cpp
12fcd1b82f59ca464be925c639dd662149238488
[ "MIT" ]
permissive
shacker6868/signatumclassicd
ccddbf0213613ec7b5eccb6d4eade9a3a88c3aa6
fb2d969a7853a140088396687beb56153e2b6abd
refs/heads/master
2021-01-19T12:51:08.591971
2017-08-25T04:32:25
2017-08-25T04:32:25
100,336,108
1
0
null
null
null
null
UTF-8
C++
false
false
7,792
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); mapper->addMapping(ui->useBlackTheme, OptionsModel::UseBlackTheme); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Signatumclassic."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Signatumclassic."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
[ "signatum-classic@protonmail.com" ]
signatum-classic@protonmail.com
cf0528f61aeeefef1a010ce692318643ae80ea68
a3d61b8e29f489cba3c2ff2393af488d5c3df40b
/DeformableObject.hpp
fc8fd13168daa19b4e723276f125c925849eb976
[]
no_license
PeterZhouSZ/adaptiveDeformables
343208e4269bfd1dc1e7a60388cf6c7762f27b07
652599d10c1fae4062c6e001c4751b7ab24baa35
refs/heads/master
2021-09-18T20:46:40.541413
2018-07-19T21:34:21
2018-07-19T21:34:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,124
hpp
#pragma once #include <vector> #include <iostream> #include <json/json.h> #include "Particle.hpp" struct DeformableObject{ DeformableObject(const Json::Value& jv); void dump(const std::string& filename) const; void dumpWithColor(const std::string& filename) const; //void writeHierarchy(const std::string& filename) const; //initialization stuff void computeNeighbors(); void computeBasisAndVolume(); //void computeHierarchy(); //timestepping methods void applyGravity(double dt); void applyElasticForces(double dt); //void applyElasticForcesAdaptive(double dt); void applyElasticForcesNoOvershoot(double dt); void updatePositions(double dt); void bounceOffGround(); void damp(double dt); void springDamping(double dt); Mat3 computeDeformationGradient(int pIndex) const; Mat3 computeDeformationGradientRBF(int pIndex) const; void RBFInit(); //data std::vector<Particle> particles; double lambda, mu, density, dampingFactor; double rbfDelta; //double scalingVarianceThreshold, angularVarianceThreshold; //int hierarchyLevels, parentsPerParticle, int neighborsPerParticle; double particleSize; //static constants confuse me //int desiredNumNeighbors() const { return 24; } std::vector<RenderInfo> renderInfos; void assertFinite() const{ for(const auto& p : particles){ if(!p.position.allFinite()){ std::cout << "bad position! " << std::endl; exit(1); } if(!p.velocity.allFinite()){ std::cout << "bad velocity!" << std::endl; exit(1); } } std::cout << "all finite!" << std::endl; } private: //use to accumulate forces. Stored as a member to avoid allocationg it each timestep std::vector<Vec3> forces; std::vector<Vec3> dampedVelocities; //same for damping //hierarchy 0 is the smallest //std::vector<std::vector<int>> hierarchy; }; //return the points corresponding to cluster centers //from among those specified in indices //n is the number of clusters //returned vector IS SORTED std::vector<int> kMeans(const DeformableObject& d, const std::vector<int>& indices, int n);
[ "ben.james.jones@gmail.com" ]
ben.james.jones@gmail.com
ad107d784307f66de034af1e20db2eed41149780
f14626611951a4f11a84cd71f5a2161cd144a53a
/武侠世界/代码/客户端/SceneEdit/src/AddLightObjectPlugin.cpp
c1d589aa2de8e9f485e5222c642335db4d3eff35
[]
no_license
Deadmanovi4/mmo-resourse
045616f9be76f3b9cd4a39605accd2afa8099297
1c310e15147ae775a59626aa5b5587c6895014de
refs/heads/master
2021-05-29T06:14:28.650762
2015-06-18T01:16:43
2015-06-18T01:16:43
null
0
0
null
null
null
null
GB18030
C++
false
false
12,230
cpp
#include "AddLightObjectPlugin.h" #include "SceneManipulator.h" #include "Core/WXLightObject.h" #include "Core/WXObjectProxy.h" #include "Core/WXSceneInfo.h" #include "Core/TerrainData.h" #include <OgreEntity.h> #include <OgreSceneNode.h> #include <OgreSceneManager.h> #include <OgreCamera.h> namespace WX { class AddLightObjectPlugin::Indicator { public: Indicator(const ObjectPtr &object, Ogre::SceneManager *sceneMgr, WX::SceneManipulator *sceneManipulator) : mProxy(NULL), mOldPos(Ogre::Vector3::ZERO) { assert(sceneMgr && sceneManipulator); mProxy = new ObjectProxy(object); mSceneManipulator = sceneManipulator; mCurrentLightEntity = NULL; // 根据光源位置来定节点位置 Ogre::Vector3 pos = VariantCast<Ogre::Vector3>(object->getProperty("position")); mIndicatorSceneNode = sceneManipulator->getIndicatorRootSceneNode()->createChildSceneNode(pos); // mIndicatorSceneNode->scale(2.0,15.0,2.0); // 创建三个entity分别来代表三种光源的模型 mPointLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"point","pointLight.mesh"); mDirectionalLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"directional","directionalLight.mesh"); mDirectionalLightEntity->setQueryFlags(0); mSpotLightEntity = sceneMgr->createEntity(mIndicatorSceneNode->getName()+"spotlight","spotLight.mesh"); mPointLightEntity->setUserObject(mProxy); mDirectionalLightEntity->setUserObject(mProxy); mSpotLightEntity->setUserObject(mProxy); // 根据光源类型来挂接模型 setIndicatorModel(mProxy->getObject()->getPropertyAsString("type")); // 根据光源方向来决定scenenode方向 Ogre::Vector3 &dir = VariantCast<Ogre::Vector3>(object->getProperty("direction")); setDirection(dir); showIndicator(false); } ~Indicator() { if (mIndicatorSceneNode) { mIndicatorSceneNode->destroy(); } if (mPointLightEntity) { mPointLightEntity->destroy(); } if (mDirectionalLightEntity) { mDirectionalLightEntity->destroy(); } if (mSpotLightEntity) { mSpotLightEntity->destroy(); } if (mProxy) { delete mProxy; mProxy = NULL; } } void showIndicator( bool show ) { assert(mIndicatorSceneNode); assert( mCurrentLightEntity && mDirectionalLightEntity ); // 如果是方向光 if ( mCurrentLightEntity == mDirectionalLightEntity ) { mIndicatorSceneNode->setVisible(show); mIndicatorSceneNode->showBoundingBox(false); // 获取到摄像机与地形的交点 Ogre::Vector3 pos; Ogre::Ray cameraRay( mSceneManipulator->getCamera()->getPosition(), mSceneManipulator->getCamera()->getDirection() ); bool hit = mSceneManipulator->getTerrainIntersects(cameraRay, pos); if (hit) { // 在地形上的一米处出现光源指示器 float height = mSceneManipulator->getTerrainData()->getHeightAt(pos.x, pos.z) + 100.0f; mIndicatorSceneNode->setPosition(pos.x, height, pos.z); } } else { mIndicatorSceneNode->showBoundingBox(show); } } void setPosition( const Ogre::Vector3 &pos ) { assert(mIndicatorSceneNode); mOldPos = pos; if ( mCurrentLightEntity != mDirectionalLightEntity ) mIndicatorSceneNode->setPosition(pos); } void setDirection( const Ogre::Vector3 &dir ) { assert(mIndicatorSceneNode); // 分别计算出节点三个轴上的方向 Ogre::Vector3 yAdjustVec = -dir; yAdjustVec.normalise(); Ogre::Vector3 xVec = mIndicatorSceneNode->getOrientation().zAxis().crossProduct( yAdjustVec ); xVec.normalise(); Ogre::Vector3 zVec = xVec.crossProduct( yAdjustVec ); zVec.normalise(); mIndicatorSceneNode->setOrientation(Ogre::Quaternion( xVec, yAdjustVec, zVec )); } void setIndicatorModel( const Ogre::String &lightType ) { assert( !lightType.empty() ); assert ( mIndicatorSceneNode ); assert ( mPointLightEntity ); assert ( mDirectionalLightEntity ); assert ( mSpotLightEntity ); mIndicatorSceneNode->detachAllObjects(); if ( lightType == "point" ) { // mIndicatorSceneNode->attachObject(mPointLightEntity); mCurrentLightEntity = mPointLightEntity; if ( mOldPos != Ogre::Vector3::ZERO ) mIndicatorSceneNode->setPosition(mOldPos); } else if ( lightType == "directional") { // mIndicatorSceneNode->attachObject(mDirectionalLightEntity); // 因为方向光本身没有位置属性,不过指示器会出现在地形中心,会改变scene node的位置 // 所以这里先把旧位置保存下来 mOldPos = mIndicatorSceneNode->getPosition(); mCurrentLightEntity = mDirectionalLightEntity; // mIndicatorSceneNode->setPosition(0, 0 ,0); // 获取到地形中心点的高度 float height = mSceneManipulator->getTerrainData()->getHeightAt(0,0); mIndicatorSceneNode->setPosition(0, height ,0); } else if ( lightType == "spotlight" ) { // mIndicatorSceneNode->attachObject(mSpotLightEntity); mCurrentLightEntity = mSpotLightEntity; if ( mOldPos != Ogre::Vector3::ZERO ) mIndicatorSceneNode->setPosition(mOldPos); } mIndicatorSceneNode->attachObject(mCurrentLightEntity); } protected: Ogre::Entity *mPointLightEntity; Ogre::Entity *mDirectionalLightEntity; Ogre::Entity *mSpotLightEntity; Ogre::Entity *mCurrentLightEntity; Ogre::SceneNode *mIndicatorSceneNode; WX::SceneManipulator *mSceneManipulator; ObjectProxy* mProxy; Ogre::Vector3 mOldPos; }; AddLightObjectPlugin::AddLightObjectPlugin(WX::SceneManipulator* sceneManipulator) { assert(sceneManipulator); mSceneManipulator = sceneManipulator; mSceneManipulator->addSceneListener(this); } AddLightObjectPlugin::~AddLightObjectPlugin() { mSceneManipulator->removeSceneListener(this); clearIndicators(); } ////////////////////////////////////////////////////////////////////////// void AddLightObjectPlugin::onSceneReset(void) { clearIndicators(); typedef WX::SceneInfo::Objects Objects; const WX::SceneInfo* sceneInfo = mSceneManipulator->getSceneInfo(); const Objects& objects = sceneInfo->getObjects(); for (Objects::const_iterator it = objects.begin(); it != objects.end(); ++it) { Ogre::String type = (*it)->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { LightObject *lightObject = static_cast<LightObject *> ((*it).get()); Indicator *indicator = new Indicator( *it, mSceneManipulator->getSceneManager(), mSceneManipulator ); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(*it, indicator)); assert(inserted.second); } } } void AddLightObjectPlugin::onAddObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { LightObject *lightObject = static_cast<LightObject *> (object.get()); Indicator *indicator = new Indicator(object,mSceneManipulator->getSceneManager(), mSceneManipulator ); std::pair<Indicators::iterator, bool> inserted = mIndicators.insert(Indicators::value_type(object, indicator)); assert(inserted.second); } } void AddLightObjectPlugin::onRemoveObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { delete i->second; i->second = NULL; mIndicators.erase(i); } } } /* void AddLightObjectPlugin::onRenameObject(const ObjectPtr& object, const String& oldName) { }*/ void AddLightObjectPlugin::onSelectObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { i->second->showIndicator(true); } } } void AddLightObjectPlugin::onDeselectObject(const ObjectPtr& object) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { i->second->showIndicator(false); } } } void AddLightObjectPlugin::onDeselectAllObjects(void) { for (Indicators::iterator i = mIndicators.begin(); i != mIndicators.end(); ++i ) { if ( i->second ) { i->second->showIndicator(false); } } } void AddLightObjectPlugin::onObjectPropertyChanged(const ObjectPtr& object, const String& name) { Ogre::String type = object->getType(); // 判断,如果是能处理的类型(LightObject),就处理 if ( type == "Light" ) { Indicators::iterator i = mIndicators.find(object); if ( i != mIndicators.end() ) { if ( name == "position" ) i->second->setPosition( VariantCast<Ogre::Vector3>(object->getProperty("position")) ); else if ( name == "type" ) { Ogre::String lightType = object->getPropertyAsString("type"); i->second->setIndicatorModel(lightType); } else if ( name == "direction" ) { i->second->setDirection( VariantCast<Ogre::Vector3>(object->getProperty("direction")) ); } } } } void AddLightObjectPlugin::clearIndicators(void) { for (Indicators::iterator i = mIndicators.begin(); i != mIndicators.end(); ++i ) { if ( i->second ) { delete i->second; i->second = NULL; } } mIndicators.clear(); } }
[ "ichenq@gmail.com" ]
ichenq@gmail.com
7b9a585fa86ad340d46ca2614e14fae8621b6a44
b06d2b7a619db62dafbd1b5df065d961994cd008
/ip.cpp
6401be0268d4d49179d658eda557152d745477b3
[]
no_license
ehddud758/arp_spoofing
ca6db7654175f24a59d0d358801fd07fe4244e3f
c955f7974057cfa3d92958269756400be31b1e52
refs/heads/master
2020-03-26T06:04:11.734667
2018-08-13T16:00:40
2018-08-13T16:00:40
144,588,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,920
cpp
#ifndef __IPV4_ADDR_CPP__ #define __IPV4_ADDR_CPP__ #include "ip.h" #include <arpa/inet.h> #include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; IPv4_addr& IPv4_addr::operator = (const char* rhs) { int ret = inet_pton(AF_INET, rhs, &_ip); switch(ret) { case 0: cout << "inet_pton return zero ip='" << rhs << "'" << endl; break; case 1: _ip = ntohl(_ip); break; default: cout << "inet_pton return " << ret << endl; } return *this; } IPv4_addr& IPv4_addr::operator = (const string& rhs) { const char *c = rhs.c_str(); *this = c; return *this; } void IPv4_addr::hex_dump() { uint8_t hex[4]; uint32_t __ip = htonl(_ip); memcpy(hex, &__ip, 4); printf("%02hhX.%02hhX.%02hhX.%02hhX", hex[0], hex[1], hex[2], hex[3]); } void IPv4_addr::ascii_dump() { uint8_t hex[4]; uint32_t __ip = htonl(_ip); memcpy(hex, &__ip, 4); printf("%hhu.%hhu.%hhu.%hhu", hex[0], hex[1], hex[2], hex[3]); } void IPv4_addr::write_mem(uint8_t *mem) { uint32_t __ip = htonl(_ip); memcpy(mem, &__ip, 4); } void IPv4_addr::parse_mem(uint8_t *mem) { memcpy(&_ip, mem, 4); _ip = ntohl(_ip); } void IPv4_addr::parse_mem(char *mem) { memcpy(&_ip, mem, 4); _ip = ntohl(_ip); } bool IPv4_addr::is_equal(uint32_t val) { return _ip == val; } bool IPv4_addr::is_equal(IPv4_addr addr) { return _ip == addr._ip; } string IPv4_addr::to_string() { char buf[32]; uint32_t __ip = htonl(_ip); const char* ret = inet_ntop(AF_INET, &__ip, buf, sizeof(buf)); if (ret == NULL) { fprintf(stderr, "IPv4_addr to_string error\n"); return string(""); } string str(buf); return str; } IPv4_addr::operator struct in_addr() { struct in_addr ret; ret.s_addr = _ip; return ret; } char* IPv4_addr::to_string(char* mem, int buf_size) { uint32_t __ip = htonl(_ip); const char* ret = inet_ntop(AF_INET, &__ip, mem, buf_size); return (char*)ret; } #endif
[ "aaa7663@naver.com" ]
aaa7663@naver.com
4ad87aa1232082e9d147c2bfacebc0b2f964b894
3d4f69dba44f5e285c19c6762494073148011bbe
/solution/441. Arranging Coins/441_01.cpp
d75e56f28d0bc7cefc782222cae847d8fd95bf1d
[]
no_license
cmeslo/leetcode
a0fd9826aaf77380c6cfb6bd24f26024345077be
9b304046c2727364a3c9e5c513cb312fabdc729e
refs/heads/master
2023-08-31T02:34:56.962597
2023-08-30T17:06:07
2023-08-30T17:06:07
96,622,859
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
class Solution { public: int arrangeCoins(int n) { int coins = 0; while (n-coins > coins) n -= coins++; return coins; } };
[ "noreply@github.com" ]
cmeslo.noreply@github.com
2fedd3cbdf4915ca3749281e325f34633495e4b7
21ab8235a1deadbd3914c15645226ca45978b1ad
/simmigoogle1.cpp
1785b66a76e766bb9ef4286809c37072fb6781be
[]
no_license
surarijit/DSA_ALGO
8a9079c71444928f88995679d16dafb50df8be5b
1e1a1e189c9cd11b222150df2aa89952cb15de8d
refs/heads/master
2023-01-29T04:36:49.892183
2020-12-07T07:01:47
2020-12-07T07:01:47
281,638,964
0
4
null
2021-10-01T10:58:11
2020-07-22T09:50:53
C++
UTF-8
C++
false
false
1,407
cpp
/* ARIJIT SUR @duke_knight @surcode @comeback IIT ISM */ #include<bits/stdc++.h> #define SIZE 200 #define mod (ll)(1e9+7) #define INF 0x3f3f3f3f #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) #define abs(a) (a>0?a:-a) #define all(a) a.begin(),a.end() #define maxelem(a) *max_element(all(a)) #define minelem(a) *min_element(all(a)) #define pb push_back #define pi pair<int,int> #define sort(a) sort(all(a)) #define reverse(a) reverse(all(a)) #define input(a) {for(int i1=0;i1<a.size();i1++) cin>>a[i1];} #define display(a) {for(int i1=0;i1<a.size();i1++) cout<<a[i1]<<" "; cout<<endl;} #define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; typedef long long ll; int dp[SIZE][SIZE][SIZE]; int solve(string X, string Y, int l, int r, int k) { if (!k) return 0; if (l < 0 | r < 0) return 1e9; if (dp[l][r][k] != -1) return dp[l][r][k]; int cost = abs((X[l] - 'a') - (Y[r] - 'a')); return dp[l][r][k] = min(cost + solve(X, Y, l - 1, r - 1, k - 1), min( solve(X, Y, l - 1, r, k), solve(X, Y, l, r - 1, k))); } void solve(){ int n,m,k; string a,b; cin>>n>>m>>k>>a>>b; memset(dp, -1, sizeof (dp)); int ans = solve(a,b,n-1,m-1,k); if(ans==1e9) cout<<-1<<endl; else cout<<ans<<endl; } int main() { IOS int t=1; cin>>t; while(t--){ solve(); } return 0; }
[ "arijit.sur1998@gmail.com" ]
arijit.sur1998@gmail.com
be58a95473b63f9443359e39de7994e4e349ec9c
72251ba180a723f3e653231b265efaedf6f31f8f
/tests/src/helper_func.cpp
64d68fd5e2d8cfb3c007583cb043fc238e8daf6e
[ "MIT" ]
permissive
fundies/Crash2D
b9e6bc1fe55d1957ea1f1320a7019e797ea0a322
40b14d4259d7cedeea27d46f7206b80a07a3327c
refs/heads/master
2023-03-30T02:01:19.942794
2017-09-11T10:50:33
2017-09-11T10:50:33
63,020,131
1
4
MIT
2021-04-02T08:00:21
2016-07-10T21:59:32
C++
UTF-8
C++
false
false
897
cpp
#include "helper.hpp" #include <gtest/gtest.h> Segment mSegment(Segment s, Vector2 displacement) { return Segment(s.GetPoint(0) + displacement, s.GetPoint(1) + displacement); } Circle mCircle(Circle c, Vector2 displacement) { return Circle(c.GetCenter() + displacement, c.GetRadius()); } Polygon mPolygon(Polygon p, Vector2 displacement) { Polygon pD; pD.SetPointCount(p.GetPointCount()); for (unsigned i = 0; i < p.GetPointCount(); ++i) { pD.SetPoint(i, p.GetPoint(i) + displacement); } pD.ReCalc(); return pD; } bool vectorContains(std::vector<Vector2> &coords, Vector2 pt) { auto it = std::find(std::begin(coords), std::end(coords), pt); return (it != std::end(coords)); } bool vectorEQ(std::vector<Vector2> &a, std::vector<Vector2> &b) { if (a.size() != b.size()) return false; for (auto i : a) { if (!vectorContains(b, i)) return false; } return true; }
[ "cheeseboy16@gmail.com" ]
cheeseboy16@gmail.com
950a9f6167ab15c462bd28748effa1cd092d6849
cec0ca2a70535e17488b3bb6b23d678d7e2dadbb
/BirdGame/CGridNums.h
94e8c4ed86d57517d1b669a28892a81cd8e7f16e
[]
no_license
hb2008hahaha/NumberRecognitionGame
0327938624c43f1cd6ca6995f83a3c9f54010135
4d6193f94e53476a20d58e2d596a0134525e3f5a
refs/heads/master
2021-01-22T14:39:48.517902
2014-08-29T02:41:19
2014-08-29T02:41:19
null
0
0
null
null
null
null
GB18030
C++
false
false
2,013
h
#ifndef CGRIDNUMS_H #define CGRIDNUMS_H ////网格数字 #define BlockNums 10 //不超过32 #define ColNum 5 //每列5个方块 #include "global.h" class CGridNums{ public: CGridNums() { #ifdef QImage ImgBlock.load("://res/pig.png"); #endif } int Nums; char BlockFlag[BlockNums]; void InitGame() { int TmpNum=(2<<BlockNums)-1; int Value=rand()%(TmpNum-1)+1; for(int i=0;i<BlockNums;i++) BlockFlag[i]=(Value&1<<i)!=0; Nums=0; for(int i=0;i<BlockNums;i++) { Nums+= BlockFlag[i]; } } void DrawBoard(QPainter *painter) { for(int i=0;i<BlockNums;i++) DrawBlock(painter,i); } private: #ifdef QTImage QPixmap ImgBlock; #endif void DrawBlock(QPainter *painter,int pos) // { if(pos<0||pos>=BlockNums)return ; int x=pos%ColNum; int y=pos/ColNum; int m=x*BlockSize+1+LocX; //坐标变换 int n=y*BlockSize+1+LocY; #ifdef QTImage if(ImgBlock.isNull()!=true) { if(BlockFlag[pos]!=0)painter->drawPixmap(m,n,BlockSize,BlockSize,ImgBlock); } else { QColor penColor = Qt::green; penColor.setAlpha(80);//将颜色的透明度减小,使方框边界和填充色直接能区分开 if(BlockFlag[pos]==0)//如果被选中的话则变色 painter->setBrush(Qt::NoBrush); else painter->setBrush(Qt::blue); painter->setPen(penColor);//色绘制画笔 painter->drawRect(m,n,BlockSize-1,BlockSize-1);//输入参数依次为左上角坐标,长,宽 } #else QColor penColor = Qt::green; //penColor.setAlpha(80);//将颜色的透明度减小,使方框边界和填充色直接能区分开 if(BlockFlag[pos]==0)//如果被选中的话则变色 painter->setBrush(Qt::NoBrush); else painter->setBrush(Qt::blue); painter->setPen(penColor);//色绘制画笔 painter->drawRect(m,n,BlockSize-1,BlockSize-1);//输入参数依次为左上角坐标,长,宽 #endif } }; #endif // CGRIDNUMS_H
[ "hb2008hahaha@163.com" ]
hb2008hahaha@163.com
38a4707f7a24d9fd1c0ce72c15c2bc7149a2bff9
3b3b9e16fbc253d599783e1e36c7509bb7ceb273
/lg/도로건설3_다익스트라.cpp
d06c381c4afe39c931e659e08dcebd6f0e805734
[]
no_license
ttt977/algorithm
91e7357d4972a10b0b9af9a895249d8952a9d869
828a96b7d3ea6bf99830957d2626f2cd2c8722e0
refs/heads/master
2021-09-11T09:03:51.193340
2021-09-06T09:07:06
2021-09-06T09:07:06
191,852,243
0
0
null
null
null
null
UHC
C++
false
false
1,696
cpp
//다익스트라 알고리즘 활용 최단비용계산 #include <iostream> #include <queue> #include <algorithm> using namespace std; typedef pair<int,pair<int,int> > pii; //현재까지 거리,x,y 위치 저장 int N;//지도 크기 char map[110][110];//지도 정보 int visited[110][110];//방문여부체크 void Input_Data(){ cin >> N; for (int i = 0; i < N; i++){ cin >> map[i]; } } int bfs(int y, int x) //y,x 위치에서 N-1,N-1 위치까지의 최단 경로를 반환 { int arri[4] = {0,-1,0,1}; //좌/상/우/하 방문 int arrj[4] = {-1,0,1,0}; priority_queue<pii> q; //현재 위치에서 상/하/좌/우중 비용이 적은 것을 우선으로 탐색하기 위함 q.push(make_pair(0,make_pair(y,x))); //초기 거리,위치 q에 push visited[y][x] = 1; while(!q.empty()) { int cur_d = q.top().first; int cur_i = q.top().second.first; int cur_j = q.top().second.second; cur_d *= -1; //들어갈 때 (-) 했으므로 뺄때도 (-) 필요 if(cur_i == N-1 && cur_j == N-1) return cur_d; q.pop(); for(int k=0;k<4;k++) { int ni = cur_i + arri[k]; int nj = cur_j + arrj[k]; int nd = 0; if(ni < 0 || nj < 0 || ni > N-1 || nj > N-1) //범위초과냐? continue; if(visited[ni][nj] != 0) //기존방문했냐? continue; visited[ni][nj] = 1; //방문체크 nd = cur_d + (map[ni][nj] - '0'); //이전에방문했던 노드까지 거리 + 내 위치의 값 더하기 nd *= -1; //작은 값 기준으로 우선순위큐에서 뽑아내기 위함 q.push(make_pair(nd,make_pair(ni,nj))); } } } int main(){ int ans = -1; Input_Data(); ans = bfs(0,0); cout << ans << endl; return 0; }
[ "hslim@lginnotek.com" ]
hslim@lginnotek.com
1128dd5a6f655c57c61ee4de6db2126f1c08418f
8c5c24633f216d08c8a8e6c7d395d22f5a61076e
/Stacks/stack.h
288ac6eb446bf97d42168681fa3fbd945fa75a3f
[]
no_license
williamchin999/Implementing-Stack-C
ba89f48d74d929671abdbe5b963be79ec6c78889
e97350a0ce43818d198f16d3148deb44b7ecdffa
refs/heads/main
2023-08-28T20:24:51.651575
2021-10-26T23:47:56
2021-10-26T23:47:56
421,616,536
0
0
null
null
null
null
UTF-8
C++
false
false
2,087
h
//Copyright 2021 William Chin //Email: wchin1@sfsu.edu //This file is apart of CSC340 -Assignment 3 #pragma once #include <iostream> #include "stackinterface.h" #define SIZE 6 template<class ItemType> class stack { ItemType * arr; int top; int capacity; public: stack(int size = SIZE); // constructor ~stack(); // destructor bool push(const ItemType&); bool pop(); ItemType peek() const; bool isEmpty() const; bool isFull(); int size(); }; using namespace std; template<class ItemType> stack<ItemType>::stack(int size) { arr = new ItemType[size]; capacity = size; top = -1; } template<class ItemType> stack<ItemType>::~stack() { delete[] arr; } template<class ItemType> bool stack<ItemType>::push(const ItemType & x) { //overflow chek if (isFull()) { cout << "Stack is full, doubling size" << endl; ItemType* old_arr = arr; arr = new ItemType[2 * capacity]; for (int i = 0; i < capacity; i++) { arr[i] = old_arr[i]; } delete [] old_arr; capacity *= 2; } cout << "Pushing " << x << endl; arr[++top] = x; return true; } template<class ItemType> bool stack<ItemType>::pop() { //underflow check if (isEmpty()) { cout << "Underflow" << endl; } else { cout << "Popping " << peek() << endl; arr[top--]; } return true; } template<class ItemType> ItemType stack<ItemType>::peek() const { if (!isEmpty()) return arr[top]; else { ItemType temp{ ' ' }; cout << "Empty" << endl; return temp; } } template<class ItemType> int stack<ItemType>::size() { return top + 1; } template<class ItemType> bool stack<ItemType>::isEmpty() const { return top == -1; } template<class ItemType> bool stack<ItemType>::isFull() { if (top == capacity - 1) { return 1; } else return 0; }
[ "noreply@github.com" ]
williamchin999.noreply@github.com
5fca83dadbcbc189da9c3e40178a9113c7772fc1
5f9b26a41102c38da28b8f757a5586f9bc7cf71a
/crates/zig_build_bin_windows_x86_64/zig-windows-x86_64-0.5.0+80ff549e2/lib/zig/libcxx/include/compare
48564c8ef860a0164c34767202ceccc931766a43
[ "MIT", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
jeremyBanks/zig_with_cargo
f8e65f14adf17ed8d477f0856257422c2158c63f
f8ee46b891bbcdca7ff20f5cad64aa94c5a1d2d1
refs/heads/master
2021-02-06T10:26:17.614138
2020-03-09T04:46:26
2020-03-09T04:46:26
243,905,553
4
1
null
null
null
null
UTF-8
C++
false
false
27,204
// -*- C++ -*- //===-------------------------- compare -----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_COMPARE #define _LIBCPP_COMPARE /* compare synopsis namespace std { // [cmp.categories], comparison category types class weak_equality; class strong_equality; class partial_ordering; class weak_ordering; class strong_ordering; // named comparison functions constexpr bool is_eq (weak_equality cmp) noexcept { return cmp == 0; } constexpr bool is_neq (weak_equality cmp) noexcept { return cmp != 0; } constexpr bool is_lt (partial_ordering cmp) noexcept { return cmp < 0; } constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; } constexpr bool is_gt (partial_ordering cmp) noexcept { return cmp > 0; } constexpr bool is_gteq(partial_ordering cmp) noexcept { return cmp >= 0; } // [cmp.common], common comparison category type template<class... Ts> struct common_comparison_category { using type = see below; }; template<class... Ts> using common_comparison_category_t = typename common_comparison_category<Ts...>::type; // [cmp.alg], comparison algorithms template<class T> constexpr strong_ordering strong_order(const T& a, const T& b); template<class T> constexpr weak_ordering weak_order(const T& a, const T& b); template<class T> constexpr partial_ordering partial_order(const T& a, const T& b); template<class T> constexpr strong_equality strong_equal(const T& a, const T& b); template<class T> constexpr weak_equality weak_equal(const T& a, const T& b); } */ #include <__config> #include <type_traits> #include <array> #ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER #pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD #if _LIBCPP_STD_VER > 17 // exposition only enum class _LIBCPP_ENUM_VIS _EqResult : unsigned char { __zero = 0, __equal = __zero, __equiv = __equal, __nonequal = 1, __nonequiv = __nonequal }; enum class _LIBCPP_ENUM_VIS _OrdResult : signed char { __less = -1, __greater = 1 }; enum class _LIBCPP_ENUM_VIS _NCmpResult : signed char { __unordered = -127 }; struct _CmpUnspecifiedType; using _CmpUnspecifiedParam = void (_CmpUnspecifiedType::*)(); class weak_equality { _LIBCPP_INLINE_VISIBILITY constexpr explicit weak_equality(_EqResult __val) noexcept : __value_(__val) {} public: static const weak_equality equivalent; static const weak_equality nonequivalent; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept; #endif private: _EqResult __value_; }; _LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::nonequivalent(_EqResult::__nonequiv); _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY inline constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v.__value_ != _EqResult::__zero; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY inline constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY inline constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept { return __v; } #endif class strong_equality { _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_equality(_EqResult __val) noexcept : __value_(__val) {} public: static const strong_equality equal; static const strong_equality nonequal; static const strong_equality equivalent; static const strong_equality nonequivalent; // conversion _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == _EqResult::__zero ? weak_equality::equivalent : weak_equality::nonequivalent; } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept; #endif private: _EqResult __value_; }; _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equal(_EqResult::__equal); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequal(_EqResult::__nonequal); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequivalent(_EqResult::__nonequiv); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v.__value_ == _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != _EqResult::__zero; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v.__value_ != _EqResult::__zero; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept { return __v; } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class partial_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr partial_ordering(_NCmpResult __v) noexcept : __value_(_ValueT(__v)) {} constexpr bool __is_ordered() const noexcept { return __value_ != _ValueT(_NCmpResult::__unordered); } public: // valid values static const partial_ordering less; static const partial_ordering equivalent; static const partial_ordering greater; static const partial_ordering unordered; // conversion constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::unordered(_NCmpResult ::__unordered); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__is_ordered() && __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v.__is_ordered() && 0 >= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return !__v.__is_ordered() || __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return !__v.__is_ordered() || __v.__value_ != 0; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept { return __v < 0 ? partial_ordering::greater : (__v > 0 ? partial_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class weak_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr weak_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr weak_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} public: static const weak_ordering less; static const weak_ordering equivalent; static const weak_ordering greater; // conversions _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } _LIBCPP_INLINE_VISIBILITY constexpr operator partial_ordering() const noexcept { return __value_ == 0 ? partial_ordering::equivalent : (__value_ < 0 ? partial_ordering::less : partial_ordering::greater); } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 != __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return 0 >= __v.__value_; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept { return __v < 0 ? weak_ordering::greater : (__v > 0 ? weak_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR class strong_ordering { using _ValueT = signed char; _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_ordering(_EqResult __v) noexcept : __value_(_ValueT(__v)) {} _LIBCPP_INLINE_VISIBILITY explicit constexpr strong_ordering(_OrdResult __v) noexcept : __value_(_ValueT(__v)) {} public: static const strong_ordering less; static const strong_ordering equal; static const strong_ordering equivalent; static const strong_ordering greater; // conversions _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept { return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } _LIBCPP_INLINE_VISIBILITY constexpr operator strong_equality() const noexcept { return __value_ == 0 ? strong_equality::equal : strong_equality::nonequal; } _LIBCPP_INLINE_VISIBILITY constexpr operator partial_ordering() const noexcept { return __value_ == 0 ? partial_ordering::equivalent : (__value_ < 0 ? partial_ordering::less : partial_ordering::greater); } _LIBCPP_INLINE_VISIBILITY constexpr operator weak_ordering() const noexcept { return __value_ == 0 ? weak_ordering::equivalent : (__value_ < 0 ? weak_ordering::less : weak_ordering::greater); } // comparisons _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept; #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept; _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept; #endif private: _ValueT __value_; }; _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::less(_OrdResult::__less); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equal(_EqResult::__equal); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equivalent(_EqResult::__equiv); _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::greater(_OrdResult::__greater); _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v.__value_ >= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 == __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 != __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 < __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 <= __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 > __v.__value_; } _LIBCPP_INLINE_VISIBILITY constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return 0 >= __v.__value_; } #ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR _LIBCPP_INLINE_VISIBILITY constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept { return __v; } _LIBCPP_INLINE_VISIBILITY constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept { return __v < 0 ? strong_ordering::greater : (__v > 0 ? strong_ordering::less : __v); } #endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR // named comparison functions _LIBCPP_INLINE_VISIBILITY constexpr bool is_eq(weak_equality __cmp) noexcept { return __cmp == 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_neq(weak_equality __cmp) noexcept { return __cmp != 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_lt(partial_ordering __cmp) noexcept { return __cmp < 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_lteq(partial_ordering __cmp) noexcept { return __cmp <= 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_gt(partial_ordering __cmp) noexcept { return __cmp > 0; } _LIBCPP_INLINE_VISIBILITY constexpr bool is_gteq(partial_ordering __cmp) noexcept { return __cmp >= 0; } namespace __comp_detail { enum _ClassifyCompCategory : unsigned{ _None, _WeakEq, _StrongEq, _PartialOrd, _WeakOrd, _StrongOrd, _CCC_Size }; template <class _Tp> _LIBCPP_INLINE_VISIBILITY constexpr _ClassifyCompCategory __type_to_enum() noexcept { if (is_same_v<_Tp, weak_equality>) return _WeakEq; if (is_same_v<_Tp, strong_equality>) return _StrongEq; if (is_same_v<_Tp, partial_ordering>) return _PartialOrd; if (is_same_v<_Tp, weak_ordering>) return _WeakOrd; if (is_same_v<_Tp, strong_ordering>) return _StrongOrd; return _None; } template <size_t _Size> constexpr _ClassifyCompCategory __compute_comp_type(std::array<_ClassifyCompCategory, _Size> __types) { std::array<int, _CCC_Size> __seen = {}; for (auto __type : __types) ++__seen[__type]; if (__seen[_None]) return _None; if (__seen[_WeakEq]) return _WeakEq; if (__seen[_StrongEq] && (__seen[_PartialOrd] || __seen[_WeakOrd])) return _WeakEq; if (__seen[_StrongEq]) return _StrongEq; if (__seen[_PartialOrd]) return _PartialOrd; if (__seen[_WeakOrd]) return _WeakOrd; return _StrongOrd; } template <class ..._Ts> constexpr auto __get_comp_type() { using _CCC = _ClassifyCompCategory; constexpr array<_CCC, sizeof...(_Ts)> __type_kinds{{__comp_detail::__type_to_enum<_Ts>()...}}; constexpr _CCC _Cat = sizeof...(_Ts) == 0 ? _StrongOrd : __compute_comp_type(__type_kinds); if constexpr (_Cat == _None) return void(); else if constexpr (_Cat == _WeakEq) return weak_equality::equivalent; else if constexpr (_Cat == _StrongEq) return strong_equality::equivalent; else if constexpr (_Cat == _PartialOrd) return partial_ordering::equivalent; else if constexpr (_Cat == _WeakOrd) return weak_ordering::equivalent; else if constexpr (_Cat == _StrongOrd) return strong_ordering::equivalent; else static_assert(_Cat != _Cat, "unhandled case"); } } // namespace __comp_detail // [cmp.common], common comparison category type template<class... _Ts> struct _LIBCPP_TEMPLATE_VIS common_comparison_category { using type = decltype(__comp_detail::__get_comp_type<_Ts...>()); }; template<class... _Ts> using common_comparison_category_t = typename common_comparison_category<_Ts...>::type; // [cmp.alg], comparison algorithms // TODO: unimplemented template<class _Tp> constexpr strong_ordering strong_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr weak_ordering weak_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr partial_ordering partial_order(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr strong_equality strong_equal(const _Tp& __lhs, const _Tp& __rhs); template<class _Tp> constexpr weak_equality weak_equal(const _Tp& __lhs, const _Tp& __rhs); #endif // _LIBCPP_STD_VER > 17 _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP_COMPARE
[ "_@jeremy.ca" ]
_@jeremy.ca
a2d68aa98db6f4b9fa2b72255547dcbe84c0764c
63ae3dbfae3e4273e9d6d98d945341512a4b2177
/Andrew_Sandbox/Version_14/Resources.h
2922155b8f7d0a462119a00d60514b134368d15b
[]
no_license
akm0012/Comp5360_Project1
a89686ee5f56ab00227334363869323a4940245c
3c1fe98c3455d3673276cf80ae71caf8b6470cd1
refs/heads/master
2020-05-17T19:42:58.042454
2015-04-12T19:50:32
2015-04-12T19:50:32
31,297,604
0
0
null
null
null
null
UTF-8
C++
false
false
4,492
h
/* * Comp5360: Project 1 * * File: Resources.h * Created by Andrew K. Marshall on 2/23/15 * Refactored by Evan Hall on 3/12/15 * Repatterened by Andrew Marshall on 3/13/15 * Due Date: 3/18/15 * Version: 1.0 * Version Notes: Final Version. */ #ifndef RESOURCES_H #define RESOURCES_H #define MAX_MESSAGE_LEN 4096 #define MAX_PACKET_LEN 4096 #define NUM_THREADS 1 #define LEFT_LANE 5 #define RIGHT_LANE 0 #define PASSING_SPEED_INCREASE 5 // 5 m/s #define PASSING_BUFFER 20 #define PLATOON_SPACE_BUFFER 15 // The space in between cars #define TRUCK_LENGTH 10 #define CAR_LENGTH 5 #define DANGER_CLOSE 20 #define MAX_NUM_OF_NODES 11 // Packet Types #define INIT_LOCATION_PACKET 7 // Indicates this is a new node joining the sim #define LOCATION_PACKET 8 // Indicates this packet has updated location info #define REQUEST_PACKET 16 // Indicates this packet is a request #define PLATOON_JOIN_INFO_PACKET 32 // Indicates this packet has platoon info for a joining car #define PLATOON_WAIT_TO_JOIN_PACKET 33 // Indicates the car should wait to join #define CAR_JOIN_STATUS 64 // Used to give the all clear // Pre-defined Messages #define ALL_CLEAR 20 #define REQUEST_DENIED 100 #define REQUEST_GRANTED 101 #define REQUEST_ENTER_PLATOON 50 // A request to enter the car train #define REQUEST_LEAVE_PLATOON 51 // A request to leave the platoon #define MAX_HOSTNAME_LENGTH 50 #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <iomanip> #include <iostream> #include <cstdlib> #include <unistd.h> #include <fstream> #include <pthread.h> #include <deque> #include <time.h> using std::string; using std::cout; using std::endl; using std::ifstream; using std::ofstream; using std::deque; using std::to_string; using std::setprecision; typedef double Timestamp; // Used for timing and statistics typedef struct { time_t sec; long nsec; } utime; // This is the struct that represents our packet struct packet_to_send { // Header unsigned int sequence_num; // 4 bytes unsigned int source_address; // 4 bytes unsigned int previous_hop; // 4 bytes (address of last hop) int port_num; // 4 bytes, the port number of the source int previous_hop_node_num; // Node number of last hop unsigned int destination_address; // 4 bytes (All 1's means broadcast) double time_sent; // 8 bytes int node_number_source; // 4 bytes // Only used for status packets bool was_sent; // Used to keep track of if this was "sent in the simulator" // Payload unsigned short packet_type; // 2 bytes (Defines if update location packet or request packet) float x_position; // 4 bytes int y_position; // 4 bytes float x_speed; // 4 bytes bool platoon_member; // 1 byte (Indicates if this node is in a platoon) int number_of_platoon_members; unsigned short message; // 2 bytes int size_of_packet_except_hostname; // Size of everything in this packet, except the hostname char hostname[MAX_HOSTNAME_LENGTH]; } __attribute__(( __packed__ )); typedef struct packet_to_send tx_packet; struct node_info { int node_number; string node_hostname; string node_port_number; float node_x_coordinate; int node_y_coordinate; //int number_of_links; int connected_nodes[MAX_NUM_OF_NODES + 1]; // string connected_hostnames[MAX_NUM_OF_NODES]; // string connected_ports[MAX_NUM_OF_NODES]; }; struct cache_table { unsigned int source_address[MAX_NUM_OF_NODES]; int highest_sequence_num[MAX_NUM_OF_NODES]; int number_of_broadcasts[MAX_NUM_OF_NODES]; // # Times we have bradcasted highest seq.# packet }; // Prototypes extern void send_packet(string hostname_to_send, string port_to_send, packet_to_send packet_out); static int get_number_of_digits(int number) { int result; if (number < 0) { number *= -1; result++; } else if (number == 0) { return 1; } do { number /= 10; result++; } while (number != 0); return result; } static int get_number_of_digits(float number) { int result; if (signbit(number)) { number *= -1; result++; } else if (number == 0.0) { return 1; } double intpart, fractpart; fractpart = modf(number, &intpart); while (intpart != 0.0) { intpart /= 10; result++; } while (fractpart != 0.0) { fractpart *= 10; fractpart = modf(fractpart, &intpart); result++; } return result; } #endif
[ "akm0012@auburn.edu" ]
akm0012@auburn.edu
976454f1f09baa171d6308c2152a1df1d235ecc6
cc8a3923b471d5645d7d349d87b8bd44c3121737
/T/T16/schmidtt,adejumool-csc236T16/smallclass.cpp
51bff13e28e3657c8e40d57868d581fd3ff4a903
[]
no_license
Tradd-Schmidt/CSC236-Data-Structures
85c3b9c9b613ea8fbd5dfd6cb13a5c92e2be8879
4952163644ffe6dd91873a5aaea44b3f57e5496e
refs/heads/master
2021-04-09T10:57:35.691220
2019-03-14T20:12:30
2019-03-14T20:12:30
125,456,245
1
0
null
2019-03-14T20:12:31
2018-03-16T03:05:32
Python
UTF-8
C++
false
false
866
cpp
//small class called DayOfYear #include <iostream> #include "stdlib.h" #include "smallclass.h" using namespace std; //Uses iostream: void DayOfYear::input( ) { cout << "Enter the month as a number: "; cin >> month; cout << "Enter the day of the month: "; cin >> day; check_date( ); } //Uses iostream: void DayOfYear::output( ) { cout << "month = " << month << ", day = " << day << endl; } void DayOfYear::set(int new_month, int new_day) { month = new_month; day = new_day; check_date(); } void DayOfYear::check_date( ) { if ((month < 1) || (month > 12) || (day < 1) || (day > 31)) { cout << "Illegal date. Aborting program.\n"; exit(1); } } int DayOfYear::get_month( ) { return month; } int DayOfYear::get_day( ) { return day; }
[ "noreply@github.com" ]
Tradd-Schmidt.noreply@github.com
ad8f5239146d53b7968fc59f16e00ae1e0ff200e
3606ebb854d102a67ab65f5f37ad981244a2f9e1
/cpp/design_patterns/singleton.cpp
1d3bcf8e6c92f959e60f97e073f47d032817d720
[]
no_license
pashnidgunde/Code
ebbe0d8fac65bc840a00baf281cf0d6bfcdfd1db
418e68406738ba10b25433b5c4173dc28e2e037a
refs/heads/master
2023-02-25T03:08:50.252370
2022-08-21T20:59:16
2022-08-21T20:59:16
56,103,688
1
0
null
2022-08-13T10:28:22
2016-04-12T22:59:30
C++
UTF-8
C++
false
false
578
cpp
#include <cassert> #include <iostream> #include <mutex> #include <thread> class Singleton { private: Singleton() = default; ~Singleton() = default; static Singleton *instance; std::mutex _m; public: static Singleton *getInstance() { if (nullptr == instance) { std::lock_guard<mutex>(m); if (nullptr == instance) instance = new Singleton(); } return instance; } }; Singleton *Singleton::instance = nullptr; int main() { Singleton *s = Singleton::getInstance(); Singleton *s1 = Singleton::getInstance(); assert(s == s1); }
[ "pashnidgunde@gmail.com" ]
pashnidgunde@gmail.com
0fa5d9f11a60f90ff00db7bc4392de83cf57565a
d4433d8c51e9dc6e0c2904def0a524c9125555de
/hero/HeroExpItem.h
1afe92fef3c1facd8bb025b64abfd18eb82459cf
[]
no_license
54993306/Classes
3458d9e86d1f0e2caa791cde87aff383b2a228bb
d4d1ec5ca100162bd64156deba3748ce1410151d
refs/heads/master
2020-04-12T06:23:49.273040
2016-11-17T04:00:19
2016-11-17T04:00:19
58,427,218
1
3
null
null
null
null
UTF-8
C++
false
false
825
h
 #ifndef __HEROEXPITEM_ #define __HEROEXPITEM_ #include "AppUI.h" #include "scene/layer/LayerManager.h" #include "mainCity/CityData.h" #include "hero/HeroData.h" class CHeroExpItem: public BaseLayer { public: CREATE_LAYER(CHeroExpItem); virtual bool init(); void onEnter(); void onEvolveBtn(CCObject* pSender); void onExit(); void showMoveDirection(CHero* hero); void evolveTask(const CEvolInfo& evInfo ); void showItem(CItem* item); bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); protected: CCObject* tableviewDataSource(CCObject* pConvertCell, unsigned int uIdx); void addTableCell(unsigned int uIdx, CTableViewCell * pCell); void onRecvTask(CCObject* pSender); private: CLayout *m_ui; CHero *m_hero; CLayout *m_cell; CTableView *m_tableView; CEvolInfo m_evolInfo; }; #endif
[ "54993306@qq.com" ]
54993306@qq.com
8c00a5ed93401e7ae58ad9eeb4dd4e9fe3fc883c
90517ce1375e290f539748716fb8ef02aa60823b
/solved/f-h/hotel-booking/hotel.cpp
336470bc837871c3046f543eb00e62693fd3978c
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
Code4fun4ever/pc-code
23e4b677cffa57c758deeb655fd4f71b36807281
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
refs/heads/master
2021-01-15T08:15:00.681534
2014-09-08T05:28:39
2014-09-08T05:28:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,637
cpp
#include <cstdio> #include <cstring> #include <list> #include <set> #include <vector> using namespace std; #define MAXN 10000 const int INF = 600 * 100000 + 10; #define Zero(v) memset(v, 0, sizeof(v)) #define cFor(t,v,c) for(t::const_iterator v=c.begin(); v != c.end(); ++v) typedef vector<int> IV; typedef vector<IV> IVV; // Graphs typedef int w_t; struct Graph { struct Edge { int v; w_t w; Edge(int V, w_t W) : v(V), w(W) {} }; typedef list<Edge> EL; typedef vector<EL> ELV; ELV adj; int n; void init(int N) { n=N; adj.clear(); adj.resize(n); } void add(int u, int v, w_t w) { adj[u].push_back(Edge(v, w)); } struct Node { int s; // number of hotel stops made int t; // accumulated travel time from last stop int v; // city Node(int S, int T, int V) : s(S), t(T), v(V) {} bool operator<(const Node &x) const { if (s != x.s) return s < x.s; if (t != x.t) return t < x.t; return v < x.v; } }; typedef set<Node> NS; int dijkstra(bool hs[], int H) { NS q; // dis[v][s] is the best known distance to reach v after s stops IVV dis = IVV(n, IV(H + 1, INF)); dis[0][0] = 0; q.insert(Node(0, 0, 0)); while (! q.empty()) { Node nd = *(q.begin()); q.erase(q.begin()); if (nd.v == n - 1) return nd.s; if (dis[nd.v][nd.s] < nd.t) continue; cFor (EL, e, adj[nd.v]) { int d = nd.t + e->w; if (d <= 600 && d < dis[e->v][nd.s]) { dis[e->v][nd.s] = d; q.insert(Node(nd.s, d, e->v)); } if (! hs[nd.v] || nd.s == H) continue; d = e->w; if (d <= 600 && d < dis[e->v][nd.s + 1]) { dis[e->v][nd.s + 1] = d; q.insert(Node(nd.s + 1, d, e->v)); } } } return -1; } }; int n, h, m; bool hotels[MAXN]; Graph g; int main() { while (true) { scanf("%d", &n); if (n == 0) break; Zero(hotels); scanf("%d", &h); for (int i = 0; i < h; ++i) { int c; scanf("%d", &c); hotels[c - 1] = true; } g.init(n); scanf("%d", &m); while (m--) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u, --v; g.add(u, v, w); g.add(v, u, w); } printf("%d\n", g.dijkstra(hotels, h)); } return 0; }
[ "leonardo@diptongonante.com" ]
leonardo@diptongonante.com
0ba27240f97b9236796448232c12bc11ec7747a2
23d096a2c207eff63f0c604825d4b2ea1a5474d9
/CRUZET/DataTest/plugins/deltaR.h
9ac3b1690876b52509002c816f1bbafb3475c7f9
[]
no_license
martinamalberti/BicoccaUserCode
40d8272c31dfb4ecd5a5d7ba1b1d4baf90cc8939
35a89ba88412fb05f31996bd269d44b1c6dd42d3
refs/heads/master
2021-01-18T09:15:13.790891
2013-08-07T17:08:48
2013-08-07T17:08:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,197
h
// -*- C++ -*- // // Package: deltaR // Class: deltaR // /**\class deltaR deltaR.h Description: <one line class summary> Implementation: <Notes on implementation> */ // $Id: deltaR.h,v 1.3 2008/11/13 17:33:37 govoni Exp $ // // system include files #include <memory> #include <vector> #include <map> #include <set> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalRawData/interface/EcalRawDataCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "CaloOnlineTools/EcalTools/interface/EcalTrackLengthMeasurement.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "PhysicsTools/UtilAlgos/interface/TFileService.h" #include "TFile.h" #include "TH1F.h" #include "TH2F.h" #include "TH3F.h" #include "TGraph.h" #include "TTree.h" #include <vector> // *** for TrackAssociation #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/Common/interface/Handle.h" #include "TrackingTools/TrackAssociator/interface/TrackDetectorAssociator.h" #include "TrackingTools/TrackAssociator/interface/TrackAssociatorParameters.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" // *** //for track length #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/EcalAlgo/interface/EcalBarrelGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" // class deltaR : public edm::EDAnalyzer { public: explicit deltaR (const edm::ParameterSet&) ; ~deltaR () ; private: virtual void beginJob (const edm::EventSetup&) {} ; virtual void analyze (const edm::Event&, const edm::EventSetup&) ; virtual void endJob () ; void initHists (int) ; private: edm::InputTag barrelSuperClusterCollection_ ; edm::InputTag endcapSuperClusterCollection_ ; edm::InputTag muonTracksCollection_ ; TrackDetectorAssociator trackAssociator_ ; TrackAssociatorParameters trackParameters_ ; TH1F * m_deltaRSCMu ; TH1F * m_deltaPhiSCMu ; TH1F * m_deltaEtaSCMu ; int m_totalMuons ; } ;
[ "" ]
8ad52db9984d49e517fed0a11e173ed94aa0f2f6
c4537de39f9a35c5e96df6203aa8df4aca725235
/PrintCommand.cpp
31d0ea9648f31fdcf02be3e18cba94fa6bf85133
[]
no_license
galsnir/Flight-Simulator-Part-1
a625cd60952310f056bb928442a66a18e95518fb
5dace7d017ac4ea0ad2d664f1141daeb5bc63e89
refs/heads/master
2020-04-14T00:44:52.306278
2018-12-29T21:14:26
2018-12-29T21:14:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
// // Created by anton on 12/21/18. // #include <iostream> #include "PrintCommand.h" /** * Method reads argument to command. If argument if variable, it prints value of that variable. If argument * is string, it takes off quotes, and prints contents of this string. * @param it - pointer to argument */ void PrintCommand ::execute(vector<string>::iterator &it) { Expression* tempExp; it++; string str = *it; if(str.at(0) == '\"' && str.at(str.length() - 1) == '\"') { str.erase(0, 1); str.erase(str.length() - 1, 1); cout << str << endl; } else if( dataBase->haveVar(*it)) { cout << dataBase->getVar(*it) << endl; } else { tempExp = dataBase->getNumericExpression(it); if(tempExp != NULL) cout << tempExp->calculate() << endl; else { throw RunTimeException("Error syntax, throw exception"); } } it++; }
[ "noreply@github.com" ]
galsnir.noreply@github.com
a974103cf067e446aa86e3db1dcef1e8e394a06d
8b9b1249163ca61a43f4175873594be79d0a9c03
/deps/boost_1_66_0/libs/test/test/writing-test-ts/assertion-construction-test.cpp
303e6c157564327fe8f6f0dfa463da739b1d6e88
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
maugf214/LiquidCore
f6632537dfb4686f4302e871d997992e6289eb65
80a9cce27ceaeeb3c8002c17ce638ed45410d3e6
refs/heads/master
2022-12-02T01:18:26.132951
2020-08-17T10:27:36
2020-08-17T10:27:36
288,151,167
0
1
MIT
2020-08-17T10:32:05
2020-08-17T10:32:04
null
UTF-8
C++
false
false
21,624
cpp
// (C) Copyright Gennadiy Rozental 2011-2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 62023 $ // // Description : unit test for new assertion construction based on input expression // *************************************************************************** // Boost.Test #define BOOST_TEST_MODULE Boost.Test assertion consruction test #include <boost/test/unit_test.hpp> #include <boost/test/tools/assertion.hpp> #include <boost/test/utils/is_forward_iterable.hpp> #include <boost/noncopyable.hpp> #include <map> #include <set> namespace utf = boost::unit_test; //____________________________________________________________________________// #define EXPR_TYPE( expr ) ( assertion::seed() ->* expr ) #if !defined(BOOST_TEST_FWD_ITERABLE_CXX03) // some broken compilers do not implement properly decltype on expressions // partial implementation of is_forward_iterable when decltype not available struct not_fwd_iterable_1 { typedef int const_iterator; typedef int value_type; bool size(); }; struct not_fwd_iterable_2 { typedef int const_iterator; typedef int value_type; bool begin(); }; struct not_fwd_iterable_3 { typedef int value_type; bool begin(); bool size(); }; BOOST_AUTO_TEST_CASE( test_forward_iterable_concept ) { { typedef std::vector<int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // should also work for references, but from is_forward_iterable typedef std::vector<int>& type; BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::list<int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::map<int, int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef std::set<int, int> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef float type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_1 type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_2 type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef not_fwd_iterable_3 type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { typedef char type; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(!utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // C-tables are in the forward_iterable concept, but are not containers typedef int type[10]; BOOST_CHECK_MESSAGE(!utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(!utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); } { // basic_cstring should be forward iterable and container typedef boost::unit_test::basic_cstring<char> type; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type >::value, "is_container_forward_iterable failed"); typedef boost::unit_test::basic_cstring<const char> type2; BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_size<type2>::value, "has_member_size failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_begin<type2>::value, "has_member_begin failed"); BOOST_CHECK_MESSAGE(utf::ut_detail::has_member_end<type2>::value, "has_member_end failed"); BOOST_CHECK_MESSAGE(utf::is_forward_iterable< type2 >::value, "is_forward_iterable failed"); BOOST_CHECK_MESSAGE(utf::is_container_forward_iterable< type2 >::value, "is_container_forward_iterable failed"); } } //is_container_forward_iterable_impl #endif BOOST_AUTO_TEST_CASE( test_basic_value_expression_construction ) { using namespace boost::test_tools; { predicate_result const& res = EXPR_TYPE( 1 ).evaluate(); BOOST_TEST( res ); BOOST_TEST( res.message().is_empty() ); } { predicate_result const& res = EXPR_TYPE( 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); } { predicate_result const& res = EXPR_TYPE( true ).evaluate(); BOOST_TEST( res ); BOOST_TEST( res.message().is_empty() ); } { predicate_result const& res = EXPR_TYPE( 1.5 ).evaluate(); BOOST_TEST( res ); } { predicate_result const& res = EXPR_TYPE( "abc" ).evaluate(); BOOST_TEST( res ); } { predicate_result const& res = EXPR_TYPE( 1>2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [1 <= 2]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_comparison_expression ) { using namespace boost::test_tools; { predicate_result const& res = EXPR_TYPE( 1>2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [1 <= 2]" ); } { predicate_result const& res = EXPR_TYPE( 100 < 50 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [100 >= 50]" ); } { predicate_result const& res = EXPR_TYPE( 5 <= 4 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [5 > 4]" ); } { predicate_result const& res = EXPR_TYPE( 10>=20 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [10 < 20]" ); } { int i = 10; predicate_result const& res = EXPR_TYPE( i != 10 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [10 == 10]" ); } { int i = 5; predicate_result const& res = EXPR_TYPE( i == 3 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [5 != 3]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_arithmetic_ops ) { using namespace boost::test_tools; { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( i+j !=8 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [3 + 5 == 8]" ); } { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( 2*i-j > 1 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 * 3 - 5 <= 1]" ); } { int j = 5; predicate_result const& res = EXPR_TYPE( 2<<j < 30 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 << 5 >= 30]" ); } { int i = 2; int j = 5; predicate_result const& res = EXPR_TYPE( i&j ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [2 & 5]" ); } { int i = 3; int j = 5; predicate_result const& res = EXPR_TYPE( i^j^6 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [3 ^ 5 ^ 6]" ); } // do not support // EXPR_TYPE( 99/2 == 48 || 101/2 > 50 ); // EXPR_TYPE( a ? 100 < 50 : 25*2 == 50 ); // EXPR_TYPE( true,false ); } //____________________________________________________________________________// struct Testee { static int s_copy_counter; Testee() : m_value( false ) {} Testee( Testee const& ) : m_value(false) { s_copy_counter++; } Testee( Testee&& ) : m_value(false) {} Testee( Testee const&& ) : m_value(false) {} bool foo() { return m_value; } operator bool() const { return m_value; } friend std::ostream& operator<<( std::ostream& ostr, Testee const& ) { return ostr << "Testee"; } bool m_value; }; int Testee::s_copy_counter = 0; Testee get_obj() { return Testee(); } Testee const get_const_obj() { return Testee(); } class NC : boost::noncopyable { public: NC() {} bool operator==(NC const&) const { return false; } friend std::ostream& operator<<(std::ostream& ostr, NC const&) { return ostr << "NC"; } }; BOOST_AUTO_TEST_CASE( test_objects ) { using namespace boost::test_tools; int expected_copy_count = 0; { Testee obj; Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( obj ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee const obj; Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( obj ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( get_obj() ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; predicate_result const& res = EXPR_TYPE( get_const_obj() ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); BOOST_TEST( Testee::s_copy_counter == expected_copy_count ); } { Testee::s_copy_counter = 0; Testee t1; Testee t2; predicate_result const& res = EXPR_TYPE( t1 != t2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [Testee == Testee]" ); BOOST_TEST( Testee::s_copy_counter == 0 ); } { NC nc1; NC nc2; predicate_result const& res = EXPR_TYPE( nc1 == nc2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [NC != NC]" ); } } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_pointers ) { using namespace boost::test_tools; { Testee* ptr = 0; predicate_result const& res = EXPR_TYPE( ptr ).evaluate(); BOOST_TEST( !res ); } { Testee obj1; Testee obj2; predicate_result const& res = EXPR_TYPE( &obj1 == &obj2 ).evaluate(); BOOST_TEST( !res ); } { Testee obj; Testee* ptr =&obj; predicate_result const& res = EXPR_TYPE( *ptr ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)Testee is false]" ); } { Testee obj; Testee* ptr =&obj; bool Testee::* mem_ptr =&Testee::m_value; predicate_result const& res = EXPR_TYPE( ptr->*mem_ptr ).evaluate(); BOOST_TEST( !res ); } // do not support // Testee obj; // bool Testee::* mem_ptr =&Testee::m_value; // EXPR_TYPE( obj.*mem_ptr ); } //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test_mutating_ops ) { using namespace boost::test_tools; { int j = 5; predicate_result const& res = EXPR_TYPE( j = 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j -= 5 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j *= 0 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j /= 10 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 4; predicate_result const& res = EXPR_TYPE( j %= 2 ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } { int j = 5; predicate_result const& res = EXPR_TYPE( j ^= j ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [(bool)0 is false]" ); BOOST_TEST( j == 0 ); } } BOOST_AUTO_TEST_CASE( test_specialized_comparator_string ) { using namespace boost::test_tools; { std::string s("abc"); predicate_result const& res = EXPR_TYPE( s == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( s == "abc" ); } { predicate_result const& res = EXPR_TYPE( std::string("abc") == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } { predicate_result const& res = EXPR_TYPE( "abc" == std::string("a") ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } { predicate_result const& res = EXPR_TYPE( std::string("abc") == std::string("a") ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); } } BOOST_AUTO_TEST_CASE( test_comparison_with_arrays ) { using namespace boost::test_tools; { char c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( c_string_array == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( c_string_array == "abc" ); } { char c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( "a" == c_string_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [a != abc]" ); BOOST_TEST( "abc" == c_string_array ); } { char const c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( c_string_array == "a" ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [abc != a]" ); BOOST_TEST( c_string_array == "abc" ); } { char const c_string_array[] = "abc"; predicate_result const& res = EXPR_TYPE( "a" == c_string_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == " [a != abc]" ); BOOST_TEST( "abc" == c_string_array ); } { long int c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( c_long_array == v_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 4 != 7. \nMismatch at position 2: 7 != 4. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( v_long_array == c_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 7 != 4. \nMismatch at position 2: 4 != 7. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int const c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( c_long_array == v_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 4 != 7. \nMismatch at position 2: 7 != 4. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } { long int const c_long_array[] = {3,4,7}; std::vector<long int> v_long_array(c_long_array, c_long_array + sizeof(c_long_array)/sizeof(c_long_array[0])); std::swap(v_long_array[1], v_long_array[2]); predicate_result const& res = EXPR_TYPE( v_long_array == c_long_array ).evaluate(); BOOST_TEST( !res ); BOOST_TEST( res.message() == ". \nMismatch at position 1: 7 != 4. \nMismatch at position 2: 4 != 7. " ); std::swap(v_long_array[1], v_long_array[2]); BOOST_TEST( c_long_array == v_long_array ); } } // EOF
[ "eric@flicket.tv" ]
eric@flicket.tv
9ef92fbe19b376a1dba70fdcd3367368348df6b0
3f5fbaeaaf62da1e4f9bfb7b349cf7a3a6e4efcb
/DSA/Linked List/mid of LL (2 methods).cpp
e303c5bdc8890fdb5a003895263dcbba8f306ea3
[]
no_license
dipesh-m/Data-Structures-and-Algorithms
f91cd3e3a71c46dc6ffe22dac6be22d454d01ec3
f3dfd6f1e0f9c0124d589ecdb60e7e0e26eb28fc
refs/heads/master
2023-05-26T05:14:19.258994
2021-05-26T16:41:11
2021-05-26T16:41:11
276,396,488
1
1
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
#include<iostream> using namespace std; #include "class Node.h" #include "taking input and printing LL.h" void printAt(Node* head, int i) { int j=0; while(j<i && head!=NULL) { head=head->next; j++; } if(head!=NULL) { cout<<head->data<<endl; } } int sizeIteratively(Node* head) { if(head==NULL) { return 0; } int c=0; while(head!=NULL) { c++; head=head->next; } return c; } int midOfLLUsingSize(Node* head) { if(head==NULL) { return INT_MIN; } int get_size=sizeIteratively(head); int mid=(get_size-1)/2; return mid; } int midOfLLUsing2Ptrs(Node* head) { if(head==NULL) { return INT_MIN; } Node* slow=head; Node* fast=head->next; int mid=0; while(fast!=NULL) { if(fast->next!=NULL) { fast=fast->next->next; mid+=1; } else { fast=fast->next; } slow=slow->next; } return mid; } int main() { cout<<"INSERT THE LL DATA:-"<<endl; Node* head=takeInput(); //for even sized LL, the index 1 less than (size of LL)/2 is treated as mid int mid1=midOfLLUsingSize(head); if(mid1!=INT_MIN) { cout<<"Mid of LL Using Size: "; printAt(head, mid1); } cout<<endl; int mid2=midOfLLUsing2Ptrs(head); if(mid2!=INT_MIN) { cout<<"Mid of LL Using 2 Pointers: "; printAt(head, mid2); } }
[ "62656237+dipesh-m@users.noreply.github.com" ]
62656237+dipesh-m@users.noreply.github.com
b37fb86311fbee709cb703096f8fe047728cda12
df6481f4023d47cfcbfa87318ceae38d870d14a6
/heimdall/source/FlashAction.h
b4e1b6baa070f6e41b931667ce4cf72ac927bbd0
[ "MIT" ]
permissive
nka11/Heimdall
152bd30e8bd9faef5f7a4136cddf5888056a8dea
efedda846db56b6ba9c0b8e337210843f084345a
refs/heads/master
2021-01-17T22:56:34.881802
2013-01-18T17:26:57
2013-01-18T17:26:57
6,088,699
1
0
null
null
null
null
UTF-8
C++
false
false
1,276
h
/* Copyright (c) 2010-2012 Benjamin Dobell, Glass Echidna 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.*/ #ifndef FLASHACTION_H #define FLASHACTION_H namespace Heimdall { namespace FlashAction { extern const char *usage; int Execute(int argc, char **argv); }; } #endif
[ "benjamin.dobell+git@glassechidna.com.au" ]
benjamin.dobell+git@glassechidna.com.au
d5bd7de2d25a51669dc06f714bb96c608d0bd850
6a310ae5f8e5fb460a3869ea0fcab25b133dea3e
/src/defin.cpp
b40db238ef913bbf752d73899f5003b146c0112f
[]
no_license
NZT48/nztKernel
4ef0c2a6be12007d0b749efa5795eae64e8fe35b
e043ba48ad0045b7db76df8e7711ec6438faf4a7
refs/heads/master
2022-04-09T22:59:32.391207
2020-03-15T17:14:59
2020-03-15T17:14:59
187,092,514
0
0
null
null
null
null
UTF-8
C++
false
false
52
cpp
#include "defin.h" unsigned volatile lockFlag = 0;
[ "nikolaztodorovic26@gmail.com" ]
nikolaztodorovic26@gmail.com
d27fcb69ef8452171f1fb4e3912465e111142484
276bf5f1534176d7ecdd28f49b5167fc141d7e33
/systemc-tutorial-examples/tlm/buffer/main.cpp
5d727b32c4e4dba4b26e9d45c977622f62d0c4c5
[]
no_license
vj-sananda/systemc
dfa56b8e1131e86ac1322be885fad3528fc24e74
492fa6effb304e18ec66918dd10f17b1fe86b4d8
refs/heads/master
2021-01-05T01:15:41.328636
2020-02-16T03:41:26
2020-02-16T03:41:26
240,826,440
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
#include "systemc.h" #include "flatbuffer.cpp" #include "complexbuffer.cpp" #include "bufwriter.cpp" /* simulation main function */ int sc_main(int argc, char *argv[]) { // instantiate a FlatBuffer and a Bufwriter FlatBuffer buf1("Buffer1"); Bufwriter writer("BufWriter1"); /* alternative: instantiate a ComplexBuffer */ ComplexBuffer buf2("Buffer2"); // link the buffer to the writer writer.buf(buf2); // also try: //writer.buf(buf2); // feeding writer the complex buffer // start the simulation sc_start(); }
[ "vsananda@macbook-pro-9.lan" ]
vsananda@macbook-pro-9.lan
cf27a0e5e839b5159ef0a950c74e6976e1bada74
c3d6476e0e8e44a2e4a196f975457e8ef8327c39
/Circular Linked List/Node.h
201660e87190745314ea39814a7c96b921f2212b
[]
no_license
mukulsaluja18/Linked-List
c8aacc08d39229298e28276dd26537cc366e9090
bf63b2a1ffd369599cf54d2c07ecc2f191dc54f9
refs/heads/main
2023-06-18T04:17:31.546437
2021-07-12T12:59:36
2021-07-12T12:59:36
385,247,692
0
0
null
null
null
null
UTF-8
C++
false
false
178
h
#include<iostream> using namespace std; class Node{ public: int data; Node* next; Node(int data){ this->data=data; next=NULL; } };
[ "noreply@github.com" ]
mukulsaluja18.noreply@github.com
9e7fd22557f5dc3b3e3d2dfd39481b4fc121be5c
46d7d80c1315a8c3f3f242445559b1b29f7ce782
/Gladiator/main.cpp
2c753923a645cb62297f822b0b7ae1280b663669
[]
no_license
lafferc/Gladiator
eb78943d21350a2fff9b58dea3532c35b004c516
0e5957d8f94ba8a92e87f0b18c88693ae36f8740
refs/heads/master
2022-11-08T09:49:40.246535
2020-06-16T22:52:50
2020-06-16T22:52:50
272,063,353
0
0
null
null
null
null
UTF-8
C++
false
false
2,938
cpp
#include<iostream> #include"gladiator.h" #include<string> #include<ctime> #include<Windows.h> using namespace std; void level1(Gladiator& player); void main() { srand((unsigned)time(0)); string name = ""; Gladiator player; SetConsoleTitle(L"Gladiator v0.0.2"); cout << "What is your name ?..."; cin >> name; cout << "Welcome to Rome " << name << ", you have been condemned to die in the arena\n"; cout << "Here are your stats\n"; player = Gladiator(name, 100, 1, 1, 1, 0, "condemned"); player.print(); cout << "If your health reaches 0 you will die\n starting level 1\n"; system("Pause"); level1(player); system("Pause"); } void battle(Gladiator& player, Unit& oponent) { char command; bool success; oponent.print(); while (player.alive == true && oponent.alive == true) { cout << "use 'a' for normal attack or 's' for strong attack (ignores targets defence rolls). "; cin >> command; if (command == 's') { if ((success = player.strongattack(oponent)) == false) cout << "You cannot perform that attack\n"; } else { if ((success = player.attack(oponent)) == false) cout << "Your attack failed\n"; } if (success == true) { oponent.print(); } if (oponent.alive == true) { if (oponent.attack(player) == true) player.print(); else cout << oponent.name << "'s attack failed\n"; } } if (player.alive == true) { player.print(); } } void level1(Gladiator& player) { Gladiator* boss; cout << "You must defeat the 5 others that have also been condemned\n"; for (int i = 0; i < 5; i++) { Unit* unit; if (player.alive == false) { cout << "You were killed by unit" << i << endl; cout << "You died in the arena\n"; return; } unit = Gladiator::create_condemned("unit" + to_string(i + 1)); battle(player, *unit); delete unit; } player.heal(25); player.s_a_remaining += 2; player.print(); cout << "You are alone in the arena, surrounded by your fallen foe\n"; cout << "You barely have time to catch your breath, when a gate opens and another gladiator enters.\n This is not going to be easy\n"; system("Pause"); boss = Gladiator::factory("gladiator1"); battle(player, *boss); if(boss->alive==false) { cout << "\nGood work you kill the gladiator\n"; cout << "\ngold taken from " << boss->name << ": " << boss->money << endl; player.money += boss->money; player.skill += 2; player.print(); } else if(player.alive==false){ cout<<"You died in the arena\n"; } delete boss; }
[ "lafferc@tcd.ie" ]
lafferc@tcd.ie
1928bc5ac7bac74d0c2e35cfe70584ef08d51768
acd990e4b571c6be0508bc8e5a6b54efaf656bde
/src/caffe/layers/coral_loss_layer.cpp
9116e7daca53467cbeb19498a653c350ef159bca
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
baochens/Caffe-Deep_CORAL
f119c60d71282600c4d4f98641bb906a28dfede4
c0921c1131227a2d1d48adea7c0727a6aae62dfc
refs/heads/master
2021-01-13T07:51:19.778102
2017-06-20T20:33:54
2017-06-20T20:33:54
94,930,877
4
1
null
null
null
null
UTF-8
C++
false
false
5,611
cpp
#include <vector> #include "caffe/layers/coral_loss_layer.hpp" #include "caffe/util/math_functions.hpp" #include <algorithm> namespace caffe { template <typename Dtype> void CORALLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); // CHECK_EQ might not be necessary as the size of the covariance matrices of //source and target are always the same even if the batch size is different. CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1)) << "Inputs must have the same dimension."; const int count = bottom[0]->count(); const int num = bottom[0]->num(); const int dim = count / num; diff_.Reshape(dim, dim, 1, 1); cov_s.Reshape(dim, dim, 1, 1); cov_t.Reshape(dim, dim, 1, 1); mean_s.Reshape(dim, 1, 1, 1); mean_t.Reshape(dim, 1, 1, 1); square_mean_s.Reshape(dim, dim, 1, 1); square_mean_t.Reshape(dim, dim, 1, 1); diff_data_s.Reshape(num, dim, 1, 1); diff_data_t.Reshape(num, dim, 1, 1); identity.Reshape(num, 1, 1, 1); bp_mean_s.Reshape(dim, num, 1, 1); bp_mean_t.Reshape(dim, num, 1, 1); bp_der_s.Reshape(dim, num, 1, 1); bp_der_t.Reshape(dim, num, 1, 1); } template <typename Dtype> void CORALLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const int count = bottom[0]->count(); const int num = bottom[0]->num(); const int dim = count / num; const int size_cov = dim * dim; // calculating D'D for source and target caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, dim, dim, num, 1., bottom[0]->cpu_data(), bottom[0]->cpu_data(), 0., cov_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans, dim, dim, num, 1., bottom[1]->cpu_data(), bottom[1]->cpu_data(), 0., cov_t.mutable_cpu_data()); // divide D'D by (num-1) caffe_scal<Dtype>(size_cov, Dtype(1./(num-1)), cov_s.mutable_cpu_data()); caffe_scal<Dtype>(size_cov, Dtype(1./(num-1)), cov_t.mutable_cpu_data()); // identity is a row vector of 1s caffe_set(num, Dtype(1.), identity.mutable_cpu_data()); // calculate the mean of D per column caffe_cpu_gemv<Dtype>(CblasTrans, dim, 1, 1., bottom[0]->cpu_data(), identity.cpu_data(), 0., mean_s.mutable_cpu_data()); caffe_cpu_gemv<Dtype>(CblasTrans, dim, 1, 1., bottom[1]->cpu_data(), identity.cpu_data(), 0., mean_t.mutable_cpu_data()); // calculate the squared mean caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, dim, dim, 1, 1., mean_s.cpu_data(), mean_s.cpu_data() , 0., square_mean_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, dim, dim, 1, 1., mean_t.cpu_data(), mean_t.cpu_data() , 0., square_mean_t.mutable_cpu_data()); // divide squared mean by (num*(num-1)) caffe_scal(size_cov, Dtype(1./(num*(num-1))), square_mean_s.mutable_cpu_data()); caffe_scal(size_cov, Dtype(1./(num*(num-1))), square_mean_t.mutable_cpu_data()); //cov is (1/(num-1))*(D'*D) - (1/(num*(num-1)))*(mean)^T*(mean) caffe_sub(size_cov, cov_s.cpu_data(), square_mean_s.cpu_data(), cov_s.mutable_cpu_data()); caffe_sub(size_cov, cov_t.cpu_data(), square_mean_t.cpu_data(), cov_t.mutable_cpu_data()); //cov_s - cov_t caffe_sub(size_cov, cov_s.cpu_data(), cov_t.cpu_data(), diff_.mutable_cpu_data()); Dtype dot = caffe_cpu_dot(size_cov, diff_.cpu_data(), diff_.cpu_data()); //loss = (1/4)*(1/(dim*dim))*dot Dtype loss = dot / Dtype(4. * dim * dim); top[0]->mutable_cpu_data()[0] = loss; } template <typename Dtype> void CORALLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { int count = bottom[0]->count(); int num = bottom[0]->num(); int dim = count / num; // using chain rule to calculate gradients caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, num, dim, 1, (1./num), identity.cpu_data(), mean_s.cpu_data(), 0., bp_mean_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, num, dim, 1, (1./num), identity.cpu_data(), mean_t.cpu_data(), 0., bp_mean_t.mutable_cpu_data()); // calculate bp_der_s and bp_der_t caffe_sub(count, bottom[0]->cpu_data(), bp_mean_s.cpu_data(), bp_der_s.mutable_cpu_data()); caffe_sub(count, bottom[1]->cpu_data(), bp_mean_t.cpu_data(), bp_der_t.mutable_cpu_data()); //Calculate diff_data caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num, dim, dim, (1./(dim*dim*(num-1))), bp_der_s.cpu_data(), diff_.cpu_data(), 0., diff_data_s.mutable_cpu_data()); caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, num, dim, dim, (1./(dim*dim*(num-1))), bp_der_t.cpu_data(), diff_.cpu_data(), 0., diff_data_t.mutable_cpu_data()); for (int i = 0; i < 2; ++i) { if (propagate_down[i]) { const Dtype sign = (i == 0) ? 1 : -1; const Dtype alpha = sign * top[0]->cpu_diff()[0]; if(i==0){ caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_data_s.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } else{ caffe_cpu_axpby( bottom[i]->count(), // count alpha, // alpha diff_data_t.cpu_data(), // a Dtype(0), // beta bottom[i]->mutable_cpu_diff()); // b } } } } #ifdef CPU_ONLY STUB_GPU(CORALLossLayer); #endif INSTANTIATE_CLASS(CORALLossLayer); REGISTER_LAYER_CLASS(CORALLoss); } // namespace caffe
[ "baochens@gmail.com" ]
baochens@gmail.com
997bc4d8d54f9ca989d05152c46cd3782acf4ba9
fb6b896efa29883cd25cfb449c906f430c45d6f2
/MemoryDispatcher.cpp
13770d64692bbee7d50784399ea202d17c21cf70
[]
no_license
Savvato/MemoryDispatcher
575d049c5e69985128599fb829b26e13c1c812ec
011118a76add31f18790c9024b6881cf740f75f5
refs/heads/master
2021-04-27T00:49:45.580499
2018-02-23T19:15:27
2018-02-23T19:15:27
122,661,559
0
0
null
null
null
null
UTF-8
C++
false
false
5,699
cpp
#pragma once #include "stdafx.h" namespace MemoryDispatcher { const string INPUT_TEXT_FILE_NAME = "Karamzin_page.txt"; const string INPUT_DATA_FILE_NAME = "page1.dat"; const string OUTPUT_TEXT_FILE_NAME = "result.txt."; const int PAGE_SIZE = 256; const int VIRTUAL_PAGES_COUNT = 256; const int PHYSICAL_PAGES_COUNT = 128; class Frame { public: int index; string content; Frame(){} Frame(int frameIndex, string frameContent) { this->index = frameIndex; this->content = frameContent; }; char getSymbol(int offset) { try { return this->content[offset]; } catch (...) { printf("ERROR ON REFERENSING TO PAGE\n"); return ' '; } }; }; class InputFileReader { public: InputFileReader() { this->readFile(); this->createFrames(); } Frame getFrame(int frameNumber) { return this->frames[frameNumber]; } private: void readFile() { ifstream file(INPUT_TEXT_FILE_NAME); string currentString; while (getline(file, currentString)) { fileContent += currentString; } file.close(); } void createFrames() { for (int index = 0; index < VIRTUAL_PAGES_COUNT; index++) { int startSymbolNumber = PAGE_SIZE * index; int endSymbolNumber = startSymbolNumber + PAGE_SIZE-1; string frameContent = fileContent.substr(startSymbolNumber, endSymbolNumber); Frame frame = *(new Frame(index, frameContent)); this->frames[index] = frame; } } Frame frames[VIRTUAL_PAGES_COUNT]; string fileContent; }; struct TLB_Frame { int frameIndex; int physicalFrameIndex; bool isLoaded; }; class TLB { public: array<TLB_Frame, VIRTUAL_PAGES_COUNT> frames; TLB() { for (int index = 0; index < VIRTUAL_PAGES_COUNT; index++) { TLB_Frame frame = *(new TLB_Frame()); frame.frameIndex = index; frame.isLoaded = false; frame.physicalFrameIndex = -1; this->frames[index] = frame; } } TLB_Frame getVirtualFrame(int filePageNumber) { return frames.at(filePageNumber); }; void setPhysicalFrameStatus(int physicalFrameIndex, bool status) { for (int index = 0; index < VIRTUAL_PAGES_COUNT; index++) { TLB_Frame frame = frames[index]; if (frame.physicalFrameIndex == physicalFrameIndex) { frame.isLoaded = status; if (status == false) { frame.physicalFrameIndex = -1; } break; } } } }; class PhysicalMemory { public: deque<Frame> frames; Frame getFrame(int frameNumber) { for (Frame page : this->frames) { if (page.index = frameNumber) { return page; } } } }; class MemoryDispatcher { public: MemoryDispatcher() { this->fileReader = *(new InputFileReader()); this->tlb = *(new TLB()); this->physicalMemory = *(new PhysicalMemory()); }; void run() { ifstream file(INPUT_DATA_FILE_NAME, ios::binary); ofstream out(OUTPUT_TEXT_FILE_NAME); int data = 0; while (!file.eof()) { file.read((char*)&data, sizeof(data)); int offset = data & 255; int pageNumber = (data >> 8) & 255; TLB_Frame tlbFrame = this->tlb.getVirtualFrame(pageNumber); if (!tlbFrame.isLoaded) { this->loadPage(pageNumber); } tlbFrame = this->tlb.getVirtualFrame(pageNumber); Frame frame = this->physicalMemory.frames.at(tlbFrame.physicalFrameIndex); char symbol = frame.getSymbol(offset); out << symbol; cout << pageNumber << " " << offset << " " << symbol << endl; } out.close(); file.close(); } private: InputFileReader fileReader; TLB tlb; PhysicalMemory physicalMemory; void loadPage(int pageNumber) { this->physicalMemory.frames.push_front(this->fileReader.getFrame(pageNumber)); this->tlb.setPhysicalFrameStatus(pageNumber, true); this->tlb.frames.at(pageNumber).frameIndex = this->physicalMemory.frames.size() - 1; if (this->physicalMemory.frames.size() > PHYSICAL_PAGES_COUNT) { Frame deletedPage = this->physicalMemory.frames.back(); this->tlb.setPhysicalFrameStatus(deletedPage.index, false); this->physicalMemory.frames.pop_back(); } this->sync(); } void sync() { for (int index = 0; index < this->physicalMemory.frames.size(); index++) { Frame page = this->physicalMemory.frames.at(index); this->tlb.frames.at(page.index).physicalFrameIndex = index; } } }; }
[ "noreply@github.com" ]
Savvato.noreply@github.com
f19e70a28eee10a62a132dae4d7de068280db398
2dd0661678a9f63948b7134934036de614c8e338
/c++ code/factorial of any number.cpp
950ce703723376eb3689ff4d62844f54bc300709
[]
no_license
hariharan-devarakonda/PGJQP_hariharan
5c8c46670c9b8ae05e4f30c389760c59da7e7b90
a87417d0b7103444276639abbe8e62cbb4436506
refs/heads/main
2023-02-03T09:20:05.959015
2020-12-22T17:27:35
2020-12-22T17:27:35
311,329,834
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include<iostream> using namespace std; class factorial { int i,fact=1,num; public :void display() { cout<<"Enter any number:"<<endl; cin>>num; for(i=1;i<=num;i++) { fact=fact*i; } cout<<"Factorial of number is:"<<fact<<endl; } }; int main() { factorial f1; f1.display(); }
[ "noreply@github.com" ]
hariharan-devarakonda.noreply@github.com
a4b38bbb324c72b52723a2918eaf2480ef910dec
bb287b07de411c95595ec364bebbaf44eaca4fc6
/src/work/test/WorkTests.cpp
a38e36e432512d0cc61f9a505ee1050656e2e9c6
[ "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT", "BSD-2-Clause" ]
permissive
viichain/vii-core
09eb613344630bc80fee60aeac434bfb62eab46e
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
refs/heads/master
2020-06-28T06:33:58.908981
2019-08-14T02:02:13
2019-08-14T02:02:13
200,164,931
0
0
null
null
null
null
UTF-8
C++
false
false
22,806
cpp
#include "lib/catch.hpp" #include "lib/util/format.h" #include "main/Application.h" #include "main/Config.h" #include "process/ProcessManager.h" #include "test/TestUtils.h" #include "test/test.h" #include "work/WorkScheduler.h" #include "historywork/RunCommandWork.h" #include "work/BatchWork.h" #include <cstdio> #include <fstream> #include <random> #include <xdrpp/autocheck.h> using namespace viichain; class TestBasicWork : public BasicWork { bool mShouldFail; public: int const mNumSteps; int mCount; int mRunningCount{0}; int mSuccessCount{0}; int mFailureCount{0}; int mRetryCount{0}; int mAbortCount{0}; TestBasicWork(Application& app, std::string name, bool fail = false, int steps = 3, size_t retries = RETRY_ONCE) : BasicWork(app, std::move(name), retries) , mShouldFail(fail) , mNumSteps(steps) , mCount(steps) { } void forceWakeUp() { wakeUp(); } protected: BasicWork::State onRun() override { CLOG(DEBUG, "Work") << "Running " << getName(); mRunningCount++; if (--mCount > 0) { return State::WORK_RUNNING; } return mShouldFail ? State::WORK_FAILURE : State::WORK_SUCCESS; } bool onAbort() override { CLOG(DEBUG, "Work") << "Aborting " << getName(); ++mAbortCount; return true; } void onSuccess() override { ++mSuccessCount; } void onFailureRaise() override { ++mFailureCount; } void onFailureRetry() override { ++mRetryCount; } void onReset() override { mCount = mNumSteps; } }; class TestWaitingWork : public TestBasicWork { VirtualTimer mTimer; public: int mWaitingCount{0}; int mWakeUpCount{0}; TestWaitingWork(Application& app, std::string name) : TestBasicWork(app, name), mTimer(app.getClock()) { } protected: BasicWork::State onRun() override { ++mRunningCount; if (--mCount > 0) { std::weak_ptr<TestWaitingWork> weak( std::static_pointer_cast<TestWaitingWork>(shared_from_this())); auto handler = [weak](asio::error_code const& ec) { auto self = weak.lock(); if (self) { ++(self->mWakeUpCount); self->wakeUp(); } }; mTimer.expires_from_now(std::chrono::milliseconds(1)); mTimer.async_wait(handler); ++mWaitingCount; return BasicWork::State::WORK_WAITING; } return BasicWork::State::WORK_SUCCESS; } }; TEST_CASE("BasicWork test", "[work][basicwork]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto checkSuccess = [](TestBasicWork const& w) { REQUIRE(w.getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w.mRunningCount == w.mNumSteps); REQUIRE(w.mSuccessCount == 1); REQUIRE(w.mFailureCount == 0); REQUIRE(w.mRetryCount == 0); }; SECTION("one work") { auto w = wm.scheduleWork<TestBasicWork>("test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); } SECTION("2 works round robin") { auto w1 = wm.scheduleWork<TestBasicWork>("test-work1"); auto w2 = wm.scheduleWork<TestBasicWork>("test-work2"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w1); checkSuccess(*w2); } SECTION("work waiting") { auto w = wm.scheduleWork<TestWaitingWork>("waiting-test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); REQUIRE(w->mWaitingCount == w->mWakeUpCount); REQUIRE(w->mWaitingCount == w->mNumSteps - 1); } SECTION("new work added midway") { auto w1 = wm.scheduleWork<TestBasicWork>("test-work1"); auto w2 = wm.scheduleWork<TestBasicWork>("test-work2"); std::shared_ptr<TestBasicWork> w3; while (!wm.allChildrenSuccessful()) { clock.crank(); if (!w3) { w3 = wm.scheduleWork<TestBasicWork>("test-work3"); }; } checkSuccess(*w1); checkSuccess(*w2); checkSuccess(*w3); } SECTION("new work wakes up scheduler") { while (wm.getState() != TestBasicWork::State::WORK_WAITING) { clock.crank(); } auto w = wm.scheduleWork<TestBasicWork>("test-work"); REQUIRE(wm.getState() == TestBasicWork::State::WORK_RUNNING); while (!wm.allChildrenSuccessful()) { clock.crank(); } checkSuccess(*w); } SECTION("work retries and fails") { auto w = wm.scheduleWork<TestBasicWork>("test-work", true); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(w->mRunningCount == w->mNumSteps * (BasicWork::RETRY_ONCE + 1)); REQUIRE(w->mSuccessCount == 0); REQUIRE(w->mFailureCount == 1); REQUIRE(w->mRetryCount == BasicWork::RETRY_ONCE); } SECTION("work shutdown") { auto w = wm.scheduleWork<TestBasicWork>("test-work", false, 100); while (!wm.allChildrenDone()) { clock.crank(); w->shutdown(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w->mAbortCount == 1); REQUIRE(w->mCount == w->mNumSteps); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } } class TestWork : public Work { public: int mRunningCount{0}; int mSuccessCount{0}; int mFailureCount{0}; int mRetryCount{0}; TestWork(Application& app, std::string name) : Work(app, std::move(name), RETRY_NEVER) { } BasicWork::State doWork() override { ++mRunningCount; return WorkUtils::checkChildrenStatus(*this); } template <typename T, typename... Args> std::shared_ptr<T> addTestWork(Args&&... args) { return addWork<T>(std::forward<Args>(args)...); } void onSuccess() override { mSuccessCount++; } void onFailureRaise() override { mFailureCount++; } void onFailureRetry() override { mRetryCount++; } }; TEST_CASE("work with children", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto w1 = wm.scheduleWork<TestWork>("test-work1"); auto w2 = wm.scheduleWork<TestWork>("test-work2"); auto l1 = w1->addTestWork<TestBasicWork>("leaf-work"); auto l2 = w1->addTestWork<TestBasicWork>("leaf-work-2"); SECTION("success") { while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("child failed") { auto l3 = w2->addTestWork<TestBasicWork>("leaf-work3", true); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l3->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("child failed so parent aborts other child") { auto l3 = w2->addTestWork<TestBasicWork>("leaf-work3", true, 3, TestBasicWork::RETRY_NEVER); auto l4 = w2->addTestWork<TestBasicWork>("leaf-work4", false, 100); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(l1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(l2->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w2->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l3->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE(l4->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(wm.getState() == TestBasicWork::State::WORK_WAITING); } SECTION("work scheduler shutdown") { wm.shutdown(); REQUIRE(wm.isAborting()); REQUIRE(w1->isAborting()); REQUIRE(w2->isAborting()); REQUIRE(l1->isAborting()); REQUIRE(l2->isAborting()); REQUIRE_NOTHROW(l1->forceWakeUp()); REQUIRE_NOTHROW(l2->forceWakeUp()); REQUIRE(l1->isAborting()); REQUIRE(l2->isAborting()); REQUIRE_THROWS_AS(w1->addTestWork<TestBasicWork>("leaf-work-3"), std::runtime_error); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(wm.getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w1->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(w2->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(l1->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(l2->getState() == TestBasicWork::State::WORK_ABORTED); } } TEST_CASE("work scheduling and run count", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); auto mainWork = wm.scheduleWork<TestWork>("main-work"); SECTION("multi-level tree") { auto w1 = mainWork->addTestWork<TestBasicWork>("3-step-work"); auto w2 = mainWork->addTestWork<TestWork>("wait-for-children-work"); auto c1 = w2->addTestWork<TestBasicWork>("child-3-step-work"); auto c2 = w2->addTestWork<TestBasicWork>("other-child-3-step-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w1->mRunningCount == w1->mNumSteps); REQUIRE(w2->mRunningCount == c1->mNumSteps); REQUIRE(c1->mRunningCount == c1->mNumSteps); REQUIRE(c2->mRunningCount == c2->mNumSteps); REQUIRE(mainWork->mRunningCount == (c1->mRunningCount * 2 + w2->mRunningCount)); } SECTION("multi-level tree more leaves do not affect scheduling") { auto w1 = mainWork->addTestWork<TestWork>("test-work-1"); auto w2 = mainWork->addTestWork<TestWork>("test-work-2"); auto c1 = w1->addTestWork<TestBasicWork>("child-3-step-work"); auto c2 = w1->addTestWork<TestBasicWork>("other-child-3-step-work"); auto c3 = w2->addTestWork<TestBasicWork>("2-child-3-step-work"); auto c4 = w2->addTestWork<TestBasicWork>("2-other-child-3-step-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w2->mRunningCount == c1->mNumSteps); REQUIRE(c1->mRunningCount == c1->mNumSteps); REQUIRE(c2->mRunningCount == c2->mNumSteps); REQUIRE(mainWork->mRunningCount == (c2->mRunningCount * 2 + w2->mRunningCount)); } } TEST_CASE("work scheduling compare trees", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("linked list structure") { auto w1 = wm.scheduleWork<TestWork>("work-1"); auto w2 = w1->addTestWork<TestWork>("work-2"); auto w3 = w2->addTestWork<TestBasicWork>("work-3"); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w3->mRunningCount == w3->mNumSteps); REQUIRE(w2->mRunningCount == w3->mRunningCount); REQUIRE(w1->mRunningCount == w2->mRunningCount + w3->mRunningCount); } SECTION("flat work sequence") { auto w1 = std::make_shared<TestWork>(*appPtr, "work-1"); auto w2 = std::make_shared<TestWork>(*appPtr, "work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w3, w2, w1}; auto sw = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(w3->mRunningCount == w3->mNumSteps); REQUIRE(w2->mRunningCount == 1); REQUIRE(w1->mRunningCount == 1); } } class TestRunCommandWork : public RunCommandWork { std::string mCommand; public: TestRunCommandWork(Application& app, std::string name, std::string command) : RunCommandWork(app, std::move(name)), mCommand(std::move(command)) { } ~TestRunCommandWork() override = default; CommandInfo getCommand() override { return CommandInfo{mCommand, std::string()}; } BasicWork::State onRun() override { return RunCommandWork::onRun(); } }; TEST_CASE("RunCommandWork test", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("one run command work") { wm.scheduleWork<TestRunCommandWork>("test-run-command", "date"); while (!wm.allChildrenSuccessful()) { clock.crank(); } } SECTION("round robin with other work") { wm.scheduleWork<TestRunCommandWork>("test-run-command", "date"); wm.scheduleWork<TestBasicWork>("test-work"); while (!wm.allChildrenSuccessful()) { clock.crank(); } } SECTION("invalid run command") { auto w = wm.scheduleWork<TestRunCommandWork>("test-run-command", "_invalid_"); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("run command aborted") { #ifdef _WIN32 std::string command = "waitfor /T 10 pause"; #else std::string command = "sleep 10"; #endif auto w = wm.scheduleWork<TestRunCommandWork>("test-run-command", command); while (w->getState() != TestBasicWork::State::WORK_WAITING) { clock.crank(); } REQUIRE(appPtr->getProcessManager().getNumRunningProcesses()); wm.shutdown(); while (wm.getState() != TestBasicWork::State::WORK_ABORTED) { clock.crank(); } REQUIRE(w->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(appPtr->getProcessManager().getNumRunningProcesses() == 0); } } TEST_CASE("WorkSequence test", "[work]") { VirtualClock clock; Config const& cfg = getTestConfig(); Application::pointer appPtr = createTestApplication(clock, cfg); auto& wm = appPtr->getWorkScheduler(); SECTION("basic") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1"); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); while (!wm.allChildrenSuccessful()) { if (!w1->mSuccessCount) { REQUIRE(!w2->mRunningCount); REQUIRE(!w3->mRunningCount); } else if (!w2->mSuccessCount) { REQUIRE(w1->mSuccessCount); REQUIRE(!w3->mRunningCount); } else { REQUIRE(w1->mSuccessCount); REQUIRE(w2->mSuccessCount); } clock.crank(); } } SECTION("WorkSequence is empty") { std::vector<std::shared_ptr<BasicWork>> seq{}; auto work2 = wm.scheduleWork<WorkSequence>("test-work-sequence-2", seq); while (!wm.allChildrenSuccessful()) { clock.crank(); } REQUIRE(work2->getState() == TestBasicWork::State::WORK_SUCCESS); } SECTION("first work fails") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1", true); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2"); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.executeWork<WorkSequence>("test-work-sequence", seq); auto w1RunCount = w1->mNumSteps * (BasicWork::RETRY_ONCE + 1); REQUIRE(w1->mRunningCount == w1RunCount * (BasicWork::RETRY_A_FEW + 1)); REQUIRE(w1->getState() == TestBasicWork::State::WORK_FAILURE); REQUIRE_FALSE(w2->mRunningCount); REQUIRE_FALSE(w2->mSuccessCount); REQUIRE_FALSE(w2->mFailureCount); REQUIRE_FALSE(w2->mRetryCount); REQUIRE_FALSE(w3->mRunningCount); REQUIRE_FALSE(w3->mSuccessCount); REQUIRE_FALSE(w3->mFailureCount); REQUIRE_FALSE(w3->mRetryCount); REQUIRE(work->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("fails midway") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1"); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2", true); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3"); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.executeWork<WorkSequence>("test-work-sequence", seq); auto w2RunCount = w2->mNumSteps * (BasicWork::RETRY_ONCE + 1); REQUIRE(w2->mRunningCount == w2RunCount * (BasicWork::RETRY_A_FEW + 1)); REQUIRE(w2->getState() == BasicWork::State::WORK_FAILURE); REQUIRE(w1->getState() == TestBasicWork::State::WORK_SUCCESS); REQUIRE(w1->mRunningCount); REQUIRE(w1->mSuccessCount); REQUIRE_FALSE(w1->mFailureCount); REQUIRE_FALSE(w1->mRetryCount); REQUIRE_FALSE(w3->mRunningCount); REQUIRE_FALSE(w3->mSuccessCount); REQUIRE_FALSE(w3->mFailureCount); REQUIRE_FALSE(w3->mRetryCount); REQUIRE(work->getState() == TestBasicWork::State::WORK_FAILURE); } SECTION("work scheduler shutdown") { auto w1 = std::make_shared<TestBasicWork>(*appPtr, "test-work-1", false, 100); auto w2 = std::make_shared<TestBasicWork>(*appPtr, "test-work-2", false, 100); auto w3 = std::make_shared<TestBasicWork>(*appPtr, "test-work-3", false, 100); std::vector<std::shared_ptr<BasicWork>> seq{w1, w2, w3}; auto work = wm.scheduleWork<WorkSequence>("test-work-sequence", seq); clock.crank(); CHECK(!wm.allChildrenDone()); wm.shutdown(); while (!wm.allChildrenDone()) { clock.crank(); } REQUIRE(work->getState() == TestBasicWork::State::WORK_ABORTED); REQUIRE(wm.getState() == TestBasicWork::State::WORK_ABORTED); } } class TestBatchWork : public BatchWork { bool mShouldFail; int mTotalWorks; public: int mCount{0}; std::vector<std::shared_ptr<TestBasicWork>> mBatchedWorks; TestBatchWork(Application& app, std::string const& name, bool fail = false) : BatchWork(app, name) , mShouldFail(fail) , mTotalWorks(app.getConfig().MAX_CONCURRENT_SUBPROCESSES * 2) { } protected: bool hasNext() const override { return mCount < mTotalWorks; } void resetIter() override { mCount = 0; } std::shared_ptr<BasicWork> yieldMoreWork() override { bool fail = mCount == mTotalWorks - 1 && mShouldFail; auto w = std::make_shared<TestBasicWork>( mApp, fmt::format("child-{:d}", mCount++), fail); if (!fail) { mBatchedWorks.push_back(w); } return w; } }; TEST_CASE("Work batching", "[batching][work]") { VirtualClock clock; Application::pointer app = createTestApplication(clock, getTestConfig()); auto& wm = app->getWorkScheduler(); SECTION("success") { auto testBatch = wm.scheduleWork<TestBatchWork>("test-batch"); while (!clock.getIOContext().stopped() && !wm.allChildrenDone()) { clock.crank(true); REQUIRE(testBatch->getNumWorksInBatch() <= app->getConfig().MAX_CONCURRENT_SUBPROCESSES); } REQUIRE(testBatch->getState() == TestBasicWork::State::WORK_SUCCESS); } SECTION("shutdown") { auto testBatch = wm.scheduleWork<TestBatchWork>("test-batch", true); while (!clock.getIOContext().stopped() && !wm.allChildrenDone()) { clock.crank(true); wm.shutdown(); } REQUIRE(testBatch->getState() == TestBasicWork::State::WORK_ABORTED); for (auto const& w : testBatch->mBatchedWorks) { auto validState = w->getState() == TestBasicWork::State::WORK_SUCCESS || w->getState() == TestBasicWork::State::WORK_ABORTED; REQUIRE(validState); } } }
[ "viichain" ]
viichain
2d06c97be4ea22ef6e1f3c2f05d373378ab637d8
e5aa28feb4461043db39238a717436476f34ed72
/src/qtimespan.cpp
09c84a543bf721cd4e9e81fd221fe813d5dec0f5
[]
no_license
siquel/SotkuMuija-sailfish
45fe1b34b8759695f4b38608db6f60f3ab5afc0e
74dade95f8679049e6eab31f5f629e1ad3f8ff5a
refs/heads/master
2021-01-10T19:51:54.509534
2014-02-22T21:21:47
2014-02-22T21:21:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
76,295
cpp
/**************************************************************************** ** ** Copyright (C) 2011 Andre Somers, Sean Harmer. ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qplatformdefs.h" #include "qregexp.h" #include "qdatastream.h" #include "qlocale.h" #include "qtimespan.h" #include "qdebug.h" #include "qcoreapplication.h" #include "QtGlobal" #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE) #include <qt_windows.h> #endif #ifndef Q_WS_WIN #include <locale.h> #endif #include <time.h> #if defined(Q_OS_WINCE) #include "qfunctions_wince.h" #endif #if defined(Q_WS_MAC) #include <private/qcore_mac_p.h> #endif #if defined(Q_OS_SYMBIAN) #include <e32std.h> #endif #if defined(Q_WS_WIN) #undef max #endif #include <limits> #include <math.h> /*! \class QTimeSpan \brief The QTimeSpan represents a span of time \since 4.8 QTimeSpan represents a span of time, which is optionally in reference to a specific point in time. A QTimeSpan behaves slightly different if it has a reference date or time or not. \section1 Constructing a QTimeSpan A QTimeSpan can be created by initializing it directly with a length and optionally with a reference (start) date, or by substracting two \l QDate or \l QDateTime values. By substracting \l QDate or \l QDateTime values, you create a QTimeSpan with the \l QDate or \l QDateTime on the right hand side of the - operator as the reference date. \code //Creates a QTimeSpan representing the time from October 10, 1975 to now QDate birthDay(1975, 10, 10); QTimeSpan age = QDate::currentDate() - birthDay; \endcode QTimeSpan defines a series of static methods that can be used for initializing a QTimeSpan. \c second(), \c minute(), \c hour(), \c day() and \c week() all return QTimeSpan instances with the corresponding length and no reference date. You can use those to create new instances. See the section on \l {Date arithmetic} below. \code //Creates a QTimeSpan representing 2 days, 4 hours and 31 minutes. QTimeSpan span(2 * QTimeSpan::day() + 4 * QTimeSpan::hour() + 31 * QTimeSpan::minute()); \endcode Finally, a QTimeSpan can be constructed by using one of the static constructors \l fromString() or \l fromTimeUnit(). \section1 Date arithmetic A negative QTimeSpan means that the reference date lies before the referenced date. Call \l normalize() to ensure that the reference date is smaller or equal than the referenced date. Basic arithmetic can be done with QTimeSpan. QTimeSpans can be added up or substracted, or be multiplied by a scalar factor. For this, the usual operators are implemented. The union of QTimeSpans will yield the minimal QTimeSpan that covers both the original QTimeSpans, while the intersection will yield the overlap between them (or an empty one if there is no overlap). Please refer to the method documentation for details on what happens to a reference date when using these methods. QTimeSpans can also be added to or substracted from a \l QDate, \l QTime or \l QDateTime. This will yield a new \l QDate, \l QTime or \l QDateTime moved by the interval described by the QTimeSpan. Note that the QTimeSpan must be the right-hand argument of the operator. You can not add a \l QDate to a QTimeSpan, but you can do the reverse. \code QTimeSpan span(QTimeSpan::hour() * 5 + 45 * QTimeSpan::hinute()); QDateTime t1 = QDateTime::currentDateTime(); QDateTime t2 = t1 + span; // t2 is now the date time 5 hours and 45 minutes in the future. \endcode \section1 Accessing the length of a QTimeSpan There are two sets of methods that return the length of a QTimeSpan. The to* methods such as \l toSeconds() and \l toMinutes() return the total time in the requested unit. That may be a fractional number. \code QTimeSpan span = QTimeSpan::hour() * 6; qreal days = span.toDays(); //yields 0.25 \endcode On the other hand, you may be interested in a number of units at the same time. If you want to know the number of days, hours and minutes in a QTimeSpan, you can use the to*Part methods such as \l toDayPart() and \l toHourPart(). These functions take a \c QTimeSpan::TimeSpanFormat argument to indicate the units you want to use for the presentation of the QTimeSpan. This is used to calculate the number of the requested time units. You can also use the parts method directly, passing pointers to ints for the units you are interested in and 0 for the other units. \section1 Using months and years It is natural to use units like months and years when dealing with longer time periods, such as the age of people. The problem with these units is that unlike the time units for a week or shorter, the length of a month or a year is not fixed. It it dependent on the reference date. The time period '1 month' has a different meaning when we are speaking of Februari or Januari. Qt does not take leap seconds into account. QTimeSpan can only use the month and year time units if a valid reference date has been set. Without a valid reference date, month and year as time units are meaningless and their use will result in an assert. The largest unit of time that can be expressed without a reference date is a week. The time period of one month is understood to mean the period from a day and time one month to the same date and time in the next. If the next month does not have that date and time, one month will be taken to mean the period to the end of that month. \b Examples: \list \o The time from Januari 2, 12 PM to Februari 2, 12 PM will be understood as exactly one month. \o The time from Januari 30, 2 PM to March 1, 00:00:00.000 will also be one month, because Februari does not have 30 days but 28 or 29 depending on the year. \o The time from Januari 30, 2 PM to March 30, 2 PM will be 2 months. \endlist The same goes for years. \section1 Limitations and counterintuitive behaviour QTimeSpan can be used to describe almost any length of time, ranging from milliseconds to decades and beyond. QTimeSpan internally uses a 64 bit integer value to represent the interval; enough for any application not dealing with geological or astronomical time scales. The use of a single interval value also means that arithmetic with time periods set as months or years may not always yield what you might expect. A time period set as the year describing the whole of 2007 that you multiply by two, will not end up having a length of two years, but of 1 year, 11 months and 30 days, as 2008 is one day longer than 2007. When months and years are used, they are converted to the exact time span they describe relative to the reference date set for the QTimeSpan. With another reference date, or when negated, that time span may or may not describe the same number of years and months. */ QT_BEGIN_NAMESPACE QTimeSpan QTimeSpan::second() {return QTimeSpan( Q_INT64_C(1000) );} QTimeSpan QTimeSpan::minute() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) );} QTimeSpan QTimeSpan::hour() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) );} QTimeSpan QTimeSpan::day() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) );} QTimeSpan QTimeSpan::week() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) * Q_INT64_C(7) );} class QTimeSpanPrivate : public QSharedData { public: qint64 interval; QDateTime reference; void addUnit(QTimeSpan* self, Qt::TimeSpanUnit unit, qreal value) { if (unit >= Qt::Months) { QTimeSpan tempSpan(self->referencedDate()); tempSpan.setFromTimeUnit(unit, value); interval += tempSpan.toMSecs(); } else { switch (unit) { case Qt::Weeks: interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) * Q_INT64_C(7); break; case Qt::Days: interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24); break; case Qt::Hours: interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60); break; case Qt::Minutes: interval += value * Q_INT64_C(1000) * Q_INT64_C(60); break; case Qt::Seconds: interval += value * Q_INT64_C(1000); break; case Qt::Milliseconds: interval += value; break; default: break; } } } //returns the number of days in the month of the indicated date. If lookback is true, and //the date is exactly on the month boundary, the month before is used. int daysInMonth (const QDateTime& date, bool lookBack = false) const { QDateTime measureDate(date); if (lookBack) measureDate = measureDate.addMSecs(-1); return measureDate.date().daysInMonth(); } class TimePartHash: public QHash<Qt::TimeSpanUnit, int*> { public: TimePartHash(Qt::TimeSpanFormat format) { for (int i(Qt::Milliseconds); i <= Qt::Years; i *= 2) { Qt::TimeSpanUnit u = static_cast<Qt::TimeSpanUnit>(i); if (format.testFlag(u)) { int* newValue = new int; *newValue = 0; insert(u, newValue); //perhaps we can optimize this not to new each int individually? } else { insert(u, 0); } } } ~TimePartHash() { qDeleteAll(*this); } inline bool fill(const QTimeSpan& span) { bool result = span.parts(value(Qt::Milliseconds), value(Qt::Seconds), value(Qt::Minutes), value(Qt::Hours), value(Qt::Days), value(Qt::Weeks), value(Qt::Months), value(Qt::Years)); return result; } inline void addUnit(const Qt::TimeSpanUnit unit) { if (value(unit) != 0) return; int* newValue = new int; *newValue = 0; insert(unit, newValue); } }; //returns a string representation of time in a single time unit QString unitString(Qt::TimeSpanUnit unit, int num) const { switch (unit) { case::Qt::Milliseconds: return qApp->translate("QTimeSpanPrivate", "%n millisecond(s)", "", num); case::Qt::Seconds: return qApp->translate("QTimeSpanPrivate", "%n second(s)", "", num); case::Qt::Minutes: return qApp->translate("QTimeSpanPrivate", "%n minute(s)", "", num); case::Qt::Hours: return qApp->translate("QTimeSpanPrivate", "%n hour(s)", "", num); case::Qt::Days: return qApp->translate("QTimeSpanPrivate", "%n day(s)", "", num); case::Qt::Weeks: return qApp->translate("QTimeSpanPrivate", "%n week(s)", "", num); case::Qt::Months: return qApp->translate("QTimeSpanPrivate", "%n month(s)", "", num); case::Qt::Years: return qApp->translate("QTimeSpanPrivate", "%n year(s)", "", num); default: return QString(); } } #ifndef QT_NO_DATESTRING struct TimeFormatToken { Qt::TimeSpanUnit type; //Qt::NoUnit is used for string literal types int length; //number of characters to use QString string; //only used for string literals }; QList<TimeFormatToken> parseFormatString(const QString& formatString, Qt::TimeSpanFormat &format) const { QHash<QChar, Qt::TimeSpanUnit> tokenHash; tokenHash.insert(QChar('y', 0), Qt::Years); tokenHash.insert(QChar('M', 0), Qt::Months); tokenHash.insert(QChar('w', 0), Qt::Weeks); tokenHash.insert(QChar('d', 0), Qt::Days); tokenHash.insert(QChar('h', 0), Qt::Hours); tokenHash.insert(QChar('m', 0), Qt::Minutes); tokenHash.insert(QChar('s', 0), Qt::Seconds); tokenHash.insert(QChar('z', 0), Qt::Milliseconds); QList<TimeFormatToken> tokenList; format = Qt::NoUnit; int pos(0); int length(formatString.length()); bool inLiteral(false); while (pos < length) { const QChar currentChar(formatString[pos]); if (inLiteral) { if (currentChar == QLatin1Char('\'')) { inLiteral = false; //exit literal string mode if ((pos+1)<length) { if (formatString[pos+1] == QLatin1Char('\'')) { ++pos; TimeFormatToken token = tokenList.last(); token.string.append(QChar('\'', 0)); token.length = token.string.length(); tokenList[tokenList.length()-1] = token; inLiteral = true; //we *are* staying in literal string mode } } } else { TimeFormatToken token = tokenList.last(); token.string.append(currentChar); token.length = token.string.length(); tokenList[tokenList.length()-1] = token; } } else { //not in literal string if (currentChar == QLatin1Char('\'')) { inLiteral = true; //enter literal string mode TimeFormatToken token; token.type = Qt::NoUnit; token.length = 0; tokenList << token; } else { if (tokenHash.contains(currentChar)) { Qt::TimeSpanUnit unit = tokenHash.value(currentChar); TimeFormatToken token; token.length = 0; token.type = unit; if ((!tokenList.isEmpty()) && (tokenList.last().type == unit)) token = tokenList.takeLast(); token.length+=1; tokenList.append(token); format |= unit; } else { //ignore character? TimeFormatToken token; token.length = 0; token.type = Qt::NoUnit; if ((!tokenList.isEmpty()) && (tokenList.last().type == Qt::NoUnit)) token = tokenList.takeLast(); token.string.append(currentChar); token.length= token.string.length(); tokenList.append(token); } } } ++pos; } return tokenList; } #endif }; /*! Default constructor Constructs a null QTimeSpan */ QTimeSpan::QTimeSpan() : d(new QTimeSpanPrivate) { d->interval = 0; } /*! Constructor \overload QTimeSpan() Constructs QTimeSpan of size \a msecs milliseconds. The reference date will be invalid. */ QTimeSpan::QTimeSpan(qint64 msecs) : d(new QTimeSpanPrivate) { d->interval = msecs; } /*! Copy Constructor */ QTimeSpan::QTimeSpan(const QTimeSpan& other): d(other.d) { } /*! Constructor \overload QTimeSpan() Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference date and time. */ QTimeSpan::QTimeSpan(const QDateTime &reference, qint64 msecs) : d(new QTimeSpanPrivate) { d->interval = msecs; d->reference = reference; } /*! Constructor \overload QTimeSpan() Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference date. The reference time will be 0:00:00.000 */ QTimeSpan::QTimeSpan(const QDate &reference, quint64 msecs) : d(new QTimeSpanPrivate) { d->interval = msecs; d->reference = QDateTime(reference); } /*! Constructor \overload QTimeSpan() Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference time. The reference date will be today's date. */ QTimeSpan::QTimeSpan(const QTime &reference, quint64 msecs) : d(new QTimeSpanPrivate) { d->interval = msecs; QDateTime todayReference(QDate::currentDate()); todayReference.setTime(reference); d->reference = todayReference; } /*! Constructor \overload QTimeSpan() Constructs a QTimeSpan of the same length as \a other from the given \a reference date time. */ QTimeSpan::QTimeSpan(const QDateTime& reference, const QTimeSpan& other) : d(new QTimeSpanPrivate) { d->reference = reference; d->interval = other.d->interval; } /*! Constructor Constructs a QTimeSpan of the same length as \a other from the given \a reference date. The reference time will be 00:00:00.000 */ QTimeSpan::QTimeSpan(const QDate& reference, const QTimeSpan& other) : d(new QTimeSpanPrivate) { d->reference = QDateTime(reference); d->interval = other.d->interval; } /*! Constructor Constructs a QTimeSpan of the same length as \a other from the given \a reference time. The reference date will be today's date. */ QTimeSpan::QTimeSpan(const QTime& reference, const QTimeSpan& other) : d(new QTimeSpanPrivate) { QDateTime todayReference(QDate::currentDate()); todayReference.setTime(reference); d->reference = todayReference; d->interval = other.d->interval; } /*! Destructor */ QTimeSpan::~QTimeSpan() { } /*! Returns true if the time span is 0; that is, if no time is spanned by this instance. There may or may not be a valid reference date. \sa isNull() hasValidReference() */ bool QTimeSpan::isEmpty() const { return d->interval == 0; } /*! Returns true if the time span is 0; that is, if no time is spanned by this instance and there is no valid reference date. \sa isEmpty() */ bool QTimeSpan::isNull() const { return isEmpty() && (!hasValidReference()); } /*! Assignment operator */ QTimeSpan& QTimeSpan::operator=(const QTimeSpan& other) { if (&other == this) return *this; d = other.d; return *this; } /*! Returns a new QTimeSpan instance initialized to \a interval number of units \a unit. The default reference date is invalid. Note that you can only construct a valid QTimeSpan using the Months or Years time units if you supply a valid \a reference date. \sa setFromTimeUnit() */ QTimeSpan QTimeSpan::fromTimeUnit(Qt::TimeSpanUnit unit, qreal interval, const QDateTime& reference ) { switch (unit){ //note: fall through is intentional! case Qt::Weeks: interval *= 7.0; case Qt::Days: interval *= 24.0; case Qt::Hours: interval *= 60.0; case Qt::Minutes: interval *= 60.0; case Qt::Seconds: interval *= 1000.0; case Qt::Milliseconds: break; default: if (reference.isValid()) { QTimeSpan result(reference); result.setFromTimeUnit(unit, interval); return result; } Q_ASSERT_X(false, "static constructor", "Can not construct QTimeSpan from Month or Year TimeSpanUnit without a valid reference date."); return QTimeSpan(); } return QTimeSpan(reference, qint64(interval)); } /*! Returns the number of the requested units indicated by \a unit when formatted as \a format. \sa parts() */ int QTimeSpan::part(Qt::TimeSpanUnit unit, Qt::TimeSpanFormat format) const { if (!format.testFlag(unit)) return 0; if (!hasValidReference()) { Q_ASSERT_X(!(unit == Qt::Months || unit == Qt::Years), "part", "Can not calculate Month or Year part without a reference date"); if (format.testFlag(Qt::Months) || format.testFlag(Qt::Years)) { qWarning() << "Unsetting Qt::Months and Qt::Years flags from format. Not supported without a reference date"; //should this assert instead? format&= (Qt::AllUnits ^ (Qt::Months | Qt::Years)); } } //build up hash with pointers to ints for the units that are set in format, and 0's for those that are not. QTimeSpanPrivate::TimePartHash partsHash(format); bool result = partsHash.fill(*this); if (!result) { //what to do? Assert perhaps? qWarning() << "Result is invalid!"; return 0; } int val = *(partsHash.value(unit)); return val; } #define CHECK_INT_LIMIT(interval, unitFactor) if (interval >= (qint64(unitFactor) * qint64(std::numeric_limits<int>::max()) ) ) {qWarning() << "out of range" << unitFactor; return false;} /*! Retreives a breakup of the length of the QTimeSpan in different time units. While \l part() allows you to retreive the value of a single unit for a specific representation of time, this method allows you to retreive all these values with a single call. The units that you want to use in the representation of the time span are defined implicitly by the pointers you pass. Passing a valid pointer for a time unit will include that unit in the representation, while passing 0 for that pointer will exclude it. The passed integer pointers will be set to the correct value so that together they represent the whole time span. This function will then return true. If it is impossible to represent the whole time span in the requested units, this function returns false. The \a fractionalSmallestUnit qreal pointer can optionally be passed in to retreive the value for the smallest time unit passed in as a fractional number. For instance, if your time span contains 4 minutes and 30 seconds, but the smallest time unit you pass in an integer pointer for is the minute unit, then the minute integer will be set to 4 and the \a fractionalSmallestUnit will be set to 4.5. A negative QTimeSpan will result in all the parts of the representation to be negative, while a positive QTimeSpan will result in an all positive representation. Note that months and years are only valid as units for time spans that have a valid reference date. Requesting the number of months or years for time spans without a valid reference date will return false. If this function returns false, the value of the passed in pointers is undefined. \sa part() */ bool QTimeSpan::parts(int *msecondsPtr, int *secondsPtr, int *minutesPtr, int *hoursPtr, int *daysPtr, int *weeksPtr, int *monthsPtr, int *yearsPtr, qreal *fractionalSmallestUnit) const { /* \todo We should probably cache the results of this operation. However, that requires keeping a dirty flag in the private data store, or a copy of the reference date, interval and last used parts. Is that worth it? */ // Has the user asked for a fractional component? If yes, find which unit it corresponds to. Qt::TimeSpanUnit smallestUnit = Qt::NoUnit; if (fractionalSmallestUnit) { if (yearsPtr) smallestUnit = Qt::Years; if (monthsPtr) smallestUnit = Qt::Months; if (weeksPtr) smallestUnit = Qt::Weeks; if (daysPtr) smallestUnit = Qt::Days; if (hoursPtr) smallestUnit = Qt::Hours; if (minutesPtr) smallestUnit = Qt::Minutes; if (secondsPtr) smallestUnit = Qt::Seconds; if (msecondsPtr) smallestUnit = Qt::Milliseconds; } QTimeSpan ts(*this); qint64 unitFactor; if (yearsPtr || monthsPtr) { //deal with months and years //we can not deal with months or years if there is no valid reference date if (!hasValidReference()) { qWarning() << "Can not request month or year parts of a QTimeSpan without a valid reference date."; return false; } QDate startDate = ts.startDate().date(); QDate endDate = ts.endDate().date(); //Deal with years int years = endDate.year() - startDate.year(); if (endDate.month() < startDate.month()) { years--; } else if (endDate.month() == startDate.month()) { if (endDate.day() < startDate.day()) years--; } if (yearsPtr) *yearsPtr = years; QDate newStartDate(startDate); unitFactor = Q_INT64_C(365) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000); newStartDate = newStartDate.addYears(years); ts = QDateTime(endDate, ts.endDate().time()) - QDateTime(newStartDate, ts.startDate().time()); if (smallestUnit == Qt::Years) { if (QDate::isLeapYear(newStartDate.year())) unitFactor = Q_INT64_C(366) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000); *fractionalSmallestUnit = static_cast<qreal>(years) + (static_cast<qreal>(ts.toMSecs()) / static_cast<qreal>(unitFactor)); return true; } //Deal with months if (monthsPtr) { int months = endDate.month() - startDate.month(); if (months < 0) months += 12; if (endDate.day() < startDate.day()) months--; newStartDate = newStartDate.addMonths(months); ts = QDateTime(endDate, ts.endDate().time()) - QDateTime(newStartDate, ts.startDate().time()); if (!yearsPtr) months += years * 12; *monthsPtr = months; if (smallestUnit == Qt::Months) { unitFactor = Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000); //one day unitFactor *= d->daysInMonth(QDateTime(newStartDate), isNegative()); *fractionalSmallestUnit = static_cast<qreal>(months) + (static_cast<qreal>(ts.toMSecs()) / static_cast<qreal>(unitFactor)); return true; } } } //from here on, we use ts as the time span! qint64 intervalLeft = ts.toMSecs(); if (weeksPtr) { unitFactor = Q_INT64_C(7) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000); CHECK_INT_LIMIT(intervalLeft, unitFactor) *weeksPtr = intervalLeft / unitFactor; if (smallestUnit == Qt::Weeks) { QTimeSpan leftOverTime(referencedDate(), -intervalLeft); leftOverTime.normalize(); *fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit); return true; } if (*weeksPtr != 0) intervalLeft = intervalLeft % unitFactor; } if (daysPtr) { unitFactor = (Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)); CHECK_INT_LIMIT(intervalLeft, unitFactor) *daysPtr = intervalLeft / unitFactor; if (smallestUnit == Qt::Days) { QTimeSpan leftOverTime(referencedDate(), -intervalLeft); leftOverTime.normalize(); *fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit); return true; } if (*daysPtr != 0 ) intervalLeft = intervalLeft % unitFactor; } if (hoursPtr) { unitFactor = (Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)); CHECK_INT_LIMIT(intervalLeft, unitFactor) *hoursPtr = intervalLeft / unitFactor; if (smallestUnit == Qt::Hours) { QTimeSpan leftOverTime(referencedDate(), -intervalLeft); leftOverTime.normalize(); *fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit); return true; } if (*hoursPtr != 0 ) intervalLeft = intervalLeft % unitFactor; } if (minutesPtr) { unitFactor = (Q_INT64_C(60) * Q_INT64_C(1000)); CHECK_INT_LIMIT(intervalLeft, unitFactor) *minutesPtr = intervalLeft / unitFactor; if (smallestUnit == Qt::Minutes) { QTimeSpan leftOverTime(referencedDate(), -intervalLeft); leftOverTime.normalize(); *fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit); return true; } if (*minutesPtr != 0 ) intervalLeft = intervalLeft % unitFactor; } if (secondsPtr) { unitFactor = (Q_INT64_C(1000)); CHECK_INT_LIMIT(intervalLeft, unitFactor) *secondsPtr = intervalLeft / unitFactor; if (smallestUnit == Qt::Seconds) { QTimeSpan leftOverTime(referencedDate(), -intervalLeft); leftOverTime.normalize(); *fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit); return true; } if (*secondsPtr > 0 ) intervalLeft = intervalLeft % unitFactor; } if (msecondsPtr) { unitFactor = 1; CHECK_INT_LIMIT(intervalLeft, unitFactor) *msecondsPtr = intervalLeft; if (fractionalSmallestUnit) { *fractionalSmallestUnit = qreal(intervalLeft); } } return true; } /*! Sets a part of the time span in the given format. setPart allows you to adapt the current time span interval unit-by-unit based on any time format. Where \l setFromTimeUnit resets the complete time interval, setPart only sets a specific part in a chosen format. \b Example: If you have a time span representing 3 weeks, 2 days, 4 hours, 31 minutes and 12 seconds, you can change the number of hours to 2 by just calling \code span.setPart(Qt::Hours, 2, Qt::Weeks | Qt::Days | Qt::Hours | Qt::Minutes | Qt::Seconds); \endcode Note that just like with any other function, you can not use the Months and Years units without using a reference date. */ void QTimeSpan::setPart(Qt::TimeSpanUnit unit, int interval, Qt::TimeSpanFormat format) { if (!format.testFlag(unit)) { qWarning() << "Can not set a unit that is not part of the format. Ignoring."; return; } QTimeSpanPrivate::TimePartHash partsHash(format); bool result = partsHash.fill(*this); if (!result) { qWarning() << "Retreiving parts failed, cannot set parts. Ignoring."; return; } d->addUnit(this, unit, interval - *(partsHash.value(unit) ) ); } /*! Returns \c Qt::TimeSpanUnit representing the order of magnitude of the time span. That is, the largest unit that can be used to display the time span that will result in a non-zero value. If the QTimeSpan does not have a valid reference date, the largest possible time unit that will be returned is Qt::Weeks. Otherwise, the largest possible time unit is Qt::Years. */ Qt::TimeSpanUnit QTimeSpan::magnitude() { qint64 mag = d->interval; mag = qAbs(mag); if (mag < 1000) return Qt::Milliseconds; if (mag < (Q_INT64_C(60) * Q_INT64_C(1000))) return Qt::Seconds; if (mag < (Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000))) return Qt::Minutes; if (mag < (Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000))) return Qt::Hours; if (mag < (Q_INT64_C(7) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000))) return Qt::Days; //those the simple cases. The rest is dependent on if there is a reference date if (hasValidReference()) { //simple test. If bigger than 366 (not 365!) then we are certain of dealing with years if (mag > (Q_INT64_C(366) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000))) return Qt::Years; //we need a more complicated test int years = 0; int months = 0; parts(0, 0, 0, 0, 0, 0, &months, &years); if (years > 0) return Qt::Years; if (months > 0) return Qt::Months; } return Qt::Weeks; } /*! Returns \c true if there is a valid reference date set, false otherwise. */ bool QTimeSpan::hasValidReference() const { return d->reference.isValid(); } /*! Returns the reference date. Note that the reference date may be invalid. */ QDateTime QTimeSpan::referenceDate() const { return d->reference; } /*! Sets the reference date. If there currently is a reference date, the referenced date will not be affected. That means that the length of the time span will change. If there currently is no reference date set, the interval will not be affected and this function will have the same effect as \l moveReferenceDate(). \sa moveReferenceDate() setReferencedDate() moveReferencedDate() */ void QTimeSpan::setReferenceDate(const QDateTime &referenceDate) { if (d->reference.isValid() && referenceDate.isValid()) { *this = referencedDate() - referenceDate; } else { d->reference = referenceDate; } } /*! Moves the time span to align the time spans reference date with the new reference date \a referenceDate. Note that the length of the time span will not be modified, so the referenced date will shift as well. If no reference date was set before, it is set now and the referenced date will become valid. \sa setReferenceDate() setReferencedDate() moveReferencedDate() */ void QTimeSpan::moveReferenceDate(const QDateTime &referenceDate) { d->reference = referenceDate; } /*! Sets the referenced date. If there currently is a reference date, that reference date will not be affected. This implies that the length of the time span changes. If there currently is no reference date set, the interval will not be affected and this function will have the same effect as \l moveReferencedDate(). \sa setReferenceDate() moveReferenceDate() moveReferencedDate() */ void QTimeSpan::setReferencedDate(const QDateTime &referencedDate) { if (d->reference.isValid()) { *this = referencedDate - d->reference; } else { d->reference = referencedDate.addMSecs(-(d->interval)); } } /*! Moves the time span to align the time spans referenced date with the new referenced date. Note that the length of the time span will not be modified, so the reference date will shift as well. If no reference date was set before, it is set now. \sa setReferenceDate() setReferencedDate() moveReferencedDate() */ void QTimeSpan::moveReferencedDate(const QDateTime &referencedDate) { d->reference = referencedDate.addMSecs(-(d->interval)); } /*! Returns the referenced date and time. The referenced QDateTime is the "other end" of the QTimeSpan from the reference date. An invalid QDateTime will be returned if no valid reference date has been set. */ QDateTime QTimeSpan::referencedDate() const { if (!(d->reference.isValid())) return QDateTime(); QDateTime dt(d->reference); dt = dt.addMSecs(d->interval); return dt; } // Comparison operators /*! Returns true if this QTimeSpan and \a other have both the same reference date and the same length. Note that two QTimeSpan objects that span the same period, but where one is positive and the other is negative are \b not considdered equal. If you need to compare those, compare the normalized versions. \sa matchesLength() */ bool QTimeSpan::operator==(const QTimeSpan &other) const { return ((d->interval == other.d->interval) && (d->reference == other.d->reference)); } /*! Returns true if the interval of this QTimeSpan is shorter than the interval of the \a other QTimeSpan. */ bool QTimeSpan::operator<(const QTimeSpan &other) const { return d->interval < other.d->interval; } /*! Returns true if the interval of this QTimeSpan is shorter or equal than the interval of the \a other QTimeSpan. */ bool QTimeSpan::operator<=(const QTimeSpan &other) const { return d->interval <= other.d->interval; } /*! Returns true if the interval of this QTimeSpan is equal to the interval of the \a other QTimeSpan. That is, if they have the same length. The default value of \a normalize is false. If normalize is true, the absolute values of the interval lengths are compared instead of the real values. \code QTimeSpan s1 = 2 * QTimeSpan::day(); QTimeSpan s2 = -2 * QTimeSpan::day(); qDebug() << s1.matchesLength(s2); //returns false qDebug() << s1.matchesLength(s2, true); //returns true \endcode */ bool QTimeSpan::matchesLength(const QTimeSpan &other, bool normalize) const { if (!normalize) { return d->interval == other.d->interval; } else { return qAbs(d->interval) == qAbs(other.d->interval); } } // Arithmetic operators /*! Adds the interval of the \a other QTimeSpan to the interval of this QTimeSpan. The reference date of the \a other QTimeSpan is ignored. */ QTimeSpan & QTimeSpan::operator+=(const QTimeSpan &other) { d->interval += other.d->interval; return *this; } /*! Adds the number of milliseconds \a msecs to the interval of this QTimeSpan. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator+=(qint64 msecs) { d->interval += msecs; return *this; } /*! Substracts the interval of the \a other QTimeSpan from the interval of this QTimeSpan. The reference date of the \a other QTimeSpan is ignored while the reference date of this QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator-=(const QTimeSpan &other) { d->interval -= (other.d->interval); return *this; } /*! Substracts the number of milliseconds \a msecs from the interval of this QTimeSpan. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator-=(qint64 msecs) { d->interval -= msecs; return *this; } /*! Multiplies the interval described by this QTimeSpan by the given \a factor. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator*=(qreal factor) { d->interval *= factor; return *this; } /*! Multiplies the interval described by this QTimeSpan by the given \a factor. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator*=(int factor) { d->interval *= factor; return *this; } /*! Divides the interval described by this QTimeSpan by the given \a factor. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator/=(qreal factor) { d->interval /= factor; return *this; } /*! Divides the interval described by this QTimeSpan by the given \a factor. The reference date of the QTimeSpan is not affected. */ QTimeSpan & QTimeSpan::operator/=(int factor) { d->interval /= factor; return *this; } /*! Modifies this QTimeSpan to be the union of this QTimeSpan with \a other. The union of two QTimeSpans is defined as the minimum QTimeSpan that encloses both QTimeSpans. The QTimeSpans need not be overlapping. \warning Only works if both QTimeSpans have a valid reference date. \sa operator&=() \sa operator|() \sa united() */ QTimeSpan& QTimeSpan::operator|=(const QTimeSpan& other) // Union { Q_ASSERT_X((hasValidReference() && other.hasValidReference()), "assignment-or operator", "Both participating time spans need a valid reference date"); //do we need to check for self-assignment? QDateTime start = qMin(startDate(), other.startDate()); QDateTime end = qMax(endDate(), other.endDate()); *this = end - start; return *this; } /*! Modifies this QTimeSpan to be the intersection of this QTimeSpan and \a other. The intersection of two QTimeSpans is defined as the maximum QTimeSpan that both QTimeSpans have in common. If the QTimeSpans don't overlap, a null QTimeSpan will be returned. The returned QTimeSpan will be positive. \warning Only works if both QTimeSpans have a valid reference date. \sa operator&=() \sa operator&() \sa overlapped() */ QTimeSpan& QTimeSpan::operator&=(const QTimeSpan &other) // Intersection { Q_ASSERT_X((hasValidReference() && other.hasValidReference()), "assignment-or operator", "Both participating time spans need a valid reference date"); //do we need to check for self-assignment? const QTimeSpan* first = this; const QTimeSpan* last = &other; if (other.startDate() < startDate()) { first = &other; last = this; } //check if there is overlap at all. If not, reset the interval to 0 if (!(first->endDate() > last->startDate()) ) { d->interval = 0; return *this; } *this = qMin(first->endDate(), last->endDate()) - last->startDate(); return *this; } /*! Returns true if this QTimeSpan overlaps with the \a other QTimeSpan. If one or both of the QTimeSpans do not have a valid reference date, this function returns false. */ bool QTimeSpan::overlaps(const QTimeSpan &other) const { if (!hasValidReference() || !other.hasValidReference()) return false; const QTimeSpan* first = this; const QTimeSpan* last = &other; if (other.startDate() < startDate()) { first = &other; last = this; } return (first->endDate() > last->startDate()); } /*! Returns a new QTimeSpan that represents the intersection of this QTimeSpan with \a other. The intersection of two QTimeSpans is defined as the maximum QTimeSpan that both QTimeSpans have in common. If the QTimeSpans don't overlap, a null QTimeSpan will be returned. Any valid returned QTimeSpan will be positive. \warning Only works if both QTimeSpans have a valid reference date. \sa operator&=() \sa operator&() */ QTimeSpan QTimeSpan::overlapped(const QTimeSpan &other) const { Q_ASSERT_X((hasValidReference() && other.hasValidReference()), "assignment-or operator", "Both participating time spans need a valid reference date"); const QTimeSpan* first = this; const QTimeSpan* last = &other; if (other.startDate() < startDate()) { first = &other; last = this; } //check if there is overlap at all. If not, reset the interval to 0 if (!(first->endDate() >= last->startDate()) ) { return QTimeSpan(); } return qMin(first->endDate(), last->endDate()) - last->startDate(); } /*! Returns a new QTimeSpan that represents the union of this QTimeSpan with \a other. The union of two QTimeSpans is defined as the minimum QTimeSpan that encloses both QTimeSpans. The QTimeSpans need not be overlapping. \warning Only works if both QTimeSpans have a valid reference date. \sa operator|=() \sa operator|() */ QTimeSpan QTimeSpan::united(const QTimeSpan &other) const { Q_ASSERT_X((hasValidReference() && other.hasValidReference()), "assignment-or operator", "Both participating time spans need a valid reference date"); QDateTime start = qMin(startDate(), other.startDate()); QDateTime end = qMax(endDate(), other.endDate()); return ( end - start ); } /*! Determines if the given \a dateTime lies within the time span. The begin and end times are taken to be contained in the time span in this function. If the time span does not have a valid reference date, this function returns false. */ bool QTimeSpan::contains(const QDateTime &dateTime) const { if (!hasValidReference()) return false; return ((startDate() <= dateTime) && (endDate()) >= dateTime); } /*! Determines if the given date lies within the time span. The begin and end times are taken to be contained in the time span in this function. Just like in the QTimeSpan constructors that take a QDate, the time will assumed to be 00:00:00.000. If the time span does not have a valid reference date, this function returns false. */ bool QTimeSpan::contains(const QDate &date) const { QDateTime dt(date); return contains(dt); } /*! Determines if the given \a time lies within this QTimeSpan. The begin and end times are taken to be contained in the time span in this function. Just like in the QTimeSpan constructors that take a QTime, the date will be set to today. If the time span does not have a valid reference date, this function returns false. */ bool QTimeSpan::contains(const QTime &time) const { QDateTime dt(QDate::currentDate()); dt.setTime(time); return contains(dt); } /*! Determines if the \a other QTimeSpan lies within this time span. Another time span is contained if its start time is the same or later then the start time of this time span, and its end time is the same or earlier than the end time of this time span. If either time span does not have a valid reference date, this function returns false. */ bool QTimeSpan::contains(const QTimeSpan &other) const { if (!(hasValidReference() && other.hasValidReference())) return false; return ((startDate() <= other.startDate()) && (endDate()) >= other.endDate()); } /*! Returns a new QTimeSpan representing the same time span as this QTimeSpan, but that is guaranteed to be positive; that is, to have the reference date before or equal to the referenced date. \sa normalize() \sa abs() */ QTimeSpan QTimeSpan::normalized() const { QTimeSpan ts(*this); ts.normalize(); return ts; } /*! Modifies this QTimeSpan to represent the same time span, but that is guaranteed to be positive; that is, to have the reference date before or equal to the referenced date. If there is no valid reference date, the interval will just be made positive. \sa normalized() \sa abs() */ void QTimeSpan::normalize() { if (d->interval < 0) { if (hasValidReference()) d->reference = referencedDate(); d->interval = qAbs(d->interval); } } /*! Returns a copy of this QTimeSpan that is guaranteed to be positive; that is, to have the reference date before or equal to the referenced date. The reference date is not modified. That implies that if there is a reference date, and the QTimeSpan is negative, the returned QTimeSpan will describe the time span \i after the reference date instead of the time span \i before. If there is no valid reference date, the interval will just be made positive. \sa normalize() \sa normalized() */ QTimeSpan QTimeSpan::abs() const { QTimeSpan result(*this); result.d->interval = qAbs(result.d->interval); return result; } /*! Returns true if the interval is negative. \sa isNormal() */ bool QTimeSpan::isNegative() const { return d->interval < 0; } /*! \fn QTimeSpan::isNormal() const Returns true if the interval is normal, that is: not negative. \sa isNegative() */ /*! Returns the first date of the spanned time period. If there is no valid reference date, an invalid QDateTime will be returned. */ QDateTime QTimeSpan::startDate() const { if (isNegative()) return referencedDate(); return referenceDate(); } /*! Returns the last date of the spanned time period. If there is no valid reference date, an invalid QDateTime will be returned. */ QDateTime QTimeSpan::endDate() const { if (isNegative()) return referenceDate(); return referencedDate(); } /*! Returns the duration of the QTimeSpan expressed in milliseconds. This value may be negative. */ qint64 QTimeSpan::toMSecs() const { return d->interval; } /*! Returns the duration of the QTimeSpan expressed in the given TimeSpanUnit. This value may be negative. */ qreal QTimeSpan::toTimeUnit(Qt::TimeSpanUnit unit) const { qreal interval = qreal(d->interval); switch (unit){ //fall through is intentional case Qt::Weeks: interval /= 7.0; case Qt::Days: interval /= 24.0; case Qt::Hours: interval /= 60.0; case Qt::Minutes: interval /= 60.0; case Qt::Seconds: interval /= 1000.0; case Qt::Milliseconds: break; default: Q_ASSERT_X(hasValidReference(), "toTimeUnit", "Can not convert to time units that depend on the reference date (month and year)."); qreal result(0.0); int intResult(0); bool succes(false); if (unit == Qt::Months) { succes = parts(0, 0, 0, 0, 0, 0, &intResult, 0, &result); } else if (unit == Qt::Years) { succes = parts(0, 0, 0, 0, 0, 0, 0, &intResult, &result); } if (!succes) return 0.0; return result; } return interval; } /*! Sets the length of this QTimeSpan from the given number of milliseconds \msecs. The reference date is not affected. */ void QTimeSpan::setFromMSecs(qint64 msecs) { d->interval = msecs; } /*! Sets the length of this QTimeSpan from the \a interval number of TimeSpanUnits \a unit. The reference date is not affected. */ void QTimeSpan::setFromTimeUnit(Qt::TimeSpanUnit unit, qreal interval) { switch (unit){ case Qt::Weeks: //fall through of cases is intentional! interval *= 7.0; case Qt::Days: interval *= 24.0; case Qt::Hours: interval *= 60.0; case Qt::Minutes: interval *= 60.0; case Qt::Seconds: interval *= 1000.0; case Qt::Milliseconds: break; case Qt::Months: setFromMonths(interval); return; case Qt::Years: setFromYears(interval); return; default: Q_ASSERT_X(false, "setFromTimeUnit", "Can not set a QTimeSpan duration from unknown TimeSpanUnit."); } d->interval = qint64(interval); } /*! Sets the interval of the time span as a number of \a months. \warning This function can only be used if a valid reference date has been set. The setFromMonths method deals with fractional months in the following way: first, the whole number of months is extracted and added to the reference date. The fractional part of the number of months is then multiplied with the number of days in the month in which that date falls. If the number of months is negative and adding a whole month yields a date exactly on a month boundary, the number of days in the month before is used instead. That number is used as the number of days and is added to the interval. \code QTimeSpan ts(QDate(2010,01,01)); ts.setFromMonths(1.5); // ts's referenced date is now Februari 15, 0:00:00 ts.setFromMonths(2.5); // ts's referenced date is now March 16, 12:00:00 QTimeSpan ts2(QDate(2008,01,01)); //2008 is a leap year ts2.setFromMonths(1.5); // ts2's referenced date is now Februari 15, 12:00:00 QTimeSpan ts3(QDate(2008,03,01)); //2008 is a leap year ts3.setFromMonths(-0.5); // ts3's referenced date is now Februari 15: 12:00:00 // \endcode */ void QTimeSpan::setFromMonths(qreal months) { Q_ASSERT_X(hasValidReference(), "setFromMonths", "Can not set interval from time unit month if there is no reference date."); int fullMonths = int(months); qreal fractionalMonth = months - fullMonths; QDateTime endDate = d->reference; endDate = endDate.addMonths(fullMonths); int days = d->daysInMonth(endDate, fractionalMonth < 0); QTimeSpan tmp = endDate - d->reference; qreal fractionalDays = fractionalMonth * days; d->interval = tmp.toMSecs() + qint64(fractionalDays * 24.0 * 60.0 * 60.0 * 1000.0); } /*! Sets the interval of the time span as a number of \a years. \warning This function can only be used if a valid reference date has been set. The setFromYears method deals with fractional years in the following way: first, the whole number of years is extracted and added to the reference date. The fractional part of the number of years is then multiplied with the number of days in the year in which that date falls. That number is used as the number of days and is added to the interval. If the number of years is negative and adding the whole years yields a date exactly on a year boundary, the number of days in the year before is used instead. */ void QTimeSpan::setFromYears(qreal years) { Q_ASSERT_X(hasValidReference(), "setFromYears", "Can not set interval from time unit year if there is no reference date."); int fullYears = int(years); qreal fractionalYear = years - fullYears; QDateTime endDate = d->reference; endDate = endDate.addYears(fullYears); qreal days = 365.0; QDateTime measureDate(endDate); if (fractionalYear < 0) measureDate = measureDate.addMSecs(-1); if (QDate::isLeapYear(measureDate.date().year())) days += 1.0; //februari has an extra day this year... QTimeSpan tmp = endDate - d->reference; qreal fractionalDays = fractionalYear * days; d->interval = tmp.toMSecs() + qint64(fractionalDays * 24.0 * 60.0 * 60.0 * 1000.0); } #ifndef QT_NO_DATASTREAM /*! Streaming operator. This operator allows you to stream a QTimeSpan into a QDataStream. \sa operator>>(QDataStream &stream, QTimeSpan &span) */ QDataStream & operator<<(QDataStream &stream, const QTimeSpan & span) { stream << span.d->reference << span.d->interval; return stream; } /*! Streaming operator. This operator allows you to stream a QTimeSpan out of a QDataStream. \sa operator>>(QDataStream &stream, QTimeSpan &span) */ QDataStream & operator>>(QDataStream &stream, QTimeSpan &span) { stream >> span.d->reference >> span.d->interval; return stream; } #endif /*! Adds two QTimeSpan instances. The values of the intervals of the QTimeSpans are added up with normal arithmetic. Negative values will work as expected. If the \a left argument has a reference date, that reference will be used. If only the \a right argument has a reference date, then that reference date will be used as the new reference date. The above can have suprising consequences: \code // s1 and s2 are two QTimeSpan objects QTimeSpan s12 = s1 + s2; QTimeSpan s21 = s2 + s1; if (s12 == s21) { //may or may not happen, depending on the reference dates of s1 and s2. } \endcode \sa operator-() */ QTimeSpan operator+(const QTimeSpan &left, const QTimeSpan &right) { QTimeSpan result(left); result += right; // only keep the right reference date if the left argument does not have one if (!left.hasValidReference() && right.hasValidReference()) result.setReferenceDate(right.referenceDate()); return result; } /*! Substracts one QTimeSpan from another QTimeSpan. The value of the interval of the \a right QTimeSpan is substracted from the \a left QTimeSpan with normal arithmetic. Negative values will work as expected. If the \a left argument has a reference date, that reference will be kept. If only the \a right argument has a reference date, then that reference date will be used as the new reference date. \sa operator+() */ QTimeSpan operator-(const QTimeSpan &left, const QTimeSpan &right) { QTimeSpan result(left); result -= right; // only keep the right reference date if the left argument does not have one if (!left.hasValidReference() && right.hasValidReference()) result.setReferenceDate(right.referenceDate()); return result; } /*! Multiply a QTimeSpan by a scalar factor. Returns a new QTimeSpan object that has the same reference date as the \a left QTimeSpan, but with an interval length that is multiplied by the \a right argument. */ QTimeSpan operator*(const QTimeSpan &left, qreal right) { QTimeSpan result(left); result*=right; return result; } /*! Multiply a QTimeSpan by a scalar factor. \overload */ QTimeSpan operator*(const QTimeSpan &left, int right) { QTimeSpan result(left); result*=right; return result; } /*! Divide a QTimeSpan by a scalar factor. Returns a new QTimeSpan object that has the same reference date as the \a left QTimeSpan, but with an interval length that is devided by the \a right argument. */ QTimeSpan operator/(const QTimeSpan &left, qreal right) { QTimeSpan result(left); result/=right; return result; } /*! Divide a QTimeSpan by a scalar factor. \overload */ QTimeSpan operator/(const QTimeSpan &left, int right) { QTimeSpan result(left); result/=right; return result; } /*! Devides two QTimeSpans. The devision works on the interval lengths of the two QTimeSpan objects as you would expect from normal artithmatic. */ qreal operator/(const QTimeSpan &left, const QTimeSpan &right) { return (qreal(left.toMSecs()) / qreal(right.toMSecs())); } /*! Returns a QTimeSpan object with the same reference date as the \a right hand argument, but with a negated interval. Note that unlike with the \l normalize() method, this function will result in a QTimeSpan that describes a different period if the QTimeSpan has a reference date because the reference date is not modified. \sa normalize() */ QTimeSpan operator-(const QTimeSpan &right) // Unary negation { QTimeSpan result(right); result.setFromMSecs(-result.toMSecs()); return result; } /*! Returns the union of the two QTimeSpans. \sa united() */ QTimeSpan operator|(const QTimeSpan &left, const QTimeSpan &right) // Union { QTimeSpan result(left); result|=right; return result; } /*! Returns the intersection of the two QTimeSpans. \sa overlapped() */ QTimeSpan operator&(const QTimeSpan &left, const QTimeSpan &right) // Intersection { QTimeSpan result(left); result&=right; return result; } // Operators that use QTimeSpan and other date/time classes /*! Creates a new QTimeSpan object that describes the period between the two QDateTime objects. The \a right hand object will be used as the reference date, so that substracting a date in the past from a date representing now will yield a positive QTimeSpan. Note that while substracting two dates will result in a QTimeSpan describing the time between those dates, there is no pendant operation for adding two dates. Substractions involving an invalid QDateTime, will result in a time span with an interval length 0. If the right-hand QDateTime is valid, it will still be used as the reference date. */ QTimeSpan operator-(const QDateTime &left, const QDateTime &right) { QTimeSpan result(right); if (left.isValid() && right.isValid()) result = QTimeSpan(right, right.msecsTo(left)); return result; } /*! Creates a new QTimeSpan object that describes the period between the two QDate objects. The \a right hand object will be used as the reference date, so that substracting a date in the past from a date representing now will yield a positive QTimeSpan. Note that while substracting two dates will result in a QTimeSpan describing the time between those dates, there is no pendant operation for adding two dates. \overload */ QTimeSpan operator-(const QDate &left, const QDate &right) { QTimeSpan result = QDateTime(left) - QDateTime(right); return result; } /*! Creates a new QTimeSpan object that describes the period between the two QTime objects. The \a right hand time will be used as the reference time, so that substracting a time in the past from a time representing now will yield a positive QTimeSpan. Note that that both times will be assumed to be on the current date. Also observe that while substracting two times will result in a QTimeSpan describing the time between those, there is no pendant operation for adding two times. */ QTimeSpan operator-(const QTime &left, const QTime &right) { return QDateTime(QDate::currentDate(), left) - QDateTime(QDate::currentDate(), right); } /*! Returns the date described by the \a left hand date, shifted by the interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is ignored. No rounding takes place. If a QTimeSpan describes 1 day, 23 hours and 59 minutes, adding that QTimeSpan to a QDate respresenting April 1 will still yield April 2. \overload */ QDate operator+(const QDate &left, const QTimeSpan &right) { QDateTime dt(left); return (dt + right).date(); } /*! Returns the date and time described by the \a left hand QDateTime, shifted by the interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is ignored. */ QDateTime operator+(const QDateTime &left, const QTimeSpan &right) { QDateTime result(left); result = result.addMSecs(right.toMSecs()); return result; } /*! Returns the time described by the \a left hand QTime, shifted by the interval described in the QTimeSpan \right. The reference date of the QTimeSpan, if set, is ignored. \note that since QTimeSpan works with dates and times, the time returned will never be bigger than 23:59:59.999. The time will wrap to the next date. Use QDateTime objects if you need to keep track of that. \overload */ QTime operator+(const QTime &left, const QTimeSpan &right) { QDateTime dt(QDate::currentDate(), left); dt = dt.addMSecs(right.toMSecs()); return dt.time(); } /*! Returns the date described by the \a left hand date, shifted by the negated interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is ignored. No rounding takes place. If a QTimeSpan describes 1 day, 23 hours and 59 minutes, adding that QTimeSpan to a QDate respresenting April 1 will still yield April 2. \overload */ QDate operator-(const QDate &left, const QTimeSpan &right) { QDateTime dt(left); return (dt - right).date(); } /*! Returns the date and time described by the \a left hand QDateTime, shifted by the negated interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is ignored. */ QDateTime operator-(const QDateTime &left, const QTimeSpan &right) { QDateTime result(left); result = result.addMSecs( -(right.toMSecs()) ); return result; } /*! Returns the time described by the \a left hand QTime, shifted by the negated interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is ignored. \note that since QTimeSpan works with dates and times, the time returned will never be bigger than 23:59:59.999. The time will wrap to the next date. Use QDateTimes if you need to keep track of that. */ QTime operator-(const QTime &left, const QTimeSpan &right) { QDateTime dt(QDate::currentDate(), left); dt = dt.addMSecs( -(right.toMSecs()) ); return dt.time(); } #if !defined(QT_NO_DEBUG_STREAM) && !defined(QT_NO_DATESTRING) /*! Operator to stream QTimeSpan objects to a debug stream. */ QDebug operator<<(QDebug debug, const QTimeSpan &ts) { debug << "QTimeSpan(Reference Date =" << ts.referenceDate() << "msecs =" << ts.toMSecs() << ")"; return debug; } #endif //String conversions #ifndef QT_NO_DATESTRING /*! Returns an approximate representation of the time span length When representing the lenght of a time span, it is often not nessecairy to be completely accurate. For instance, when dispaying the age of a person, it is often enough to just state the number of years, or possibly the number of years and the number of months. Similary, when displaying how long a certain operation the user of your application started will run, it is useless to display the number of seconds left if the operation will run for hours more. toApproximateString() provides functionality to display the length of the QTimeSpan in such an approximate way. It will format the time using one or two neighbouring time units, chosen from the units set in \a format. The first time unit that will be used is the unit that represents the biggest portion of time in the span. The second time unit will be the time unit directly under that. The second unit will only be used if it is not 0, and if the first number is smaller than the indicated \a suppresSecondUnitLimit. The \a suppressSecondUnitLimit argument can be used to suppres, for instance, the number of seconds when the operation will run for more than five minutes more. The idea is that for an approximate representation of the time length, it is no longer relevant to display the second unit if the first respresents a time span that is perhaps an order of magnitude larger already. If you set \a suppressSecondUnitLimit to a negative number, the second unit will always be displayed, unless no valid unit for it could be found. \sa magnitude() toString() */ QString QTimeSpan::toApproximateString(int suppresSecondUnitLimit, Qt::TimeSpanFormat format) { if (format==Qt::NoUnit) return QString(); //retreive the time unit to use as the primairy unit int primairy = -1; int secondairy = -1; Qt::TimeSpanUnit primairyUnit = magnitude(); while (!format.testFlag(primairyUnit ) && primairyUnit > Qt::NoUnit) primairyUnit = Qt::TimeSpanUnit(primairyUnit / 2); Qt::TimeSpanUnit secondairyUnit = Qt::NoUnit; if (primairyUnit > 1) { secondairyUnit = Qt::TimeSpanUnit(primairyUnit / 2); } else { primairy = 0; } while (!format.testFlag(secondairyUnit) && secondairyUnit > Qt::NoUnit) secondairyUnit = Qt::TimeSpanUnit(secondairyUnit / 2); //build up hash with pointers to ints for the units that are set in format, and 0's for those that are not. if (primairy < 0) { QTimeSpanPrivate::TimePartHash partsHash(format); bool result = partsHash.fill(*this); if (!result) { qDebug() << "false result from parts function"; return QString(); } primairy = *(partsHash.value(primairyUnit)); if (secondairyUnit > 0) { secondairy = *(partsHash.value(secondairyUnit)); } else { secondairy = 0; } } if ((primairy > 0 && secondairy > 0 && primairy < suppresSecondUnitLimit) || (suppresSecondUnitLimit < 0 && secondairyUnit > Qt::NoUnit) ) { //we will display with two units return d->unitString(primairyUnit, primairy) + QLatin1String(", ") + d->unitString(secondairyUnit, secondairy); } //we will display with only the primairy unit return d->unitString(primairyUnit, primairy); } /*! Returns a string representation of the duration of this time span in the requested \a format This function returns a representation of only the \i length of this time span. If you need the reference or referenced dates, access those using one of the provided methods and output them directly. The format parameter determines the format of the result string. The duration will be expressed in the units you use in the format. \table \header \o character \o meaning \row \o y \o The number of years \row \o M \o The number of months \row \o w \o The number of weeks \row \o d \o The number of days \row \o h \o The number of hours \row \o m \o The number of minutes \row \o s \o The number of seconds \row \o z \o The number of milliseconds \endtable Use a letter repeatingly to force leading zeros. Note that you can not use years or months if the QTimeSpan does not have a valid reference date. Characters in the string that don't represent a time unit, are used as literal strings in the output. Everything between single quotes will always be used as a literal string. This makes it possible to use the characters used for the time span format also as literal output. To use a single quote in the output, put two consecutive single quotes within a single quote literal string block. To just put a single quote in a the output, you need four consequtive single quotes. \sa toApproximateString() */ QString QTimeSpan::toString(const QString &format) const { Qt::TimeSpanFormat tsFormat = Qt::NoUnit; QList<QTimeSpanPrivate::TimeFormatToken> tokenList = d->parseFormatString(format, tsFormat); QTimeSpanPrivate::TimePartHash partsHash(tsFormat); bool result = partsHash.fill(*this); if (!result) return QString(); QString formattedString; foreach(QTimeSpanPrivate::TimeFormatToken token, tokenList) { if (token.type == 0) { formattedString.append(token.string); } else { Qt::TimeSpanUnit unit(token.type); formattedString.append (QString(QString::fromLatin1("%1")) .arg(*partsHash.value(unit), token.length, 10, QChar('0', 0) ) ); } } return formattedString; } /*! Returns a time span represented by the \a string using the \a format given, or an empty time span if the string cannot be parsed. The optional \a reference argument will be used as the reference date for the string. \note You can only use months or years if you also pass a valid reference. */ QTimeSpan QTimeSpan::fromString(const QString &string, const QString &format, const QDateTime &reference) { /* There are at least two possible ways of parsing a string. On the one hand, you could use the lengths of string literals to determine the positions in the string where you expect the different parts of the string. On the other hand, you could use the actual contents of the literals as delimiters to figure out what parts of the string refer to what unit of time. In that case, the length of the time units would only matter if they are not surrounded by a string literal. Both seem useful. Perhaps we need two different modes for this? The code here implements the first option. The overloaded version below implements a more flexible regexp based approach. */ //stage one: parse the format string QTimeSpan span(reference); Qt::TimeSpanFormat tsFormat = Qt::NoUnit; QList<QTimeSpanPrivate::TimeFormatToken> tokenList = span.d->parseFormatString(format, tsFormat); //prepare the temporaries QTimeSpanPrivate::TimePartHash partsHash(tsFormat); QString input(string); //extract the values from the input string into our temporary structure foreach(const QTimeSpanPrivate::TimeFormatToken token, tokenList) { if (token.type == Qt::NoUnit) { input = input.remove(0, token.length); } else { QString part = input.left(token.length); input = input.remove(0, token.length); bool success(false); part = part.trimmed(); int value = part.toInt(&success, 10); if (!success) return QTimeSpan(); *(partsHash.value(token.type)) = value; } } //construct the time span from the temporary data //we must set the number of years and months first; for the rest order is not important if (partsHash.value(Qt::Years)) { span.d->addUnit(&span, Qt::Years, *(partsHash.value(Qt::Years))); delete partsHash.value(Qt::Years); partsHash.insert(Qt::Years, 0); } if (partsHash.value(Qt::Months)) { span.d->addUnit(&span, Qt::Months, *(partsHash.value(Qt::Months))); delete partsHash.value(Qt::Months); partsHash.insert(Qt::Months, 0); } //add the rest of the units QHashIterator<Qt::TimeSpanUnit, int*> it(partsHash); while (it.hasNext()) { it.next(); if (it.value()) { span.d->addUnit(&span, it.key(), *(it.value())); qDebug() << "Added unit" << it.key() << "with value" << *(it.value()) << "new value" << span.d->interval; } } return span; } /*! Returns a time span represented by the \a string using the \a patern given, or an empty time span if the \a string cannot be parsed. Each pair of capturing parenthesis can extract a time unit. The order in which the units appear is given by the list of arguments unit1 to unit8. Captures for which the corresponding type is set to Qt::NoUnit will be ignored. The \a reference argument will be used as the reference date for the string. \note You can only use months or years if you also pass a valid \a reference. */ QTimeSpan QTimeSpan::fromString(const QString &string, const QRegExp &pattern, const QDateTime &reference, Qt::TimeSpanUnit unit1, Qt::TimeSpanUnit unit2, Qt::TimeSpanUnit unit3, Qt::TimeSpanUnit unit4, Qt::TimeSpanUnit unit5, Qt::TimeSpanUnit unit6, Qt::TimeSpanUnit unit7, Qt::TimeSpanUnit unit8) { if (pattern.indexIn(string) < 0) return QTimeSpan(); QTimeSpanPrivate::TimePartHash partsHash(Qt::NoUnit); QList<Qt::TimeSpanUnit> unitList; unitList << unit1 << unit2 << unit3 << unit4 << unit5 << unit6 << unit7 << unit8; for (int i(0); i < qMin(pattern.captureCount(), 8 ); ++i) { if (unitList.at(i) > Qt::NoUnit) { partsHash.addUnit(unitList.at(i)); QString capture = pattern.cap(i + 1); bool ok(false); int value = capture.toInt(&ok, 10); if (!ok) return QTimeSpan(); *(partsHash.value(unitList.at(i))) = value; } } //create the time span to return QTimeSpan span(reference); //construct the time span from the temporary data //we must set the number of years and months first; for the rest order is not important if (partsHash.value(Qt::Years)) { span.d->addUnit(&span, Qt::Years, *(partsHash.value(Qt::Years))); delete partsHash.value(Qt::Years); partsHash.insert(Qt::Years, 0); } if (partsHash.value(Qt::Months)) { span.d->addUnit(&span, Qt::Months, *(partsHash.value(Qt::Months))); delete partsHash.value(Qt::Months); partsHash.insert(Qt::Months, 0); } //add the rest of the units QHashIterator<Qt::TimeSpanUnit, int*> it(partsHash); while (it.hasNext()) { it.next(); if (it.value()) span.d->addUnit(&span, it.key(), *(it.value())); } return span; } #endif QT_END_NAMESPACE
[ "squual@kahvipaussi.net" ]
squual@kahvipaussi.net
495c133809f1be0759d9d317921fdb258f849e89
c37be0d1ddf85325c6bd02a0c57cb1dfe2df8c36
/chrome/browser/media/router/mojo/extension_media_route_provider_proxy_unittest.cc
e324ddcdb4ddc7ff8e06880556332c8433687387
[ "BSD-3-Clause" ]
permissive
idofilus/chromium
0f78b085b1b4f59a5fc89d6fc0efef16beb63dcd
47d58b9c7cb40c09a7bdcdaa0feead96ace95284
refs/heads/master
2023-03-04T18:08:14.105865
2017-11-14T18:26:28
2017-11-14T18:26:28
111,206,269
0
0
null
2017-11-18T13:06:33
2017-11-18T13:06:32
null
UTF-8
C++
false
false
11,392
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/router/mojo/extension_media_route_provider_proxy.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/test/mock_callback.h" #include "chrome/browser/media/router/event_page_request_manager.h" #include "chrome/browser/media/router/event_page_request_manager_factory.h" #include "chrome/browser/media/router/mojo/media_router_mojo_test.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::ElementsAre; using testing::Invoke; using testing::Mock; using testing::StrictMock; using testing::WithArg; namespace media_router { namespace { using MockRouteCallback = base::MockCallback<MockMediaRouteProvider::RouteCallback>; using MockTerminateRouteCallback = base::MockCallback<mojom::MediaRouteProvider::TerminateRouteCallback>; using MockBoolCallback = base::MockCallback<base::OnceCallback<void(bool)>>; using MockSearchSinksCallback = base::MockCallback<base::OnceCallback<void(const std::string&)>>; const char kDescription[] = "description"; const bool kIsIncognito = false; const char kSource[] = "source1"; const char kRouteId[] = "routeId"; const char kSinkId[] = "sink"; const int kTabId = 1; const char kPresentationId[] = "presentationId"; const char kOrigin[] = "http://origin/"; const int kTimeoutMillis = 5 * 1000; } // namespace class ExtensionMediaRouteProviderProxyTest : public testing::Test { public: ExtensionMediaRouteProviderProxyTest() = default; ~ExtensionMediaRouteProviderProxyTest() override = default; protected: void SetUp() override { request_manager_ = static_cast<MockEventPageRequestManager*>( EventPageRequestManagerFactory::GetInstance()->SetTestingFactoryAndUse( &profile_, &MockEventPageRequestManager::Create)); ON_CALL(*request_manager_, RunOrDeferInternal(_, _)) .WillByDefault(Invoke([](base::OnceClosure& request, MediaRouteProviderWakeReason wake_reason) { std::move(request).Run(); })); provider_proxy_ = base::MakeUnique<ExtensionMediaRouteProviderProxy>( &profile_, mojo::MakeRequest(&provider_proxy_ptr_)); RegisterMockMediaRouteProvider(); } const MediaSource media_source_ = MediaSource(kSource); const MediaRoute route_ = MediaRoute(kRouteId, media_source_, kSinkId, kDescription, false, "", false); std::unique_ptr<ExtensionMediaRouteProviderProxy> provider_proxy_; mojom::MediaRouteProviderPtr provider_proxy_ptr_; StrictMock<MockMediaRouteProvider> mock_provider_; MockEventPageRequestManager* request_manager_ = nullptr; std::unique_ptr<mojo::Binding<mojom::MediaRouteProvider>> binding_; private: void RegisterMockMediaRouteProvider() { mock_provider_.SetRouteToReturn(route_); mojom::MediaRouteProviderPtr mock_provider_ptr; binding_ = base::MakeUnique<mojo::Binding<mojom::MediaRouteProvider>>( &mock_provider_, mojo::MakeRequest(&mock_provider_ptr)); provider_proxy_->RegisterMediaRouteProvider(std::move(mock_provider_ptr)); } content::TestBrowserThreadBundle thread_bundle_; TestingProfile profile_; DISALLOW_COPY_AND_ASSIGN(ExtensionMediaRouteProviderProxyTest); }; TEST_F(ExtensionMediaRouteProviderProxyTest, CreateRoute) { EXPECT_CALL( mock_provider_, CreateRouteInternal(kSource, kSinkId, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, _)) .WillOnce(WithArg<7>(Invoke( &mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess))); MockRouteCallback callback; provider_proxy_->CreateRoute( kSource, kSinkId, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, JoinRoute) { EXPECT_CALL( mock_provider_, JoinRouteInternal( kSource, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, _)) .WillOnce(WithArg<6>(Invoke( &mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess))); MockRouteCallback callback; provider_proxy_->JoinRoute( kSource, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, ConnectRouteByRouteId) { EXPECT_CALL( mock_provider_, ConnectRouteByRouteIdInternal( kSource, kRouteId, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, _)) .WillOnce(WithArg<7>(Invoke( &mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess))); MockRouteCallback callback; provider_proxy_->ConnectRouteByRouteId( kSource, kRouteId, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, TerminateRoute) { EXPECT_CALL(mock_provider_, TerminateRouteInternal(kRouteId, _)) .WillOnce(WithArg<1>(Invoke( &mock_provider_, &MockMediaRouteProvider::TerminateRouteSuccess))); MockTerminateRouteCallback callback; provider_proxy_->TerminateRoute( kRouteId, base::BindOnce(&MockTerminateRouteCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, SendRouteMessage) { const std::string message = "message"; EXPECT_CALL(mock_provider_, SendRouteMessageInternal(kRouteId, message, _)) .WillOnce(WithArg<2>(Invoke( &mock_provider_, &MockMediaRouteProvider::SendRouteMessageSuccess))); MockBoolCallback callback; provider_proxy_->SendRouteMessage( kRouteId, message, base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, SendRouteBinaryMessage) { std::vector<uint8_t> data = {42}; EXPECT_CALL(mock_provider_, SendRouteBinaryMessageInternal(kRouteId, ElementsAre(42), _)) .WillOnce(WithArg<2>( Invoke(&mock_provider_, &MockMediaRouteProvider::SendRouteBinaryMessageSuccess))); MockBoolCallback callback; provider_proxy_->SendRouteBinaryMessage( kRouteId, data, base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, StartAndStopObservingMediaSinks) { EXPECT_CALL(mock_provider_, StopObservingMediaSinks(kSource)); provider_proxy_->StopObservingMediaSinks(kSource); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, StartAndStopObservingMediaRoutes) { EXPECT_CALL(mock_provider_, StopObservingMediaRoutes(kSource)); provider_proxy_->StopObservingMediaRoutes(kSource); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, StartListeningForRouteMessages) { EXPECT_CALL(mock_provider_, StartListeningForRouteMessages(kSource)); provider_proxy_->StartListeningForRouteMessages(kSource); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, StopListeningForRouteMessages) { EXPECT_CALL(mock_provider_, StopListeningForRouteMessages(kSource)); provider_proxy_->StopListeningForRouteMessages(kSource); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, DetachRoute) { EXPECT_CALL(mock_provider_, DetachRoute(kRouteId)); provider_proxy_->DetachRoute(kRouteId); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, EnableMdnsDiscovery) { EXPECT_CALL(mock_provider_, EnableMdnsDiscovery()); provider_proxy_->EnableMdnsDiscovery(); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, UpdateMediaSinks) { EXPECT_CALL(mock_provider_, UpdateMediaSinks(kSource)); provider_proxy_->UpdateMediaSinks(kSource); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, SearchSinks) { EXPECT_CALL(mock_provider_, SearchSinksInternal(kSinkId, kSource, _, _)) .WillOnce(WithArg<3>(Invoke( &mock_provider_, &MockMediaRouteProvider::SearchSinksSuccess))); auto sink_search_criteria = mojom::SinkSearchCriteria::New(); MockSearchSinksCallback callback; provider_proxy_->SearchSinks(kSinkId, kSource, std::move(sink_search_criteria), base::BindOnce(&MockSearchSinksCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, ProvideSinks) { const std::string provider_name = "provider name"; MediaSinkInternal sink; sink.set_sink_id(kSinkId); const std::vector<media_router::MediaSinkInternal> sinks = {sink}; EXPECT_CALL(mock_provider_, ProvideSinks(provider_name, ElementsAre(sink))); provider_proxy_->ProvideSinks(provider_name, sinks); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, CreateMediaRouteController) { EXPECT_CALL(mock_provider_, CreateMediaRouteControllerInternal(kRouteId, _, _, _)) .WillOnce(WithArg<3>( Invoke(&mock_provider_, &MockMediaRouteProvider::CreateMediaRouteControllerSuccess))); mojom::MediaControllerPtr controller_ptr; mojom::MediaControllerRequest controller_request = mojo::MakeRequest(&controller_ptr); mojom::MediaStatusObserverPtr observer_ptr; mojom::MediaStatusObserverRequest observer_request = mojo::MakeRequest(&observer_ptr); MockBoolCallback callback; provider_proxy_->CreateMediaRouteController( kRouteId, std::move(controller_request), std::move(observer_ptr), base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback))); base::RunLoop().RunUntilIdle(); } TEST_F(ExtensionMediaRouteProviderProxyTest, NotifyRequestManagerOnError) { // Invalidating the Mojo pointer to the MRP held by the proxy should make it // notify request manager. EXPECT_CALL(*request_manager_, OnMojoConnectionError()); binding_.reset(); base::RunLoop().RunUntilIdle(); } } // namespace media_router
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
30a02e5de3fa2d8f8b3c2cbd43ea7f6019403106
424601113e009bf6efecc9ef33b964eb89ad4cea
/mediadevice/qffmpegencoder.cpp
1ad40910d4dc5befc1343068d6649abee67fa3fe
[]
no_license
robby31/multimedia
b34ad589559b2124c460e7bfb057f5ad8c74ecf5
ba4c9c51cd0e347e703c3dcfeafc01f9aa770fdd
refs/heads/master
2021-06-07T07:28:28.635996
2020-02-15T07:42:12
2020-02-15T07:42:12
96,641,230
0
0
null
null
null
null
UTF-8
C++
false
false
4,351
cpp
#include "qffmpegencoder.h" QFfmpegEncoder::QFfmpegEncoder(QObject *parent): QFfmpegCodec(parent) { } QFfmpegEncoder::~QFfmpegEncoder() { _close(); } void QFfmpegEncoder::close() { _close(); } void QFfmpegEncoder::_close() { #if !defined(QT_NO_DEBUG_OUTPUT) if (codecCtx() != Q_NULLPTR) qDebug() << format() << codecCtx()->frame_number << "frames encoded."; #endif if (!m_encodedPkt.isEmpty()) qWarning() << m_encodedPkt.size() << "frames not encoded remains in encoder" << format(); clear(); QFfmpegCodec::close(); } bool QFfmpegEncoder::encodeFrame(QFfmpegFrame *frame) { bool result = false; if (isValid()) { AVPacket *pkt = Q_NULLPTR; pkt = av_packet_alloc(); if (!pkt) { qCritical() << "Could not allocate packet"; } else { int ret; av_init_packet(pkt); /* send the frame to the encoder */ if (frame != Q_NULLPTR && frame->ptr() != Q_NULLPTR) ret = avcodec_send_frame(codecCtx(), frame->ptr()); else ret = avcodec_send_frame(codecCtx(), Q_NULLPTR); // flush encoder if (ret == AVERROR_EOF) { // EOF reached } else if (ret < 0) { qCritical() << "Error sending a frame for encoding"; } else { while (ret >= 0) { ret = avcodec_receive_packet(codecCtx(), pkt); if (ret == 0) { m_encodedPkt << pkt; pkt = av_packet_alloc(); av_init_packet(pkt); } else if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { result = true; } else if (ret < 0) { qCritical() << "Error during encoding"; } av_packet_unref(pkt); } } } av_packet_free(&pkt); } else { qCritical() << "codec is invalid for encoding."; } return result; } qint64 QFfmpegEncoder::encodedPktAvailable() const { return m_encodedPkt.size(); } AVPacket *QFfmpegEncoder::takeEncodedPkt() { if (!m_encodedPkt.isEmpty()) return m_encodedPkt.takeFirst(); return Q_NULLPTR; } QByteArray QFfmpegEncoder::getRawData() { QByteArray res; foreach (AVPacket *pkt, m_encodedPkt) { if (pkt != Q_NULLPTR) res.append(QByteArray::fromRawData(reinterpret_cast<char *>(pkt->data), pkt->size)); } return res; } bool QFfmpegEncoder::setSampleFmt(const AVSampleFormat &format) { if (codecCtx()) { codecCtx()->sample_fmt = format; return true; } return false; } bool QFfmpegEncoder::setPixelFormat(const AVPixelFormat &format) { if (codecCtx()) { codecCtx()->pix_fmt = format; return true; } return false; } bool QFfmpegEncoder::setChannelLayout(const uint64_t &layout) { if (codecCtx()) { codecCtx()->channel_layout = layout; codecCtx()->channels = av_get_channel_layout_nb_channels(layout); return true; } return false; } bool QFfmpegEncoder::setChannelCount(const int &nb) { if (codecCtx()) { codecCtx()->channel_layout = static_cast<uint64_t>(av_get_default_channel_layout(nb)); codecCtx()->channels = nb; return true; } return false; } bool QFfmpegEncoder::setSampleRate(const int &rate) const { if (codecCtx()) { codecCtx()->sample_rate = rate; return true; } return false; } bool QFfmpegEncoder::setBitRate(const qint64 &bitrate) { if (codecCtx()) { codecCtx()->bit_rate = bitrate; return true; } return false; } qint64 QFfmpegEncoder::nextPts() const { return next_pts; } void QFfmpegEncoder::incrNextPts(const int &duration) { next_pts += duration; } void QFfmpegEncoder::clear() { while (!m_encodedPkt.isEmpty()) { AVPacket *pkt = m_encodedPkt.takeFirst(); av_packet_free(&pkt); } }
[ "guillaume.himbert@gmail.com" ]
guillaume.himbert@gmail.com
ba1170d9c00eaf7450e27fbea157c8e4cb4fd402
f5bfa81cf4a06d449bd1a7e33587ef84d6b1c9a3
/source/DirectionalLight.cpp
f3d159b10862ee5d7f10aada7baaca59344260dc
[]
no_license
kevanvanderstichelen/Rasterizer
8a23b6cb9ac50b3105ddca261447f0bdcb1ae5ff
53a249abe25400c6c840e55b4bb37080f397733f
refs/heads/main
2022-12-28T04:11:55.830748
2020-10-10T15:19:27
2020-10-10T15:19:27
302,929,640
0
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
#include "DirectionalLight.h" DirectionalLight::DirectionalLight(const FVector3& normal, const RGBColor& color, float intensity) :m_Direction{ GetNormalized(normal) } ,m_Color{ color } ,m_Intensity{ intensity } { } const RGBColor DirectionalLight::CalculateShading(const FVector3& normal, const RGBColor& diffuse) const { const float observedArea = Dot(-normal, m_Direction); if (observedArea < 0.f) return RGBColor{ 0, 0, 0 }; return (m_Color * m_Intensity * diffuse * observedArea); } const FVector3& DirectionalLight::GetDirection() const { return m_Direction; }
[ "52068354+kevanvanderstichelen@users.noreply.github.com" ]
52068354+kevanvanderstichelen@users.noreply.github.com
14af0182179b5958c7a3eac6f57110e0b10d1896
598e1b350648db9fc0b3ce8a5a75b4a7d2382b65
/JsonApp_Andrusenko_2020/JsonLibrary/KeyValuePair.cpp
b0196441f34882ec50241cb9067b2e0b8b699346
[]
no_license
Maureus/CPP_Andrusenko
d629e39d192434c3fd465a417e1c7fbb3ef56395
ad69042e8f0d21868344d8f046efbd12d9c8f2a4
refs/heads/main
2023-02-11T06:25:59.207782
2021-01-05T17:28:35
2021-01-05T17:28:35
300,827,284
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
#include "pch.h" #include "api.h" KeyValuePair::KeyValuePair() = default; KeyValuePair::KeyValuePair(std::string key, Value * value) { if (key.empty() || value == nullptr) { throw invalid_argument("String is empry or value is nullptr"); } this->key = key; this->value = value; } KeyValuePair::~KeyValuePair() { } std::string KeyValuePair::getKey() const { return key; } Value* KeyValuePair::getValue() const { return value; }
[ "andriiandrusenko@gmail.com" ]
andriiandrusenko@gmail.com